# Question
Title: emailing users in user reference field with rules
I am working on a site for an academic conference. Right now, we have two content types (1) proposal and (2) peer review. In the proposal content type, an author can add multiple presenters to a user reference field. When the node is saved, I have a rule that loops through the user reference field and sends an email notification to all the presenters that the proposal has been submitted. Works great!

Now the question. I want to send an email to that same group of users when someone else posts a peer review. I have figured out how to notify the "author" of the proposal but I want to notify all the users listed in the node reference field.

Right now my rule is set up as follows: Event: after saving new content Conditions: content is of type \> peer review Actions: Fetch entity by property: -Value: node -Value: node reference -Data selector: node Variable label: Fetched proposal Variable name: fetched\_proposal

Then I have a loop: Data selector: fetched-proposal Current list item Variable label: Current proposal item Variable name: proposal\_list\_item

Then I have an action to send the mail. Since I've looped over the proposal connected to the peer review, I have available a token for the presenter field which contains the node reference. I've used that token in the "To" value field.

I think this should work but I don't get emails when testing.

When I check my log messages I see this error: The loop Loop () fails the integrity check and cannot be executed. Error: Data selector fetched-proposal: for parameter list is invalid.

Can anyone help me figure this out?

# Answer
I think you are fetching the user reference wrongly. You should try this:

* On the Action:Fetch Entity by ID
* Value:User
* Data selector :node:field-name:uid (this is your user reference field
* Variable label:Fetched entity
* Variable name :user\_entity

Then you are good to go!
> 0 votes

---
Tags: 7, users, rules
---


# Question
Title: Is hook_file_download the right hook for taking action when a private file is downloaded?
I'm trying to create a module that will fire send an event via google analytics' Measurement Protocol API when a file is downloaded. These files are all in the private file system outside of the document root.

`hook_file_download` looks like a somewhat likely candidate for triggering an http request to google analytics, but since the hook is responsible for access, it seems possible that another module might deny access after this version of the hook is run, and google analytics would get an event even in cases where the download didn't go through. If there a better hook that would be run after all the access check have finished? I should probably mention that I am using the media module.

Supplementarily, the existence of both `hook_file_download` and `hook_file_download_access` is confusing since they both claim to control access to files. Is it a correct understanding that `hook_file_download_access` basically controls whether a user has access in relation to the entity the file is attached to (so likely would control whether the download link is displayed at all or not), and `hook_file_download` only applies to private files, and checks on access after a request for the file has been made?

## Follow Up

I ended up implementing two hooks: `hook_file_download` and `hood_file_transfer` which as far as I could tell is undocumented in the drupal api site as a hook. Both of those hooks calls a function passing the $uri parameter which in turn builds the google analytics request and then sends an http request. That seems to cover the two different cases when a file download passes through drupal for my setup.

# Answer
> 1 votes
If I recall correctly, there's an access pass before hook\_file\_download is ever called. hook\_file\_download is called so you can modify headers, or do a last minute abort on the download.

So on the assumption that no one else is calling that hook (which you should check for the modules you have installed), a hook\_file\_download implementation is a perfectly fine place to do something like call a Google API. The only caveat is that if you're calling a web service, you want to make sure it doesn't take so long as to screw up the download.

I'm fairly certain that the hook will be called for any file scheme (i.e., "private:", or a custom scheme). You may want to look at the Drupal 7 Example module "File" example, which I believe shows a hook\_file\_download implementation.

The behavior in Drupal 8 is similar, BTW.

---
Tags: 7, hooks, files
---


# Question
Title: Display all comments of node without pager (300+ comments)
I have a content type with threading comments. The max number of comments per page is set to 300 (that is the absolute max). If there is more than 300 comments - they get paged.

How do I show all comments of the node without the pager (300+ comments)?

This is a desired function knowing the negative impact on UX.

I couldn't find any theme functions/ hooks that can be used for setting a new max for comment pagers. Please, do not suggest to render comments via Views.

# Answer
It's stored in a variable per content type, you can override it like so:

```
variable_set('comment_default_per_page_CONTENT_TYPE', 500);

```

Where CONTENT\_TYPE is the machine name of the content type.

If you want to change the options in the UI, you can do it through a form alter:

```
function MYMODULE_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node_type'] == 'foo') {
    $new_options = drupal_map_assoc(array(10, 30, 50, 70, 90, 150, 200, 250, 300, 500, 1000));
    $form['comment']['comment_default_per_page']['#options'] = $new_options;
  }
}

```
> 4 votes

# Answer
Paging on comments is provided in Drupal Core without any contribute modules.

If you go to your content type configuration screen:

```
D7 Path: admin/structure/types/manage/[node-type-name]

```

You will see there's a Comment field-set/tab(d7) with some options. The option you want to check out is the comments per page setting. Select the number you'll like for when a page should break and save your settings. Once you're comment have pass that threshold you will see a pager for your comments. See in attached screen also

Now for the comment counts there a variable available to you in Drupal 7 in the node template. The name of that variable is $comment\_count.
> 1 votes

# Answer
> How do I show all comments of the node without the pager (300+ comments)?
>
> This is a desired function knowing the negative impact on UX.

I highly advice not to display/load 300 comments at the same time, not only it will make your page slower, but also it will increase your server costs. Will all users read all 300 comments? I doubt it, maybe a few might.

> use an endless scroll to get rid of the pager.
>
> Sadly I'm not familiar with the implementation of endless scroll widgets. – Eyal

This is the right approach. All you need is a little jQuery magic using AJAX load() method

First, set comments per page to 10.

Second, you need to modify the comments-wrapper.tpl.php file. This is bartik's:

```
<div id="comments" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php if ($content['comments'] && $node->type != 'forum'): ?>
    <?php print render($title_prefix); ?>
    <h2 class="title"><?php print t('Comments'); ?></h2>
    <?php print render($title_suffix); ?>
  <?php endif; ?>

<div class="ajax-wrap"> // added this wrapper

  <?php print render($content['comments']); ?>

  <div class="loadmore"></div> // added this div to load the next page stuff here

</div> // closes ajax-wrap

  <?php if ($content['comment_form']): ?>
    <h2 class="title comment-form"><?php print t('Add new comment'); ?></h2>
    <?php print render($content['comment_form']); ?>
  <?php endif; ?>
</div>

```

Added the `ajax-wrap` div since there was no wrapper that only wrapped the comments and the pager as we don't want the "add comment box/form". We will load the next page comments inside `loadmore` div.

Third, we are going to use jQuery Visible to check if the `loadmore` div is visible on your browser window. If it's visible, we are going to load the next page comments using AJAX load() method

```
(function ($) {
!function(t){var i=t(window);t.fn.visible=function(t,e,o){if(!(this.length<1)){var r=this.length>1?this.eq(0):this,n=r.get(0),f=i.width(),h=i.height(),o=o?o:"both",l=e===!0?n.offsetWidth*n.offsetHeight:!0;if("function"==typeof n.getBoundingClientRect){var g=n.getBoundingClientRect(),u=g.top>=0&&g.top<h,s=g.bottom>0&&g.bottom<=h,c=g.left>=0&&g.left<f,a=g.right>0&&g.right<=f,v=t?u||s:u&&s,b=t?c||a:c&&a;if("both"===o)return l&&v&&b;if("vertical"===o)return l&&v;if("horizontal"===o)return l&&b}else{var d=i.scrollTop(),p=d+h,w=i.scrollLeft(),m=w+f,y=r.offset(),z=y.top,B=z+r.height(),C=y.left,R=C+r.width(),j=t===!0?B:z,q=t===!0?z:B,H=t===!0?R:C,L=t===!0?C:R;if("both"===o)return!!l&&p>=q&&j>=d&&m>=L&&H>=w;if("vertical"===o)return!!l&&p>=q&&j>=d;if("horizontal"===o)return!!l&&m>=L&&H>=w}}}}(jQuery);

// The above lines of code is the minified version of jQuery Visible.js see  https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery

   (function Forever(){ // we create a function called Forever

      var graburl = $('.pager-next a').attr('href');   // we create a variable called graburl which gets the url inside the href of the pager-next div class

      $('#comments .pager').css("display", "none"); // hides the comments pager div

      if ($('.loadmore').visible(true) && graburl != null) { // we check if the load here div is visible and also if the grab url is not empty (will be empty when we reach the last page, since there is no "next" button.

          $('.pager').remove(); // we remove/delete the pager from our website as we already grab the href with graburl variable and also we don't need this pager anymore.
          $('.loadmore').html('<center><img src="https://i.stack.imgur.com/RCEAe.gif"></center>').load('' + graburl + ' .ajax-wrap').attr("class", "loaded"); // We place a loading gif. Then load the content inside the ajax-wrap div of "next page". Then we rename the div loadmore to loaded.

          }

       setTimeout(Forever, 1); // if it was 1000 we would run this code every 1 second, but since it is 1, we run this code every millisecond. Basically we are looping this code.

   })();

})(jQuery);

```

The cool thing, if for some reason the user browser blocks jQuery, they will be able to browse the comments using the pager.

**PS:** In comments-wrapper.tpl.php you should move the comment form above the comments, that way people don't have to scroll all the way to the end to get the comment box. (something I did not do)
> 1 votes

---
Tags: 7, comments, paging
---


# Question
Title: Restrict search results to only documents user can see
In my application, I have a content type called `resource`. In the resource content type, I have an `entity reference` that defines which roles should be able to view that resource.

When somebody is logged in as a certain role and does a search, he is able to view documents that don't belong to his role. How can I `hook` to the search results and remove the ones he should not be able to see?

Thanks

# Answer
I think this module will help you Access by term and don't forget to enable Node access settings in search api settings.
> 0 votes

---
Tags: search, theming
---


title: How to use EntityFieldQuery with dates?

text:
# Question
Title: How to use EntityFieldQuery with dates?
I need to select entities with specific dates.

How should the following be formatted. Do I need to parse 15-May-2010

Also how I get the error page.

```
function events2() {

$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('status', 1, '=')
  ->propertyCondition('type', 'event')
  ->propertyCondition('field_event_date', '15-May-2010', '=');

$result = $query->execute();

 return $result;

}

```

# Answer
With Drupal 7 and Date module 2.2:

```
$query = new EntityFieldQuery;
$result = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'event')
->propertyCondition('status', 1) // Getting published nodes only.
->fieldCondition('field_dates', 'value2', date("Y-m-d"), '<') // end date before today
->execute();

```
> 12 votes

# Answer
I haven't used `EntityFieldQuery`, but looking at the code suggests that you'll need to make sure that `field_event_date` is stored as a MySQL DateTime field, and that the format of the argument is in one of the preferred formats:

> As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted here, too. For example, '98-12-31', '98.12.31', '98/12/31', and '98@12@31' are equivalent.
> 2 votes

# Answer
Here is the code for checking date range using BETWEEN keyword,

```
$month = $form_state['values']['month'];
$year = $form_state['values']['year'];
$num_padded = sprintf("%02d", $month);
$first_day = date($year.'-'.$num_padded.'-01 00:00:00');
$last_day =  date("Y-m-t 23:59:59", strtotime($first_day));
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'YOUR_CONTENT_TYPE')
            ->fieldCondition('DATE_FIELD', 'value', array($first_day,$last_day), 'BETWEEN');

```
> 2 votes

---
Tags: database
---


# Question
Title: Setting up local dev, "call to undefined function" from a module that I uninstalled a few months ago
I'm attempting to set up Acquia Dev Desktop with a database dump and git repo from Pantheon.

I was using the Computed Field module in this project but I rewrote the code in my own custom module and uninstalled Computed Field a couple months ago (uninstall from modules page and removal from my git repo afterwards). I had no errors on the Pantheon site related to this, and I just made the db and code dump yesterday.

However, when I import into Dev Desktop, I'm getting the following error:

> Call to undefined function computed\_field\_entity\_property\_callback() in /Users/pk/dev/mysite/sites/all/modules/contrib/entity/modules/field.info.inc on line 30

`computed_field_entity_property_callback()` is a function defined in the Computed Field module, which shouldn't exist on my site anymore. So somehow there is a "ghost" left in my db somewhere-- **how can I locate where this error comes from**, because I can't even get a page to load-- all I'm getting is this error.

# Answer
Most of the time this a cache problem.

1. First try to clear the cache via Drupal (Clear cache button). Or use Drush (`drush cc all`).
2. You can clear the cache tables by truncating them. Check all the tables with `cache_` prefix.
3. If `#1` and `#2` didn't fix the problem then check if you have `Memcache` or similar installed. Flush the cache as well.
4. Another thing could be `APC` or similar opcode cache.
> 1 votes

---
Tags: installation
---


title: Image Styles Broken?

text:
# Question
Title: Image Styles Broken?
I have a new view that is coming up with a new issue, there is a "main image" for every entry, and for some reason after loading the page, almost all images break. But what's odd is that when you click on the Title Number or the Image (whichever you want to get to the content), the images in the format of "Original Image" loads almost automatically.

My link is below, let me know if it is something I am not doing right (and can't seem to see it at all)

http://cocemproject.org/pueblo/survey-register

Thanks!

-----------UPDATE---------------

If I stylize the main image as "Original Image", the image shows - but when it is stylized to my new Image Style "125x125" (which is 125px by 125px Scaled & Cropped), it breaks.

-----------UPDATE---------------

I tried a different Image Style that I know works elsewhere on the site, and it doesn't work here. Also, tried the format "Colorbox" just out of curiosity, and it makes the image field image disappear completely, not even a broken picture.

-----------UPDATE---------------

I also right-clicked the broken image and clicked "View Image", it leads me to http://cocemproject.org/pueblo/sites/default/files/styles/125x125/public/DSC\_0131\_1.jpg?itok=kGUeABuy but there is nothing there.

-----------UPDATE---------------

Now, I have gotten around to looking into my files and it appears that the Styles were never generated for these images.

-----------UPDATE---------------

Saw https://www.drupal.org/node/1109312#comment-10021707 and that clean URLs might be causing this, disabled the module, ran cron, cleared caches. Still no change.

-----------UPDATE---------------

Below are the folders with the permissions. I tried altering them and then flushing caches and running crons (just to hit everything).

-----------------UPDATE------------------------

Turns out that these photos are too large for this site, and Drupal's just giving up on applying the styles to them. What's odd is that this site is technically a complete copy of an old one, just better planned out to incorporate recent changes on the old version. However, I used the exact same styles with the exact same pictures and had no problems. I'm still on the same server, just a different folder. What might be causing this?

# Answer
This should be a folder permission issue. What you need to do is check the image style folder (`sites/all/default/files/styles`) if it is writable. You can use `ls` command to check the directory permission. To change the permission you either need `chmod` or `chown` commands to make the folders writable by Drupal.

Once the permission are correct you may need to flush the cache for images. If you have Drush you can do that by running `drush image-flush STYLE_NAME` or by clearing them all by running `drush image-flush all`.
> 1 votes

---
Tags: views, media
---


# Question
Title: how to include main navigation twice with different display
i started working with drupal 8 few days ago.
I am working on theming with Twig.
I included the main Navigation on the header, after the activation of twig debug mode , i followed the suggestion of twig and i created menu-main.html.twig contains the html respresentation of the links and i had this display:
My Problem is :
I included the Main navigation on the footer too but it appears the same way as the header but i want to change the display to be like this:
What should i do ?

# Answer
Don't rely on a hardcoded class in your overridden template to style the menu, but instead rely on a container to style it (for example the containing block or region).
> -1 votes

---
Tags: theming, 8, navigation
---


# Question
Title: Teaser is missing CKEditor when uncollapsed
I have text with summary fields on my entity and for some reason the ckeditor is present only on the body, not on the teaser if I uncollpse it. What could be the issue?

# Answer
> 4 votes
Never use "Text and summary" fields. It's a sad/unfortunate fact that Drupal 8 didn't manage to remove them.

Instead, create a *separate* (independent) summary field.

---
Tags: entities, 8, wysiwyg
---


# Question
Title: How to use multiple text fields in widget "image" in content type
I'm new in Drupal and I'm working on a website built in Drupal. I want to use multiple text fields like title, medium, photo credits with image widget in content type. I have attached two screen-shots to make clear what I really want to do.

Please help to find out the way to do this. I'll be thankful to you.

# Answer
> 0 votes
You can take a look on Image Field Caption module.

Adds an extra text area for captions on image fields.

Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

Media module also work for you.

---
Tags: entities, media
---


# Question
Title: How can I create a custom ajax callback command?
I found different type of ajax commands like htmlCommand, invoke command etc. I want to create a custom ajax command that sets the response of ajax callback as the value of specifying markup in the callback argument. Is it possible? I created one as per this tutorial.

```
    public function ajax_call_back_function() {
       $response = new AjaxResponse();
       $element  = $form_state->getTriggeringElement();
       $returnDelta = $element['#array_parents'][2]; // get levels
       $delta = $element['#value']; // eg : 944 THis is the ata i want to set as the value of markup
       $response->addCommand(new ReadMessageCommand($delta, $returnDelta));
       return $response;
    }

```

The `ReadMessageCommand` class is the following.

```
    class ReadMessageCommand implements CommandInterface {
      protected $message;
      // Constructs a ReadMessageCommand object.
      public function __construct($message,$level) {
      $this->message = $message;
      $this->level = $level;
      }
     // Implements Drupal\Core\Ajax\CommandInterface:render().
    public function render() {
       return array(
      'command' => 'readMessage',
      'message' => $this->message,
      'level' => $this->level,
     );
   }
  }

```

I include a JavaScript file.

```
    (function($, Drupal) {
      Drupal.AjaxCommands.prototype.readMessage = function(ajax, response, status){
      $('#edit-field-region-management-'+response.level+'-valueregion').val(response.message);
     };
    })(jQuery, Drupal);

```

The controller class is the following.

```
   class AjaxCommandsAddController extends ControllerBase {
     public function messagesPage() {
       $page[] = array(
         '#type' => 'markup',
         '#markup' => $content,
     );
// Attach JavaScript library.
       $page['#attached']['library'][] = wms_ajax_commands/wms_ajax_commands.commands';
       return $page;
      }
    }

```

But when executing, I get the following error.

> Fatal error: Class 'Drupal\Core\Ajax\ReadMessageCommand' not found in Path-to-module/src/Plugin/Field/FieldWidget/RegionWidgetType.php

# Answer
> 4 votes
It seems like you have a namespace error(s). The error happens in a file you didn't mention `RegionWidgetType.php`. It's trying to use `Drupal\Core\Ajax\ReadMessageCommand` which as I understand it is something you made. Which means that the namespace should definitely not be `\DrupalCore\...` for the auto load to work.

The name space of your custom files should be `Drupal\MODULE_NAME\folder\structure`

---
Tags: 8, ajax
---


title: Disable rewrite of html_tag?

text:
# Question
Title: Disable rewrite of html_tag?
In my module

```
    function hook_page_attachments(array &$page) {

      $og_image = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'property' => 'og:image',
          'content' =>   'http://example.com/pic.php?id=839813.jpg&size=300',
        ),
      );

      $page['#attached']['html_head'][] =  [$og_image, 'og:image'];
}

```

On the page the results look like this

```
<meta property="og:image" content="http://example.com/pic.php?id=839813.jpg&size=300" />

```

The & is replaced for html use. Can I avoid that or added meta tags in another way?

# Answer
I build a workaround. I created a custom path in drupal that redirect to the external image url like /image/{img-id} . If anyone find an answer on the main question please post.
> 0 votes

---
Tags: 8, meta-tags
---


# Question
Title: remove description in views exposed filter
Is it possible to remove the description of views exposed filter widgets in other way as css display:none?

I tried to unset $widget-\>description, but without any success.

# Answer
it can be done either via theme or custom module:

```
function MODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id)
{
    if($form['#id'] == 'FORM_NAME')
    {
        $form['#info']['filter-FIELD_MACHINE_NAME']['label'] = '';
    }
}

```

use `dpm($form);` from the Devel Module to get the complete form name, and field names for non-content type filter criteria:

A suite of modules containing fun for module developers and themers ...

> Devel Helper functions for Drupal developers and inquisitive admins. This module can print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took (short is good - use cache for complex queries). Also a dprint\_r($array) function is provided, which pretty prints arrays. Useful during development. Similarly, a ddebug\_backtrace() is offerred.

Be aware that removing the label (description) will change the layout of the filter itself, so some css might be required to fix things.
> 0 votes

# Answer
The question has already an answer, that is very technical, as it is supposed to be on this site.

Base-level developers, who find hard to dig through a ton of information like Drupal's dump($variables), can fulfill the 'impossible' task of removing the description from an exposed filter via the Better Exposed Filters module. https://www.drupal.org/node/766974

The module can tweak exposed filters in various ways. One is to override the description, so you may want to override the exposed filter's unwanted text with a blank space.

HTML in the override form gets interpreted, so you can enter the corresponding HTML entity. If a single blank space is still "too big", wrap it with a and style it to 1x1 pixel size.
> 0 votes

---
Tags: views
---


# Question
Title: How to insert multiple tables into their respective backup tables using insert sql?
For the purpose of backup and restore i want few tables to be just backup while performing a restore process. I have created backup tables but now whenever i do restore process it shows:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062      Duplicate entry '1' for key 'PRIMARY':

```

Actually both tables have same schema and same primary key so whenever it try to update it there is conflict. Can anyone please tell me how to do it ? One more thing can i use drupal Features to do it and if yes please let me how.

# Answer
> 0 votes
You should use

### Merge Queries

> a Merge query is a combination of an Insert query and an Update query. If a given condition is met, such as a row with a given primary key already existing, then an Update query is run. If not, an Insert query is run.

The above is for drupal

If you are using mysql then you can use `UPDATE` or `ON DUPLICATE KEY UPDATE`

# Answer
> 0 votes
I have resolved the issue by doing following thing, hope it may be useful to anyone too.

The cause of the problem is that the parent table and its corresponding backup table have same schema so whenever Restore process is took place it just encounter a problem due to same primary key on both tables. Hence to overcome it,first remove Primary Key from backup table as:

```
ALTER TABLE $backup_tbl_name DROP PRIMARY KEY, CHANGE $primary_key $primary_key int(11) NOT NULL

```

and then add a new column 'ID' to all backup tables using :

```
ALTER TABLE $backup_tbl_name ADD `id` BIGINT unsigned NOT NULL   AUTO_INCREMENT COMMENT 'Auto increment field for backup table.' PRIMARY KEY

```

and making this newly added column Primary key of backup table.

And at last INSERT query has to be modified as well as during insertion newly added column also has to be pass. And it modified as:

```
INSERT INTO $backup_tbl_name SELECT * , NULL FROM $tbl;

```

---
Tags: database
---


title: Connect multiple AD's to one site

text:
# Question
Title: Connect multiple AD's to one site
Is it possible to connect 2 AD's to drupal intranet to have single sign on (with the LDAP module)?

thank you in advance

# Answer
> 0 votes
Yes you can. After installing the ldap module:

1. Set up the two servers via: admin/config/people/ldap/servers
2. Set up authentication via: admin/config/people/ldap/authentication. Make sure to "Check all LDAP server configurations to use in authentication."
3. Do your other settings as per your requirements.

---
Tags: users
---


# Question
Title: How do I move content from one field to another?
I have created a field called `people_field`. I used this in another content type as an existing field. The problem is now it's screwing up a view that uses the field in a relationship.

So what I want to do is keep the content but make move all the data from one filed into a new field, if that makes sense?

I can't figure a way to do this without losing all my data.

# Answer
> 5 votes
Let's consider that your content type is `article` and existing field is `field_old` and new field is `field_new`. Then you can use the script at once to copy all the data from old field to new field.

```
$article_nodes = node_load_multiple(array(), array('type' => 'article'));
foreach ($article_nodes as $article_node) {
  $article_node->field_new = $article_node->field_old;
  field_attach_update('node', $article_node);
}

```

Am not sure, if this is what you are looking for.

# Answer
> 2 votes
If you have a content type A and their have two field "field\_old" and "field\_new", then you can transfer data like this code :

```
$node_load_multiple = node_load_multiple(array(), array('type' => 'A'));
foreach ($node_load_multiple as $node) {
 $node->field_new = $node->field_old;
 unset($node->field_old);
 field_attach_update('node', $node);
}

```

This code will transfer one field value to another for a perticular content type and your another content type have now different field with it's own data.

**Note**: Create a menu item and in callback of that menu item put this code and run your menu.

# Answer
> 1 votes
# Step 1: Create a Rules Component

Have a look at this example of a **Rules Component** (in Rules export format):

```
{ "rules_copy_a_field_value_to_another_field" : {
"LABEL" : "Copy a field value to another field",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_people_field_old" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_people_field_new" } }
],
"DO" : [
  { "data_set" : {
      "data" : [ "node:field-people-field-new" ],
      "value" : "[node:field-people-field-old]"
    }
  }
]

```

} }

Some more details to further explain the above above example:

* This Rules Component will be used in "Step 2" below.
* In my case I have a field with machine name `field_people_field_old`, and I want all its content to be copied to `field_people_field_new`.
* I also added the Rules Conditions `Entity has field` to make that those fields are available for further processing in this Rules Component.

I've not added a Rules condition here about selected content types, that's possibly an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the `Entity has field` conditions should be sufficient already.

If you want, just grab (copy) the exported rule above, change all occurrences of the machine names of those fields to match the machine names of your fields. After doing so you can simply import this Rules Component in your own environment.

After you imported this Rules Component, navigate to `admin/config/workflow/rules/components` in your own site. Then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says ***`Switch to direct input mode`***. Then you'll be able to enter some ***Node identifier*** and hit the ***`Execute`*** button. Depending on the node id you selected (i.e. if it has that field, and if the Rules Condition is satisfied), your node will be updated accordingly.

After you're confident your Rules Component works perfect for all variations of your nodes, move on to step 2 below.

# Step 2: Let VBO to the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: **Execute the Rules Component from Step 1**.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO".

Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

PS: I'm assuming this question is about D7.

---
Tags: entities
---


title: Theme Simplenews with MailSystem

text:
# Question
Title: Theme Simplenews with MailSystem
I would like SimpleNews use another theme (Bartik for example) than the admin one (Seven). I configured MailSystem to use "Bartik" as theme to render emails, as written in SimpleNews README.txt:

> The template files are self documented listing all available variables. Depending on how the mails are sent (e.g. how cron is triggered), either the default or the admin theme might be used, if one has been configured. To prevent this, Simplenews supports the mail theme setting from the mailsystem module (http://drupal.org/project/mailsystem). Install it, choose the mail theme and the newsletter templates from that theme will be used no matter which other themes are enabled.

In the simplenews.module file, I got the line:

```
2674.  $theme = function_exists('mailsystem_get_mail_theme') ? mailsystem_get_mail_theme() : path_to_theme();

```

And `$theme` is evaluated as "theme/bartik". Great, but it keeps use the "simplenews-newsletter-body.tpl.php" file in "theme/seven" directory.

I struggle with that for weeks now, any help would be welcome!

Thanks.

# Answer
> 1 votes
You do have the template files in themes/bartik\*? Make sure to rebuild the theme registry.

This feature is relatively new but we've used it several times for ourself now and have multiple confirmations from other people that it works for them.

Note that the only thing that "using a theme" means is the place where Simplenews looks for the template files. Additionally, Mimemail also looks for for either the css files to embed or the mail.css (Hint: Older versions of Mimemail have their own setting, switch to the most recent dev version of Mimemail to get that fixed).

It does in no way take over the look and feel of your website, if you're looking for that, have a look at HTML Mail.

\*Hint: You should *not* alter a core theme or add files into it, instead, create a subtheme and put that in sites/all/themes. Try Google to find more information about subthemes.

# Answer
> 0 votes
It's been a while but this issue is still hanging around:

https://www.drupal.org/node/1524718

A proper fix would involve digging deep into Mail System, Mime Mail and Simplenews modules (depending on your setup) and this can take a long time to debug.

I was able to bypass this issue by using the following recipe:

* Install and enable Themekey module
* Install and enable sub-module: `themekey_compat`
* Configure Themekey Compatibility module, add System and Views modules to Theme Switching Chain (setting found at admin/config/user-interface/themekey/settings/compat)
* Create a new Themekey rule which switches to the right theme (for example when viewing a specific node type or accessing a custom URL).

---
Tags: 7, theming, emails
---


# Question
Title: Only Publish a node in certain languages
In D8 I have a node with several translations - not all translations will be ready to publish at the same time. If I unpublish one translation it unpublishes all transaltions and default translation. Is this a bug or do I have an incorrect setting somewhere?

# Answer
> 3 votes
First of all lets make sure you have set up Drupal correctly:

* Do you have activated the core Content translation module
* Do you have activated the core Language module
* Do you have set up at least 2 or more languages (of course you have)
* Do you have set up detection and selection correctly (I think you have)
* Do you have set up content types correctly to allow multiple languages (sure otherwise it won't work)
* Now when you start to list your nodes in `content/admin` overview you should be able to select translate each node
* If you choose this and you **translate** it you should see the button below saying `translate and publish` which can be switched to `translate and unpublish` this selection
* if you choose the second your translation will not be published automatically. Violá

Hope it helps ...

---
Tags: 8, i18n-l10n
---


# Question
Title: How to use the Rules module to award userpoints to referring users?
I am creating a referral program on Drupal. I have almost everything working right except awarding userpoints to users. I want to award userpoints to users after the person they refer to the site becomes a paid member. I have tried severally with Rules but no success.

I am using these modules:

What I want is to create a rule using Rules that automatically awards userpoints to a user once the person that a user refers to the site becomes a paid member of the site.

Anyone with better knowledge able to help me out here?

# Answer
> 3 votes
Add a field to user registration form that collects the uid of the referring user. Then ask current users to invite other people to the site using a custom URL to user registration form and this URL should include as query parameter the uid of the referring user. Hook the user registration form and fill in the uid of the referrer based on the query parameter. You should hide the referrer field completely. Then you do counts in the database for how many paid users a given uid had invited. The referrer uid in regard to each user is kept in the custom user profile field and becomes meaningful in your situation if the user becomes a paid member.

# Answer
> 2 votes
# Part 1 - Clarification

Here is part of what you wrote in your own comment (below the question now):

> **Event**: after user becomes a member
>
> **Condition**: user was referred by another user
>
> **Action**: award points to user ( this is where I have issue....I can't find the 'referring-user' from data selector)

Refer to the feature request (not bug ...) "Rules Action: Fetch Referring User", which states the following:

> Referral's Rules integration doesn't have a way to do that natively - the 'referring\_user' variable only exists when the new account is being created. It would be very nice to have a Rules action that could fetch the referring user.

This issue, in status "needs review", does have a patch via which you may get it to work.

# Part 2 - As-good-as-it-gets alternative

Here is the rule (in Rules export format) that you can use as a prototype, to partially answer your question:

```
{ "rules_award_userpoints_to_referring_users" : {
    "LABEL" : "Award userpoints to referring users",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules", "referral" ],
    "ON" : { "referral_recorded" : [] },
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "referring-user" ],
          "points" : "50",
          "tid" : "0",
          "entity" : [ "new-user" ],
          "description" : "You earned some points because user [referring-user:name] just registered using referral link [referring-user:referral-link].",
          "operation" : "New referral occured",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

I've selected an (arbitrary) amount of 50 points. If you tune that to fit your own requirement, then these points will be rewarded (already) when that new account is created (with no relationship/dependency about becoming a member).

Be aware that the Rules / User Points integration has way more facilities you can take advantage of (that's why I consider this sample rule as a prototype only).

You should be able to use the Rules UI to perform an import of the above (exported) rule, provided you first enabled these modules (as indicated also within the **REQUIRES** section of the exported rule above):

* Rules, and the Rules UI sub-module, to further tune this rule if needed.
* User Points, and its sub-module "**Userpoints rules integration**".
* User Referral ... of course ...

# Part 3 - Heading for the golden cradle

If you'd add an entity reference field to your user accounts (for entity type = user), you could replace the Rules Action from Part 2 by adding a reference to the "Referring user" (and not yet grant those user points).

Next you could create an additional rule based on an event like "After saving a new membership" (which you get from the Membership Entity module). And possibly you may want to add a Rules Condition to that rule to perform a Data Comparison about the `membership-entity:type`, to check if it matches the membership type for which you want to grant the user points.

Finally you could use a Rules Action to grant the user points, similar to the Rules action as in part 2. But with the `referring-user` (within the Rules Action from Part 2) replaced by the user indicated via the user reference indicated in the user profile.

If you're not familiar (enough/yet) with Rules, then checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

# Answer
> 0 votes
As per your question you have managed everything except assigning points to user. Then I suggest you to have a rule with execute custom php code. The code for assigning points to user is as follow. (Do your necessary changes accordingly.)

```
$params = array(
    'uid' => $user->uid,
    'moderate' => 0,
    'points' => 15,
    'tid' => 0,
    'entity_id' => $user->uid,
    'entity_type' => 'user',
    'operation' => 'Vote Added',
);

userpoints_userpointsapi($params);

```

---
Tags: 7, users, rules, userpoints
---


# Question
Title: How to update Twig - does it need to be updated?
Does Twig will be updated automatically? Or does an updated version comes with a new Drupal 8.x release? Or does Drupal just stuck on the current version? I'm just wondering because Twig will be further developed. Thanks.

# Answer
Drupal core may update that dependency if it complies with the Allowed changes during Drupal 8 release cycle documentation page. A library may be updated to a more recent version in a minor release of Drupal (such as 8.1.0 or 8.2.0). Any feature requests or bug reports should be discussed in the issue queue for Drupal core.

Composer dependencies do not update automatically, but are based on running the composer command on the composer.json (or lock file).

However a contrib module may add its own Composer dependencies, which *could* alter dependencies added by Drupal core outside of a release. Composer looks through the entire dependency graph to choose a version to install, and this might update Symfony or Twig or Behat for instance. You can learn more about how Composer deals with semantic versions, which is similar to npm (node.js).

It is probably not safe to update to an *arbitrary* version of Twig because that may break core or contrib, but it is possible to update to a compatible version without waiting for an update in Drupal core.
> 3 votes

---
Tags: 8, theming, composer
---


# Question
Title: With out www in url redirecting to home page
I know this can be done using .htaccess file, but not sure what I have to write.

when I am entering `example.com/abc` it is redirecting to `example.com`, but when I am entering `www.example.com/abc` it is working properly.

Can I get some help?

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock))$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Add headers to all responses.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
</IfModule>

```

# Answer
> 2 votes
The .htaccess file you show above is not doing that redirect. You must have some code in PHP that is causing example.com/abc to redirect to example.com. I would look through your code for 'www' to see if you can find the place where this logic exists.

However, you could write an .htaccess rewrite that would send the browser from example.com/abc to www.example.com/abc so that the PHP code (which suspect is at the root of your problem) never triggers.

That .htaccess code would go below the commenteded out #RewriteBase line:

```
RewriteCond %{HTTP_HOST} ^example.com$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

This takes any requests on the bare domain, specifically not with a www, and redirects them to www.example.com/$path.

---
Tags: .htaccess
---


# Question
Title: Use different indexes for Solr searches on local dev environment
I'm using the Search API Solr module for search on my Pantheon site. Pantheon's Solr module automatically sets the search index for the dev, staging, and live environments.

But now I want to install Solr locally and I want to use that index instead on my local dev environment. I know I can change the environment settings in `settings.php`-- I have already done this for some things on my local environment.

I defined the **Server** for my local copy of Solr at `admin/config/search/search_api`. I have two different **Indexes** on this page, and these default to the Pantheon **Server**. I can easily switch them to the local solr **Server**, but I don't want to do this every time I reset my dev environment.

What variable can I set to force the **Indexes** to use my local Solr **Server**?

# Answer
> 2 votes
Sadly, Solr servers and their settings are not variables. They're not entities, nor anything else Drupal would know about, and subsequently be able to effect.

The settings for the server host/path are stored in a serialised PHP string in the search\_api\_server table. (the `options` column).

The best I think you'll be able to do is to add a step to your pull-from-pantheon process to run a script after the database has been updated. The script would perhaps delete all existing servers and add a new record with only the known good configuration for your local host.

Or you could have a module enabled locally only that checks for the host on each request, something like that. I don't think there's a way to do it without altering the database manually, or at least by using one of the API functions provided by search\_api\_solr.

---
Tags: search, configuration
---


title: Import/Export of Panelized Nodes

text:
# Question
Title: Import/Export of Panelized Nodes
I'm using Panelizer to *panelize* nodes of a specific content. This content type is used so that content editors on the website can easily edit (with the help of Panels IPE) the content of pages which all have unique custom layouts (ie. different sets of panels panes at different positions).

To ease deployments, I"m looking for a way export *panelized* nodes from the development (local) site to the validation and production sites in a non-interactive fashion. Import/Export of nodes themselves is not the issue here, there is several solutions. But, AFAIK, none of them handle the panelizer part. The solutions to use will likely depend on the exact how to export/import the panelizer part of the *panelized* nodes and how it can be integrated in an automated workflow.

So far, for a *panelized* `$node`, I've found the following

```
// Export the panelized entity information
ctools_export_crud_export('panelizer_entity', $node->panelizer['page_manager']);
// Export the panel display of the entity
ctools_export_crud_export('panels_diplay', $node->panelizer['page_manager']->display);

```

# Answer
> 1 votes
You can do that by using uuid\_features the dev version (dev+36) and you may need Panelizer (dev) there are some patches there that will solve problems for you.

Also you can try deploy module, though I didn't use it, but it looks like it will become a more promising solution.

# Answer
> 0 votes
Depending on your Panel contents, you may be able to use Node Export and Features modules. With this, I'm able to export the fully configured and populated Panelizer node.

However, I'm running into a problem where, if I've added an existing node, the NID isn't being translated to the new NID.

If you are just exporting a Panelizer node with panes to fields, or views, etc., i.e. something where the machine ID is the same on all servers, this should work very well.

Make sure to configure your Node Export Features settings the same way on all servers.

Additionally, you should use the XML export option or PHP serialize (if that works for you). See this thread for issues with Panelizer exports: https://www.drupal.org/node/1304942 and https://www.drupal.org/node/1916524

---
Tags: 7, nodes, importing-exporting, panels
---


# Question
Title: Using variable_get() still returning a form with the default value?
So, I have a form with a default value 'You have not enabled TFA' that is editable for the user. This works, and user input is recorded in the database, but when the form is returned it shows the default value again, and I think it would be better to return the form with the inputted values.

Here is my admin.inc file:

```
function my_module_admin_settings_form($form, $form_state, $nid = 0){
  $form = array();
  $form['subject'] = array(
    '#title' => t('Subject Line'),
    '#descirption' => t('Default email subject line.'),
    '#type' => 'textfield',
    '#size' => '50',
    '#required' => TRUE,
    '#default_value' => variable_get('subject', 'You have not enabled TFA'),
  );

...

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

```

Here is the code for variable\_get function (for reference):

```
function variable_get($name, $default = NULL) {
  global $conf;

  return isset($conf[$name]) ? $conf[$name] : $default;
}

```

Can anybody see what is going on?

# Answer
If I understand your question correctly, your values are not saved.

This is because you either need to handle storing variables (using `variable_set()`) in your submit callback, or use `system_settings_form()` to do this for you.

The latter approach is generally used for administrative settings, unless you need some additional processing or storing part of the settings somewhere else.

Do note that with `system_settings_form()` you don't need to add the form actions - they will be added for you.

Here's an example:

```
function my_module_admin_settings_form($form, $form_state, $nid = 0){
  $form = array();
  $form['subject'] = array(
    '#title' => t('Subject Line'),
    '#descirption' => t('Default email subject line.'),
    '#type' => 'textfield',
    '#size' => '50',
    '#required' => TRUE,
    '#default_value' => variable_get('subject', 'You have not enabled TFA'),
  );

  // Add more fields.

  return system_settings_form($form);
}

```
> 2 votes

# Answer
Do check that `$form['subject']` not repeated in any where of the form because `$form['subject']` should always be unique .

And yes you need to use `return system_settings_form($form);` to store in `variable` table
> 0 votes

# Answer
You need to return form wrapped to system\_settings\_form, and also its recommended to add prefix with your module name to your variable. This an example with menu hook.

```
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['admin/config/system/my-settings'] = array(
    'title' => 'My settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_settings'),
    'access arguments' => array('administer site configuration'),
    'weight' => 20,
  );

  return $items;
}

/**
 * Form builder; Settings form.
 */
function my_module_settings() {
  $form['my_module_subject'] = array(
    '#title' => t('Subject Line'),
    '#descirption' => t('Default email subject line.'),
    '#type' => 'textfield',
    '#size' => '50',
    '#required' => TRUE,
    '#default_value' => variable_get('my_module_subject', 'You have not enabled TFA'),
  );

  return system_settings_form($form);
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How to force Views (or whole Drupal) to lowercase page paths?
Is it possible to force Views to always lowercase URL paths? Here is a detailed example. I'm using contextual filters to filter by node field (field's name is country). Here are the node examples:

```
Node title: Madrid | country: spain
Node title: Rome | country: italy

```

Country name values are intentionally lowercased. Now I create a `country` contextual filter with this path: `results/%`. These are the results:

```
Path: results/spain
Result: Madrid

Path: results/Spain
Result: Madrid

Path: Results/Spain
Result: Madrid

```

I want the results to be available only on these paths:

```
results/spain

results/italy

```

Is there a way to force Views to convert all of the paths to lowercase letters? If it's not possible in Views, is there a way to make Drupal convert all of the URL requests to lowercase paths?

# Answer
This is untested, but I believe you can use a `hook_url_outbound_alter()` for this, since I think Views URLs still get run through `url()` when they get generated:

```
function MYMODULE_url_outbound_alter(&$path, &$options, $original_path) {
  $path = drupal_strtolower($path);
}

```

*(Updates to address some comments post acceptance.)*

This should update URLs that get generated by Views, and will prevent the uppercased ones from getting out into the wild.

Drupal 7 is case-insensitive with regards to inbound URL routing. However, I am not 100% sure this is always the case with Views arguments being pulled from the URL. I suspect that the base part of the path w/o the argument is being matched by Drupal as case-insensitive, and the argument is matching case-insensitive because of database collation being case-insensive.
> 3 votes

---
Tags: 7, views, uri
---


# Question
Title: Working with a checkbox and EntityFieldQuery
So I have a custom field which is a checkbox and is called 'field\_hide\_panel'.

The on value is '1' and the off value is '0'. But bare in mind, this field was added later so there are a lot of rows in my database which will not have any field\_hide\_panel value.

When this checkbox is selected it should be omitted from the results of my query.

I have this line to try to achieve this:

```
$query->fieldCondition('field_hide_panel','value', '1', '!=');

```

The problem is, I'm not getting anything returned. I think this is because most of my nodes don't have a 'field\_hide\_panel' value at all but I still want these returned as my logic says these should still show because field\_hide\_panel does not equal 1.

Is there any way around this without me having to go through hundreds of nodes and re-save them so they get '0' as the field\_hide\_panel?

# Answer
> 0 votes
You can add tag to your query and use hook\_query\_TAG\_alter() to add additional conditions. Here's an example:

```
function mymodule_get_nodes() {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->addTag('node_is_not_tagged');
  return $query->execute();
}

/**
 * Implements hook_query_TAG_alter().
 */
function mymodule_query_node_is_not_tagged_alter(QueryAlterableInterface $query) {
  $query->leftJoin('field_data_field_hide_panel', 'hp', 'node.nid = hp.entity_id AND hp.entity_type = :entity_type');
  $or = db_or()
    ->condition('hp.field_hide_panel', 0)
    ->isNull('hp.field_hide_panel');
  $query->condition($or);
}

```

Link to relative issue: https://www.drupal.org/node/1157006

---
Tags: entities
---


# Question
Title: How can i give link in block for only listed paths based on user id?
I have created block and i want to give the only listed paths

i.e user/user\_id ex: user/123

i have given **user/\*** but it displays all pages where users pages are there.

i tried below ways

and enabled PHPFILTER and tried this

# Answer
> 1 votes
Try "extended\_block\_visibility" module, install it and then on block setting page select last option "pages on which this php code will return true" and then you can write php code inside php tag like :

```
<?php
if(arg(0) == 'user' && is_numeric(arg(1))){
return TRUE;
}
return FALSE;
?>

```

But remember this code will save inside the DB and will break site if write wrong code. Alternatively you can define theme specific visibility using this module.

# Answer
> 0 votes
As an option you can use path alias, for example If my user's page alias is `/users/myusername` then you can set `users/*` in *Visibility settings*. So it will be available on `user/*` page, but not on `user/*/*` pages.

---
Tags: blocks
---


# Question
Title: How to set permission to ALWAYS be full on for administrator?
I'm looking for a module that will give the administrator permission on ABSOLUTELY everything.

Not only to retroactively give all permissions after having installed modules in the past. But also for every new module installed.

By default giving the Administrator permission to do EVERYTHING.

I have tried:

https://www.drupal.org/project/fpa

But still a lot of configuration and clicking..

Isn't there a way to click on a sigle box and set everything to ON in one shot for administrator?

I'm the only one touching the website, no collaborators, EVER ;)

# Answer
> 1 votes
Did you try to set Administrator role `/admin/config/people/accounts`?

---
Tags: users
---


# Question
Title: How to set field permission with time limit
I want to set up a customer´s private recording system, where the customer can record his private issues. This record cannot be changed after one hour. The record includes time,episode and my comments. I used "field collection" module to set up the record first, then use "edit limit" module to limit the edit time-everything works fine but I found after one hour, though the customer cannot use the "edit" tab for the whole node, he can still click a "edit" link below each field (time, episode, etc.). Is there anyway to disable the "edit" link for each field after one hour as well?

# Answer
You can hide at all links to separately edit/delete field collections values, go to `Structure » Content types » YOUR_CONTENT_TYPE » Manage display`, click to field collection settings cogwheel and clear fields.

Also you have to forbid an access to edit/delete by direct link, place in your custom module:

```
/**
 * Implements hook_menu_alter().
 */
function yourmodule_menu_alter(&$items) {
  $path = 'field-collection/' . strtr('your_field_name', array('_' => '-'));
  $items[$path . '/%/edit']['access callback'] = FALSE;
  $items[$path . '/%/delete']['access callback'] = FALSE;
  $items[$path . '/add/*/*']['access callback'] = FALSE;
}

```

Don't forget to clear cache.
> 0 votes

---
Tags: entities
---


# Question
Title: How to use conditional not to print a field if empty in user profile?
As in node.tpl.php, I would like in user-profile.tpl.php to test if a field is empty or not to show my html.

I tried it :

```
<?php if (!empty($user_profile['field_myfield'])): ?>
<?php print render($user_profile['field_myfield']); ?>
<?php endif; ?>

```

But it does not work.

Have you the solution?

# Answer
Have you thought of using Entity Metadata Wrappers?

You can wrap the user profile using `$user_profile_wrapper = entity_metadata_wrapper('user', $user_profile);`, and then you can find out if the field has a value with:

```
if (isset($user_profile_wrapper->field_myfield)) {}

```

This should tell you if the user profile HAS the field, and then you might use:

```
$value = $user_profile_wrapper->field_myfleid->value();

```

to actually get the value and test if it's empty or not.

Sources:
> 1 votes

---
Tags: 7, theming, entities
---


# Question
Title: Numerous dependencies don't get installed with "drush en -y" command for rooms module
I tried to install the rooms module, obviously a very complex module with lots of dependencies, I tried with drush:

```
drush en rooms -y

```

This is the module:

https://www.drupal.org/project/rooms

But even after doing that, from the back end, tons of dependencies are missing.

Additionally, the Rooms page has absolutely no information on required dependencies...

Am I missing something here?

# Answer
> 0 votes
Drush will only check the .info file for dependencies, in the case of the Rooms module those are:

```
dependencies[] = date
dependencies[] = date_api
dependencies[] = date_popup
dependencies[] = jquery_update
dependencies[] = libraries (>=2.x)
dependencies[] = variable

```

If Drush is missing any of those out, you have a buggy version of Drush and need to get an issue opened for it (or check for a similar existing one).

Other than that any "missing" dependencies are either down to a bug in the Rooms module, or your expectations being incorrect.

For example, maybe you're expecting Drush to auto-download all of the dependencies for the sub-modules included with Rooms as well?

It won't, those are considered separate modules. If you want those dependencies downloaded/installed automatically, you'll need to run `drush en` for each module individually.

# Answer
> 0 votes
Unfortunately, the implementation of the dependency-resolution feature is incomplete. Note that dependencies in an info file are *modules*, and Drush download requests *projects*. It is easy to get a list of modules that a given project contains; however, there is no way to tell what project a given module is contained in, because this information simply is not maintained on drupal.org. So, at the current time, `drush en` will only fetch those dependencies where the module name equals the project name.

There have been some 3rd-party efforts to build a mapping from the module name to the project name, but so far, no one has attempted to implement this feature in Drush. The best way to get the required dependencies for a complex module is to find a distribution for it, such as drupalrooms. Some distributions work better than others; I have not tried this one myself.

# Answer
> 0 votes
Rooms' dependencies are documented here: http://docs.roomify.us/rooms/requirements.html#rooms-requirements (You can find this by following the standard Documentation link on https://www.drupal.org/project/rooms)

Additionally there are detailed installation instructions here: http://docs.roomify.us/rooms/installation.html

hope this helps.

---
Tags: drush
---


# Question
Title: Error after installing and enabling "Rooms-Drupal Booking for Hotels, B&B and Vacations" and dependent modules
After installing and enabling "Rooms-Drupal Booking for Hotels, B&B and Vacations" and dependent modules, I get this error when I try to go to the content menu. Does anybody have anything to fix this issue? I had to download multiple modules since they were dependent.

If you don't, can you recommend me a better solution for Room Reservations?

# Answer
The `dr8` part of your table name seems suspicious ... since you're using Drupal 7, while that `dr8` might refer to something related to Drupal 8.

If that's not what is causing your problem, and as per the last phrase in your question ("*... a better solution for Room Reservations ...*"), then have a look at these alternative modules (with a stable release) for managing reservations in D7 (quotes are from their project pages):

* Availability Calendars.

> ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
>
> An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.
* Simple Reservation.

> ... 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.
>
> The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
>
> There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.
* MERCI.

> ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.
* Resource Conflict.

> ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.
> 1 votes

# Answer
try seeing if the Commerce Product module is enabled - if it is, try running database updates. If that doesn't work, try disabling commerce product, uninstalling it, and re-enabling it.
> 0 votes

---
Tags: 7, commerce, debugging
---


title: Views two content type relations

text:
# Question
Title: Views two content type relations
I have two content types.
1. Referrals: Name, other info type fields
2. Referral semesters: start date, end date

I want to list all referral semesters out while counting the number of referrals there were in between the referral semesters start and end time. Looking at the referral creation date.

I've started a view of semesters but see no where I can relate it to referrals in the relationship area.

example:
Spring 2016: 17
Summer 2016 : 22

# Answer
> 1 votes
I think the entity reference view may help you in this case.

Ref: http://codekarate.com/daily-dose-of-drupal/entity-reference-view-widget

---
Tags: views
---


# Question
Title: How to filter content in Views based on multiple term custom fields?
I'm trying to find a way to filter Views through contextual filters based on custom taxonomy term fields. Here is an example:

```
Content type: Article
Taxonomy vocabulary: Tags
Tags custom field: UniqueString

```

When I create an article, I assign tags to it. To every tag (taxonomy term) I assign an unique string. Example:

```
Article title: John Smith's best songs
Tags: John | Guitar
UniqueString for tag John: uid1
UniqueString for tag Guitar: uid2

```

Now I want to display articles that are tagged with both `John` and `Guitar`. This works:

```
Contextual filters:

Content: Has taxonomy term ID
Content: Has taxonomy term ID

View page path: views/taggedby/%/%

```

Path `views/taggedby/john/guitar` will display:

```
John Smith's best songs

```

However, I want to filter based on UniqueString value and not on tag names:

```
Relationships:

Content: Taxonomy terms on node

Contextual filters:

(term) Taxonomy term: UniqueString
(term) Taxonomy term: UniqueString

View page path: views/taggedby2/%/%

```

Path `views/taggedby2/john/guitar` will display an empty view. What's confusing is that everything works when there is only one filter and the path is `views/taggedby2/%`, so there has to be a way to make it work with multiple filters as well. E. g. if I change View page path to `views/taggedby2/%` and use `guitar` as an argument, it will display:

```
John Smith's best songs

```

How to make it work with two (or more) arguments?

# Answer
> 2 votes
I have finally found a solution - it's necessary to add another relationship for the same field :

```
Content: Taxonomy terms on node, Identifier: term
Content: Taxonomy terms on node, Identifier: term2

```

The second contextual filter should use the second relationship (term2) and then everything works as expected.

---
Tags: 7, views
---


# Question
Title: How to show tooltips on form labels based on view filter descriptions in a Bootstrap sub-theme?
I am trying to find a way to display tooltips when a user hovers the mouse over a filter label of a views search page. Preferably, to reduce hard-coding, I would like to take into advantage the filter description and get the tooltip text from there (and subsequently hide descriptions through css).

Also the best way I found to actually activate the tooltips in Bootstrap is to add the attribute `data-toggle="tooltip"` to the element that we need to show a tooltip for.

So far I am using the recipe from here adding the `data-toggle` element

```
 function mytheme_form_element($variables){
     dpm($variables);
  $original = theme_form_element($variables);
  $return = '<div data-toggle="tooltip">' . $original . '</div>';
  return $return;
 }

```

but I don't see the filter description anywhere in the `$variables` array plus this snippet themes the filter field and not the label but would probably do the trick.

# Answer
You can do it in form alter, here's an example (add additional conditions yourself):

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function yourmodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $field_name = 'filter-title';
  $form['title']['#attributes'] = array(
    'data-toggle' => 'tooltip',
    'data-original-title' => $form['#info'][$field_name]['description']
  );
  $form['#info'][$field_name]['description'] = '';
}

```
> 2 votes

# Answer
As per this post

> For performance reasons, the Tooltip and Popover data-apis are opt-in, meaning you must initialize them yourself.

So you have to initialize and use like

```
<script>
(function($) {
$(document).ready(function() {
$('[data-toggle=tooltip]').tooltip();
});
})(jQuery);
</script>

```

Please visit on this post.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Autofilling fields based on another field
I have a very complex situation where I need some advice. I have a content type `my_content`, which has a field collection field attached to it `field_mycollection`, which has an entity reference field referencing to user `field_my_userreference`, a phone field `field_my_phone`, a text field `field_my_text`, and another text field `field_my_anothertext`.

```
My Content
|_ field_mycollection
   |_ field_my_userreference
   |_ field_my_phone
   |_ field_my_text
   |_ field_my_anothertext

```

The user entity has also have fields `field_my_phone`, `field_my_text` and `field_my_yetanothertext` which the latter has a different machine name.

What I want to do, if in `my_content` edit/add form, in `field_my_userreference` a user is selected, the other fields should be auto-populated from the selected user's data. The auto-populated fields should still be editable.

How could I achieve this goal? I'd like to do it, if possible, with some coding, using `hook_form_FORM_ID_alter()`.

# Answer
> 11 votes
If you want it to happen live, and all fields are on the form already, safest way would be to use `hook_form_FORM_ID_alter()` to add following to a form:

```
$form['#attached']['js'] = array(
  drupal_get_path('module', 'module_name') . '/js/copy_field_value.js',
);

```

Then in `copy_field_value.js` create behavior:

```
(function($) {
  Drupal.behaviors.moduleNameCopyFieldValue = {
    attach: function (context, settings) {

      // Repeat this for all fields as needed
      $('#source', context).on('blur', function () {
        // above you can use change instead of blur if element is not changed by another js
        if (!$('#destination').val() || 0 === $('#destination').val().length) {
          $('#destination').val($(this).val());
          // wrap line above in "if no value" like I did, or other condition you like
        }
      });
      // end of "repeat this"
    }
  };
})(jQuery);

```

You can also use `hook_form_FORM_ID_alter()` to add `#ajax` parameter to source field, but it would make your form to call a server on each field copy. If you need to actually query database, it is the way to go. It would be pretty broad to describe it anew here. You need to alter `$form_state["input"]` array to update real values seen by user. Do it in form creation function, wrapping it with `isset` to avoid notices.

If your form element is `$form["something"]["something"]["element"]`, its value will be in `$form_state["input"]["something"]["something"]["element"]` \- and you can set it in `hook_form_alter` all right, just remember to take both `$form` and `$form_state` by reference.

**Note**: `.on()` method was added in jQuery 1.7, so you will need jQuery Update to use this answer directly, or translate my code to use `.change()` or `.blur()` method.

# Answer
> 4 votes
You can do it using the computed field module

> Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!

# Answer
> 2 votes
I want to post how I achieved it thanks to great helps of @Mołot.

1. Implemented the hook\_form\_FORM\_ID\_alter().
2. Added a wrapping div around the field collection.
3. Since the my field collection is a multi-value field, iterated over it and set the `#ajax` property for the field `field_my_userreference`.
4. Created a callback function which simply returns the field collection item back.
5. Checked in the hook\_form\_FORM\_ID\_alter() implementation, if $form\_state for the field collection is set. If yes, get the values from the user entity and populate the form input fields with those values.

My code looks like:

```
function MYMODULE_form_my_content_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_mycollection']['#prefix'] = '<div id="mycollection-wrapper">';
  $form['field_mycollection']['#suffix'] = '</div>';
  foreach ($form['field_mycollection']['und'] as $key => $fc_mycollection) {
    if (is_numeric($key)) {
      $form['field_mycollection']['und'][$key]['field_my_userreference']['und']['#ajax'] = array(
        'callback' => 'MYMODULE_mycollection_callback',
        'wrapper' => 'mycollection-wrapper',
      );
      if (isset($form_state['values']['field_mycollection']['und'][$key]['field_my_userreference']['und'][0]['target_id'])) {
        $user_wrapper = entity_metadata_wrapper('user', $form_state['values']['field_mycollection']['und'][$key]['field_my_userreference']['und'][0]['target_id']);
        $form_state['input']['field_mycollection']['und'][$key]['field_my_text']['und'][0]['value'] = $user_wrapper->field_my_text->value() ? $user_wrapper->field_my_text->value() : '';
        $form_state['input']['field_mycollection']['und'][$key]['field_my_anothertext']['und'][0]['value'] = $user_wrapper->field_my_text->value() ? $user_wrapper->field_my_yetanothertext->value() : '';
      }
    }
  }
}

function MYMODULE_mycollection_callback($form, &$form_state) {
  return $form['field_mycollection'];
}

```

# Answer
> 0 votes
This might be a little late but this module https://www.drupal.org/project/entityreference\_autofill, seems to do what you are describing. I have used it and it can help you as well.

---
Tags: 7, entities
---


title: Custom comment access

text:
# Question
Title: Custom comment access
I need to prevent users from posting comments based on some conditions but I can't find any hooks I can implement.

For nodes we have `hook_node_access()` but apparently there is no `hook_comment_access()`

Any ideas on how I can implement this?

I have tried something like this but apparently it doesn't work:

```
function my_module_entity_info(&$entity_info) {
  $entity_info["comment"]["access callback"] = "my_module_comment_access_callback";
}

function my_module_comment_access_callback($op, $comment){
  // some custom logic and return false...
  //...
  return comment_access($op, $comment);
}

```

My form is a custom form, displayed on multiple pages. I would like to prevent access to the comment entity and not to the form or page.

# Answer
You can get code from Comment Permissions and Comment Access modules.

something like

```
function comment_perm_form_alter(&$form, $form_state, $form_id) {
  #comment_node_merci_reservation_form
  if ($form['#id'] == 'comment-form' and arg(0) == 'comment') {
    $types = variable_get('comment_perm_node_types', array());
    $form_id_types = array();
    if (is_array($types)) {
      foreach ($types as $type) {
        if ($form_id == 'comment_node_' . $type . '_form') {

          $nid = $form['nid']['#value'];
          if (! comment_perm_access($nid)) {
            // for comment reply pages, redirect back to the node
            if (arg(0) == 'comment' && arg(1) == 'reply' && is_numeric(arg(2))) {
              drupal_set_message(_comment_perm_access_denied_message($nid), 'error');
              drupal_goto('node/' . arg(2));
    }
  }

          if (arg(0) == 'comment' && arg(2) == 'edit' && is_numeric(arg(1))) {
            if (! comment_perm_edit_access($nid)) {
              drupal_set_message(_comment_perm_access_denied_message($nid), 'error');
              drupal_goto('node/' . $nid);
            }
          }
      }
  }
    }
  }

}

```

then you can add you own condition.

You can also use above module ,if it is fulfilling your requirement.
> 2 votes

# Answer
Good answer from @visabhishek, will try something similar, but more minimal:

```
function youmodule_form_alter(&$form, $form_state, $form_id) {
  // You can add more specific conditions here based on your reqs
  if ($form['#id'] == 'comment-form' && _your_conditions_callback() ) {
      $form['#disabled'] = true;
      $form['#prefix'] = '<div class="messages warning"><h2>Not allowed</h2></div>';
  }
}

function _your_conditions_callback() {
  // Conditions block
  // return true;

  return false;
}

```

Maybe this helps as well, with lot less overhead.
> 1 votes

---
Tags: 7, users, comments
---


# Question
Title: Advance Poll block keeps caching results
We have begun testing the Advanced Poll module. We are having an issue where the results from the very first vote are cached, and then all page views from that point are only the results of that single vote.

I need a way to make sure the blocks for the Advanced Poll are not cached.

We use Memcached, and everything I read on it is vague.

# Answer
> 0 votes
You can try to use Lazy Pane or Block Lazyloader modules to output your poll block. Your block will be loaded from the client side, on demand, via AJAX.

---
Tags: 7, polls
---


# Question
Title: Import REST API web Application to Drupal 7
I have a REST API web Application which is in core PHP. Now I want to change that application to Drupal 7. How to use those application in Drupal 7. I am new to REST API services..

# Answer
You should use services module to create rest services in drupal 7. Simply install it and create end point by admin setting form. When will you create this then you can check your end point like this :

http://www.yoursite.com/{end-point}

If this will give success message then you successfully created end point and now you can move forward.

Services module will give some predefined service resource for user, node and comment etc. simply enable those and use them and if you want to create your own services then you should implement hook\_services\_resources hook, it will create a service resource. It will return an associative array which include api version, operations (create, delete, retrieve), actions etc. You can simply convert your services to drupal just follow some standard that is defined by services module and my recommendation is just look at any resource of this contrib module, for example look at user resource inside services module you will understand it.
> 0 votes

# Answer
Another good option (I think) is the RESTful module in D7. It gives you very fine grained control over what is exposed from your API, as compared to Services, which sort of opens the floodgates when it is enabled.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How is the class loader set to load the files containing classes?
I was trying to understand how Drupal 8 initializes the class loader to look for files containing classes in core/lib and modules/\*/src.

I found out that the class loader is set to an instance of `ApcClassLoader` in `DrupalKernel::initializeSettings()`.

```
  // If the class loader is still the same, possibly upgrade to the APC class
  // loader.
  // ApcClassLoader does not support APCu without backwards compatibility
  // enabled.
  if ($class_loader_class == get_class($this->classLoader)
   && Settings::get('class_loader_auto_detect', TRUE)
     && extension_loaded('apc')) {
    $prefix = Settings::getApcuPrefix('class_loader', $this->root);
    $apc_loader = new \Symfony\Component\ClassLoader\ApcClassLoader($prefix, $this->classLoader);
    $this->classLoader->unregister();
    $apc_loader->register();
    $this->classLoader = $apc_loader;
  }

```

Following the methods that are called after that, I cannot find the exact method setting the class loader to correctly find the files containing Drupal classes. I expect it to be done from Drupal code, since the directory layout is very specific for Drupal.

Which method set the class loader to look in the right directories Drupal uses?

# Answer
For modules with composer dependencies in 7.x, try https://www.drupal.org/project/composer\_manager. If you want to support modules with PSR-4 autoloading, see https://www.drupal.org/project/registry\_autoload (integrates with the standard 7.x class loading registry) or https://www.drupal.org/project/xautoload.

That said, the code you pasted is just the APCu wrapper for the class loader. The actually relevant line is this, in `\Drupal\Core\DrupalKernel::discoverServiceProviders()`:

```
$this->classLoaderAddMultiplePsr4($this->getModuleNamespacesPsr4($module_filenames));

```

What it does is register a PSR-4 namespace for each module with composer. Below that, everything follows the standard rules.

But composer dependencies is something else, that's handled automatically by composer's autoload.php and all the files that that then loads. Which is basically what composer\_manager does, load the generated autoload.php file.
> 1 votes

---
Tags: 8
---


# Question
Title: Why some features are overriden after installation
This is my hook\_install:

```
function moocollar_web_install() {

  // enable features
  $global_features = array ('display_modes_feature' , 'field_bases_feature' , 'image_styles_feature' , 'roles_permissions_feature' , 'sitewide_feature'  , 'wysiwyg_feature' , 'menus_feature');
  $functionality_features = array ('blog_feature');

  $enable_dependencies = TRUE;
  module_enable($global_features, $enable_dependencies);
  module_enable($functionality_features, $enable_dependencies);

  // create editor user
  $role = user_role_load_by_name ('editor');
  $new_user = new stdClass();
  $new_user->name = 'editor';
  $new_user->pass = user_password(8); // random password.
  $new_user->mail = 'editor@example.com';
  if ($role) {
    $new_user->roles = array ($role->rid => $role->name);
  }
  $new_user->status = 1;
  $new_user->is_new = TRUE;
  user_save($new_user);

  variable_set('features_default_export_path', 'profiles/moocollar_web/modules/features');
}

```

After install the blog\_feature is overriden:

```
drush features-diff blog_feature
Legend:
Code:       drush features-revert will remove the overrides.
Overrides:  drush features-update will update the exported feature with the displayed overrides

Component type: info
  features[field_instance][] = node-blog_post-body
  features[field_instance][] = node-blog_post-field_image
< features[menu_links][] = menu-editor-menu_aadir-post:node/add/blog-post
  features[node][] = blog_post
  features[user_permission][] = create blog_post content

Component type: menu_links
< array(
<   'menu-editor-menu_aadir-post:node/add/blog-post' => array(
<     'customized' => 1,
<     'link_path' => 'node/add/blog-post',
<     'link_title' => 'Añadir post',
<     'menu_name' => 'menu-editor-menu',
<     'module' => 'menu',
<     'options' => array(
<       'identifier' => 'menu-editor-menu_aadir-post:node/add/blog-post',
<     ),
<     'router_path' => 'node/add/blog-post',
<   ),
< )
---
> array()

```

But if I execute revert features via drush, the features is on default state:

```
drush features-revert blog_feature
Do you really want to revert blog_feature.menu_links? (y/n): y
Reverted blog_feature.menu_links.                                                                       [ok]
vagrant@precise32 (linkinicio *) httpdocs$ drush fd blog_feature
Feature is in its default state. No diff needed.

```

On the blog\_feature.info I've the dependency and the item:

```
...
dependencies[] = menu
dependencies[] = menus_feature
....
features[menu_links][] = menu-editor-menu_aadir-post:node/add/blog-post
....

```

Thanks you all for your time.

# Answer
Normally Features automatically detects ctools exportables and add the modules containing those exportables to the dependency list, unless a module requirement for an exportable was not detected, or dependent modules were installed since feature was enabled.

Based on your menu link machine name (`menu-editor-...`), it seems it relies on Menu Editor module and you've missing dependency to that module, therefore Features module didn't detect that component as a requirement, so it become overridden and unrevertable.

The solution is to add the missing module into `dependencies` list. Then either disable the feature module and reenable it, or manually enable any dependencies not enabled (see Feature Diff to expose them).

See: Troubleshooting: Reasons Features may be stuck as Overridden at Drupal.org
> 1 votes

---
Tags: 7, features, installation
---


# Question
Title: How do I fill form elements via onblur events?
I have a user form in which I have to fill all information related to a user. I have only the email address, and I'd like all other fields to be filled when I enter the email address by using the onblur event. So I have to create a module that is called after I have filled email on the form. Via the module I will fetch all other field data.

# Answer
You just need to AJAXify the form. Take a look at this article for more info on Drupal AJAX forms. To actually look up the user info you can just use the `user_load_by_mail()` function (more info).
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: Zoom and center a GMap according to its markers is not working?
Zooming and positioning the map to the center was not working in (Google map) So we come up with small change in the code by adding time delay to it, then it was started working, may be it will use for someone. (fitbounds method googlemap api v3 for drupal 7 gmap)

```
jQuery(document).ready(function() {
  // time delay for the maps to initialize.
  setTimeout(function() {

// Loop through all gmap instances.
jQuery(".gmap").each(function() {

  // Get a map reference using the element ID.
  gmapID = jQuery(this).attr("id");
  var gmap = Drupal.gmap.getMap(gmapID).map;

  // Ensure map exists.
  if (gmap) {
    alert(gmap.toSource());
    // Create a new map boundary.
    var bounds = new google.maps.LatLngBounds();
    // Iterate though the current maps marker collection.
    jQuery.each(gmap.markers, function(index) {
      // Find the current markers position (latitude, longitude).
      var data = gmap.markers[index];
      var pos = data.getPosition();

      // Extend the new boundary so the new marker/pin will be in view.
      bounds.extend(new google.maps.LatLng(pos.lat(), pos.lng()));
    });
    // Set the current maps bounding box to our new defined boundary.
    gmap.fitBounds(bounds);
  }
  else {
    // GMap was not initialised in time.
  }

});

 }, 100);
});

```

This is what the code We added time delay on top of it. https://stackoverflow.com/questions/3520810/zoom-and-center-a-google-map-according-to-its-markers-javascript-api-v3

# Answer
> 0 votes
Instead of a delay, wait for a map loaded event. I could not find a direct one so used a mutation event.

```
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
  var target_id = mutations[0].target.id;
  var map = Drupal.gmap.getMap(target_id).map;
  if (typeof map != 'undefined') {
    var initialLocation = new google.maps.LatLng(old_lat, old_lon);
    map.setCenter(initialLocation);
    // map.vars.zoom
    map.setZoom(12);
  }
});

jQuery(".gmap").each(function() {
  var gmapID = jQuery(this).attr("id");

  observer.observe($("#" + gmapID)[0], {
    subtree: false,
    attributes: true
  });
});

```

Subtree = false should mean that once the map is loaded this doesn't get triggered again. Add another test if needed.

---
Tags: google-maps
---


# Question
Title: Add attribute to all textboxes in the site
The question is simple , in my theme I want to apply an attribute to all textboxes in whole forms . I know how to add an attribute to an specific element in drupal using hook\_form\_alter , but it is too time consuming for lots of elements , so I'm eager to see if there is an easier way to do that.Any suggestion?

# Answer
If you don't want to use form\_alter type of hooks, I would do it like this:

```
<?php

function somemodule_preprocess_textfield(&$variables) {
  $variables['element']['#attributes']['custom_attr'] = 'somevalue';
}

```

You can replace \_textfield with \_textarea, I don't know what you mean by textbox :-)

Hope this helps!
> 2 votes

# Answer
You'll want to use hook\_field\_widget\_WIDGET\_TYPE\_form\_alter() for this. The following will add the "my-class" class to all textfields:

```
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function test_field_widget_text_textfield_form_alter(&$element, &$form_state, $context) {
  $element['value']['#attributes']['class'][] = 'my-class';
}

```
> 2 votes

---
Tags: 7, theming, forms
---


title: I need to format text with a token

text:
# Question
Title: I need to format text with a token
I am using tokens to display a field and want it formatted with plain text: \[node:body:format-plain\_text\]

I have a feeling my syntax is wrong, how do I make it right?

# Answer
> 0 votes
Unfortunately, the answer to your question is "You cannot make it right". This will not work like that. You are probably using entity\_token as well as token. But this syntax is not supported. You will need to find a workaround for that.

Cheers and good luck!

---
Tags: tokens
---