# Question
Title: How to programmatically assign (attach) a file to file field while creating/saving the node?
I'm trying to assign (not upload) files to nodes programmatically.

This is the scenario:

I will create 2000 nodes and there are 2000 PDF files (one PDF per node). I don't want to upload these files via Drupal interface. I will upload all these PDF files via FTP.

These PDF files are well-named, I mean all of them have a **standardized** name such as `{field_magazine_name}-{field_issue_number}.pdf` (under sites/default/files/pdf for example).

**What I want to do is to assign these PDF files to related nodes while creating/saving the nodes.**

### Possible Method 1

One method to do this would be to use the File Field Sources module.

I think **remote file transfer** can be used with some JavaScript code. The remote file transfer input can be automatically filled with the fields I want and it will work (for example `http://example.com/sites/default/files/pdf/{field_magazine_name}-{field_issue_number}.pdf`)... but I don't create nodes **manually**, I'm creating the nodes via Feeds. So, using JavaScript isn't the method I can use.

## Is there any way to programmatically assign (attach) a file to file field while creating/saving the node?

# Answer
> 4 votes
I had a similar situation. My situation is attach a file to a node in the creation of a different content type node. Done this in hook\_node\_insert

1. Initially i uploaded all files into a temp directory in /default/files/.
2. Then for each node, i created a new file object with my file attributes.
3. Then moved that particular file into the destination where i want the files to be placed. This results a clean complete file object with **fid**.
4. Then simply assign this file object attributes to file field and save the node.

The code used is follows..

```
$source_node = node_load($nid);
$filename = $bio_file_name; //your specific filename
$dir = 'public://temp-path/'.$filename; //path to specific file with name
$file_size = filesize($dir);

//New file object
$file = new stdClass;
$file->uid = $source_node->uid;
$file->filename = $filename;
$file->uri = $dir;
$file->filemime = file_get_mimetype($dir);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;
// Save file object to make it a 'managed file'.
$file_obj = file_move($file, 'public://newpath', FILE_EXISTS_REPLACE);

$source_node->your-file-field-name['und'][0] = array(
 'fid'  => $file_obj->fid,
 'uid'  => $file_obj->uid,
 'filename'  => $file_obj->filename,
 'uri'  => $file_obj->uri,
 'filemime'  => $file_obj->filemime,
 'filesize'  => $file_obj->filesize,
 'status'  => 1,
 'display'  => 1,
 'description'  => '',
 );

 node_save($source_node);

```

Hope this will help you..

# Answer
> 2 votes
**Add file / image fields**

```
// Some file on our system
$file_path = drupal_realpath('somefile.png'); // Create a File object
$file = (object) array(
  'uid' => 1,
  'uri' => $file_path,
  'filemime' => file_get_mimetype($file_path),
  'status' => 1,
);
$file = file_copy($file, 'public://'); // Save the file to the root of the files directory. You can specify a subdirectory, for example, 'public://images'
$node->field_image[LANGUAGE_NONE][0] = (array)$file; //associate the file object with the image field:

```

For more details

# Answer
> 1 votes
In addition to Abin: also set the file usage by adding this code after the node save:

```
file_usage_add($file_obj, 'file', 'node', $source_node->nid);

```

See the drupal docs.

One more thing apart from this: it is best practice to use LANGUAGE\_NONE instead of 'und'.

---
Tags: 7, files
---


# Question
Title: Update.php with errors in multisite (WAMP)
I have 4 sites using the same features / modules and have the db main (general), and a "bd for each site." Sure, but the update modules / drupal core is made only once. During the execution of update.php I get the error:

```
An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.
Please continue to the error page
An AJAX HTTP request terminated abnormally. Debugging information follows. Path: http://LINK_OF_SITE.com.br/update.php?op=selection&token=ouRkHusqVcR48Xy0n-j8hc-C2pMOEc3ABwv7oMgHbzo&id=99&op=do StatusText: ResponseText: ReadyState: 4

```

What should I do? I'm using WAMP (localhost) with Apache (2.4.9) and PHP (5.5.12) and MySQL (5.6.17)

in the log, http://teste/mea/?q=admin/reports/dblog

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'teste\_mea.backup\_migrate\_sources' doesn't exist: SELECT * FROM {backup\_migrate\_sources}; Array ( ) in backup\_migrate\_item-\>all\_items() (line 923 of C:\wamp\www\TESTE\sites\all\modules\backup\_migrate\includes\crud.inc).

# Answer
> 0 votes
probably an inconsistant module state. try to disable the migrate module in the database.

```
UPDATE system SET status='0' WHERE name='migrate';

```

for more details see here: How to manually uninstall a module?

---
Tags: multi-sites
---


title: field_view_field()

text:
# Question
Title: field_view_field()
I'm new to Drupal 8 and Twig and I can't figure out what the equivlent of field\_view\_field is? So lets say I did this in Drupal 7 within a template file:

```
print render(field_view_field('node', $node, 'body', array(
    'type' => 'text_summary_or_trimmed',
    'label' => 'hidden',
)));

```

How would I output a custom field in drupal 8 template?

# Answer
> 4 votes
The php equivalent in drupal 8 is:

```
$build = $node->body->view('view_mode');
$output = \Drupal::service('renderer')->renderRoot($build);

```

In twig you don't need to render yourself, twig does this for you. So you can simply put the first line in a preprocess function:

```
function theme_preprocess_hook(&$variables) {
   $variables['body123'] = $node->body->view('view_mode');
}

```

and output in twig:

```
{{ body123 }}

```

Edit: I see you are using a field formatter, not a view mode, and use the preloaded node, so this is the preprocess for a node template:

```
function mytheme_preprocess_node(&$variables) {
       $variables['body123'] = $variables['node']->body->view(array('type' => 'text_summary_or_trimmed'));
}

```

Put this in the `mytheme.theme` file in the theme root directory.

More information is available in the change record.

---
Tags: 8, theming
---


# Question
Title: change node types file fields widgets programatically?
I have installed multi\_upload\_filefield\_widget.

I would like to change every file widget of every file type fields of every node type programatically.

i would need to automate this change since i have multiple sites and multiple content type.

```
  //when enabling the module
  function multi_upload_filefield_widget_enable() {
        //code to loop through all node types fields for one site

       // if type is file
            // replace widget 'file' to 'multiupload
            //save content type with this new value
}

```

Here is where i am at

```
       $types = node_type_get_types();

       foreach ($types as $type){
           $fields=field_info_instances("node",$type->type);

            foreach ($fields as $field){
               if ($field['widget']['module']=='file'){
                    $field['widget']['module']='multiupload_filefield_widget';
                    $field['widget']['type']='file_mfw';
                }
                 // my fields don't get saved !?
                //field_attach_update("node", $field);
                 //field_update_field ( $field );
             }

          $fields=field_info_instances("node",$type->type);
          print_r($fields);
        }

```

How can i save these modified fields ?

any help would be appreciated

# Answer
It seems like this could do the job: Programmatically change form widget type for a field
> 1 votes

---
Tags: entities, hooks, files
---


# Question
Title: Which Rules condition can be used to email a user when an admin updates their profile?
I am trying to set up a rule (using the Rules module) that will email a user if their user record has been updated by an admin.

It is easy to generate an email when their profile is updated, but I can't see any way to make a Rules condition that the logged in user has a specific role.

# Answer
> 1 votes
Interesting Rules question! Have a look at this rule (in Rules export format, just import it in your site and check the results of it):

```
{ "rules_notify_user_about_profile_updates_by_an_admin" : {
    "LABEL" : "Notify user about profile updates by an admin",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "site:current-user" ], "type" : "user" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Bingo ... it seems to work ..." } } ]
  }
}

```

To verify if it does what you're looking for, perform these steps:

