title: An explanation on user_save() works

text:
# Question
Title: An explanation on user_save() works
I was writing on a module for drupal and i had to update some fields in the user-object. I first tried this code:

```
$account = user_load($user->uid); // Loading account
$edit = array(
  'gitlab_refresh_token' => $response_data['refresh_token'],
);
user_save($account, $edit);

```

This did not update the the field.

Then i found this code on the Internet:

```
$existingUser = user_load($user->uid);
$existingUser->data['gitlab_refresh_token'] = $response_data['refresh_token'];
user_save((object) array('uid' => $existingUser->uid), (array) $existingUser);

```

This code works. But the question is why?

The documentation for `user_save()` says, that `$edit` just needs to contain an array with key/value pairs of what you want to change and it will be put in the user's data field,
and that is what i did, right?

# Answer
> 2 votes
The first snippet doesn't work because Drupal doesn't use any `'gitlab_refresh_token'` array index, and it doesn't know any field with that name. If you were trying to change the value of a field added with the field UI, the array needs to have a different structure, to be saved.

The second snippet works because Drupal effectively uses that array index, as also said in the documentation.

> Key / value pairs added to the `$edit['data']` will be serialized and saved in the {users.data} column.

```
// Prepopulate $edit['data'] with the current value of $account->data.
// Modules can add to or remove from this array in hook_user_presave().
if (!empty($account->data)) {
  $edit['data'] = !empty($edit['data']) ? array_merge($account->data, $edit['data']) : $account->data;
}

```

---
Tags: users
---


# Question
Title: How can I check if the author of the current node is the current logged in user?
I am trying to execute a Rule based on the condition of whether the currently logged in user, is currently viewing their node (a node they are the author of), or viewing someone else's node. The Rule event/trigger I am using is "User saves a Status" from Statuses module. Next I have used the Rules condition "Execute Custom PHP code", and set an if statement that checks whether the current node uid (the uid of the node's author) equals the current user uid:

```
if ($node->uid == $user->uid) {
  return TRUE;
}
else {
  return FALSE;
}

```

This is causing a bunch of "Trying to get property of non-object" errors, as both the `$node` and `$user` variables are not being recognised. I'm not sure why this is the case, do I need to use the `node_load()` and `user_load()` functions before using these variables? If so how?

# Answer
I have managed to work it out! Below is the code for checking whether the current user is viewing content they are an author of:

```
global $user;
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

if($node->uid == $user->uid){
return TRUE;
} else {
return FALSE;
}

```

Hope this is helpful to someone.
> 2 votes

# Answer
You don't need to write any PHP code to achive that.

1. Create a new rule
2. React on event: **Content is viewed** (under **Node** section)
3. Add condition: **Data comparison** (under **Data** section). Continue.
4. Data to compare, data selector: **node:author**. Continue.
5. Data value, data selector: **site:current-user**. Save.

### UPDATE:

According to you latest edit, my above answer becomes invalid. As I already written in comments, I am not sure if `$node` object is loaded in your script, however I am almost sure that the `$user` object is not. You can load the currently logged in user adding:

```
global $user;

```

at the beginning of you code block. Since I never used PHP in UI, I am not sure if there are tokens available to use. Look around the UI to find out this information, and if they are available, try to make use of them in your code.
> 1 votes

# Answer
I have a little bit of a different method. It's very similar to FrontEnd's method, but I try to stay away from arg() as much as possible (for better or worse). It uses menu\_get\_object() so this won't work in D8, but I've not moved into D8 yet for anything I'm doing.

Here she is:

```
global $user;
// Logged in user
$uid = $user->uid;

$node = menu_get_object();
if (!empty($node)) {
  // Node creator ID
  $nuid = $node->uid;
}

if ($uid==$nuid) {
  $creator = TRUE;
} else {
  $creator = FALSE;
}

```

Then, if I need to display specific information to the content creator I just use:

```
if ($creator) {
  // Hello Creator
}

```

Now I've got uid of the logged in user and the content creator to use further down the function as well.
> 0 votes

---
Tags: nodes, users, rules
---


# Question
Title: Programmatically added block does't appears in block admin page
I created a programmatically block in a custom module for Drupal 8.1. The custom module and the block plugin are created via Drupal Console.

I installed my module and I clear cache via `drush cr`, but when I go to the admin block page, my block does't appear.

For view an example, I installed the "examples module" and the "block example module". When I do that, there aren't blocks example" in a block admin page too.

I don't understand.

The content of my block class form my custom module is the following.

```
/**
 * @file
 * Contains \Drupal\nomads_pdf\Plugin\Block\nomads_pdf_block.
 */

namespace Drupal\nomads_pdf\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'nomads_pdf_block' block.
 *
 * @Block(
 *  id = "nomads_pdf_block",
 *  admin_label = @Translation("Nomads_pdf_block"),
 * )
 */
class nomads_pdf_block extends BlockBase {

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

}

```

My custom module structure is the following.

>

# Answer
> 6 votes
Did you use the button "Place block"? The block does not appear in the block layout by itself. The block layout is a bit misleading by providing the disabled section, which suggests that all blocks not used are listed there.

The technical background is, that the block layout only lists blocks that have a configuration. When you install a module with a block plugin this block is not registered with a configuration entity yet. That happens when you press the button "Place block" for the first time. You can do this multiple times to get multiple instances of the block. The configured blocks will keep their configuration entity and will stay in the block layout, even when disabled.

---
Tags: 8, blocks
---


title: How do I alter the submit function?

text:
# Question
Title: How do I alter the submit function?
I want to do array\_unshift for submit function in D8. Array\_unshift working perfectly for validate function but not submit function. Below is my code:

```
function example_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == "commerce_order_default_edit_form") {
    array_unshift($form['#validate'], 'example_manual_validate');
    array_unshift($form['#submit'], 'example_manual_submit');
  }
}
function example_manual_validate(&$form, \Drupal\Core\Form\FormStateInterface &$form_state) {
  $values = $form_state->getValues();
  dsm($values);
}

function example_manual_submit(&$form, \Drupal\Core\Form\FormStateInterface &$form_state) {
  $values = $form_state->getValues();
  dsm($values);
}

```

# Answer
Found Solution to alter submit function in D8 , this will be helpful https://www.drupal.org/node/2637958

```
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'mymodule_node_form_submit';
      }
    }
}
function mymodule_node_form_submit($form, FormStateInterface $form_state) {
   $node = $form_state->getFormObject()->getEntity();
  // mymodule_do_something($node);
 \Drupal::logger(' mymodule')->notice('mymodule submit ') ;

}

```
> 0 votes

# Answer
Here am altering the submit handler of the article content type while creating new article type contents

```
  /**
     * Implements hook_form_alter().
     */
    function example_module_form_alter(&$form, FormStateInterface $form_state,$form_id) {
   // dsm($form_id);

      switch ($form_id) {

        case 'node_article_form':      // New article nodes.
        // Attach our custom submit handler.
     array_unshift( $form['actions']['publish']['#submit'], 'example_module_node_article_form_submit');
          break;

      }

    }

    function example_module_node_article_form_submit($form, FormStateInterface $form_state) {
      drupal_set_message('custom submit ...');
    }

```

Source
> 2 votes

---
Tags: forms, 8
---


# Question
Title: Why is this block found but not installed?
I have a custom block that **is** found by "Place Block" but does not actually get placed. The spinny just spins for second and then nothing happens; the screen just stays at the list of available blocks.

1. Is there any method within Drupal 8 to see what the error is?
2. What incompatibilities might be causing this?

### Setup Notes

1. Drupal 8.1
2. Lots of cache refreshing attempts
3. Lots of uninstall/reinstall attempts
4. Same behavior on a fresh D8 install
5. The module **does** install and the controller works at its prescribed URL
6. The base directory of the module is nrs\_raceroftheday

This is the content of ROTDBlock.php.

```
/**
 * @file
 * Contains \Drupal\nrs_raceroftheday\Plugin\Block\ROTDBlock.
 */

namespace Drupal\nrs_raceroftheday\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Racer Of the Day' Block
 *
 * @Block(
 *   id = "rotd_block",
 *   admin_label = @Translation("RacerOTD v4 block"),
 *   )
 */
class ROTDBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build()
    {
    $pageContent='asdf';
    return array('#markup' => $this->t($pageContent),  );
  }
}

```

Here's the routing file nrs\_raceroftheday.routing.yml.

```
nrs_raceroftheday.controller:
  path: '/racer-of-the-day'
  defaults:
    _controller: 'Drupal\nrs_raceroftheday\Controller\NrsRacerOfTheDayController::content'
    _title: 'Racer of the Day'
  requirements:
    _permission: 'access content'

```

# Answer
In general, that can have many possible causes. But it's very likely some sort of syntax or other error that leads to an exception or a fatal error.

Open the Place block link in a new tab to see the response, check the network tab and/or check your apache or drupal logs.

That should give you a hint about the problem. In this specific example, it was a trailing space after the closing PHP tag, as suggested by @kiamlaluno, that's why Drupal coding standard says that they should be left out.
> 2 votes

---
Tags: 8, blocks
---


title: Formatting email sent with Contact form

text:
# Question
Title: Formatting email sent with Contact form
I created a custom form (adding some additional fields) using the **Contact module** from the core of **Drupal 8**.

When I submit the form is sent an **email** containing all values, but it is really **bad formatted**. The email only contains form's values without any field label and it is **unreadable**.

How can I customize the template of the email sent on the form's submit?

---

## What I already tried

### hook\_mail\_alter

I found some answer about the same problem for Drupal 7 suggesting to implement a custom `hook_mail_alter` function (for example: , ).

So I created a custom module with my function:

