# Question
Title: Page Manager user/%user/edit selection rule only called when user has 'administer users' permission
I have a page manager page for user/%user/edit.

This page has a selection rule, for which I wrote a ctools access plugin.

(In my case the selection rule checks if the logged in user is the owner of an organic group, and the user being viewed is a member of that group).

The problem I have is that I get access denied.

In the debugger, the code does not even touch the ctools access plugin. It just checks if the user role has permission 'administer users'. The role doesn't have this permission, so I get access denied.

Interestingly, if I give the role the 'administer users' permission, then the code in my ctools access plugin runs!

In other words, page\_manager\_user\_edit\_page() is hit when the user has permission to get to the page anyway. What I need to happen is for page\_manager\_user\_edit\_page() to be hit always, because of course my og owners do not have global 'administer users' permission.

EDIT:

I ended up fixing the problem using hook\_menu\_alter() to call the function in the ctools access plugin.

In my case, it looks like this - I have a custom module (sites/all/modules/custom/og\_user\_admin/og\_user\_admin.module) where I call the access function.

```
 function og_user_admin_menu_alter(&$items) {
   $items['user/%user/edit']['access callback'] = 'og_user_admin_access_edit_callback';
 }

```

# Answer
> 0 votes
use context rule in page manager page.

**Home » Administration » Structure » Pages-\> selection rule-\> from drop down select role-\> add-\> assign role(selecting by check box).**

done.

---
Tags: 7, users, panels, chaos-tool-suite
---


title: Add field date to node tpl

text:
# Question
Title: Add field date to node tpl
I'm using a template that has this on the portfolio.tpl:

But I don't want to display the date of node created. So, I added in the content type portfolio a field "date\_field" (please see picture)

What I need now is to display **this field** on the tpl, replacing the "$node-\>created".

This is what I tried:

But it doesn't work.

How can I accomplish this?

# Answer
> 0 votes
Try

```
<?php print format_date($node->field_date["und"][0]["value"], 'custom','d M Y'); ?>

```

# Answer
> 0 votes
Make sure that the field is visible under 'Manage Display' for the view mode you are working with.

If you setup the field to display in a format you like you can also just do this in your template file (instead of the format\_date() part):

```
<?php print render($content['field_date'] ?>

```

In any case make sure that you also do the following before $content is rendered:

```
<?php print hide($content['field_date']) ?>

```

---
Tags: theming, entities
---


title: Local Drupal 7 user in database

text:
# Question
Title: Local Drupal 7 user in database
I want to save a user's email and username when a button is clicked. I assume I have to do this via PHP but I can find the user column at localhost/phpmyadmin. Where is the users' information being stored and which is the MySQL query to achieve that?

# Answer
You should not use a direct MySQL query to update anything.

In this case you can use user\_save(); which it is basically, load the user `object -> change` `data -> pass` it to `user_save()`; or even better user entityAPI and entity\_metadata\_wrappers

The default table where drupal saves user data is `users`, there you can find the email and username
> 0 votes

---
Tags: database
---


# Question
Title: How to eMail a file uploaded to a Webform to a sysadmin using the Rules module?
I have a webform where a user can upload a file to the webform. I would like to be able to email the file via Rules to a sysadmin. I know I can send it from Webform directly, but I am also needing to attached a FillPDF file that can only be sent via Rules.

# Answer
> 1 votes
Yes it is possible to use the Rules module for sending an eMail with an attached file. To do so, make sure you have the Mail System and Mime Mail modules installed/enabled.

The Rules Event you want to use is probably when the Webform is submitted.

Then create a rule with a Rules Action to **Send an HTML email**. Specify the eMail body content, and then the email's attachment(s). If you have multiple attachments, make sure to specify 1 file (only) per line. The tricky part you probably run into is to correctly specify the filename of the attached files. The correct way to do so is like so:

```
[node:field-file-attachments:file:path]

```

That is also what is suggested in Comment # 25 of support issue (not bug ...) #1431572.

In your case, make sure that this path refers to the webform that is submitted and contains the attached file. Using the "Webform Rules" module, you should be able to have Rules react on an event like "Webform submitted". And if you then add a Rules Condition like "entity has field" (with the field corresponding to your attached file), you should be able to "do something" with that filename of your attachement. E.g. trigger another Rules Component that uses as a parm ... the path of your attached file. With that, your Rules Component should then take care of sending the actual eMail, with the correct value of the filename for the file to be attached.

# Use Rules debugging

This question is pretty tough to answer with the limited info you provided (and without access to "your" site). Therefor I suggest you also consider 2 variations of Rules debugging, which are:

* Within the rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).
* (Temporary) enable the Devel module, so that you can (temorary) add a Rules Action like "Display a value" (in your case of the entire node/webform that's used to submit that attached file).

For way more details about these 2 variations, refer to **Rules debugging**, as explained in the answer to "How can I display the value of a variable inside a condition?".

# Answer
> 0 votes
The video tutorial Send email with attachments via Rules explains how to use **Rules** and modules **Mail System** & **Mime Mail** for sending emails with attachments

I tried it before and it works.

---
Tags: rules, webforms, emails
---


# Question
Title: How can I enable the Front Page on minimal profile?
I installed D8 using the minimal profile but it does not have or does not enable the front page view, redirecting requests to the user page. How can I enable the standard front page (with the recent posts)?

# Answer
> 0 votes
I got it. So, to document the solution:

1. Enable Views and Views UI modules
2. Either set the Front Page to the now-available `frontpage` for the traditional recent posts page

Another way (which was more suited to my intents) is to create a new content type (e.g. Static Page), create a new node of that type and set the site frontpage to that. This is useful when you are developing a theme with a custom frontpage template featuring several regions to be filled with different views.

---
Tags: 8
---


# Question
Title: jQuery dialog is duplicated when set on a form that uses AJAX
Im using jQuery dialog on my form.

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

    $('.form-container').once('form-cont', function () {
      Drupal.custom.modalLinks();
    });

    $('.my-form').once('my-form', function () {
       Drupal.custom.setModal(this);
    });

);

  Drupal.custom.modalLinks = function () {
    $('body').on('click', '.modal-link', function (e) {
      var id = $(this).data('modal-id');
      var className = $(this).data('modal-class');
      var $modal = $('.modal--' + id);

      $modal.dialog('widget').
        addClass('modal__wrap--' + className).
        addClass('modal__wrap');
      $modal.dialog('open');

      e.preventDefault();
    });
  };

Drupal.custom.setModal = function (container) {

    var $container = $(container);

    $container.find('.my-modal').
      dialog({
        autoOpen: false,
        draggable: false,
        width: 900,
        minHeight: 120,
        modal: true
    });

};

