How to increase book weight range for a same-level chapters I have a book of 33 chapters. These chapters are numbered with roman numbers: Chapter I, chapter II and so on.I'm a blind user, so I can't use drag & drop reorder. In Drupal 7, weight range is -15 to 15.
There is a way to modify this range? Or there is an other module similar to book module, with the same navigation style?

I was surprised to hear that the weight range numbers are limited, I expected to get a number input field (so I could enter any number value) but instead, the weight choice widget is a select options type, and for the Book module weights it really is limited to values between -15 and 15, and it still is in Drupal 8!
This is an important accessibility issue, but it doesn't seem so easy to fix once you dig into it. This was on the radar for a long time: Reordering fails with more than 31 book pages in a book that turned to Add a scalable weight select element which circled back to Improve #weight select element behavior based on the number of items and finally in D8 Books: Better Sorting. Maybe you can test that patch and help get it implemented in D8? There is an Accessibility Group you can join and advocate for better weights handling without javascript.
In the meantime, there is a number of modules you can use to reorder book pages a different way.
Book helper seems to be the best to try out first.
There's also a comparison page: Comparison of Node/Entity Ordering Modules


How to show basic page without summary? So I've got a basic page 'home' I want to use as my homepage. But when I make one and publish it to front page, I only see a summary, like it's an article. And if I don't publish it to front page, it's just not there, even with homepage link setup.

So basically I want text on my front page without the "read more" button, just the full text.

Go to Configuration > Site Information. Under the Front Page section, change FRONT PAGE to include your node information - meaning set the path you want to show as front page and then click save. see the below screenshot.

If you made the above settings then it will show the new front page without summary.


Displaying translated taxonomy terms I am trying to achieve a multilingual site that shares its content across all the (currently two) languages, so the same content resides under the same term no matter what language is currently active.

I've been told that I should use the i18n module, which I did. So right now I have all the names of the terms translated in both languages, so that is all working as it should.

The problem is that when I change the language to, for example, Arabic, all the term titles are still in English, even though I have a nice list of translated Arabic counterparts.

So the question I would like to ask is: is there a way to get Drupal to replace all the English terms with the Arabic ones wherever a term's name is displayed? (so make it behave as if every term name has been run through Drupal's t() function)

Most people who tried to answer this question just suggested I use the i18n module. So yeah, I already did that. I have the translations for the term names, but when changing the language, the term names are still in English

Any help would be greatly appreciated

Edit: Please note that I am not talking about a specific module here. For example, when I go to the admin panel's "Add Node" page, I have a drop-down box filled with terms that I have translated, with the language set to Arabic, and yet they still show up as English. This goes to show that it does not work with Drupal Core modules, so it is not likely to be caused by a poorly coded module per se.

Fixed, the problem was that the translations did not have the correct context linked to the translation.


Bulk Generating URL aliases for taxonomy terms doesn't do anything In D7, I've imported ~8000 taxonomy terms. All these need to have a url alias, based off their names.

I can check the 'Generate automatic URL alias' checkbox when editing each taxonomy term individually but I cannot go through and do this for all 8000.

I tried updating the paths with Bulk Generate. In the Patterns tab for my taxonomy term vocab I have set [term:name]. But when I hit Bulk Generate it doesn't update anything.

Would anyone know of a solution? An SQL query perhaps?

You'll need to troubleshoot your own site configuration to understand what's not causing the path update on the bulk form. If you look at the flow of execution, you can follow

The bulk update submission handler
The bulk update batch processor
The bulk updater

Ultimately, all the form is doing to update is using pathauto_taxonomy_term_update_alias_multiple() to load/save a group of tids in bite-sized chunks; if you fail to pinpoint the problem, you can use that function to do what you're already doing manually.


Send email to specific user by using webform Send email to specific user :

For this i have added a webform contact to this person using webform.

after filling the information in webform by anonymous user , a mail should be sent to that user whose profile is  he/she seeing.

Note: this functionality should only work for anonymous user and by using webform.

How to achieve this?

Finally i found the solution by myself

1) Create a hidden field in webform say username field.

2)then go to /webform/emails .select the component value that is equal to username hidden field you previously created.then edit added component value in E-mail from address section select the component radio button instead of Default: abc@yahoo.com radio button.

3)then create a custom module add this code

 function your_module_form_alter(&$form, &$form_state, $form_id){

 if ($form_id == 'your_webform_id') {
    $uid = arg(1);
   if ( arg(0) == 'user' && is_numeric($uid) ) {
       $account = user_load($uid);
        $form['submitted']['Your-hidden-field-machine-name']['#value']   = $account->mail;
     }
   }

   }


How can I rebuild an image field with values in an Ajax callback? in Drupal 8 I have media form with select box having ajax property and an image field.
on select box value change I want to assign specific file to the image field.
On form_alter this code work, the image field received the file and correctly rendered.
$form['field_media_image']['widget'][0]['#default_value'] = array('target_id' => "165", 'alt' => 'ttt', 'fids' => ["165"]);

but on ajax callback it's not working even if I set value.
function myAjaxCallback(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['field_media_image']['widget'][0]['target_id']['value'] = array('target_id' => 165, 'alt' => 'ttt', 'fids' => [165]);
  return $form['field_media_image'];
}

Thanks for helping

You cannot alter the form in the Ajax callback. Instead, you must put a check in your form if an Ajax action is triggered and if so, set the default value.
I did this once in D7 and managed to get it to work by doing the following:

Give the Ajax button a name attribute.
Somewhere in the form, check if $form_state['input']['_triggering_element_name'] is set and when it matches the name of the Ajax button, alter the $form.

In D8, I think you can get the clicked button with $form_state->getTriggeringElement().


How to manage reservations with Drupal for something that is not something like a room? I am looking for a reservation module for either Drupal 6 or 7. I know there is a really good looking module for room reservations for Drupal 7 but my use case is different. I am looking for a reservation/booking module that could be used for booking photographers or DJs. I have searched around but haven't really found anything suitable yet.

The Room Reservations module that is being created for Drupal 7 looks great, but it needs to be generalized so that the administrator could define what it is that needs to be booked. Right now it is hard coded for rooms only.

Does anyone know of such a module and more importantly worked with it?

For Drupal 6 there is a stable release of Simple Reservation module.

  This module provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

For Drupal 7 you can try Reservations API.

  The core focus in on the Reservations API that enables any Content Type to be reservable based on a variety of default settings. A Reservation -> Confirmation -> Checkout -> Checkin workflows is included, but it is created entirely using Views. Additional modules can enforce custom validation, add pricing, or add additional availability to the basic hours of operation.


The provided host name is not valid for this server I'm trying to migrate a drupal website from a server into my localhost but I trigger the error

  The provided host name is not valid for this server.

I've seen I need to add the trusted host pattern, but looks like this is not working I still get the error

My server is run on port 9000

sudo php -S 127.0.0.1:9000

My trusted hosts, and I've no Vhost

$settings['trusted_host_patterns'] = array(
  '^serverStuffWeDontMind$',
  '^localhost\:9000$',
);

If this is a dev - env, simply add

$settings['trusted_host_patterns'] = [$_SERVER['SERVER_NAME']];

But never do this in production.


Entity Translation - create a translation for all existing nodes Using Entity Translation, is there a way to create a translation for all existing nodes, instead of translating each one manually? For other languages there is lots of missing content, and would like to create temporary English versions for all languages before they are edited.

A possible solution could be to use a custom module that uses hook_node_view, as in this example:

function yourmodule_node_view($node, $view_mode, $langcode){
   global $language;
   if (!empty($node->language) && $node->language != $language->language) {
      drupal_goto('path/to/some/temporary/version');
   }
}

What the content of such path/to/some/temporary/version node should be is up to you. E.g. you could point to some custom 404 page.


Fixing Multi-site files path I have two separate fully developed Drupal 7 sites, which I now want to make as Multi-site.

I did it like in the above pic, and it worked, except all the images on both sites are broken.

Upon inspecting element, the paths are still trying to read from /sites/default/files folder instead of /sites/site1.com/files and /sites/site2.com/files respectively.

How can I fix the paths so it reads from /sites/site1.com/files and /sites/site2.com/files?

You may be aware of this. Change file path for individual sites at Configuration/Media/File system. By default it is set to sites/default/files. So your both sites are addressing same path.

So just change the path there accordingly for both sites.


How to activate some flag field when create a content? I have a many flag fields. When Authenticated users bookmark a content, they can enter value in flag fields.

I want to activate some fields of flag field when I create (add) a content.

For example, I have many flag fields of colors. When I create (add) a content, I want to activate some of the flag fields of colors. Because I want users to enter value of some colors, not all of color's field.

When I create first content I want to active 5 fields and when I create second content I want active 3 fiels and etc. I want to active some fields when I creating a content actually I want to have a control on flag fields.

How can I do it?

Consider using the Conditional Fields module. Excerpt from its project page:

Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.


How to force to upload a image with exact sizes? When adding an image field to a content type I can set the minimum sizes under which the image will not upload. I also can set maximum sizes but if the image is bigger the system will resize the image. How can I change this?

I need to set both limits: minimum a maximun sizes. This mean a exact size for the image, then if the image has not the exact size it shouldn't be allow to upload.

This is mostly based on memory, so some details might be off.

The image field widget assumes that downsizing an image is a valid action in all cases, so you'll need to override it.

Implementing your own field widget requires a little bit of fiddling with the field api, but since your change is fairly small, you should be able to just wrap a number of image field function and add a single validation step.

Since image field already is mostly a wrapper around a file field, looking at the image field itself for how to implement the above is probably a good start.


Define multiple variables in a custom module using hook_variable_info() Im using the Variable module and need to define a variable with the type "multiple" in my custom module. I've been googled whole my day searching for any documentation or just an example and haven't found anything.