* use a userid with role "administrator" (which I assume to be role id = `3`, if not adapt that to the role id you're using for admins).
* edit any existing user profile.

If you get a drupal "message" like "**Bingo ... it seems to work ...**", then adapt the Rules "Action" with that "easy to generate eMail" you seem to already have (or know about).

Of course, if you have another userid available that has permission to edit user profiles, but without admin permission, then that should NOT result in such a "**Bingo ...**".

For anyone wondering what the actual missing piece of your puzzle was (= the "clue"): adding the condition with `entity_is_of_type` makes the `user_has_role` available. That role is related to the user performing the profile update (the "logged in user") ... which of course is different from the account being updated ...

---
Tags: rules, users, emails
---


title: user_save does not save data

text:
# Question
Title: user_save does not save data
if a user changes his email address, I want him to lose a specific role (if he had that role in the first place). To make matters more complicated, we have the "email confirm" module enabled and this bitchy little module uses user\_presave() in a way that leaves no traces of an email change when it is called during the edit of a profile. So I wrote a module and gave it weight -1 to make sure it gets a chance to compare $edit-\>mail to the users current mail before "email confirm" begins to work.

My code looks like this (version with a lot of debug statements that will be removed in the live environment):

```
function xyz_user_presave(&$edit, $account, $category) {
  if (!empty($edit['mail']) && (!empty($account->mail) && $account->mail != $edit['mail']) && !user_access('administer users') && !drupal_installation_attempted()) {
    // remove xyz role if the users changes his email address
    $user = user_load_by_mail($account->mail);
    $role = user_role_load_by_name('xyz');
    if (array_key_exists($role->rid, $user->roles)){
      drupal_set_message('In if-clause.');
      $return1 = print_r($user->roles, TRUE);
      drupal_set_message($return1);
      $user2 = user_save($user, array('roles' => array_filter($user->roles, function($item) use ($role) {return $item != $role->name;})));
      $user3 = user_load_by_mail($account->mail);
      $return2 = print_r($user3->roles, TRUE);
      drupal_set_message($return2);
      if (!$user2){
        drupal_set_message('User_save() failed.');
      }
    }
  }
}

```

If I log in with a test user that has role xyz and change his email address at the "edit profile" site, i receive these status messages:

* In if-clause.
* Array ( \[2\] =\> authenticated user \[5\] =\> abc \[8\] =\> xyz )
* Array ( \[2\] =\> authenticated user \[5\] =\> abc )

The debug messages tell me that:

1. It has been found out, that the user has the role xy and therefor the if-clause was entered.
2. Before the call to user\_save(), the user had the role xyz
3. After the call to user\_save(), the user was freshly loaded and he did not have the role xyz anymore

Yet despite all this, the user does not lose the role, no matter how often I change the email address or flush the cache.

My question now is: What the hell?

Using user\_save() in the user\_presave() function seems to be odd, but when I put the $roles array in $edit without the xyz-role, I receive pdo exception that states, that the roles are already set for this user.

# Answer
> 0 votes
This did the trick.

```
function xyz_user_presave(&$edit, $account, $category) {
  if (!empty($edit['mail']) && (!empty($account->mail) && $account->mail != $edit['mail']) && !user_access('administer users') && !drupal_installation_attempted()) {
    $role_position = array_search('xyz', $account->roles);
    // Use !== or === here since $role_position may be zero or FALSE
    if ($role_position !== FALSE) {
      unset($account->roles[$role_position]);
      $edit['roles'] = $account->roles;
    }
  }
}

```

I still do not know what's wrong with the code in the initial post, but whatever...

---
Tags: 7, users
---


# Question
Title: How to raise Notifications on new discussion posts?
How do I enable notifications for a user who subscribes to a Discussion Post section so that the user gets a notification when a new discussion topic is created by another user?

The notification should show up on his profile dashboard as well as sent by email.

Presently, the user dashboard has the block View - Open Atrium Content - Recently Updated Subscribed Content, but this block only shows updates for new comments on specifically subscribed content topics, not new discussion topics.

# Answer
> 0 votes
You can use Flag module to create "subscribe button" on any content (forum category, post or comment) and then Rules to create rule:

1. what reacts to new content
2. then load parent entity (if new post, load it's category)
3. load all flaggings on it
4. send e-mails to authors of all flaggings OR create notification (so you can show them on some dashboard)

There are also modules specialized for subscribing to content and then send notifications, but they usually are not so flexible like solution based on Rules.

# Answer
> 0 votes
Have a look at the Message Stack, these are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.

---
Tags: distributions
---


title: I can't add users

text:
# Question
Title: I can't add users
I'm having a permissions issue with organic groups. I can get to the OG Node permissions page and set general OG permissions there, and have given administrative member full permissions, but when I go to add or view the existing people, I get the "You are not authorized to access this page" message. For example, "/group/node/\[nid\]/admin/people/add-user" gives me the not-authorized message.

I've tried all combinations of the "Group roles and permissions" and content visibility settings, but no changes. It just doesn't make sense that user 1 can be blocked out like this, or any user with the Drupal administrator role. I'm also seeing this on my local system, with all content nodes having been created by user 1, which is also a member of every group.

I should point out that I can access the OG People, Add People and other pages for the top level groups, as well as for other group content that's marked as both groups and group content.

Is there an additional setting that I need to check, or is there a combination of settings I need to have to be able to edit the groups' memberships?

# Answer
The issue was that the og\_role table was missing records for the content type in question. I needed to insert a record with the gid set and the group\_bundle field set to the content type, then 3 more records for that content type with the name set to one of each of the following: non-member, member, administrator member.

Alternatively, it seems that just removing all OG fields from the OG Field settins page and then reading them also solved the issue. I'm not sure how the data became corrupted, but it sure would have been nice if OG was smart enough to detect the missing data.
> 0 votes

# Answer
I've experienced something similar after changing the machine name of the group content type - the `og_role` table column `group_bundle` is not updated. Rebuilding the table by uninstalling, reenabling and reconfiguring the Organic groups access control module was necessary
> 1 votes

---
Tags: 7, users, organic-groups
---


# Question
Title: Drupal 7.x + Ubercart 3.x + Domain Access
I have a full working Drupal 7 with Ubercart 3 running fine. It is well configured with thousands of products in it. I would like to create a sub-domain where all the contents and users are the same, but some things (theme, views, ubertcart) are configured differently. Domain Access module seemed to be the best way to acomplish my goal (it can handle differnt views, settings, themes, etc), but there is no such an option for Ubercart.

So, my problem is that I can not set different configuration on my subdomain for my Ubercart.

My questions are: \- Is there any way to force Ubercart to use maybe an other db prefix, where Im storing the different settings. \- Is there any other solution (other module) to my multisite problem?

Any help, tip or suggestion is much appreciated!

# Answer
There is no working UC\_domain module for Ubercart 3 - Drupal 7, and many issues of configuration - including payment methods per domain user are not availble
> 0 votes

---
Tags: ubercart, multi-sites, domain-access, subsites
---


title: Embedding Storify posts

text:
# Question
Title: Embedding Storify posts
I help manage a site with about 20-30 staff/trusted users and thousands more regular authenticated users. We would like to be able to allow our staff to embed Storify entries in their blog posts without exposing ourselves to undue risk.

We have Media, with add-on modules for YouTube and Vimeo embeds, but there is no Media: Storify module. We tried Media: oEmbed paired with the third-party Embedly service which can provide a Storify post in oEmbed format. However we could not get this to work. Possibly because of this bug.

We also tried the StoryPal module, but it doesn't seem well maintained and produces a WSOD. We are apparently not alone with this problem either.

Has anyone found a good solution for Storify embeds or maybe know how to get the above solutions to work? Thanks for all advice!

# Answer
> 0 votes
Perhaps the lack of activity is an indicator of the obscurity of my problem, but Storify is a very popular tool so I imagine someone else might also have this issue. Here is how I solved it, thanks to a couple of colleagues helping me think creatively about this. Unfortunately my solution only works for one tool, but it could be made to work for any service with a consistent embed code.

1. Make a new field called Storify slug that contains the URL of the storify after `storify.com/`.
2. Add the embed code to the field's template. Below is field--field-storify-slug.tpl.php

```
<?php foreach ($items as $delta => $item): ?>
  <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>

    <div id="storify-wrapper">
    <div class="storify" id="storify-story">

    <iframe allowtransparency="true" frameborder="no" height="750" src="//storify.com/<?php print render($item); ?>/embed?header=false&border=false" width="100%"></iframe>
    <script src="//storify.com/<?php print render($item); ?>.js?header=false&border=false"></script>
    <noscript>[<a href="//storify.com/<?php print render($item); ?>" target="_blank">View on Storify</a>]</noscript>

    </div>
    </div>

  </div>
<?php endforeach; ?>

```

I added the `storify-story` ID to deal with some bad behavior where the Storify script was rewriting the DIV it was in and adding `clear: left;` as in inline style.

---
Tags: 7, nodes, media
---


# Question
Title: How do I add rate widget to certain content type?
I have a certain content type I want users to be able to rate. I decided to go with the rate module, since I want to be able to change the value of each star.

My problem is I don't know how to add the certain rate widget to a content type. In widget settings there are no checkboxes in the "Node types" option. Screenshot below.

# Answer
> 0 votes
I cannot find a clear reason for why this happened. The best answer I can give to someone with the same problem (doesn't seem to be a common problem at all) is to start over with a clean Drupal install.

---
Tags: nodes, rating
---


title: How to combine taxonomy terms?

text:
# Question
Title: How to combine taxonomy terms?
I use Taxonomy with Contextual Filter, so I can categorize content (nodes), associating taxonomy terms to each content, and filter them in a View.

I can have a node and 2 different vocabularies, lets say **A = {1,2,3}** and **B={a,b,c}**. I can, by default in Drupal usual behaviour, associate a node with multiple values of A and B, lets say that node Nid has associated 1,2 and a,b.

What I need, if it is at all possible, is to have paired associations, i.e., not only 1,2 and a,b separatedly, but in combination. Let's say `{1,a}` and `{2,b}` and the contextual filter or equivalent, if looking for `{1,a}` will return the node, but if looking for `{1,b}` it will return nothing. Of course, `{1,all}` would have to return the node.

Is there such a module or behaviour in Drupal 7 ?

**Note:** the problem does not lie with the search or filter part. The very basic problem is how to assign a combined value to the node, in the very first place. Later I will face the problem of looking for or filtering for that data. But I don't know how to merge both taxonomy fields into one, so the node is assigned to {1,a} and not to "1" and "a" separatedly.

# Answer
Do you always need to search on multiple terms at the same time? And how do you want to search, via an exposed filter or with query parameters?

In both cases you need to add references to the vocabularies A and B.

If you want to search through an exposed filter, you can add the term name fields (with relation to the references) to the normal filter and just expose them. I'm not sure, but I think there is a way to combine this with global text search.

If you want to work with query parameters you need contextual filters. Just add a term name for both vocabularies and let them match the value of the query parameters. You can specify what results must be shown if the parameter value is 'all' for example.

I don't think you need the or operator because you mentioned you want to match on both terms at the same time. However, if you want to match on multiple combinations you might want to check this module. I haven't tested it myself, but it really saves you some time if it works. The or operator is not native in contextual filters.

Good luck! Contextual filters and references can be a real pain in the ...
> 0 votes

# Answer
I have finally found the solutions, which is very simple: Field Collection. I can group the taxonomies and other fields. I have checked with a View with exposed filters and works perfectly.
> 0 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: Views Table with Taxonomy Terms for Columns and Rows
I have a content type for manuals that has a vocabulary for "Model Year" and another for "Model Name" with a file upload that is for owners manuals for the specific Model Name + Model Year.

I want to push this content type into a view to provide a table where the years are columns and the model names are rows with the resultant cells having the download link.

```
---------------------------------------
        | 2016     |  2015   |  2014   |
---------------------------------------
Model 1 | download |download |download |
---------------------------------------
Model 2 | download |download |download |
---------------------------------------
Model 3 | download |download |download |

```

I've been wrestling with the views all night and the table. I can't seem to get close to what I want. I've tried making sure all the taxonomy terms were added as a relationship.

If I use fields and bring the content of the year and the model forward I can display them, but not as columns, only rows and not as rolled up results in a year - so 10 2016 column instead of one 2016 columns with 10 rows.

I've tried the Views Flipped Table module, but that didn't solved the problem.

# Answer
> 1 votes
The Forena module can be used for this type of reporting. More specifically by using its facility to create a Display of a table in ***crosstab*** format.

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

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

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

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

In this specific case, if I was to create such crosstab table, for "*the resultant cells having the download link*" I'd create a hyperlink which would actually mention the number of manuals corresponding to the selected combination of Model Name and Model Year. And by following such link, you'd get a drilldown report with links to the actual manuals.

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.

# Answer
> 0 votes
It's simple.

In your content type (lets pretend its called Cars) add various (1 value) download fields, like this

* download 2016
* download 2015
* download 2014

Add nodes/pages to your Cars content type

* Ford
* Ferarri
* Honda

Upload the corresponding files to each download field.

Add all the fields to your view. For field **Label** you delete the download part and just leave the year.

**No need to use taxonomy terms here.**

---
Tags: views
---


# Question
Title: How to assign 2 taxonomy vocabularies in a single field for a node?
I have a node. I want to manage fields of this node in the Admin, so I can have a field which is of type Term reference and which uses two or more taxonomy vocabularies. So I can make combinations of 2 vocabularies in the field.

Let's say I have vocabularies A and B. I want to have the field "Categories", which gives the option of choosing from vocabularies A and B. Now, in the normal behaviour of Drupal, I must select one and only one vocabulary when creating the field.

# Answer
Usually is is not good to rely on modules what are not widely used (like Combined Termref), because of worse community support and maitainance.

Consider using Entity Reference module what can connect any type of entities together. You can use it almost the same way like Term reference field.

There propably will be some differences in configuration, but nothing critical (blocking use-cases), just less straightforward. Internally it will works the same - is saves entity ID of term into "term reference field".
> 1 votes

# Answer
Combined Termref

> This module allows you to associate upto 3 vocabularies to a term-reference field. Standard drupal term reference fields allows you to reference terms in a single vocabulary.

I am not already use this module but i think it solve your problems
> 0 votes

# Answer
I have finally found the solutions, which is very simple: Field Collection. I can group the taxonomies and other fields. I have checked with a View with exposed filters and works perfectly.
> 0 votes

---
Tags: 7, entities, taxonomy-terms
---


# Question
Title: How to print user role in body profile page
I've got two roles in my website and I'd like to print the role name in the user profile page body classes for the user being viewed. How can I do this?

# Answer
The **html.tpl.php** template uses the `$classes` variable to add classes to the body element. You can use `template_preprocess_html()` to add classes to this variable. Add this function to your theme's **template.php**

```
//Replace MYTHEME with the name of your theme
function MYTHEME_preprocess_html(&$variables) {

  //Check if the path is a profile page with a valid user
  if(preg_match('/^user\/(\d+)/', current_path(), $matches) == 1) {
    if($user = user_load($matches[1])) {

      //Add each role to the $classes_array which makes it available in $classes
      foreach($user->roles as $rid => $role) {
        $variables['classes_array'][] = str_replace(' ', '-', $role);
      }
    }
  }
}

```
> 0 votes

---
Tags: theming, hooks
---


# Question
Title: How to add wysiwyg (like CKeditor) to Disqus module textarea?
As shown in the following image the input textarea of the Disqus is just plain. Is there a way so we can add wysiwyg (like CKeditor) to it? And that input textbox always located at the top of comments, Is there a way so we can shift it to the bottom of the comments (like core comment module of drupal 7)?

# Answer
> 1 votes
Unfortunately, this is impossible. The Disqus comment form is in an iframe originating from disqus.com. It is basically a separate web page embedded within the content of your website.

If your page were to access the Disqus form, it would violate the Same-origin policy. This policy is to keep your information safe. Imagine if another page could read or modify data when you log in to your bank. Bad news.

---
Tags: wysiwyg, comments
---


# Question
Title: How to resolve the error encountered while trying to import a rule using the Rules module?
I have created a rule by using php code,i want to import it.When i click on import button it is showing that import block border as red(shown in the fig..)

1. Image

2. Code

And my code is shown in below,

```
{ "rules_send_warning_email" : {
    "LABEL" : "Send Warning Email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "text_matches" : { "text" : [ "site:current-user:field-warnings" ], "match" : "New litter" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "New litter was born",
          "message" : "[site:current-user] selected new litter",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

# Answer
Your rule is looking for a field on the user entity type called "field\_warnings". That field doesn't exist, or can't be found for whatever reason, so the import will fail.

You need to either add the field, or find out why Drupal can't find it, to continue with the import.
> 0 votes

# Answer
The way you created this rule (using PHP?) seems to me like equivalent to handwriting a rule in Rules export format. Using the Rules UI you can pretty sure not create a rule that, after save and export, looks like your rule you're trying to import.

The reason why you get that "red border around your import block", is because of the \*Failed integrity check". And that check failed because in your Rules condition it is impossible (for the Rules module) to find that `field_warnings`-field, similar to what Clive also mentioned as a possible cause.

The real reason why that field cannot be found (even if it would exist as a field related to the user account), is because before you can actually use it in a Rules condition, you "must make it available" to Rules. The way (or "a" way) to do that, is to insert an extra condition in your Rules condition, in front of the condition you already have, which looks something like so:

```
{ "entity_is_of_type" : { "entity" : [ "site:current-user" ], "type" : "user" } },

```

**Attention** (1): I'm assuming that field is related to an entity "***user***". If it's another type of entity where that field is related to, then change "user" accordingly. If that still doesn't work, then try with an extra condition that is something about "entity has field".

**Attention** (2): make sure to correctly differentiate between "`user_update`" and "`current-user`":

* `user_update` is related to the userid for which the profile is being updated.
* `current-user` is the userid actually performing the update.

Refer to my answer to "Which Rules condition can be used to email a user when an admin updates their profile?" for a similar case to illustrate the difference between those 2 variations of user ids.
> 0 votes

---
Tags: rules
---


# Question
Title: Setting two default text formats for two long text fields in the same content type
I need to use a specific text format (filtered html) for all user roles for one specific field in a content type and another specific text format (code) for another field in the same content type.

I installed 'Better formats' module using the suggestion here but couldn't see any way to make it do what I want.

Is it possible - and if so, how - to specify a text format for each long text field so that when a user creates a new node of that content type, using the default creation form, they do not select the text type for each of those fields but it is already set for them?

Maybe it DOES use the better formats module and I just can't see how to use it. If so I'd be happy to hear what I could do with that module to solve my problem as well. Thank you.

# Answer
> 1 votes
You need to edit each field and there should be a betters format option there.

**ex:**

Body field: Filter HTML

Code field: FULL HTML

---
Tags: theming, nodes
---


# Question
Title: What are my options to rename a (huge) cache_form table which takes way to long?
I inherited a website that has cache\_form more than 33Gb.

I've followed the following steps:

```
CREATE TABLE new_cache_form LIKE cache_form;

RENAME TABLE cache_form TO cache_form_backup;

```

And in other session:

```
RENAME TABLE new_cache_form TO cache_form;

```

Query is taking long long time and site is not responding.

What could the solutions be?

# Answer
> 0 votes
"Waiting for table metadata lock" will happen with a TRUNCATE or a RENAME and once this query is slated to run all other requests behind it will be stalled. There is no way to tell if a query will have a metadata lock unless you attempt to run it. So if the query does indeed cause a metadata lock you'll want to kill that query and use DELETE FROM instead as this is a DML statement where as TRUNCATE or RENAME are DDL statements.

I created a module that handles the above logic: APDQC

If you want to investigate this you self slides 104 \- 113 of my 2015 DIY Drupal 7 Performance talk is a good start. How to create a stored procedure in order to auto kill stalled queries: http://mysqlblog.fivefarmers.com/2012/08/28/identifying-and-killing-blocking-transactions-in-innodb/

---
Tags: caching
---


title: Not able to access pear.drush.org

text:
# Question
Title: Not able to access pear.drush.org
So what happend to pear.drush.org I havent been able to access that page and drushs puppet module relies on it. Is the site down?

# Answer
> 2 votes
The Pear installation method for Drush was deprecated many years ago; I am not sure how long it has been unavailable, but it will not be coming back. The recommended and supported ways to download Drush are:

1. Use composer
2. Clone the git repository, then run `composer install`
3. Download the .phar

The Drush Puppet module on drupal.org claims to support git and composer installation mechanisms; perhaps you'd have the best luck if you switched to using that one.

---
Tags: drush
---


title: Drupal 8. Error join() Twig function

text:
# Question
Title: Drupal 8. Error join() Twig function
I try to print `field_tags` inline and comma separated. My code in `node.html.twig`:

```
<p>{{ content.field_tags | join(', ') }}</p>

```

This return error message: `The website encountered an unexpected error. Please try again later.`

Whats wrong? Help.

# Answer
> 1 votes
Anything in content is a render array, you can't use functions like that on those directory.

You can loop over it and print out each item, that works as it is then automatically rendered.

---
Tags: 8, theming
---


title: 500 Server Error after deployment

text:
# Question
Title: 500 Server Error after deployment
I apologized as I'm not well versed specifically with drupal. But anyway, I was migrating an existing installation on a Windows Server to a Linux Server (debian).

I went ahead and moved all the files, setup the database, updated `settings.php` in `/sites/default`

I also chown'd with correct user, and set `/sites/default/files` to 777 permissions with all other directories set to 755 and files set to 644.

I have errors with some images, css, and js. I checked the files, and they exist. When attempting to access via GET request (http protocol) I get 500 Internal Server error.

Looking at PHP's error logs I see these alerts (no errors):

```
/sites/default/files/.htaccess: Option FollowSymLinks not allowed here

```

When I edit said .htaccess files to:

```
#Options None
#Options +FollowSymLinks

```

The images load, but the CSS and JS does not (it exists but tries pulling from incorrect directory). I am also worried about security in this folder.

ie:

Actual Request: `GET site.com/css/css_49249400b301b59bd86200648ba96215.css`

Correct Request: GET `site.com/sites/default/files/css/css_49249400b301b59bd86200648ba96215.css`

Anything I could be doing wrong?

Help is appreciated!

UPDATE: Rewrites are enabled and working.

# Answer
Did you have "Clean URLs" enabled on the Windows install? You may need mod\_rewrite enabled in Apache (a2enmod rewrite)

I'm not sure how your server is configured (os/php version/etc), but I had a similar issue that required me to change the following in .htaccess

```
# RewriteBase /
to
RewriteBase /

```

Another thing to check would be that overrides are allowed at all. Apache needs to be set to something like "AllowOverride All"

More info regarding AllowOverride:

How can I enable clean URLs?

How to enable Clean URLs?

Regarding permissions, there is a bunch of information available including a script that can help repair permissions (obviously use extreme caution when running and verify before you do.)

Source for the script below.

```
#!/bin/bash

# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:

  1) Path to your Drupal installation.
  2) Username of the user that you want to give files/directories ownership.
  3) HTTPD group name (defaults to www-data for Apache).

Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}