```

This is working fine when the page is first loaded. However my form has AJAX submission. When submitted the form then returns a new form which also has a dialog modal link.

If I submit the form then when it reloads with AJAX then the jQuery dialog modal is duplicated (not visible but I can see with dev tools). If I open the dialog now then 2 modals are opened.

From reading about duplicate dialogs (but not for Drupal specifically) it seems the solution is to use remove or destroy on the modal. However when I try this is always completely disables the modal, it doesn't just remove the duplicates. https://stackoverflow.com/questions/2864740/jquery-how-to-completely-remove-a-dialog-on-close

# Answer
The behavior you describe is not related to the dialog function. From your provided code you can see that dialogs are created with all elements that have the identifier ".my-modal".

So I suppose within your AJAX call the original dialog element is not replaced by another version of the dialog, but a further element having the class "my-modal" is added to your markup.

You should investigate your AJAX callback function, whether it replaces the original markup or adds elements.
> 0 votes

---
Tags: theming, ajax, javascript
---


# Question
Title: Parent term relations select list as Hierarchical select list
I would like to change the Taxonomy relation select list like as Hierarchical Select list, how can I change its nature?

Please help\]

# Answer
> 1 votes
Check "Hierarchical Select Taxonomy" sub-module in Hierarchical Select module. After installing "Hierarchical Select Taxonomy" module it will automatically convert normal select list into hierarchical select list. Please check screenshot below:

---
Tags: theming, taxonomy-terms, entities
---


# Question
Title: Drupal and Git workflow using Acquia cloud
Currently i have my central repo (origin repo) on a Bonobo Git Server.

I have followed those steps to use Acquia Cloud with a remote repository.

On my Acquia cloud repo i installed Drupal 8.

* also i already cloned my origin repo (Bonobo Git Server) locally to my computer.

Now i think the best workflow is to clone the Acquia Cloud repo locally isn’t it? With the whole Drupal 8 core and all files from the Drupal 8 installation.

So after that i can add contributed modules and themes to my local repo and commit and push them to my origin repo (Bonobo Git Server) and the Acquia Cloud repo?

1. Is this the a correct workflow? And how do i get all the Drupal 8
files from Acquia Cloud to my local repo?
2. i have read also something about *'Translating your root directory with git subtree'* in this article. Is this correct and what do i have to do exactly regarding my workflow
3. Is it advisable to use Acquia dev desktop also?

# Answer
> 1 votes
Disclaimer: I work for Acquia

This library article you linked to originates from an blog post that was written 4 years ago to answer questions about deploying from Jenkins build servers, private Github repos, etc. There's nothing specific to Acquia Cloud per se and it's rather a Git strategy you need to come up with for your development needs.

Is the Bonobo Git Server going to be the 'origin' going forward?

* If yes, then simply add the Acquia Cloud as a new remote (e.g. 'ac'). Git allows you to push to different remotes without any issue.
* If not, then you should make Acquia Cloud the 'origin' and Bonobo a regular remote (probably easier).

Since Git is decentralized, you 'own' the repo at any point in time and the main reason for keeping a remote is if you have a continuous integration system you need to pass your codebase through before you deploy code to Acquia Cloud. Another good reason is if you have a preferred Git workflow (think Github pull requests for instance) you wish to continue working with. But if you simply want to mirror your Acquia Cloud repo to (for instance) back it up, then I'd argue to just keep the Acquia Cloud repo and simplify your workflow.

The idea to keep in mind is you need only **one** checkout of your codebase. Having several remotes allows you to handle where to push to as described in the article.

---
Tags: 8, workflows, version-control, acquia-dev-desktop
---


title: Referenced Entity as an Exposed Filter

text:
# Question
Title: Referenced Entity as an Exposed Filter
I have 2 Content Types: Activity and Event.

For each of Event node, there will be an Entity Reference field which References Activity Node.

Example:

Event:

* Title: Hiking in Utah
* Activity: Hiking (Entity reference field referencing Activity node hiking)

I am Referencing Activity In an Entity Reference Field in Event Content type...

How can we use "Referenced Entity" within Views and make them available as Exposed Filters ?

In the end I want the Referenced Entities to be visible in a Dropdown field and filter results on selection.

I've had a look at EVA, but i am unable to understand if that can be used to accomplish this.

# Answer
> 15 votes
You have to actually go into your entity reference field settings on your content type and enable the following:

Render Views filters as select list. Provides a select list for Views filters on this field. This should not be used when there are over 100 entities, as it might cause an out of memory error.

This will then allow your exposed filter in views to be rendered as a select list.

# Answer
> 5 votes
There is a better way to handle this using the Views Reference Filter Module

Create your view and reference it in your view in a field.

> This module provides the views filter for entity ID or entity reference fields:
>
> * node ID
> * user ID
> * taxonomy term ID
> * term reference field (Drupal core)
> * entity reference field (Entity reference module)

# Answer
> 0 votes
You can do this natively with Views. Add a relatinoship on the entity field, and a field as a filter and set it to use the relationship.

---
Tags: entities
---


# Question
Title: How to prevent article titles to become links
I am making a website in Drupal 8. I made a new content type 'Slide' and a view called 'Presentation' that shows all slides as a blog page. I enabled the pager and set it to 1 item per page. This results in a nice slide show. See screenshot ('presentatie' is Dutch for 'presentation'):

The slides are small articles, containing text content and an image. They are shown by the Presentation view as full content, but their titles are still shown as links to the full article (slide) content. I don't want this linking, because by going to the full article, you leave the presentation page with pager for navigating through the slides. See screenshot of result on site below:

I am pretty new to Drupal and I can not find where or how to switch this off. Could anyone tell me?

# Answer
In the view **Presentation**, under **FORMAT** change **Show: Content** into **Show: Fields**.

Then under **FIELDS** add the desired fields, in my case:

* **Content: Title**
* **Content: Body**
* **Content: Image**

To get the correct formatting and css styling by my theme:

* Under **FORMAT** open **Format: Settings**, set **Row class** to "node".
* Under **FIELDS** open **Content: Title**, under **STYLE SETTINGS** check **Customize field HTML** and set **HTML element** to "H2".
* Under **FIELDS** open **Content: Body**, under **STYLE SETTINGS** check **Customize field HTML** and set **HTML element** to "DIV".
> 0 votes

# Answer
To remove link from Title, what you have to do is click on the title field in views, and there is a checkbox `Link to the Content`. To unlink this, you have to uncheck this field. I am attaching a screenshot to it :
> 1 votes

# Answer
You can't do this in views when using rendered nodes. In fact, you can't do it in the UI with just core. This is hardcoded in the node template, unfortunately.

You have to either provide a node template for that node type and view mode (see https://www.drupal.org/node/2354645) and then remove the link tag around the title, or use a module like Display Suite
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to show list & thumbnail widget in plupload?
I have installed the following modules:

FileField Sources Plupload, FileField Sources, Plupload module and added latest plupload library.

While uploading multiple files it is showing only list of files but its not showing the widget for thumbnail & list view.

So how to show that widget.

# Answer
> 0 votes
The Plupload integration module does not support the UI components of the Plupload Library. It is just as the module name suggest an integration with the library. The actual preview/thumbnails of uploaded images is handled by other modules like in your case FileField Sources Plupload and FileField Sources. You can check the module maintainers answer here. For modules that integrate with Plupload scroll down to the list on the module page.

---
Tags: files
---


# Question
Title: Features - branch 2.x results in large info files that exceed the 'info' column limit in the 'system' table
Original thread on DO (will keep it up to date)

Hello. I am currently developing a mid-to-large project. As i've done before, but using the 1.x branch, I use Features to track all structural and functional components of my site in order to be able to transfer them from my local installation, to the staging server, to the production server etc, while also having svn capabilities and tracking.

The current project consists of 45 Content Types with an average of 15 fields each. There are also ~15 vocabularies, ~10 fieldgroups, and a couple of tons of views.

The problem occurs when trying to track all this stuff with Features. It produces a large (initially, just alpha versions of the Content Types) .info file ( \> 100K) which results in the following error:

`PDOException: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'info' at row 1: UPDATE {system} SET info=:db_update_placeholder_0 WHERE
// yada yada yada serialized array of the .info file`

Which is totally natural seeing that the collumn is declared as a BLOB.

My question, is how should one go about to manage such a problem?
1) perform a `ALTER TABLE `system` CHANGE `info` `info` LONGBLOB /* or MEDIUMBLOB */ NULL DEFAULT NULL`? (Ouch)
2) Use branch 1.x instead which is less verbose in the .info file declarations?
3) Break down the project and track it in multiple features? (I'd avoid this cause it will make reverting those features a hellish job since one would depend on the other and vice versa)
4) ...?

I'd appreciate any input on the matter

# Answer
The way I see it, you have options:

**Features**

Break your Features down into smaller Features. Yes, this might make the dependencies a little more effort to manage, but a Feature containing that many content types, as well as other config does seem a little extreme.

If you do break them up, and are worried about dependencies, create a controller module to deal with them. Every time you add/break down a Feature, add it as a dependency to this controller module, then make your new Feature depend on the controller module.

This means that all other dependencies will be inherited by the Feature, but you've only had to declare it in one place. When you then disable any part of your Feature, everything will get disabled - which is the same behaviour as having one monolithic Feature.

As an added bonus, if you perform updates to your Features that require `hook_install` or `hook_update_N`, they can go in the controller module.

**Configuration Management**

If the idea of breaking down your Features *really* sends shivers down your spine, then check out Configuration Management, which can do what you want (track EVERYTHING), and if pretty easily extensible if you are happy writing your own code. This is also the route Drupal 8 is taking/has taken with configuration management, so with this method you'll be future-proofing your own knowledge.

My *personal* preference is Features, but if you are looking for something that wouldn't involve you breaking down a huge Feature into smaller ones, then Configuration Management is a solid option.
> 2 votes

# Answer
The error happens, because `info` column is not long enough to serialize data from `.info` file of the module.

The solution includes:

* breaking down your Feature module into smaller pieces (e.g. by separating components by type, or by base definition and its instances),
* increasing size of `info` column.

If you decide to increase `info` column, you've the following possibilities:

* apply simple Drupal core patch from: Increase size of info column in system table (and re-install Drupal),
* run the following one-time off SQL query:

```
ALTER TABLE `system` CHANGE `info` `info` LONGBLOB /* or MEDIUMBLOB */ NULL DEFAULT NULL

```
* more Drupal way is to change the field by using: `db_change_field`:

+ as one-time run, either from the code (e.g. as `hook_update_X`):

    ```
    db_change_field("system", "info", "info", array('type' => 'blob', "size" => "big"));

    ```

    check some field change examples in `system_update_7055()`,
    + or using `drush`:

    ```
    drush ev 'db_change_field("system", "info", "info", array('type' => 'blob', "size" => "big"));'

    ```
    + or using appropriate hook (e.g. `hook_system_info_alter`) which could not work properly for `system` table,
    + on Drupal install, some example with profile install:

    ```
    /**
     * Custom callback to recreate system table.
     *
     * This fixes Drupal issue when data is too long for column 'info'.
     * This happens for large feature modules.
     * @see: https://www.drupal.org/node/2580473
     */
    function myprofile_install_system() {
      try {
        drupal_install_system();
      } catch (PDOException $e) {
        // This catches: SQLSTATE[22001]: Data too long for column 'info'.
        // Then we alter info column in order to resize it.
        db_change_field("system", "info", "info", array('type' => 'blob', "size" => "big"));
      }
      // Rebuild, save, and return data about all currently available modules again.
      system_rebuild_module_data();
    }

    myprofile_install_system();

    ```

    however this could have some side effects.
> 0 votes

---
Tags: 7, database, features
---


# Question
Title: Create custom and unlimited Node list per user
Lets suppose I have a content type (movie) and I have all movies of Hollywood, I want let each user can create it's own lists,as example I want to create "My Top 10 movie","My 12 Hot movie","Top fincher","Top Kubric" etc,I know I can do it by `Nodequeue` module,it is good for users that know how work to Drupal Nodequeues ( they should first create a nodequeue add machine Name and its machine name should be unique(select machine name that the other users not create it before) then surf the site and find desire movies and go to nodequeue tab and add that node to it\`s nodequeue (really is it too hard for popular users)),But my problem is my user of website is popular web surfers ( not Drupal expert).

Also I can create a content type ( movie lists) with entity reference,each user can create a node of movie lists, add desire movies by auto complete field and save it.

**I want to know is there another way to create lists of nodes per user and each user could have serveral lists and can control add/remove nodes to their lists ?**

# Answer
> 3 votes
You can have a look on these modules