There are plenty examples how to set the variable in such type like: string, number, radios, but nothing about the "multiple" type.

My "multiple" variable should look like this:

How can I build this kind of variable using hook_variable_info() ?

I figure out this on my own. Hope will be useful for someone.

/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {

    // Use '[custom]' as a placeholder for the variable name.
    // It will set these properties ('type' and 'multiple') automatically.
    $variables['custom_vars_[custom]'] = array(
        'title'     =>  t('Custom multiple variable'),
        'group'     =>  'site_information',
        'repeat'    =>  array('type' => 'string', 'default' => 'some default value'),
    );

    // if you need to expose your custom variable as token
    // you have to set 'token' key as TRUE,
    // and ought to set the properties (name, description and type)
    // Notice that 'first' it's a name of variable defined in custom_variable_options().
    $variables['custom_vars_first'] = array(
                    'token' => TRUE,
                    'title' => 'Custom variable',                       // name
                    'description' => 'My first variable description',   // description
                    'type'  => 'string'                                 // type
                    );
  return $variables;
}

/**
 * Implements hook_variable_type_info().
 * @return
 *  An array of information defining variable types.
 *  The array contains a sub-array for each variable type
 *  with the variable type as the key.
 *  The possible attributes are the same as for hook_variable_info().
 */
function MY_MODULE_variable_type_info() {
    $type['custom'] = array(
        'title' => t('Custom variables'),
        'type'  => 'select',
        'options callback' => 'custom_variable_options',
    );
    return $type;
}

/**
 * Callback for custom options.
 * @return
 *  An array of variables with the variable name as the key.
 */
function custom_variable_options($variable, $options) {
  return array(
    'first'  => t('My first variable', array(), $options),
    'second' => t('My second variable', array(), $options),
    'third'  => t('My third variable', array(), $options),
  );
}

Want to see how it works?

Install Variable module
Enable: Variable, Variable store, Variable Admin
Place this code in your custom module (replace 'MY_MODULE' to your module name)
Clear caches.

Results:

admin/config/system/variable -> site information

admin/config/system/variable/group/site_information

admin/config/search/path/patterns


Deleted content still in database? I recently went through a Drupal site I'm helping manage, doing a batch delete on a bunch of spam tickets through Administer > Content > Edit.

As it turns out, though, the data for this content seems to still be stored in the database, and is shown on our ticket list. Taking a look at a database dump taken after the deletion took place, confirms that they are in fact still present in the node and node_revisions tables.

Trying to access any of the tickets gives a "Page not found", and they're not listed in the "Edit Content"-list. Clearing the cache has been tried, and didn't resolve the issue.

In case it's useful, the node types are ticket.

Any insight into what has gone wrong and how to fix it would be most appreciated.

Turns out that tickets posted by deleted users do not show up in the management interface, but did show up in our view.

Problem was resolved by changing the owner of the tickets to a dummy user, then deleting them through the management interface.


Complicated module update error HTTP error 0 I'm recently getting the error below:

  HTTP error 0 occurred when trying to fetch https://ftp.drupal.org/files/projects/captcha-7.x-1.5.tar.gz.
  Downloading updates failed:

  Failed to download captcha from https://ftp.drupal.org/files/projects/captcha-7.x-1.5.tar.gz

  Blockquote

I'm running my website on a shared platform, so I can't change the parameters of PHP...

Based on this long thread drupal dot org/node/247009 I have already tried several many potential solution with no luck so far. This is what I tried and it did not work:

gave 777 recursive permissions to tmp and site/default/
tried on different browsers (Edge, Firefox, Chrome)
in jquery update module I changed the jquery default version to 1.10
I set the jquery source from google, and I set the jquery to non-minified
I checked and in settings.php I do not have any base url set
the file which failes to be downloaded is very small in size 103KB, so I
    guess it's not about uploading to large files
I checked my PHP version and it did not change recently it;s 5.3.29
I also checked the PHP memory limit and it's set to 256MB which to me it's not that low for uploading a 103KB file
I I tried the update of a different module, and I get the same error

What could be the problem? Where to look next?

I had the exact same problem and the solution given by Neograph734  was to manually add the module. If you have Filezilla, connect to your drupal site files. Go to Sites-->all--->modules--->  Locate the captcha folder, delete everything in that folder. Upload the updated captcha module files. (Download and upzip first).

Once this is done, you will also need to update the database. It will show you where to do that once you click on reports. Once the database is updated, your module should now be upgraded and working. :)

No more nasty notices about having to upgrade it!


Severe health issues are found on your site I have just put a Drupal website online. I registered it in Google WebMaster's tool and it sent me back a Severe health issues are found on your site message related to a robot.txt file.

The content of this file is:

#
# robots.txt
#
# This file is to prevent the crawling and indexing of certain parts
# of your site by web crawlers and spiders run by sites like Yahoo!
# and Google. By telling these "robots" where not to go on your site,
# you save bandwidth and server resources.
#
# This file will be ignored unless it is at the root of your host:
# Used:    http://example.com/robots.txt
# Ignored: http://example.com/site/robots.txt
#
# For more information about the robots.txt standard, see:
# http://www.robotstxt.org/wc/robots.html
#
# For syntax checking, see:
# http://www.sxw.org.uk/computing/robots/check.html

User-agent: *
Crawl-delay: 10
# Directories
Disallow: /includes/
Disallow: /misc/
Disallow: /modules/
Disallow: /profiles/
Disallow: /scripts/
Disallow: /themes/
# Files
Disallow: /CHANGELOG.txt
Disallow: /cron.php
Disallow: /INSTALL.mysql.txt
Disallow: /INSTALL.pgsql.txt
Disallow: /INSTALL.sqlite.txt
Disallow: /install.php
Disallow: /INSTALL.txt
Disallow: /LICENSE.txt
Disallow: /MAINTAINERS.txt
Disallow: /update.php
Disallow: /UPGRADE.txt
Disallow: /xmlrpc.php
# Paths (clean URLs)
Disallow: /admin/
Disallow: /comment/reply/
Disallow: /filter/tips/
Disallow: /node/add/
Disallow: /search/
Disallow: /user/register/
Disallow: /user/password/
Disallow: /user/login/
Disallow: /user/logout/
# Paths (no clean URLs)
Disallow: /?q=admin/
Disallow: /?q=comment/reply/
Disallow: /?q=filter/tips/
Disallow: /?q=node/add/
Disallow: /?q=search/
Disallow: /?q=user/password/
Disallow: /?q=user/register/
Disallow: /?q=user/login/
Disallow: /?q=user/logout/

I believe Drupal generated this itself.

I have another Drupal site live, but it does not have a robot.txt file, and Google WebMaster Tool does not throw me such messages.

How to solve this issue? Is it safe to remove my robot.txt file?

UPDATE

I am still struggling with these strange warning messages from Google Webmaster Tools on my Drupal website:

Is robots.txt blocking important pages?
Some important page is blocked by robots.txt.

When I click on 'important page', it points to:

http://www.mydrupalsite.com/misc/jquery.js?v=1.4.4

Why would Google want to access /misc?

There's nothing in your robots.txt file that is out of the ordinary and for the most part you probably want to keep all of those exclusions, checks, etc. to save on bandwidth and for security. The health message you're seeing is likely due to another issue within the site or maybe just a temporary Google hiccup that will resolve itself shortly. Are there any other messages within the Google Webmasters page that indicate other issues, ex. permission problems?

Another possibility is to submit an XML Sitemap to Google directly to tell it exactly what you are expecting it to index:

http://drupal.org/project/xmlsitemap

I've found that this resolves some Google crawl issues in the past.


Changing the confirm delete message for comments I have a website where I have comments on certain content but I am not allowing any replies to these comments. When deleting a comment the confirm delete message shows as

'Any replies to this comment will be lost. This action cannot be undone.'

This is not ideal because obviously there will never be any replies.

I have found the function which creates the text for the message on line 257 of comment.admin.inc

function comment_confirm_delete($form, &$form_state, $comment) {
  $form['#comment'] = $comment;
  // Always provide entity id in the same form key as in the entity edit form.
  $form['cid'] = array('#type' => 'value', '#value' => $comment->cid);
  return confirm_form(
    $form,
    t('Are you sure you want to delete the comment %title?', array('%title' => $comment->subject)),
    'node/' . $comment->nid,
    t('Any replies to this comment will be lost. This action cannot be undone.'),
    t('Delete'),
    t('Cancel'),
    'comment_confirm_delete');
}

How would I go about changing this text. Could I use template.php? If so how would I find the correct preprocess function. And then what is the way in which I could best find the variable in its current state in order to change it?

You can do this with hook_form_alter(). https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7

Just add an if statement to check if the $form_id is 'comment_confirm_delete', then you can alter anything in the $form object, including the text.


View data not showing after moving website I just move a drupal 7 website from my localhost WAMP server to a production server (using phpmyadmin for the database).

Everything is fine except the views which didn't show anything. The data are here but even with the views ui, the preview doesn't show a single data.

I suspect a database problem but I don't know what to do

You can export the whole view from local server to production server, if it works it means that there must be a problem in db, so try exporting the database again. And one suggestion you can use features module for deployment process.


How to enable inactive fields I have a content type with a field that has been set to inactive. This happened after I reverted my feature in an attempt to undo a change I made to the content type.

The error message given is the following:

  This content type has inactive fields. Inactive fields are not included in lists of available fields until their modules are enabled.

I've disabled and re-enabled the feature module, but the field is still inactive.

How can I activate my field?

I've had this quite a few times, I'm not sure what the initial problem is but I've solved it by doing either one of the following:

Disabling the feature and re-enabling it
If above fails disable delete content type then re-enable (not an option if there existing content on the site)
Manually editing the content_field_instance table (D6) and enabling it there.


