# Question
Title: Customize Search Result Snippet to use Teaser
I would like to customize the output of each search result item printed on the search result page. Right now it automatically prints a portion of the content of each item, but I'd like more control. I would like to specify what fields to display in the search result. For example I'd like to output field\_image followed by field\_mytextfield. Rather than whatever Drupal is doing to output the trimmed content of the result.

I'm using a template to customize the output already

```
{{ title_prefix }}
<div class="search-result-item">
<div class="search-title-header">
    <h4{{ title_attributes }}>
        <a href="{{ url }}">{{ title }}</a>
    </h4>
</div>
{{ title_suffix }}
{% if snippet %}
  <p{{ content_attributes }}>{{ snippet }}</p>
{% endif %}

</div>

```

However I don't seem to have access to what is inside snippet, and I'm not sure how to directly access the fields of the result. I'd like to use the content type's teaser as the result display but I'm not sure how to use that.

# Answer
You can take control on which content the snippet is based by modifying the view mode "search\_result". If you want to hide information from a field, then simply remove it there. But you can't change the behavior, how the snippet is composed out of this content. This is hard coded. And it will be text only with all tags removed.

If you want to provide additional elements for the search result, beside the snippet, you can do this by implementing template\_preprocess\_search\_result in your module/theme file:

```
function [MODULE_NAME]_preprocess_search_result(&$variables) {
  $node = $variables['result']['node'];
  if (isset($node)) {
    $variables['teaser'] = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node,'teaser');
  }
};

```

And use it in twig:

```
{{ teaser }}

```
> 5 votes

---
Tags: theming, 8, search
---


title: How to display a Quick Tab with count?

text:
# Question
Title: How to display a Quick Tab with count?
I'd like to display the # (count) of Blogs on my quick tab menu. Ex: Blogs (3)

I found a way to overwrite the quicktab titles using the following function with an if statement

```
   function mymodule_quicktabs_alter($quicktabs) {
if ($quicktabs->machine_name == 'quick_tab_front_page') {
$quicktabs->tabs = array(
  0 => array(
    'machine_name' => 'quick_tab_blogs',
    'title' => 'BLOGS',
    'weight' => '-100',
    'type' => 'qtabs',
  ),
  1 => array(
    'machine_name' => 'quick_tab_news',
    'title' => 'NEWS',
    'weight' => '-89',
    'type' => 'qtabs',
  ),
);
$quicktabs->renderer = 'quicktabs';
$quicktabs->style = 'Arrows';
$quicktabs->options = array();
}
}

```

I created a view, using the Views module, which contains all the blog titles written by a user.

Now I need to figure-out a way to display the views' count on the quick tab title

I have tried

```
function mymodule_quicktabs_alter($quicktabs) {
    $view = views_get_view('user_blogs');
    $view->set_arguments(array($account->uid));
    $view->execute();
    $count = count($view->result);
if ($quicktabs->machine_name == 'quick_tab_front_page') {
$quicktabs->tabs = array(
  0 => array(
    'machine_name' => 'quick_tab_blogs',
    'title' => t('Blogs @count', array('@count' => $count));

```

but it gives me an error of Fatal error: Call to a member function execute() on a non-object for the line $view = views\_get\_view('user\_blogs');

I don't get why, I am new to php.

# Answer
Check your view name that you are passing to `views_get_view()` and also from where are you getting the `$account` variable from (credits: wolverine).

And get rid off `$view->set_arguments(array($account->uid));`, you don't need it (credits: No Sssweat).
> 1 votes

---
Tags: 7, views, blocks
---


# Question
Title: "Drupal calls should be avoided in classes, use dependency injection instead"
In my module using below code for getting url alias of given url:

```
$alias = \Drupal::service('path.alias_manager')->getPathByAlias($_POST['url']);

```