1. Flag
2. Flag Lists

Using Flag module users can save nodes in to their bucket and Flag lists module will make those lists as like folder structure.

---
Tags: nodes
---


title: Some images are not displayed in IE

text:
# Question
Title: Some images are not displayed in IE
Some images fails to load on IE.

```
DOM7009: Unable to decode image at URL: '[some unique url]'.

```

The URL are set to `sites/default/files/styles/image/image_name.jpg?itok=RANDTOKEN`

I can fix the error by removing the header in .htaccess

```
Header always set X-Content-Type-Options nosniff

```

But that does not seem to be a right solution. Any ideas why it behaves like this?

# Answer
I'm inclined to believe this is a MIME type (or Content Type) configuration issue on the server because the "X-Content-Type-Options nosniff" would bypass this kind of problem. That header is telling Internet Explorer to not extract MIME type info from the server response.

IE is very unforgiving these days (since IE 10 or so) with respect to the MIME type reported by the server. If your server is reporting that Jpegs are text or pngs, for example, Internet Explorer will fail to render it even if the extension is a well-known extension like "jpg."

# Adding/Correcting MIME Types in Apache

You have many different ways to fix your server's reported mime type.

## .htaccess (overrides server configuration)

If you're stuck with just editing your .htaccess file, add `AddType image/jpeg jpeg jpg jpe` to it in order to override whatever is happening with the server.

## mime.types or httpd.conf (actually fixing the server configuration)

If you have full access to your server, try to locate the "mime.types" file on your server (assuming it exists) or add the "AddType" line to your httpd.conf file if jpegs aren't defined anywhere. It's possible that the "jpg" extension or "jpeg" MIME type already exists in one of these files and is just not correctly configured.

A restart of Apache will make sure config changes are in place when you see if the problem is fixed, too.

# See also

If this problem persists, there is also another question in Stack Overflow at: https://stackoverflow.com/questions/27934411/images-failing-to-load-in-ie-with-dom-7009-error-unable-to-decode-in-console that has many alternative causes.
> 5 votes

---
Tags: media, .htaccess
---


# Question
Title: How to limit access for some special user to a single (Views) page?
I'm using Drupal 7.43 and I have to create a special user, with access to a single page (a Views page) and nothing else.

What would be the best approach for this situation?

**Note**: The view is already made (I show a custom content type made in a custom module). The website is private (the only thing an anonymous user can see is the login page).

# Answer
Not sure if it is the "best" approach, but for sure a "possible" approach for this would be to use the Rules module for this. All you'd have to do is to create a (rather basic) rule like so:

* **Rules Event**: Drupal is initializing.
* **Rules Conditions** (both must be true):

+ Check if the user's Id (`uid`) or user's name matches your "special user".
    + If the URL being accessed (= "`site:current-page:url`") does NOT match with the URL of your "single (Views) page"
* **Rules Action**: Perform a redirect to your "single (Views) page".

Done ...

Happy Rules-ing!

**Note**: Obviously, this rule only takes care of what that special user is allowed to use as URLs (while logged in). If that user does not login (yet) or logs out again, then anything an anonymous user is allowed to navigate to will also be available to this not-yet-logged-in-user. For whatever that is not allowed as an anonymous user, you must ensure that the permissions for anonymous users are set to deny such access.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to hide the "help-block" on an Image field in the Comment Form
I have added an image field to the comments.

This allows to my visitors to add images with a comment.

But I have annoying "help-block" for the image field in the form of adding a comment.

How to gracefully to remove this stuff?

# Answer
Drupal 7

I done it through the ***node\_view\_alter*** hook and my custom theme.

In the theme's **template.php** file I added the following function

```
function MyThemeName_node_view_alter(&$build) {
  if ($build['#node']->type !== 'My_Node_Type'){
    return;
  }

  // Your image field can not exist while saving comment.
  if(isset($build['comments']['comment_form']['My_Image_Field'])){
    // We can't use the unset function. Otherwise we can get something like this:
    // Notice: Undefined index: #file_upload_description in theme_file_widget_multiple() (row 863 file .../docs/modules/file/file.field.inc).
    $build['comments']['comment_form']['My_Image_Field']['und']['#file_upload_description'] = NULL;
  }
}

```

This removes the entire ***\<p class="help-block"\>...\</p\>*** element.
> 0 votes

---
Tags: comments
---


# Question
Title: How do I edit individual meta tags on a panelized page?
Setup I have: Drupal 7, Panopoly 7.x-1.30, Metatag 7.x-1.13

I've installed and enabled both the metatag and metatag\_panels modules. Perhaps I'm just not looking in the right place, but I don't see any way to add custom metatags (title and description) to an individual panelized landing page.