if [ $(id -u) != 0 ]; then
  printf "**************************************\n"
  printf "* Error: You must run this with sudo or root*\n"
  printf "**************************************\n"
  print_help
  exit 1
fi

drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"

# Parse Command Line Arguments
while [ "$#" -gt 0 ]; do
  case "$1" in
    --drupal_path=*)
        drupal_path="${1#*=}"
        ;;
    --drupal_user=*)
        drupal_user="${1#*=}"
        ;;
    --httpd_group=*)
        httpd_group="${1#*=}"
        ;;
    --help) print_help;;
    *)
      printf "***********************************************************\n"
      printf "* Error: Invalid argument, run --help for valid arguments. *\n"
      printf "***********************************************************\n"
      exit 1
  esac
  shift
done

if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
  printf "*********************************************\n"
  printf "* Error: Please provide a valid Drupal path. *\n"
  printf "*********************************************\n"
  print_help
  exit 1
fi

if [ -z "${drupal_user}" ] || [[ $(id -un "${drupal_user}" 2> /dev/null) != "${drupal_user}" ]]; then
  printf "*************************************\n"
  printf "* Error: Please provide a valid user. *\n"
  printf "*************************************\n"
  print_help
  exit 1
fi

cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .

printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;

printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;

printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;

printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
  find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
  find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done setting proper permissions on files and directories"