Why is my view for Solr indexing is not showing any results? I have installed solr 8.2.0 for drupal 8.7.6.

My Solr server and index are enabled and indexed. But when try to search via views, the results are not showing up. Please help me in solving this.

My New view

You need to export the solr conf from drupal and import it into solr server.

The export button is on your server conf in drupal.

The readme of the search api module can guide you about that.


Can Drupal nodes and taxonmy be used to store "data" rather than "content"? I'm very new to Drupal so please excuse the noobishness of this question.

After combing through the documentation and considering the flexibility of Drupal (Version 7) in defining it's own content, I find myself asking where the lines between content and data are drawn.  Some insight and advice on the limitations of things like nodes, content types and taxonomy would be appreciated.

Here's a basic overview of what I'm looking to accomplish at this stage:

I need to setup a website that will be able to keep track of a community of users that are segregated into clubs;
Clubs will be able to offer courses to their members;
Club members will be able to apply to take said courses;
A history of courses a user has taken will be recorded;
This information will be used to create reports by the administration.

My first instinct is to create separate tables for this information and handle all this through modules (WordPress being my previously relatable experience).  With that said, I find myself pondering the idea if these things could be handled through nodes, content types and taxonomy.

Would this, or some variant thereof, be a valid use of Drupals mechanisms or would this basically be the hack & slash approach that I'll end up lamenting down the road?

I recommend leaving the database structure to Drupal, its modules will handle all of the management process and you will not have to code anything.

Taxonomy is very flexible for creating categories.  These taxonomy vocabularies can be attached to a content type.  Create a new type and add fields for each applicable vocabulary.  You can make assigning values to each field mandatory if you want and Drupal will enforce the requirement when new content is generated.

You will then use views to filter through all of your content and deliver custom pages.  It is incredibly flexible but can take a while to learn.  Check out the "Taming the Beast" video series at NodeOne.SE for an excellent video series to master views.


Comment Form Missing I'm baffled by this issue on my new site. I have double checked permissions to verify that authenticated users can post so I'm just getting that out of the way first off.

However, what is odd is that each node (where I rely off of the default Drupal node template, and those in which I have created a custom template) has a "Login or Register to Post Comments" div and appropriate links, however, when I login as a test user, there is no comment form.

I'm not sure where to go from here, as even my Admin account cannot see the comments form.

EDIT-----------

Also, all comment settings are set to "Open" for all content types and individual content postings.

EDIT-----------

I have rebuilt the permissions as well, just in case. Nothing has changed.

EDIT-----------

I happened to remember that I had previously posted a test comment on one of the pages, and now I can't see that comment, even if I go through the admin panels. I can see that there is a comment, but I cannot see the comment itself.

Turns out the solution was to Disable Panels

or you could add the comment form to the Panel.


Getting info from an external database - Base table or view not found Currently working on getting some info from an external application's database onto my user profile page as a test.

I've run into a snag that I can't seem to get past. This is probably something so simple, but I'm pulling my hair out over it.

I have 2 databases - one is Drupal, and the other is from SocialEngine. These are both hosted on the same server(not localhost).

My error is this: Base table or view not found: 1146 Table 'uitv.engine4_users' doesn't exist: SELECT email FROM {engine4_users} WHERE enabled = :enabled; Array ( [:enabled] => 1 )

Awesome. Okay, well I think I can see the issue here... engine4_users is actually in the uitv_social database, while my Drupal installation is in the 'uitv' database. I've used db_set_active($social); which relates to my database settings in settings.php - and I've set it back to the default database after I query the social one.

What am I missing here? (Drupal 7 database documentation seems to be blank on this subject)

[EDIT: I did something silly - use db_set_active('yourdbkey'); - and make sure your query is right. Hope this helps a Googler. Curiously, I had done this several times before, but since the query was incorrect it wasn't giving me anything, obviously.]

I know you answered your own question with a solution -- here is additional info.

The helper functions db_select(), db_update(), db_insert(), db_merge() all use the default database connection defined in settings.php. As you pointed out you can use db_set_active() to set an active database within a given scope of code. I personally dont like this approach, because X months from writing the code you will forget that, "oooohhh I used db_set_active X lines above" and run into annoying maintenance issues.

There is another solution, dont simply use the helper db functions. Use their parent Objects, which they are wrapping ... as in below:

    // 'remote_database' is a 2nd db connection defined in settings.php
    $query = Database::getConnection('default', 'remote_database')->select('survey_item', 'si');
$query->fields('si', array('item_id', 'presentation_order', 'question_type', 'stem', 'choice_1','choice_2', 'choice_3', 'choice_4', 'choice_5', 'choice_6', 'choice_7', 'choice_8'));
$query->condition('survey_id', $current_row->survey_id);
$query->orderBy('presentation_order', 'ASC');
$current_row->form_items = $query->execute()->fetchAll();

So you can create a Query as I have above by specifying the connection first. You may do this for all ->select() or ->update() or ->insert() functions which drupal supplies wrappers for.

Or, you can even pass as a 3rd argument to a SelectQuery() constructor the connection to use for the query, see the docs here:

http://api.drupal.org/api/drupal/includes--database--select.inc/class/SelectQuery/7

  // This is the constructor for SelectQuery() from select.inc
  public function __construct($table, $alias = NULL, DatabaseConnection $connection, $options = array()) {
$options['return'] = Database::RETURN_STATEMENT;
parent::__construct($connection, $options);
$this->where = new DatabaseCondition('AND');
$this->having = new DatabaseCondition('AND');
$this->addJoin(NULL, $table, $alias);

}

So you can also start a db_select() query as follows to tie it to a non default connection in another means:

$query = new SelectQuery('my_table', 'table_alias', Database::getConnection('default', 'remote_database'));
// other things you build onto your query
// $query->addJoins(...); $query->fields(...); ...
return $query->execute()->fetchAll();

So in a nutshell -- the db helper functions are convenience when talking to 1 database. Beyond that, you can specify per-query what connection to use ... if you like more fine control of your queries and not use db_set_active() all over the place.


Locations geocoding to province, not country I previously asked a question but since have done much research and am getting more focused on my problem.

I have a locations cck field in a profiles 2 profile. Here, I get users to select just countries (no cities or provinces) and they are geocoded to points and displayed on a user specific map. Many of the countries are not accurate. I have discovered the locations are being geocoded by their province code. Example: the country code is being ignored and it is selecting a province code.

I had a problem that Barbados was being displayed in Germany. Barbados has a country code of "BB", but I found that the point was being displayed in Brandenburg Germany, the province code "BB". Every wrong point can be explained this was but 3.

I have the geocoding setup to be at a country level accuracy. I dont think its a config problem and I have yet to find any other people with this problem.

Any ideas on what to do?

Thanks

The problem is not actually with that snippet of code in _google_geocode_flatten(), but is just a result of google's geocoding algorithms.

For example, your search for BB finds 2 results, Brandenburg Germany & Barbados, however google puts the former as the first result, possibly due to popularity of searches or something.

See http://maps.googleapis.com/maps/api/geocode/json?address=bb&region=bb&sensor=false

The solution I can see is to also pass in the component param when requesting from google geocoder, which allows you to specify specific parts of the address in addition to the full address string.

See https://developers.google.com/maps/documentation/geocoding/#ComponentFiltering

I have posted a patch back to your issue on drupal.org


Render image field with custom image style in custom block template This is basically the same question as this, but I can't get the technique to work in a custom block type template: https://drupal.stackexchange.com/a/219052/71100

I have a custom block type called link_card.
I have an image field field_link_card_image.
I have a List(text) field to select an image style field_link_card_size
I have confirmed that field_link_card_size is outputting the key, which is the machine name of my image style.
My theme template is block--bundle-link-card.html.twig. It overrides block.html.twig. The template is working.
I want to render the image and use the image size selected.

Here is the first way I tried based on what worked in the answer for page.html.twig.

{% set image = {
  '#theme':      'image_style',
  '#style_name': content.field_link_card_image_size[0],
  '#uri':        file_url(content.field_link_card_image['#items'].entity.uri.value),
  '#alt':        content.field_link_card_image[0].alt,
 } %}

 {{ image }}

I get this white screen error:

  Error: Call to a member function transformDimensions() on null in
  template_preprocess_image_style() (line 303 of
  core/modules/image/image.module).

And this error in Report Log in the admin area:

  Warning: array_flip(): Can only flip STRING and INTEGER values!

If I replace the value for '#style_name: with the just the  machine name of one of my image styles (such as square) it almost kinda works.

The image renders but with the _incorrect image src: /D8_1318_LinkCard/web/files/styles/square/public//D8_1318_LinkCard/web/files/2019-06/unsplash_1500x500-4.jpg?itok=c16MdkOY (You can see it's sort of repeated itself.)
The alt text doesn't come in at all, so I probably have that wrong, too.

This leads me to believe that there are problems how I'm pulling in the field content from the block.

Here is the second way I tried:

{% set image = content.field_link_card_image[0] %}
{% set imagestyle = content.field_link_card_image_size[0] %}|
{% set image = setimage|merge({ '#image_style': imagestyle }) %}

{{ image }}

The errors are:

  Error: Call to a member function transformDimensions() on null in
  template_preprocess_image_style() (line 303 of
  core/modules/image/image.module).

  and

  Warning: array_flip(): Can only flip STRING and INTEGER values!

  and

  Error: Call to a member function transformDimensions() on null in template_preprocess_image_style()

This works if I do imagestyle = 'square'. But of course I'm trying to use the value of the field.

Here the problem seems to be an issue with getting in the field_image size to sneak into the variable imagestyle.

TLDR: How do I render an image field with a custom style in the custom block template.

Thanks!

This module is exactly what I need. https://www.drupal.org/project/field_image_style

:D


Ubercart Recurring fees I'm using uc_recurring module in Drupal 6.
Added these options to the Recurring orders:

0 day|Every this one...

1 week|Every week

2 week|Every other week

3 week|Every third week

4 week|Every four week

Added recurring fee for fortnight from Product Features.

"add a fee for $2.00 charged first after 0 days and every 2 weeks after that unlimited times".

1) It's working in the cart page.(Recurring order options are showing up), and at the end it's not counting 2$. 2$ is not playing any role, how does it work?