On an individual node page (which isn't panelized), I can click the "edit" tab, and at the bottom is a form that lets me customize the metatags for just that node. But if I click the "edit" tab on my landing page, there is no such form. Clicking the "customize this page" button which invokes the panelizer doesn't seem to offer any way to edit the metatags, either.

I've read the documentation and searched the drupal.org forums, but nothing has made a solution clear to me.

# Answer
Apparently it has nothing to do with the panels; the Metatag plugin just doesn't support landing pages. Converting the needed landing pages to customized content pages solved my problem.
> 0 votes

---
Tags: 7, panels, meta-tags, distributions
---


# Question
Title: Naming conventions for fields machine name in Drupal
There is a naming convention for the fields machine name such as:

```
entity_name_field_name

```

for not shared fields

or

```
field_name

```

for shared fields.

When I go to start a project, what should be the naming convention I must use on it?

# Answer
> 2 votes
Unless your entity is resuable (like say apart of a Feature) I typically name my fields as "field\_PROJECTNAME\_SOMETHING\_DESCRIPTIVE" that fits within the 25-ish character limit for field names.

If I put the content type into a Feature then yes I use a consist naming pattern for all fields. If I have a Feature for a content type called DIET (short for Digital Identity) I can make a field called `field_diet_presidential_number`.

For example I'm working on a project I call internally the "Presidency Project". I may name my fields with a prefix of `prez`. This is true for anything that requires a `machine_name`. This way when making Features or exporting code I can at a glance see some piece of configuration that is *project specific* and I know to export it somehow.

Machine names should at the least be globally distinguisable from Core fields and other configuration values (such as system variables, and Pattern machine names, Rule machine names, etc).

# Answer
> 4 votes
TL;DR Always use a short succinct but entity agnostic machine name for your fields because requirements will change.

I would never put the entity name in the field name. While today you might think that a field will only ever be used on a node. Requirements change over time. Today's assumptions will bite you tomorrow.

For example you might have a *"Hero image"* field and decide to use "node\_hero\_image" (or worse "node\_blog\_hero\_image") because it is only used for nodes. Later someone decides that they want to use hero images on another entity type - say taxonomy terms to create nice "category landing pages". You have hard coded the entity type into the field. You have 2 choices, either keep the poorly named field or create a new one - both options are less than idea an increase the technical debt in your project.

If you had've used "hero" as the machine name for your field it would remain flexible. The purpose of the field is clear to anyone who sees it in the UI. You don't need "\_image" in the name either as most places in the UI will tell you it is an image field.

# Answer
> 2 votes
Have a look at the (illuminating) article "Relativity Model for Drupal", especially the related page about "Wrapping Information Architecture and Documentation". Here is a quote from it:

> To create an Event content type in Drupal is a simple task. But there's a nuance to that task that is overlooked very often. That nuance is the machine name. But why is the machine name of a content type such an important step?
>
> * It gives the content type an explicit name of your choosing and allows database indexing to act on that machine name while being queried.
> * All fields contained within that content type will share the same machine name before the field name. This allows the Views module to clearly gather field data in a very defined manner using the indexed machine name.
> * Fields that are entity references out to other content types also begin with the same machine name followed by their own machine name. This allows simple and visual identification for origination and destination of data relationship.

It also contains an interesting example of what seems to be a great naming convention.

# Answer
> 1 votes
There is no generally accepted convention as far as I am aware, but clearly it makes very good sense to develop some internal standards within your project or company.

The *field\_* prefix is, in my opinion, not necessary nor useful. It's a legacy from Drupal 6's CCK module, which was the forerunner of Drupal 7's *field* subsystem. Although that prefix is included by default when creating fields via the standard core UI, that behaviour can be changed, for example with this module: Remove field name prefix

It would probably make sense to use a short initial prefix that you can expect to be unique, to help avoid possible conflicts with field ids or database table names used by other modules. I often use a prefix of *ng\_* which is short for my own domain name and so *hopefully* won't be used by anybody else. Of course, this does not *guarantee* that there will be no conflicts, but it helps.

If you are developing a Drupal module or distribution for general use, then using a short initial prefix representing the name of that module or distribution would make sense, again to help avoid name conflicts with other modules. This is very common practice for naming PHP functions within module and theme code, where the full project name of the module or theme is usually used as a prefix.

# Answer
> 1 votes
I use one of those options:

1. field\_type\_function#

> field\_img\_heroimage1
>
> field\_img\_figure1
>
> field\_img\_icon1
>
> field\_longtext\_details1
>
> field\_longtext\_details\_exp1
>
> field\_longtext\_details2
>
> ...

2. field\_type#

> field\_img1
>
> field\_img2
>
> field\_img3
>
> field\_longtext1
>
> field\_longtext2
>
> field\_longtext3
>
> ...

Also you could add the project name before the type: field\_projectname\_type# . I don't recommend to put the entity name in the field name like skwashd said.

---
Tags: entities
---


# Question
Title: How to update a record with drupal_write_record?
I do not understand how to update a record with drupal\_write\_record.

I want to update column "vid," in table "node," with the value `$value`, where "nid" equals `$key`.

This is what I have, and it doesn't look right, nor does it work. I can't find any examples.

```
$table = 'node';
$record = new stdClass();
$record->vid = $value;
drupal_write_record($table, $record, array('nid' => $key));

```

To be clear: I want to insert `$value` into column "vid" where the value `$key` exists in column "nid"; this is all happening in table node.

# Answer
`drupal_write_record` updates an entire record, not a single column. With `drupal_write_record` you could do this.

```
$node = node_load($nid);
$node->vid = $vid;
drupal_write_record('node', $node, 'nid');

```

But dealing with nodes, you can use `node_save` instead, which also handles saving fields and other data. Using `node_save` is recommended way of saving alterations to a node, since it also deals with revisions issues along with fields, hook notification ect. It's simple to use:

```
$node = node_load($nid);
$node->vid = $vid;
node_save($node);

```

If you want to update a single value in a datebase, you can use SQL (`db_query`) or the `db_update` function which is two ways of running SQL on your database. The `db_update` utilizes the Drupal query builder, and will work on any database backend the Drupal supports (now and in the furture):

```
db_query("UPDATE {node} SET vid = :vid WHERE nid = :nid;",
  array(':nid' => $nid, ':vid' => $vid)
);

$num_updated = db_update('node')
  ->fields(array(
    'vid' => $vid,
  ))
  ->condition('nid $nid)
  ->execute();

```

`drupal_write_record` will itself use `db_update`, a snippet of the code looks like this:

```
$query = db_update($table)->fields($fields);
  foreach ($primary_keys as $key) {
    $query->condition($key, $object->$key);
  }

```

Which basicly creates an update query, updating all of the fields, and using all of the values set in primary key as the condition.
> 7 votes

# Answer
According to drupal\_write\_record the operation was an `UPDATE` or an `INSERT` you need to know whether the record existed or not before committing the transaction. This is not what drupal\_write\_record() does. This function just checks it's arguments and issues an update or an insert accordingly. So there is **really no way** to tell if the function did an `INSERT` or an `UPDATE`.

The solution is using db\_merge() query, it is a relatively new SQL ANSI standard that does exactly what I needed (and in the case of MySQL does it in an atomic transaction).

```
$return_value = db_merge('mytable')
            ->key(array('id' => $key))
            ->fields($fields)
            ->updateFields(array(
                'updatedon' => $now,
            ))
            ->execute();

```

The return value is an integer returning 1 for inserts and 2 for updates.
> 0 votes

---
Tags: nodes
---


# Question
Title: How can I find out the machine names of user variables?
I'm creating a custom user profile page and I know how to print certain items attached to the user like

```
$user_profile['user_picture']

```

but I don't know the names of any of the other fields. Is there a way that I can view a list of user profile field machine names?

# Answer
All of the user variables are located in `configuration->People->Account Settings->Manage Fields`. So simply look at them over there.
> 0 votes

---
Tags: theming, users
---


# Question
Title: How to update a Drupal 6 website to latest release with drush?
I want to update my Drupal 6 website (version 6.36) to the latest realease (6.38).

When i'm using the shell-command "drush update drupal", i'm getting following result:

```
Drupal                     6.35      6.35      Installed version not supported

```

How can i do an update to the latest release with drush?

# Answer
> 2 votes
As near as I can tell, drupal.org just removed all of the release xml for all contrib modules, and every version of Drupal 6.x core except for the latest release.

See the Drupal 6.x release xml for reference; all versions except 6.38 have been removed. Ah, look, the Views 6.x release xml contains content again! Just a short while ago, it was gone.

Without the full release XML for Drupal 6 core, Drush cannot your existing versions; if it has no information about the current release, it gives up. It is possible that this situation was accidental, and is being updated (c.f. the views release XML, which was recently restored). Maybe this will start working again later.

# Answer
> 1 votes
Currently you can't, but I think Drush will be updated to handle this situation. I suggest that you follow the relevant issue on GitHub. (There is already an ugly work-around for older versions of Drush.)

---
Tags: 6, drush, updating
---


# Question
Title: How can I use Drush 8 command to enable the site set up bin the Acquia DevDesktop to online mode?
I forgot to put the site back online when I'd finished updating the site. How can I use Drush command to enable the site to online mode?

# Answer
> 0 votes
You are talking about maintenance mode. If you had use the correct term, you would have been pointed to for example the following question which has the info you need:

```
drush sset system.maintenance_mode 0

```

---
Tags: drush
---


# Question
Title: How to use the Webform Serial in a Webform Rule?
Is there a way to use the Webform Serial (not the SID) be used in a webform rule?

I've tried the following with no success:

```
[data:serial]
[webform:serial]
[node:serial]

```

I do have Webform Rules & Webform Tokens installed.

# Answer
> 1 votes
Have a look at comment #2 in issue #2572067, which states this:

> The correct token for that is `[submission:serial]`, but some module is going to have to make that token available to the rules module. Webform itself doesn't do that. I haven't tried it, but the Webform Rules modules would be the place to start.
>
> The serial number is a relatively new feature, but I would have though it would work without an update to the Webform Rules module. If not, you might file an issue in that module's queue.

---
Tags: rules, webforms
---


title: Drush Permissions Issue

text:
# Question
Title: Drush Permissions Issue
With the help of the support team of my dedicated server, I have setup Drush globally on my server. Now I can run multiple Drush versions like drush6 status, drush7 status, drush8 status with a little tweak in my .bashrc file

One problem I am unable to resolve is that when I download or update drupal it starts giving 500 Internal server error.

My Support Team Told me

When you use Drush to download Drupal, it gives files 664 permission. The PHP handler in the server is suPHP, which requires 644 file permission, so you need to run the file permission fixing script for the account after using Drush install/update commands.

Is there any way we can instruct Drush to download the files with 644 permission?

# Answer
Drush does not handle platform-specific issues such as file permissions. To get rid of group write, just run `chmod -R g-w /path/to/drupal`. If you wanted to do this automatically, you could make a post-update hook for the pm-updatecode command. See the example Drush pm\_update hook file for one example post hook function.

In your case, you would want something like this:

```
function drush_myhook_post_pm_updatecode() {
  passthru('chmod -R g-w .');
}

```

Save that in a file named `myhook.drush.inc`, and put it somewhere that Drush will find it, such as DRUPAL\_ROOT/drush. Then run `drush cc drush`, and your hook should run the next time you call `drush pm-update`.
> 1 votes

# Answer
This isn't a Drush issue. It's about the configuration of your shell. The file creation mode is controlled by the umask. The correct solution is to set umask to 0022 (022) in the start up files of your shell. Or better, ask your hoster to add it to the global startup files which they already should have done if suPHP requires it ;-)
> 0 votes

---
Tags: drush
---


# Question
Title: How do I get Views content items in "my language" but fall back to "default" if the content isn't translated?
This is probably very easy but endless searching has proved fruitless - there's lots of UI changes between the D7 and D8 versions of these modules it seems.

What I want to do is create a blog in two languages. The default language is English. Mostly, the author will be translating the articles to Italian. However, I would like to create the blog view such that:

1. only one translation shows in the list, per node
2. if viewing the site in italian but there is no translation of a specific list item to italian, the english version shows (fall back to default language)
3. if he's only written an italian version, show that anyway instead of the non-existent english one

The options in views are similar looking to everywhere else, but in those other places this isn't really an issue. In standard nodes, the fallback kicks in automatically. Any ideas of how to configure this?

# Answer
I think your requirements can be restructured into the following:

1. Show all content once.
2. Show the content in the current language, fall back to the other.

Then it becomes pretty easy:

1. Add the "Default Translation" filter to a view. That basically ensures that all your nodes are shown once because each node can only have one default translation.
2. Select "Interface text language selected for page" for "Rendering" language. That will attempt to display the site in the current language and fall back if that's not available. (Interface text sounds a bit misleading, but unless you explicitly enabled separate content language negotiation, that's the same as the content language).
> 41 votes

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


# Question
Title: Can you change the list builder class used by an entity?
There's an entity created by another module and I'd like to change some of the fields used on a listing page. Currently that page is using the entity's list builder class. Is there a way I can define a new list builder class, make my changes, and use that for this entity? I have tracked this down to where D8 get's entity definition and loads the list builder class from that. I can't find a way to alter the definitions or another way to inject a different class here.

In more specific terms, I have created an entity with ECK and want to override the functionality around `EckEntityListBuilder`.

# Answer
> 22 votes
You want something like this:

```
<?php

/**
 * Implements hook_entity_type_alter().
 */
function MY_MODULE_entity_type_alter(array &$entity_types) {
  /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
  $entity_types['node']->setListBuilderClass('Drupal\MY_MODULE\NewListBuilder');
}

```

---
Tags: 8, entities
---


# Question
Title: Theme Organic Group Entity Reference on user profile
On my site, users join groups via an Entity Reference field using the "Check boxes/radio buttons" widget.

The widget default is to display only the group Title. Like so (where the list bullet is a checkbox):

* Group1Name
* Group2Name
* Group3Name

The group content type has an additional field called "description" that I'd like to include on this display. Like so:

* Group1Name: Group1Description
* Group2Name: Group2Description
* Group3Name: Group3Description

Is there a way to theme either the checkbox widget or something in Organic Groups to display this additional field?

# Answer
> 1 votes
You need to create an entity reference view and use it for your og\_groups\_ref field. In Views where you click Add, you will see entity reference view next to block, page etc.

Create the view to show the groups and the add fields for title and description. Place description above title and exclude it from display.

Rewrite the title in field settings to something like \[title\] -\[description\]. The replacement patterns are in the view field settings.