```
> 1 votes

---
Tags: deployment
---


# Question
Title: How to fix search result "Access denied You are not authorized to access this page"
How to fix search result "Access denied You are not authorized to access this page"? Have tried to change permissions and search module configuration, nothing helps...

# Answer
In admin/people/permissions, make sure that the roles that should be allowed to search are checked. Under the *Search* heading, look for the *Use search* permission. If anonymous users need this permission, check the box next to *Anonymous User*.
Next, clear your Drupal cache.

If you use Drush, you can use the following command.

```
drush cc all

```

There are several other ways to clear your cache as well.

Lastly, you can try rebuilding your permissions at admin/reports/status/rebuild.
> 2 votes

---
Tags: search
---


# Question
Title: Missing the message status when saving Node
Of the handful of content types on our site, some of them don't display the message status (ex. **Article *Test* has been created**) when the node is saved.

Where can I investigate the cause?

# Answer
This message comes from node.pages.inc (never edit Drupal core) in a form submit function and I believe messages are stored in the `$_SESSION['messages']` variable. I would try to get at these with a hook\_form\_alter() and custom validation and submit handlers to see where it might be dropping.

If you're running any custom code look specifically for interactions with the $\_SESSION variable. Clobbering or unsetting it could prematurely remove these messages.

If you use the devel module you can simply use the following.

```
dd($_SESSION['messages']); //Logs to drupal logs
dpm($_SESSION['messages']); //Outputs debug information to screen

```

You can also create your own messages using drupal\_set\_message()

For example:

```
drupal_set_message(t('It worked!'), 'status');

```

You may also want to check that you don't have something like the Disable Messages module installed or misconfigured.
> 1 votes

# Answer
It may also be necessary to insert a `drupal_get_messages()` statement in `hook_node_insert()`, `hook_node_submit()` or if you are using tpl files for the nodes then place that in the tpl file or any form callbacks. Not sure why it would work for other content types but not others though.
> 0 votes

---
Tags: nodes
---


# Question
Title: Can't seem to make use of new user account field in display suite
I need to be able to display a particular user field in my node display.

The user field is a new, custom field I created, here: /admin/config/people/accounts and it's called 'organization role'. I was able to successfully add values for this field to my users. So the field itself works just fine in the user account settings. When you look at a user it shows their organization role. All that is fine.

However, in my node display I show the photo and name of the author of the node. These fields were made available to me when I installed display suite module and made a custom layout using that module, for my node page(s). However, no matter how many times I flush the cache my new user field 'organization role' is not available to me in my node's 'manage display' tab.

So my question is: how can I make that field available to my node display so I can display it with the rest of the node fields? (and once I make it available how do I actually display it?)

# Answer
Display Suite only shows user fields **Author** and **User Picture** by default. However, there is a way to do this by defining a **Code Field** with Display Suite

Go to `admin/structure/ds/fields`and create a **Code Field**

Select Entities: Node (make this field available to nodes). You can do some additional filtering in **Limit field** if you want

Use the following code (be sure to select **Display Suite code** en `Text format` and use the php tags)

```
 $author = $entity->uid;
 $u = user_load($author);
 if (isset($u->field_special_field[LANGUAGE_NONE][0]['value'])) {
   return $u->field_special_field[LANGUAGE_NONE][0]['value'];
 }

```

(Replace `field_special_field` with the name of your field,e.g. `field_organization_role`). Then go to your Content type Manage display and add the new field.

Another way:

This is really easy to do with Views, though. Create a View of your content type, select `Unformatted list` of `fields`. Add all the fields you want from your Content Type. Go to Advanced and create a **Relationship** to `Content: Author`. This will expose ALL the User fields in the list of Fields. You can add them at your heart's content. If you want to show only one node (rather than a list of all nodes) you can use `Content: Nid` in the `Contextual filter` area and pass the nid at the end of the url, as in www.example.com/view\_name/\[nid\]
> 1 votes

---
Tags: theming, display-suite
---


# Question
Title: Hardening Drupal server running the Update Manager
We are going to do the hardening on one of our Linux server running SELinux and Drupal 7 with firewall; on the Drupal Update Manager, if we want only to get periodic emails / notifications on modules / cores update but NOT update using the UI via SSH / FTP, what ports should we enable on the server and what URL (on the formal Drupal website??) need to be unblocked? What SELinux setting need to be set?

Also, what ports to be enable and setting need to be done for using Drush for update?

# Answer
> 0 votes
I answer my own question: After investigating the update module of Drupal 7.4, I found that Drupal will try to fetch the update information *usually* from

```
http://updates.drupal.org/release-history/<project_name>/<drupal_api_compatibility_version>

```

using drupal\_http\_request function, where project name is usually the plugin module name e.g.

```
http://updates.drupal.org/release-history/views/7.x

```

that means the server need to allow the port 80 for the operation to access pages

```
http://updates.drupal.org/release-history/*/*

```

However, if the plugin module have its own update URL, the update check will check this instead of drupal update site. Therefore, SELinux must allow for network operation, use this command to turn it on:

```
setsebool -P httpd_can_network_connect 1

```

# Answer
> 0 votes
I cannot answer your question regarding ports.

But I will recommend installing the Update Status Advanced Settings module to tailor the notification messages you get from Drupal:

> Users of the 5.x Update status contrib module will probably want to use this once they upgrade to 6.x, since some of the functionality in the contrib version was deemed too complicated to include in core. In particular, the per-project settings to ignore certain projects or even specific releases, is absent in the core version of the module. The "Update status advanced settings" module restores these settings, and might eventually provide additional functionality for the core "Update status" module.

This way if your site uses Features, or custom made modules not hosted on Drupal.org the update notification will not inform you of issues related to looking up version information on them. But you'll have to configure this setting on a site by site basis -- it's not a system-wide server configuration.

---
Tags: updating, security
---


# Question
Title: How can I write an input selector for the states API?
I'm trying to use the `#states` API but my input selector isn't being picked up. This is the code I've added to `hook_form_alter()` in a custom module:

```
  case 'my_form':
    $form['revision_information']['#access'] = FALSE;
    $form['field_guide_link_hosting']['#states'] = array(
      'visible' => array(
        ':input[name="field_guide_types[und]"]' => array('value' => 's'),
      ),
      'required' => array(
        ':input[name="field_guide_types[und]"]' => array('value' => 's'),
      ),
    );

```

And here's the rendered form for `field_guide_types`:

```
<div class="form-item form-type-checkboxes form-item-field-guide-types-und">
  <label for="edit-field-guide-types-und">How can you help tourists? <span class="form-required" title="This field cannot be left blank.">必須</span></label>
 <div id="edit-field-guide-types-und" class="form-checkboxes"><div class="form-item form-type-checkbox form-item-field-guide-types-und-o">
 <input type="checkbox" id="edit-field-guide-types-und-o" name="field_guide_types[und][o]" value="o" class="form-checkbox">  <label class="option" for="edit-field-guide-types-und-o">Answer questions and offer information online </label>

</div>
<div class="form-item form-type-checkbox form-item-field-guide-types-und-m">
 <input type="checkbox" id="edit-field-guide-types-und-m" name="field_guide_types[und][m]" value="m" checked="checked" class="form-checkbox">  <label class="option" for="edit-field-guide-types-und-m">Meet in person </label>

</div>
<div class="form-item form-type-checkbox form-item-field-guide-types-und-s">
 <input type="checkbox" id="edit-field-guide-types-und-s" name="field_guide_types[und][s]" value="s" class="form-checkbox">  <label class="option" for="edit-field-guide-types-und-s">Provide a place to stay (like through AirBNB, CouchSurfing, etc.) </label>

</div>
</div>
</div>

```