2) On the whole how are recurring orders and recurring fee connected?

Be sure that you added the sell price of product and after that in product feature add recurring fee ammount of 2$.


Node registration form block - hide if registered I'm using "Node registration: this page's form" block, but I want to hide it when user has registered for this node already. I know i should use 'If' statement but i don't know what condition to use.

Node registration not providing a function in it's API for that, however you could include the "node_registration\includes\node_registration.api.inc" file and use their internal function that the module use to check for user access for  a specific node.

// Include the file
    module_load_include('inc', 'node_registration', 'includes/node_registration.api');

 if (_node_registration_user_registered($node, $account)) {
    //do something
  }


basic page within a basic page Is there any way to create a basic page within a basic page?
For example, when you create new content, you have the option of making a top menu.
Within that basic page you have just created, can you also make another basic page with a top menu within that basic page?

Sorry if this is confusing.

Well, I guess that you are asking about creating hierarchical menu structure, so that menu item pointing to your "another basic page" is a child of menu item for first "basic page"?

Then yes, there is a way, and pretty easy to it, when creating a second "basic page" and providing a menu link for it (in Menu settings section), make sure that you select your first "basic page" in Parent item dropdown.


How can you print the field class you entered in a View 's style settings? So in Views you can add a CSS class (under style settings) to your field.
I need to print the same class in a parent div of the calendar module.

The fields are rendered to calendar content with the calendar-item.tpl.php
That file looks like this:

$index = 0;
?>
<div class="<?php print !empty($item->class) ? $item->class : 'item'; ?>">
  <div class="view-item view-item-<?php print $view->name ?>">
  <div class="calendar <?php print $item->granularity; ?>view">
    <?php print theme('calendar_stripe_stripe', array('item' => $item)); ?>
    <div class="<?php print $item->date_id ?> contents">
      <?php foreach ($rendered_fields as $field): ?>
        <?php if ($index++ == 0 && (isset($item->continuation) && $item->continuation)) : ?>

&laquo;

        <?php endif;?>
        <?php print $field; ?>
      <?php endforeach; ?>

    <?php if (isset($item->continues) && $item->continues) : ?>

&raquo;

    <?php else : ?>

&nbsp;

    <?php endif;?>

So I need to get that class in the first DIV

<div class="<?php print !empty($item->class) ? $item->class : 'item' . ENTER-FIELDCLASS-HERE; ?>">

I've been looking in the VIEWS module and the code taht checks if you entered a CSS class should be this part in the THEME.inc file:

if ($classes = $object->handler->element_classes($view->row_index)) {
          if ($class) {
            $class .= ' ';
          }
          $class .=  $classes;
        }

A more complete part:

$previous_inline = FALSE;
  $vars['fields'] = array(); // ensure it's at least an empty array.
  foreach ($view->field as $id => $field) {
    // render this even if set to exclude so it can be used elsewhere.
    $field_output = $view->style_plugin->get_field($view->row_index, $id);
    $empty = $field->is_value_empty($field_output, $field->options['empty_zero']);
    if (empty($field->options['exclude']) && (!$empty || (empty($field->options['hide_empty']) && empty($vars['options']['hide_empty'])))) {
      $object = new stdClass();
      $object->handler = &$view->field[$id];
      $object->inline = !empty($vars['options']['inline'][$id]);

      $object->element_type = $object->handler->element_type(TRUE, !$vars['options']['default_field_elements'], $object->inline);
      if ($object->element_type) {
        $class = '';
        if ($object->handler->options['element_default_classes']) {
          $class = 'field-content';
        }

        if ($classes = $object->handler->element_classes($view->row_index)) {
          if ($class) {
            $class .= ' ';
          }
          $class .=  $classes;
        }

        $pre = '<' . $object->element_type;
        if ($class) {
          $pre .= ' class="' . $class . '"';
        }
        $field_output = $pre . '>' . $field_output . '</' . $object->element_type . '>';
      }

Not the most clear code to me.
It can't be that hard. If only something like $field->class would work!

Thanks in advance!

You can add a class through the views interface:

Go to views ui
Under "Fields", click on the field you want to change
Click on "Style Setting"
Choose "Customize Field HTML"
Click "CSS Class" and enter your new css class

Alternatively, you can also achieve this through theme pre rendering.

View machine name: "your_view_name"
Field machine name: 'yourfield'
New class: "your_new_css_class"

Add to the file template.php in your theme directory:

function yourtheme_views_pre_render(&$view) {

  if ($view->name == "your_view_name") {
     $view->field['yourfield']->options['element_class'] = "your_new_css_class";
  }

}

To debug, download and enable the devel module (http://drupal.org/project/devel), and write out the variables:

function yourtheme_views_pre_render(&$view) {
    if ($view->name == "your_view_name") {
        drupal_debug($view->field['yourfield']->options['element_class']);
    }
}

The output will appear in tmp/drupal_debug.txt (depending on how you configured your tmp directory).


How to test if a variable is been sanitized? I have been doing coder review, and the coder module is showing this complain:

Line 111: Potential problem: drupal_set_message() only accepts filtered text, be sure to
use check_plain(), filter_xss() or similar to ensure your $variable is fully sanitized.
drupal_set_message($message);

So my question is if there is a way to test if the variable been sanitized ?. In the past, the coder module have show me false positive, that is why I'm asking how to check if is been sanitized or not.

I have check the entire project and does not have check_plain(), nor  filter_xss().

Your answer is already in the comments by @Geoff and @Clive above. If there was a way to unambiguously detect sanitation status of variables in PHP then the Coder module (and probably some IDE:s) would have incorporated it already.

But in some (not all) instances you can name your variables according to their sanitation status, to make it easier to keep track of which variables are sanitised and which are not.

<?php
  $myVar_raw = some_source();
  $myVar_safe = check_plain($myVar_raw);
  unset($myVar_raw); // Optional, to make sure raw variable is not used again later
?>


where are menu item configurations stored? In drupal 8, which file holds the information of the menu items?  I do a config-export and do not see which file is changed when I change the menu items.

Menu is a Entity, like a Node (sure, with some differences). There is a config and content, config you can export and import through UI, but not with content, this you will find only in DB.

Maybe you can find some modules to import/export content, but its not available at default install of Drupal 8.


Error during import (The header record must be an empty or a flat array with unique string values) I want to import some content into my site from a CSV file (bellow) [the file is originally an .xlsx and I use a online CSV converter to get the CSV file)
format,type,name,address,id,ttx
open,semi-transparent,Thomas Chao,,rk39k3as22,coming soon

And here's my migration file:
id: migrate_content
label: 'Import content from CSV to CMS'
migration_group: migration
source:
  plugin: csv
  # Full path to the file.
  path: '/var/www/html/myproject/web/sites/default/files/migrations/test_1.csv'
  header_offset: 1
  ids: [id]
  keys:
    - id
  constants:
    status: 1
process:
  title:
    plugin: create_title
  field_format: format
  field_type: type
  field_name: name
# field_address: address
  field_ttx: ttx
  status: constants/status
destination:
  plugin: 'entity:node'
  default_bundle: granularity_type
migration_dependencies:
  required: {  }
  optional: {  }

When I run drush migration:import migrate_content, I get this error.

The header record must be an empty or a flat array with unique string values.

Ok so the answer was pretty obvious header_offset should be 0


Can I set a cron for deleting and re-indexing Search API daily? Using Commerce Kickstart 2.

When we add new products, the facet search index does not re-index automatically as it says it does (Maybe because we are using some Aggregated Fields?) -Whatever-, we have to re-build the index manually to get certain search fields to work.

I read a bit and it -seems- as though the standard cron tasks -should- add to the index, but that ain't happening.

So: Is there a way to create an 'Re-build Index' to a list of nightly Cron jobs?

If you have Drush on your server, you can use the drush search-api-reindex command. This way you don't need to invoke a cron, but can force a reindex.

Note: You'll need to run drush search-api-list first to get the numeric identifier for the index when you run the re-index command.

Reference more info here: http://drushcommands.com/drush-6x/search-api/search-api-reindex


Can a view "a" appear only in the page of view "b"? I have a view I want it appears only in the page of another view.

Is it possible without writing code?

Put him in a block and show that block only on the page of the other view.  Or more precisely, create a block display for view a and have it displayed only on the path defined by the page display in view b.


How to use the gmap module withouth a API key? I use gmap module to show maps in a website. This module require an API key from google maps. But today I found this page http://code.google.com/intl/es-ES/apis/maps/signup.html when I try to generate a new API key which says:

  The API keys generated by this page are no longer available.

But the gmap module still require it:

As suggested in the issue someone opened for the GMap project page, head to this page and follow the steps to obtain a key (Google account required).


Drupal 8 Add Javascript What is the best way to add javascript to Drupal theme now that drupal_add_js is gone?

I want to use specifically jQuery ui animate, which I suspect is in Core, but I cant find out how to add it to my theme.

Use the following function in template.php of your theme.

function MYTHEME_preprocess_page(&$vars, $hook) {
  $path = drupal_get_path('theme', 'MYTHEME');
     // Render the main scripts file.
  $local_js = array(
    '#attached' => array(
      'js' => array(
        $path . '/js/scripts.js' => array(
          'group' => JS_THEME,
          'weight' => 9999),
      ),
    ),
  );
  \Drupal::service('renderer')->renderRoot($local_js);
}


Drupal hook_preprocess_hook not working I have a webform with id 32.

I created a template (which works fine) in my theme/templates folder named webform-form-32.tpl.php.

I also created a preprocess function in my template.php file. My theme is called emuse and my hook is:

function emuse_preprocess_webform_form_32(&$vars){
}

but this doesnt get called. Can anyone help me out ?

Nealv, the preprocess function can only be implemented for the base name, not for the additional suggestions you used for creating your tpl.php file.
The suggestions for alternate template files are added in the preprocess functions themselves.

See https://drupal.org/node/223440 - These naming suggestions are set from preprocess functions.

So call THEMENAME_preprocess_webform_form and check if it's the right form to alter within the function itself.


Disable lock_release_all I am testing my module, using a custom SQLite database. It has minimal amount of tables, necessary for the module. I run this function.

function test_header(&$modules, &$path_var = null) {
  $file_path = dirname(__FILE__);
  $path = preg_replace('/sites.*/', "", $file_path);
  $path = substr_replace($path ,"",-1);
  $_SERVER['DOCUMENT_ROOT'] = $path;

  define('DRUPAL_ROOT', $path);

  if (!is_null($path_var)) {
    $path_var = $path;
  }

  error_reporting(E_ALL ^ E_NOTICE);
  $path .= DIRECTORY_SEPARATOR . 'includes'.  DIRECTORY_SEPARATOR . 'bootstrap.inc';
  require_once($path);
  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

  foreach($modules as $value) {
    drupal_load('module', $value);
  }

  return $file_path;
}

I run it with modules that need to be loaded.

$modules = array("members");
$file_path = test_header($modules);

Then I load the SQLite database, using this function.

function set_db($db_name, $db_alias, $driver = 'sqlite') {
  $test_database = array(
    'database' => $db_name,
    'username' => 'user',
    'password' => '',
    'host' => 'localhost',
    'driver' => $driver,
  );

  Database::addConnectionInfo($db_alias, 'default', $test_database);
  db_set_active($db_alias);
}

For one of the modules it works correctly. But for another one it gives an error, when I change DRUPAL_BOOTSTRAP_DATABASE to DRUPAL_BOOTSTRAP_FULL.

  General error: 1 no such table: semaphore: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array([:db_condition_placeholder_0] => 8994220325229a65a473108.08075181)
  in lock_release_all()

Without DRUPAL_BOOTSTRAP_FULL it gives some cryptic error.

It seems that it runs this function in the end, and it doesn't find the semaphore table in the SQLite database.

How can I turn off this function and everything else unnecessary?

The lock system is initialized during bootstrap (during the DRUPAL_BOOTSTRAP_VARIABLES phase, which follows the DRUPAL_BOOTSTRAP_DATABASE one) using the following code.

// Initialize the lock system.
require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
lock_initialize();

You could:

Bootstrap Drupal to the DRUPAL_BOOTSTRAP_DATABASE phase
Change the value of the lock_inc Drupal variable to make it point to an include file containing your implementation of the lock system, with functions that don't do anything
Execute the rest of the code, including the one to raise the bootstrap level to the desired one

Since you are loading other modules, this resolves the problem with the lock database table, but it doesn't avoid that modules try to access a database table that normally exists on a Drupal installation, including the ones they install. If you need to execute a query (for example, a SELECT) on a database that is different from the default one you could use the following code.

Database::addConnectionInfo($db_alias, 'default', $test_database);
query = Database::getConnection('default', $db_alias)->select('table name', 'table alias');
// The rest of the code goes here.

The first two arguments for Database::addConnectionInfo() and Database::getConnection() are flipped: The first argument of Database::addConnectionInfo() becomes the second argument of Database::getConnection(), and the second argument of Database::addConnectionInfo() becomes the first argument of Database::getConnection().


hide unpublished content in view, for everybody except the author I'm trying to make a view of articles written by an author.
I use the author UID from the URL as a contextual filter.

I want to hide unpublished content from everybody except the author himself.

I have removed the published filter, hence all unpublished content is visible.
My first guess was to write some php code to check if the uid of the logged in user and that from the URL are same or not. If true display unpublished content or else hide unpublished content. But could not implement it.

Please suggest any possible solutions. Thank You.

I think the similar question asked previously . You can find the solution at Use Views to display unpublished nodes to authors, but not to other users


How to allow a user with some role to let people to register their new accounts in drupal 7? Is it possible to let a user with some role (not an admin) that will decide if somebody can register in drupal?

I know there is an option in admin menu

  Configuration->Account settings Option: Registration and cancellation Who can
  register accounts?

Is there any other option to do it like a module that user has a permission to switch on or off registration new users?

In Drupal 7 you can use Administer Users by Role module

  Administer Users by Role : This module allows site builders to set up fine-grained permissions for allowing users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

Reference:

Create role for changing user accounts and not admins


Quicktab visibility by programing I have a Quicktab with 2 tabs. The block is placed in user profile.

Now I want to show one of the blocks only when the user visits his own profile and hide it when he is visiting other profiles. How may I do this?

In Drupal 7 you can use hook_quicktabs_alter

    /**
     * Implementing hook_quicktabs_alter
     * @param type $quicktabs
     */
    function MODULE_NAME_quicktabs_alter(&$quicktabs) {
        global $user;
        foreach ($quicktabs->tabs as $key => $tab) {
            if ($tab['title'] == 'Tab1' && arg(0) == 'user' && is_numeric(arg(1)) && $user->uid == arg(1)) {//check condition as per your requirement
                unset($quicktabs->tabs[$key]);
            }
        }
    }


How to limit a user to specific OG groups based on user role? In a quite complex project page, I have several user roles (from Drupal core). Further, the page has an internal area which is built upon Organic Groups (OG). There are a lot of groups available, each group is part of a so-called "area". These areas correspond to user roles and what I want to achieve is that users of a role may only subscribe to groups of the area with the same name.

To visualize the concept, let's say I have three user roles (besides anonymous, authenticated and administrator): A, B and C.

There is a node type called "Group" which has a select field for area, the available options are A, B and C.

There are nine groups, called A1, A2, A3, B1, B2, B3, C1, C2 and C3. I don't want users to apply for a group but immediately join (subscribe) to it, but only if the group's area matches the user's role. So user Alex of role A may only see and join A1 through A3 but not any other group.

The OG group permissions only distinguishes between non-member, member and manager. There's the option to subscribe to a group without approval, which I want. But how to combine that with the Drupal user role?

Due to other restrictions in OG I couldn't overcome, I ended up using the Group module instead. In addition to other advantages for my use case, it offers some functions to easily add group memberships (these are entities) by using something like

$entity_type = 'group_membership';
$entity = entity_create($entity_type, array('gid' => $gid, 'uid' => $uid));
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->status = 'active';
$wrapper->added_on = time();
$wrapper->added_by = 1;
$wrapper->save();

Adding that into a hook_user_update(&$edit, $account, $category) function, I am able to add and revoke memberships based on the updated account's roles.


How to reorder vertical tabs by weight in Drupal 7? I have some vertical tabs I am trying to reorder and the dpm()'d weights are not matching the visual output. Can someone explain this or point me to the right documentation on how weights and vertical tabs work?

If you are calling the hook function through your module it can happen that other modules are calling the same hook function after your hook. This would make the changes you made overwritten by the other module.

So if you want to make sure your hook is called last, either call the function in the themes template.php file or change the weight of your module to something higher so that it gets executed last. The second option would require you to edit the system table in the database.


PDOException Deadlock Yesterday I had a peek in visitors and I saw following PDOException in my logs:

PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: SELECT revision.order_number AS order_number, revision.revision_id AS revision_id, revision.revision_uid AS revision_uid, revision.mail AS mail, revision.status AS status, revision.log AS log, revision.revision_timestamp AS revision_timestamp, revision.revision_hostname AS revision_hostname, revision.data AS data, base.order_id AS order_id, base.type AS type, base.uid AS uid, base.created AS created, base.changed AS changed, base.hostname AS hostname FROM {commerce_order} base INNER JOIN {commerce_order_revision} revision ON revision.revision_id = base.revision_id WHERE (base.order_id IN (:db_condition_placeholder_0)) FOR UPDATE; Array ( [:db_condition_placeholder_0] => 6131 ) in DrupalDefaultEntityController->load() (line 191 of /var/www/vhosts/shopmybooks.com/releases/20141208090103/web/includes/entity.inc).

I can't seem to find any good solution for this.
Drupal version 7.27

Any help?

I had some similiar issue.

Problem was that drupal was cosuming 100% of cpu usage, sometimes making the execution of some queries to take to long and reaching the max timeout on LOCK_TIMEOUT

If you have acccess to command line, check proccess, cpu usages, sql usage and so on

Hope it helps

There are some threads about drupal sites cosuming 100% of cpu (Kind of old but i had this problem recently), take a look

See this thread for a bit of debuging


Create a view with a list of webform without any submission by current user I am currently stuck trying to build a view wich contains a simple list of webform's name not submitted yet by the current user so that the current user can only see a list of webforms to be filled.
How can this be accomplished?

I experimented a lot of settings but i couldn't get the expected result.
Any help would be much appreciated

I'm not sure if there is a solution to create such kind of view using the Views module. But the Forena module (disclosure: I'm a co-maintainer) can be used for this type of reporting. More specifically by using its facility to create a Display of a table in crosstab format.

A crosstab table is a table with a special layout. It is formatted as a grid, with:

the rows representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), etc.
the columns representing one or more other facts, such as periods (months of a year, years, etc), available types/flavors of something (like types of errors), etc.
the intersections of rows and columns containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) include a hyperlink to a drill-down report.

Below is a sample of such crosstab report (including drilldown links also, i.e. the numbers in red in it):

