title: How do I override field output (twig)?

text:
# Question
Title: How do I override field output (twig)?
I have a field\_category field and the field--default--node--field-category--insight.html.twig template is used to display the output of the field. I want to override the field link attribute.

The content of field--default--node--field-category--insight.html.twig is the following.

```
    {#
    /**
     * @file
     * Theme override for a field.
     *
     * To override output, copy the "field.html.twig" from the templates directory
     * to your theme's directory and customize it, just like customizing other
     * Drupal templates such as page.html.twig or node.html.twig.
     *
     * Instead of overriding the theming for all fields, you can also just override
     * theming for a subset of fields using
     * @link themeable Theme hook suggestions. @endlink For example,
     * here are some theme hook suggestions that can be used for a field_foo field
     * on an article node type:
     * - field--node--field-foo--article.html.twig
     * - field--node--field-foo.html.twig
     * - field--node--article.html.twig
     * - field--field-foo.html.twig
     * - field--text-with-summary.html.twig
     * - field.html.twig
     *
     * Available variables:
     * - attributes: HTML attributes for the containing element.
     * - label_hidden: Whether to show the field label or not.
     * - title_attributes: HTML attributes for the title.
     * - label: The label for the field.
     * - multiple: TRUE if a field can contain multiple items.
     * - items: List of all the field items. Each item contains:
     *   - attributes: List of HTML attributes for each item.
     *   - content: The field item's content.
     * - entity_type: The entity type to which the field belongs.
     * - field_name: The name of the field.
     * - field_type: The type of the field.
     * - label_display: The display settings for the label.
     *
     *
     * @see template_preprocess_field()
     */
    #}
    {%
    set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    ]
    %}
    {%
    set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
    ]
    %}
    {% if label_hidden %}
      <div{{ attributes.addClass(classes) }}>
        <div class="field__items">
          {% for item in items %}
            <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
          {% endfor %}
        </div>
      </div>
    {% else %}
      <div{{ attributes.addClass(classes) }}>
        <div{{ title_attributes.addClass(title_classes) }}>{{ label }}</div>
        <div class="field__items">
          {% for item in items %}
            <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
          {% endfor %}
        </div>
      </div>
    {% endif %}

```

This template outputs the following.

```
    <!-- THEME DEBUG -->
    <!-- THEME HOOK: 'field' -->
    <!-- FILE NAME SUGGESTIONS:
       x field--default--node--field-category--insight.html.twig
       * field--default--node--insight.html.twig
       * field--default--node--field-category.html.twig
       * field--default--field-category--insight.html.twig
       * field--default--insight.html.twig
       * field--default--field-category.html.twig
       * field--default.html.twig
       * field--theme-ds-field-default.html.twig
       * field--node--field-category--insight.html.twig
       * field--node--field-category.html.twig
       * field--node--insight.html.twig
       * field--field-category.html.twig
       * field--entity-reference.html.twig
       * field.html.twig
    -->
    <!-- BEGIN OUTPUT from 'themes/custom/myproject/myproject_child/templates/field/field--default--node--field-category--insight.html.twig' -->
      <div data-quickedit-field-id="node/1/field_category/en/teaser" class="field field--name-field-category field--type-entity-reference field--label-hidden">
        <div class="field__items">
                  <div class="field__item"><a href="/myproject/insights/1" hreflang="en">Legal Services</a></div>
              </div>
      </div>

    <!-- END OUTPUT from 'themes/custom/myproject/myproject_child/templates/field/field--default--node--field-category--insight.html.twig' -->

    <!-- THEME DEBUG -->
    <!-- THEME HOOK: 'field' -->
    <!-- FILE NAME SUGGESTIONS:
       x field--default--node--field-category--insight.html.twig
       * field--default--node--insight.html.twig
       * field--default--node--field-category.html.twig
       * field--default--field-category--insight.html.twig
       * field--default--insight.html.twig
       * field--default--field-category.html.twig
       * field--default.html.twig
       * field--theme-ds-field-default.html.twig
       * field--node--field-category--insight.html.twig
       * field--node--field-category.html.twig
       * field--node--insight.html.twig
       * field--field-category.html.twig
       * field--entity-reference.html.twig
       * field.html.twig
    -->
    <!-- BEGIN OUTPUT from 'themes/custom/myproject/myproject_child/templates/field/field--default--node--field-category--insight.html.twig' -->
      <div data-quickedit-field-id="node/1/field_category/en/teaser" class="field field--name-field-category field--type-entity-reference field--label-hidden">
        <div class="field__items">
                  <div class="field__item"><a href="/myproject/insights/2" hreflang="en">Product Liability</a></div>
              </div>
      </div>

    <!-- END OUTPUT from 'themes/custom/myproject/myproject_child/templates/field/field--default--node--field-category--insight.html.twig' -->

```

I used the Pathauto module to generate the aliases for the category with the pattern /insights/\[term:tid\]. I have tried to use the question mark in the pattern to generate the path aliases like /insights?tid=\[term:tid\], but the question mark is not allowed by the module.

How do I rewrite the field attribute in `<div class="field__item"><a href="/myproject/insights/2" hreflang="en">Product Liability</a></div>` to make it `<div class="field__item"><a href="/myproject/insights?tid=2" hreflang="en">Product Liability</a></div>`?

# Answer
You're just looking for the taxonomy term in your template, it can be found on the URL object like this:

```
  <div class="field__item"><a href="/myproject/insights?tid={{ item.content['#url'].routeParameters.taxonomy_term }}" hreflang="en">Product Liability</a></div>

```
> 2 votes

# Answer
I've used `{{ kint(item.content) }}` to debug the data like below.

```
 <div{{ attributes.addClass(classes) }}>
        <div class="field__items">
          {% for item in items %}
             {{ kint(item.content) }}
             ...
             ...

```

and i got the output like below

and I've updated the template file to get the output according to my requirement.

***field--default--node--field-category--insight.html.twig***

```
    {#
    /**
     * @file
     * Theme override for a field.
     *
     * To override output, copy the "field.html.twig" from the templates directory
     * to your theme's directory and customize it, just like customizing other
     * Drupal templates such as page.html.twig or node.html.twig.
     *
     * Instead of overriding the theming for all fields, you can also just override
     * theming for a subset of fields using
     * @link themeable Theme hook suggestions. @endlink For example,
     * here are some theme hook suggestions that can be used for a field_foo field
     * on an article node type:
     * - field--node--field-foo--article.html.twig
     * - field--node--field-foo.html.twig
     * - field--node--article.html.twig
     * - field--field-foo.html.twig
     * - field--text-with-summary.html.twig
     * - field.html.twig
     *
     * Available variables:
     * - attributes: HTML attributes for the containing element.
     * - label_hidden: Whether to show the field label or not.
     * - title_attributes: HTML attributes for the title.
     * - label: The label for the field.
     * - multiple: TRUE if a field can contain multiple items.
     * - items: List of all the field items. Each item contains:
     *   - attributes: List of HTML attributes for each item.
     *   - content: The field item's content.
     * - entity_type: The entity type to which the field belongs.
     * - field_name: The name of the field.
     * - field_type: The type of the field.
     * - label_display: The display settings for the label.
     *
     * @see template_preprocess_field()
     */
    #}
    {%
    set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    ]
    %}
    {%
    set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
    ]
    %}
    {% if label_hidden %}
      <div{{ attributes.addClass(classes) }}>
        <div class="field__items">
          {% for item in items %}

          {% if item.content['#url'].routeParameters['taxonomy_term'] is defined %}

            <div{{ item.attributes.addClass('field__item') }}><a href="{{ base_path }}insights?tid={{ item.content['#url'].routeParameters['taxonomy_term'] }}">{{ item.content['#title'] }}</a></div>

           {% else %}

                <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>

            {% endif %}

          {% endfor %}
        </div>
      </div>
    {% else %}
      <div{{ attributes.addClass(classes) }}>
        <div{{ title_attributes.addClass(title_classes) }}>{{ label }}</div>
        <div class="field__items">
          {% for item in items %}
            <div{{ item.attributes.addClass('field__item') }}>{{ item.content }}</div>
          {% endfor %}
        </div>
      </div>
    {% endif %}

```
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Search API isn't returning results with words in the title
I just installed search api and setup a server and index. Then I setup a Views page and exposed the search filter option. Searching all fields work, but for some reason its not searching the title. What could be the issue? I tried turning all fields off on the index and just left the title field option and its still not working.

# Answer
I had to turn on the setting *Search on parts of a word* on the Server's page in order to get it to work. Now it searches titles. I'm not sure why it doesnt search titles with that unchecked.
> 0 votes

---
Tags: views, search
---


# Question
Title: get commerce order variables dpm without loading order again
I try to get order variables using devel module from inside custom order template page--admin--commerce--orders\__%.tpl.php.

I use code `$order = commerce_order_load(123);`

Question: is it possible not to load full order again and get the variables ? (assuming that I am on order page, the variables should be loaded anyways correct?) Thank you for explanation.

# Answer
> 0 votes
Don't worry about it.

Loaded entities are cached for at least that request, so you're either loading up an entity which hasn't been loaded yet, in which case the DB load is inevitable, or you're simply retrieving the already-loaded entity from static cache.

As an aside, don't load up entities in template files - always do it in a preprocess hook and pass the variable in.

# Answer
> 1 votes
You need to use `commerce_order_load` to load the order with all the data. If the order already has been loaded somewhere else on the page, the order won't be loaded twice, but the order will be fetched from static cache instead. So it's fine to load the same order multiple times.

If you do need to clear the cache, (maybe you need to compare the order to what is in the datebase to see what has changed), then you can use use `commerce_order_load_multiple` or call `entity_load` directly.

---
Tags: 7, theming
---


# Question
Title: Submit handler in hook_form_alter not working in d8
I have **hook\_form\_alter** as follows :

```
function auto_ga_form_alter(&$form, &$form_state, $form_id) {
    global $base_url;
    if($form_id == 'node_p_request_form' || $form_id == 'node_p_request_edit_form' || $form_id == 'node_f_pro_request_form' ) {
      $form['#submit'][] = 'custom_form_submit_fn';
      $form['actions']['submit']['#submit'][] = 'custom_form_submit_fn';
   }
}

function custom_form_submit_fn(&$form, $form_state) {
  echo 'reached in submit handler';exit;
}

```

But its not going to the submit handler . both usage ( **`$form['#submit'][] OR $form['actions']['submit']['#submit'][]`**) of submit handlers not working