Go back to your groups audience field settings (main settings, not widget) and choose entity reference view instead of organic groups or simple. Use the view you created.

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


# Question
Title: How to hide a DIV if ther's no value in that Content in a node--customtpl.tpl.php file
How can I hide a DIV if ther's no value in that Content in a node--customtpl.tpl.php file? I have used a code something like this, but if hides everything weather it has data or not. Can anyone help me with this code?

I want to hide this "special-offer" div if there's no value in that field in drupal (this\_is\_a\_drupal\_field).

```
<?php
if ($content['this_is_a_drupal_field'])
  {
  print "<div class='special-offer'>";
  print render($content['this_is_a_drupal_field']);
  print "</div>";
  }
?>

<?php if(empty($content['this_is_a_drupal_field'])){ ?>

```

# Answer
> 0 votes
Your if statement needs a condition, ex: 'greater than' `>` 'less than' `<` 'equal to' `==` or 'not equal to' `!=`

The special **NULL** value represents a variable with no value.

So try:

```
<?php if ($content['this_is_a_drupal_field'] != NULL): ?>
  <div class='special-offer'>
    <?php print render($content['this_is_a_drupal_field']); ?>
  </div>
<?php endif; ?>

```

So basically we're saying if `$content['this_is_a_drupal_field']` is not equal to empty print...

---
Tags: theming
---


# Question
Title: How to enable contextual links for views content panes?
If I do not enable module "Views content panes", I see all block generated by Views in "Miscellaneous" category. When I insert such block in my panels, contextual links are displayed well fore each block.

But If I enable "Views content panes" module, all views are moved to "Views" category and disappear from "Miscellaneous" category. I get some additional options, but I miss contextual links: no contextual links rendered for views.

How to output contextual links for views inserted with "Views content panes"?

# Answer
For contextual links to show, you need to create a content pane in your view. +Add \> Content Pane. There will be a new panels category automatically created called "View Panes".
> 1 votes

---
Tags: views, panels, chaos-tool-suite
---


# Question
Title: How can I check the user status of node author in Rules condition?
I set `Content is going to be saved` for `Rules Event`.

And then the following code in `Execute custom PHP code` for `Rules condition`. But it seems to return always TRUE no matter if the user account of node author is Active or Blocked.

```
return $author->status = 0;

```

How can I check the user status of node author in Rules condition? I would like the condition which returns TRUE when the the user status of node author is Blocked.

# Answer
You need to use the double equation sign. What your code does right now, is that it assigns the value 0 to `$author->status`.

Here's updated code:

```
return $author->status == 0;

```
> 1 votes

---
Tags: 6, users, rules
---


# Question
Title: Where should I put a modified version of l() function?
I want to customize `l()` function, which is part of Drupal 7 core and it is located in the common.inc file.

Where should I put such a function?

Modifying `l()` function or putting a new function in the `common.inc` would be considered hacking the core.

# Answer
You should put it in your custom module. I think it's anyway good development practice to have a custom module in every project you develop.

What I do usually, is that I create `MY_MODULE.helpers.inc` file, and include it at the top of the `.module` file.

Here's an example of `.module` file:

```
// Get helper functions.
require_once dirname(__FILE__) . '/MY_MODULE.helpers.inc';

```

This way, if your module is enabled, the function will become available to other modules or your theme, and your `.module` file is cleaner because it doesn't include the helper functions.

You can see my Drupal 7 Boilerplate and specifically the `boilerplate.helpers.inc` file on Github.
> 2 votes

---
Tags: 7
---


# Question
Title: How to create a "wall" with Drupal Commons?
Does anyone know a way to show a sort of "wall" for any users, under the profile sections, like facebook with drupal commons? I think i'll have to add a block under the bio section right? My goal is that when a user will go to the profile of a trusted contact (friend) he/she can see all it's activities under the bio section. However, if the user is not marked as trusted contact (friend) the activity will not be published.

I've found this answer but it's a little incomprehensible: https://forums.acquia.com/acquia-products-and-services/drupal-commons/drupal-commons-wall-facebook-wall ...

# Answer
# Flag

To implement "a trusted contact"? you could use the Flag module, whereas a user can "flag" another user as "***I trust that user***".

# Views

Create some view using the Views module, in the format of a block, whereas you use the userid as a filter for such view. The actual content of such view should match with the "activities" you have in mind.

# Rules block visibility

Use the Rules block visibility module to control the visibility of such block. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to creating a Rules Component to verify if the "current user" has flagged the user of the profile being viewed as a trusted contact. As per the great integration of the Flag module with Rules, that should really be like a "Getting started with Rules" exercise.
> 0 votes

---
Tags: blocks, 7
---


title: Pathologic relative path on multisite

text:
# Question
Title: Pathologic relative path on multisite
Old multisite subsite relative path to image (in block/Full HTML with CKeditor and on localhost/XAMPP):

```
/sites/site1.localhost/files/image.png

```