Refer to my comment in the Forena issue queue for more details about the above screenshot. And/or have a look at the video about How to generate crosstab reports with graphs (Forena also supports charting of those data, a typical related requirement ...).

Specific to your question here, I'd create such table in crosstab format with rows/columns like so:

The rows should represent your users (1 row for each user).
The columns should represent your webforms (1 column for each webform).

With such setup, the answer to your question is then contained in the intersections of all rows and columns that are shown as "blank" (= zero submissions of the specific webform by the specific user).

PS: I'm assuming you're using D7 ...


Prevent Entityform Duplicate Submissions I have a simple text entityform setup on my drupal website. I was wondering if there was a way to prevent users from submitting a submission that has already been submitted. I am new to using Rules, but my guess would be there is a way to do so using that.

Thanks

You can try the Hide Submit moddule:

  Some users accidentally click the submit button more than once while
  waiting for their post to be saved. In some cases this may result
  duplicate postings or duplicate e-commerce orders.

  There are few ideas on how to solve duplicate postings but none is
  perfect. One of the solutions is a bit of jQuery to hide or disable
  the submit button after it has been clicked and replace it with an
  informative text such as "Processing..." .

  This module wraps that jQuery code and provides some options. Of
  course this, too, is not a perfect solution as it requires Javascript
  to be enabled. For browsers with Javascript disabled this module will
  have no effect at all.


How to adapt #prefix/#suffix for each option in radio form using hook_form_alter()? I need to modify the html code of radio buttons generated by Ubercart Attributes. So I want to do it using hook_form_alter().

If I dsm() the $form I need to change using hook_form_alter() I get this

attributes (Array, 7 elements)
#theme (String, 24 characters ) uc_attribute_add_to_cart
#id (String, 42 characters ) uc_product_add_to_cart_form-472-attributes
    #type (String, 6 characters ) radios
    #default_value (NULL)
    #options (Array, 4 elements)
        0 (String, 7 characters ) Color 1
        1 (String, 7 characters ) Color 2
        2 (String, 7 characters ) Color 3
        3 (String, 8 characters ) Color 17
    #ajax (Array, 2 elements)
    #title (String, 4 characters ) yeah
    #description (String, 0 characters )
    #required (String, 1 characters ) 1

I can apply a #prefix/#suffix to div wrapping all radio buttons:

I proceed like that for this result:

$form['attributes']['8']['#prefix'] = '
';
$form['attributes']['8']['#suffix']= '
';

The problem is that I want to apply this #prefix/#suffix to all options instead, I tried something like that but it doesn't work:

$form['attributes']['8']['#options'][0]['#prefix'] = '
';
$form['attributes']['8']['#options'][0]['#suffix']= '
';

So is it possible to do it this way? Any suggestion?

In your form_alter you can tell drupal to use your custom theme_radio like this:

$form['attributes']['#theme'] = 'MYCUSTOM_radio_theme';

Then in 'MYCUSTOM_radio_theme:

$element = $variables['element'];

$element['#attributes']['type'] = 'radio';

element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';

}
  _form_set_class($element, array('form-radio'));

  return '
<input' . drupal_attributes($element['#attributes']) . ' />
';


Using hook_form_alter on exposed view filters on Drupal 7 I'm having some trouble using hook_form_alter() with Views 3 and Drupal 7.

I'm unable to add an if statement to uniquely identify a view; whatever I put in, the if statement is never found to be true. However, I can easily use the form_id using the following so I'm not sure where I am going wrong!

if ($form_id == 'views_exposed_form') {
}

How do I use hook_form_alter() to uniquely alter a single view of mine?

You can get access to the view object within hook_form_alter by accessing $form_state['view']. That allows you to identify a specific view:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'views_exposed_form') {
        $view = $form_state['view'];
        if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
            // alter your exposed form here
        }
    }
}


Cron removes dblog watchdog I set the cron to run every day.

I want to prevent the cron from deleting some of the watchdog table content.

But i didn't find a way to do it, i still want the cron to run for the search index.

How can i prevent the cron from deleting dblog (watchdog) informations only ?

What you can do easily is configure how many records are kept at /admin/config/development/logging, you can set it up to 1 million, which is quite a lot.

To disable it completely (which I would not recommend), you could use a module like ultimate cron, which allows to control how often the cron job of each module is called separately.


Is there a way to easily add image swap/rollover to images on a Basic Page? I would like to do some simple image rollovers on a Basic Page, without having to write a bunch of individual CSS cases for each specific image. (Ie. - swap Img1 for Img2 on mouseover.) Is there an easy way, or a useful module that anyone knows of?  I didn't find anything on drupal.org.

You can try Rollover Filter module. This is the only module for rollover effect AFAIK.

  This module provides a simple method to enable content editors to use
  image rollover states. It makes no checks against the referenced image
  types, it simply converts [rollover] wrappers into actual rollover
  images. It does use a Javascript based approach, and causes no harm to
  images in an environment where there is no Javascript.


dynamically choose filters/fields in an aggregation table on a View I need users to customize which kind of aggregation to apply to a table (view).

Example: let´s choose counts of species X and Y in an area. This means apply two filters.
          I also want to give the option to choose fields 'species', 'area' and 'place'. The table resulting of applying these 3 filters would give a completely different table than before.

Insert all the (3) filters into the same view creates allways the same result. I don't think there is some way of let user choose 'disabling' one of the filters.

Should I create two different views (each one with its corresponding filters) inserted into a panel or there is some better way to solve that?

To make more clear, here are two screenshots:

1) Without 'Place' field (and filter): for especie Cuniculus paca, number of counts is 60.

2) With'Place' field: as for each especie we have different places names, the results are completely different.

In fact I think the question should not be exclusively about filters but also about Views.

There is a chance to avoid a Field to be 'executed' (applied to the resulting View) allways? 'Exclude from Display' with Aggregation options YES doesn't do any effect, the results are grouped by this new field also, changing completely all the results.

You can expose the filters (and for markup and additional functionality, there is a nice module Better exposed filters). You can find it when adding a filter "Expose this filter to visitors, allow tthem to change it", under the advanced sction on the right (by default collapsed) you can group them into a block and then add them to your site whereever you need them.

Hope I understood the question the right way.


How to check if a term has a published content associated with it? I have taxonomy term list called clients. I have managed to list all the terms on the taxonomy term list page by adding contents for each term, some contents are published some are not.
what I want to do is check and remove the term page link for those terms whose contents are not published and display them without the link.

There is an existing Question that handles this for views 2 and views 3: https://stackoverflow.com/questions/421972/how-to-display-only-taxonomy-terms-with-nodes-associated-to-in-views-2


Customise taxonomy select options I have a vocabulary with a user reference field. In a content type I have a field that references one or more terms from this vocabulary with a select widget. I would like to restrict the options to only the terms that are referencing the logged in user.

Drupal 7, Entityreference module is used for the user reference in the term and the select widget that I want to customize in the node is a Term reference.

EDIT: If you use Features and the field under that references the taxonomy term under question is in one of your features, there's is much easier way to do this. Add this to your my_module.field_base.inc:

// Exported field_base: 'field_user_blogs_ref'
$field_bases['field_user_blogs_ref'] = array(
    ...
    'settings' => array(
      ...
      'options_list_callback' => 'my_callback',
    ),

Neat. This has the additional benefit that it applies only to this field base as there might be more fields referencing this vocabulary. The same could probably be done with the code below as well but extra effort.

ORIGINAL ANSWER: still leaving this as this method might be useful for some cases.

I finally did this by altering the code that provides the options to the select widget. You can see how this is done in the content_taxonomy module

1) Provide a hook_field_info_alter to set the callback function

function content_taxonomy_field_info_alter(&$info) {
    $info['taxonomy_term_reference']['settings']['options_list_callback'] = 'content_taxonomy_allowed_values';
}

2) Provide the callback that returns the options

function content_taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($tree['vocabulary'] == 'user_blogs') {
        return my_callback($vocabulary);
      }
      $max_depth = (isset($tree['depth']) && !empty($tree['depth'])) ? $tree['depth'] : NULL;
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'], $max_depth)) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('- ', $term->depth) . $term->name;
        }
      }
    }
  }
  return $options;
}

Notice that the function provides the options for all taxonomy vocabularies, but if the vocabulary is of a certain type then it calls another function that returns the options the way required. If you don't use the content_taxonomy module you can copy and use the taxonomy_allowed_values function from the taxonomy module.


Privatemsg with user_relationships - views link → send a private message to use Trying to output Views link - send a private message to a user. But its displaying nothing. Using privatemsg 6.x - 2.x Dev version and user_relationships 6.x - 1.x

solved problem with the code below:

<?php
$profile = content_profile_load('profile', $data->users_user_relationships_uid);
$url = privatemsg_get_link(array(user_load($profile->uid)));
print '
'. l(t('Send a private message to the author'), $url, array('attributes' => array('class' => 'lichnoe'))) .'
';
?>


How do I use render() for my custom content? I am creating a custom module to read content from text files and generate various custom content types I have defined on a project.  Some will have specialized lists and tables and all will have specific class assignments.  I can easily generate the appropriate markup added to the text and send it to the node->body, but have been researching render().

I understand that render takes an array that encodes the content and styling, but cannot find a framework for the array to know how to structure it for my content.

How does render work?

There is no magic framework involved (just magic array structures). You just need to build up your array (Or in your case, extend $node->content in hook_node_view() if you want to alter how a node is displayed).