```
/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(&$message) {

  // Process only 'contact_page_mail' messages
  if ($message['id'] != 'contact_page_mail') {
    return;
  }

  $params = $message['params'];

  // Body
  $message['body'] = [];
  $message['body'][] = t('Some custom message');

  // I don't know what should I do here?
  // How can I access values of all fields in the form?
  // ...

  return;
}

```

The function is correctly triggered before the email is sent, but I can't access field's values so I'm not able to build a custom email.

Also I can't get the form's id (only a generic `'contact_page_mail'` valid on all contact forms) so I'm not able to handle different contact forms in this function.

### Swift Mailer

As suggested in this other similar question, I tried with the Swift Mailer module.

After some effort, I'm able to get it working and now I have a `swiftmailer.html.twig` template file with this content:

```
<div>

  {{ body }}

</div>

```

But as for the `hook_mail_alter` solution, I don't know how to access form's field values so I can't customize the email format.

Moreover, the Swift Mailer module currently is an *alpha* version (8.x-1.0-alpha1) and the Mailsystem module (required to get things working) is a *beta* version. So I would like to avoid to install unstable modules on a production website (anyway this can be the last solution, if no other works).

---

**EDIT**

Thanks to @Berdir, now within the `hook_mail_alter` function I can access field values with:

```
$contactMessage = $message['params']['contact_message'];

// Value of 'field_my_field_name'
$contactMessage->get('field_my_field_name')->getString();

```

So I can put them inside the `$message['body']`.

Quite complicated, but it works.

Is there a way to get field values within the Swift Mailer template? I tried with `{{ params.contact_message.field_work_with_us_name }}` but it doesn't works.

What happen if I have two or more contact forms? The function `hook_mail_alter` will be triggered on all of them. Is there a way to have a specific function for each contact form?

# Answer
Putting together an answer based on the comments/discussion there so this can be accepted/closed.

* General instructions on how to theme a mail can be found in this existing answer: How can I theme the outgoing contact mail?
* You might want to watch https://www.drupal.org/node/2680731, once resolved, you can rely on that instead of your own custom code to send the mail as HTML.
* To use a custom template for the inner parts of the mail, you can set a custom template in `hook_contact_message_view()`. Or use field templates for specific fields.
* To check for a specific contact form, you can use the `bundle()` method of the contact message entity, which you can find in `$message['params]['contact_message']` in `hook_mail_alter()`. Make sure you combine this with a check that it is there and an entity object, otherwise you could have fatal errors for other mails.
> 2 votes

---
Tags: theming, forms, 8, emails
---


# Question
Title: What hook can access every field label at once and change the label of one?
I am trying to change the display label of one field on a node (not the form), depending on the value set in another field in Drupal 7. I don't want to change the label in the database, just on the final node page when you view it, if another field is set to a certain value.

I tried a few different hooks with no luck. Some can access every field, but only the value and not the label. Some can access the label on a per field basis which I can get half working (Set a flag in another function if the field is set correctly) but that only worked if the fields are checked in the right order.

So which painfully obvious hook will allow me to check a field setting and then edit the display of a label on another only on the node page? My perusing of the hook documentation and Google have not helped.

Thanks!

# Answer
A guaranteed solution for all fields is hard. It depends on:

1. The field formatters you have chosen
2. the template files used

For a general approach try:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function YOUR_MODULE_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'YOUR_DEPENDENT_FIELD' && !empty($variables['element']['#object']->YOUR_DEPENDENCY_FIELD)) {
    // YOUR LOGIC IN RELATION TO YOUR_DEPENDENCY_FIELD
    $new_value = 'something';
    $variables['label'] = $new_value;
  }
}

```

Notes:

1. This will change the label **display** everywhere, not only on a node display. Since you don't mention anything about view modes, I guess the given solution is good enough.
2. Make sure you sanitize $new\_value if you are showing user input.
> 1 votes

# Answer
Seems I forgot to log in last time and it's not letting me mark that as the answer. dmsmidt was exactly correct. I just had to dig a little deeper in DPM to find the info I needed. Thanks!
> 0 votes

---
Tags: hooks
---


# Question
Title: Set Generate automatic URL alias during import in Taxonomy
how to set 'Generate automatic URL alias' for my terms during Feeds import?

I tried to set 1 or '1' in URL (url) field but it does not work for me.

# Answer
use views bulk operation module and then you can update nodes or taxonomy on the fly via view....

I have the same problem now for nodes...
> 1 votes

---
Tags: taxonomy-terms, feeds
---


# Question
Title: How can I alter an "Add to cart" button at the submission time?
I am using the Drupal Commerce module, and I need to fire some operation at the time the users click on the *Add to cart* button, but I am unable to find any hook for this.

I am using this code but it is not working.

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'commerce_cart_add_to_cart_form') {
    $form['#submit'][] = 'custom_submit';
  }
}

function custom_submit($form,$form_state) {
  die("Tesing");
  drupal_set_message(t("Don't panic!"), 'warning');
}

```

# Answer
You can use the form alter as follows:

```
function hook_form_alter(&$form, &$form_state, $form_id) { //hook can be replaced by theme name if being defined in *template.php* of a theme and by the module name if function is being defined inside a custom module

  if($form_id == 'commerce_cart_add_to_cart_form') {

//HERE YOU CAN DEFINE A SUBMIT HANDLER, WHICH WILL ACT ON HITTING ADD TO CART BUTTON. Example:

    $form['#submit'][] = 'custom_submit';
  }

function custom_submit($form, &$form_state) { //custom submit handler

  //Add here the functionality you want to do on click of add to cart button

}

```
> 0 votes

---
Tags: commerce
---


title: Migrating 301 redirects

text:
# Question
Title: Migrating 301 redirects
Drupal 7 to 8 Migration works only on core. It doesn't migrate 301 redirects created in Drupal 7 with the Global redirect module.

Is there a way to migrate all the 301 redirects to Drupal 8 that doesn't require manually copying them after migrating the site?

# Answer
The Global Redirect module doesn't store paths on a per-node basis. That's the role of the core path module which stores aliases that map to system paths in the `url_alias` table (in both D7/D8).

The Global Redirect module could broadly described as settings (set on its administration page) that drive logic for 301 redirecting (in a `hook_init()` invocation) while setting the `rel="canonical"` metatag (a signal that tells the search engine to index that path). Thus, there really isn't anything to migrate from the module besides various `globalredirect_settings` variables that store redirect settings.