And idea ??

# Answer
> 2 votes
What you are doing looks like it should work.

Doing an `echo` is undetecable in the submit handler, since Drupal will do a redirect after the POST request and thus clearing all of the output generated but Drupal in the actual submit handler.

A simple way to test if the submit handler is called or not is to insert a `die()`

Reasons for submit handler not being called could be:

* You submit the form with a button you haven't added a submit handler on and that already have one or more attached to it.
* Another alter hook removes your submit handler (unlikely)

# Answer
> 0 votes
In Drupal 8 the parameters are changed

Please add following parameters in hook\_form\_alter and example\_form\_submit\_handler:

```
hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

example_form_submit_handler($form, \Drupal\Core\Form\FormStateInterface $form_state)

```

Hope this will help you.

---
Tags: 8, forms
---


# Question
Title: Adsense tokens "[adsense:XxY:SlotID]" in node content aren't being replaced by ads
I've added adsense tags in my node body/content and I'm using Full HTML as text format.

For this Full HTML ipnut format I've enabled "replace adsense tags". I've also given it the highest "Priority" so that it is done before anything else related to formatting node content.

In the end, adsense tokens are printed as is "\[adsense:XxY:SlotID\]" and no ads. From developer console I can see one error that states:

```
TagError: adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them.

```

I'm quite sure that if these tokens were replaced by ad markup that error wouldn't show up in the developer console.

And to be honest, I'm not sure which modules is responisble for formatting adsense tokens into adsense markup i.e. which modules provides.

# Answer
> 0 votes
Wow, finally solved. Since pages are rendered via Panels the solution was to check "Clean" option from Panel content manager to the node body which removes "dangerous" markup.

In other words it seems like node body doesn't respect text format settings when rendered via Panels. Or at least not all of it without checking this option.

---
Tags: javascript, input-formats, tokens
---


title: Create block content programmatically

text:
# Question
Title: Create block content programmatically
I've created a custom block type.

I want to create a block with 19 translations programmatically. I've seen that you can use Block::create() method...for which I can neither find proper documentation nor examples. Could anyone provide an example?

Fyi my code is:

```
Block::create([
  'id' => 'my_header_dk',
  'settings' => [
    'id' => 'my_header',
    'label' => 'My header',
    'label_display' => FALSE,
    'provider' => 'my_block',
    'status' => TRUE,
    'langcode' = 'da',
    'icon' => [
      33,
     ],
    'header' => 'This is the header text',
    'link_text' => 'Click here',
    'visibility' => [],
    'region' => 'header',
    'plugin' => 'my_header',
    'theme' => 'my_theme',
    'status' => TRUE,
 ])->save();

```

# Answer
If you want to create content for the custom block type `basic`:

```
use Drupal\block_content\Entity\BlockContent;

$block = BlockContent::create([
  'info' => 'block 1',
  'type' => 'basic',
  'langcode' => 'en',
]);
$block->save();

```

And add a french translation:

```
$french_block = $block->addTranslation('fr', ['info' => 'bloc 1']);
$french_block->save();

```

Custom block types are content, not configuration. See this answer https://drupal.stackexchange.com/a/218244/47547
> 9 votes

---
Tags: 8, blocks
---


# Question
Title: how can i get Drupal webform confirmation message on popup?
I have been surfing for a solution since yesterday, got hell lot of irrelevant solution. My requirement is very simple,

> I just want to get the conformation message(Thank you, your submission has been received.) in a popup window.

tried several modules not satisfied. Friends please help me out, its urgent for me.

# Answer
> 2 votes
Here is an example using a custom module (called it `wcm_overlayer`). Basically, this will show the confirmation message in an overlayer using the jQuery Fancybox library. For the webform configuration (under `form settings`), you need to set the `redirection location` setting to `No redirect (reload current page)`.

**wcm\_overlayer.module**

```
/**
 * Implements hook_init()
 */
function wcm_overlayer_init()
{
    // Add library & js file
    drupal_add_library('wcm_overlayer', 'fancybox');
    drupal_add_js(
        drupal_get_path('module', 'wcm_overlayer') . '/js/wcm_overlayer.js');
}

/**
 * Implements hook_node_view()
 *
 * @param type $node
 * @param type $view_mode
 * @return boolean
 */
function wcm_overlayer_node_view($node, $view_mode)
{
    // Verify if webform is attached to a node
    if (!isset($node->webform)) {
        return false;
    }

    // Retrieve confirmation message
    $confirmation_message = check_markup(
        $node->webform['confirmation'], $node->webform['confirmation_format']);

    // Retrieve all status message
    $messages = drupal_get_messages('status');

    // None is found, don't do anything
    if (!isset($messages['status'])) {
        return false;
    }

    // Loop through all messages and get confirmation message
    foreach ($messages['status'] as $message) {
        if ($message !== $confirmation_message) {
            drupal_set_message($message);
            continue;
        }

        $found = true;
    }

    // Confirmation message is not found, don't do anything
    if (!isset($found)) {
        return false;
    }

    // Confirmation message is found, pass this as a setting
    drupal_add_js(array(
        'wcm_overlayer' => $confirmation_message,
    ), 'setting');
}

/**
 * Implements hook_library()
 *
 * Define the jQuery Fancybox 1.3.4 as a library
 * @return string
 */
function wcm_overlayer_library()
{
    $path = drupal_get_path('module', 'wcm_overlayer');

    $libraries['fancybox'] = array(
        'title' => 'jQuery Fancybox',
        'version' => '1.3.4',
        'js' => array(
            $path . '/js/vendor/jquery.easing.js' => array(),
            $path . '/js/vendor/jquery.mousewheel.js' => array(),
            $path . '/js/vendor/jquery.fancybox.js' => array(),
        ),
        'css' => array(
            $path . '/css/vendor/jquery.fancybox.css' => array(),
        ),
    );

    return $libraries;
}

```

**js/wcm\_overlayer.js**

```
(function ($) {
    Drupal.behaviors.wcm_overlayer = {
        attach: function(context, settings) {
            if (!settings.hasOwnProperty('wcm_overlayer')) {
                return false;
            }

            this.showOverlayer(settings.wcm_overlayer);
        },
        showOverlayer: function(message) {
            $(window).load(function() {
                $.fancybox({ content: function() {
                        return $(message);
                }});
            });
        }
    };
}) (jQuery);

```

Hope it helps.

# Answer
> 0 votes
Mike Vranckx's solution is an elegant solution but unfortunately i was unable to get it to work properly. For some reason, the wcm\_overlayer.js showed me an error message "The requested content cannot be loaded. Please try again later."

After searching a while, i found an alternative solution on http://fancyapps.com/fancybox/ API documentation , that eventually not only solved this error but also opened up other configuration option, like padding :

```
(function ($) {
  Drupal.behaviors.webform_popup = {
    attach: function(context, settings) {
      if (!settings.hasOwnProperty('webform_popup')) {
        return false;
      }

      this.showOverlayer(settings.webform_popup);
    },
    showOverlayer: function(message) {
      $.fancybox.open([
        {
          content : message
        }],
        {
          padding : 20
        }
      );
    }
  };
}) (jQuery);

```

It might help solving others with the same issue. More info on http://fancyapps.com/fancybox/#license

---
Tags: webforms, javascript
---


# Question
Title: How to clean up multiple Drush Composer installs?
I've been setting up a new Ubuntu 16.04 laptop for Drupal development. I had trouble installing Drush using Composer, but eventually got things working. Today, while setting up Drush tab completion, I discovered five instances of drush.complete.sh:

`$ locate drush.complete.sh
/home/monkey/.composer/global/drush/drush/vendor/drush/drush/drush.complete.sh
/home/monkey/.composer/vendor/bin/drush.complete.sh
/home/monkey/.composer/vendor/drush/drush/drush.complete.sh
/home/monkey/.config/composer/vendor/bin/drush.complete.sh
/home/monkey/.config/composer/vendor/drush/drush/drush.complete.sh`

*\*cough\** I think I need to clean things up and start from scratch. How can I correctly uninstall all these Drush instances?

# Answer
> 1 votes
`composer global remove drush/drush` will get rid of either the ~/.composer or the ~/.config copy, depending on your current configuration. However, if you are no longer using the components that you installed via `composer global`, you can just use `rm -rf` to delete the directories you don't need, which is `vendor` and `bin` in `~/.composer` and `~/.config`.

---
Tags: drush, composer
---


# Question
Title: How to properly inject services into other services
I'm trying to figure out how to inject Drupal services into a custom service class. The class in question is my `MenuService` which builds an associative array of menu items which will be encoded to json and sent as a response for my custom REST endpoint ( `/api/menu/{menu_name}` ).

As a part of that, I need three classes:

`\Drupal\Core\Path\AliasManager`

`\Drupal\Core\Menu\MenuTreeParameters`

`\Drupal\Core\Menu\MenuLinkTree`

Any help on tracking down the `MenuTreeParameters` service would be helpful. I don't see it on this list. If it's not a defined service, can it be injected?

*Note: Made some edits as I answered most of my own question*

# Answer
Alright, I think I figured it out. It should look something like this:

I couldn't find the service name anywhere for `MenuTreeParameters` so it's omitted in the examples for now.

I setup my menu service in `rest_api.services.yml`

```
services:
  rest_api.menu_service:
    class: Drupal\rest_api\Services\MenuService
    arguments: ['@path.alias_manager', '@menu.link_tree']

```

And created my service:

```
namespace Drupal\rest_api\Services;

use \Drupal\Core\Menu\MenuLinkTree;
use \Drupal\Core\Path\AliasManager;
use \Drupal\Core\Menu\MenuTreeParameters;

class MenuService {

  protected $aliasManager;

  public function __construct(AliasManager $aliasManager, MenuLinkTree $menuTree) {
    $this->aliasManager = $aliasManager;
    $this->menuTree = $menuTree;
    $this->items = array();
  }

```
> 2 votes

---
Tags: dependency-injection, symfony-services
---


# Question
Title: How to attach a date field from another entity to a new form
I am attaching a few fields from the user entity to a custom form with the following:

```
$account = user_load($user->uid);
foreach ($fields_to_collect as $field) {
  field_attach_form('user', $account, $form, $form_state, NULL, [
    'field_name' => $field
  ]);
}

```