# Answer
> 3 votes
`drupal_process_states()` has a great set of information on handling inputs for different types of input elements.

You have checkboxes, so you have to use `checked` assertion.

```
case 'my_form':
    $form['revision_information']['#access'] = FALSE;
    $form['field_guide_link_hosting']['#states'] = array(
      'visible' => array(
        ':input[name="field_guide_types[und][s]"]' => array('checked' => TRUE),
      ),
      'required' => array(
        ':input[name="field_guide_types[und][s]"]' => array('checked' => TRUE
      ),
    );

```

Notice I replaced the `value` assertion with a checked, and also changed the jQuery selector to use the full `name` attribute of the checkbox.

---
Tags: javascript
---


title: How to configure the popular TAGS block

text:
# Question
Title: How to configure the popular TAGS block
I need this effect, but I don't know how to do that:

# Answer
Hello You can use Tag Cloud Module for this purpose it is easy to use, following is simple method to show Popular Tags block

1. Unzip and copy the directory to `/sites/all/modules`.
2. `/admin/modules` activate **TagClouds**.
3. `/admin/config/content/tagclouds` set the Settings to what you want. See **Module Settings** bellow.
4. `/admin/structure/block` and find the block titled "Tags in \[taxonomy name\]" and move to where you want it displayed. See "Block Settings" bellow.

Your all set up!

Best Wishes Rana
> 0 votes

# Answer
cctags

> flexible configuration and advanced features for theming clouds. (individual files of templates for tags, the names of the dictionary, pages clouds)
>
> Possibility (in settings include several dictionaries (as for dictionaries with tree structure - in addition to enable / disable the desired level)) tags. Automatic generation of the required number of blocks and / or pages. Generation unit of Tag attached to the node. Generation of block-related materials for the node (via tags) Cloud members users (block and page) (with weights proportional to the number of published material)

TagCloud

> Tag clouds is a light weight stable module that provides span tags, optimizations; It is also singular in purpose and stable.
>
> Provides a link to the node and not the taxonomy display if the node count is equal to 1. This avoids taxonomy pages with only one node. Defaults to On, can be turned off

OR you can do it

You can do this with views:

* create a view of terms
* add a required relationship to "content using tags"
* set use aggregation: yes
* add the "term name" field a second time, set one of the to "aggregation type: count"
* add "term name" as a sort criteria, set "aggregation type: count"
> 1 votes

# Answer
There are certain modules that will do this.

**TagCloud**

> This module Provides a TagCloud and List of Tags. Tag clouds is a light weight stable module that provides span tags, optimizations; It is also singular in purpose and stable.

**Tagadelic**

> Tagadelic provides an API and a few simple turnkey modules, which allows you to easily create tagclouds, weighted lists, search-clouds and such. With the API you can build a module with a few lines of PHP, to turn anything that can be counted into a weighted cloud. Which can be presented to your users anyway and anywhere on your site.

**cctags**

> module cctags - as an alternative to module tagadelic. flexible configuration and advanced features for theming clouds. (individual files of templates for tags, the names of the dictionary, pages clouds)

and with effects **Cumulus**

> Cumulus allows you to display your site's tags using Flash that rotates them beautifully in 3D. It works like a regular tag cloud, but is more visually exciting.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Language detection method "Browser" doesn't work if I check "Cache pages for anonymous users"
I have two method detection activated in this order:

1- URL

2- Browser

Problem is that the method "Browser" doesn't work at all if "Cache pages for anonymous users" at 'admin/config/development/performance' is checked. **The default language is loaded all the time regardless the Browser language.**

It works fine if I uncheck "Cache pages for anonymous users".

See the captures.

# Answer
> 2 votes
have you seen and tried:

https://stackoverflow.com/questions/22792062/drupal-7-always-redirecting-to-default-language

> You might be affected by a bug in Drupal core. I had the same problem for a while and finally found the cause and a workaround for it.
>
> It goes like this:
>
> 1. Add this code to a custom module (change "mymodule" to your modules' name):
>
> ```
> /**
>  * Implements hook_language_negotiation_info_alter().
>  *
>  * Remove the 'cache' setting from LOCALE_LANGUAGE_NEGOTIATION_BROWSER since
>  * the code that utilizes this setting will in fact prevent browser negotiation.
>  */
> function mymodule_language_negotiation_info_alter(&$negotiation_info) {
>     unset($negotiation_info[LOCALE_LANGUAGE_NEGOTIATION_BROWSER]['cache']);
> }
>
> ```
> 2. Clear all caches (e.g. "drush cc all")
> 3. Go to admin/config/regional/language/configure and press "Save settings" once (this will rebuild the variable 'language\_negotiation\_language').
>
> Now browser language detection should work properly.
>
> I'm also looking for a real solution but this requires changes in core and probably some discussion beforehand because of the nature of the bug. I've opened an issue here: Browser language detection for anonymous requests is broken

**there is now a patch from Berdir**

# Answer
> 0 votes
You need to write custom module to unset the local languages, then it will be sort out your issue

---
Tags: caching, i18n-l10n
---


# Question
Title: Drupal 7 PHP version migration from PHP 5.3 to PHP 5.6
Our current Drupal 7 site runs on PHP 5.3 environment. But the server provider insisting to upgrade the PHP version to PHP 5.6 as they are about to end the support for PHP 5.3 and PHP 5.5 .

Is there any known issues for an existing Drupal 7 site migration into php 5.6?

Any tools/modules to check the version compatibility of current Drupal 7 in PHP 5.6 ?

Other than this any suggestion or advices prior to the migration ?

# Answer
> Is there any known issues for an existing Drupal 7 site migration into php 5.6?

For Drupal core specifically, that information will be in the issue queue. A quick search for "5.6" brings up no results. It it helps, I've been running D7 on 5.6 for ages now with no problems.

Contrib modules might be a different story, you'll need to check each of those individually, unless they offer that info specifically on the project page, or through a minimum PHP version specified in the module's .info file.

> Any tools/modules to check the version compatibility of current Drupal 7 in PHP 5.6 ?

Not Drupal-specific tools (it wouldn't make sense for there to be since this just a plain PHP question). You can probably make good use of something like PHPLint. Personally I would start with IDE tools (switch the language version to 5.6, run a validator, then check the current issue list for errors)

> Other than this any suggestion or advices prior to the migration ?

The only sane advice is for you to treat this as any other upgrade, whether that be code or server - make sure the site is **fully** tested in a development environment before pushing anything live. Have a plan in place to downgrade quickly on the live servers in case something goes wrong. If that's not an option (i.e. you don't control the server software), then re-double your testing efforts, and make sure server config is as identical as you can get it before pushing anything live.
> 7 votes

# Answer
Today, I tried Drupal 7 on PHP 5.6 on a shared hosting plan. I can see it works slower when `taxonomy_menu` and `views` are enabled. But if you do not have these, it works just a bit slower. So I use PHP 5.5 in this case.

However, Drupal 8 works slower with PHP 5.5 and does not even install. But it will work when installing it under PHP 5.6 and then switching the server back to PHP 5.5.
> 1 votes

---
Tags: migrations
---


# Question
Title: How to print date in format «long» on node.html.twig template?
Try this code (at `node.html.twig`, Drupal 8.0.0-rc3):

```
{% set date = node.created|format_date('long') %}

```

And next:

```
{{ dump(date) }}

```

Return error:

```
Exception: The timestamp must be numeric. in Drupal\Component\Datetime\DateTimePlus::createFromTimestamp() (line 165 of core/lib/Drupal/Component/Datetime/DateTimePlus.php).

Drupal\Core\Datetime\DateFormatter->format(Object, 'long')

```

# Answer
> 16 votes
you are not using the actual timestamp. Here's what you should do:

```
{% set date = node.createdtime|format_date('long') %}

```

See? You only need to replace created with createdtime. Hope this helps.

# Answer
> 5 votes
Try in this way.

```
{% set date = node.created %}
{{ set date|date("m/d/Y") }}

```
* Refer here to know more about filter date in **TWIG**.
* Refer here to know more about **date formats in php**.

Hope this will help you.

---
Tags: theming, 8, datetime
---


# Question
Title: How do I override the Bootstrap3 user registration form?
I am trying to override the default user registration form (`user_register_form`). I would like for the form to create a CCK node (`membership_request`) that is already on the system. I am able to get all of the hook overrides setup correctly but I can not get the fields of the CCK form to show up.

Here is what I have done so far:

**sites/all/themes/bootstrap/includes/registry.inc**

```
 $hooks['membership_request_node_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'bootstrap') . '/templates/forms',
        'template' => 'node--membership-request-form',
        'arguments' => array('form' => NULL),
        'preprocess functions' => array(
                'bootstrap_preprocess_membership_request_node_form'
        )
  );

```

**sites/all/themes/bootstrap/template.php**

```
function bootstrap_preprocess_membership_request_node_form(&$vars) {
    //$args = func_get_args();
    //array_shift($args);
    //$form_state['build_info']['args'] = $args;
    //$vars['form'] = drupal_build_form('membership_request_node_form', $form_state['build_info']['args']);
    //$vars['form'] = drupal_build_form('membership_request_node_form', membership_request_node_form(array()));
    $vars['intro_text'] = t('This is my super awesome reg form');
}

```

**sites/all/themes/bootstrap/templates/forms/node--membership-request-form.tpl.php**

```
<?php
print $intro_text;
//print drupal_render_children($form);
?>

```

In the below examples, "This is my super awesome reg form" will show up as expected  in the new registration form. However, 1) all attempts to pass the form from the preprocess function have failed for me (as shown with the commented lines in the template.php file) 2) when the `drupal_render_children` line is uncommented in the tpl file I get the following errors:

Thanks

# Answer
Why don't you alter the user registration form by adding fields at `admin/config/people/accounts/fields` there is an option `Display on user registration form`.

This will then modify the User entity to use those fields, which may mean your `membership_request` node is not needed, but if it still is you can use Rules to automatically create a node when a user registers.
> 0 votes

---
Tags: theming, forms
---


# Question
Title: It says "No Solr instance available when trying to clear the cache", should I reinstall that module?
In admin/reports/apachesolr/solr "No Solr instance available when trying to clear the cache", should I reinstall that module? I can\`t cope with setting up the search block to return the search result.

# Answer
> 2 votes
First check whether your solr instance working properly or not. Goto http://localhost:8080**(your port)**/solr/admin/. And in your site goto **admin/config/search/apachesolr/settings/solr/edit** page and enter **SOLR SERVER URL** and click on test connection whether your solr instance working or not. If not try to re-install solr if there is not indexing.

---
Tags: search
---


# Question
Title: Autocomplete field search start character limitation?
How can I limit the number of characters on when the search starts send a request to the server?

What happens if I do for example always call my own API (in the sense of using the autocomplete\_path attribute)? Is the minimum still 3 characters?

# Answer
Will you explain the search that you are using (ex.solr, default). Basic limitation of characters is 3. if you want to increase this go to admin/config/search/settings and change the length of Minimum word length to index to **your-limit** and re-index the site. If you type minimum word length then only your search send a request to server.
> 1 votes

---
Tags: ajax
---


# Question
Title: Change menu link before rendered in mmenu module
I've used Mobile sliding menu module version 7.x-1.0-dev.

We can change menu link using `theme_menu_link()`.

Similarly is any other hook for change menu link in this module?

# Answer
You want to implement hook\_translated\_menu\_link\_alter() and hook\_menu\_link\_alter(&$item). This hook is not called for all menu items.

According to the API documentation:

It is only invoked if $item\['options'\]\['alter'\] has been set to a non-empty value (e.g., TRUE). This flag should be set using hook\_menu\_link\_alter(). Here's an example:

```
function MODULE_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['options']['alter'] = TRUE;
  }
}

function MODULE_translated_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['href'] = 'node/5';
  }
}

```

### Some notes

You may want to filter additionally by $link\['menu\_name'\]; MODULE\_menu\_link\_alter() is invoked on cache clear for all menus items declared via hook\_menu(). For menu items created via web it is only invoked on save, that is, for this code to take effect you need to edit-and-save menu links you want to alter.
> 1 votes

---
Tags: routes, hooks
---


# Question
Title: Whats the impact of changing image styles and jpeg compression
I've inherited a 10-year-old image-heavy (tens of thousands of images) Drupal 7 site. I'm moving the site to a full-width grid, and before I break anything, would someone be able to tell me what happens to the images after you change an image style, or the image compression ratio?

Does this cause the server to process each image and regenerate the images which would take forever and possibly break things. Or does this happen on a page load basis?

# Answer
> 2 votes
All 10,000 will **not** be regenerated at the same time. They are regenerated on page load basis. Depending on how big in size these images are, will affect how fast they are regenerated. Once they are regenerated, should load fast from then on.

The old image style will get auto deleted from the /styles folder.

---
Tags: media
---


# Question
Title: Why do OG Vocabulary terms not list content?
Drupal 7.41, OG 2.7, og\_vocab 1.2.

I've created a group, and a group content type. I added a og vocab to the group and enabled it for the content type. The og\_vocab field shows on the node edit page, and the terms in the og\_vocab are displayed on the node view. But when I click a term to view all content that has been tagged with that term, the term page does not list any content.

It looks something like:

```
# Term
Primary tabs
View(active tab)    Edit

There is currently no content classified with this term.

```

If I do the same thing with a **normal** vocabulary, the term page **does** list the content.

I've tried just the `taxonomy/term/<term id>` path, as well as the alias pathauto generated `<og vocab name>/<term name>`. Both show the same thing.

As far as I can tell, the only modules that could be overriding the path are views and page manager. I made sure neither was doing so.

So, how do I get the term page for og\_vocab terms to list the associated content?

# Answer
I waited a few days on this to see if anyone posted a solution but no luck..

I've never had any luck with og\_vocab and instead use a content type as a group type and use that just like taxonomy. This is possible by using entity reference fields that use entity reference views for values instead of a taxonomy field. But the "taxonomy term" ie. Field value must be set before hand as far as I can tell.

If this solution, and I actually like it a lot, sounds like it could work, I can write up a more detailed guide.
> 0 votes

---
Tags: taxonomy-terms, organic-groups
---


# Question
Title: How should I balance Features and Installation Profile in a Code Driven Development workflow?
Drupal Installation Profiles (in Drupal 7) are pretty powerful and can do just about anything a module can do. I'm using an Installation Profile along with Features to develop my site, keeping everything in code so I don't have to version my database.

Given the power of Installation Profiles, many of the things you can do in a Features module can also be done in an Installation Profile. E.g., creating content types, configuring permissions, etc. How should you go about deciding whether something belongs in an Installation Profile or in a Features module when using a Code Driven Development workflow in Drupal?

# Answer
I've recently started using the Features module as a deployment system, as described in this presentation on features deployment. Assuming your using a similar setup with hook\_update\_N, features has one clear advantage that I'm aware of: it's aware of any changes that are not in code. This makes it a fair bit easier to track changes to (for example) views and content types, and also allows you to auto-generate the new features code to be committed and deployed.

I'm not overly familiar with installation profiles, but from the link you've provided it doesn't look like they provide this functionality. However it might be a case of use whichever suits you the best.

Edit: rethought response.
> 1 votes

# Answer
I'm using drush quite a bit for this. I have three combined commands (never tried it in one line lol) that I execute after installing Drupal. I got most of the things up and running quite quickly.

So many things you can do with Drush. Downloading and enabling multiple modules is as simple as

```
drush dl rules views admin_menu && drush en -y rules views admin_menu && drush dis -y toolbar

```

multiple views can be imported per module easily https://www.drupal.org/node/1393228.

Just annoying that I can't import multiple rules (without the Features module).
> 0 votes

---
Tags: features, distributions, version-control
---


# Question
Title: How to translate a panel page title and a pane title
I want to ask if there is a way to translate the title of a panel and also its panes titles whatever content they are. I use panels to override user/%user page and there i putted as panel title the token "Profile of %user:user-raw" and i have also other content(views,blocks,nodes) with their titles. Thanks in advance.

# Answer
> 8 votes
Latest version of Panels module (**7.x-3.4** as today) includes **Panels translation** module (`i18n_panels`), which provides a fix for this issue.

# Answer
> 5 votes
I'm sorry to say that, in short, you cant.

Translation never was a feature of Panels until very recently, and the patch is currently only for D7, although it will likely be backported.

The problem at it's core is that Pane titles could come from a source that has already translated, which makes translating them a bit complicated.

With that said, there is a work-around:

```
/**
 * Implements hook_panels_pane_content_alter().
 */
function HOOK_panels_pane_content_alter($content, $pane, $args, $context) {
  if ($content->title) {
    $content->title = t($content->title);
  }
  return $content;
}

```

But it's important to realize that if you have a title like

> Content tagged with %term

then you will end up with one translatable string for each value of `%term`.

# Answer
> 1 votes
Just had the same issue, where the panel title I needed to translate was "on same day as %node:title". I fixed this with the Custom token module, where I added a custom node token with this content:

```
<?php $on-same-day = t('On same day as'); return $on-same-day; ?>