That said, you can run the Migration module which will import your node path aliases (and thus the paths you're concerned with 301 redirecting to) and adjusting the settings for Global Redirect module so that it matches the settings in your D7 installation.
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: CKEditor removes HTML/CSS when switching to plain texteditor and back
My CKEditor seems to remove formatting in a table when I switch from `plain text editor` back to `rich text editor` even though the additional formattibn was added in the `rich text editor` \- it seems to persist whenb I switch to plain text but gets removed when I go back to `rich text` \- I have tried around and Disabled the `ADVANCED CONTENT FILTER` under /admin/config/content/ckeditor/edit/Full but that did not seem to help,. How can I get my changes to persist even past text editor style switches?

**EDIT 1**

My configuration under `/admin/config/content/formats/full_html` looks like below but it still doesn't seem to work correctly (yes, I also cleared my caches):

and I selected **Disabled** `/admin/config/content/ckeditor/edit/Full` \- **ADVANCED CONTENT FILTER**

**EDIT 2** Now after all these changes , on another page my content doesn't seem to properly display anymore:
link http://www.lslib.ca/content/skwlax-wellness-centre
problem: under `<div class="field-item even">` I have a colorbox image declared: `<p><a class="colorbox colorbox-insert-image init-colorbox-processed cboxElement" href="http://lslib.ca/sites/default/files/wellness%20centre.jpg" rel="gallery-all"></a></p>` and it wouldn't show up anymore in HTML and I have no idea why...

# Answer
> My CKEditor seems to remove **formatting in a table**

You need to add the HTML Table tags

```
<table><tr><td>

```

to your **Allowed HTML Tags**
> 2 votes

---
Tags: wysiwyg, input-formats
---


title: Fuctioning of Views Relationship?

text:
# Question
Title: Fuctioning of Views Relationship?
I am trying to understand the Views relationship. As I am searching the tutorials, it all described, "When you want to include data which is not directly available Views relationship lets you include that data through the common connector(joint)." Now in theory it is very straight there is a some connector which does provide the data, but How to get visualize this thing in the Views User Interface.

Let me put this way for the ease of visualization and understanding, Lets say, there is A, C and B in the following image, where C is a connector, A is data available and B is the data which is not directly available. So how can I find the A, B and C looking at Views User Interface, Hence I can Put All this three on the paper and put the logic.

Why I am putting this way, because after observing too much, I realize that why people have difficulty in understanding the views Relationship is that, what comes from where are not so clear, hence people gets confuse which content comes from where and how they connect each other and which one is actually not accessible. If this gets clear, the understanding of Views Relationship will be much simpler.

# Answer
First understand entities, attributes, bundles and fields:

**Node and User are entities**. Both have a unique identifier. For Node it is nid, for User it is uid. **Entities have attributes** associated with them. These are the fields that you will see in the Node or Users table in the database. For instance, Node has author, data published etc, and User has name, mail etc.

Between the attributes of entities there are links, for instance: Node has an author, which is just the uid key of the User entity. In other words via a SQL join you can get from the one to the other. This is what Views do when you add a user relationship on the node view to bring in the extra information of the user table.

**Bundles have fields**. A bundle is an entity type with additional fields attached. For instance, Article is a bundle of entity type node. Article has all the attributes of Node, and it also has an image field. If you look at the Node table there is no image field on it. The image field is created as its own table, field\_data\_field\_image. In this table there is a field entity\_id which contains the nid of the node it belongs to.

When you add a field that is not part of the node entity (node table) but part of the bundle (ie Article) to Views, Views will do a SQL join to get that field into the display. Therefore Views is bringing in a relationship for you, nl. the relationship between the entity and the field.

When you install Entity reference you can add a field to an entity that will reference another entity. For instance, you add an entity reference field to an Article that can reference Basic Pages.

In the database you have now added a new field as a separate table which points to the node, of type article, as its parent container, as well as to the node of type Basic Page as the referenced node. It looks like this:

To add it to Views you need to include the relationship manually as an **Entity Reference**. There will be two possibilities:

* Entity Reference: Referenced Entity - A bridge to the Content entity that is referenced via field\_reference
* Entity Reference: Referencing entity - A bridge to the Content entity that is referencing Content via field\_reference

which is just the **direction of the relationship**. If I have the article in my View and I want to include the Basic Page, then it will be **Referenced Entity**. If I have the Basic Page and I want the Article, then it will be **Referencing entity**.

Views will bring in this relationship via two joins, the first to bring in the field belonging to the Article, and the second to bring in the Basic Page node that is pointed to by the entity reference field (the order depending on the direction)

**NOTE** that you can bring in even more relationships in a chain-like fashion. You may have a node whose author user has an entity reference to a profile type node that has a Taxonomy Tag etc.
> 3 votes

---
Tags: 7, views
---


# Question
Title: How can I grant users permissions to edit certain views (add/remove fields in a view) in drupal?
We offer a Drupal site to our client with a set of views. The client wants to edit a (predefined) set of views. So, say for example the application got 3 views. The client is allowed to edit one of them.

I have been looking for a module to take care of this but couldn't find any. I was hoping there would be a module which would take the Views tags into account, so you can set permissions on this tag. Say I assign the tag 'Client' to a view. I then can assign the edit permission for a certain role on this tag.

How would you solve this or is there already a solution available?

Thanks!

# Answer
> 2 votes
If your client need only to edit the basic settings of some views (header, footer, title, or empty text...), you should give a try to the Views UI: Edit Basic Settings module. It allows you to define which views are editable by a certain role.

# Answer
> 0 votes
Unfortunately that is not possible. Either a user is allowed to edit fields, or they're not. Having a view editable by the Views UI is also not desirable for version control

One workaround is to use a different content type that they can edit, which is editable as normal, and pull that through into the view.

Chandeep

# Answer
> 0 votes
I needed the same functionality for my latest project, so I created a sandbox module for that.

https://www.drupal.org/sandbox/sgurlt/2717137

It adds a permission per view you got. The menu path is not working for now, but i am going to check that soon.

---
Tags: views, users, nodes
---


# Question
Title: How to create a node from a Webform using rules?
I want to create a node based on a webform data using the Rules module. This is because of a complication surrounding relationships within the associated CRM system.

I am already at the point where I have the webform created and have got to the following (and working) point within Rules:

```
{ "rules_member_news_import_" : {
"LABEL" : "Member News (cloned)",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "webform_rules", "rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "webform_has_id" : {
      "form_id" : [ "form_id" ],
      "selected_webform" : { "value" : { "webform-client-form-730" : "webform-client-form-730" } }
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "newsfrommembers",
        "param_title" : "[data:title_member_news-value-raw]",
        "param_author" : [ "user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  }
]

```

What I need to do is use the rest of the fields in the webform to transpose the information across, for example the body text and an image.

What I am trying to learn is how to also incorporate the body and other information. I used the export to add what I thought would work, for example:

```
"param_body" : "[data:body]"

```

within the entity\_create action, however when I imported the edited text it simply disappeared, so I am assuming that I have to add a separate action to add entity variables.

I went back to using the menus and I again could not get it to work. I must be doing something basic wrong.

# Answer
> 4 votes
# 1st attempt

Before using a Rules Action like "Set a data value" for your a field, you have to make sure to add a Rules condition `Entity has field` (related to the field for which you want to set a value). And make sure to add that `Entity has field` condition BEFORE other Rules Conditions in which you might want to refer to this field.

That's also what is mentioned in the Rules UI, e.g. 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')*".

The above applies to any of your "*... rest of the fields in the webform*" (as in your question).

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 it.

# 2nd attempt

The prior attempt is more or less like a *Getting-started-with-Rules* that resolves various situations where some variables appear to not be available in Rules Actions, etc. However, for this specific question, which is about using Rules in combination with Webform, things are a very little bit more complicated, as further explained below.

Let's assume I have a webform created with some of its fields with machine names like so:

* `contact_us_first_name`.
* `contact_us_last_name`.
* `contact_us_subject`.

After you add these fields (with identical machine names) to any of your own forms, you should be able to import the *prototype*-rule below (using the Rules UI) in your own environment (without running into an integrity constraint):

```
{ "rules_create_a_node_from_a_submitted_webform" : {
    "LABEL" : "Create a node from a submitted webform",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "user" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform component submitted by [data:contact_us_first_name-value] (= [data:contact_us_first_name-title]) [data:contact_us_last_name-value] (= [data:contact_us_last_name-title]) contains a field labeled \u0022[data:contact_us_subject-title]\u0022 which has value \u0022[data:contact_us_subject-value]\u0022." } }
    ]
  }
}

```