But one I run Automated Review(http://pareview.sh/) in my module I am getting below warning:

> 16 | WARNING | \Drupal calls should be avoided in classes, use dependency injection instead

How can I update above code using dependency injection? My entire class code is given below.

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * MyModule Class defines ajax callback function.
 */
class MyModule extends ControllerBase {
/**
 * Callback function for ajax request.
 */

  public function getUserContent() {
    $alias = \Drupal::service('path.alias_manager')->getPathByAlias($_POST['url']);
    $alias = explode('/', $alias);
    $my_module_views = views_embed_view('my_module', 'default', $alias[2]);
    $my_module= drupal_render($my_module_views);
    return array(
      '#name' => 'my_module_content',
      '#markup' => '<div class="my_module_content">' . $my_module. '</div>',
    );
  }

}

```

# Answer
> 20 votes
Take the `BlockLibraryController` class as example; it extends the same class as your controller.

You define:

* A static and public `create()` method that gets the values from the dependency container, and creates a new object of your class
* A class constructor that saves the values passed from the previous method in object properties
* A set of object properties to save the values passed in the class constructor

In your case, the code would be similar to the following one.

```
class MyModuleController extends ControllerBase {
  /**
   * The path alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected aliasManager;

  /**
   * Constructs a MyModuleController object.
   *
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   *   The path alias manager.
   */
  public function __construct(AliasManagerInterface $alias_manager) {
    $this->aliasManager = $alias_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('path.alias_manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getUserContent() {
    $alias = $this->aliasManager->getPathByAlias($_POST['url']);
    // Omissis.
  }

}

```

Don't forget to put `use \Drupal\Core\Path\AliasManagerInterface;` on the top of the file containing the code you are showing.

As side note, the code you use to render the view is wrong: You don't need to use `drupal_render()` because `views_embed_view()` already returns a renderable array.
Then, the render array you are returning is probably not giving the output you expect. #name is probably not going to be used from Drupal, and #markup filters the markup you are passing to it, as described on Render API overview.

> * **#markup**: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through `\Drupal\Component\Utility\Xss::filterAdmin()`, which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, `<script>` and `<style>` are not allowed.) See `\Drupal\Component\Utility\Xss::$adminTags` for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed\_tags to alter which tags are filtered.
> * **#allowed\_tags**: If #markup is supplied this can be used to change which tags are using to filter the markup. The value should be an array of tags that `Xss::filter()` would accept. If #plain\_text is set this value is ignored.

# Answer
> 2 votes
In order to utilize dependency injection, your class needs to implement `ContainerInjectionInterface` interface. `ContainerInjectionInterface` mandates that implementing class has to have `create()` method. With additional class constructor which accepts the injected dependencies, `create()` method returns an instance of your class by passing the defined instances of dependencies to your class.

**Update:** It was rightfully pointed by @kiamlaluno that `ContainerInjectionInterface` is not required in this case since `ControllerBase` already implements it.

```
<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Path\AliasManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * MyModule Class defines ajax callback function.
 */
class MyModule extends ControllerBase {

  /** @var \Drupal\Core\Path\AliasManagerInterface $aliasManager */
  protected $aliasManager;

  /**
   * MyModule constructor.
   *
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   */
  public function __construct(AliasManagerInterface $alias_manager) {
    $this->aliasManager = $alias_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('path.alias_manager')
    );
  }

  /**
   * Callback function for ajax request.
   */
  public function getUserContent() {
    $alias = $this->aliasManager->getPathByAlias($_POST['url']);
    // Your code.
  }

}

```

---
Tags: 8, dependency-injection
---


# Question
Title: Is it possible to give users different roles/profiles on different part of the website?
For example, is it possible to give *userA* full read/write access on some part but read-only access on others?

Most importantly, is this possible without too much hassle? I mean what I'm looking for is some sort of "inheritance", i.e. if I give *userA* full read/write access on *nodeA*, I'd like those exact same rights are granted to *userA* on every child node of *nodeA*, recursively.

I've seen Flexi Access but this module does not seem to satisfy my "inheritance" constraint.

# Answer
> 2 votes
A widely accepted solution for this would be using the Organic Groups module.

With this module, you can define different access settings and local roles for a given group type, and for all the nodes associated to it (this would be the "inheritance" you are looking for).

It is not the simplest module to use, though. You can find some "getting started" documentation here: https://www.drupal.org/node/861418

# Answer
> 0 votes
Another solution for this would be using the Group module, which is getting accepted more and more (an Organic groups alternative ...).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

# Resources

**Note**: I can't wait for somebody to (re-)create .

---
Tags: users
---


# Question
Title: Sort by one criteria and have another to fall back on
I'm trying to configure a view (using the Views module) that sorts the content by content weight, then by total content views (loading a max of 6 items).

For a quick explanation, this is to list the most popular 'resources' on the resources page (PDFs). I'd like the list to be sorted by total views, which I've already achieved. However, I want to be able to give a weight to specific resources (resource is a content type, I've created a weight field using a simple list(integer) field that goes from -3 to 3) which the 'Popular Resources' view sorts by first before loading by total views.

I've tried giving the view 2 sort criteria, which are:

* Content: Most Popular Resources Block Weight (asc)
* Content statistics: Total views (desc)

I have 1 resource with a popular resource block weight set (the rest don't have a weight set), but the view isn't showing this resource as it has a lower number of total views than the others being loaded.

If possible I'd like the view to sort by resources that have a weight set, then when it runs out of blocks that have a weight, use total views to load and sort the rest of the resources. I've tried looking for a way to do this but haven't found anything yet.

Any assistance would be greatly appreciated.

# Answer
> 0 votes
Managed to find the issue. The resources that didn't have a weight set were treated as having a lower weight than ones that did. I changed the weighting to sort by descending, which is the opposite of how weight should work, but seems to be the only solution.

---
Tags: views
---


title: Create an admin page from template

text:
# Question
Title: Create an admin page from template
I want to create a completely bespoke admin page for some custom functionality. I don't want to hack the concept into render arrays as it will get messy fast.

I've got a menu declaration with a callback function, in here I can include and render templates. Using buffer streams, however, this only renders the file i'm passing.

Is it possible and if so how, to extend Drupal's default admin layout (header/footer/scripts/css) and print my 'template' in where `$page` would normally go?

I know I could view source and copy the code required, but I feel that would be an awful approach so please don't suggest.

---

Attempted solution not working.

```
function MYMODULENAME_menu() {
    $items = array (
        'admin/content/xxx' => array(
            'title' => 'xxx',
            'page callback' => 'MYMODULENAME_timetable_admin',
            'access arguments' => array('access content'),
        )
    );

    return $items;
}

function xxx_theme() {
  return array(
    'funky_admin_page_content' => array(
      'variables' => array(),
    ),
  );
}

function xxx_funky_admin_page_content() {
    echo "hello world";
  return 'hello world';
}

function MYMODULENAME_timetable_admin() {
  return array(
    '#theme' => 'xxx',
  );
}

```

Hello world isn't found in view-source. So I can only gather that the function isn't firing. I've cleared caches several times. Am I missing something obvious?

# Answer
Absolutely, it's quite straightforward.

You'll need a path for the page:

```
function MYMODULE_menu() {
  $items['admin/foo/bar'] = [
    'title' => 'Foo',
    'page callback' => 'MYMODULE_admin_page_callback',
    'access arguments' => ['whatever makes sense'],
  ];

  return $items;
}

```

A theme declaration:

```
function MYMODULE_theme() {
  return [
    'funky_admin_page_content' => [
      'variables' => [],
    ],
  ];
}

```

Your function to build/get the content. Note that you could also put this in a template file, see `hook_theme()` for more details.

```
function theme_funky_admin_page_content() {
  // Build your HTML, return it as a string.
}

```

And your page callback:

```
function MYMODULE_admin_page_callback() {
  return [
    '#theme' => 'funky_admin_page_content',
  ];
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: Taxonomy term not translated in edit node
I have a taxonomy called « **categories** » which have terms as listed below:

Here the term “**visuels**” is the French version of “**visuals**” that has been translated.

Now in the edit section of an article with ‘french’ selected as the language, I am not getting the French term but instead it is listing the English version as shown below:  Can someone help me with this?

# Answer
> 0 votes
It seems you are using 'Entity Translation' module and a field type 'Term reference'.

In the content type 'Article' you could try to create a new field type 'Entity Reference' with Target type 'Taxonomy term' and Entity selection '\[Your category vocabulary\]'

It should works.

---
Tags: taxonomy-terms, i18n-l10n
---


title: How to add JS to the search form?

text:
# Question
Title: How to add JS to the search form?
```
<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter()
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'search_form') {

     $form['#attached']['library'][] = 'mymodule/mylibrary';

  }

}

```

Doing a `dpm($form)` on the search form, I see it has the my attached library, so what gives?

---

**Solution:**

The above code works fine, turns out it was my js code, I had copied over from another js file and it had an if statement that somehow I missed (it was 4 am). Credit @Alexei Rayu

# Answer
In Drupal 8, you first need to define assets in a library in your theme or module: https://www.drupal.org/developing/api/8/assets

and then you can attach that library to your form like this:

```
$form['#attached']['library'][] = 'mymodule/mylibrary';

```
> 2 votes

---
Tags: 8
---


# Question
Title: How to replace spaces with dashes when redirecting users through Rules?
I have a rule that redirects users on login to a matching taxonomy term, ie. there is a taxonomy term that is identical to the user name and when a user logs in they are redirected to the url of that taxonomy term using tokens. The redirected url is as follows:

taxonomy/\[account:name\]

However, when there is a space in the user name then this causes problems, the URL of the taxonomy term has spaces automatically replaced with dashes, however the rule treats spaces as spaces and creates a url such as "mysite.com/taxonomy/first%20second"

Is there a way to replace the spaces with dashes?

# Answer
> 1 votes
Sometimes the solution to a problem, is to prevent the problem from happening.

So therefor I suggest you just do not allow spaces in your user names. To do so, use the Rules module (which you already have), and implement a rule that looks something like so:

```
{ "rules_disallow_spaces_in_user_names" : {
    "LABEL" : "Disallow spaces in user names",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_presave" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "account:name" ],
          "match" : "\\b \\b",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "User names are not allowed to contains spaces, please correct",
          "type" : "error"
        }
      }
    ]
  }
}

```

Some more details about this rule (which you should be able to import in your own site using the Rules UI):

* Rules Event: "Before saving a user account".
* Rules Condition: use a regex to check of the user name contains a space (adapt the regex if needed).
* Rules Action: set an appropriate error message (adapt if needed).

The additional advantage of this approach is also that you don't need the PHP filter for it to work (as suggested in one of the comments).

---
Tags: users, rules, redirection
---


# Question
Title: How to make a view list entities, not translations?
I need to list content entities in their original languages, but views module shows all content translations.

I need something like grouping by entity IDs.

# Answer
> 3 votes
I think the proper filter is the following:

"Content: Default translation (= True)"

# Answer
> 0 votes
I achieved the desired result by adding the `Translation source (= Not specified)` filter.

The original entity translations have the `Translation source` field empty. And it's pretty safe to use the `Not specified` language because entities using it are untranslatable.

---
Tags: views, 8
---


# Question
Title: Create container.html.twig template for specific page
I'm attempting to edit the search page. I've edited container.html.twig to contain

```
{%
  set classes = [
    has_parent ? 'js-form-wrapper',
    has_parent ? 'form-wrapper',
  ]
%}
<h2>Search Results</h2>
<div{{ attributes.addClass(classes) }}>{{ children }}</div>

```

It works fine when I leave the file name as container.html.twig. But I'd like for it to only apply to the search page. I've tried naming it container--search-results.html.twig but that did not work.

How do I rename container.twig.html to only apply to my search page?

# Answer
Am not sure if this contains the answer, but you should definitely read this:

Twig Debugging
> 0 votes

---
Tags: theming, 8
---


title: Change block data with page cache

text:
# Question
Title: Change block data with page cache
I have enable page cache for anonymous users and no cache for block. There are some random data in cache that change on every page refresh.

Once the page cached by cache\_page bin block content is not changing, but it working fine with administrator.

How can I fixed this problem with page cache enable.

# Answer
> 1 votes
For Drupal 7, there is Authcache module. In Drupal 8, you could use Dynamic Page Cache from core.

You could also use some JavaScript. If you have random data to display, you could display them all, hidden by default and use javascript to display one of them each time. Or you could use AJAX, request a URL that will return your new block content, on each page refresh. Disable cache for specific blocks has more information that can help you.

If you have multiple dynamic blocks in your website, my suggestion is to use a module, as it will take you less time to implement it. Writing JavaScript for each dynamic block will take you more time, to implement it and maintain it.

# Answer
> 1 votes
You have to think of the different levels of caching as "layers". If you cache your page, the blocks will also get cached no matter the setting for the block. If you don't cache your whole page, then the block caching config will kick in.

Ajax Blocks module exists for this purpose. Basically the page cache will only cache the HTML that gets **replaced** using Ajax by the actual block content (uncached).

> Permits to load some blocks by additional AJAX request after loading the whole cached page when the page is viewed by anonymous user. It is suitable for sites which are mostly static, and the page caching for anonymous users is a great benefit, but there are some pieces of information that have to be dynamic.

---
Tags: 7, blocks, caching, performance
---


# Question
Title: Display main menu for logged in users only
I'm new to drupal and using the latest version (7.x). I want hide the Main Menu in all pages until user log-in to the site. I set the Main Menu block role set to "Authenticated Users" only. But I can see the Main Menu on all pages as anonymous user.

How could I hide the Main Menu for anonymous user and show them once logged In ?

# Answer
> 2 votes
If you are assigning main menu (as block) to region, you can control it's visibility by "Visibility settings". If you are rendering it in .tpl.php file then you can do it like this: Example (bartik's page.tpl.php):

```
<?php if ($main_menu && user_is_logged_in()): ?>
  <div id="main-menu" class="navigation">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#main-menu -->
<?php endif; ?>

```

# Answer
> 1 votes
When you move to the **menu block configure settings** there is tab for role. You can restrict it to authenticated users only. This would work.

# Answer
> 1 votes
Use this module **https://www.drupal.org/project/menu\_item\_visibility** The module uses the exact same UI used for block visibility settings for familiarity.

---
Tags: 7, routes
---


title: Add text field to poll entity

text:
# Question
Title: Add text field to poll entity
I have installed the Poll module in Drupal 8. I need to add a field to it, such as a text area for the poll description.

How can I add a field to a content entity like Poll, which is not a content type?

# Answer
Poll is not a fieldable entity, so this is not possible in ui.

You can do this in code:

```
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
/**
 * Implements hook_entity_base_field_info().
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'poll') {
    $fields['description'] = BaseFieldDefinition::create('text')
      ->setLabel(t('New discription field'))
      ->setTranslatable(TRUE);
    return $fields;
  }
}

```

Apply the schema update on the database:

```
drush entity-updates

```
> 1 votes

---
Tags: entities, 8
---


# Question
Title: Available approaches for moving userpoints from one user to another
Using the User Points module, I have this use case to design:

**"move user points from User A to User B"**

What are the possible approaches we have here?

# Answer
> 1 votes
There are at least 2 approaches you can choose from, as further detailed below ...

# User points donations

Use the Userpoints Donation module, which is one of the modules included in the (D7 version of the) Userpoints Contrib module.

To use it, make sure to also grant the required permission related to it (and to avoid asking yourself "How is the module Userpoints Donation intended to work?" ...).

# Rules

Use the integration between the User Points module and the Rules module to "roll your own cookies", by writing some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

```
{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

If you simply adapt the amount of points (-2 and -1) to something like (eg) +25 and -25, you've a prototype to transfer (25) user points from one user to another.

If you replace the Rules event by an event like "something is flagged" (created with the Flag module), a simple click could be used to indicate "I want to transfer 25 user points of mine to this user). You could take this even a step further: since flags are fieldable, you could add a field to indicate the amount of points to be "moved".

However, the above Rules example may need further refinements, e.g. if you want to ensure that after moving points van User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.

---
Tags: 7, userpoints
---


title: How can I set the email sender name?

text:
# Question
Title: How can I set the email sender name?
below code is not working in our custom module.

```
$site_name = \Drupal::config('system.site')->get('name');
$site_mail = \Drupal::config('system.site')->get('mail');

$message['headers']['From'] = $site_name . ' <' . $site_mail . '>';
$message['headers']['Sender'] = $message['headers']['Return-Path'] = $site_mail;
$message['from'] = $site_name . ' <' . $site_mail . '>';

It gives the output like this :

 MailSender <MailSender> <email@example.com>

```

and I want the output like this :

```
MailSender <email@example.com>

```

How can I do this?

# Answer
If you look at your code and the output you wrote, it come clearly out, that either:

* $message\['headers'\]\['From'\] = $site\_name . ' \<' . $site\_mail . '\>';
* $message\['from'\] = $site\_name . ' \<' . $site\_mail . '\>';

is not working at all.

I would get rid of the unnecessary code first, and then trying to modify the working line.
> 1 votes

---
Tags: 8
---


title: Migrate fields to another site?

text:
# Question
Title: Migrate fields to another site?
I have a Drupal 8 site with a contact form that has a lot of fields. I need to duplicate these fields onto another Drupal 8 site but can't find where they are stored in the DB.

In the config table there is a row per field, but when I try to copy these across, I get this message:

> Drupal\Core\Field\FieldException: Attempt to create a field my\_field\_name that does not exist on entity type contact\_message. in Drupal\field\Entity\FieldConfig-\>getFieldStorageDefinition() (line 286 of core/modules/field/src/Entity/FieldConfig.php).

Does anyone know if it's possible to copy the contact form fields to another site via the Database?

# Answer
Yes. One way could be:

1. You export your configuration. (drush cex -y, or on the interface configuration management)
2. You filter the configuration you need.
3. You import those configuration files into the other site (drush cim, or manually).
> 1 votes

---
Tags: 8, database, emails
---


# Question
Title: Print object in template_preprocess_page
In `template_preprocess_page()` in my MYTHEME.theme file, I'm trying to validate if node has specific value. When I `dpm($variables)` I get:

```
Array
(
    [node] => stdClass Object
    (
        [__CLASS__] => Drupal\node\Entity\Node
        [in_preview] =>
        [values] => Array
        (
            [vid] => Array
                (
                    [x-default] => 2
                )
...
    [page] => Array
    (
...

```

When I `dpm($variables['node'])` I get:

```
stdClass Object
(
    [__CLASS__] => Drupal\node\Entity\Node
    [in_preview] =>
    [values] => Array
        (
...

```

When I `dpm($variables['node']->values)` I get empty result.

**Why so?**

# Answer
you can use :

dpm($variables\['node'\]-\>toArray());
> 5 votes

# Answer
And for better debug view I advise you to use "kint" instead! You can iterate better through your objects.
> 0 votes

---
Tags: 8
---


title: Site broken after update

text:
# Question
Title: Site broken after update
I am building a drupal 8 site and I am keeping my code on git. I am using a copy of example.gitignore as my .gitignore which exclude vendor folder. I have been working on my sandbox, at some point I have update drupal core from version 8.1.1 to version 8.1.3 and push it to git.

I have created a new sandbox, pulled code from git and system throw few errors because vendor folder wasn't there so I run composer install. Even then, I still had errors. I run composer update and I had errors again.

What is the right procedure in order to keep drupal 8 on git and at the same time not having problem with vendor folder?

If you download drupal 8 from drupal.org it contains vendor folder, should I keep vendor folder on git?

Thanks in advance.

# Answer
I strongly recommend you (as a current best practice), to use Drupal8 Composer project

In this case, the root folder is going to contain "web" and "vendor" directories, so you will have to set your apache/nginix vhost for looking the index.php for one directory deeper.
> 0 votes

---
Tags: 8, updating, installation, composer
---


# Question
Title: How to determine if user X has access to operation Y on node Z
How can I programatically determine whether a certain user has "view" (or any other operation) permission for a given node?

I'm trying this, but it doesn't seem to be calling the node access hooks, and it's overall pretty ugly:

```
$node_grant_storage = \Drupal::service('node.grant_storage');

$current_user_has_access = is_a(
  $node_grant_storage->access(
    $node,
    'view',
    \Drupal::currentUser()->getAccount()
  ),
  'Drupal\Core\Access\AccessResultAllowed'
);

```

Ideally I'd like something to return a boolean and not a class (I have no use for the "neutral" option here, I just want to know if a user went into the `node/X` page, would they get a 403 or not).

# Answer
> 2 votes
This was easier than it seemed:

```
$current_user_has_access = $node->access();

```

This function has an optional parameter where you can pass an arbitrary user account, which defaults to the logged in user (suits my purpose).

---
Tags: nodes, 8, users
---


title: how to add tags to article pages

text:
# Question
Title: how to add tags to article pages
I'm new to Drupal. I accidentally deleted the Tag feature on our article page. Could someone explain how I can add it back to that page.

It also populated on a specific page.

# Answer
in Drupal 7

1. Go to admin/structure/types/manage/article/fields and add a new field named "Tags" with the type "Term reference" and the widget " Autocomplete term widget (tagging)"
2. in the setting field page, configure it to reference the vocabulary named "Tags" (if the vocabulary doesn't exist, just add it in admin/structure/taxonomy/add)
> 2 votes

---
Tags: 7, meta-tags
---


# Question
Title: Weirdness in views when grouping by a field, and a user has more than one entry in that field
I have a view that shows users. Users are associated with an Area in the organization. The view groups by Area (a vocabulary) and gives a list with nice area headings, with a list of Users inside it. Unfortunately there is one executive in the organization that is also in charge of another Area, and he needs to appear in both places. When I assign both areas to his account (entity reference field), we get the following (problematic user in bright blue):

What should happen, is that the blue user should appear once in the Executives area and once in the PMO area. Instead as you can see, he appears twice in his own special Executives \n PMO area. It would even be ok, if he only appeared in the Executives area here. What can I change to get this view to be nice to me?

# Answer
> 2 votes
In your hidden entity reference field's setting in Views, scroll down to *Multiple field settings* and **uncheck** *Display all values in the same row*.

When grouping, the content / user will get shown twice instead of what your screenshot shows.

---
Tags: 7, views
---


# Question
Title: How to have a field that counts the nodes submitted by the current user?
My site with existing content needs a field that shows the number of nodes of a certain content type that have been created by the current user.

I can't use Views because the field needs to be able to be used in a Rules condition.

Nor can I use Rules Actions and Flag at the time of adding nodes because so many nodes are pre-existing.

Nor can I use Display Suite code fields because I don't think they are able to be used in Rules either.

Is a computed field and a custom query the best option?

I have so far failed to find a code snippet and I am not experienced in PHP.

# Answer
> 3 votes
A method of using VBO+Rules to have a *minimum number of results* rule condition. It's a commonly used module and this can be really useful for a lot of things.

1. Create a standard view and add the author: uid as a contextual filter. The default value must be Raw: Path Component 2.
2. Add the VBO field, *Bulk Operations*.

Next, we add the condition to the rule.

1. Add *Check number of results returned by a VBO view* condition.
2. Select the VBO view we just created. Master is fine.. It just needs the Bulk Operations field to show up here.
3. Pass the current user's uid as an argument to the view. This gets sent as path component 2 which is why we had to choose it in the view.
4. Set your minimum number of nodes / users / comments etc. that your view is counting.

And done.

# Answer
> 5 votes
You can use the Computed Field module but you need to consider this:

> **When is the field actually computed?**
>
> If you wish to store the values in the database then you have to update or re-submit the node to compute the value of the field.
>
> If it is not stored in the database then the value computes when the node loads and only when the node is loaded. The field will not work in views nor will it function properly if it depends on other non-stored computed fields.

This is the code of your field:

```
global $user;
$type = 'article';

$query = new EntityFieldQuery;
$result = $query
->entityCondition('entity_type', 'node')
->propertyCondition('status', 1)
->propertyCondition('type', $type)
->propertyCondition('uid', $user->uid)
->execute();

$cant = count($result['node']);
$entity_field[0]['value'] = $cant;

```

Another way that come to my mind is have a variable to store this value, and you will edit this var each time a new node is created (`hook_node_insert`) or deleted (`hook_node_delete`), so in this case you will have always the real value.

**Rerefences:**

Computed Field

# Answer
> 2 votes
You could try using the Token Embed Views module, and then use this token on that field. I have not tried this method, but you could give it a try.

So, I suggest to create a view that does this counting, and embed this view into your field, using the module above.

---
Tags: 7, rules, entities
---


# Question
Title: Where and how should I use Composer and the drupal-composer/drupal-project scaffold to install the required libraries?
I installed Drupal 8 using the drupal-composer/drupal-project scaffold. I also installed the Devel module, and enabled its Webprofiler submodule.

Drupal status reports that Webprofiler needs:

* D3.js library
* highlight.js library

There's no libraries path in my Drupal installation.

As I'm using composer, both D3 and highlight have packages.

That's a preferred option.

Where do the libraries need to actually go when using this scaffold? What path?

How do I correctly use Composer on this install to put them there?

Although Where should I download libraries for modules through composer? talks about it, it's only for the case of Composer Manager, which I am NOT using.

# Answer
> 0 votes
This

https://github.com/drupal-composer/drupal-project/issues/68

clarifies the how-to install in custom locations, and NOT get redundant deps part of this question.

not yet, though, how to make Drupal -- particularly 'status' -- happy about it.

# Answer
> 2 votes
I use https://github.com/oomphinc/composer-installers-extender in my projects. It provides an composer installer for any package type.

---
Tags: installation, theming, composer
---


# Question
Title: How to change a user to a different role based on the number of their posts?
Are there any techniques out there that can put a user in a specific role into a different role automatically after they make X number of posts (core forum topics or/and replies)?

I'd like to implement a functionality where when users first register to my site they get put into a role which has limited privileges, but after certain number of posts to the forum (new topic or replies to existing) they get put into a different role that doesn't require CAPTCHA and they can post links etc. FYI using the core `Forum` and the Advanced Forum module.

# Answer
I found a module User Stats which integrates with Rules and provides tokens like \[user:post-count\] which can be used for numerical comparison. Hope this helps someone else.
> 9 votes

# Answer
The User Stats module only has a dev version for D7 (I'm assuming this question is about D7). However, your question seems like a perfect usecase for the Goals module (disclosure: I'm the maintainer of it). Below is a possible configuration for your specific case, using Goals.

# Configure a goal

Navigate to the relative path `admin/config/goals/manage` and use the link "Add a goal" to define just 1 **goal**, with a description (say):

> ***Make X number of posts (core forum topics or/and replies)***.

# Configure tasks

To achieve the *goal* "make X number of posts (core forum topics or/and replies)", define the **Task(s)** to be completed.

* Post a certain number of core forum topics.
* Post a certain number of replies.

A more advanced way to use (configure) Goals, is to configure tasks like so:

* some tasks might have to be repeated multiple times.
* some tasks may require some amount of time to expire in between any 2 similar tasks (eg: if a task is performed multiple times a day, only the first one counts).
* ... (there are others ...).

# Track progress while performing tasks

To track the progress made by a single user to complete some task, you only have to write the appropriate rules, using the Rules module, to record relevant events happening in your site, which are related to the completion of the various tasks.

For the goals/tasks described above as an example, you'd only need 2 (extremely basic) rules, which would be triggered like so:

* After posting a core forum topic.
* After posting a reply.

Note that these 2 rules can be re-used to measure progress on multiple goals (eg if your goal has a task like "after posting 1 reply", and a 2nd goal haS a task like "after posting 10 replies").

Moreover, the above challenges are pretty straight forward (basic) as examples of Challenges. But you can do this for virtually any entity for which you can think of a way to track them via the Rules module.

# Use Rules to process completed goals

After all tasks specific to a goal are completed by a user, the goal is automagically marked as completed. **But**, there is more: you can also create additional rules that will be triggered (Rules Event) when a goal is completed by a user. With that, the answer to your question is extremely easy: perform a Rules Action to "***... change the user to a different role***" ... which is exactly what your question is about, no?

# More of the same

Instead of the (boring) description of the goal above, you could have used a goal description like (say) "***Participating User***" instead. Which BTW could be a nice description of the role to be granted also.

If you then define (say) 3 more (similar) goals, with each of them an appropriate set of tasks to be completed, you could use the very same technique for goals (and/or roles) labeled something like so (if they sound familiar to something on Drupal.SE, that's purely be accident):

* Loyal User.
* Established User.
* Trusted User.
* Moderator.

# More info

Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for additional details about the Goals module.

Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).
> 2 votes

---
Tags: rules, users
---


title: Save a managed file with cURL

text:
# Question
Title: Save a managed file with cURL
I want to save a managed file from an external site. Previously, I've used this code:

```
$managed = TRUE; // Whether or not to create a Drupal file record
$image_file = system_retrieve_file($product['img'], 'public://product-img-' . time() . '.jpg', $managed);
if ($image_file) {
  $file = file_load(db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField());
  $item['field_image']['und'][0] = (array) $file;
}

```

However, it's throwing 403 errors for me so I decided to use cURL in my PHP code to get this image:

```
$ch = curl_init('http://g02.a.alicdn.com/kf/HTB15eliFVXXXXbKaXXXq6xXFXXXa/Original-Blackberry-Z10-Dual-Core-4-2-TouchScreen-2GB-RAM-16GB-ROM-8MP-Camera-Blackberry-os.jpg');
$fp = fopen('test.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

```

With cURL, it works correctly, and I can get the image. How can I save this data as a Drupal managed file?

# Answer
`file_save_data()` will take the contents of a file and place into a location specified by a file URI. In your example, you can take your downloaded **test.jpg**, retrieve its contents, and have `file_save_data()` do the rest.

```
// Assuming same cwd where curl & fopen was executed.
$image_file = file_save_data(file_get_contents('test.jpg'), 'public://test.jpg', FILE_EXISTS_REPLACE);

// test.jpg will be placed/overwritten into your managed file system.
// $image_file contains the Drupal file object.

```
> 1 votes

---
Tags: 7, files
---


title: Saving a line-item object

text:
# Question
Title: Saving a line-item object
Can anybody explain me why the right way for programmatically saving a line item object with Drupal Commerce is the following one?

```
commerce_line_item_save($item);
entity_get_controller('commerce_line_item')->resetCache(array($item->line_item_id));

```

I wish to be smarter after knowing that.

# Answer
> 1 votes
That isn't the right way to save a line item. All that second line does is remove the item from the entity controller's static cache.

As `CommerceLineItemEntityController::save()` already manipulates the static cache directly to ensure the updated entity is in it, the second line is redundant. All it does is force unnecessary database usage if/when the same line item is loaded again in the same request.

This is all you need to create or update a line item:

```
commerce_line_item_save($item);

```

Remember that `$item` is an object, so doesn't need to be passed by reference as you mentioned in the comments.

---
Tags: commerce
---


# Question
Title: How to get the entity that field belongs to in the case of an entity reference field
Here is my use case:

I have created a media bundle (FILM IMG) to store a media entity (image) field. I can manage it at `admin/structure/media/manage/film_img/fields`

In a content type named "FILM" , I have added a entity reference field which reference my "FILM IMG" media entity bundle.

I am also using file\_field\_path module to rename the uploaded images. When I am adding a new image for a new Film, I would like to use hook\_filefield\_paths\_process\_file to rename my image file name.

This hook is providing me the media entity ($entity) as a parameter, but of course it is not providing the Film entity that I need (I need it to get some info to rename my file name)

Here is my question: How to get the "parent" entity from the referenced entity;

In other words, with my use case: How to get my film node from the image media entity provided by the hook.

# Answer
> 3 votes
You can get that with an entity query:

```
// Get IDs of all film nodes that reference this entity
$nids = Drupal::entityQuery('node')
  ->condition('type', 'film')
  ->condition('field_foo.target_id', $entity->id())
  ->execute();

// Load the nodes
$nodes = Drupal::entityManager()
  ->getStorage('node')
  ->loadMultiple($nids);

```

---
Tags: 8, entities
---


title: One exposed filter for multiple views

text:
# Question
Title: One exposed filter for multiple views
One exposed filter for multiple views

I have an exposed filter which is a date field containing a month and year using the “date module”.

I want to use different views to read the URL and filter with a “Contextual Filter”. This is how the URL looks and I can see it has separated out the Month and Year;

```
?field_month_value%5Bvalue%5D%5Bmonth%5D=6&field_month_value%5Bvalue%5D%5Byear%5D=2016&=Apply.

```

I know the contextual filter in views is looking for 062016 so I’m struggling to read the URL in the contextual filter. Is it possible to use PHP GET in the contextual filter to get the month and year and convert it to 062016?

```
if(isset($_GET[' field_month_value']))
    return $_GET[' field_month_value'];
else
    return;

```

I’m using D7. Thanks loads

# Answer
> 1 votes
From your question, I believe you want one exposed filter to reload the page when chosen and then all the other views on the page follow that filter?

A workaround if no one else answers is to expose the filter on all views and hide the ones you don't want with css. In each view, go to the filter's settings under Admin at the bottom and you can rename them all to *field\_month\_value* if they're different.

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


# Question
Title: View sorting becomes arbitrary with grouping field?
**The setup:**

A view that lists out nodes containing study abroad *Program* information. Its format is *Unformatted List*. There is a *Grouping field* of *Country* (which is a field on the *Program* content type). The list is sorted by *Country* (asc) and then *Program* title (asc).

There are exposed filters (via Better Exposed Filters) for a few of the fields from the *Program* content type... one of which is *Country*. These filters are exposed in a block that's included on the view page.

**The Problem:**

When you perform a search via the exposed filter block with multiple *Countries* selected, the sort order seems arbitrary. The grouping (by *Country*) works, but the *Countries* are listed out of order... not alphabetical asc or desc... just arbitrary.

Worth mentioning: any other search using any of the other exposed filters, but not selecting any *Country* values, works fine.

What's going on here? Why does sort get wacky when searching by *Country*... which, coincidentally or not, is also the grouping field?

---

# Answer
> 2 votes
It seems that disabling "Reduce duplicates" on the exposed filter of the grouping field will bring the sort back in order. So, in this case, unchecking "Reduce duplicates" on the exposed filter, Country (which is also the grouping field) did the trick.

---
Tags: views
---


title: Retrieve GET request from Block Plugin

text:
# Question
Title: Retrieve GET request from Block Plugin
I'd like a block plugin to display content dependent on a GET request. Inside my block plugin I have

```
class BlogPage extends BlockBase {
    public function build() {
        $query = \Drupal::entityQuery('node')
            ->condition('type', 'blog_post')
            ->sort('created', 'DESC')
            ->range(0, $range);
        return $query;
    }
}

```

I'd like to make $range retrieve info from a GET request. For example I'd like 127.0.0.1/page?range=5 to make $range = 5. I've tried

```
$range = Request::get('range');

```

But that does not work. Is there a way to return the values in a GET request from inside the block plugin?

# Answer
You need to get the current request object first:

```
$request = \Drupal::request();
$range = $request->get('range');

```

Or

```
$range = \Drupal::request()->get('range');

```
> 4 votes

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


title: How to translate a mobile jQuery menu?

text:
# Question
Title: How to translate a mobile jQuery menu?
`Drupal.t('Select a page')` is not translated into another language (mobile menu) after clearing cache and translating strings through the translation menu. What should be added or changed to get translation? Theme Growth Lite (jquery.mobilemenu.js)

```
var settings = {
    combine: true,  //combine multiple menus into a single
select
    groupPageText: 'Main',  //optgroup's aren't selectable, make an option for it
    nested: true,                   //create optgroups by default
    prependTo: 'body',              //insert at top of page by default
    switchWidth: 480,               //width at which to switch to select, and back again
    topOptionText: Drupal.t('Select a page')    //default "unselected" state
},

```

# Answer
> 0 votes
Actually, it was not clear but there is an option in the theme itself to put change the phrase 'Select a page' and it becomes untranslatable. You have to remove it in the theme itself and change it in the file jquery.mobilemenu.js and then translate it through Drupal.

---
Tags: javascript
---


# Question
Title: When 'cron_safe_threshold' is set to 0 in settings.php, should the dropdown value on admin/config/system/cron be "Never"? or is it irrelevant?
I've installed Drupal 8.1.6. As Ultimate\_Cron won't work on this site consistently or reliably, I've decided to just use Drupal's core cron, triggered externally (via /etc/crontab) rather than using Poormanscron.

The documentation on https://www.drupal.org/cron says:

> ### Disabling "automated cron"
>
> Another way to disable cron is to add the following line to your settings.php: $conf\['cron\_safe\_threshold'\] = 0; Note that this fixes the setting at admin/config/system/cron to "Never", and administrative users cannot override it.

I set `$conf['cron_safe_threshold'] = 0;` in the settings.php file, but when I go to admin/config/system/cron, I still see the following:

> Cron settings
> Run cron every 3 Hours

What does *fixes the setting at admin/config/system/cron to "Never"* actually mean?

1. The value I see is set to "Never", and can't be changed
2. The value is overwritten in the {variables} table to a fixed value equal to 0, and that the displayed drop-down value on admin/config/system/cron is irrelevant

p.s.

There's gotta be an easier way to find out available $conf settings than this

1) realize that cron in Drupal8 is actually controlled by a core module

```
cd web/core/modules/automated_cron

```

2) look for any drupal::config() assignments

```
grep -i "drupal::config(" *.module
    $automated_cron_settings = \Drupal::config('automated_cron.settings');

```

3) for each one found, get set-able vars

```
grep -i "automated_cron_settings" *.module | grep "=>"
    '#default_value' => $automated_cron_settings->get('interval'),

```

NOTE: in default.settings.php

```
 * Example:
 * @code
 *   $conf1) realize that cron in Drupal8 is actually controlled by a core module

     cd web/core/modules/automated_cron

     2) look for any drupal::config() assignments

         grep -i "drupal::config(" *.module
                 $automated_cron_settings = \Drupal::config('automated_cron.settings');

                 3) for each one found, get set-able vars
                     grep -i "automated_cron_settings" *.module | grep "=>"
                             '#default_value' => $automated_cron_settings->get('interval'),
                             ig_directories = array(
 *     CONFIG_SYNC_DIRECTORY => '/directory/outside/webroot',
 *   );
 * @endcode
 */

```

Re: automated cron, no less

and, a 'simpler' method:

```
drush cli | grep -i cron
    automated_cron.settings
    system.cron

drush cget automated_cron.settings
    interval: 10800
    ...

drush cget system.cron
    threshold:
      requirements_warning: 172800
      requirements_error: 1209600
    ...

```

# Answer
This setting is for Drupal 7. In Drupal 8, the equivalent is in the config management system as `automated_cron.settings.interval`. To override it, like in Drupal 7, you can add:

```
$config['automated_cron.settings']['interval'] = 0;

```

to your **settings.php**.

To address the other question, the relevance of `automated_cron.settings.interval` & `cron_safe_threshold` is the minimum amount of time (in seconds) since the last cron run that Drupal is allowed to run again. This value is checked (D7 & D8) for a 0 threshold which it will interpret as `FALSE` and thus never run cron.
> 7 votes

---
Tags: 8, drush, cron, configuration
---


# Question
Title: How to check if a database is set up in settings.php?
I am creating a module for Drupal 8. One of the requirements is that you first add a new database in settings.php. On the admin page, I want to check if the user did this step and show a warning if he didn't. I tried this:

```
global $databases;

```

But doing a var\_dump shows nothing.

How do I access the databases variable so I can check if the database is setup?

# Answer
global $databases has been removed in favor of the preexisting static connection info management methods on the Database class.

Drupal 7

```
global $databases;
// Check whether we have a default connection.
$has_connection = !empty($databases['default']['default']);

```

Drupal 8

```
use Drupal\Core\Database\Database;
$has_connection = (bool) Database::getConnectionInfo('default');

```

More links

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

https://www.drupal.org/node/1951216
> 10 votes

---
Tags: 8, configuration
---


title: How to add class to teaser P?

text:
# Question
Title: How to add class to teaser P?
In Drupal 8, how can I add a class to teaser p html tag. I want to style the paragraph in teaser only, not when whole content is shown.

# Answer
We can style that with simple css,

```
.node--view-mode-teaser .node__content p {
  /* write you style */
}

```

I think, you don't need to add separate class in P tag for that. and it would also affect only the teaser mode content :)
> 4 votes

# Answer
**Assuming you're talking about the default front page teasers**:

Edit the Frontpage view, and Instead of `Show: Teaser`, click on teaser and change it `Show: Fields`

Then you basically create your own custom teaser.

Add Fields: title, body (summary or trimmed), post date, comments link, etc...

Then **click on Style Settings** and the classes to your body (re-using pic from another answer)
> 3 votes

---
Tags: theming, 8
---


# Question
Title: LoginToBoggan + Don't use set password mail
I would like to give my user the opportunity to register and login with username AND email.

Therefore I installed the module LoginToBoggan where you can enable that users can login using their e-mail address.

When you want users to set their password at registration you need to check the checkbox **Set password**. But when you do this you also get a mail to set your password (can only be used once).

But I don't want that. I just want them to register with email/username and directly login in without getting ANY email. I fire a rule to send a mail after I created an invoice so I don't want the drupal account emails.

But I didn't found out how I can simply do this?

# Answer
I use the same type of setup as the one you describe:

* Register and login with username and email.
* Login using the email address.
* User sets password upon registration (i.e. no email confirmation required).

I've found that the process where user receives a one-time link to set password is a huge stumbling block in the registration process.

Drupal let set up the site to have user sets password upon registration (Uncheck "Require e-mail verification when a visitor creates an account" on *Administration » Configuration » People » Account settings*).

However, I do *not* use LoginToBoggan to allow the users to login using the email address.

Instead, I use Realname Reg. Please note that this is a sandbox project, but it is actively maintaned (by me), and it has been tuned specifically for the use case you describe. I've used it on a dozen production sites for about a year with no issues.
> 1 votes

# Answer
I faced the same problem a few days ago, I was using this logintoboggan module but didn't want my user to confirm emails, just register with password and login as well, so what I did is to remove the 'non-authenticate' user role from the user and add 'authenticate' role when the user login for the first time.

```
/**
 * Implements hook_user_login().
 */
function mymodule_user_login(&$edit, $account) {
  if (in_array('non authenticated user', $account->roles)) {
    // remove non-auth role from user object.
    _remove_role_from_user($uid, 'non authenticated user');
    // Add auth role to user object.
    _add_role_to_user($uid, 'authenticated user');
  }
}

function _add_role_to_user($user, $role_name) {

  // For convenience, we'll allow user ids as well as full user objects.
  if (is_numeric($user)) {
    $user = user_load($user);
  }
  // If the user doesn't already have the role, add the role to that user.
  $key = array_search($role_name, $user->roles);
  if ($key == FALSE) {
    // Get the rid from the roles table.
    $roles = user_roles(TRUE);
    $rid = array_search($role_name, $roles);
    if ($rid != FALSE) {
      $new_role[$rid] = $role_name;
      $all_roles = $user->roles + $new_role; // Add new role to existing roles.
      user_save($user, array('roles' => $all_roles));
    }
  }
}

function _remove_role_from_user($user, $role_name) {
  // For convenience, we'll allow user ids as well as full user objects.
  if (is_numeric($user)) {
    $user = user_load($user);
  }
  // Only remove the role if the user already has it.
  $key = array_search($role_name, $user->roles);
  if ($key == TRUE) {
    // Get the rid from the roles table.
    $roles = user_roles(TRUE);
    $rid = array_search($role_name, $roles);
    if ($rid != FALSE) {
      // Make a copy of the roles array, without the deleted one.
      $new_roles = array();
      foreach($user->roles as $id => $name) {
        if ($id != $rid) {
          $new_roles[$id] = $name;
        }
      }
      user_save($user, array('roles' => $new_roles));
    }
  }
}

```
> 0 votes

---
Tags: users, authentication-authorization
---


# Question
Title: Catch the English name of a translated taxonomy term (token)
I'm building up a multilingual website (Drupal 7) with Locale and Content translation modules enabled for nodes. The node category is managed thru a content\_area field (taxonomy term thru Entity Reference module), which is translated with Entity Translation and Title modules in order to have a translated path in URL (using Pathauto module). Everything goes as expected, the content\_area is translated in URL, in the breadcrumb and in the tags area.

As each node manages more images, shared among languages, we've built a file folders structure which comply with paths (not equal but similar) in order to keep a clean images structure, using File (Field) Paths module. Problems arise: if the content\_area field (taxonomy term) is untranslated (i.e. English), we have only one folder for images of all languages (as expected), but if we translate the content\_area field we get a translated folder keeping images, as we do not want.

When setting up File (Field) Paths for images field in File path, we expected to find a token related to the untranslated/translated \[node:field\_content\_area:name\], with no luck. Even \[node:source:field\_content\_area\] cannot work and do not work, as we cannot know if the editor building up the node content will begin ('source') from English or from another language.

I hope I have been clear, it is my first post. Thanks in advance

# Answer
> 0 votes
Decipher's blog suggested the answer: I initially created a custom module to define a custom token to use in FileField Paths, and then I installed Custom Tokens module, and created same token as before.

Both methods worked, and at the end I'll use second method (installing Custom Tokens module, without my custom module), as it will be easier to create other tokens when needed.

Method 1:

```
/**
 * Implements hook_token_info().
 * gw_content_area_en is the token used as [node:gw_content_area_en]
 */
function MODULENAME_token_info() {

    $info['tokens']['node']['gw_content_area_en'] = array(
      'name' => t('Gw Content Area EN'),
      'description' => t('English version of field_gw_content_area'),
    );

    // Return associative array of tokens & token types
    return $info;

}

/**
 * Implements hook_tokens().
 */
function MODULENAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  // Check if token type is node
  if($type == 'node'){
    foreach ($tokens as $name => $original) {
      switch ($name) {
        // Check token is gw_content_area_en
        case 'gw_content_area_en':
          $tid = $data['node']->field_gw_content_area[LANGUAGE_NONE][0]['target_id'];
          $term = taxonomy_term_load($tid);
          $replacements[$original] = $term->name_original;
          break;
      }
    }
  }
  return $replacements;
}

```

Method 2:

1. Install Custom Tokens module;
2. Create a new token with following settings:

* Token name: Gw Content Area EN
    * Token description: English version of field\_gw\_content\_area
    * Token type: Nodes
    * Content:

$tid = $data\['node'\]-\>field\_gw\_content\_area\[LANGUAGE\_NONE\]\[0\]\['target\_id'\];

$term = taxonomy\_term\_load($tid);

return $term-\>name\_original;

---

New custom token used to set FileField Path.

Note: i18n\_taxonomy module disabled.

---
Tags: 7, entities, tokens
---


# Question
Title: Add "Request new Password" link to user logIn page
I am using the Logintoboggan module to redirect users to the login page when they try to visit a page for which they don't have the permission to visit.

How do I add a *Request new Password* or *Forgot Password?* link to this page?

# Answer
This should be already there as a link. if it is a custom login page, you can add a link with "/user/password" href
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: How do I execute code before update the content?
How do I execute code before updating nodes?

I am looking for a hook to use in a custom module.

I have created a content type. What I need to do is execute a hook before updating any content. I want to keep the history of every content, so I want to execute some code before updating, which will compare previous and currently update record. If there is any change, I want to insert it in another table.

I also want to show that history on the content detail page.

# Answer
> 5 votes
I use the Hook Post Action module because it's execute after the action. So you know that the node is really updated.

> So this module introduces several new Drupal hooks to overcome this limitation
>
> * hook\_entity\_postsave
> * hook\_entity\_postinsert
> * hook\_entity\_postupdate
> * hook\_entity\_postdelete
> * hook\_node\_postsave
> * hook\_node\_postinsert
> * hook\_node\_postupdate
> * hook\_node\_postdelete

But, if you want you can use the hook\_node\_update.

To show info in the node page you can use the EVA module.

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

# Answer
> 5 votes
I think, `hook_node_presave` would help for your requirement. Act on a node being inserted or updated. This hook is invoked from `node_save()` before the node is saved to the database.

# Answer
> 2 votes
The hooks that are called before Drupal saves the node in the database are the following ones (in the order from the first to the last one):

They are all equivalent, since they get the object being saved.

Keep in mind that, since `node_save()` is using a database transaction, you cannot be sure the data is rolled back, or effectively saved in the database, until the last database operation is not completed.

---
Tags: nodes, hooks
---


title: Custom theme covering up admin toolbar.

text:
# Question
Title: Custom theme covering up admin toolbar.
I am trying to convert a template to a custom drupal 8 theme and am having trouble with it covering the admin toolbar when logged in. I tried to inspect bootstrap when installed to see what was added but to no avail. I am trying to create a custom theme from scratch and not a subtheme. Any help is appreciated to find out what css that I can add that will push the content down while logged in?

Thanks

# Answer
Drupal 8 admin toolbar z-index value is 502 only, but the bootstrap default static navbar z-index value is 1000, I think, Increase the admin toolbar z-index value would fix the issue,

```
.toolbar-oriented .toolbar-bar {
 z-index: 1001 /* or more */
}

```

Place that code in your theme's custom css file :)
> 3 votes

---
Tags: theming, toolbar
---


# Question
Title: Is there any way to use views contextual filters in block configuration?
For my situation, i need to create views for taxonomy terms content listing, I have created that with blocks. I am using contextual filter in that views to filter the content with taxonomy terms dynamically.

Is there any way to give value for contextual filter from block configuration page ?

If we have that options, then it would save me from creating separate blocks for each terms.

Contextual filter configuration :

My question is can i give value for the contextual filter from the block configuration page ?

# Answer
> 2 votes
The contextual filter is not possible to be exposed on a block. It is only possible with filter criteria.

The other posibility is use a taxonomy term view and use the module Taxonomy menu or Taxonomy menu block to show a list of taxonomy terms on a block.

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


# Question
Title: how to add other component (html tag, js, and css) in form module
Suppose I have the following code.

```
class customCreateForm extends FormBase {

/* code code code... */

  public function getFormId() { /* code */ }
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['label'] = array(
      '#type' => 'textfield',
      '#title' => t('title'),
      '#description' => $this->t('Your title'),
      '#default_value' => "",
      '#size' => 10,
      '#maxlength' => 8,
      '#required' => TRUE,
    );
    /* code code code... */
    return form;
  }
  /* code code code... */
}

```

I can understand how to add a form element, but how can I add HTML markup or JavaScript?

For example, I want to add the following in my custom form.

```
<link type="text/css" rel="stylesheet" href="bla...">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div id="something" class="something">
        <img src="bla" />
    </div>
<table id="something" class="something"><tr><td>aaa</td></tr></table>

<script>
/* code code code */
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=aaaa&libraries=places&callback=initAutocomplete" async defer></script>

```

# Answer
you should add a library like this :

```
$form['#attached']['library'][] = 'my_module/mylibrary';

```

Create mylibrary.libraries.yml file with the content :

```
mylibrary:
  version: 1.x
  css:
    theme:
      css/my-css.css: {}
  js:
    js/my-js.js: {}

```

more documentation: https://www.drupal.org/developing/api/8/assets
> 3 votes

# Answer
Add html content with #markup type form field for example,

```
$form['html-content'] = array(
  '#markup' => '<div class="your-class"><h2>your content</h2></div>,
);

```

Form API have an option to add javascript and css with #attached option, we could add as library,

```
$form['#attached']['library'][] = 'module/library-name';

```
> 2 votes

# Answer
See Render API overview. What reported there is also valid in the case of a form, which is a render array nonetheless.

* Libraries, JavaScript settings, feeds, HTML `<head>` tags and HTML `<head>` links are attached to elements using the `#attached` property.

```
$build['#attached']['library'][] = 'core/jquery';

```

```
    $build['#attached']['drupalSettings']['foo'] = 'bar';

```

```
    $build['#attached']['feed'][] = [$url, $this->t('Feed title')];

```
* To output generic HTML markup you use:

+ `#type` or `#theme`, which are preferable when the output is complex
    + `#markup`, which is preferable when the output is simple, considering also that its output is filtered by `\Drupal\Component\Utility\Xss::filterAdmin()`; in this case, if you need to output one of tags that is not listed in `Xss::$adminTags`, you need to use `#allowed_tags`

    ```
    $build[
      '#type' => 'view',
      '#name' => $name,
      '#display_id' => $display_id,
      '#arguments' => $args,
    ];

    ```

```
        $form['contacts'] = array(
          '#type' => 'table',
          '#caption' => $this->t('Sample Table'),
          '#header' => array($this->t('Name'), $this->t('Phone')),
        );

        for ($i=1; $i<=4; $i++) {
          $form['contacts'][$i]['name'] = array(
            '#type' => 'textfield',
            '#title' => $this->t('Name'),
            '#title_display' => 'invisible',
          );

          $form['contacts'][$i]['phone'] = array(
            '#type' => 'tel',
            '#title' => $this->t('Phone'),
            '#title_display' => 'invisible',
          );
        }

```

```
        $output['filtered_string'] = array(
          '#markup' => '<audio controls><source src="horse.ogg" type="audio/ogg"><source src="horse.mp3" type="audio/mpeg">Your browser does not support the audio tag.</audio>',
          '#allowed_tags' => ['audio', 'source'],
        );

```
> 0 votes

---
Tags: forms, 8
---


# Question
Title: How do you 301 redirect links in Drupal via the .htaccess modredirect rules to keep spidered links?
I am migrating a site to a new domain and I would like to do a 301 redirect via the .htaccess file to create a redirect rule. I have over a 1000 dynamic links generated via views so this isn't do able with a redirect module as easily. I just want to get an example modrewrite rule to put in my .htaccess file.

# Answer
> 1 votes
Also have a look at the Redirect module. Managing redirects in the database might have some advantages over putting them in a .htaccess file.

# Answer
> 0 votes
Here's what i put in my .htaccess file:

I wanted to redirect urls from: www.abc.com/buy/tennis/shoes/1232

TO: www.xyz.com/buy/tennis/shoes/1232

Line 100:

```
RewriteRule ^buy(/?.*) http://www.xyz.us/buy$1 [R=301,L]

```

Note: You have to put this rule above the other rewriterules. I put it below the rewriterule ^ index.php and broke the site. just an fyi as I'm not exactly sure why it broke. if someone else can shed some light on this it would be great.

---
Tags: 7, migrations, redirection
---


# Question
Title: How to display users with same select list value on a custom user profile page
Firstly in my site, using Profile 2. i created a 'Select list field' that allows each user to choose his/her country.

I then created a custom user profile page using views by following these steps:

1.Create a view and add a "page" display. 2. Use "user/%" as the page path. 3. Add a contextual filter "user uid" and select "provide default value" user ID from URL.

Now i want to add a block to each users profile page that displays all users from the same country as the currently viewed user profile

I have tried adding the "Profile Country" contextual filter and selecting "provide default value" user ID from URL but no results are displayed.

Is there a way to do this?

# Answer
The problem is you're relying on your contextual filter to mean 2 things:

* For the page it has to be the UID.
* For the block it has to be the country select value that corresponds to the UID.

If you're wanting to configure it this way, you'll need your block view to derive the profile country value from a UID. One way you could do this is to use *Provide default value* \> **Type**: *PHP Code* options with something like this:

```
if ($user = user_load(arg(1))) {
  $profile = profile2_load_by_user($user);
  return $profile['my_profile_machine_name']->field_my_country_field_name[LANGUAGE_NONE][0]['value'];
}

```

The actual code will vary based on your Profile2 configuration.
> 2 votes

# Answer
Try the following:

* Create a new view that shows Profiles of the types you defined.
* Select "Create block" instead of "Create page".
* Give it a title, and select a display, either table, unformatted list of fields or entities, or anything else
* Add a "Contextual filter". Select the **Country field** as contextual filter
* In "When filter value is *not* available" choose "Provide default value"
* Select Type: PHP code

Use a variation of this code, without the php tag

```
global $user;
$profile = profile2_by_uid_load($user->uid, 'YOUR_PROFILE_MACHINE_NAME');
$filter = $profile->field_YOUR_COUNTRY_FIELD_NAME[LANGUAGE_NONE][0]['value'];
return $filter;

```

So, what this code does is: it provides a value to the contextual filter for your profile view, so that only records that match the country code for the currently logged in user will be shown.

NB: you may need to modify the part after \[LANGUAGE\_NONE\] depending on how the value for your country field is store. Alternatively you can use a entity\_metadata\_wrapper in line 3, as in

```
$w = entity_metadata_wrapper('profile2', $profile);
$filter = $w->field_YOUR_COUNTRY_FIELD_NAME->value();

```

Additionally you may want to test if the field for Country is empty before everything else.

Don't forget to enable the block in Structure \> Blocks so that you can view it.

Good luck.
> 0 votes

---
Tags: users
---


# Question
Title: Drush stoped working and drush status -v shows Executing: vagrant
It's important to say that *I don't use vagrant!*

For some reason this afternoon drush stoped working, it remains stuck. If I run `drush status -v` I can see it get stuck at `Executing: vagrant`. I may have typed something wrong at some point, maybe installed vagrant instead of varnish module but I can't remember and now I can't use drush anymore.

Does anyone have a clue on how to stop drush from trying to execute vagrant silently?

# Answer
I just realize that I in the `~/.drush/` folder there is a `drush-vagrant` folder, after deleting it everything started working again. The folder is from the drush-vagrant module that I installed by mistake. See drush folder download answer: How to download directly to ~/.drush folder?
> 2 votes

---
Tags: drush, virtual-machine
---


# Question
Title: style.css doesn't refresh while Bootstrap sub-theming
I followed the Drupal Bootstrap sub-theming documentation: basically copied the CDN starterkit and renamed all the files and it seems to work. I then added a line to the empty css/style.css.

At first it didn't work except when I went to /admin/appearance/settings/ and clicked the advanced tab and set the theme to 'Bootstrap (Default)'.

I then made more modifications to the style.css, this time it didn't refresh on the pages. Checking the rendered pages I found the css file is coming as a mangled named css file.

What is involved in generated this mangled file and how to refresh after modifying css/style.css?

Can I choose a different theme from the Bootstrap settings page and still use my css modified styles?

# Answer
> 1 votes
The mangled file comes from aggregating CSS files. You will need to clear/flush the cache in order to see changes.

You can turn CSS caching off by going to `/admin/config/development/performance` and unchecking aggregate CSS files. Now you don't need to clear the cache to see CSS changes.

**PS:** Remember to turn this back on when your website is ready for production/going live.

---
Tags: 8, theming
---


title: Cannot seem to find jQuery

text:
# Question
Title: Cannot seem to find jQuery
The jQuery module is said to be part of core in Drupal 8, but I couldn't find on the admin pages and still pages are loaded without any jQuery links.

I am using the Bootstrap theme. How do I set it up to load jQuery?

# Answer
> 3 votes
It's the jQuery Update module that is not necessary with Drupal 8, since *Drupal 8 ships with the latest jQuery, and the plan is to continue increasing the shipped version (with BC available) in further minor releases*.
Drupal always used the jQuery library; the jQuery Update module is only necessary to use a version of jQuery different from the one shipped with Drupal.

As for loading jQuery together the theme assets, as explained in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme you need to add core/jquery to the dependencies. For example, the following content of an hypothetic fluffiness.libraries.yml file would load the jQuery library on the pages where the theme with that file is used.

```
cuddly-slider:
  version: 1.x
  css:
    theme:
      css/cuddly-slider.css: {}
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery

```

# Answer
> 2 votes
JavaScript and CSS assets in Drupal 8 are implemented as libraries. There is an API for adding those to your modules and themes. jQuery is one of them.

---
Tags: 8, javascript
---


title: Show Author's Info in a Block

text:
# Question
Title: Show Author's Info in a Block
How would I go about creating a block that displays the current page's author name, picture and short bio? I'm new to Drupal and don't know if this is done using a View block, custom block or by editing a block template. The block should only display if in a page or certain content type.

# Answer
This will be little bit lengthy process but can be done. This you can do by Views module which is in core in Drupal 8, BUT before that you have to do some other stuff with the user account. The entire process I am listing out in steps.

Since your question is not complete clear, I am providing the method for Author Info only, if you clarify I will add the second part.

**Author Info Block**

1. Adding - Bio field & Social media profile field
2. Creating Views.
3. Add created block to appropriate place.
4. Block visibility setting

**1. Adding - Bio field & Social media profile field**

Now, the user profile setting do not provide the Bio field by default hence we need to create that one.

1.1 Go to Configuration\>Account Setting\>Manage field

1.2 Add new field name: **Bio**, field type: Long text(formatted, long)\>save

1.3 Add new field **Social Links**: Install and enable the Social Profile Field. What this module does, this module provide the field which provide the provision for adding the social media links, The link will automatically converts to **ICONS**, that is the good part.

Again go to Configuration\>Account Setting\>Manage field and add new field **Social link** and for this choose field type: Social profile field. Note: The picture field is by default, which provides by core.

The final screen shot will be looks as below,

*Now, Under the user profile- Bio and Links will be added as new field so you can add this by going under Edit of any user profile.*

Now, we add set to go for Views,

**2. Creating Views: Author info**

2.1 Go to Structure\>Views.

2.2 **Add new view:** Author Info. Select Users in views setting. Select Create a block in Block setting. Set Unformatted list of Filed under Block display settings. Select 1 under items per block. Click-\>Save and edit.

2.3 **Views setting page:**

2.3.1 Now add Relationship: Go under Advanced setting. under relationship click add and from the list select Content Author, give it a name Author node as shown in the following image of 2.3.4.

2.3.2 Now add contextual filter: Same as above step, click add to contextual filter. select ID. And select Provide default value. Under that select Content ID from Url. (as shown in following image)

2.3.3 Come under FIELDS and add following field: Picture(category: User), Bio(category: User), Links(category: User).

2.3.4 Remove anything which is under the FILTER CRITERIA. Save it. Your final views setting page will be looks like this,

**3. Add the created block:** Go to Structure\>Block\> and under first sidebar add this block.

**4. Block visibility setting:** Now, till this step, everything works fine, but these blocks are not visible to Anonymous user, And to set that, Go to Again go to views setting as shown in just above image, under BLOCK SETTING \> Access click permission and select none option, and save. Now, this block will be visible to all users.

**Output Image:** I have reprocessed this above mentioned process in my Drupal 8 trial site and you can see in following image, with all Author info. on only page which has been authored by that author.
> 6 votes

# Answer
Create a new View, of `Show: users` and checkmark block

Add the fields you want, user pic, user name, etc...

Under Advanced, Add CONTEXTUAL FILTER of User ID with these settings:

Your view preview will go blank, which is normal here, since views is not able to get the node author from the view url. The view will show up when you go to the page/node where you placed the block.

Now create a another user block view. This will be the "Latest Stuff". This time under advanced, add RELATIONSHIP of `Content authored`

Add your title field and other fields you want.

Use same contextual filter as the 1st view.
> 3 votes

---
Tags: 8, blocks
---


title: Multistep form makes same submissions

text:
# Question
Title: Multistep form makes same submissions
I created a Ctools Multistep form. Its working fine. But when a user opens this multistep form in two tabs and fill the form fields simultaneously and submits it, **both the submitted forms have same values for all the fields. Means both the submissions have same data**.

When I have submitted this form in different browsers simultaneously, then both submissions have their own data.

I followed this tutorial to make Ctools Multistep form : http://www.xenyomedia.com/content/4-steps-form-multistep-form-ctools

I think, the problem is with **$object\_id = 'ctools\_multistep';**, because its same for both the forms in different tabs. Thats why it creates the same submissions for both forms.

Can anyone help me regarding this?

# Answer
You have picked up correctly, the root cause for this issue is the object\_id used by ctools multistep form, which is being generated per session. And for different tabs in a browser, we have the same session. So basically we need to figure out a way to get different object\_id for each tab. This can be done in two ways: 1. Modify session mechanism to have a different session per tab. (Difficult) 2. Use query\_parameters to handle two different requests. (For eg: time as id)

So, using 2nd way to solve our the problem: Get object\_id dynamically.

```
$object_id = _module_get_object_id();

```

Ensure if id exists in URL, else return newly generated id.

```
function _module_get_object_id() {
  $params = drupal_get_query_parameters();
  if (isset($params['id'])) {
    return $params['id'];
  }
  else {
    $params['id'] = time();
    return $params['id'];
  }
}

```

and most **important step**, for **adding id in URL as query parameter** we need to add following code in the ctools\_multistep\_wizard\_next function:

```
drupal_goto($form_state['redirect'][0], array('query' => array('id' => $form_state['object_id'])));

```

Reference: http://savaslabs.com/2015/06/23/implementing-ctools-multi-step-form-block.html
> 0 votes

---
Tags: 7, chaos-tool-suite, forms
---


# Question
Title: Drush dl not working with PHP 7 and ubuntu 16.04
When i try to do:

```
drush dl drupal-8

```

i get the following error:

```
PHP Fatal error:  Uncaught Error: Call to undefined function Drush\UpdateService\simplexml_load_file() in /home/alexander/.config/composer/vendor/drush/drush/lib/Drush/UpdateService/Project.php:74
Stack trace:
#0 /home/alexander/.config/composer/vendor/drush/drush/lib/Drush/UpdateService/ReleaseInfo.php(64): Drush\UpdateService\Project::getInstance(Array, 86400)
#1 /home/alexander/.config/composer/vendor/drush/drush/lib/Drush/UpdateService/ReleaseInfo.php(122): Drush\UpdateService\ReleaseInfo->get(Array)
#2 /home/alexander/.config/composer/vendor/drush/drush/commands/pm/download.pm.inc(111): Drush\UpdateService\ReleaseInfo->selectReleaseBasedOnStrategy(Array, '', 'auto', false, NULL)
#3 /home/alexander/.config/composer/vendor/drush/drush/includes/command.inc(366): drush_pm_download()
#4 /home/alexander/.config/composer/vendor/drush/drush/includes/command.inc(217): _drush_invoke_hooks(Array, Array)
#5 /home/alexander/.config/composer/vendor/drush/drush/includes/command.inc(185): drush_command()
#6 /home/alexander/.config/compos in /home/alexander/.config/composer/vendor/drush/drush/lib/Drush/UpdateService/Project.php on line 74
Drush command terminated abnormally due to an unrecoverable error.

```

Other commands does work: drush cc, drush status.

Here's output of drush status:

```
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php/7.0/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/alexander/.config/composer/vendor/drush/drush/drush.php
 Drush version          :  8.1.2
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

```

# Answer
Sounds like you managed to install/configure PHP without the simplexml extension.

Install the php7.0-xml package with apt-get as follows.

```
sudo apt-get install php-xml

```

Also check the UI installer, if you're missing this, then you're likely also missing a bunch of other extensions link mbstring, gd and so on to install/use Drupal.
> 21 votes

---
Tags: 8, drush
---


# Question
Title: What is the latest drush version and how do I install it?
I have drush installed using what in principle is the latest stable build as per the instructions. When I run `drush version` then i get the reply `8.0.3`, however on my workstation with Dev Desktop installed it tells me it's `8.0.5`.

Running `drush dl drush` proposes a version `8.x-6.x-dev` dated 30 September 2013 which seems very old, and I can see no sign of a v8.1

Looking at the documentation I have not been able to see any other indications of how to go about this, and I am confused. Can anyone tell me whether the `drush dl drush` is still valid and what the current latest version actually is?

# Answer
`drush dl` was never supposed to be used to download Drush. It happens to work because Drush is hosted on drupal.org as module, but the latest development are done on github.com. On drupal.org, you find just old versions, dated 2013.

As per July 17, 2016, the latest version is 8.1.2. You can install it using Composer, if you are using any Linux OS, or OS X, and in this case it is easy as running the following command:

```
composer global require drush/drush:~8

```

Don't forget to add ~/.composer/vendor/bin to your shell PATH variable, or the shell will not find Drush's executable.
> 1 votes

# Answer
You can read on drupal.org/project/drush that:

> The Drush project has moved to Github.

so that explains why the latest git commits are from 2013.

Therefore you should follow the installation instruction available at docs.drush.org (Drush documentation) or installation via Composer. Here is installation of latest Drush via Phar on Linux:

```
sudo install <(curl http://files.drush.org/drush.phar) /usr/local/bin/drush

```

On OS X, you can install via brew (`brew install drush`), on Windows download release files manually.
> 1 votes

# Answer
First, you can find your exact location of drush you installed. If you are Mac/Linux user, you can use below command.

```
which drush

```

In my computer, it shows that is an alias which maps to another location.

```
lrwxrwxrwx  1 root root      28 Dec  8  2015 drush -> /usr/local/share/drush/drush

```

If you list the files in `/usr/local/share/drush`, you will find that there is .git folder.

```
-rw-r--r--  1 root root   617 Dec  8  2015 box.json.dist
drwxr-xr-x  8 root root  4096 Dec  8  2015 commands
-rw-r--r--  1 root root  1997 Jun  3 12:01 composer.json
-rw-r--r--  1 root root 53683 Jun  3 12:01 composer.lock
-rw-r--r--  1 root root  2469 Dec  8  2015 CONTRIBUTING.md
drwxr-xr-x  2 root root  4096 Jun  3 12:01 docs
-rwxr-xr-x  1 root root  4368 Jun  3 12:01 drush
-rw-r--r--  1 root root 14013 Jun  3 12:01 drush.api.php
-rwxr-xr-x  1 root root   743 Dec  8  2015 drush.bat
-rwxr-xr-x  1 root root  1937 Jun  3 12:01 drush.complete.sh
-rw-r--r--  1 root root    20 Jun  3 12:01 drush.info
-rwxr-xr-x  1 root root  4954 Dec  8  2015 drush.launcher
-rw-r--r--  1 root root 23280 Dec  8  2015 drush_logo-black.png
-rwxr-xr-x  1 root root   221 Dec  8  2015 drush.php
drwxr-xr-x  2 root root  4096 Jun  3 12:01 examples
drwxr-xr-x  8 root root  4096 Jun  3 12:01 .git
-rw-r--r--  1 root root   199 Jun  3 12:01 .gitignore
drwxr-xr-x  2 root root  4096 Jun  3 12:01 includes
drwxr-xr-x  3 root root  4096 Dec  8  2015 lib
drwxr-xr-x  3 root root  4096 Dec  8  2015 misc
-rw-r--r--  1 root root   644 Jun  3 12:01 mkdocs.yml
-rw-r--r--  1 root root  3152 Dec  8  2015 README.md
drwxr-xr-x  7 root root  4096 Jun  3 12:01 tests
-rw-r--r--  1 root root  6523 Jun  3 12:01 .travis.yml
-rwxr-xr-x  1 root root    83 Dec  8  2015 unish.sh
drwxr-xr-x 16 root root  4096 Dec  8  2015 vendor

```

You can list all drush version with `git tag`, then you pick one and checkout the version you like.

```
git checkout 8.0.5

```

If you don't have the version you want, just simply `git pull` the latest commits.
> 0 votes

---
Tags: drush
---


title: Entity reference field in REST

text:
# Question
Title: Entity reference field in REST
I'm trying to create content with REST, everything worked correctly until we need to an entity Reference field,I add it to my content type and in want to pass entity referenced nid to it with

Part of my code :

```
    formValues.gender = parseInt($('input[name=optradio]:checked').val());
    var postData = {};
    postData.title = [{'value': formValues.name }];
    postData.field_enroll_email = [{'value': formValues.email}];
    postData.field_gender = [{'value': formValues.gender }];
    postData.field_phone_number = [{'value': formValues.phone }];
    postData.field_course_ref = [{'value': formValues.nid }];
    if(formValues.ac != "") {
        postData.field_academic_certificate = [{'value': formValues.ac }];
    }
    if(formValues.ec != "") {
        postData.field_english_certificate = [{'value': formValues.ec }];
    }
    postData.type = 'enroll';
    jQuery.ajax({
        url: "/entity/node",
        method: "POST",

```

my entity referenced machine name field is `field_course_ref` and I tried following method (formValues.nid contain nid of Node that I want to referenced it )

```
    postData.field_course_ref = [{'value': formValues.nid }];

```

**How can I fill entity referece field with REST ?**

# Answer
After some research (How to POST an "entity reference" field to a node ? , REST views entity reference issue

I found the solution, we should pass nid as `target_id`, final asnwer is

```
postData.field_course_ref = [{'target_id': formValues.nid }];

```

it's work correctly, I answer my question maybe be helpful for another guy later.
> 2 votes

---
Tags: nodes, 8
---


# Question
Title: Auto-complete and form auto-populate from wikipedia
I have some taxonomy terms that would benefit from being (at least in part) being based on wikipedia articles.

It looks possible to make a request via the wikipedia api in PHP, and then link that to my Term via Computed fields, but to make the initial request I need to relate the restful query to the term. I found something similar, but I have no idea how to make this work in my example...

Is there a module out there that would let me run a `prefixsearch` query to show autocomplete options while typing in the term name on the 'add new term' page, and then autopopulate using a `parse` query?

Is no module how would I go about coding this up? I don't have any PHP knowledge but it looks like it wouldn't be too hard to do.

# Answer
> 2 votes
To create your own autocomplete callback, you can see Textfield that uses autocomplete which shows a custom autocomplete.

Since all the data is stored of site though, you can save some time and load by implementing it client, since the user must rely on javascript anyway.

Managing JavaScript in Drupal 7 shows how to add the javascript to your site.

I'm not aware of any module, or even php/js library, that does all the wikipedia integration. If you go with the PHP option, you'll probably be interested in Guzzle. When I tried last, it was complicated to integrate composer packages with Drupal 7 though, but it looks like the situation may have improved through Composer manager.

# Answer
> 2 votes
The Puzzler module integrates with Wikipedia API. You might be able to use its PHP function `puzzler_wikipedia()` to retrieve just the piece of content that you need.

---
Tags: taxonomy-terms, ajax, 8
---


# Question
Title: How to show a Drupal Commerce coupon system on the cart page?
I am new in Drupal and working over a shopping site using Drupal Commerce. My client's requirement is that to show a coupon field in the cart page through which user can add a coupon code. I have installed the Commerce Coupon module, but did not understand how to show the coupon form on the cart page.

# Answer
> 1 votes
https://www.drupal.org/project/commerce\_cp \- Commerce Cart Pane module allows to add Coupon form on cart page.

# Answer
> 0 votes
Basic rule of thumb using any module in Drupal is first read Documentation or Readme or Install files inside Drupal module.. That will tell you how the module works... Go through Project page for full details

For Example - Readme file explains how to create %off coupon

## Example - Create a '10% off' coupon

1) Install modules

Install: \- Commerce Coupon \- Commerce Coupon UI \- Commerce coupon percentage

2) Create a 'Percentage coupon' coupon

Go to: Home \> Administration \> Store \> Coupons

Click 'Create Coupon'

Choose 'Create Percentage coupon' (if you have no other coupon types clicking 'Create Coupon' will redirect to the 'Create Percentage coupon' form)

Create a percentage coupon with the following:

* Coupon Code: 10%OFF
* Number of Uses: 1 (change as necessary)
* Percentage Amount: 10
* Active: Yes

Save

3) Enable the 'Coupons' area on one of your Commerce checkout panes

Go to: Home \> Administration \> Store \> Configuration \> Checkout settings

Move the 'Coupons' item into one of the checkout panes

Save

4) Test it!

Please do some basic research before posting questions like above .. Otherwise they will be put onhold :-)

---
Tags: commerce
---


# Question
Title: Dashboard doesn't contain the "Customize dashboard" link
The dashboard page doesn't contain the *Customize dashboard* link.

A normal dashboard would appear as in the following screenshot.

How do I make the link appear is it should?

# Answer
> 1 votes
To see the *Customize dashboard* link, the logged in user needs the *Admin blocks* permission, as said in admin/people/permissions.

> Customizing the dashboard requires the *Administer blocks* permission.

This is how I see it when logged in as user #1, who has all the permissions.

>

This is how I see it with an account without that permission.

>

If then I give the *Administer blocks* permission to that account, this is how the dashboard appears.

>

---
Tags: 7
---