This works fine *except* for date fields (I am using the date\_popup widget but I haven't yet narrowed that down as responsible). Attaching a date field results in the following error: `Warning: implode(): Invalid arguments passed in date_limit_format() (line 2262 of sites/all/modules/date/date_api/date_api.module).` The date field is just shown as a text field with the text `Format` shown as a description.

The error is due to `$granularity` being `NULL`. On, for example, the user account edit page which has this field, `$granularity` is something like:

```
[
  'month',
  'day',
  'year'
]

```

Thanks for any help/suggestions.

# Answer
Unsurprisingly, it was my error.

Further up in my function I was building `$form_state` with `form_state_defaults()`. Once I provided a proper `form_state` everything worked as expected.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: making correct return array of ControllerBase
I am new to Drupal 8 and it is hard to comprehend the documentation. I am required to make a custom module. I came across examples in creating custom modules, but I am having difficulty in making the correct return type. For example, consider the code snippet take from doc:

```
<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.
 */

namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {
  public function content() {
    return array(
        '#type' => 'markup',
        '#markup' => $this->t('Hello, World!'),
    );
  }
}

```

In this example, the controller is called when some page (defined in route) is visited. In this case an array is returned with **#type** and **#markup**, whose definition I cannot find anywhere. Similary consider another example:

```
<?php
namespace Drupal\acme\Controller;
use Drupal\Core\Controller\ControllerBase;
class DefaultController extends ControllerBase {
  public function hello($name) {
    // the {name} in the route gets captured as $name variable
    // in the function called
    return [
      '#theme' => 'hello_page',
      '#name' => $name,
      '#attached' => [
        'library' => [
          'acme/acme-styles', //include our custom library for this response
        ]
      ]
    ];
  }
}

```

In this case, the return type is **#theme**, **#name** and **#attached**. These two code clearly shows different return type. As a beginner, I am having difficulty in understanding what to return from function as I cannot see those definitions in the documentation of **ControllerBase** class.

Where in the documentation are these tags defined and how do I use them in different scenarios? Thanks.

# Answer
The return type of a Controller can be either a Response or a render array.

A render array is an array that you see in your code, and this is generally the best thing to return for a visible page as it provides the theme layer with opportunity to render into a template.

Render array types (`#type`) are defined in the Render Arrays docs page. See also the API docs for the RenderElement plugin I linked below.

> The element type. If this array is an element, this will cause the default element properties to be loaded, so in many ways this is shorthand for a set of predefined properties which will have been arranged through a RenderElement plugin.

However the render array could also be defined to use a theme/template directly with (`#theme`), which is defined as

> A single theme function/template which will take full responsibility for rendering this array element, including its children. It has predetermined knowledge of the structure of the element.

So the render array return for a Controller will depend on how you wish to structure the content that is displayed in the main content area.
> 6 votes

---
Tags: theming, 8
---


# Question
Title: Twig template suggestions for user default, compact, and user account view modes
Is there a way i can create a diffrent template than user.html.twig to have a diffrent View mode when i use default, compact or user account

Something like user--compact.html.twig ?

# Answer
You can do this by creating a theme suggestion alter hook in your theme.

```
/**
 * Implements hook_theme_suggestions_user_alter().
 *
 *   An array of alternate, more specific names for template files or theme
 *   functions.
 */
function MYTHEME_theme_suggestions_user_alter(&$suggestions, $vars, $hook) {

  // Define the view mode.
  $mode = $vars['elements']['#view_mode'];

  // Create a theme hook suggestion which has the view mode name in it.
  $suggestions[] = 'user__' . $mode;
}

```

Note, `$vars['elements']['#view_mode'];` was derived from using `kint($vars)` under this function to see the view mode array in user.

You can add this code to your theme's .theme file and then clear cache. Once you clear cache, you will then see the new theme suggestions appear within Twig debug.

Note, in my case, I am in "full view mode so that's why `user--full.html.twig` shows up. If you are view the user in compact mode, then a suggestion of `user--compact.html.twig` will show up.
> 15 votes

---
Tags: theming, users, 8, hooks
---


title: How to export a module's configuration?

text:
# Question
Title: How to export a module's configuration?
I've set up a module on one site and want to export it to another site. From researching, I understand you can use Features to do this. However there is no documentation detailing this.

Any suggestions about how to do this?

# Answer
> 0 votes
Many

Drupalise Me Feature introduction

Phase 2 feature slides.

Code Karate Feature Series Video

Acquia Video Series

As far my experience features is not just about how to do it, but also how well you do it. Doing it in wrong way can make the development nightmare. Once you get acquinted with features, I would recommend you to look for features best practices. Do's and Don'ts for feature module.

---
Tags: 7, features, configuration
---


# Question
Title: Protect previous migrated field values on system of record migration
I have a successful migration of content type A, B and C. In the migration of C, I have entity reference fields that get populated with the correct values coming from migration A and B.

My reference fields is a multi value node entity reference field. To prevent the values being over ridden from my previous migrations, I use the system of record method.

https://www.drupal.org/node/1117454 https://www.drupal.org/node/2550939

The example is very specific to a commerce migration.

```
// If "updating" a product, protect these fields.
        // We know its updating if the product exists in the database with the sku.
        // Migrate updates by deleting an entire entity and replacing with
        // the new one. We circumvent the removal of the values of these
        // fields by pulling them and overriding the defaults provided
        // in the mapping.
        // You could do the same with a nid id found with a title, or something similar.
        // $row->migrate_map_sourceid1 is usually the entity id you're looking for,
        // our example here uses a commerce_product and loads it with the provided sku
        if ($product = commerce_product_load_by_sku($row->sku)) {
            // Use the metatdata wrapper to pull values
            $product_wrapper = entity_metadata_wrapper('commerce_product', $product);

            // field_stock
            // Some products have a NULL stock, lets keep the zero default if NULL
            if ($product_wrapper->field_stock->value() !== NULL) {
                $row->stock = $product_wrapper->field_stock->value();
            } else { $row->stock = 0; }

            // field_max
            $row->max = $product_wrapper->field_max->value();
        }

```

I am not sure how I would use my prepare row, current content types, their ids etc to remove the current values, update the new values, and then add the previous ones again? Or am I misunderstanding how this is suppose to work? Thanks in advance!

# Answer
> 0 votes
My solution was to use the prepare($node, stdClass $row). This basically takes the current values and joins them to the new ones.

https://www.drupal.org/node/1222668#comment-4795190

---
Tags: migrations
---


# Question
Title: How to restrict access to a non-drupal url on a site's domain?
So, I've just run into this issue with a drupal 7 site that I am maintaining. Access to the mailing list URL www.XXXmysite.com/mailman/listinfo is accessible to the general public. Is there someway of restricting access to this URL through drupal's permissions? This isn't obvious how to do because the mailman program isn't a part of drupal, I'm not sure where the program actually runs from, but the url is mapped from the site's domain.

# Answer
> 0 votes
Nope. It sounds like your web server has the mailman web interface alias to that path. If that's the case, Drupal is never evoked so it wouldn't have any say on how that request is handled (i.e. **index.php?q=mailmain/listinfo** isn't executed for page handling).

You'll need look at configuring your web server to remove your alias, or remove it for your hostname.

---
Tags: 7, users
---


# Question
Title: generate multiple custom blocks from a single api call
I have created a custom module that generates a single custom block based on content retrieved from a remote API. The content is currently displayed in a single contiguous block above the main content.

It works great, however, I am now being asked to split up the custom block content on the page. Essentially, I need to move some of the content into a sidebar and some into a smaller block at the top of the page.

The simple way to do this I guess is to create 2-3 custom blocks through the plugin system and then place them in the desired regions I create on the page templates. The problem with this is that each block would be calling out to the remote api so I would go from a single API call to 3 or even more on the same page. The remote API we are using just returns the entire set of content so I would be loading the same thing 3 or more times.

What I would really like to be able to do is keep my existing block class (in whatever form) and pass that same single API call to 3 seperate templates that can be placed as three separate blocks.

How do I do this?

Alternatively, is is there some way to generate the API call through a function in the `.theme` file in my theme (abandoning my custom module completely) and then just pass the variables directly to the page rather than going through the block system? I could also live with that though i am not sure how to do it.

# Answer
> What I would really like to be able to do is keep my existing block class (in whatever form) and pass that same single API call to 3 seperate templates that can be placed as three separate blocks. How do I do this?

This is possible. Add a configuration option to the block class in `blockForm()` and then use this option in `build()` to change the content and template. Then place the block three times and choose for each instance a different option. To avoid calling the remote API three times in one request use `drupal_static()`.

> Alternatively, is is there some way to generate the API call through a function in the .theme file in my theme (abandoning my custom module completely) and then just pass the variables directly to the page rather than going through the block system?

This is no problem. You can put three variables in `mytheme_preprocess_page()` and use them directly in `page.html.twig`.

Think about caching. You can cache the remote API call with `\Drupal::cache('data')->set()` with a certain expire time. In a block this is not necessary, you can set a cache max-age and as long the block stays in the cache the remote API is not called.
> 3 votes

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


# Question
Title: Keep info in one place to be use in several locations
As per title, what is the best practice, say if i want to save/keep info such as details of the website in one place so that when i want to change something i dont have to go thru every pages/blocks to amend it.

For example : company phone number.

Right now i have it in footer and contact page. Is there a way to change it so that every place that have the phone number will automatically change too?

# Answer
There really isn't a best practice. I'd say it depends on the intent and what part of Drupal's CMS functions best fit your scenario. For example:

* Is it a part of distributed theme template? It could be a theme settings.
* Is it a part of functional application logic? It could be a variable added to a site configuration form.

For most practical purposes of boilerplate phone info in a footer, I'd think most people would go for block with a region placed in the theme's footer, but Drupal is flexible by design so you could see alternative decisions depending on the intent.
> 1 votes

---
Tags: emails
---


# Question
Title: Correct way to change the active Drupal theme programmatically?
What is the correct way to change the active Drupal theme programmatically?

# Answer
**Drupal 6 solution:**

You want to make sure you change the global `$custom_theme` variable fairly early in page execution.

```
global $custom_theme;
$custom_theme = 'garland';

```
> 16 votes

# Answer
I know you asked how to do it programattically, but in case that's your solution, not the actual problem, you can also use the ThemeKey module. This allows you to set conditions which, when met, changes the theme. You can make conditions based on paths, taxonomy, content type, create or edit date and more. You can also add in the Themekey Properties module module to get even more options.

Again, I know this isn't programmattically, but I'm not sure if the real question behind your question is how to change themes based on conditions.
> 16 votes

# Answer
The best way to do this is to create an update hook in a module:

```
function yourmodule_update_N() {
  variable_set('theme_default','yourtheme');
}

```
> 15 votes

# Answer
# Changing the active theme via Drush

```
drush vset theme_default garland
drush vset admin_theme garland
drush cc all

```

---

# Changing the active theme via a module

The basics of changing the default theme and administration theme:

```
// Changes the theme to Garland
variable_set('theme_default', $theme_default);
// Changes the administration theme to Garland
variable_set('admin_theme', $admin_theme);

```

Here's a small function to set back the themes safely to default Drupal themes like Bartik or Garland (tested in Drupal 6 and 7):

```
/**
 * Set the active Drupal themes (the default and the administration theme) to default ones.
 * Tested in Drupal 6, 7 (but possibly working in version 8 too according to the documentations [some similarities between 7 and 8]).
 */
function TESTMODULE_set_active_theme_to_default($affect_admin_theme = TRUE) {

  // Provides a list of currently available themes.
  $list_themes = list_themes(TRUE);
  // 6, 7, 8, etc.
  $major_version = (int)VERSION;

  $theme_default = isset($list_themes['bartik']) ? 'bartik' : 'garland';
  $admin_theme   = isset($list_themes['seven']) ? 'seven' : 'garland';

  // Changes the theme to Garland
  variable_set('theme_default', $theme_default);

  // Changes the administration theme to Garland if argument is TRUE
  if($affect_admin_theme){
    variable_set('admin_theme', $admin_theme);
  }

  // if Switchtheme module (https://drupal.org/project/switchtheme) is enabled, use it
  if (module_exists('switchtheme')) {
    if (empty($_GET['theme']) || $_GET['theme'] !== $theme_default) {
      $query = array(
        'theme' => $theme_default
      );
      // in D6, drupal_goto's second argument is the query string,
      // in >=D7, a more general $options array is used
      if($major_version < 7){
        $options = $query;
      }
      else{
        $options = array('query' => $query);
      }

      drupal_goto($_GET['q'], $options);
    }
  }

  drupal_set_message(t('Default theme has been changed to %theme_default, administration theme has been changed to %admin_theme.', array(
    '%theme_default' => $theme_default,
    '%admin_theme' => $admin_theme
  )));

}

```

You can call it in a hook\_init() implementation (comment it out after it's not needed):

```
/**
 * Implements hook_init()
 */
function TESTMODULE_init() {
  // ATTENTION! Comment out the following line if it's not needed anymore!
  TESTMODULE_set_active_theme_to_default();
}

```
> 8 votes

# Answer
In Drupal 7, use `hook_custom_theme()`:

```
/**
 * Implements hook_custom_theme()
 * Switch theme for a mobile browser
 * @return string The theme to use
 */
function mymodule_custom_theme()  {
    //dpm($_SERVER['HTTP_USER_AGENT']);
    $theme = 'bartik'; // core theme, used as fallback
    $themes_available = list_themes(); // get available themes
    if (preg_match("/Mobile|Android|BlackBerry|iPhone|Windows Phone/", $_SERVER['HTTP_USER_AGENT'])) {
        if (array_key_exists('custommobiletheme', $themes_available)) $theme = 'custommobiletheme';
        else { drupal_set_message("Unable to switch to mobile theme, because it is not installed.", 'warning'); }
    }
    else if (array_key_exists('nonmobiletheme', $themes_available)) $theme = 'nonmobiletheme';
    // else, fall back to bartik

    return $theme;
}

```

Adapted from \<emoticode /\>

Return the machine-readable name of the theme to use for the current page.

The comments for this function may be worth reading:

> This hook can be used to dynamically set the theme for the current page request. It should be used by modules which need to override the theme based on dynamic conditions (for example, a module which allows the theme to be set based on the current user's role). **The return value of this hook will be used on all pages except those which have a valid per-page or per-section theme set via a theme callback function in hook\_menu(); the themes on those pages can only be overridden using hook\_menu\_alter().**
>
> Note that returning different themes for the same path may not work with page caching. This is most likely to be a problem if an anonymous user on a given path could have different themes returned under different conditions.
>
> Since only one theme can be used at a time, the last (i.e., highest weighted) module which returns a valid theme name from this hook will prevail.
> 8 votes

# Answer
# For Drupal 8:

## In settings.php

```
$config['system.theme']['default'] = 'my_custom_theme';

```

## Update config programatically:

```
\Drupal::configFactory()
->getEditable('system.theme')
->set('default', 'my_custom_theme')
->save();

```
> 4 votes

---
Tags: theming, 6
---


# Question
Title: How to set the user must login as member before purchase?
How do I set the user must login as member before purchase?

I'm using Drupal version 7, with Drupal Commerce.

# Answer
> 2 votes
Use the Commerce Checkout Redirect for implementing this:

> This module redirects anonymous users to a page where they can login or create a new account when they try to checkout.

---
Tags: 7, commerce
---


# Question
Title: How to change the order of fields in field account in the user profile form?
In the user detail screen (user\_profile\_form) there is a field: account.

In this field there a different form fields. How to change the order of these form fields? I would like to group the fields current password, new password and confirmation password together.

I did by form\_alter ...

```
if($form_id == "user_profile_form") {
   dpm($form)
}

```

But then? I do not see any key or weight in this array..

# Answer
You're half-way there: just add something like

```
$form['account']['pass']['#weight'] = -6;

```

(event if you don't see the #weight key) and check the results - in this example you should see the current password field go right below password fields.
> 3 votes

---
Tags: 7, forms
---


# Question
Title: How can I convert special characters to normal characters in an URL query string?
`?` and `=` will be used as parts in my url. In generating the url, I use

`<?php echo l('node/'. $someID .'/delete?destination=chapter/'. $anotherID);?>`. When I check on `Firebug`, the `href` attribute of the link is not the usual `url`, instead of having `?`, it is being replaced with `%3F` and `=` is being replaced with `%3D`. How do I fix this?

# Answer
To generate URL we use url() function. l() function is used to generate a text with link. See the example below:

```
// Generate a Text with link
echo l('Link Text', 'node/' . $nid . '/delete', array('query' => array('destination' => 'chapter/' . $cnid)));

// Generate a Link.
echo url('node/' . $nid . '/delete', array('query' => array('destination' => 'chapter/' . $cnid)));

```
> 1 votes

# Answer
Try:

```
 <?php echo l('/node/'. $someID .'/delete?destination=chapter/'. $anotherID,'/node/'. $someID .'/delete?destination=chapter/'. $anotherID);?>

```

And you will see what Jimajamma is talking about. The first string is converted to special characters to display on the page. The second string becomes the href="" string.
> 0 votes

---
Tags: 6, uri
---


title: Add custom class according to taxonomy

text:
# Question
Title: Add custom class according to taxonomy
I have content type car, which has three fields: car model, year model and category (taxonomy term). In taxonomy term, I have three lists: volvo, toyota and BMW.

In the picture below, I have added a custom class called grid-item and besides that I would like to add a category name such as volvo, toyota or BMW. I would able to add category name if replacement patterns has been available :/

In the source code, you guys can see that I have class grid-item and I want to have a category name accoding to cars next to it.

# Answer
> 3 votes
You add taxonomy filed in view and Exclude from display this field.

---
Tags: 8, views, taxonomy-terms
---


# Question
Title: Form text field is too wide for the side bar
I created custom block for my entity and I want to add this entity creation form to the 2nd sidebar. I managed to do this and this is how it looks like now:

First textfield goes out of bounds, where as second one, which is textarea type, is okay. After looking at Form API, I realized that textarea is re-sizable and textfield is not. How can I solve this? If I put title as text area it doesn't look that nice so I would be very happy if I could stick to textfield and make it fit somehow?

# Answer
> 1 votes
You can use the #size attribute if you are creating the field from `hook_form` function in custom module.Below is the example

```
$form['level_of_effort'] = array(
    '#type' => 'textfield',
    '#title' => t('Level of Effort'),
    '#description' => t('Level of Effort value must be between 0 and 100.'),
   ** '#size' => 3, **
    '#maxlength' => 3,
  );

```

or **you can do the css**, using the field selector and then applying "width:in px"

# Answer
> 1 votes
You can change field size .Default size is 60.You can text field width by css.

---
Tags: 7, forms, blocks
---


title: Exclude title from display not working

text:
# Question
Title: Exclude title from display not working
I want to hide the titles of the webform by using Exclude form display module. I installed and given permission for anonymous user to use it. For all webform I am having a common template file that is webform-form.tpl.php. In this template file I am printing the title of the webform like below

```
print $form['#node']->title;

```

I thought because of this the module is not working, So i decided to check the checkbox of Exclude title from display is checked or not in this template file. I am not getting `exclude_node_title` varibale in my template file. So please help me to get this in template file.

# Answer
I've not gone in detail of the module code, but from brief overview it seems that module doesn't define any variable at template level. You can check if you're able to access `$node->exclude_node_title` variable in template file. If not, then to hide a node title, you can call `_exclude_node_title()` function which determine whether the node title should be excluded. Check the example usage of `_exclude_node_title()` function in `_exclude_node_title_preprocess()` function.

```
/**
 * Remove the title from the variables array.
 * NOTE : Example usage from module.
 */
function _exclude_node_title_preprocess(&$vars, $node, $view_mode) {
  // If node title needs to be excluded from display.
  if (_exclude_node_title($node, $view_mode)) {
    $vars['title'] = '';
    if ($view_mode == 'nodeform') {
      // Prevent access to the title field on nodeform view mode.
      $vars['page']['content']['system_main']['title']['#access'] = FALSE;
    }
  }
}

```
> 0 votes

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


title: multiple selection widget

text:
# Question
Title: multiple selection widget
I am using Drupal 8 and I cannot find where the multiple selection checkbox for my taxomomy field is.

And the result is radio buttons.

# Answer
You have selected field cardinality to one . So its not reflecting checkbox. Please follow the below steps you can achieve what you asked

1. Go to Structure \> Content Type.
2. Select the {{Custom Content Type}} . Click on Manage Fields.
3. Edit the taxonomy Entity Reference field.Click on Field Settings Beside Edit Tab
4. Change Allowed number of values from Limited to Unlimited
> 2 votes

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


# Question
Title: How to custom theme Inline Entity Form (IEF) - using a .tpl.php file
Is there a way to theme the Inline Entity Form (IEF) for example creating a .tpl.php file for that form and just declaring it on the theme's template.php?

I wanted to create a .tpl.php specifically since I want to add in custom codes in the form like, views, a little html, jquery and css.

Any help would be greatly appreciated.

# Answer
> 0 votes
I don't think that Inline Entity form supports that. You could alter the behaviour of the form itself though with

```
 function THEMENAME_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
   // your alters
}

```

---
Tags: theming, forms, entities
---


title: How to format a custom field

text:
# Question
Title: How to format a custom field
excuseme if this question can (seem to) be stupid, but I don't figure how to solve...

Shortly, my custom module:

* exposes a node type
* exposes an entity type
* attach to that node a field containing a set of these entities (by using entity\_reference)

I would like to customise how those entities are visualised in the node view page: I would like to show more info instead of just the entity label.

I read something about `hook_field_formatter_info()`, that seems to be the best solution, but my debugger suggests that is not invoked (neither after a cache clear)... on the other I can't find any info about how to explain this to `hook_theme()`.

The ideal behaviour should be to tell to Drupal:

* use a specific template file to render all fields belonging to a given field instance
* allow a theme to override that representation in a new template file

Do you have a snippet of code or a web resource explaining how to instruct my module to do this?

Thank you

# Answer
> 2 votes
`hook_field_formatter_info()` hook lets Drupal know about the new display denfinition and field settings, you will see your display type under Manage display settings of your content type. However the actual format of the field is returned with help of hook\_field\_formatter\_view.

Example Code

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


# Question
Title: How to fill select options based on previous select?
I'm trying to get the hang of Forms'N'Ajax in Drupal 8.

I have a classic problem with my selects in D8:

```
$form['manufactureYear'] = array(
  '#type' => 'select',
  '#title' => $this->t('Manufacture year'),
  '#options' => $manufactureYears,
  '#required' => TRUE,
  '#ajax' => [
    'callback' => array($this, 'populateDurationYears'),
    'wrapper' => 'edit-loanDurationYears'
  ],
);

```

Then I have a second select:

```
$form['loanDurationYears'] = array(
  '#type' => 'select',
  '#title' => $this->t('Loan duration years'),
);

```

The function **populateDurationYears** is the one that are killing me. I've tried with the ReplaceCommand in a AjaxResponse, but when I submit the form the *loanDurationYears* select is empty.

Can somebody help me here?

**EDIT:** \- If I change *ReplaceCommand* with *AppendCommand* it's almost correct. The code now looks like this:

```
<select id="edit-loandurationyears" class="form-select" name="loanDurationYears" data-drupal-selector="edit-loandurationyears">
  <div>
    <option value="3">3 years</option>
    <option value="4">4 years</option>
    <option value="5">5 years</option>
    <option value="6">6 years</option>
    <option value="7">7 years</option>
    <option value="8">8 years</option>
    <option value="9">9 years</option>
  </div>
</select>

```

What's up with that `<div>`? It messes up the select :-(

**EDIT 2:**

The populateDurationYears method looks like this:

```
$response = new AjaxResponse();
if($maxDurationYears != 0) {
  for($i = $minLoanDurationYears-1; $i < $maxDurationYears; $i++) {
    $option .= "<option value='" . (string)($i+1) . "'>" . (string)($i+1) . " år</option>";
  }
  $response->addCommand(new AppendCommand('#edit-loandurationyears', $option));
}
return $response;

```

# Answer
I've figured it out on how to do this...

I fill out the #options for the second `<select>` when I build the form. I hide it with a #states.

When the user then selects something in the first `<select>` I use the populateDurationYears method to remove invalid options like this:

```
$options = [];
if($maxDurationYears != 0) {
  for($i = $minLoanDurationYears-1; $i < $maxDurationYears; $i++) {
    $options[] = ($i+1) . " years";
  }
  $form['loanDurationYears']['#options'] = $options;
}
return $form['loanDurationYears'];

```

This does the trick :-) No need for AjaxResponse or anything like the ReplaceCommand etc... Keep it simpel Stupid! ;-)
> 2 votes

# Answer
You should use `#prefix` and `#suffix` to add a wrapper around $form\['loanDurationYears'\]. Your code would look like this:

```
$form['manufactureYear'] = array(
  '#type' => 'select',
  '#title' => $this->t('Manufacture year'),
  '#options' => $manufactureYears,
  '#required' => TRUE,
  '#ajax' => [
    'callback' => array($this, 'populateDurationYears'),
    'wrapper' => 'loanduration-wrapper'
  ],
);

$form['loanDurationYears'] = array(
  '#type' => 'select',
  '#title' => $this->t('Loan duration years'),
  '#prefix' => '<div id="loanduration-wrapper">',
  '#suffix' => '</div>',
);

```
> 0 votes

# Answer
The drupal core ajax.js will check the number of elements inside the string you pass to the response. The div container will only be added if you pass more than 1 element. Adding one option at a time will prevent this behaviour. In your case the correct way to go by ajax would be:

```
$response = new AjaxResponse();
if($maxDurationYears != 0) {
  for($i = $minLoanDurationYears-1; $i < $maxDurationYears; $i++) {
    $option = "<option value='" . (string)($i+1) . "'>" . (string)($i+1) . " år</option>";
    $response->addCommand(new AppendCommand('#edit-loandurationyears', $option));
  }
}
return $response;

```
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: Make Flippy links available in page.html.twig
Using the Flippy Module I would like to make the links that it prints in its theme file available in **page.html.twig** because I want to print them in a different region from where the node content gets printed.

The module states: "*If you turn on Flippy for a content type, but hide the pager in the Manage Display page, its links will still be available in the theme layer when it comes time to output node.tpl.php*"

That's correct, using Devel Module enter link description here I used `dpm(content)` on my `node.html.twig`template.

Doing `{{ content.flippy_pager}}` allows me to print the links, but it's all **within** `node.html.twig`.

How could I possible pass that information on to `page.html.twig` since my goal is to print it in a different region from where the node's main content gets printed.

# Answer
I didn't realize the module provides a "Flippy" block.

* Remove "Pager" from `Structure>Content types>MyContentType>Manage display`
* Add block in `Structure>Block layout`. Go to the region you want the links to appear, click `Place block`, search for **Flippy Bock** and you are done.

ps: the answer came from stackoverflow, but I reposted it here just in case it's useful for others too.
> 1 votes

---
Tags: theming, 8
---


title: Theme stylesheets not loaded

text:
# Question
Title: Theme stylesheets not loaded
I am learning Drupal 8 and have installed Drupal 8.1.2 version on XAMP. No theme files are included when page is loaded (viewed source).

When trying to solve this, I changed theme from default bartik to stark. Still no theme files are loaded. And now I am trying to switch it back to bartik, but I am unable to.

"Bartik is now the default theme." is displayed but Stark 8.1.2 (default theme) is default theme.

See screenshot below:

# Answer
> 3 votes
I recommend you use Aquia Dev Desktop, easier to use than Xamp, one click install.

https://dev.acquia.com/sites/default/files/downloads/dev-desktop/AcquiaDevDesktop-2-2016-09-05.exe

Just use that, and it will all work 100% the first time.

Something else you might need to do with Xamp is adjust timeouts ect...with Aquia dev desktop the settings are usually already adapted to Drupal requirements.

# Answer
> 1 votes
Maybe your page is cached. Go to /admin/config/development/performance and hit "Clear all caches".

---
Tags: 8
---


# Question
Title: How to install drush 8 properly on Debian 8?
Finding hundreds of articles and documents about how to install drush and none of it explains where exactly and how properly I got a bit lost.

I've got a Debian 8 system with a root user, NGinx and a ssh user.
Now I'd like to go with drush 8 to be ready for Drupal 8 soon.
But I don't feel like installing git on my server - is this common practice? I usually think the fewer software the better?

So - any chance of installing drush without having git?

Next thing that all instructions seem to forget: As which user do I need to install drush and composer? (I did it now as the ssh user with the result that root can't use drush).

And eventually: Which directory would be correct to have drush installed? /usr/bin/ ? With a symlink? Or directly there? Does the NGinx user (www-data) need to be able to use drush? (I guess yes for drush pm-update?)

Very lost here - hope someone can shed some light.

# Answer
(Updated to fix links and clarify Drush 8 vs 9.)

Debian still (as of February 8th 2018) comes with Drush 5.10 which is completely unacceptable.

There is no reason to use Git to download Drush. Either
> 2 votes

# Answer
\[update\] If you are happy with an older version (Drush 5.10) then you could install from Debian repos.

```
sudo apt-get update && sudo apt-get install drush

```

Note that git is a suggested package but it shouldn't auto install by default. Reference: https://packages.debian.org/jessie/drush

If Drush 5 is too old then you can always re-evaluate your options then...

What version control do you use for your server/CMS/etc? If you don't use version control then I would strongly argue that you should just learn how to use git. IMO it is the most awesome vc system that I have ever used... I would say that using git (let alone installing it) is pretty common dev practice!

Regardless there are possibly ways to install drush without installing git but you could just install git then remove it again after if you don't want it!? AFAIK drush now requires composer to complete the installation and I'm pretty sure that needs git too. So perhaps just bite the bullet...

So my suspicion is that even if it's possible then it will be a lot more painful and a lot more mucking around...

For the record this is how I install drush (latest dev version) then use it to install drupal8:

```
SRC=/usr/local/src
WEBROOT=/var/www/drupal
# install composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

# install drush dev-master
git clone --depth 1 https://github.com/drush-ops/drush.git $SRC/drush
cd $SRC/drush
composer install
ln -s $SRC/drush/drush /usr/local/bin/drush
ln -s $SRC/drush/drush.complete.sh /etc/bash_completion.d/drush

mkdir -p /etc/drush
cat > /etc/drush/drushrc.php << EOF
<?php
// by default use the drupal root directory
\$options['r'] = '$WEBROOT';
EOF

# download latest drupal8 and install
drush dl drupal-8 --destination=$(dirname $WEBROOT)
mv $(dirname $WEBROOT)/drupal-8* $WEBROOT

```
> 1 votes

---
Tags: drush, version-control, composer
---


# Question
Title: drush ard fails with error Database dump failed, drush 5.10.0 drupal 7.39
```
sudo drush ard -v --destination=sites/default/files/sitearchive.tgz

```

fails with error "Database dump failed"

```
Initialized Drupal 7.39 root directory at /var/www/drupal                                                                                [notice]
Initialized Drupal site default at sites/default                                                                                [notice]
php /usr/share/php/drush/drush.php  --backend=2 --verbose --root=/var/www/drupal --uri=http://default  sql-conf   --all 2>&1                                              [notice]
Executing: tar  --exclude "drupal/sites" --dereference -cf /var/www/drupal/sites/default/files/drupal.20161018_203926.tar drupal
Executing: tar  --dereference -rf /var/www/drupal/sites/default/files/drupal.20161018_203926.tar drupal/sites/all
Executing: tar --dereference -rf /var/www/drupal/sites/default/files/drupal.20161018_203926.tar drupal/sites/README.txt
Executing: tar --dereference -rf /var/www/drupal/sites/default/files/drupal.20161018_203926.tar drupal/sites/example.sites.php
Executing: mysqldump --result-file /tmp/drush_tmp_1476823166_5806887e850ef/drupal.sql --no-autocommit --single-transaction --opt -Q  drupal --host=xxxxxx.ceiixl6nbq74.us-east-1.rds.amazonaws.com --port=3306 --user=xxxxxxx --password='xxxxxxxxx'
Database dump failed.                                                                                [error]
Command dispatch complete

```

I haven't really used Drush, but I'm working through migrating a site to Pantheon and this is the way they suggest.

Here is the output of drush status. (the xs are subbed in for identifiable info)

```
sudo drush status
 Drupal version                  :  7.39
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  xxxxx.ceiixl6nbq74.us-east-1.rds.amazonaws.com
 Database username               :  xxxxx
 Database name                   :  xxxxx
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  mytheme
 Administration theme            :  mytheme
 PHP configuration               :  /etc/php5/cli/php.ini
 Drush version                   :  5.10.0
 Drush configuration             :
 Drupal root                     :  /var/www/drupal
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  /tmp

```

Attempting to run the mysqldump command as shown in the output of the drush command (as suggested in the comments) simply returns 'mysqldump: command not found'

Can anyone shed some light on this problem? I have zero experience with drush so I'm not even sure how to troubleshoot it.

I'm happy to provide any additional information deemed useful.

# Answer
> 1 votes
If `mysqldump` is not found, it means that you miss the mysql-client or mysql-client-5.5 package (if you are using Debian). Your version of Drush indicates that you are using Debian as it is severely outdated ;-)

---
Tags: 7, drush
---


# Question
Title: Unable to create multi-site sub-directory in drupal
I need help creating multi-site sub-directory in drupal. I have done all setting changes in localhost windows wamp server don't know what is missing.

let say, mysite is a main site and project1, project2 sub directory. Sharing same code base but different database.

In hosts file i have done the changes like this.

127.0.0.1 project1 127.0.0.1 project2

created project1 and project2 folder under sites folder and added setting files

DocumentRoot "C:/wamp/www/mysite" ServerName project1

Its working fine for http:// localhost/mysite/ and http:// project1/,http:// project2.

But I want to show it in sub-directory like http:// localhost/mysite/project1 or http:// localhost/mysite/project2.

I have tried with doing Apache alias as well and it is point to relevant DB also but when I clicked any links from http:// localhost/mysite/project1 it will show an error message.

# Answer
You don't need to alter the hosts file if you don't care about serving on more than one address. If you have an Apache vhost entry for 127.0.0.1/localhost (you will by default, and I think Apache will add a hosts entry for 127.0.0.1) then if you have a public\_html dir at `mysite` you can just dump any number of Drupal installs under that dir.

E.g. `/home/niklp/public_html/index.html <- get this working, then you can do:
/home/niklp/public_html/drupal1
...
/home/niklp/public_html/drupalx`

Sorry if this is a little vague but it's not a Drupal issue, it's an Apache config thing that should be easily resolved.

Edit: you will have a billion less issues if you get off windows and onto linux even for basic setups.
> 0 votes

---
Tags: multi-sites
---


# Question
Title: Drupal database not found after running update.php
after installing a module I run update.php and then click take me to front page or take me to admin pages the page takes a while to load and eventually gives me the following error:

```
PDOException: SQLSTATE[HY000] [2002] No route to host in lock_may_be_available() (line 167 of /code/includes/lock.inc).

```

This seems to happen even if there are no pending updates. There was no changes to settings.php, This also happens if i try and open to many pages to the site at the same time.

the only way to get the site back up and running is to restart the container(Kalabox.)

Any insight on how i can fix this or at least how to trouble shoot it would be great.

# Answer
"No route to host" looks like something related to DNS. If you're not, try using an IP for your database server in settings.php

If it's localhost, use 127.0.0.1
> 0 votes

# Answer
When I've had lock messages like that, restarting mysql has always helped. I've never been convinced that it should happen in the first place though.
> 0 votes

---
Tags: 7, database, updating
---


# Question
Title: How to check for product taxonomy term in Rules actions (Ubercart)
I am using Drupal 7 with Ubercart. I am trying to configure to send an email when customer makes a purchase of a product mapped to one particular taxonomy term.

I tried adding actions in a custom rule (created with Rules). But there is no such action available to check the product field values or based on taxonomy terms.

Is there any alternative ways to check product fields in Rules actions?

# Answer
> 1 votes
Have a look at this, rather basic, rule (in Rules export format):

```
{ "rules_check_taxonomy_term" : {
    "LABEL" : "Check Taxonomy Term",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_tags" } },
      { "list_contains" : { "list" : [ "node:field-tags" ], "item" : "21" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A node containing the tag [node:field_tags] just got created or updated." } }
    ]
  }
}

```

Here is what this rule does:

* Rules Event: After saving new content, After updating existing content
* Rules Conditions:

+ ***Entity has field*** "`field_tags`", which is the machine name of the term reference field I want to check for.
    + ***List contains item*** "node:field-tags" and with Taxonomy term identifier value "`21`" (which is the term id of the term I want to check in this Rules Condition).
* Rules Action: Show a message on the site (which is "*A node containing the tag \[node:field\_tags\] just got created or updated.*" (with `[node:field_tags]` the actual term with term id = `21`).

What is crucial in the above rules example in the context of this question, are the 2 Rules Conditions.

Use the Rules UI to import the above rule in your site. Here are the tweaks you'll need to make it fit your case:

* Replace the Rules Event with an event that matches your "*when customer makes a purchase of a product*".
* Within the Rules Conditions, perform these changes:

+ replace the "node" entity with your entity.
    + replace the machine name of term reference "field\_tags", and adapt the "term id" to fit your case.
* Replace the Rules Action by "send an appropriate eMail".

---
Tags: 7, taxonomy-terms, rules, ubercart
---


# Question
Title: How to add users in organic groups using services Rest api?
I'm having problem while adding users in organic group. Here I'm trying to add user in organic group called "Supervisor", I'm using following json and Rest api :

```
Json :
{ "title":"Supervisor",
  "type":"group",
  "og_group_ref": { "und": [{ "target_id": "1921" }]},
  "field_records": { "und": [{ "value": "5" }]}
}

```

Rest api : http://localhost/dev/test/node/1921

but, above json and api is not working, am I using correct json and rest api ?

# Answer
1. Install this module: https://www.drupal.org/project/og\_services
2. Go to `admin/structure/services/list/[MY-ENDPOINT]/resources`
3. Enable at minimum the `join` resource
4. Flush all of Drupal's caches
5. Make a `POST` call to `[MY-ENDPOINT]/og/join/[GROUP-NID]/[USER-UID]`
> 1 votes

# Answer
I think this what you need

```
/*
 * Implements hook_services_resources
 */
function your_module_name_services_resources() {
  return array(
    'add_user' => array(
      'create' => array(
        'help' => 'Add users to group',
        'callback' => 'your_module_add_user_to_group',
        'access callback' => TRUE,
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'uid',
            'type' => 'id',
            'description' => 'The uid of the user to add in group',
            'source' => array('data' => 'uid'),
            'optional' => FALSE,
          ),
        ),
      ),
    ),
  );
}

/*
 * Call back to add the user
 */
function your_module_add_user_to_group($uid) {
  $user_account = user_load($uid);
  $og_values = array(
     'entity_type' => 'user',
     'entity' => $user_account,
     'state' => OG_STATE_ACTIVE,
   );
   //This is will add the group to the user.
  og_group('node', $your_group_nid, $og_values);
  user_save($user_account);
  return success;
}

```

Put this code in your custom module file. And go to "**Structure-\>service-\>your\_end\_point-\>enable 'add\_user' resources**"

Then call **url : http://localhost.com/endpoint/add\_user**

**method: POST**

**In data field data: uid=595 (pass the user id for whom you need to add the group);**

I think this will do the trick.
> 0 votes

---
Tags: 7, services
---


# Question
Title: Passing multiple values in fields as mentioned in another field (as number of values) by user
I want a field that upon getting a value in a text field (eg. 1, 2 anything) shows respective fields. If user inputs 5, then five fields will appear (similar to multiple values of a field, unlimited)

How can I make this possible? There is a conditional module that provides UI for state API but is that enough for the working?

# Answer
I think some of the options mentioned in this thread is kind of what you want maybe not the approach you wanted. For a form to optionally display more form elements you'll have to use state API or some sort of ajax form.

Take this form element for instance:

```
$form['advanced']['s3fs_use_cname'] = array(
    '#type'          => 'checkbox',
    '#title'         => t('Use a CNAME'),
    '#default_value' => _s3fs_get_setting('use_cname'),
    '#description'   => t('Serve files from a custom domain by using an appropriately named bucket, e.g. "mybucket.mydomain.com".'),
);

$form['advanced']['s3fs_cname_settings_fieldset'] = array(
        '#type'   => 'fieldset',
        '#title'  => t('CNAME Settings'),
        '#states' => array(
        'visible' => array(
            ':input[id=edit-s3fs-use-cname]' => array('checked' => TRUE),
        ),
    ),
    's3fs_domain' => array(
        '#type'          => 'textfield',
        '#title'         => t('CDN Domain Name'),
        '#default_value' => _s3fs_get_setting('domain'),
        '#description'   => t('If serving files from CloudFront, the bucket name can differ from the domain name.'),
    ),
);

```

This example from the s3fs module uses a check box to display a form input field. If we look at the documtation for drupal\_process\_states() we can see that as a remote conditions we can use value as a determining factor. So we can almost accomplish what you're asking from here. We would first need a input field

```
$form['field_instance_value'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Number of fields'),
    '#default_value' => NULL,
    '#description'   => t('This serves as the number of fields to display below.'),
);

```

This field is our instance control. On it's own with default values it won't do much. I set it to default to NULL in this case so we can determine if the user has filled in a value or not. Next we'll need to control the group of fields and each additional field. This might be better to do using an ajax form since you can dynamically add as many fields as you like based on the number but i won't cover that.

```
$form['field_instances'] = array(
    '#type'   => 'fieldset',
    '#title'  => t('Field Instances'),
    '#states' => array(
        'visible' => array(
            ':input[id=edit-field_instance_value]' => array('filled' => TRUE),
        )
    ),
);

$form['field_instances']['field_instance_one'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Field Instance one'),
    '#states' => array(
        'visible' => array(
            ':input[id=edit-field_instance_value]' => array('value' => 1),
        )
    ),
);

$form['field_instances']['field_instance_two'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Field Instance two'),
    '#states' => array(
        'visible' => array(
            ':input[id=edit-field_instance_value]' => array('value' => 2),
        )
    ),
);

```

So from the above example you can see that we have two control states, the first being on the fieldset containing the field instances and the second being on the instances themselves. The idea here is that we want to make sure that the instances can be seen if there is a value in the field, then we want to only show the field instances that the form 'field\_instance\_value' element specifies. You could even put in a default value here if the value of the input is empty or something else.

Keep in mind this code isn't tested just what i've come up with based on your question and years of working with Drupal's Form API. Below are some references i used.
> 1 votes

# Answer
You can ref Examples for Developers Module. The module comes with various sub-modules for developers to start with.

Similar kind of functionality is already provided as an example in "**AJAX Example**" module in **Examples** module. i.e. User has been given a dropdown field with predefined numbers to render those many fields. Check screenshot below:

Hope this helps.
> 1 votes

# Answer
assuming that the fields you want to repeat are text fields.

```
//the form

function module_form($form,&$form_state){

    $form['first_box']=array(
    '#type' => 'textfield',
    '#title' => t('enter the number'),
    '#ajax' => array(
    'callback' => 'module_callback',
    'wrapper' => 'my-wrapper',
),
);

$form['multiple_box']=array(
    '#prefix' => '<div id="my-wrapper">',
    '#suffix' => '</div>',
);
return $form;
}
 function module_callback($form,&$form_state){
    $temp=$form_state['values']['first_box'];
    $page=array();
    while($temp>0){
        $page[]=array(
        '#type' => 'textfield',
        '#title' => t('name'),
        );
        $temp=$temp-1;
}
    return $page;
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How does Drupal 7's SQL call for 'node' and retrieve an image?
I have the following query shown in one of my views:

```
SELECT node.nid AS nid, node.title AS node_title, node.created AS node_created,
node.sticky AS node_sticky,
'node' AS field_data_field_featured_image_node_entity_type,
'node' AS field_data_body_node_entity_type,
'node' AS field_data_field_premium_content_node_entity_type,
'node' AS field_data_field_article_type_node_entity_type,
'node' AS field_data_field_video_upload_node_entity_type
    FROM
    {node} node
    INNER JOIN {field_data_field_sports_type} field_data_field_sports_type ON node.nid = field_data_field_sports_type.entity_id AND (field_data_field_sports_type.entity_type = 'node' AND field_data_field_sports_type.deleted = '0')
    WHERE (( (node.status = '1') AND (node.type IN  ('article')) AND (field_data_field_sports_type.field_sports_type_tid = '1884') ))
    ORDER BY node_sticky DESC, node_created DESC
    LIMIT 8 OFFSET 1

```

What does the `'node'` in this query return, for instance when I'm calling:

```
...'node' AS field_data_field_featured_image_node_entity_type,

```

It seems to me that this should just return the string "node" but in the preview it's actually showing the image. When I do the SQL query in the console it's just returning the string 'node'. I'm confused because I don't see any `JOIN` statements on things like the `field_featured_image` table in this query, which I would have expected if the query actually was pulling the image.

How is the image getting shown via this query?

# Answer
> 0 votes
It's utilizing a loaded entity to fill in these placeholder columns. Per the `views_handler_field_field::query()` docs:

> By default, the only columns added to the query are entity\_id and entity\_type. This is because other needed data is fetched by entity\_load(). Other columns are added only if they are used in groupings, or if 'add fields to query' is specifically set to TRUE in the field definition.

In the post-execute phase, during `views_handler_field_field::post_execute()`, you can see where the field values are dropped in from the entity values.

---
Tags: 7, views, database
---


# Question
Title: How to link a title from one view to a page of another view
I created a content type x.

I added 4 contents.

My contents look like this.

>

I created a views page. (xxx.com/mypage),

>

I created a views block placed in sidebar. (displayed sidebar of xxx.com/mypage),

>

This is how the page looks like,

>

Each time I click a title in sidebar, I like the corresponding views page to be displayed. Currently, title takes me to orginal content. Thats not what I want.

Example: If I click Chapter1 Title1, I like to see chapter1 title1 body page, If I click Chapter2 Title1, I like to see chapter2 title1 body page.

I think I need to use contextual filter and I am not sure how I can do that to make it happen.

Please advise.

---

# Answer
> 2 votes
You are correct. You can use contextual filters to achieve this. There are two parts to the solution.

The first is the views page, which you labeled xxx.com/mypage. You will need to add a contextual filter using Content:NID. You would then change your views page's path to uft/%. Then, for instance, navigating to xxx.com/uft/2 in your browser would result in accessing your views page with only the information for node 2 shown.

The other half of the solution is in the block. You will first need to add one more field to your block's fields, NID. Make sure to check the 'Exclude from display' checkbox while adding it. Once you've added NID, you'll need to rearrange the fields so NID is above title. Now you are ready to change what the Titles in your block link to. When you click Content:Title under the Fields section you will first want to uncheck 'Link this field to the original piece of content'. Next, you should see a collapsed fieldset titled 'Rewrite Results'. Click that to expand it. In the text box, entering `uft/[nid]` should complete the process.

At this point, your views block should be generating xxx.com/uft/target\_nid as the link targets for the titles in the block and when you click them you should arrive at your views page with the selected nid passed as a contextual filter argument.

---
Tags: views
---


title: Set form_state values on Ajax form

text:
# Question
Title: Set form_state values on Ajax form
I am editing a node/add/ form using `hook_form_alter()`. The form that I have added has Ajax functionality.

The first part of the form allows the user to build a search which then retrieves a list of legislators, and populates the `#options` array of the tableselect with those legislator

The second part of the form, needs to move legislators from the first tableselect to the second tableselect, as they are selected, using Ajax.

The issue: when I set the `#options` array for the `legislator_tableselect` in the `contact_rep_node_add_ajax_get_legislators_callback`, it does not update the `$form_state['values']` array, which prevents be from retrieving the values in my next callback.

How do I go about forcing the `$form_state['values']` to update? Or is there a better way to do this?

P.S. there is more to this form, I edited it for the sake of brevity though

```
function contact_rep_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'contact_rep_node_form') {

    $form['search_container'] = array(
      '#type' => 'fieldset',
      '#title' => t('Get a list of legislators to contact by building a search below'),
      '#collapsible' => FALSE,
    );

    $form['search_container']['select_state'] = array(
      '#title' => t("Select a state for your legislators"),
      '#type' => 'select',
      '#required' => FALSE,
      '#options' => array(
        //Contains a list of US states. Removed for brevity
      ),
      '#ajax' => array(
        'wrapper' => 'filteredLegislatorsSearch-div'
      ),
    );

    $form['search_container']['first_name'] = array(
      '#title' => t('Legislator\'s first name'),
      '#type' => 'textfield',
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => FALSE,
    );

    $form['search_container']['last_name'] = array(
      '#title' => t('Legislator\'s last name'),
      '#type' => 'textfield',
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => FALSE,
    );

    $form['search_container']['chamber'] = array(
      '#type' => 'select',
      '#title' => t('Chamber'),
      '#options' => array(
        0 => t(''),
        'upper' => t('Upper'),
        'lower' => t('Lower'),
      ),
    );

    $form['search_container']['district'] = array(
      '#type' => 'textfield',
      '#attributes' => array(
        'data-type' => 'number'
      ),
      '#title' => 'District',
      '#size' => 10,
      '#maxlength' => 3,
      '#required' => FALSE,
    );

    $form['search_container']['party'] = array(
      '#type' => 'textfield',
      '#title' => 'Party',
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => FALSE,
    );

    $form['search_container']['filtered_submit'] = array(
      '#type' => 'submit',
      '#name' => 'filtered_search',
      '#value' => t('Find Legislators'),
      '#ajax' => array(
        'submitter' => FALSE,
        'callback' => 'contact_rep_node_add_ajax_get_legislators_callback',
        'wrapper' => 'legislator_container',
      ),
    );

    $form['search_container']['legislator_container'] = array(
      '#prefix' => '<div id="legislator_container">',
      '#suffix' => '</div>',
    );

    // The problem?
    $form['search_container']['legislator_container']['legislator_tableselect'] = array(
      '#options' => array(),
      '#type' => 'tableselect',
      '#empty' => t('Build your search above to get a list of legislators'),
      '#attributes' => array(
        'id' => 'legislatorTableSelect',
      ),
      '#header' => array(
        'first_name' => t('First Name'),
        'last_name' => t('Last Name'),
        'chamber' => t('Chamber'),
        'district' => t('District'),
        'party' => t('Party'),
      ),
      '#ajax' => array(
        'event' => 'change',
        'callback' => 'contact_rep_node_add_ajax_legislators_list_callback',
        'wrapper' => 'legislatorsToContact',
      ),
    );

    $form['search_container']['legislators_to_contact_container'] = array(
      '#prefix' => '<div id="legislatorsToContact">',
      '#suffix' => '</div>',
    );

    $form['search_container']['legislators_to_contact_container']['legislators_to_contact_tableselect'] = array(
      '#type' => 'tableselect',
      '#empty' => t('Legislators in this table will be emailed'),
      '#header' => array(
        'first_name' => t('First Name'),
        'last_name' => t('Last Name'),
        'chamber' => t('Chamber'),
        'district' => t('District'),
        'party' => t('Party'),
      ),
    );
  }
}

/**
 * Implements ajax callback for contact_rep_form_alter
 */
function contact_rep_node_add_ajax_callback($form, $form_state) {
  return $form['search_container'];
}

// Callback connected to filtered_submit button.
function contact_rep_node_add_ajax_get_legislators_callback($form, $form_state) {
  // Get form values and pass the to fetch function, save result to $legislators.
  /* Gets the form values from form elemets, passes them to a function and saves the out put to a variable. */
  $legislators = fetchFilteredLegislators($state, $chamber, $first_name, $last_name, $district, $party);
  // Creates the $options array for the tableselect.
  $element = $form['search_container']['legislator_container']['legislator_tableselect'];
  $element['#options'] = $legislators; // Set the options array to preformated $legislators array.
  $element = form_process_tableselect($element);// This has to be called in order to reset the $options in the tableselect items.
  return $element;
}

// Callback that is supposed to handle the the tableselect data.
function contact_rep_node_add_ajax_legislators_list_callback($form, $form_state) {
  $options = $form_state['values']['legislator_tableselect'];
  $element = $form['search_container']['legislator_to_contact_container']['legislators_to_contact_tableselect'];
  $element['#options'] = $options;
  $element = form_process_tableselect($element);// This has to be called in order to reset the $options in the tableselect item.
  return $element;
}

```

Edit: So after doing some more googling it seems that I need to set `$form_state['rebuild'] = TRUE`. And I added that to `contact_rep_node_add_ajax_get_legislators_callback`, but it still is not working.

Is that the correct place to put the the `$form_state['rebuild']`, or is there a better place to put it?

# Answer
In your callback function save values to a secondary key such as `$form_state['storage']`. This will be retained each callback but `$form_state['values']` will be overwritten with the current form elements values.
> 1 votes

---
Tags: 7, forms, ajax
---


# Question
Title: How to display all children on parent node for custom content type?
I have a custom content type, let's call it 'parent'. I have another custom content type, let's call it 'child'.

I created a template file where I can display the 'parent' content type fields any way I want: `node--parent.tpl.php`. By using code such as...

```
<?php
  print $content['field_city'][0]['#markup'];
?>

```

I can move fields around and customize the markup, which is great. But **how would I also display the parent's children on the same page?**

(I don't use Views. I create a content type template file instead because gives me more flexibility for arranging the HTML).

# Answer
How are the children linked to the parent? Do you use an Entity Reference field?

Also, what do you want to display from the children? The titles? The entire, rendered nodes?

If you look up entity\_metadata\_wrapper (see: Entity metadata wrappers) you can see how to access an Entity Reference field.

You also may want to reconsider Views. Overriding templates for Views can give you a lot of flexibility.
> 0 votes

# Answer
I know its an old one but it does not seem satisfactorily answered

For drupal 7 usually don't need to mess with template files for such a task.

I would use https://www.drupal.org/project/field\_extractor which is a field formatter for entity reference that will let you output any referenced fields from the list of referenced entities (only 1 field though)

If you want to output more than one fields I would suggest the https://www.drupal.org/project/eva which will allow you to create a special entity reference view which you can associate with the referencing entity (parent) and will allow you to output any fields from that entity and format it any way you would format a view. Automatically the view will be available in the display settings of the referencing entity so you can change the order of appearence.

if the previous 2 modules don't seem to help you can try 1 of the following which work with views but they are a little more difficult to setup and I am not going to go into detail here

drupal.org/project/field\_embed\_views

drupal.org/project/viewfield

drupal.org/project/views\_field\_view

(sorry my reputation wont allow me to post more than 2 links)
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Display Field Collection items as select list in other content type
I have 2 content types, lets say A and B. There is field collection item in content type A (in which unlimited values could be added). User adds data in this field as he creates new content.

I want all those field collection options filled by user in A to appear as a select list while submitting content type B.

I create an entity reference field in content type B and tried to display all options of field collection item from A. It shows perfectly as I tested it in view.

**Issue:**

* If I select to display all values in a single row, it shows all options in one row of select list.
* I actually want to display each option in separate row, but it shows only the last item.

Anyone knows the solution?

Here are Settings of my View:

And this is my Field Setting:

As you can see, in View it shows both option. But in select list it shows only last option or all options in single row (by changing setting).

# Answer
***This is a partial answer, looking for further guidance!***

After a lot of exploration, I still couldn't find exact solution to my question.

*While searching I found this topic titled: Entity Reference view to populate select list for reference field =\> only one result when using a contextual filter, might help others. This is a long node addressing similar problem.*

But my problem was not solved by above mentioned link. So I used `hook_form_alter`,

```
function module_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'your_form_id'){
        $url_arg=arg(); //get arguments from URL
        $node_id=$url_arg[1];
        $node=node_load($node_id); //load appropriate node of Content type A
        $info = field_info_field('field_testing_code'); //load field from Content Type B's form
        $values = &$info['settings']['allowed_values']; //get list of allowed values
        $values= array(); //remove all existing values
        $i=0;
        while($node->field_consignment_text_field[und][$i][value]){
            $values[$node->field_consignment_text_field[und][$i][value]] = $node->field_consignment_text_field[und][$i][value];
            $i++;
        }
    field_update_field($info);
  }
}

```

As I mentioned, each B content type is a sub part of A content type. And URL contains id of A. When I open content type B's creation form one at a time, it works fine. When I open more that one forms having different A parent, form\_alter shuffles data e.g Field data of tab 1 gets assigned to tab 2.This is the issue now. Looking for some solution for this.
> 3 votes

# Answer
In a setting of of that particular field, there is a option under title of,

`MULTIPLE FIELD SETTING`,

Where there is a option of `Display all values in the same row`. Now suppose in my case this is the field collection filed (FC101 is a entire filed), Now if I check this option is will show entire field collection as a one field, on the otehr hand if, I uncheck this option the field in field collection are treated as they are in their own row. Now you can check the setting of of your field which is fetching this data in view, whether this option is there on not.

Just to explain properly I am describing this in answer, If this is not what you are looking for please let know, I will delete answer.

So, whatever field
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How to get site url with twig in Views custom text?
In Drupal 8 I try to get the absolute site url in a Views custom text field.

I added `{{ url('view.frontpage.page_1') }}` which gives me example.com/node

Drupal docs say `{{ url('view.frontpage') }}` would do it, but it just gives me wsod and throws an error like so:

```
AH01071: Got error 'PHP message: Uncaught PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "view.frontpage" does not exist." at /../../docroot/core/lib/Drupal/Core/Routing/RouteProvider.php line 187\n'

```

Any ideas?

# Answer
The documentation could be out of date. Check your `router` table for the name of the route. In my Drupal 8 site it is `view.frontpage.page_1`.
> 1 votes

---
Tags: views, theming, 8
---


title: How to manage Sticky Content?

text:
# Question
Title: How to manage Sticky Content?
I want to manage sticky content on front page of website.

I have made five content sticky on top for front page but my query its show by default according to publish date order but I want to fix the order of that sticky content.

Any suggestion or solution about how to do so?

# Answer
Enable the "sticky" option within publishing options for 5 of your nodes. Then create a view (using the Views module) and for this view, within the "Sort criteria" of it, make sure to add "***Node: Sticky***" as your primary sort criterium (using the Views UI).

When adding this sort criterium to your view, you'll also see "*...To list sticky nodes first, set this to descending.*" (which is what you seem to be looking for).

To finish enter a path for the Views result, and use this path to set it as your frontpage.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Problem with field storage for custom content type modules
*I have multiple modules for custom content types (like "node\_type\_food" and "node\_type\_wine"), based on "node\_type\_example" in the drupal examples module.*

I can install a content type like "node\_type\_food" without any problems but installing a second content type like "node\_type\_wine" with a common field (food & wine both have a field "field\_text") results in this error:

> Unable to install Content type wine, field.storage.node.field\_text already exists in active configuration.

Without the field.storage.node.field\_text.yml in config/install I can't install a content type when no other content type provides the field storage..

> Unable to install Node type wine, field.field.node.wine.field\_text has unmet dependencies.

*Edit: Problem also descibed in comment on Install a module that creates a content type with fileds via YAML*

# Answer
> 1 votes
The Drupal's config management system which are you using to install configuration isn't really built for this. There are several ways to go about this. The main issue is that the config management system automatically create dependencies and such for you, which is a bit troublesome to manage.

Drupal doesn't have a concept of a shared field, it simple has a field store and field instance, but this isn't owned by a module.

So for solutions, there are some ways to go about this.

1. Let one module own the field storages you want to want to share and let modules that share fields depend on the module. Note the field can be deleted eventhough it's in a modules install folder, as it's just configuration, unless you lock it. A variation of this would be to combine the modules, into a single module, so all config is install at the same time.
2. Don't use shared fields - if the modules are independent, it makes sense that they shouldn't share configuration.
3. Use code to install fields. This is similar to how you define fields for entities, only you need to use `FieldConfig` and `FieldStorageConfig`. Drupal have many test cases that does this, which you can use as a guide. Some example code looks like this:

```
$this->fieldStorage = FieldStorageConfig::loadByName('entity_test', $field_name);
if (!$this->fieldStorage) {
  $this->fieldStorage = FieldStorageConfig::create(array(
    'field_name' => $field_name,
    'entity_type' => 'entity_test',
    'type' => 'link',
  ));
  $this->fieldStorage->save();
}

$this->field = FieldConfig::create([
  'field_storage' => $this->fieldStorage,
  'bundle' => 'entity_test',
  'settings' => array(
    'title' => DRUPAL_DISABLED,
    'link_type' => LinkItemInterface::LINK_GENERIC,
  ),
]);
$this->field->save();

```

---
Tags: 8, entities
---


# Question
Title: how to make the field label in Views hidden or visible?
i have a view page with Table format i want to control the label of the fields that i added befor . i changed the php code in (views-view-table.tpl.php) befor so now i can't control the field label ( hidden / visible ) from the view this is the code that i have now :

and this is the view page even i check the label nothing happen!

anyone can help me with this please ?

# Answer
> 0 votes
after 1 week searching i found the solution : simply by adding this code :

```
<?php print $header['$field_name']; ?>

```

this code will print the label of your field.

# Answer
> 0 votes
This is normal because you are using a template file, view's will use your template file and nothing from the UI (User Interface) for fields.

Therefore, you will need to type `Address:` in your template file, just like you did for `Location:`, on line 47.

---
Tags: views
---