In the above rule I included an extra Rules Condition to prevent the Rules Action from being executed for anonymous users (feel free to adapt the role id of it, or just remove that Rules Condition. And the rule is triggered via Rules Event "After a webform has been submitted".

The Rules Action only displays an (informational) message on the site (my recommended way of writing and debugging Rules ...) after a webform gets submitted. Here is what I specified (in the rules UI) as the message to be shown:

> The webform component submitted by \[data:contact\_us\_first\_name-value\] (= \[data:contact\_us\_first\_name-title\]) \[data:contact\_us\_last\_name-value\] (= \[data:contact\_us\_last\_name-title\]) contains a field labeled "\[data:contact\_us\_subject-title\]" which has value "\[data:contact\_us\_subject-value\]".

Here is a sample of the message shown in my own setup:

> ***The webform component submitted by Dries (= First name:) Buytaert (= Last name:) contains a field labeled "Subject:" which has value " Rumour goes that the rules module can even replace the node\_convert module! ".***

What the above prototype-rule shows is that the "clue" to answer your question is that you have access to all labels and all values of any field of a webform available, ie:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name MachineFieldName.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name MachineFieldName

# 3rd attempt

The above is a good start, but still not sufficient to achieve your goal (= "... use the rest of the fields in the webform to transpose the information across, for example the body text ...", as in your question). However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

* Add an extra Rules Action to `Add a variable` (for each of the Webform components to transpose the information across, with a value assigned to it equal to your `[data:ComponentName-value-raw]` (and with a data type which equals the data type of your Webform component).
* In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).

# Demo

### Webform components

Assume a webform with `form_id=191` and with these Webform Components:

* Label = Title, Machine name = `demoform_title`, Data type = Textfield.
* Label = Text, Machine name = `demoform_text`, Data type = Textarea.
* Label = Number, Machine name = `demoform_number`, Data type = Number.
* Label = Option, Machine name = `demoform_option`, Data type = Select options (single value).

### Article content type

Assume an Article content type with these fields:

* Label = Title, Machine name = `title`, Field type = Node module element.
* Label = Body, Machine name = `body`, Field type = Long text and summary.
* Label = Free Format Nr, Machine name = `field_free_format_nr`, Field type = Integer.
* Label = OptionList, Machine name = `field_optionlist`, Field type = List(text).

### Custom Rule

Here is a custom rule (in Rules export format), which is an extended (improved) version of the rule included in the question. This rule will create a new node (of type `Article`), and which will use the data included in the above mentioned Webform components:

```
{ "rules_create_a_node_from_webform_data" : {
    "LABEL" : "Create a node from webform data",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "webform_rules", "rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form_id" ],
          "selected_webform" : { "value" : { "webform-client-form-191" : "webform-client-form-191" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The webform submitted contains these fields:\r\n\u003C\/ul\u003E\r\n\u003Cli\u003Ethe field labeled \u0022[data:demoform_title-title]\u0022 which has value \u0022[data:demoform_title-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_text-title]\u0022 which has value \u0022[data:demoform_text-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_number-title]\u0022 which has value \u0022[data:demoform_number-value-raw]\u0022.\u003C\/li\u003E\r\n\u003Cli\u003E the field labeled \u0022[data:demoform_option-title]\u0022 which has value \u0022[data:demoform_option-value-raw]\u0022.\u003C\/li\u003E\r\n\u003C\/ul\u003E" } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_text-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_text" : "Form variable text" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_number-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_number_text" : "Form variable number text" } }
        }
      },
      { "data_convert" : {
          "USING" : { "type" : "integer", "value" : [ "var-demoform-number-text" ] },
          "PROVIDE" : { "conversion_result" : { "var_demoformvar_number" : "Form variable number" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:demoform_option-value-raw]" },
          "PROVIDE" : { "variable_added" : { "var_demoform_option" : " Form variable option" } }
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "article",
            "param_title" : "[data:demoform_title-value-raw]",
            "param_author" : [ "user" ]
          },
          "PROVIDE" : { "entity_created" : { "article_created" : "Created article" } }
        }
      },
      { "data_set" : {
          "data" : [ "article-created:body:value" ],
          "value" : [ "var-demoform-text" ]
        }
      },
      { "data_set" : {
          "data" : [ "article-created:field-free-format-nr" ],
          "value" : [ "var-demoformvar-number" ]
        }
      },
      { "data_set" : {
          "data" : [ "article-created:field-optionlist" ],
          "value" : [ "var-demoform-option" ]
        }
      },
      { "data_set" : { "data" : [ "article-created:comment" ], "value" : "0" } },
      { "entity_save" : { "data" : [ "article-created" ], "immediate" : "1" } },
      { "drupal_message" : { "message" : "A new article got created, with nid=[article-created:nid] and url=[article-created:url]" } }
    ]
  }
}

```

Some more details about the Rules Actions that were added:

* **`Show a message on the site`**: This is just for debugging/demo purposes (remove it you don't want/need it anymore). Here is a sample message that gets displayed after submitting a webform:

> The webform submitted contains these fields:
>
> + the field labeled "Title" which has value "Some interesting title of my webform".
>     + the field labeled "Text" which has value "Just some text, with some additional text and yet another line and another one".
>     + the field labeled "Number" which has value "842316".
>     + the field labeled "Option" which has value "A".
* **`Add a variable`** (twice): To make the value of the Webform components `demoform_number` and `demoform_option` available in subsequent Rules Actions. Note that for `demoform_number` an additional Rules Action **`Convert data type`** is needed to get it to work.
* **`Set a data value`** (3 times): To populate the node's body and the 2 node fields, using the variables created in a preceeding Rules Action.
* **`Set a data value`**: To set "Comments closed" for the node being created (this is an optional Rules Action, just an illustration of other things you can do with such node being created).
* **`Save entity`**: To actually save the node.
* **`Show a message on the site`**: This is just for debugging/demo purposes (remove it you don't want/need it anymore). Here is a sample message that gets displayed after submitting a webform:

> A new article got created, with nid=123 and url=http://www.example.com/node/123

### Final result

After submitting the webform with data as in the sample above, a new article (with node id = `123`) got created, and with these details about that node:

* **Title**: Some interesting title of my webform
* **Body**:

> Just some text,
>
> with some additional text
>
> and yet another line
>
> and another one
* **Free Format Nr**: 842316
* **OptionList**: Advanced (the label corresponding to key-value "`A`")

### Additional possibilities

With some further refinements, the above prototype-rule can also be used to create a Rules based alternative for the Node Convert module ... and seems to have the potential also to create like an **Entity Convert** equivalent also.

---
Tags: 7, rules, webforms
---


# Question
Title: How to redirect all node aliases to <front>?
I created a module with a `hook_menu()` to redirect every `$items[%node]` to `drupal_goto('<front>')`. Is it possible to do the same for every alias path and how would I do that?

The background is that it's a one-pager with all nodes displayed only on the `<front>` page. No single node should be viewed. Nevertheless every single node has a Facebook Like Button and so has to be like-able/share-able with Facebook. But that's another story, on the whole.

# Answer
> 0 votes
Using the Rules module you can implement a rule that looks like so:

```
{ "rules_redirect_all_node_aliases" : {
    "LABEL" : "Redirect all node aliases",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "my_homepage" } }
    ]
  }
}

```

It will redirect any path starting with `node/` to a path named `my_homepage` (adapt that path to fit your homepage path).

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function.

**Note**: A variation of this rule could be to replace the Rules Condition with something like "if the current path is not `my_homepage`" (in which case the same Rules Action will redirect to `my_homepage`.

---
Tags: 7, uri, redirection, routes
---


title: Call a custom form in node template

text:
# Question
Title: Call a custom form in node template
Following the Form generation example from DrupalAPI (https://api.drupal.org/api/drupal/core!core.api.php/group/form\_api/8.1.x), I have an error when I call the form in my template\_preprocess\_node.

Here's my code.

### mymodule/src/Form/ExampleForm.php

```
namespace Drupal\mymodule\Form;

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

class ExampleForm extends FormBase {
  public function getFormId() {
    // Unique ID of the form.
    return 'example_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    // Create a $form API array.
    $form['phone_number'] = array(
      '#type' => 'tel',
      '#title' => $this->t('Your phone number')
    );
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    // Validate submitted form data.
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Handle submitted form data.
  }
}

```

### mytheme/mytheme.theme

```
function cmimmo_preprocess_node(&$variables) {
  $variables['simulator_form'] = \Drupal::formBuilder()->getForm(\Drupal\mymodule\Form\ExampleForm::class);
}

```

I get the following error:

> InvalidArgumentException: The form argument Drupal\mymodule\Form\ExampleForm is not a valid form. in Drupal\Core\Form\FormBuilder-\>getFormId() (line 190 of core\lib\Drupal\Core\Form\FormBuilder.php).

Why am I getting that error message? What is wrong with my code?

# Answer
My Form folder in my module was named "Forms". Be carefull with your file structure. Too bad the error is not very explicit. It should be "not exist" instead of "not valid".
> 3 votes

---
Tags: forms, 8
---


# Question
Title: Want parent MENU_LOCAL_TASK tab to show when on a child page
I have a set of **local task** menu items defined in my module. This includes the following items:

* control =\> MENU\_NORMAL\_ITEM
* control/jobs =\> MENU\_DEFAULT\_LOCAL\_TASK
* control/jobs/% =\> MENU\_???
* control/download =\> MENU\_LOCAL\_TASK
* control/settings =\> MENU\_LOCAL\_TASK

The three menu items (jobs, download and settings), display as tabs, as I want. When someone clicks through to see a particular job, I want this to show as having the jobs tab selected.

If I add MENU\_LOCAL\_TASK to "control/jobs/%," the tabs show up, but I get notice errors (because Drupal is trying to define a link to % and can't know that). If I don't, the specific job page does not have any tabs at the top.

Have I misunderstood anything? Can I achieve this in another way?

# Answer
> 0 votes
You can do what you want, but you need to change the url structure a bit. If I understand you correctly:

* `control/jobs`: List of all jobs, should be MENU\_NORMAL\_ITEM
* `control/jobs/%node` (You should have a load function for the job, if not a node than something else), should be MENU\_NORMAL\_ITEM
* `control/jobs/%node/view`: MENU\_DEFAULT\_LOCAL\_TASK (doesn't have a callback)
* `control/jobs/%node/download`: The download page for a specific job, MENU\_LOCAL\_TASK
* `control/jobs/%node/settings`: The settings page for a specific job, MENU\_LOCAL\_TASK

You can take a look at the node and user module to get an idea on how create tabs in Drupal

---
Tags: routes
---


title: Add Glyphicon to titles?

text:
# Question
Title: Add Glyphicon to titles?
I am attempting to add glyphicon options to titles. Is there a way I can add a field to a content type in order to render the html showing the glyphicon? I am trying to add it to just the basic page content type and the page it shows on title click.

I tried adding a select list with the inside as options for example, but it would not render the html.

EDIT:::

I tried the title html module, but it only allows a few elements. I would ideally like to add a select list to my content type that contains all the glyphicons i'd like to use on the page and i could just select which one to show before the title from that select list. It would then show the glyphicon before the title on save.

# Answer
> 1 votes
an easier way to do this will be using this module:

***Icon API***

# Answer
> 1 votes
I think you're on the right track with adding a second custom field to allow the user to choose the glyph.

Once the user has set the title, selected the glyph and saved, you can merge the two using a template file.

https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7

The one you'd want I think would be named something like this: field--title--basic-page.tpl.php

In there, you can stick the value of the glyph next to the title. Does that make sense?

---
Tags: 7, nodes
---


# Question
Title: Drupal 8 function from controller returns html markups only
I have been creating a table from mysql result , but its printing the html markup only and says controller must return a response . what may be the reason ?

> LogicException: The controller must return a response (
>
> #
>
> (5 rows)group\_nameparent\_nameEditDeleteSelect itemsL2V9http://192.168.1.236/mailusers/usergroup/edit/6\>edithttp://192.168.1.236/mailusers/usergroup/delete/6\>delete
> > L3v3http://192.168.1.236/mailusers/usergroup/edit/7\>edithttp://192.168.1.236/mailusers/usergroup/delete/7\>deleteAdminsV6http://192.168.1.236/mailusers/usergroup/edit/8\>edithttp://192.168.1.236/mailusers/usergroup/delete/8\>deleteL4Vodafonehttp://192.168.1.236/mailusers/usergroup/edit/9\>edithttp://192.168.1.236/mailusers/usergroup/delete/9\>deleteVCNONetworkhttp://192.168.1.236/mailusers/usergroup/edit/12\>edithttp://192.168.1.236/mailusers/usergroup/delete/12\>delete
> > given). in Symfony\Component\HttpKernel\HttpKernel-\>handleRaw() (line 157 of vendor/symfony/http-kernel/HttpKernel.php).

# Answer
The error message is not pointing in the right direction. It should say:

"The controller must return a render array"

For example the most basic one:

```
return [
  '#markup' => '<p>This is html markup</p>',
];

```

Usually the render array is more complex, for example to build a table, see https://www.codimth.com/blog/web/drupal/render-table-drupal-8

The error message is raised by Symfony, and from the stand point of Symfony this is correct. A controller must provide a response, but Drupal has extended the response handling to look for render arrays, that are then used to generate a response with the rendered html. If you don't provide a render array, then there is no response and then this error message will come up.
> 11 votes

---
Tags: forms, 8
---


# Question
Title: How to use EntityFieldQuery::fieldCondition for entity reference field?
Suppose, we have an entity "*song*", that has an entity reference field, called "*authors*":

I added a filter for this field as a group of checkboxes:

After the user submits the form with checkboxes group, it must be used inside `WHERE` condition for the list of songs. So, I added the following code:

```
//query to get the list of entities
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'song');

if(!is_null($form_state['input']['field_authors'][LANGUAGE_NONE]))
{
    $query->fieldCondition('field_authors', /* what to put here? */,
            $form_state['input']['field_authors'][LANGUAGE_NONE], 'in');
}

```

I don't understand, what value to put into column parameter. I tried `target_id`, but it doesn't work. Here is the description of `field_data_field_authors` table:

```
DESCRIBE field_data_field_authors;
+-------------------------+------------------+------+-----+---------+-------+
| Field                   | Type             | Null | Key | Default | Extra |
+-------------------------+------------------+------+-----+---------+-------+
| entity_type             | varchar(128)     | NO   | PRI |         |       |
| bundle                  | varchar(128)     | NO   | MUL |         |       |
| deleted                 | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id               | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id             | int(10) unsigned | YES  | MUL | NULL    |       |
| language                | varchar(32)      | NO   | PRI |         |       |
| delta                   | int(10) unsigned | NO   | PRI | NULL    |       |
| field_authors_target_id | int(10) unsigned | NO   | MUL | NULL    |       |
+-------------------------+------------------+------+-----+---------+-------+

```

# Answer
You need to use `'target_id'`

Your code should by this:

```
//query to get the list of entities
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'song');

if(!is_null($form_state['input']['field_authors'][LANGUAGE_NONE]))
{
    $query->fieldCondition('field_authors', 'target_id',
            $form_state['input']['field_authors'][LANGUAGE_NONE], 'in');
}

```

You can found a good explanation here:

How to use EntityFieldQuery with a simple text field?
> 3 votes

---
Tags: 7, entities
---


# Question
Title: How to use the Features module in a 3 dev environnement?
Working on a project, making heavy use of Features, there is sometimes 3 devs for this application.

We have tried a few approaches, but when we merge our git branches it seems we often 'over-write' each other's feature changes. Conflicts abound, breaking the feature module making it painful to use, it seems.

Features is really an awesome timesaver for configuration for one on projects, and I am quite sure there is a way to tackle this.

Is there a workflow or procedure that reduces risks of conflicts and overwrites?

Any clues on features is welcome.

# Answer
> 20 votes
Welcome to the land of **F**eatures **C**onfiguration **M**anagement, aka **FCM**! It is not only about Features, and not about ***Configuration Management*** (as introduced in Drupal version 8). Instead, it is a special case of **S**oftware **C**onfiguration **M**anagement, aka **SCM**. Mostly because Features can be considered as a code generator, whereas that generated code needs to be migrated through multiple environments. Read on for more details.

# 1 - Pros and cons of using Features

### Advantages of using Features

* Automate the deployment of changes applied to a Drupal development site to one or more target Drupal (pre-) production sites (instead of manual deployment).
* Facilitates sharing (shipping) of ongoing Drupal development between Drupal developers / site builders (eg to make some View(s) created by a views expert available to a Drupal Themer working in another development site to theme that view).
* Great integration with both GIT and Drush for shipping a copy of the code generated by Features (on the development site) to selected target (pre-) production sites.

### Disadvantages of using Features

* Avoiding Feature **Conflicts** and/or managing Feature **Dependencies** can be challenging!
* It's not easy to start using Features on an existing (production) site.
* Install/enable of the Features module is easy (just a module), but to learn to use Features correctly is a major challenge.

# 2 - Techniques for features packaging

Using Features it is up to your own imagination how to package (compose) the content of a feature. Here are some techniques that can be used for it.

### A single super feature

This is a pretty simple packaging technique: everything is packaged together in a single feature (some call it the "God" feature ...). Seems easy, pretty forward, etc. But this technique also leads to "conflicts" (as explained below) more or less right away ...

A good usecase for this appears to be when creating a "Drupal distribution", where all users of it are assumed to use the same set of modules, configuration, etc. If however such distribution consists of multiple website functionalities (to not use the word "features" ...), it seems more appropriate to split such features in multiple features, as explained below.

### Based on website functionality

This packaging technique creates a separated feature for each functionality of a website, such as:

* Feature A = implement a "**\*Gallery**".
* Feature B = implementg a "**\*Blog**".
* Feature C = implement a "**\*Event Calendar**".

### Based on Drupal admin sections

This packaging technique creates separated features for each of the (major) admin sections of a Drupal website that is used to create the site, such as:

* All required modules are contained in feature A,
* All base field definitions are contained in feature B,
* All content types are contained in feature C,
* All permissions are contained in feature D,
* All roles are contained in feature E,
* All variables are contained in feature F,
* All (custom) Views are contained in feature G,
* All (custom) Rules are contained in feature H,
* Etc.

The above list is virtually unlimited: in the end you could even think of it as 1 feature for each Drupal admin menu option ... if you want to go that far.

IMO it is also the most recommended approach to package features.

# 3 - Reducing the probability of conflicts in Features and/or GIT

### Do not reuse fields

Quite a few conflicts seem to be caused by reusing fields among multiple content types. E.g. in content type A you have a field with machine name `field_somefield`, which is also used as field in content type B with the very same machine name `field_somefield` but which as another field type and/or some other field setting(s) that are different.

By not reusing fields among content types, you avoid running in this issue. Have a look at an interesting naming convention for the machine name of your content types and fields as shown in table of Wrapping Information Architecture and Documentation, which is part of the articles about "Relativity Model for Drupal". For more details on that refer to my answer to "How do I model content (types) from a database-centric point of view?".

### Split features depending on who works on what

If multiple people are working on a single site, the amount of conflicts can be reduced by organizing (= creating separate) features based on who is working on what. An illustration of this could be as in this example:

* Views goes in feature A,
* Rules goes in feature B,
* Charts goes in feature C,
* Anything about **Theming** goes in feature D,

# 4 - Recommended Drupal environments

Everything above should help to somehow facilitate the usage of Features. However, to ensure that things will work as expected (designed), you also need to have an appropriate set of environments (logically related Drupal websites) for basically these reasons:

* merge functionality provided by multiple features.
* predict and resolve conflicts.
* end-user testing of all merged features that are certified to not have any conflicts.

In the ideal world, these logically related Drupal websites should be configured, and used, like so:

1. **Personal Dev Site** \- each website developer has a separated dev site. When some part of the development is ready to be shared with somebody else, an appropriate feature is created, which is shipped to the staging environment.
2. **Sandbox Site** \- this is a Drupal environment which only contains Drupal core, used to unit test the completeness of a single feature. Should a feature, accidentally, have some unexpected dependencies (eg some module the feature depends on, which is not enabled in the Sandbox), then this is where that dependency will become clear.
3. **Staging Site** \- here is where one or more features (created in a dev site) are delivered to. It could be just some hotfix for some production problem, or it could be where all development for a new release of the website is consolidated. If any conflicts between multiple features do exist, then this is the environment where they will first show up ... and need to be resolved somehow.
4. **QA Site** \- after the Staging environment is considered stable, it's time to move on with the relevant features and make them available also at some higher level where they can be used for QA testing, acceptance testing, volume testing, etc. At this level you should be extremely careful in allowing any additional changes (if any). Because any such change may invalidate all prior testing efforts already completed in this environment.
5. **Shadow Production Site** \- To prepare the activation in real production, you might want to first further promote the relevant features to an environment that is considered a copy (shadow) of your real production environment. If at this point during the migration process anything still breaks, then that is a red flag to revert some of your prior steps. Get it fixed, and try again, until all parties involved approve the changes.
6. **Production Site(s)** \- If you completed all prior steps, then this step should be self explaining, and pretty easy. Depending on your needs, this could be a single site, or something equivalent to Drupal's Multi-sites whereas all the sites involved are running the very same versions of all features.
7. **Baseline Site** \- In my experience, there are not many (if any at all) Drupal implementations where this type of site is used (also). It is simply a copy of the Production Site(s), but available to the Drupal developers, testers, etc that can be used to verify what the production sites look like, or to perform user training, etc. And any time a new development cycle is started, the components of a site that will be impacted (need to be changed) should be "copied somehow" using this Baseline Site as input, with as target a **Personal Development Site**.

Obviously, the above inventory of types of Drupal sites is like the ideal world. Depending on the size of your development team, and / or the available budgets to create and maintain them, not all of them may be used (or affordable). This inventory is modelled after best practises in the area of SCM, used in mostly all huge/global corporations (banks, airlines, etc).

# 5 - Related modules

### Strongarm

The Strongarm module allows for exporting variables (of modules which store their settings in variables) with the Features module.

### Node Export

The Node export module allows users to export nodes and then import it into another Drupal installation.

### Role Export

The Role Export module allows roles to have machine\_names and generates a unique role id (rid) based off of the machine\_name. Roles can be exported with Features and get the exact same rid if imported on other sites.

### Features Banish

The Features Banish module allows for completely excluding individual features components from the features UI and features exports. Here is a quote about it from its project page:

> This module is useful when there are features components that you want to make sure NEVER get exported. If you are using features for site building or deployment then you've probably ran into the issue of someone accidentally exporting timestamp variables like cron\_last or update\_last\_check. You may also want to banish permissions for developer modules so they don't get caught up with the rest of the site permissions you want to export. Banished items will not show up in your feature module OR ANY OTHER FEATURES MODULE, so use with caution. For a central list of features that should never be exported, see https://www.drupal.org/node/2400531

### BEAN

The Bean module makes your blocks exportable. Here is a quote about it from its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. This module only started as of D7, but it has been included with Drupal 8 core already. The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved).

### Habitat

The Habitat module makes most sense in a Features-based workflow. Here is a quote about it from its project page:

> In a multi-environment setup (e.g. prod, test, dev, local) there are some modules that you'd like to always be enabled or disabled on certain environments. Each time you sync a database down though you have to re-enable/disable the same modules. Worse, you get lazy and keep development modules enabled on production.
>
> Habitat provides settings to enable or disable certain modules on each environment (habitat). Just set a variable with e.g. $conf\['habitat'\] = 'local'; in your settings.php file (the actual variable to use there is configurable for your current workflow). The disabling/enabling modules is done on hook\_init.

# 6 - Recommended resources:

# 7 - Possible alternatives to using Features

If you're not able, or willing (yet), to use Features, then you may want to check to what extend the approaches/modules below may provide some type of alternative.

### Manual Export/Import

These are the commonly known facilities (to avoid the word *features* ...) available via the admin UI, for modules such as Rules, Views, etc (incomplete list!).

### Bundle copy

Some people consider the Bundle copy module as a possible alternative. It has export/import support for:

* Node types.
* Taxonomy.
* User.
* Field API fields.
* Field groups.

# Answer
> 7 votes
Merge conflicts are probably going to be a given when multiple developers are integrating their configuration into a Feature. I wrote up several guidelines for reviewing feature code, but I think the most important is this:

### Only commit intended code changes.

What does this mean? This means that each developer **must** review code before committing. There is no "magic" to prevent unintended code changes without a developer being cautious.

* Review code changes with `git diff`.
* Make a quick diff patch using `git diff > blah.patch`, and manually modify the patch to only include the intended configuration changes.
    + Things such as "mtime", comments in view exports in the info file need not be included in the commit.
    + I've become quite adept at reviewing blocks of configuration code diffs over time. It is easier now to spot superfluous changes in views or panels, and a quick `10dd` in vim gets rid of the change in a patch (for example).
    + I think "Oh, hey, I didn't change anything to do with fields, so I won't commit `featurename.features.field_base.inc`."
* Never ever use `git commit -a`. This is a terrible practice that should be stricken from use. Always add and commit explicitly!
* Use `git rebase` on *local* git branches to make sure the feature is most up-to-date.
* A git merge strategy may also help when actually doing a merge:
    + `git merge -s recursive -X patience` (requires git 1.7+ iirc).

Finally consider adding social restrictions to developers so that a developer must have their code reviewed before merging into trunk/stable either with patch review or pull request. People will be angry about social restrictions, but they should be angry at themselves for not reviewing their code.

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


# Question
Title: Entity Tokens + Date Field + Custom Format... unable to use spaces
I have a content type (Question of the Week)... with a Date field (Used for "Publish Date". Questions won't be published until that date).

I am trying to custom format the Title for it without changing the default (Long, Medium, Short) date formats.

For "Pattern for the title"...
If I \[node:field-jcqotw-date:custom:l\] it shows the day (ex: Sunday).
If I \[node:field-jcqotw-date:custom:lF\] it shows the dayMonth, no space (ex: SundayJune).
If I \[node:field-jcqotw-date:custom:l F\] it shows "\[node:field-jcqotw-date:custom:l F\]" (ex: SundayJune).
If I \[node:field-jcqotw-date:custom:l F\] it shows "Sunday June" (ex: SundayJune).

I've tried "l F", 'l F', l\ F, (non breaking space), (Space), etc... Nothing I do seems to let "Custom" use a space.

Edit: After some research... it seems to be an Entity Tokens + CCK Date Field issue... I'll have to put an issue up in those places.

Why can't I use a space in the "Custom format"?

Also... I've created a "Date Type" simply called "myDate" =\> 'l F j, Y' ('Sunday June 5, 2011'). Is there a way to get Token to show that format? Long, medium, raw, short... "myDate"...

Edit: Updated Title and Question to be more correct. The problem has something to do with Entity API, Context, Date Field

# Answer
> 5 votes
In this commit to Date module, token integration was removed, because field tokens aren't working yet.

The error you got it reproducible with an older copy of Date module, but doesn't seem to be related at all to Automatic Nodetitles, just Date/Token.

I would wait until the above Token issue and the Date issue Re-Add Field Token Support are committed.

# Answer
> 2 votes
This is actually a core bug that spaces cannot be used in 'dynamic' tokens. You may want to try the patches available in http://drupal.org/node/1035292.

# Answer
> 0 votes
You can also insert the token multiple times, each time inserting only one part of your date format. The spaces between are then correctly interpreted.

```
<div class="posted-on">%node:created:custom:M %node:created:custom:j, %node:created:custom:Y</div>

```

---
Tags: 7, datetime, tokens
---


# Question
Title: Primary admin actions block on view dissapears if change path
There is a "primary admin actions" block in the seven theme (provided by the Drupal 8 standard install profile) which only shows up if my view if the path is "admin/content" but if I change the path to anything else, the block is gone. where is this configured ?

# Answer
> 4 votes
The LocalActionsBlock is a block plugin that displays menu action links for a given route based on the LocalActionManager::getActionsFromRoute method.

The route that corresponds to the path `/admin/content` has action links, but whichever route that corresponds to the path you are using does not have any action links defined.

Action links are defined in `MODULENAME.links.action.yml` file.

If the desired outcome is to have the local actions that correspond to `/admin/content` on a different path, then a module should be created that defines additional action links for those routes.

---
Tags: views, 8, routes, blocks
---


# Question
Title: 8 - Is there a drush command to reset a module's config back to install defaults?
I'm working on a custom module in Drupal 8 and have nested the config a bit, but getting errors and want to just reset the config for that module completely.

# Answer
I guess it doesn't provide drush integration yet, but have a look at https://www.drupal.org/project/config\_update

It provides a UI to compare and revert configuration with the defaults provided by a module.
> 3 votes

---
Tags: 8, drush
---


title: Print current base language in tpl.php

text:
# Question
Title: Print current base language in tpl.php
I statically added a link to /cart on the *page.tpl.php* template file. Since it's a multi language website, the link doesn't always work.

How do I print a link that consider the currently used language?

# Answer
If you want to display the cart link in a template you better do it with `l()` or `url()`.

```
<ul>
<li><?php print l(t('Cart', 'cart')) ?></li>
<li><a href="<?php print url('cart') ?>">Cart</a></li>
</ul>

```
> 9 votes

# Answer
This should work in your page.tpl.php

```
global $language;
global $base_url;
//get the current language
$current_lang = $language->language;
//get the default language
$default_language = language_default();

switch($current_lang) {
  case($default_language):
    $url = $base_url."/cart";
    break;
  default:
    $url = $base_url."/". $current_lang ."/cart";
}

```

I added the `language_default()` part as per Clive suggestion. You'll find more information on `global $language`.
> 4 votes

# Answer
If you just need to print "en" or "nl" somewhere, depending on the current language:

```
<?php
  global $language ;
  $curlang = $language->language;
?>

This is the prefix of the current language: <?php print $curlang; ?>

```
> 3 votes

# Answer
cptstarling is correct. I was getting error's back from SEO reports asking for Language declarations, and simply created a custom HTML.tpl.php theme template that included:

```
<!DOCTYPE html lang="<?php echo $language->language; ?>">

```

I did not declare a variable, as this was the only location that I needed the PHP language to be displayed.
> 0 votes

---
Tags: 7, theming
---


title: Add custom views options

text:
# Question
Title: Add custom views options
I am trying to add some custom view options. I am not even sure if what I'm trying to do is possible.

Basically I want to put a custom option under the **Other** category.

It would look like:

*My custom options*: disabled

When the user clicks on "disabled", it should show a custom form where the user can set some settings for that view.

I have looked into this, but couldn't find anything that would let me add custom options here.

# Answer
What you're actually looking to do is to implement a custom Views Display Extender plugin (https://api.drupal.org/api/views/views.api.php/group/views\_plugins/7.x-3.x).

It's not particularly trivial and I got most of my information from this wonderful tutorial here: How to write a Views Plugin Display Extender (D7) by Bryan Ollendyke

Here's a basic outline:

-create a custom module (let's call it mymodule) and implement hook\_views\_api().

```
/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule'),
  );
}

```

-Create a mymodule.views.inc file (remembering to add the file to your mymodule.info file) and implement hook\_views\_plugins(). It should look something like this:

```
/**
* Implements hook_views_plugins().
 */
function mymodule_views_plugins() {
  $path = drupal_get_path('module', 'my_module');
  $plugins = array();

  $plugins['display_extender'] = array(
    'mymodule' => array(
      'title' => t('Some Setting'),
      'help' => t('A description of the setting.'),
      'path' => $path,
      'handler' => 'mymodule_views_plugin_display_extender',
    ),
  );

  return $plugins;
}

```

-Note the "handler" index in the above array. You'll need to implement that in a file called mymodule\_views\_plugin\_display\_extender.inc (again, remembering to add that in your mymodule.info file). The implementation should look something like this:

```
class mymodule_views_plugin_display_extender extends views_plugin_display_extender {
  /**
   * Provide a form to edit options for this plugin.
   */
  function options_definition_alter(&$options) {
    $options['my_setting'] = array(
      'default' => 0,
    );
  }

  /**
   * Provide a form to edit options for this plugin.
   */
  function options_form(&$form, &$form_state) {
      parent::options_form($form, $form_state);

      if ($form_state['section'] === 'mymodule') {
        $form['my_setting'] = array(
          '#type' => 'checkbox',
          '#title' => t('Some Setting'),
          '#description' => t('A sample checkbox.'),
          '#default_value' => $this->display->get_option('my_setting'),
        );
      }
  }

  /**
   * Handle any special handling on the validate form.
   */
  function options_submit(&$form, &$form_state) {
    $this->display->set_option('my_setting', $form_state['values']['my_setting']);
  }

  /**
   * Provide the default summary for options in the views UI.
   *
   * This output is returned as an array.
   */
  function options_summary(&$categories, &$options) {
    $options['mymodule'] = array(
      'category' => 'other',
      'title' => t('Some Setting'),
      'value' => ($this->display->get_option('my_setting')) ? 'Yes' : 'No',
      'desc' => t('Set a setting.'),
    );
  }

}

```

After all that your mymodule.info file should look something like this:

```
name = My Module
description = Sample views display extender
core = 7.x
version = 7.x-1.0

dependencies[] = views

files[] = mymodule.views.inc
files[] = mymodule_views_plugin_display_extender.inc

```

If that all works out, you should see a setting show up under "Other" (you can change that using the 'category' in the options\_summary implementation in mymodule\_views\_plugin\_display\_extender.inc.

After that, in your module, you can access the option from the view using something like:

```
$view->display_handler->get_option('my_setting');

```

For instance, if you were implementing \`hook\_views\_post\_execute().

```
/**
 * Implements hook_views_post_execute().
 */
function mymodule_views_post_execute(&$view) {
  $my_setting = $view->display_handler->get_option('my_setting');
}

```
> 1 votes

# Answer
The form ID of the view edit form is `views_ui_edit_form`

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_ui_edit_form')
  {
        $other = &$form['displays']['settings']['settings_content']['tab_content']['details']['columns']['third']['collapse']['other'];
        $other['custom']['#theme'] = 'views_ui_display_tab_setting';
        $other['custom']['#description'] = 'Custom';
        $other['custom']['#link'] = '<a href="' .  base_path() . '/node/1" title="Get information on how to theme this display" id="views-page-1-custom">Custom</a>';

  }

}

```

The form item for the OTHER section is

```
['displays']['settings']['settings_content']['tab_content']['details']['columns']['third']['collapse']['other']

```

so in the function this form element is taken into the `$other` variable as reference for ease of use.

This one simply adds a link to the node/1 you can edit it to do what you want. And the example does not take ajax into concern you can print out the $other variable to get an idea of what all details are given and how it all works.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Mailchimp programatic subscription and updates of existing users
I'm using Mailchimp module for user registration and at this page I found a function for registering users programatically:

```
mailchimp_subscribe (
    $list_id,
    $email,
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name, // fields in your mailchimp list
        'LNAME' => $last_name,
    ),
    false,
    false
)

```

In my mailchimp account I have defined new field of radio buttons type (field name 'type' with options 'client' and 'expert').

I have 2 questions:

* How should be the 'type' column in `mailchimp_subscribe()` function specified?
* How could be an existing user in mailchimp programatically updated?

# Answer
> 1 votes
The key in the array can be `MERGEX` (where Xth field number in MailChimp) or whatever custom tag name you've set in MailChimp (it shows up as \*|TAGNAME|\*" in MailChimp field settings) . The MailChimp dropdown user fields aren't like Drupal's (with select fields containing a key/value pair); all it needs is the literal display value of option.

`mailchimp_subscribe()` eventually calls `MailchimpLists::addOrUpdateMember()` in its dependent library. Thus, the logic of adding/updating is handled for you in the function.

To put that together in the above code snippet:

```
mailchimp_subscribe(
    $list_id,
    $email,  //Will add or update $email in $list_id based on subscriber status
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name, // fields in your mailchimp list
        'LNAME' => $last_name,
        // Assuming the 'type' field in MailChimp is your 3rd field
        'MERGE3' => 'client',
    ),
    false,
    false
);

```

---
Tags: emails
---


# Question
Title: Share fields between commerce variation types?
I have 12 types of products that have 4 similar property fields, for example: weight, force, collar size, noise level. There are many other different fields for each of the 6 types.

Is there a way to set up Drupal Commerce variation types so 'weight' for example is the same fieldname on all these products types?

I'd like to do this so that a faceted search can allow customers to search for weights or collar sizes, etc, across all product types.

Or any other ideas on how to structure this? (using Drupal 7 and Drupal Kickstart 2)

# Answer
> 1 votes
Assuming you are asking about Drupal 7, the answer is yes. You can share base field types across product bundles. Each bundle will have it's own instance of the field, but the data will be stored in the same underlying storage system.

You can add them by choosing from the list of fields under "Add existing field" on the field editing screen:

---
Tags: 7, commerce, search
---


# Question
Title: How to set up multiple occurences of same event with RNG?
I am trying to find out what is the easiest way to handle this use case:

We host the same event in different cities. So event A will go to city X then city Y then city Z.

So all the information about the event is the same, just different dates and locations.

It is the same event so nobody will attend more than once. But many people will consider which city to attend the event (it may be the same distance if they go to city Y or city Z).

I assume each event should have its own RNG registration.

But what would be the easiest way to set up this thing with all the shared information?

# Answer
> 1 votes
I think you will need to create new event entities for each city, add a location field (Address?) and a date field, so your users can tell the difference. You will need to make the discovery layer before the event pages show a clear difference between your events: You could have a table view with the city and data in respective columns. Or a Google maps layer with pins for each city. Where each pin is a link to each event entity page.

If you are looking to enforce restrictions on people from attending both events, you can try RNG Conflict. However I don't think that is necessary in your case.

---
Tags: rng
---


# Question
Title: How can I export content-type and content from one site to another?
I got handed over a drupal 7 site with two branches, one is now in production and other is dev. I am working on dev and had to create new content types and made changes existing content types.

In the meantime other users made some changes to content-type and content. Administration want to merge content types and retain the latest content.
What is the workflow to do this kind of stuff.
In the past I only had to clone whole site so I used rsync to sync file and export/import db.

This looks like way more complicated than I anticipated as both sites have same content types but with some degree of variation in field names and types.

From my current Drupal knowledge it seems like a very complex task.

Where should I start and which approach/technique should I use?

I went through other answers and found that the Node export module can export the node but how can I export the content and map the fields from one content type to another ?

# Answer
> 1 votes
# Node Export

Looks like you are already familiar with the Node export module, allows users to export nodes and then import it into another Drupal installation.

# Bundle copy

The Bundle copy module has support for export/import of:

* Node types.
* Taxonomy.
* User.
* Field API fields.
* Field groups.

---
Tags: 7, importing-exporting
---


# Question
Title: How to print the node body in a custom block?
I am trying to print the node body in a custom block, but it's not showing up. I'm I doing this correctly?

```
$refer = $_SERVER[HTTP_REFERER];
$parsed = parse_url($refer);
$alias = array_pop($parsed);
$dst = \Drupal::service('path.alias_manager')->getPathByAlias($alias , $langcode);
$nid = array_pop(explode('/', $dst));
$dest_node = node_load($nid);

$body = $dest_node->get('body')->getValue();
print $body; //have tried other printing methods also but invain

```

Thanks

# Answer
> 2 votes
`$dest_node->get('body')->getValue();`

this will return an array. So,`$body` is an array. If you want the Body field values, then get it by accessing the proper index of the `$body` array. i.e **$body\[0\]\['value'\]**

just replace `print $body;` with `print $body[0]['value'];`

---
Tags: 8, blocks
---


title: Alter page content using custom module

text:
# Question
Title: Alter page content using custom module
I'm writing a custom module which will process information using an external service and need to display any errors thrown by this service.

I already have a variable containing error messages.

How can I target a page body markup to show the error message? I have tried hook\_page\_alter but failed not knowing if a page body can be processed at this stage.

Thanks

# Answer
> 1 votes
You can use the Drupal message system.

Ex: `drupal_set_message(t('Error message goes in here'), 'error');`

In you case: `drupal_set_message(t($yourvariable), 'error');`

---
Tags: 7, theming
---


# Question
Title: How to implement Instant Notifications to 'follow' or 'like' nodes?
My employer has a social intranet site with 1000s of users, groups, communities and blogs. Users are free to 'follow' or 'like' nodes, blogs and other users, subscribe to communities, join groups etc.

What I'm trying to achieve is the following.

1. User A posts some content, for the sake of argument a blog.
2. User B comes along, reads the blog and 'follow's it.
3. User A needs to be notified that the blog has been followed.
4. User B needs to be notified in the future that the blog has changed, been added to, modified or even simply 'like'd by another user.

This is all good with small numbers of people involved. However, as mentioned earlier, there are 1000s of people on this site. When a lot of users follow a blog or 'like' something, they all need to be informed of the update and it is here that I'm having the problem. The regular nodeJS module for Drupal seems to blanket broadcast to every active session on the site at that moment, and let Drupal figure out who needs to be told but the load on the server is massive as most of the notifications are unnecessary.

I've had a look at the Actions NodeJS module as well which at first glance seemed to be absolutely ideal as I know I can tell it to just get a list of the users who are followers, loop through each one and tell them that something has happened. The problem with this lies in that the initial event, 'like'ing something for example, does not complete until everyone has been notified so the system hangs until exit.

For example,

1. User A posts some content.
2. Users B through X all 'like' that content.
3. User Y comes along and 'like's it as well.

Users A through X all get told that User Y has liked it but the 'like' operation from User Y's point of view does not complete until the last person has been notified. Again, this is not so much of a problem with a handful of users, but with possibly 1000s this becomes an issue to be dealt with now. If it's just an implementation issue and you know how to solve this, shout up.

Some 'back of a crisp packet' calculations say that the slow part of the process is the looping through of all the relevant users. Accessing the database to get the list of relevant UIDs is pretty quick as is the sending of the actual message.

Am I looking at writing some custom code to handle this? Am I going to be better off handing the work to a separate thread to process the notifications? Is this even possible? Does a module exist already that can perform this task efficiently? This is greenfield by the way. Anything will be considered for this task as performance on the site with the current implementation is 100% toilet. It may be that the current implementation is flawed and the existing modules are perfectly capable of accomplishing this, this is a real possibility. However, from what I've read, I don't think that this is the case.

I don't want to blanket broadcast to the site and let Drupal sort out who needs to see the notification as that means many unnecessary hits on the server but if that's how things are supposed to work, please let me know. I'd much rather just target a list of users and hit them, that seems to me to be the better way forward. All hints, tips, ideas and suggestions are welcome. The NodeJS module allows a system-wide broadcast which is pretty much instant across all open sessions. What I'd love is to be able to harness that performance but with a targeted list of UIDs.

Other info you may need to know.

* I have a dedicated Node JS server at my disposal
* The main Drupal site has 3 web heads but only using 1 at the moment for testing. Usual behaviour is 'round robin'ned across the 3 servers.
* The site is hosted on a private network
* No anonymous users allowed; everyone has to log in to use the site so everyone has a UID.
* PHP v5.3.3
* Drupal v7
* NodeJS v0.10.36

Upgrading the software isn't really an option but if it absolutely 100% can not be accomplished any other way, then it becomes an issue for discussion for those on a higher pay grade to me. I've already said that I think things should be upgraded, particularly NodeJS, but there is definite resistance to this, don't ask me why.

# Answer
# Option 1: Message stack

Have a look at the Community documentation about the Message Stack, which consists of these modules (quotes are from the module's project page):

* Message:

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

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

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

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium. And it will make you well positioned for Drupal 8 also (because of he modules' object orientated architecture). Even though there is no such a thing as 8.x-dev yet, the Message code repository already does contain something already (not yet for the 2 other modules though). I assume the `wip` part of the branch name stands for 'Work In Progress'.

If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the *Answers Notification* sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

# Option 2: Menu badges

A completely different approach is to use the Menu Badges module, which you could use to configure them using the integration of it with the Views module.

Some more details about some views that seem appropriate for your case:

* A view of users "following" a node, whereas "following" could be implemented using the Flag module. A variation of this could be "nodes liked by users".
* A view of changed nodes followed by the current user.

For more details, refer to my answer to "How to create a basic message - notifications system displaying a real time message counter badge?".
> 0 votes

---
Tags: 7, notifications, nodejs
---


title: Commerce Point of Sale (POS)

text:
# Question
Title: Commerce Point of Sale (POS)
I do not know how to use the last module "project/commerce\_pos" version 2 dev. I can not even get a view point of sale. Can you tell me how to access the point of sale? there is no documentation.  I know how to access the settings, but I can not access the page above to use the pos

I do not see how to add products

# Answer
You will find some documentation in the README.txt that comes with the module.

To use the module, you first need to get drupal commerce up and running. Then your products will be available for sale via the POS, once installed.

Also look at the commerce pos issues queue as v2 still has some issues being resolved.

I have used 7.x-1.x-dev extensively, and you can access the POS via: admin/commerce/pos

The configuration is via: admin/commerce/pos/config

If you have any specific question, please amend your original question.

Edit:

1. Make sure you are using the latest 7.x-2.x-dev version to get latest fixes.
2. Also see this issue relating to products not showing: By default, no products are available in the POS
3. POS is available via: admin/commerce/pos
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How to display content type name on related image?
I have create one content type\[article\] with two by default field i.e. title and body. In body summary part we have contain one image on left side and description on right side.

I want display the content type name on that image which is show in summary part. Please help

# Answer
> 0 votes
1) In FIELDS add Content Type as a field and check mark exclude from display.

2) Make sure Content Type is ABOVE Body field, other wise you will not get Content Type token as a replacement pattern.

3) Click on your Body field and in REWRITE RESULTS, checkmark override output of this field.

Then use the replacement patterns.

The above is for Drupal 8, in Drupal 7 it would be `[type_1] [body__summary]`

You can add html if you need ex: `<div class="type">[type_1]</div> [body__summary]`

> **Bonus:** You could remove the image from Summary Part and instead add an image field to your content type. Then add your image as a field to your view. Then when you REWRITE RESULTS you can add the image there `[type_1][field_image][body__summary]`

---

**PS:** Next time tell us which Drupal version you are using!

---
Tags: views, theming
---


title: Hook is not invoked

text:
# Question
Title: Hook is not invoked
I have a function I want to execute when a user finishes a quiz.

```
function wilson_random_task_quiz_finished($quiz, $score, $session_data) {
  // ...
}

```

When a user finishes a quiz, I think the hook should be invoked from the following code of the Quiz module.

```
/**
 * Actions to take at the end of a quiz
 *
 * @param $quiz
 *  The quiz node
 * @param $rid
 *  Result id
 * @param $score
 *  Score as a number
 */
function quiz_end_actions($quiz, $score, $session_data) {
  // Call hook_quiz_finished().
  module_invoke_all('quiz_finished', $quiz, $score, $session_data);

  if (!empty($quiz->aid)) {
    actions_do($quiz->aid, $quiz, $score, $session_data);
  }

  return $score;
}

```

My hook is not invoked. What am I missing?

# Answer
> 1 votes
2pha is correct: `quiz_end_actions()` is not necessarily called, contrary to what the code workflow could seem. In fact, `quiz_take_quiz()` contains the following code.

```
// Remove session variables, save $rid
$session_data = $_SESSION['quiz_' . $quiz->nid];
unset($_SESSION['quiz_' . $quiz->nid]);
// NOTE: End actions might redirect the user somewhere. Code below this line might not get executed...
quiz_end_actions($quiz, $score, $session_data);

```

As the comment says, end actions could redirect the user to somewhere else, and the code after it would not be executed.

---
Tags: 7, hooks
---


# Question
Title: How to change "Save Draft" value on Webform?
I want to change the button text value from "Save Draft" to "Save". How can I target the button (CSS or custom module works for me)? I used to target forms like this:

```
$form['actions']['submit']['#value'] = 'Ask question';

```

As there are multiple submit buttons, I don't know how to target the one with the class "webform-draft form-submit".

```
function customisations_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_88') {

  }
}

```

# Answer
> 2 votes
Code to change the text for Save Draft button is:

```
function customisations_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_88') {
    $form['actions']['draft']['#value'] = 'Save';
  }
}

```

This would change only for **Save to Draft** button. In order to change the submit button text of the webform, we can use the configuration of the Webform to change it. URL for the same is **node/88/webform/configure**.

Hope that this helps.

---
Tags: 7, webforms, forms
---


# Question
Title: views contextual filter by current year missing granularity
In a view I need a contextual filter: all nodes with creation date in the current year.

In D7 i was able to provide the current date as default value and set a granularity for the date, e.g. the year.

In D8 I don't have any options to granular configure the filter.

Is there any other solution to set this contextual filter?

# Answer
> 3 votes
I think you need to use specific granularity field that you wish to add. like there are multiple option given in contextual filter which are as under.

* Created year \>\> Content Date in the form of YYYY.

in that field you can specify in "Provide default value" as "current date".

---
Tags: 8, views
---


# Question
Title: {{ front_page }} doesn't work in partial
I have a partial, partials/header.html.twig, I am calling on one of my sub pages with this code.

```
{% include directory ~ '/partials/header.html.twig' %}

```

Whenever I use `{{ front_page }}` inside the partial to link back to the front page, it doesn't work, but it works on everything else. I have been searching for an answer all morning but can't seem to find anything.

# Answer
Try:

```
<a href="{{ path('<front>') }}" title="{{ 'Some Title'|t }}" rel="home" class="some-class">
     Some Text
    </a>

```
> 1 votes

---
Tags: theming, 8
---


# Question
Title: How so I execute $query->orderBy('FIELD(node.nid, 5,12,3,6)', 'ASC')?
I am currently converting code from Drupal 7 to Drupal 8. So far I am unable to find resources on how to convert the call to `orderBy()` which uses an expression.

```
$query->orderBy("FIELD(node.nid, '5,12,3,6')", 'ASC');

```

Based on D8 Select::orderBy, it only accepts alias or fields.

What is the code I should use in Drupal 8?

# Answer
> 6 votes
I did a workaround by implementing a CASE statement then sorting by the value.

```
$query->addExpression("
    CASE node.nid
        WHEN 5 THEN 1
        WHEN 12 THEN 2
        WHEN 3 THEN 3
        WHEN 6 THEN 4
        ELSE 5
    END
", 'order_field');

$query->orderBy("order_field", 'ASC');

```

Hopefully they'll add another function to handle these special statements in the future.

---
Tags: database, 8
---


# Question
Title: hierarchical select not working in multistep form
I have created multistep form with help of

link and created hierarchial select in step 1.It is working for step 1 but when i click next button and goes to step2, and return step1 it is not working.

Please Help.

# Answer
> 0 votes
I'm hoping this will add more info to the above reporting, even though we have different websites, to hopefully enable a fix.

I have a 2 level hierarchical select taxonomy. Refer to it in my people pages. Created as Term Reference - Hierarchical Select. When registering a user go to select this term, which is supposed to save term lineage, forces user to select term from deepest level.

* Selecting from pulldown menu and clicking add, it appears that the item is being selected correctly and shows up below the pulldown menu, with the option to remove the selection. I then save, it says everything was saved correctly. I scroll down to my selection, and it says nothing has been selected.

* If I go to a view based off of this information, it indeed finds no data.
* I do get data if I change the field from hierarchical select to List Select or check boxes and have the view be rendered taxonomy term. If I have to use List Select I will have to change the terms to include the first level since it doesn't show or save this way. This list is going to expand as new courses get added. We can't do check boxes perpetually. It will get crazy long.

- I did find this **error message log**, but I don't know after which change this appeared. Notice: Undefined index: value in views\_handler\_filter\_term\_node\_tid-\>value\_validate() (line 219 of /var/www/vehicledev\_ccom\_nh/sites/all/modules/views/modules/taxonomy/views\_handler\_filter\_term\_node\_tid.inc).

Severity notice

---
Tags: forms, taxonomy-terms
---


# Question
Title: Formatting is lost after publishing the content
I am using WYSIWYG with TinyMCE in my Drupal 7 website. I observed that the copied content looks similar in editor and even preview also looks nice. But all the formatting is lost after publishing the content.

To debug the issue, I checked the HTML and found that the actual style is present in the code. Please see the below screenshot-

I noticed that after disabling the color property of `background` for `td` element, the original color appears. Please see the below screenshot-

Please suggest any way to solve this issue.

# Answer
> 0 votes
Is it possible your input format is a "filtered HTML"? If I'm not in wrong it removes a lot of attributes: try to change it to "Full HTML" and verify the behaviour...

---
Tags: wysiwyg
---