```

then translated this token via admin -\> configuration -\> translate interface, and referenced it into the panel as such:`%node:on-same-day %node:title` \- worked like a charm!

..this for Drupal 7, but should be the same for 6.

# Answer
> 1 votes
Yes it is possible to translate the title of a panel page. It just depend on how you want to approach it.

In my case, the Panels Page Manager lets you choose among three options for the page title. The option is called **Title type**:

* No title
* Manually set
* From Pane

When you set the title manually, it is hard coded in a way that seems impossible to translate. I gave up on it after spending a considerable amount of time searching for a solution.

When you choose the option "From Pane", this lets you specify which panel pane's title should be use for the page title. Here is how you do it:

1. Set the **Title type** to "From Pane". This will hide the text field for the title.
2. Click on **Update** or **Update and Save**. After that, you will notice that the contextual menu for each pane will have a extra option called **Panel title**. That option is just a toggle menu item. So when you click on it, it will have a check mark next to it. Only one pane can have that check mark at any given time. Panels will take care of make sure of that.
3. Add a pane that is translatable somehow. In my case, the Bean module was install. I used it to create translated chunks of contents that I could use as panes. Block are a little awkward when it comes to translation. In your case, use whatever you have that can be used as a Panels Pane and that is translatable.

It may seems like to many steps and chunks of content to handle just for specifying a page title, but that's what Panels is about. Peacing a page together using panes from here hand there.

Have fun.

Et Voilà

# Answer
> 0 votes
In case of not using *i18n* module but *Entity Translation* module, you can't use *i18n Panels* module.

The Panels module comes with a few templates. One of them, `panels-pane.tpl.php` holds the title, like this:

* Copy that template file to your themes directory.
* Place the `$title` variable in the `t()` function like this: `<?php print t($title); ?>`
* Empty cache, refresh your page and the title comes available for translation at `/admin/config/regional/translate/translate`

Not ideal, because you don't want content in there, but a good workaround.

---
Tags: 6, panels, i18n-l10n
---


# Question
Title: Load and render all pages from main menu
I'm trying to create a one-pager website in which I'd like to get all the main-menu links and load their complete content underneath each other on the homepage. So that's blocks, display etc. in all.

So I was thinking I could just get the page and render it in an each link; but I can't figure out how I can load and render multiple pages in one go.

I make a preprocess\_page hook and got the menu links I want. How do I go about and get all those pages underneath each other now?

```
function myproject_preprocess_page (&$vars) {

    //Get ALL The pages from the main menu and ALL the content
    //And make one large content for all of it to create a one-pager
    if (isset($vars['node']) && strtolower($vars['node']->title) == "home") {
        $menu = menu_tree_all_data('main-menu');
        if ($menu) {
            foreach ($menu as $menuItem) {
                $a = menu_get_item($menuItem['mlid']);
                //echo render ($a); // Gives nothing
                //echo drupal_render_page($a); //time-out
            }

        }

}

```

}

I also tried with menu\_load\_links but I can't really see if I'm extracting the node now and how to render that.

```
$menu = menu_load_links('main-menu');

if ($menu) {
    foreach ($menu as $item) {
        $b = menu_get_item($item['link_path']);
    }
}

```

# Answer
> 1 votes
you cannot render menu entries, but render arrays. you need to get the node from the menu item's path (see here) and then you can use node\_view to get its render array.

a way better solution would be to make a views page, with a menu\_node relationship.

---
Tags: nodes, routes, theming
---


title: Table width in view not run

text:
# Question
Title: Table width in view not run
i have problem with table width in view.
This is my setup of view: in my style.css i have this:

```
.novinky-telo{
width:50px;
background-color:red;
owerflow:hidden;
}

```

but result is:

I need only 50px width, have you any ideas?

# Answer
set the following in your class .novinky-telo

```
word-break: break-all;

```
> 1 votes

# Answer
> owerflow:hidden;

you missed spelled overflow

```
overflow: hidden;

```
> 1 votes

---
Tags: views
---


# Question
Title: How can I change the default system message shown on form submission
I've created a business card request form as an EntityForm and am scratching my head trying to figure out where in the module i can find the line - ( " The submission has been saved " ) .

This message displays after every form submission/edit/save, and I would like to get rid of it but cant figure out where its coming from ! :)

# Answer
> 0 votes
That message comes from entityform\_edit\_form\_submit

You could try setting the translatable text string to an empty string in settings.php

```
$conf['locale_custom_strings_en'][''] = array(
  'The submission has been saved' => ''
);

```

Or else look into another way to alter drupal\_set\_message text.

# Answer
> 0 votes
Instead of that, I would recommend going to the "Form overrides" Tab of the entity form and set the Your Submissions Text and Submission Confirmation Text to ""

# Answer
> -1 votes
Click edit and choose tab form overrides and Submission Confirmation Text. write your text.

---
Tags: forms, entities
---


title: Add reverse IN clause to db API

text:
# Question
Title: Add reverse IN clause to db API
I need to add **IN** clause while implementing **hook\_views\_pre\_execute**

But it's not the regular **IN** added like the next line

> {table1}.col1 IN (val1, val2)

```
$query->condition('author', array($user->uid), 'IN');

```

Wanted to add reverse

> {val} IN ({table1}.col1, {table2}.col2)

```
$query->condition($user->uid, array(pm_message.author, pm_index.recipient), 'IN');

```

But the query takes the fields as values not column names

Is it possible to be added in drupal

Simply I need to get messages where the user is the author or the reciever in privatemsg

# Answer
> 4 votes
That's (arguably) non-standard, so you'll need a `where`.

For example,

```
$query = db_select('foo');
$query->where(':val IN ({table1}.col1, {table2}.col2)', array(':val' => $user->uid));

```

will get you

```
SELECT
FROM
{foo} foo
WHERE  (:val IN ({table1}.col1, {table2}.col2))

```

(with `:val` replaced by `$user->uid`).

---
Tags: views, database, privatemsg
---


# Question
Title: Migrate_d2d: Excluding node import based on a date comparison
For a migrate\_d2d project, D7 -\> D7, I wish to exclude the importing of nodes whose date field is less than the current date. My only class overrides are for mapping custom fields. The migrate function is working as I expect. However, we don't need to import nodes whose dates have passed today's date.

The custom node field is not part of the core field data set, so the following:

```
public function prepareRow($row)
{
    $postDate = $node->field_job_start[und][0][value2];
    if ($postDate < time()) {
        return FALSE;
}

```

Will not work, as 'field\_job\_start' isn't accessible until prepare() by which time, apparently, a `return FALSE` doesn't cancel the row import.

What is the best way to exclude these rows?

# Answer
You have to do this in prepareRow. Whatever value is mapped to field\_job\_start, check its value there and return FALSE.
> 1 votes

---
Tags: migrations
---


# Question
Title: How to choose between all the Views hooks
Reading the docs about Views hooks doesn't really help me to make the right choice between all the hooks. As per this comment, this is the Views hooks execution order:

1. `hook_views_pre_view`
2. `hook_views_pre_build`
3. `hook_views_post_build`
4. `hook_views_pre_execute`
5. `hook_views_post_execute`
6. `hook_views_pre_render`
7. `hook_views_post_render`

I'm currently trying to alter properly the output of a view field :

I tried with `hook_views_post_execute(&$view)` :

```
function MODULE_views_post_execute(&$view) {
  if ($view->name == 'foo' && $view->current_display == 'bar') {

    foreach ($view->result as $result) {

      if (isset($result->field_field_status)) {

        switch($result->field_field_status[0]['raw']['value'] ) {
          case 1:
            $text = 'ABC';
            break;
          case 2:
            $text = 'DEF';
            break;
          //and so on
        }
        $result->field_field_status[0]['rendered']['#markup'] = $text;
      }
    }
  }
}

```

This worked fine at first glance : returned string display nice, but raw data were displayed again after a while. After clearing page cache the expected output turns back, but then disappeared again, and so on.

Then I tried with `hook_views_pre_render(&$view)` , with **exactly the same code inside that other hook** giving exactly the same result.

# Question(s) :

What makes the hook be applied or not ? Wrong hook use maybe ? Is there any logic to apply one or another of these hooks ? *(After reading @Alexar comments : yes I'd explicitly like to know about views hooks, the example is just to illustrate my searches and misunderstandings.)*

**I really need to understand the logic behind all that for my "learning curve".**

## Edit :

Lastly, I used a `views-view-field.tpl.php` to change the output of my field, another possibility adding more confusion to my global understanding of the view construction background... Anybody for a bit of Drupal pedagogy ?

# Answer
> 6 votes
The documentation View Hooks is clear about the purpose of every hook. It says about `hook_views_post_execute(&$view)`:

> This hook is called right after the execute process. The query has been executed, but the pre\_render() phase has not yet happened for handlers.

And gives an example what you can do with this hook:

```
function hook_views_post_execute(&$view) {
  // If there are more than 100 results, show a message that encourages the user
  // to change the filter settings.
  // (This action could be performed later in the execution process, but not
  // earlier.)
  if ($view->total_rows > 100) {
    drupal_set_message(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}

```

At this point the database query was executed and you can do something with the result of the query, for example place this warning.

When you search in drupalcontrib, you find, that it is only used once:

drupal contrib search

Here it is used following the documentation. But no one in contrib used it for other things. You would be the first, with unpredictable results.

What you want to do is not specific to views, and because of that it is not in your list of view hooks. It is more connected to theming in drupal.

It is not advisable to put extensive code in the templates `*.tpl.php`, better put it into a preprocess function. Some examples for views:

* hook\_preprocess\_views\_view
* hook\_preprocess\_views\_view\_field
* hook\_preprocess\_views\_view\_fields
* hook\_preprocess\_views\_view\_grid
* hook\_preprocess\_views\_view\_table
* hook\_preprocess\_views\_view\_unformatted
* hook\_preprocess\_views\_view\_list

Use the preprocess hook, that correspondents with your views configuration.

# Answer
> 1 votes
I am unsure about the `hook_views_post_execute` render issues. That is a new one on me. From what I understand about what you are trying to accomplish I would suggest using neither. For altering output I like to use preprocess hooks (if post\_execute does not work). I have not tested it in this exact type of situation but you may want to look at `hook_preprocess_views_view_field(&$vars)`. This should allow you to change the output directly.

---
Tags: views, hooks
---


# Question
Title: How to remove search on Site and leave only search on Content?
How to remove search on Site and leave only search on Content? When I use search on Site it says "Search is temporarily unavailable. If the problem persists, please contact the site administrator". When I search on Contents, it is OK.

# Answer
So you are trying to make sure that the core Search only searches for content? if so you can tweak the core Search module at /admin/config/search/settings.
> 3 votes

---
Tags: search
---


# Question
Title: How do I import a database through a Drush(PHP) script?
I am trying to write a Drush script locally to speed up some repetitive tasks. I am running in to issues importing a database through the script. I have tried using `drush_invoke` and `drush_invoke_process` to run the equivalent of `drush sql-cli < C:/path/to/mysql.sql`.

I have tried several different variations with the `$commandline_args` and `$commandline_arguments` with no luck and Google has not been helping me much.

Does anyone have the correct syntax for this? I would also be fine with another method that works. I would prefer one that allows for a user input path to the SQL file but hard coded would work for now.

EDIT: I am using `drush scr` to run the script. Just in case it makes a difference.

EDIT 2: The accepted answer from greg\_1\_anderson works great. To allow for using the path to the file as an argument I found that drupal\_get\_option works. Just add the argument `--arg_name=arg_value` like `drush scr script.php --file=path/to/file`. Then call the arg in the script file.

Full solution:

```
$file = drush_get_option('file');
$options = array(
  'file' => $file,
  'file-delete' => FALSE,
  'strict' => FALSE,
);
drush_invoke_process($self, 'sql-query', array(), $options);

```

# Answer
Basically, you want to run some php code to import an SQL database dump from a file. There is code that does this in the implementation of `drush sql-sync`. It looks like this:

```
  $options = $global_options + $target_options + array(
    'file' => $destination_dump_path,
    'file-delete' => TRUE,
  );
  $return = drush_invoke_process($destination, 'sql-query', array(), $options, $backend_options);
  if ($return['error_status']) {
    // An error was already logged.
    return FALSE;
  }

```

You could also call `drush sql-sync` with appropriate options for a more full-featured solution (e.g. if you want to import a local database to a remote site). For an import to a local site, though, it is more straightforward to simply use the snippet above, which essentially runs `drush sql-query --file=/path/to/dump.sql`.

n.b. You may simply remove (or make empty) `$global_options`, `$target_options` and `$backend_options`. You should also take of the `file-delete` flag, unless you really would like Drush to delete your sql dump for you after it has imported it (e.g. for temporary files).
> 5 votes

---
Tags: 7, drush
---


# Question
Title: Line breaks with theme settings textarea
I'm using the following to get a form field in the theme settings page

```
function theme_form_system_theme_settings_alter(&$form, $form_state) {
   $form['foo_example'] = array(
   '#type'          => 'textarea',
   '#title'         => t('Widget'),
   '#default_value' => theme_get_setting('foo_example'),
   '#description'   => t("Place this text in the widget spot on your site."),
 );
}

```

The problem is when I output the result in my theme file with this:

```
$foo_example = theme_get_setting('foo_example');
print render($foo_example);

```

It doesn't respect the line break and puts it all in one p tag. I'd like it to respect the line break and put each line in a p tag if possible.

# Answer
Try to use "text\_format" type.

```
 $form['foo_example'] = array(
   '#type'          => 'text_format',
   '#title'         => t('Widget'),
   '#default_value' => theme_get_setting('foo_example'),
   '#description'   => t("Place this text in the widget spot on your site."),
   '#format' => null, //I think "null" saves the default text format of your website. If you want to see your changes you must put a dynamic value.
 );
}

```

NOTA BENE: the values saved by this type of textarea, is an array with "value" and "format" keys:

```
$var_saved = array(
'value'=> 'something',
'format' => 'full_html', //could be filtered_html, plain_text or any custom text format you've created.
);

//in your field definition
'#default_value' => $var_saved['value'],
'#format' => $var_saved['format'],

```

I didn't test it for your case, but choosing the right format, will normally output the text with respect of the rules chosen for that format type.

If I understood well your problem...
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Can two profile types be created with one role?
I have created two profile types *Self Employee* and *Salaried Employee* for the role *Employee*.

I want to present these profile forms inside the user account edit form. For that, I'm using the Account Profile module. However, it's only showing the *Self employee* form.

Is it possible to show multiple profiles for role?

# Answer
> 0 votes
Yes, with Account Profile, multiple profiles can be embedded for given role. In order to make this happen, you need to:

1. Make sure both profile types have the *Show this profile as part of user account form.* checked on profile settings page (i.e. the edit links in **/admin/structure/profiles**).
2. Make sure the role in question has both the *Edit own profile* & *View own profile* permissions set for each profile type.

---
Tags: 7, users
---


title: Entity Query from comment not working

text:
# Question
Title: Entity Query from comment not working
I tried using entityquery for comment by nid but its not working here is my code :

```
$query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'comment')
    ->entityCondition('entity_id', 257, '=')
    ->addMetaData('account', user_load(1));

```

and also I tried changing to `nid` but still its showing all the comments instead of by specific `nid`:

```
$query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'comment')
    ->entityCondition('nid', 257, '=')
    ->addMetaData('account', user_load(1));

```

can someone tell me I am doing anything wrong?

thank you

# Answer
`nid` is a property of the comment entity, so try:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'comment')
    ->propertyCondition('nid', 257)
    ->addMetaData('account', user_load(1));

```
> 1 votes

---
Tags: entities, comments, database
---


title: ckeditor showing blank text area

text:
# Question
Title: ckeditor showing blank text area
I have been using ckeditor, with ckeditor drupal module with ckeditor 4.4.3 full edition. Previously, it was working fine and suddenly it was not working and it was showing blank text area in the body field as shown below.

I tried to re-install ckeditor module and library fields, but no change in the result. It appears empty, I couldn't trace the reason. How can I get to work with ckeditor.

Previously, my ckeditor was inserting span elements with a line-height of 1.6em in my paragraphs of text and I have no idea why.

The bottom shows body \> p \> span span span. Spans with 1.6em line heights.

How can I resolve the issue??

# Answer
> 1 votes
I suggest to clear cache, use jQuery update module to update the version of jQuery. This worked for me.

Wish it might help!!

# Answer
> 0 votes
I too had the same issue. My issue was solved by completely removing the older files and adding new ckeditor files. And cleared both browser cache and drupal cache. I was just overriding the files to the old Ckeditor folder , there was my issue.

---
Tags: 7, wysiwyg
---


title: Programmatically re-order role weights?

text:
# Question
Title: Programmatically re-order role weights?
I want control over the order in which roles' columns are displayed on the Permissions page..

I want to add code to my module installation file so that, after newly-configured roles' yaml settings have been applied (they list the permissions for each new role), it displays all the roles in the order I want.

How do I do this?

## Motivation

The roles' yaml settings are part of a module created by Features. Enabling the module in the target Drupal 8 system adds the new roles in the wrong order.

It is not possible to include the weights of the anonymous; authenticated and Administrator roles in the feature / module's yaml files as this causes a conflict that prevents the module from being enabled. So the solution is to apply the weights programmatically.

**\[edit\]** I mistakenly thought that the order of the roles' columns related to an hierarchy / inheritance of permissions. Corrected by @Berdir, thanks. Nevertheless I still want to display the roles' columns in the way I choose, so I have edited this question to reflect this.

# Answer
Role weight is *only* used for some lists in the backend. It has no effect on the permissions that a user has.

The permissions or a user are *always* the sum of all permissions of all roles that he has, you can not remove permissions with roles.

All "users" either have the anonymous (when they're not a user, basically) or the authenticated user role. You can give anonymous users more permissions than authenticated users. But you can never remove any permission granted by the authenticated user role through another role.

This doesn't answer your question but considering the above, I don't think you are asking the right question. Whatever problem you are trying to solve exactly, setting role weights is not the answer ;) If this is not enough to solve your problem, then try explain the actual problem that you are trying to solve.

Edit:

Anyway, to actually set the role weight in e.g. hook\_install(), you can do this:

```
$role = \Drupal\user\entity\Role::load('anonymous');
$role->setWeight(0);
$role->save();

```

Again, keep in mind that this has *no* effect on the permissions a user has, it just affects how the roles are listed on the role and permission administration pages.
> 1 votes

---
Tags: 8, features, configuration
---


title: Migrate commerce products

text:
# Question
Title: Migrate commerce products
I am looking in to migrating our D7 Commerce site to Drupal 8 (just the product entities). I expect using the migrate module will be our best bet, but I'm not really sure where to start. Has anyone successfully set up a migration for this yet? Do I need a yml file for each field?

# Answer
A migration has the following required components:

1. A source plugin, which provides the data to the migration system from D6/7, a CSV file or whatever it is it connects to.
2. A destination plugin that stores data in Drupal 8.
3. The migration config entity that connects the two by defining the mapping and any processing/transformation of those properties/values.

The destination plugins are provided for all entity types in a generic way. So you can import data into D8 commerce products. However, what's fairly certainly still missing is source plugin that reads data from a D7 site. You can implement that yourself, it's fairly easy and there are plenty of examples for node, user, .. in core.

The migration entity is then also something that you need to define since that won't exist either. Depending on how different the data is, this is often the complicated part and needs possibly various transformations/process plugins to re-structure the data for D8.

For an example, see the migrations the we are in the process of writing for simplenews.
> 1 votes

---
Tags: commerce, 8, migrations
---


# Question
Title: Update webform field value using AJAX realtime
I have a webform created using the admin panel and would like to change one of its textfield values on click of a button. I have attempted doing this from hook\_form\_alter. I have given the wrapper name 'changeText' for this textfield from admin panel.

```
function fence_quote_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_1'){
        $form['buttons']['fence_quote']  = array(
          '#type' => 'button',
          '#value' => t('Get online estimates'),
          '#ajax' => array(
              'callback' => 'fence_quote_form_callback',
              'wrapper' => 'changeText',
          ),
        );
       $form['field_meters']['#prefix'] = '<div id="changeText">';
       $form['field_meters']['#sufix'] = '</div>';
    }
}

function fence_quote_form_callback($form, &$form_state) {
   $form_state['values']['field_meters']['und'][0]['value'] = '111';
   return $form['wrapper'];
}

```

The problem is I can't update 'meters' value using AJAX callback as it is a field created from admin panel and not from hook\_form\_alter. However if I place

```
$form['submitted']['meters']['#default_value'] = '111';

```

outside of the callback it works on page refresh. How can I do this?

---

As requested by @kamal-oberoi I'm uploading a screenshot of my full code.

# Answer
Finally I figured this out!

```
$form['submitted']['total']['#prefix'] = '<div id="changeText">';
$form['submitted']['total']['#suffix'] = '</div>';

$form['buttons']['fence_quote']  = array(
            '#type' => 'button',
            '#value' => t('Get online estimates'),
            '#ajax' => array(
              'callback' => 'fence_quote_form_callback',
              'wrapper' => 'changeText',
            ),
);

```

Then inside callback function

```
$form['submitted']['total']['#value'] = '111';
return $form['submitted']['total'];

```
> 1 votes

# Answer
add wrapper to your text field which you want to update.

```
 function fence_quote_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'webform_client_form_1'){
    $form['buttons']['fence_quote']  = array(
      '#type' => 'button',
      '#value' => t('Get online estimates'),
      '#ajax' => array(
          'callback' => 'fence_quote_form_callback',
          'wrapper' => 'changeText',
      ),
    );
    /* Please add Wrapper to text_field */
    $form['wrapper']['your_textfield_name']['#prefix'] = '<div id="changeText">';
    $form['wrapper']['your_textfield_name']['#sufix'] = '</div>';
  }

}

function fence_quote_form_callback($form, &$form_state) {
     $form_state['values']['meters']['und'][0]['value'] = '111';
     return $form['wrapper'];
 }

```
> 1 votes

---
Tags: hooks, ajax, webforms, forms
---