Basically, a render array is a nested array with properties (always start with a #) and child-elements, which are assumed to be another render-array. drupal_render() will then dig itself through and convert it to HTML.

There are basically three things you can do, define a #type (types are defined in hook_element_info(), see system_element_info) including the necessary properties, define a #theme function and the necessary properties or just simply #markup, which is simply going to print whatever is in it (Note that #markup actually #type => markup, which is added automatically)

A basic example:

<?php
$render_array = array(
  '#type' => 'cointainer',
  '#attributes' => array('class' => array('your-class')),
  'child_element' => array(
    '#markup' => t('Some text'),
  ),
  'a_table' => array(
    '#theme' => 'table',
    '#rows' => $rows,
    '#header' => $header,
  ),
);
$node->content['your_module'] = $render_array;
?>

Assuming that the node template uses render($content), this will result in
Some text
...

You can also directly return such an array in a page callback function, see userpoints_list_transactions() for an example.

I have a feeling that you are however asking the wrong question: Note that is only for rendering, you can not store anything in this structure. To store that, you should first create the necessary fields on your content types and put your data in it, if you don't want it to be just text within the body. Also have a look at Display Suite, which gives you a lot of control on how to display your fields.


Why drush fails to rsync between my two local instances? I'm trying to synchronize two local drupal repositories using the following command:

drush rsync

My environment:
 - drush 6.1
 - Mac os X 10.9
 - drupal 7.24

I have followed standard security recommendations for Drupal and configured
permissions with:

MBPC:files pc$ pwd
/Users/pc/Sites/mysite.dev/sites/default/files
MBPC:files pc$ ls -al
total 8
drwxrwx---+ 8 _www  staff  272 18 jul  2012 .
drwxr-xr-x+ 4 pc    staff  136 23 nov 15:08 ..
-rwxr-----+ 1 pc    _www   477 21 nov 15:19 .htaccess
drwxrwxr-x+ 3 _www  staff  102 18 jul  2012 color
drwxr-xr-x+ 3 _www  staff  102 22 nov 09:53 ctools
drwxr-x---+ 3 _www  staff  102 23 mai  2012 pictures
drwxr-x---+ 3 _www  staff  102 23 nov 16:24 private
drwxr-xr-x+ 2 _www  staff   68 24 oct 17:37 styles

The user pc is a member of the _www group.

The .htaccess file contains (following the latests Drupal security warnings) as follows:

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

There is a similar .htaccess file in the private subdirectory.

I'm using the following command:

$ drush rsync @mysite.dev @mysite.local

and I get this error message:

You will destroy data from /Users/pc/Sites/mysite.local/ and replace with data from /Users/pc/Sites/mysite.dev//
Do you really want to continue? (y/n): y
rsync: failed to set times on "/Users/pc/Sites/mysite.local/sites/default/files": Operation not permitted (1)
rsync: recv_generator: mkdir "/Users/pc/Sites/mysite.local/sites/default/files/color" failed: Permission denied (13)
*** Skipping everything below this failed directory ***
rsync: recv_generator: mkdir "/Users/pc/Sites/mysite.local/sites/default/files/ctools" failed: Permission denied (13)
*** Skipping everything below this failed directory ***
rsync: recv_generator: mkdir "/Users/pc/Sites/mysite.local/sites/default/files/pictures" failed: Permission denied (13)
*** Skipping everything below this failed directory ***
rsync: recv_generator: mkdir "/Users/pc/Sites/mysite.local/sites/default/files/private" failed: Permission denied (13)
*** Skipping everything below this failed directory ***
rsync: mkstemp "/Users/pc/Sites/mysite.local/sites/default/files/..htaccess.bVe3a4" failed: Permission denied (13)
rsync: failed to set permissions on "/Users/pc/Sites/mysite.local/sites/default/files/styles": Operation not permitted (1)
rsync: failed to set times on "/Users/pc/Sites/mysite.local/sites/default/files": Operation not permitted (1)
rsync: failed to set permissions on "/Users/pc/Sites/mysite.local/sites/default/files/styles": Operation not permitted (1)
rsync error: some files could not be transferred (code 23) at /SourceCache/rsync/rsync-42/rsync/main.c(992) [sender=2.6.9]
Could not rsync from /Users/pc/Sites/mysite.dev// to /Users/pc/Sites/mysite.local/                                                              [error]

You cannot change the file timestamps or change permissions by being a member of a group, you have to be the file owner, or root. If you cannot be the other of that file, you might need to avoid trying to set permissions at all.

So you may try to modify your drushrc file (e.g. sites/default/drushrc.php) and add the following arguments for rsync command:

$command_specific['rsync'] = array('mode' => 'rlptzO', 'verbose' => TRUE, 'no-perms' => TRUE);

If running rsync on remotes, edit your aliases.drushrc file (e.g. sites/default/aliases.drushrc.php) and add something like:

$aliases['mysite.dev'] = array(
    // here are your settings such as uri, root, remote-host, etc.

    'command-specific' => array (
      'rsync' => array('mode' => 'rlptzO', 'verbose' => TRUE, 'no-perms' => TRUE),
    ),
);


login block has disappeared from /user The content region throughout the site seems to have disappeared.  I believe this might be a result of some mishandling of the default settings in Omega.

As a result the login prompt is gone from /user and I'm currently logged out without a way to log back in and fix it.

Any idea how I can login to the site without going to /user or how I would go about editing Omega/delta so that I can bring back the content region without logging in?  This site is still local/on my development server.  So I can still access the files.

Attached is a screenshot of what I'm looking at for those who are confused.

you could print the login block programmatically in (the top of ..) your page.tpl.php like

<?php
 $block = module_invoke('user', 'block_view', 'login');
 print render($block['content']);
?>

clear caches through drush if possible

drush cc all


How to create a "history" of activity? I've a site with users that can create and edit contents, vote, flag, comment, etc.
I would like to have a page with a history of every action, something like:

on day X user has create the content "Title".
on day X user2 has commented "Title 1".
and so on.

Is there something like this?
I've found Activity, but for D7 there is only a "dev" version, released con july 2012.

Another way could be to create, with Rules or a custom module, custom entries in Watchdog and than create a view with Views Watchdog.

Any ideas?

The Message module aims to provide specifically this functionality. It requires some configuration, as it is, like many good modules, created to work as a platform to build on, rather than as a direct solution.


Context reaction : Exclude specific block? I've got a website with 3 large contexts :
- internet
- intranet
- shop

These 3 contexts are "tight" (sorry about my english, I think this is the word).

My Block UI (admin/build/block) provides to every pages 2 blocks in my website first sidebar.

In my Shop context, I've got a specific header, footer, and about 6 blocks in the first sidebar.
The conditions are quite simples : Paths only.
- shop/*
- cart/*
and some others.

My node-product pages are in my Shop context conditions, and that's fine. (I don't want my users to lose the shop header, shop menu, shop footer and so on...) when they are on a product page.

Now, what I would like to do is to exclude 3 of my 6 side blocks on my node-product pages.

So I was thinking... What if we had an "Exclude Blocks" Reaction in context ?
That is exactly what I need to do what I'm expecting.

I tried to adjust visibility settings in block UI, but it seems that context UI overrides it...

Shall I duplicate my Shop context to have a Shop-product one ? Is that clean ?
I mean... All this context definition is correct, and I only want to exclude 3 blocks... Isn't that overkill to duplicate all my settings ?

Any Ideas ?
Thanks guys.

It might not be overkill to duplicate the context if it works ;)

Context is often used with Delta to provide layout and theme adjustments for internal pages. After setting up a few Delta layouts you will be able to specify a Context/Delta reaction and switch the applied Delta template for your Shop-product page.

Take a look at this decent Delta+Context tutorial. Good luck!

EDIT: If you're not already committed to a theme, the Omega theme has some incredible integration with Context/Delta - intro tutorial here.


Creating default object from empty value I am having issues with a template - in the template.php there is code causing a warning:

Warning: Creating default object from empty value in theme545_preprocess_html() (line 31 of /home/noramtow/public_html/sites/all/themes/theme545/template.php).

The line in questions is this:

$vars['rdf']->version = 'version="HTML+RDFa 1.1"';

The whole section of code looks like this:

function theme545_preprocess_html(&$vars) {
if (module_exists('rdf')) {
$vars['doctype'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">' . "\n";
$vars['rdf']->version = 'version="HTML+RDFa 1.1"';
$vars['rdf']->namespaces = $vars['rdf_namespaces'];
$vars['rdf']->profile = ' profile="' . $vars['grddl_profile'] . '"';
} else {
$vars['doctype'] = '<!DOCTYPE html>' . "\n";
$vars['rdf']->version = '';
$vars['rdf']->namespaces = '';
$vars['rdf']->profile = '';
}
$vars['classes_array'][] = 'body';

I'm not great with PHP - anyone have any idea how to fix this or what's causing it??
Thanks for any help you can give!!
Candace

It sounds like your system wants to make sure $vars['rdf'] is a valid object before assigning properties to it.

Try adding:

if (empty($variables['rdf']) || !is_object($variables['rdf'])) {
  $vars['rdf'] = new stdClass();
}

Just above your line 31.

For safety's sake, add it above

if (module_exists('rdf')) {

That way the object will get initialized regardless of whether the RDF module is enabled or not.


Change view & edit route or URL of Entities generated by Drupal Console I have generated a custom entity using Drupal Console.

drupal generate:entity:content

However, there is one serious problem. All the default route for the various operation related to that entity are coming under /admin/.. route. Which prevent non-admins from accessing those pages even if given permission for example to edit it.

When I generate an entity called company. My routes are as below:

View Single Entiy: /admin/structure/company_entity/{company_entity}
Add Entity: /admin/structure/company_entity/add
Edit Entity: /admin/structure/company_entity/{company_entity}/edit
Delete Entity: /admin/structure/company_entity/{company_entity}/delete
List all Enitities: /admin/structure/company_entity

Where should we edit the module to override or change these settings.

You need to edit the entity class's annotation, at e.g. module_name/src/Entity/FooEntity.php.

This is an example of what you need from the Node entity class:

links = {
    "canonical" = "/node/{node}",
    "delete-form" = "/node/{node}/delete",
    "edit-form" = "/node/{node}/edit",
    "version-history" = "/node/{node}/revisions",
    "revision" = "/node/{node}/revisions/{node_revision}/view",
}

You'll probably need to rebuild cache for the changes to be reflected.


Views Group By with profile with aggregation and relationship I am looking for solution for following problem.

Problem:

I have "article" content type.
I have list of some users who are associated with different - 2 roles.

User having role "editor" can create articles. So editors type of user have created number of contents.

Now I need to display a list of featured articles on home page using Views-block with given conditions.

Every author who have created most articles, his block should come in top of list with his recent one article.
It should be followed by author name.
I will show top 10 articles of different - 2 authors with correct author ordering. I mean  author who have created most articles should come on top followed by rest of authors.

Note: In this block one author should come once with correct order.

Resolution:

I created views block with filter criteria where content type =
'article'.
I enabled aggregation.
I make relationship with User and in fields choose COUNT(DISTINCT
Content: Title) | Aggregation settings option.
I choose Query settings: Distinct.

I tried above possible solution but unable to get correct result. I am still getting duplicate result and also the order is not correct.

Consider using the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

Curious to hear if this helps to answer this question.


Tableselect with textfields Is it possible to build tableselect form with textfield in each row?

function nowayform_form($form, $form_state) {

      $xsroads = array(
      array('id'=>'PrArcabilPodvoyskaya','xsr_name'=>t('Archabil/Podvoyskiy')),
      array('id'=>'PrArcabilSovetskaya','xsr_name'=>t('Archabil/Sovietskaya')),
      array('id'=>'PrArcabilLenina','xsr_name'=>t('Archabil/Lenina'))
      );

      $header = array(
      'xsr_name'=>t('Crossroad names')
      );

      $options = array();
      foreach ($xsroads as $xsroad){
        $options[$xsroad['id']] = array(
        'xsr_name'=>$xsroad['xsr_name']
        );
      }

      $form['table'] = array(
      '#type'=>'tableselect',
      '#header'=>$header,
      '#options'=>$options
      );

Thanks

in the options you can put another field like this:

foreach($xsroads as $xsroad){
  $options[$xsroad['id']] = array(
    'xsr_name' => $xsroad['xsr_name'],
    'xsr_input' => array(
      'data' => array(
        '#type' => 'textfield',
        '#value => 'so you wanned a field',
      ),
    ),
  );
}


Website encountered unexpected error - how to avoid? I'm having that typical problem of Website encountered unexpected error popping up sometimes and then after repairing watchdog MySQL table it all works find again.

My question is if there is a module that would do this automatically? Or any script that I could run from cron or from drupal?

I installed db maintenance module and thought it does that, but apparently no.

Thank you!

Does MySQL crash after that error? Either way your watchdog table is being corrupted. Are you running out of disk space? Make sure you are using InnoDB tables; MyISAM is prone to corruption.

You can check your table type by running this from a MySQL command prompt and looking for the Engine= parameter.

mysql> show create table watchdog;

You can also disable dblog and enable syslog instead. Syslog writes to your system logs and is much more scalable for higher traffic sites. See if that solves your problem.


Plugin to customize home page i would like to know of there's a plugin to let an authentified user customize his home page by moving and adding predifined widgets like (agenda, events ..), using drag and drop like iGoogle.

i'm still drupal newbie, any advices are welcomed.

The homebox module makes that reasonably easy to do, worth a look: https://drupal.org/project/homebox
Details from its project page:

Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.
Homebox is currently used on Drupal.org for the 'Your Dashboard' feature.


Add fields to a coded block and use them in a templated block I want to programmatically create a block to which I can add a body field, a link and an image and then create a block twig template file where I can use these fields. For the uploaded image ideally I would want to be able to use a responsive image style. Am hoping someone someone can tell me how I would do this?

Probably the easiest way to do this is a block with a settings form.

When you place a block of this class via the block layout, you can add your information in the settings.  To have another block with different settings, just place another block.

Some sample code:

 public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['my_block_text'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Foo'),
      '#description' => $this->t('my desc'),
      '#default_value' => isset($config['my_block_text']) ? $config['my_block_text'] : '',
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    $this->configuration['my_block_text'] = $values['my_block_text'];
  }
  public function build() {
    $config = $this->getConfiguration();
    $text = $config['my_block_text'];
    ...
  $block = [
   '#theme' => 'my_module_my_theme',
    '#my_text' => $text,
    ...
  ];
  return $block;
}

For images / files, you can just use the standard file form type.  The config will get the fid of the image.  In the build, you will need to load the file entity and generate the URL to the file.  (Lots of existing examples of this).

To get it all to twig, you will need to use a hook_template() implementation that defines the twig template and variables. Then pass it to the theme using the render array created in the block build code.


Is it possible to divide a field into fields? I think this is impossible. However, is it possible to change a field into fields on Drupal 7? I have a content type of author. We used the "Title" field for user full name with their title. Is it possible to change it to "First Name", "Middle Name", "Last Name", and "Title" fields?

It's definitely possible, but will require some coding. I can't work out the whole thing for you but I can point you in a direction.

You would have to create three new fields for 'first name', 'last name' and 'title' in the content type.

Then create a script that loads all of the nodes of that type with node_load_multiple then iterates through them, taking the old value of 'title' and splitting it using regex or the php 'explode' string function. Then using entity_metadata_wrapper, stick the individual values into the new fields and save the node.

Using drush, you can run the script like this: drush php-script scriptname.php


Remote attribute in mymodule.libraries.yml When creating a library, I noticed there is an attribute remote that can be added. I cannot really find any good documentation as to what it is for nor does it seem like it is required.

Questions:

What is the purpose of this remote when defining a library?
How can we be sure the value we add is correct?

Example from https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module:

font-awesome:
  remote: https://fortawesome.github.io/Font-Awesome/
  version: 4.5.0
  license:
    name: MIT
    url: https://fortawesome.github.io/Font-Awesome/license/
    gpl-compatible: true
  css:
    theme:
      https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css: { type: external, minified: true }

According to the code/comments in LibraryDiscoveryParser::buildByExtension, it's to help ensure licensing info is included for 3rd party libraries:

// If this is a 3rd party library, the license info is required.
if (isset($library['remote']) && !isset($library['license'])) {
  throw new LibraryDefinitionMissingLicenseException(sprintf("Missing license information in library definition for definition '%s' extension '%s': it has a remote, but no license.", $id, $extension));
}

It's also mentioned in the library docs, but it just says that it's a good idea to include the remote info, not why. It doesn't appear to be used in the code other than the licensing, so I think it's safe to assume it's a reference/info value for now. There is no incorrect value to-to-speak, but it would make sense to set it to the URL of the project you're referencing.


How do I include an affiliate script? I am trying to add an affiliate script to my Drupal 7 website.
I am doing this in a custom block.

Specifically, I create a block, select the scripts text format in my WYSIWYG Editor, add the script and save. I then add the block to the page I want.

This seemed to work for a few months and then suddenly, it disappeared and stopped working (probably due to an update).

The script has the below format:

<script src="https://sbhc.portalhc.com/123456/searchbox/234567"></script>

I have tried adding the code using all text formats (Plain Text, Scripts, Full HTML etc.). I've also tried adding it using one text format and then switching to another. I've also tried adding it through the Source button on the WYSIWYG editor.

As confirmed above, the script did work for a few months before disappearing and no extra modules have been added. I can confirm the script is correct because I can see what it generates on the provider portal.

If you don't want to code it manually, you can check this module JS injector which lets you inject JS code into your site.

  Allows administrators to inject JS into the page output based on
  configurable rules. It's useful for adding simple JS tweaks without
  modifying a site's official theme - for example, a 'nighttime' color
  scheme could be added during certain hours. The JS is added using
  Drupal's standard drupal_add_js() function and respects page caching,
  etc.

  This module is definitely not a replacement for full-fledged theming,
  but it provides site administrators with a quick and easy way of
  tweaking things without diving into full-fledged theme hacking.

  The rules provided by JS injector typically are loaded last, even
  after the theme JS, although another module could override these.


How to pull the value of a taxonomy term into the html.tpl.php files How does one  pull the value of a taxonomy term into the html.tpl.php file?

I know this needs to be done in the template.php file, no?

You should use the function template_preprocess_html in your template.php.

For example.

function yourtheme_preprocess_html(&$vars){
    // $tid - id of your taxonomy term
    $term = taxonomy_term_load($tid);
    $vars['head_title'] = $term->name;
}

Also, copy the html.tpl.php file to the directory in your theme, where all the template files are located. And clear cache.


Access Node image within Page template I need to access a Node's image field within the page.twig.html template in order to display it in relation to certain page-level elements such as primary/secondary menus and the page title.

In node.html.twig, I'm able to access it like so:

{{ content.field_responsive_hero_image.0 }}

but in page.html.twig if I try

{{ node.field_responsive_hero_image.0 }}

I get the following error:

Exception: Object of type Drupal\image\Plugin\Field\FieldType\ImageItem cannot be printed

I'm familiar with the workaround of loading the image with

<img src="{{file_url(node.field_responsive_hero_image.entity.fileuri)}}" />

However, I then lose the title and alt attributes (bad for 508 compliance) as well as the automatic resizing of the image served based on screen size (bad for SEO rankings).

How do I access the Node's image at a page-level?

In a preprocess hook (preferred):

/**
 * Implements hook_preprocess_HOOK() for page.html.twig.
 */
function MYTHEME_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $variables['image'] = $variables['node']->get('field_image')->first()->view('full');
  }
}

Or in Twig:

{{ node.field_image.0|view('full') }}

To use |view install the module https://www.drupal.org/project/twig_tweak