New multisite path (what I'm trying to achieve):

```
/sites/site2.localhost/files/image.png

```

So, in Full HTML input settings for Pathologic, we select the 3rd option Relative path and add lines:

```
/sites/site1.localhost/
/sites/site2.localhost/

```

And nothing happpens, it just strips the /sites/site1.localhost/ from path and now the path to image is just:

```
/files/image.png

```

How do I make it the `/sites/site2.localhost/`?

# Answer
Solved running SQL query in phpMyAdmin

```
UPDATE field_data_body  SET body_value = REPLACE(body_value,'src="/olddirectory','src="/newdirectory');

```

Source article: http://www.coolestguidesontheplanet.com/downtown/changing-image-paths-drupal-subdirectory-installation
> 0 votes

---
Tags: 7, uri, input-formats
---


# Question
Title: How can I avoid saved configuration settings to be exported?
I have a custom module and I added a form that allows the administrator to save some settings. Now, when I export the configuration (`drush cex`), I notice that these settings are being exported to a file (mymodule.settings.yml in the config directory).

I don't want to export these settings. How can I avoid it?

# Answer
> 4 votes
If you don't want to export configuration you should use State API. From documentation:

> * It is specific to an individual environment.
> * **You will never want to deploy it between environments.**
> * You can reset a system, losing all state. Its configuration remains.

---
Tags: 8, configuration
---


# Question
Title: How can I change the way list appears when I click a tag?
When I select a tag link, result shows the title and content. How can I change the list of related article appears only with title and not include any content please?

# Answer
> 3 votes
There are a few ways to achieve that.

First and the easiest way is to go to the display settings of the content type and hide all fields in **teaser** view mode.

Second way is to use **Views** module, which ships with a taxonomy term view. You need to go to the views administration, `structure/views`, and enable this view. Or better, clone this view and enable the cloned one. This way you have more options then only to show the titles. However, it can be an overkill if you only need to show titles.

# Answer
> 2 votes
tvi module should meet your needs.

> The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabulary.

The module's documentation (setup, configuration etc) is so well written, extensive and detailed that I found no reason to repeat it here.

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


# Question
Title: How to migrate files into a field with unlimited values (D6 -> D7)
I am currently migrating a D6 site into D7 and so far everything has gone smoothly. I use migrate and migrate\_d2d.

But now I am stuck :-(. I have an image field with unlimited values (a slideshow) and into that field I need to import images from the corresponding slideshow in the legacy site. My problem is that after import only one image is imported (the last one in the slideshow). How do I make every picture end up in its own subfield? In my prepareRow() I am trying to use the loop below. I fetch the field ID from $row-\>fields\_productimages\[#\] (index \> 2 are field ID's that belong to the slideshow). I then get the file path from the legacy database and use that path to import the image. But as I said, only the last image is attached to my field. There are no error messages. Any help is appreciated.

```
$i = 2;
if($row->field_productimages[$i] != ''){
    while($row->field_productimages[$i] != ''){
        $fid = $row->field_productimages[$i];
        $filepath = Database::getConnection($target='default', $key='legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',array(':fid' => $fid))->fetchAssoc();
        $this->addFieldMapping('field_bildspel_instrument')->defaultValue($filepath);
        $this->addFieldMapping('source_dir')->defaultValue('http://www.mysite.se/');
        $this->addFieldMapping('destination_dir')->defaultValue('public://instrument/bildspel');
        $this->addFieldMapping('field_bildspel_instrument:file_replace')->defaultValue('FILE_EXISTS_REPLACE');
        $this->addFieldMapping('field_bildspel_instrument:file_class')->defaultValue('MigrateFileUri');
        $this->addFieldMapping('field_bildspel_instrument:title', 'field_sensorimage:title');
        $this->addFieldMapping('field_bildspel_instrument:preserve_files')->defaultValue(1);
        $this->addFieldMapping('field_bildspel_instrument:urlencode')->defaultValue(1);
        $i++;
    }
}

```

# Answer
> 0 votes
Finally figured it out. The image field with unlimited values needs a default value with file paths presented as an array. As the array in $filepath was 2 dimensional (an array in an array), I needed two foreach loops to get down to the simple array needed. This is now a working example, I publish it here in case somebody have the same question:

```
$i = 2;
$filepath = array();
if($row->field_productimages[$i] != ''){
    while($row->field_productimages[$i] != ''){
        $fid = $row->field_productimages[$i];
        $filepath[] = Database::getConnection($target='default', $key='legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',
        array(':fid' => $fid))->fetchAssoc();
        $i++;
    }
    foreach ($filepath as $value1){
        foreach ($value1 as $value){
          $files[] = $value;
        }
    }
    $this->addFieldMapping('field_bildspel_instrument')->defaultValue($files);
    $this->addFieldMapping('field_bildspel_instrument:source_dir')->defaultValue('http://www.myoldsite.se/');
    $this->addFieldMapping('destination_dir')->defaultValue('public://product/slideshow');
    $this->addFieldMapping('field_bildspel_instrument:file_replace')->defaultValue('FILE_EXISTS_REUSE');
    $this->addFieldMapping('field_bildspel_instrument:file_class')->defaultValue('MigrateFileUri');
    $this->addFieldMapping('field_bildspel_instrument:title', 'field_productimages:title');
    $this->addFieldMapping('field_bildspel_instrument:preserve_files')->defaultValue(1);
    $this->addFieldMapping('field_bildspel_instrument:urlencode')->defaultValue(1);
}

```

---
Tags: migrations
---


# Question
Title: How to send an SMS message when a Webform is submitted?
I am trying to have an SMS message sent when a form is submitted. The form is a quote request and I would like to send a simple message to my phone to alert me.

I have installed the SMS Framework module and the Clickatell module. I have set up an account on Clickatell and have the necessary username, password, and api id.

I can send a message by pasting the url in my browser using the example on the Clickatell site but I don't know how to send a message when the quote request form is submitted.

# Answer
> 4 votes
Using the "Webform Rules" module, you should be able to have the Rules module react on an event like "Webform submitted".

So create a custom rule using this Rules Event, and then add a Rules Action to send an SMS message, similar to what is shown in the video tutorial "How to send SMS messages" (starting from around 5:25).

# Answer
> 2 votes
As I understand, you need to make a call to Clickatell API in order to send a message, and you're asking how to do this in the background.

You need to use the `drupal_http_request()` function. Here's an example:

```
$response = drupal_http_request(YOUR_API_ENDPOINT, $options);
if ($response->code == 200) {
  // Everything was OK.
}
else {
  // An error occurred. You can log this, or process further.
}

```

Hope this helps.

---
Tags: 7, webforms
---


# Question
Title: Views Image Field - Field Collection Show Only one Image
I have a view that displays an image from a list of image field collections. However, it is showing all the images from the collection. I only want the first image to be shown and hide the others.

# Answer
The Views module provides the option to select -in the field's settings- how many items you want to render for multi value fields. See the image below:
> 1 votes

---
Tags: views, entities, media
---


title: Can't attach css to table element

text:
# Question
Title: Can't attach css to table element
I have a D8 module that uses the ‘table’ element to which I want to apply a css file residing in the modules-root folder. The module runs well without the css. However when I ‘attached ’ the css I get a PHP error: “LogicException: You are not allowed to use css in #attached.”

The idea is to add classes (e.g. siteOK, ...) to each row of the table as it's built.

So far, all the methods I’ve examined for doing this shows the syntax I've used. Any ideas as to what I’m doing wrong?

../drupal8/modules/Custom/check\_website/check\_website.css:

```
    .siteOK{
    background-color:#fcfcfc;
}

```

../drupal8/modules/Custom/check\_website/src/Form/CheckWebsiteForm.php:

```
<?php

    /**
     * @file
     * Contains \Drupal\check_website\Form\CheckWebsiteForm.
     */
    namespace Drupal\check_website\Form;

    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    use PDO;

    require 'check_website.config';

    /**
     * Implements an example form.
     */

class CheckWebsiteForm extends FormBase
{

    /**
     * {@inheritdoc}
     */
    public function getFormId()
    {
        $headers = get_headers('http://cto.vermont.gov/');
        return 'check_website';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state)
    {

        $spawnedSites = $this->_getSiteList(); //

        $form['spawnedSites'] = array(
          '#type' => 'table',
          '#caption' => 'Spawned Website Table',
          '#header' => array('Name', 'Title', 'Created By', 'Site ID', 'Palette'),
        );

        $form['spawnedSites']['#attached']['css'][] = array(
          drupal_get_path('module', 'check_website') . '/check_website.css',
        );

        foreach ($spawnedSites as $value)
        {
            $rowColor = $this->_getSiteStatus($value['name']);

            // the ROW level of the table
            $form['spawnedSites'][$value['siteid']]['#attributes']['class'][] = $rowColor;

            $form['spawnedSites'][$value['siteid']]['name'] = array(
              '#type' => 'textfield',
              '#title' => t('Name'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['name'],
            );
            $form['spawnedSites'][$value['siteid']]['title'] = array(
              '#type' => 'textfield',
              '#title' => t('Title'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['title'],
            );
            $form['spawnedSites'][$value['siteid']]['createdby'] = array(
              '#type' => 'textfield',
              '#title' => t('Created By'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['createdby'],
            );
            $form['spawnedSites'][$value['siteid']]['siteID'] = array(
              '#type' => 'textfield',
              '#title' => t('Site ID'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['siteid'],
            );
            $form['spawnedSites'][$value['siteid']]['palette'] = array(
              '#type' => 'textfield',
              '#title' => t('Palette'),
              '#title_display' => 'invisible',
              '#size' => 10,
              '#default_value' => $value['palette'],
            );
            $a = 1;
        }

        $form['url'] = array(
          '#type' => 'url',
          '#title' => t('URL:'),
          '#size' => 100,
        );

        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
          '#type' => 'submit',
          '#value' => $this->t('Check'),
          '#button_type' => 'primary',
        );

// /////////////////////////////////////////////////////////////////////////////
        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state)
    {
        $a = 1;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $urlString = $form_state->getValue('url');
        $headers = get_headers($urlString);

        if (!$headers) {
            drupal_set_message($this->t('No Server at this URL'));
        }
        else {
            $headers0Tokens = explode(" ", $headers[0]);
            switch ($headers0Tokens[1])
            {
                case '200':
                    drupal_set_message($this->t('Server and page found'));
                    break;
                case '204':
                    drupal_set_message($this->t('Server is there but page has no content'));
                    break;
                case '404':
                    drupal_set_message($this->t('Server is there but page not found'));
                    break;
                case '403':
                    drupal_set_message($this->t('Server is there but page forbidden'));
                    break;
            }
        }
    }

    function _getSiteList()
    {
        $pdo = new PDO(sprintf('mysql:host=%s;dbname=%s', COMMANDER_DBHOST, COMMANDER_DB), COMMANDER_DBUSER, COMMANDER_DBPASS);

        $sth = $pdo->prepare('SELECT name, title, createdby, siteid, palette FROM site ORDER BY siteid');
        $site = new \stdClass();
        $sth->bindColumn(1, $site->name);
        $sth->bindColumn(2, $site->title);
        $sth->bindColumn(3, $site->createdby);
        $sth->bindColumn(5, $site->siteid);
        $sth->bindColumn(16, $site->palette);
        $sth->execute();

        $ret = array();

        $ret = $sth->fetchAll(PDO::FETCH_ASSOC);

        return $ret;
    }

    function _getSiteStatus($name)
    {
        $urlString = 'http://' . $name . '.vermont.gov';
        $headers = get_headers($urlString);

        if (!$headers) {
            $rowColor = 'noSerever';
        }
        else {
            $headers0Tokens = explode(" ", $headers[0]);
            switch ($headers0Tokens[1])
            {
                case '200':
                    $rowColor = 'siteOK';
                    break;
                case '204':
                    $rowColor = 'siteNoContent';
                    break;
                case '404':
                    $rowColor = 'siteNoPage';
                    break;
                case '403':
                    $rowColor = 'siteForbidden';
                    break;
            }
        }
        return $rowColor;
    }

}

```

# Answer
In Drupal 8, assets such as CSS and JS are not added directly anymore, but via an asset library.

See the relevant documentation here:

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme
> 3 votes

---
Tags: 8, theming
---


# Question
Title: With the core testing, how do I set a database variable?
I am trying to establish a test suite for my project using the core testing module. But I can't get past such a trivial thing as setting a database variable.

A lot of tutorials on the web tell you to use `$this->drupalVariableSet` \- e.g.:

```
public function setUp() {
  parent::setUp(array('my_module'));
  $this->drupalVariableSet('my_module_var', 42);
}

```

This throws "Call to undefined method Mymoduletest::drupalVariableSet()" - so it looks like it has been depreciated at some point.

Using `variable_set`, e.g.:

```
public function setUp() {
  parent::setUp(array('my_module'));
  variable_set('my_module_var', 42);
}

```

does not produce an error, but the setting has no effect (i.e. the variable has its default value when it is used in one of the my test cases.

Any help will be appreciated.

# Answer
`drupalVariableSet()` has been removed as per Remove drupalVariableSet.

`variable_set()` is the function you should use. In fact, `DrupalWebTestCase::setUp()` uses it for some persistent variables used from Drupal core, right after the call to `drupal_install_system()`.

```
  // Perform the actual Drupal installation.
  include_once DRUPAL_ROOT . '/includes/install.inc';
  drupal_install_system();

  $this->preloadRegistry();

  // Set path variables.
  variable_set('file_public_path', $this->public_files_directory);
  variable_set('file_private_path', $this->private_files_directory);
  variable_set('file_temporary_path', $this->temp_files_directory);

  // Set the 'simpletest_parent_profile' variable to add the parent profile's
  // search path to the child site's search paths.
  // @see drupal_system_listing()
  // @todo This may need to be primed like 'install_profile' above.
  variable_set('simpletest_parent_profile', $this->originalProfile);

```

As long as the following conditions are met, using `variable_set()` should work as expected.

* The test class derives from `DrupalWebTestCase` and not from `DrupalTestCase`
* `variable_set()` is called after `parent::setUp()`
* The name of the persistent variable used in `variable_set()` doesn't contain typos
> 2 votes

---
Tags: 7, testing
---


# Question
Title: How to not have an image in a facebook share
I have a problem

Although many have the problem with not have the right image, I'm trying to have no image at all. I have ads on the page that get chosen because the content type has no image.

I have tried to do put in a "\[none\]", (then a random field from another content type), in the image field under open graph in meta tags, it's still not working.

I simply want to share the text itself without the image of the ads, and if you have a better solution, please mention.

Thanks!

# Answer
> 1 votes
First of all try investigating URL you are sharing on Facebook Debugger: https://developers.facebook.com/tools/debug/

If you are not providing `og:image` meta tag, Facebook will try to get the best matching one, I guess those AD images in your case.

Unfortunately there is no way you could not provide an image, you could try with empty `og:image` meta tag, but I don't think this would work.

It would be best if you provide an image anyway. Here are some hints: https://developers.facebook.com/docs/sharing/webmasters#images

---
Tags: media, meta-tags
---


# Question
Title: How to manage exported block configuration that site users can override?
Using core config management, we export configuration from developer's site instances and put than under version control. Eventually, this configuration is merged and ends up in production, where we import it thru either Drush or the UI. Trouble is, site owners have permissions to update block configuration, and this overrides our exported configuration.

What is the intended workflow in this case?

Put more generically: how to manage exported configuration that can be overriden by users (with a core CM workflow)?

# Answer
> 0 votes
> Trouble is, site owners have permissions to update block configuration, and this overrides our exported configuration.

I thinks it's a bad idea to give site owner to change something in site-configuration. Site owner should take care only about site's content and should have permission to change site's configuration(block's configuration it's a site configuration).

# Answer
> 0 votes
My team will be altering our deployment process to ensure any production changes are incorporated into the exported configuration before final deployment.

* Setup local environment to match code on production
* Export configuration from production & overwrite local configuration
* Stash or commit any changes
* Merge with latest development code
* Deploy code to production

Ideally, if we're aware of any in-production changes we will export and merge them during development as soon as possible, rather than waiting to do one big merge before deployment.

---
Tags: 8, configuration, deployment
---


# Question
Title: How to create multi select within select box in views expose filter in Drupal?
I have created a view with exposed filter. It's working correct. But I need to use select box in exposed filter with multiselect.

# Answer
User Better Exposed Filter, this module will give exact thing.

ok then in Exposed form style -\> BEF Settings -\>
> 1 votes

# Answer
I assume you have multiple values set in your exposed filter.. Chosen is quite a nice UI for select lists. Not a checkbox but it has a search and shift click.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Compare specific fields of two nodes side-by-side
I have a content type consisting of 15 large text areas fields.

I would like to be able to select specific fields (or maybe just one for start) and **review the content of two nodes side-by-side** with the selected fields aligned horizontally (in a table maybe). Also these fields should be available for inline edit using the Editable Fields module, so I need this to be done inside a view which would allow me to use the `editable` field formatter.

I've checked the Node Compare module which is great, but it doesn't allow the user to check which fields he'd like to review side-by-side. I need to be able to filter those by exposed filters or something. Furthermore Node Compare uses a custom view that doesn't allow me to use the `editable` formatter.

Any ideas how could I achieve this?

# Answer
> 1 votes
Install and configure Node Compare module.

Some more details about this module (from its project page):

> The module to provide node comparison functionality on user request. It compares the values of the fields of nodes.

# Answer
> 1 votes
A thoroughly complicated problem since node compare isn't an option. Entity forms, entity reference and field permissions could do it though.

Of the top of my head I'd start with an entity reference form that allows you to pick all the nodes to compare.. Then when the form is saved, use rules to create a redirect to a view passing the required nids as contextual filters in the url in your edit view. This will limit the view to those nodes.

For only one field at a time, you could create 15 different views and a taxonomy field in the entity reference form to control which view it redirects to.

Or for many fields at the same time, have one view and use the field permissions module. Have a role per field and then apply (actually take away) roles based on which taxonomy terms the user selected in the entity reference form. Then only those fields will appear in the view.

You'd need another rule that would give the user the those roles back at some point.

I'd love to see some other solutions without custom coding.

---
Tags: views, nodes, entities
---


# Question
Title: How to create a rule to automatically assign users to different profile 2 types?
I'm working on a project where different people can register.

1) Only certain domains can register. I've used the User restrictions module for this purpose.

2) Admins can create files/resources and assign them to different people. To accomplish this, I installed `Profile2` module and created an entity reference field in my custom content type where admins can decide which profile types can view this resource.

My problem is now I'm trying to come up with a rule that when somebody registers, based on the domain name of their email address, I'd like to associate them to different profile types.

Is that possible?

# Answer
> 0 votes
Below is a potential solution for your "***... based on the domain name of their email address, I'd like to associate them to different profile types ...***").

You might want to try using the Conditional Rules module: use an "if condition" (contained in the Rules Action), and the Rules Action "*... to associate them to different profile types ...*" would only be executed if the "if condition" would be true. For a sample using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Instead of using ***Conditional*** (if/else) logic within the Rules Action, you can also use ***Switch*** logic.

Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

---
Tags: rules, users
---


# Question
Title: How do I (in general) track down what happens on form submit?
I am working on a site that uses the Chosen module. There is a field that I need to edit programatically. When I use the actual field edit interface, Chosen adds an option called "Apply Chosen to the select fields in this widget?" When I set that value and submit the form, all is well... it changes what I need changed. However, I need to be able to track down what this is actually doing on the back end so I can change the value of this option for this field programatically... once... in an update hook. The user needs to still be able to edit this value using the form... I just want to flip its value this one time. I don't know where to start looking. In the Chosen module, I can see where it adds the option to the form, but I don't know what piece of data that option is stored with, nor how to see what the form is doing when it saves it so I can duplicate that functionality. It's hard to even know the right terminology to ask this question.

# Answer
> 1 votes
You mean updating the field instance settings programmatically, in an update hook, `hook_update_N()`. Do it as follows:

```
function YOURMODULE_update_N(&$sandbox) {
  // First load the field instance.
  $instance = field_info_instance($entity_type, $field_name, $bundle);
  // Make the changes in the field instance configuration.
  $instance['widget']['settings']['apply_chosen'] = 1;
  // Save the field instance.
  field_update_instance($instance);
}

```

---
Tags: forms
---


# Question
Title: Place custom Block, return Internal Server Error
I create a Block Plugin in a module, it be showing the available blocks but when I try to place the block, it returns in the browser console the follow error:

> AjaxError: An AJAX HTTP error occurred. HTTP-resultaatcode: 500 Debug informatie volgt. Pad: /admin/structure/block/add/hello\_block/bartik?region=footer\_fourth Statustekst: Internal Server Error Antwoordtekst:

I have place the code on the follow place: DrupalRoot/modules/pagebuilder/src/Plugin/Block/testblock.php

```
<?php

/**
 * @file
 * Contains \Drupal\pagebuilder\Plugin\Block\testblock.
 */
namespace Drupal\pagebuilder\Plugin\Block
use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "hello_block",
 *   admin_label = @Translation("Hello block"),
 * )
 */
class testblock extends BlockBase {

    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#markup' => $this->t('Hello, World!'),
        );
    }
}
?>

```

How can i fix this problem?

# Answer
When developing and encounter 500 errors, you should see if Drupal has logged the error or your webserver has logged the error. Depending on your configuration you might be able to see a full stacktrace explaining the error.

In this case you are missing a `;` after your namespace declaration. So

`namespace Drupal\pagebuilder\Plugin\Block`

Should be

`namespace Drupal\pagebuilder\Plugin\Block;`

This should fix your error.
> 1 votes

---
Tags: blocks, 8, plugins
---


# Question
Title: Multiple forms on one page - gather values
I am using the `hook_form` to create 2 different forms in a module file. Now it depends on what the URL parameters are, it can either display, one or the other or both.

Is there a function that picks up all `form_states` so i can gather values?

# Answer
> 0 votes
You can nest form elements, so there is effectively only one form. That case you'll only need one validation and submit handler. In the end all results will be in `$form_state['values']`.

```
function form_a($form, &$form_states) {
  ..
  return $form;
}

function form_b($form, &$form_states) {
  ..
  return $form;
}

function my_form($form, &$form_states) {
  if ($need_a) {
    $form += form_a($form, &$form_states);
  }
  if ($need_b) {
    $form += form_a($form, &$form_states);
  }

  // Add the buttons.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#weight' => 5,
  );

  return $form;
}

function my_form_submit($form, &$form_states) {
  drupal_set_message(print_r($form_state['values'], TRUE));
}

```

---
Tags: 7, forms
---


# Question
Title: How to investigate (and get control over) the execution order of 3 Rules working on the same action?
I have three Rules to do something after saving content. I need to know which one is executed first and how I can control this order?

Is there a certain answer for this question?

# Answer
It's based on the weight. Edit the Rule settings and you'll find a drop down to set the weight. I believe those with a lighter weight, e.g. -1, are executed before those with heavier weight, e.g. 5.
> 2 votes

# Answer
You can set a weight for each rule.
> 1 votes

# Answer
Something that will help you find the answer to your question, is to have a look at Rules **debugging** ... Within the Rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temorary) add a Rules Action like "Display a value" (in your case of the entire node/webform that's used to submit that attached file).

For way more details about these 2 variations, refer to **Rules debugging**, as explained in the answer to "How can I display the value of a variable inside a condition?".

To actually control the order of execution of 3 rules, you may want to implement these 3 rules as Rules Components, and then build a 4th rule in which the Rules action is to execute these 3 rules components ... in the exact order that "you" want them to be executed.
> 0 votes

---
Tags: 7, rules
---


title: Change width of editable in views

text:
# Question
Title: Change width of editable in views
I am using Editable views for fast editing of fields that change a lot. It works fine but the edit field is way to long. I think it must be fixed with css but I don't know how. I am using the Corolla theme. When I use de chrome inspector on that fields this is the result:

`block input.form-text, .block input.form-password, .block input.form-file {
max-width: 400px;
width: 100%;
}`

When I change the width value it has effect but it will effect al input fields with those css classes. So that is not the solution. I tried to add a css class in field settings in de view module. I called it editable\_fields and I have added it to forms.css and corolla.settings.style.css with this line:

`editable_fields {
width: 30%;
}`

but it has no effect.

Is there a way to make the field smaller?

It looks like this now:

# Answer
> 0 votes
I think I have the answer. If I use the id selector on this way I can control the specific fields: `[id^="edit-node"] {
 max-width: 100px;
 width: 100%;`

Edit:

I was happy to fast, I want to control all of the different edit fields for the first fields it looks great, but for others it does not. The complete id of the first field is id="edit-node-431-field-aantal-und-0-value" The "431" is a variable but also the "aantal".

The css rule above works for everything that starts with edit-node, but i want to add differente rules for different fields. I have tried to put a * or a ^ in de place of the "431" like this: `[id^="edit-node-*-field-aantal"] {
 max-width: 100px;
 width: 100%;
}` But that does not work. Any ideas?

---
Tags: views, theming
---


title: hook_entity_update cancel

text:
# Question
Title: hook_entity_update cancel
When updating an entity I want to validate that the fields I am updating are correct. As this may be coming from VBO or a Drupal form I thought I could do it in hook\_entity\_update.

In hook\_entity\_update() is there a way to not update the entity and return/display a message.

Maybe I am coming from the wrong angle.

# Answer
> 0 votes
The right hook for this job is hook\_field\_attach\_validate().

(As implemented by the Field Validation module, which may also do what you want.)

`hook_entity_update()` actually fires after the entity and all fields have already been saved (in the case of nodes, at least).

---
Tags: 7, entities, views, nodes
---


# Question
Title: Should I change multiple text fields values via MySQL or is there any other preferable way?
The site has a content type and this content type has two fields:

* Text Field
* Term Reference Field

There are thousands of nodes on this content type and I want to change some values (find/replace).

For example, I want to change all the "ABCD" strings with the "WXYZ" strings on the text fields in all the nodes.

**Is it a good way to do this change via MySQL or is there any other preferable way?** (Both text field change and taxonomy term replacement).

**Note**: I saw the Search and Replace Scanner module but it gives some errors I couldn't understand why. And it gives timeout error for a large amount of nodes.

# Answer
The Drupal way is to iterate over the nodes of interest and modify the fields. Here is a simple example that shows how you could make modifications in the Body field of the Article content type:

```
  $nodes = node_load_multiple(array(), array('type' => 'article'));
  foreach($nodes as $node) {
    // Only modify nodes that have something in the body field
    if (isset($node->body[$node->language][0]['value'])) {

      $text = $node->body[$node->language][0]['value'];
      $find = 'ABCD';
      $replace = 'WXYZ';
      $text = str_replace($find, $replace, $text);
      $node->body[$node->language][0]['value'] = $text;
      node_save($node);
    }
  }

```

One thing to note about doing it this way is the last-modified time of all your nodes will be updated. You may or may not want this. If you want to update the nodes without changing the timestamp, use this instead:

```
  $nodes = node_load_multiple(array(), array('type' => 'article'));
  foreach($nodes as $node) {
    // Only modify nodes that have something in the body field
    if (isset($node->body[$node->language][0]['value'])) {

      $text = $node->body[$node->language][0]['value'];
      $find = 'ABCD';
      $replace = 'WXYZ';
      $text = str_replace($find, $replace, $text);
      $node->body[$node->language][0]['value'] = $text;
      unset($node->created);
      unset($node->updated);
      field_attach_update('node', $node);
    }
  }

```

Edit: How to modify taxonomy terms

You could use the same approach to modify taxonomy terms, i.e. load the terms, iterate over them, and do a find/replace on each.

```
  $vocab = taxonomy_vocabulary_machine_name_load('my_vocabulary');
  $terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocab->vid));

  foreach ($terms as $term) {
    $text = $term->name;
    $find = 'ABCD';
    $replace = 'WXYZ';
    $text = str_replace($find, $replace, $text);
    $term->name = $text;
    taxonomy_term_save($term);
  }

```

Depending on how expert you are with MySQL, you could try updating the database field directly and you might have success, but it's prone to error especially if your fields have revisions.
> 4 votes

# Answer
# Step 1: Create a Rules Component

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

```
{ "rules_search_and_replace_values_in_a_text_field" : {
    "LABEL" : "Search and replace values in a text field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "old_value" : { "label" : "Old Value", "type" : "text" },
      "new_value" : { "label" : "New Value", "type" : "text" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } },
      { "data_is" : {
          "data" : [ "node:field-free-format-text" ],
          "value" : "[old-value:value]"
        }
      }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-free-format-text" ],
          "value" : "[new-value:value]"
        }
      },
      { "drupal_message" : { "message" : "String \u0022[old-value:value]\u0022 was replaced to string \u0022[new-value:value]\u0022 in field \u0022field_free_format_text\u0022 for node with id \u0022[node:nid]\u0022 and title \u0022[node:title]\u0022." } }
    ]
  }
}

```

Some more details to further explain the above above example:

* This Rules Component will be used in the subsequent step.
* In my case I have a text field with machine name `field_free_format_text`.

Note that I also added the Rules Condition `Entity has field` to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

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

If you want, just grab (copy) the exported rule above, change all occurrences of the machine name of that field to match the machine name of your field, and then you can simply import this Rules Component in your own environment.

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

After you're confident your rule works perfect for all variations of your nodes, move on to the next step below.

Here is an example of the (2) Drupal messages I got when executing this Rules component for a node with ID = 48, in which I changed the string "Pierre" to "Herci":

> * String "Pierre" was replaced to string "Herci" in field "field\_free\_format\_text" for node with id "48" and title "Demo field\_free\_format\_text replacement".
> * Component rule: Search and replace values in a text field has been executed.

Variation of the display of that message could be that you use Rules to create a (similar) log record ...

**Attention**: you always get the 2nd message. But the first one only shows up if you have an actual match ... and hence the update gets performed also.

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

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

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

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

**Attention**: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

# Step 3: Straight forward variations

There are dozens (hundreds?) of straight forward variations of this question that can also be solved using the above combination of VBO and Rules. To just mention 1 of them, have a look at my answer to "How to bulk delete selected content/nodes?" ...

The flexibility you get with this approach also illustrates the advantages of this one, as compared to direct MySql approach.

Happy VBO-ing while Rules-ing!
> 2 votes

# Answer
The real Drupal way of doing this is, writing an update script implementing `hook_update_N()`, which would find all the nodes with the text to be changed. Then update all the nodes in a batch (which prevents the timeouts).

A rough layout of the update script should look like as follows. Please read my comments in the code.

```
/**
 * Replaces all "ABCD" strings with "WXYZ" strings on text fields in all nodes.
 */
function mymodule_update_7100(&$sandbox) {
  // Set our $sandbox, which will stay persistent in multiple batch processes.
  if (!isset($sandbox['total'])) {
    // Find all nodes having 'ABCD' in a text field
    // Use your favorite method here, for the sake of this example I use EFQ.
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node');
    $query->propertyCondition('bundle', 'YOUR_CONTENT_TYPE');
    $query->fieldCondition('my_text_field', '%ABCD%', 'like');
    $result = $query->execute();

    // Put the node ids into the $sandbox
    $sandbox['nids'] = array_keys($result['node']);
    $sandbox['total'] = count($sandbox['nids']);
    // Set batch size to a number of nodes your server can process in a single
    // request. If you still get timeouts, try to reduce this number.
    $sandbox['batch_size'] = 10;
    $sandbox['current'] = 0;
  }
  else {
    // The sandbox is set, so we can process the nodes in batches. We load only
    // that much of nodes set in the $sandbox['batch_size']
    $offset = $sandbox['current'] * $sandbox['batch_size'];
    $current_nids = array_slice($sandbox['nids'], $offset, $sandbox['batch_size']);
    $nodes = node_load_multiple($current_nids);

    foreach ($nodes as $node) {
      // Change the text value here and save the node.
      // Again use your favorite method here. For the sake of this example, I
      // change the value directly on the $node object and save the $node.
      $text = $node->my_text_field['und'][0]['value'];
      $text = str_replace('ABCD', 'WXYZ', $text);
      $node->my_text_field['und'][0]['value'] = $text;
      node_save($node);
    }
  }

  // Check the progress and set $sandbox['#finished'] to 1 once all nodes are
  // processed.
  $progress = $sandbox['current'] * $sandbox['batch_size'] / $sandbox['total'];
  $sandbox['#finished'] = $progress > 1 ? 1 : $progress;
}

```

Put above script in an `.install`-file of a custom module. You should adjust the name of the function. Please see the documentation of `hook_update_N()` if you are not familiar with update scripts.

Then, you run the `update.php` or use drush command `drush updb`. This update script will be called as many time as all the nodes are processed which are set in the first part of the `if` statement. On the first call, it will just find the nodes and put the node ids in the `$sandbox`. On the consequent calls, it will load the nodes in batches of 10 and process them.
> 2 votes

# Answer
IMO the fastest way to do this is trough a direct SQL query to your database, because you don't have to use any of the Drupal API functions (that can make calls to another functions) to solve this.

Remember that you must reindex your site again because you change some values in your nodes.

But if you want get the revisions updated also, this is not the way to do it.

Edit after @kiamlaluno comment:

Be aware that if you make the changes with a SQL query and if you have some Rules/Triggers/Validations/etc, then these changes can't be detected.
> 1 votes

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