title: Passing parameters to route

text:
# Question
Title: Passing parameters to route
So currently i am passing some params to a form via the route path as so:

```
my_module.action:
  path: '/status/{action}/{id}'
  defaults:
    _form: '\Drupal\my_module\Form\MyForm'
  requirements:
    _permission: 'access content'

```

And in my form:

```
public function buildForm(array $form, FormStateInterface $form_state, $action = null, $id = null) {}

```

And it works as intended, the form receives the two params. But because this way the params are exposed in the url and every user can see them. Is there a way to pass params to the router but not expose them in the url? \[passing them in Session is not really best practice, so i'd like to avid it.\]

# Answer
I do not know why you can not use the parameters of the url.

One way to do what you want is:

1) Create a new content type called, for example: "routing settings".

2) create two fields:

* field\_id of numerical type.
* field\_action of type text.

3) create several nodes with the corresponding actions and id.

4) use the nid of your node as a parameter

file: .routing.yml

```
my_module.action:
  path: '/status/{node}'
  defaults:
    _form: '\Drupal\my_module\Form\MyForm'
  requirements:
    _permission: 'access content'

```

your file form:

```
use Drupal\node\NodeInterface;
...

public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node) {

$id= $node->get("field_id")->value;
$action= $node->get("field_action")->value;

//here you put your code

}

```

....
> 0 votes

---
Tags: routes
---


# Question
Title: How to convert an order price to a different currency in Commerce 2?
The Stripe payment gateway only accepts JCB and Diners Club transactions in US dollars (no international currencies).

Most of the transactions on my site are in Japanese yen.

In fact, I would prefer to have everything in yen, but I want to try to handle JCB (major credit card in Japan) by somehow converting the JPY prices to USD and then billing in USD (of course, I will notify the user I am doing this).

Ideally, the flow looks like this:

* User browses my store where prices are shown in JPY.
* User adds a product to the cart.
* User goes to checkout and chooses a payment method (if user chooses "Pay with Mastercard/Visa" (standard Stripe payment gateway), transaction proceeds as normal.
* If the user chooses "JCB", price is converted to USD and then billed in USD.

How might I begin to implement this kind of conversion? Or, is there a better approach/flow for converting the order price from one currency to another?

# Answer
> 0 votes
This is what I've done for now.

1. Add the currencies you will use in the UI. `/admin/commerce/config/currencies`
2. Add a "currency" product attribute in the UI. `/admin/commerce/product-attributes`
3. On the product edit page for the product you want, add variations with the currencies and set the prices.

This lets the user choose the currency he/she likes. So you can just put a message "If you're using JCB, you must pay with JCB." It's not perfect but it's a decent solution.

---
Tags: 8, commerce
---


# Question
Title: How to replace authentication links with custom routes?
I am working on a custom Drupal 8 module that has its own authentication form.

For this, I created a Drupal page with the custom authentication form, i.e. I have a route at `drupalsite.com/custom-signup`

What I am not able to figure out is how can I replace Drupal's default Register and Login links which are scattered everywhere on the website to point to above route. I don't want to redirect from `/user/login` page to `/custom-signup` as I still want to allow admin to login. For all other users except admins should be redirected to `\custom-signup`.

I could use jquery to brute-force my way to replace the links, but is there an efficient way to achieve this?

TL;DR: I need to replace following default Drupal links using my module.

**Update:**

Following the first solution, I added the routing files as follows, the links are redirecting me to my custom form.

However, when I try to enter `user/login` manually in the URL, I get `page not found` message on the website.

# Answer
> 4 votes
You need to alter the route, in your custom module add:

**mymodule/src/Routing/RouteSubscriber.php**

```
namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change path '/user/login' to '/customn-login'.
    if ($route = $collection->get('user.login')) {
      $route->setPath('/custom-login');
    }
    // Change path '/user/register' to '/custom-signup'.
    if ($route = $collection->get('user.register')) {
      $route->setPath('/custom-signup');
    }
  }

}

```

**mymodule/mymodule.services.yml**

```
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

For more in depth information, see Altering existing routes and adding new routes based on dynamic ones.

---

If you still want `/user/login` to work, then you can create a new route for it.

**mymodule/mymodule.routing.yml**

```
mymodule.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

```

Remember to clear all caches to see changes.

---
Tags: 8, navigation
---


title: Ovh and composer

text:
# Question
Title: Ovh and composer
I have a site that I just put on OVH hosting shared pro and I try to update Drupal 8 but I encounter several problems:

-If I try to update through the interface I can not update because I have a message related to the PHP bug 2038

I'm trying to use composer.

I have some questions :

* Should I install directly composer on my FTP host or on the www folder?
* When I try the command php composer.phar update drupal / core I get the message "*Composer could not find a composer.json file in home / my\_id*"
* When I try in the www directory, I have the message *"Drupal / core package for update is not installed. Loading dials repositories with package information Updating dependencies (including require-dev) Nothing to install or update Generating autoload files Drupal \ Core \ Composer \ :: Composer preAutoloadDump Drupal \ Core \ Composer \ :: Composer ensureHtaccess "*

For information I have well the composer.json file in my www directory.

Could you help me to start please. Thank you

# Answer
> 0 votes
You shouldn't run Composer on your production environment. Definitely use it to build your site but push a complete build artefact to production (including all the vendor folders and such).

Also the command is `composer update drupal/core` (no spaces).

---
Tags: composer
---


# Question
Title: I want to uninstall l10n_client which may be duplicated
I use composer. The L10n\_client module could not be updated or occasionally not found. I feel that the names of L10n\_client or l10n\_client\_ui are different. It is a similar atmosphere as below. https://www.drupal.org/node/2658756 I do not know if it is the same cause. Since Composer update can not be done, I have memories that I executed composer require as override.

I got a message to install the l10n\_client module under some circumstances, so I ran the installation on admin/modules, but an error was returned. Localization Client Interface The module is unchecked. Localization Client Contributor module is not installed. Error message is ‘Unable to install Localization Client Interface, l10n\_client\_ui.settings already exists in active configuration.’

How can I solve it?

Environment:Drupal 8.4.2

# Answer
I ran "drush config-delete l10n\_client\_ui.settings". I was able to install the module.
> 2 votes

---
Tags: i18n-l10n, installation
---


# Question
Title: How to know the format when programmatically setting a field value
I am trying to create a set of entities based on a CSV file on install of a custom module. The entity has a price field and I don't know how to find out what I should be passing in as a value, the following does not work:

```
$entity = entity_create('item_price', ['type' => 'wand']);
$entity->setName('Harry Potter');
$entity->set('price', 2000);
$entity->save();

```

Although this problem is specific to the price field I would like to know as a general rule **how does one "discover" what format the value should be in for any field type**.

# Answer
> 2 votes
You will need to pass price object to it and not just a number. Do like this -

```
$price = new Price('2000', 'USD');
$entity->set('price', $price);
$entity->save();

```

You can always look at tests to know how things are working for the module. :)

---
Tags: 8, entities
---


# Question
Title: How to add a custom field image in a block, for a style background-image: url()
I'm trying to add a background image field to a block, when template-c is selected using the style property:

```
<?php
//here I can set if template AB or C 1,2,3
if ($rows[0]['field_template'] == 'Template A') {
    //template A is text left and logo right
    $show = "template-a";
}
if ($rows[0]['field_template'] == 'Template B') {
    //template B is text 2 images one right one bottom
    $show = "template-b";
}
if ($rows[0]['field_template'] == 'Template C') {
    //photo background and click video
    $show = "template-c";
    $background_image=print $rows[0]['field_slider_back_template_c'];
}
?>

<div class="work-block <?php echo $show; ?>" style="background-image: url($background_image);
<?php
    if(strpos($rows[0]['title'],'Verizon') === false) print 'color: black;';
    else 'color: white;';
?>
">

```

Is there a better way to do this?. I tried to add `print $rows[0]['field_slider_back_template_c'];` directly on the `style="background-image: url()` without success.

# Answer
> 0 votes
I think you made a mistake here -

```
  $background_image=print $rows[0]['field_slider_back_template_c'];
}
?>

<div class="work-block <?php echo $show; ?>" style="background-image: url($background_image);

```

Instead you should try -

```
  $background_image = $rows[0]['field_slider_back_template_c'];
}
?>

<div class="work-block <?php echo $show; ?>" style="background-image: url(<?php print $background_image; ?>);

```

---
Tags: views, theming, blocks, media
---


# Question
Title: Locking nodes or entities to prevent concurrent editing
I have not had a need for this, but another (home built PEAR) CMS I support for a client uses locking to prevent two users from being able to edit a piece of content at the same time. It can be irritating but could prevent loss of work.

I suppose if you have multiple site editors it could be invaluable.

Is it necessary? Is the module content lock a viable option?

# Answer
> 5 votes
I believe this is already implemented to some degree. If two users are editing the same piece of content, and one submits changes, the other user will receive this message when trying to do the same:

> The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.

It happens in the `node_validate()` function in case you're interested in checking out the code.

# Answer
> 1 votes
Below is a possible solution to address this question, which implements an edit-in-progress (EIP) feature using the Flag module, combined with the Rules module to get it to work. Read on for more details ...

# Step 1: Create an edit-in-progress flag

Create a global (not user specific) flag, and say you name (label) it **edit-in-progress** flag (='EIP' for short). The purpose of this flag is like so:

* If this flag is turned on for a node, it means "somebody is editing this node, so do not allow any additional edit sessions for this node to be started".
* If this flag is not turned on for a node, it means "the node is available for authorized users to start editing it".

# Step 2: Create a rule to disallow edit if the EIP flag is set

Create a rule to disallow edit of a node if the EIP flag for a node is already set. To recognize a request to start an edit session for a node, use an URL like `node/xyz/edit` (with `xyz` = `nid` of the node).

Refer to my answer to the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", which contains a rule that is pretty close to what's needed for this rule here:

* Use the same Rules Event, i.e. "Drupal is initializing" (you want to catch this edit event via Rules BEFORE the edit session actually allowed to be started!).
* Slightly adapt the regular expression, by adding `/edit` to it.
* Add an extra condition to verify if the EIP-flag for this node is ALREADY turned on (which indicates some other edit session for this node was started already).
* Adapt the Rules Action to (a) issue an appropriate message (that some other edit session is already started) and (b) redirect the user to whatever other path that fits your needs (e.g: just `node/xzy`).

# Step 3: Create a rule to SET the EIP flag when an edit starts

Create a rule to SET the EIP flag for a node whenever an authorized user requests to start an edit session for a node. To recognize such request, use an URL like `node/xyz/edit` (with `xyz` = `nid` of the node).

Refer to my answer mentioned in Step 2, which contains a rule that is pretty close to what's needed for this rule here:

* Use the same Rules Event, i.e. "Drupal is initializing" (you want to catch this edit event via Rules BEFORE the edit session actually allowed to be started!).
* Slightly adapt the regular expression, by adding `/edit` to it.
* Add an extra condition to verify if the EIP-flag for this node is NOT turned on (which indicates no other edit session for this node exists).
* Adapt the Rules Action to SET the EIP flag.

# Step 4: Create a rule to UNSET the EIP flag when an edit ends

Create a rule to UNSET the EIP flag for a node whenever an authorized user requests to end an edit session for a node.

Here is a summary of this rule:

* Use Rules Event "after saving content".
* Use Rules Action to UNSET the EIP flag.

# Step 5: Merge Step 2 and Step 3 (optional)

Should you want to do/consider so, you should be able to merge the 2 Rules from **Step 2** and **Step 3** in a single Rule, using the Conditional Rules module. Refer to my answer to the question How to prevent a node being saved when using the Rules module? for a sample of how to use this module (for which not a lot of documentation seems to exist).

# Answer
> 0 votes
When two people edit the same page and one submits changes there is a hight risk that at the same time the second person has made some changes to the same page that will be lost. There, I find, exists the great use of this module.

# Answer
> 0 votes
To "unblock" the node for editing it you can clear cache from within the admin page UI. In Drupal 7 it is in main menu, first icon (Home) -\> Flush all caches.

---
Tags: 7, nodes
---


# Question
Title: Get selected item in hook_form_alter in D8
I have a select box named **`field_p_destination`**, and i need to get the selected value on hook\_form\_alter .

I tried \`

```
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id){
  echo $form['field_p_destination']['widget'][0]['value']['#default_value'];`
}

```

Its not working . But in case of text fields its working fine . Any idea to get the **`select field`** ?

# Answer
> 2 votes
I am just giving you the example because your scope is not clear to me,in my case i am taking node edit form where i am having a field which is select box.

```
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == "node_page_edit_form"){

    $v=$form[field_select_field][widget]['#default_value'][0];

    //dpm($form[field_select_field]);

    dpm($form[field_select_field][widget]['#options'][$v]);
  }
}

```

---
Tags: 8, forms, hooks
---


title: Can not display user information?

text:
# Question
Title: Can not display user information?
I want to display on the user account page the following information :

* the status of the account.
* the roles attached to the accounts.
* registered since the ...
* last connection on ...

The view displays all the information for the administrator account, but with an authenticated user I only have the following information :

* the roles attached to the accounts.
* registered since the ...

How to display all the information for the authenticated user ?

```
uuid: 88c79c78-6091-4edc-bcd7-464f3a5a3baf
langcode: fr
status: true
dependencies:
  module:
    - user
id: utilisateur_informations
label: 'Utilisateur informations'
module: views
description: ''
tag: ''
base_table: users_field_data
base_field: uid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: none
        options: {  }
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Trier par'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: none
        options:
          items_per_page: null
          offset: 0
      style:
        type: default
        options:
          grouping: {  }
          row_class: views-teaser
          default_row_class: true
      row:
        type: fields
      fields:
        status:
          id: status
          table: users_field_data
          field: status
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Compte '
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: boolean
          settings:
            format: enabled-disabled
            format_custom_true: ''
            format_custom_false: ''
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: user
          entity_field: status
          plugin_id: field
        roles_target_id:
          id: roles_target_id
          table: user__roles
          field: roles_target_id
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Rôles '
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          type: separator
          separator: ', '
          entity_type: user
          plugin_id: user_roles
        created:
          id: created
          table: users_field_data
          field: created
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Membre depuis '
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: timestamp_ago
          settings:
            granularity: 2
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: user
          entity_field: created
          plugin_id: field
        login:
          id: login
          table: users_field_data
          field: login
          relationship: none
          group_type: group
          admin_label: ''
          label: 'Dernière connexion le '
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: timestamp
          settings:
            date_format: short
            custom_date_format: ''
            timezone: ''
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: user
          entity_field: login
          plugin_id: field
      filters: {  }
      sorts: {  }
      title: 'Utilisateur informations'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments:
        uid:
          id: uid
          table: users_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: ''
          default_action: default
          exception:
            value: all
            title_enable: false
            title: All
          title_enable: false
          title: ''
          default_argument_type: raw
          default_argument_options:
            index: 1
            use_alias: false
          default_argument_skip_url: false
          summary_options:
            base_path: ''
            count: true
            items_per_page: 25
            override: false
          summary:
            sort_order: asc
            number_of_records: 0
            format: default_summary
          specify_validation: false
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          not: false
          entity_type: user
          entity_field: uid
          plugin_id: user_uid
        uid_1:
          id: uid_1
          table: users_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: ''
          default_action: default
          exception:
            value: all
            title_enable: false
            title: All
          title_enable: false
          title: ''
          default_argument_type: current_user
          default_argument_options: {  }
          default_argument_skip_url: false
          summary_options:
            base_path: ''
            count: true
            items_per_page: 25
            override: false
          summary:
            sort_order: asc
            number_of_records: 0
            format: default_summary
          specify_validation: false
          validate:
            type: none
            fail: 'not found'
          validate_options: {  }
          break_phrase: false
          not: false
          entity_type: user
          entity_field: uid
          plugin_id: user_uid
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - user
      tags: {  }
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders:
        metatag_display_extender: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url
        - user
      tags: {  }

```

# Answer
Remove your first contextual argument. You only need this one:
> 0 votes

# Answer
I imported your view and tried to do it via views module. But I believe you will need to do some custom coding for this. You need to set access permissions per field in Drupal 8.

To learn more about field permissions refer `field_permissions` example module in Examples module.
> 0 votes

---
Tags: views, 8, users
---


# Question
Title: Is it possible to get node template suggestion per views row on Drupal 8
I need to theme the first row of a view page with a different image size and the theme debug suggested me:

node--view--article--page-1.html.twig

This is new on drupal 8.

I was wondering if is possible to get template suggestions per row number.

# Answer
This is probably not a simple task for a template name suggestion, because at the time of rendering the node is unaware of where it is placed in the view.

So a better approach might be to use two different view modes, one for the first and one for the rest of the nodes. Then use a row style plugin to switch the view modes, for example the module Views Parity Row.

If this is only to apply CSS, then don't try to add row classes to the node. Add them to the views row container and target elements inside of the node with multiple CSS selectors.
> 1 votes

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


# Question
Title: Cannot create release for my contributed module
I am trying to create a release for my contributed module

https://www.drupal.org/project/taxonomy\_facets

I created a tag an that seemed to get trough OK:

git push origin tag 8.x-1.0-RC1

Total 0 (delta 0), reused 0 (delta 0)

To git.drupal.org:project/taxonomy\_facets.git

* \[new tag\] 8.x-1.0-RC1 -\> 8.x-1.0-RC1

I am on the right branch:

git branch

7.x-3.x

* 8.x-1.x

But when I go to "Add new release" page:

https://www.drupal.org/node/add/project-release/1334080

In the select "Git release tag or branch" I do not see my release, I only see 7.x branch?

Is there a Drupal git suport email, I tried IRC but no luck, I also tried Drupa forums https://www.drupal.org/forum/support/module-development-and-code-questions/2017-12-08/cannot-create-release-for-my

# Answer
> 2 votes
There is just a small change that you need to make. The projects on drupal.org are expected to have the releases in lowercase. This is done to support the project infrastructure which is in place like update status and the testing bot.

You should be able to create a new release with a tag like `8.x-1.0-rc1`

More info here : https://www.drupal.org/node/1015226

---
Tags: 8, community-official-site
---


title: drush for several drupal

text:
# Question
Title: drush for several drupal
I have drupal 7.54 that are placed in /var/www/html which I use as main site. Also I have drupal 8 (for testing) that are placed in /var/www/html/drupal8 where I have drush.

And there is some problem. When I tried to launch command "drush status" it gives me information about drupal 7. And it happens regardless directory of drush.

How to specify version of drupal on which drush must operate?

And I want to notice that I installed drush not via composer but just downloaded and unzipped it.

# Answer
> 0 votes
First I assume you have drush 8 since that is required for both D7 and D8. It's also the default on drush.org.

The best way to deal with multiple Drupal sites is via Drush Aliases.

Basically you create a .drush directory in your home directory and create a aliases.drushrc.php file in it. For each site, have an entry with the minimum information of:

```
$aliases['d7'] = array (
  'uri' => 'yoursite.dev',
  'root' => '/path/to/drupal/root',
):

```

There are a lot more options but those are the required ones for local sites.

To use them, run drush commands using the @alias option. E.g.:

```
drush @d7 status

```

This will let you switch between multiple local sites.

---
Tags: drush
---


# Question
Title: Drush 8x working from directories above web root, but not in web root
I need some help trouble shooting Drush. I'm on a shared server, Hostgator, running Linux and PHP 5.6.3.

My install looks something like home/public\_html/websites/MyDrupal

I have installed Composer globally as well as Drush .bashrc includes:

```
# .bashrc
export PATH=$PATH:~/.composer/vendor/drush/drush
[ -z "$PS1" ] && return

# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi

# User specific aliases and functions
alias composer="/usr/bin/php-cli ~/bin/composer.phar"
alias drush="~/.composer/vendor/drush/drush/drush"

```

Composer runs from any directory within my host space.

Drush will run, using the directory hierarchy example above, from 'home', 'public\_html' and 'websites' but if I run drush status within 'MyDrupal' I get an error:

```
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: syntax error, unexpected 'finally' (T_STRING), expecting catch
(T_CATCH) in
/.../public_html/bhsu/vendor/symfony/dependency-injection/ContainerBuilder.php,
line 452

Parse error: syntax error, unexpected 'finally' (T_STRING), expecting catch (T_CATCH) in /.../public_html/bhsu/vendor/symfony/dependency-injection/ContainerBuilder.php on line 452

```

Would appreciate pointers... thanks

# Answer
> 0 votes
Fixed: we figured out that composer and drush were using an older version of PHP which wouldn't work w/ Drupal 8. I still don't understand how the webserver can run one version (phpinfo.php showed the site running the expected 5.6 version) while Drush is set to another. Anyway, finding and aliasing to the proper version fixed the issue. The fix was adding this to .bashrc: (your path might be different). alias php='/opt/php56/bin/php' alias composer='/opt/php56/bin/php ~/bin/composer' export DRUSH\_PHP='/opt/php56/bin/php'

---
Tags: drush
---


# Question
Title: Need to override single Drupal 8 plugin function
What I want to do is edit what is displayed in the autocomplete/drop selects for an entity reference. Basically instead of just \[title\] I want to show \[title\] - \[other\_distinguishing\_field\]. I know that I can do this by editing getReferenceableEntities in Drupal\Core\Entity\Plugin\EntityReferenceSelection. All I want to do is override that function. I read that I need to make a plugin for this, but I find all of the tutorials a bit confusing and I don't understand how to implement what I want using a plugin. Do I need a plugin manager? Do I need to use annotations? Where do I reference Drupal\Core\Entity\Plugin\EntityReferenceSelection? Where do I override the function? Do I need to configure anything on the UI the use my plugin or will it automatically work?

\**EDIT Here is what my Plugin manager looks like using the solution provided by @ya.teck

```
    <?php
/**
 * @file
 * Contains ExampleEntityReferenceManager
 */

namespace Drupal\example;

use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;

/**
 * ExampleEntityReference plugin manager.
 */
class ExampleEntityReferenceManager extends DefaultPluginManager {

  /**
   * Constructs an ExampleEntityReferenceManager object.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations,
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to invoke the alter hook with.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
    parent::__construct('Plugin/EntityReferenceSelection', $namespaces, $module_handler, 'Drupal\Core\Entity\EntityManagerInterface', 'Drupal\Core\Entity\Annotation\EntityReferenceSelection');

    $this->alterInfo('example_entity_reference_manager_info');
    $this->setCacheBackend($cache_backend, 'example_entity_reference');
  }
}

```

# Answer
> 8 votes
**Method #1** You can simply create new plugin which extends class of target Core plugin.

File: *modules/example/src/Plugin/EntityReferenceSelection/ExampleSelection.php*

```
namespace Drupal\example\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;

/**
 * Entity Reference Selection with distinguishing field.
 *
 * @EntityReferenceSelection(
 *   id = "example",
 *   label = @Translation("Example"),
 *   group = "example",
 * )
 */
class ExampleSelection extends DefaultSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $target_type = $this->configuration['target_type'];

    $query = $this->buildEntityQuery($match, $match_operator);
    if ($limit > 0) {
      $query->range(0, $limit);
    }

    $result = $query->execute();

    if (empty($result)) {
      return [];
    }

    $options = array();
    $entities = $this->entityManager->getStorage($target_type)->loadMultiple($result);
    foreach ($entities as $entity_id => $entity) {
      $bundle = $entity->bundle();

      $translated_entity = $this->entityManager->getTranslationFromContext($entity);
      $label = $translated_entity->label();
      $distinguishing_field = $translated_entity->get('field_example')->get(0);
      if ($distinguishing_field) {
        $label .= ' [' . $distinguishing_field->getValue()['value'] . ']';
      }
      $options[$bundle][$entity_id] = Html::escape($label);
    }

    return $options;
  }

}

```

Having this done navigate to field settings page and enable your reference method.

**Method #2** For select list widget you can install Entity Reference Views Select which allows to build selection options using Views fields.

**Method #3** Content Browser module (not stable yet) offers more advanced way to select entities.

**Method #4** You may globally override Entity::label() method for required entity type. So that the `[title] - [other_distinguishing_field]` pattern will be used everywhere including default entity reference selection plugin.

# Answer
> 0 votes
You should implement `hook_entity_reference_selection_alter()`.

```
function mymodule_entity_reference_selection_alter(&$definitions) {
  // Change your class here.
}

```

---
Tags: plugins
---


# Question
Title: Link to create a node, save it, and then go to the edit page
I want to enable users to click a link to create a node of a specific content type. However, instead of going to `/node/add/contenttype`, which is the standard Drupal flow, I want the node of the relevant content type to automatically be created and saved, and then redirect the user to the newly created node's edit page.

In other words, when a user clicks "add a node," I want to create the node for the user and send the user to the edit page.

I want to do this because I have a very long, complicated form and I want to use the Autosave Form module to automatically save the form; however, this module can only save a node/entity that has already been saved once (entities with an entity ID).

What's the simplest way to implement this?

I'm thinking that I will need to define a custom route that checks permission, runs code to create the node, and then redirects to the node.

**EDIT: Overriding the NodeController**

As suggested by 4k4, I overrode the NodeController as follows. However, the problem is that when I go to `/node/add/contenttype`, the node is created and the form is shown, but it's an old form; when I try to save it, I get this error: "The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved."

```
class MymoduleNodeController extends NodeController {
  public function add(NodeTypeInterface $node_type) {
    $content_type = $node_type->id();
    if ($content_type == 'MYTYPE') {
      $node = $this->entityManager()->getStorage('node')->create([
        'type' => $node_type->id(),
      ]);
      $node->save();
      $form = $this->entityFormBuilder()->getForm($node);

      return $form;
    }
    else { // Default node creation behavior

```

# Answer
> 1 votes
I think the simplest way is to save the node right after you've created it in a custom version of `NodeController::add()`:

```
  public function add(NodeTypeInterface $node_type) {
    $node = $this->entityManager()->getStorage('node')->create([
      'type' => $node_type->id(),
    ]);

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;
  }

```

**Edit:**

Because building the form directly with the saved node doesn't work, return a redirect response for the node edit form:

```
    $node->save();
    return $this->redirect('entity.node.edit_form', ['node' => $node->id()]);

```

---
Tags: 8, nodes, entities, workflows
---


# Question
Title: Drupal 8 problem to list taxonomy word of unpublished content in a view
I made a view for the backend. Something like we know from backend for listing content. I want to list the taxonomy term for all content. No matter whether content is published or not. But the view only shows content, if content is published. What do I have do to show taxonomy terms for unpublished content?

# Answer
An old question, but it's an issue I've been struggling with, too, so I thought I'd post an answer. Turns out there's a known issue (feature request, actually) with the taxonomy module going back to D7. You can get all the details at https://www.drupal.org/project/drupal/issues/962664.

There are patches there for 8.2, 8.3 and 8.4 that might solve your problem until the fix/feature makes into a stable release.
> 0 votes

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


title: Auto increment SKU

text:
# Question
Title: Auto increment SKU
It seems a simple feature to me, but I can't find a way to do the trick.

I've uploaded the products of my Drupal Commerce store with a CSV table that contains in SKU column a sequential set of integers starting on 1 until, say, 8000. I would like to register a new product that automatically generates the SKU field with 8001, the next product with 8002, and so on. I already have the AutoSKU module installed with a Commerce Kickstart 2 profile installed. But I can't see a way to generates the SKU value like I said.

Is there a simple way/module that facilitates this?

Edit:

I tried with Serial Field module. I created a field of type "serial". It's hidden.

Then I put in AutoSKU Parameters, SKU Pattern the token \[commerce-product:field\_book\_code\]. Now the SKU is automatically generated, but it starts with a number greater than the total of products that store has, and when I add a product, the SKU is incremented by 10.

Anyone could help me?

# Answer
> 2 votes
I had this issue and certain modules wouldn't work for me really bc the client wanted to start at a certain number, rather than at 0.

I ended up pre-filling the SKU field (because it's required and has to be filled out to save) and on entity\_create per variation, I would do an entity query, find the product with the highest SKU, add one and set the SKU to be that number.

This works with variations because each one is its' own entity and runs the code to search for highest the SKU each time.

# Answer
> 1 votes
I'm not sure if it works but using AutoSKU and Serial Field Module you probably can make it.

---
Tags: commerce
---


# Question
Title: How to access table tokens in views through handler
I've added a custom field of type global using views\_handler\_field. This custom field type is basically a button that needs to call a javascript function. This javascript function takes an adjacent field's value as a parameter. When I edit the view on my webpage, under rewrite rules-\>replacement values, I can see the token for the value I need in my handler's functionality. In the code example, it's \[fieldID\]

However, I don't see any way to access this value in my views\_handler\_field include file.

```
function render($values) {

    $actions = array();
    $variable = variable_get('fieldID'); // HERE is what I'd like to do to get the adjacent [fieldID] icon

    $alt = t('Download File');
    $actions[] = array(
      'name' => t('Download'),
      'html' => 'javascript:initiateDownload('.$variable.')',
      'id' => t('download-button-' . $variable),
      'icon' => theme('image', array('path' => drupal_get_path('module', 'download_process') . '/images/edit.png', 'alt' => $alt))
    );

    $output = '';

    $counter = 0;
    foreach ($actions as $action) {
      $output .= l($action['icon'], $action['html'], array('attributes' => array('id' => $action['id'] . $counter), 'html' => TRUE, 'external' => TRUE));
      $counter++;
    }
    return $output;
  }
  function query() {

  }

```

I've tried working with get\_render\_tokens, but I don't think that that's what I'm looking for. Any help here would be appreciated! For reference, I'm using Drupal 7.

# Answer
> 0 votes
The answer ended up being very simple. All I needed to do was cast $values to an array, then access the id. Like this:

```
$array = json_decode(json_encode($values), true);
$value = $array['fieldid'];

```

---
Tags: tokens, views
---


# Question
Title: How do I properly transfer content from an external source?
So I have been tasked with migrating content into Drupal 8. I wrote python to create SQL statements to insert nodes into the the Drupal database. I had to figure out how Drupal stores content for each content type and then write out the SQL.

Here's what I've done for a News Item content type. What would you do differently to insert content? What tools would you use to avoid having to manually extract how Content Types are stored in the database and then write lengthy SQL manually like I did?

```
import mysql.connector
import csv

class News_Item:
    # node and node_rev use nid vid. Other tables use entity_id and revision_id
    def node(self, type):
        file.write("INSERT INTO csr.node \n")
        file.write("SELECT `nid` + 5000, `vid` + 5000 , `type`, `uuid`, `langcode`  \n")
        file.write("FROM 8csr.node WHERE 8csr.node.type LIKE '" + type +"'")
        file.write("AND 8csr.node.nid < 5000;\n\n")

    def node_rev(self, type):
        file.write("INSERT INTO csr.node_revision \n")
        file.write("SELECT `8csr`.`node`.`nid` + 5000, `8csr`.`node`.`vid` + 5000 , `8csr`.`node`.`langcode`, `revision_uid`, `revision_timestamp`, `revision_log`  \n")
        file.write("FROM 8csr.node_revision \n")
        file.write("INNER JOIN `8csr`.node ")
        file.write("ON `8csr`.node_revision.vid = `8csr`.node.vid AND `8csr`.node.type LIKE '" + type + "'\n")
        file.write("AND 8csr.node.nid < 5000;\n\n")

    # Field data and field revision differ only in that one of them has a type field
    def field_data(self, type):
        file.write("INSERT INTO csr.")
        file.write("`node_field_data`")
        file.write("\n SELECT `node_field_data`.`nid` + 5000, `node_field_data`.`vid` + 5000 , `node_field_data`.`type`, `node_field_data`.`langcode`, `status`, `title`, `node_field_data`.`uid`, `created`, `changed`, `promote`, `sticky`, `revision_translation_affected`, `default_langcode` \n")
        file.write("FROM `8csr`.`"+ "node_field_data" +"` \n")
        file.write("INNER JOIN `8csr`.node \n")
        file.write("ON `8csr`.`"+ "node_field_data" +"`.vid = `8csr`.node.vid\n")
        file.write("AND `8csr`.node.type LIKE '" + type +"' \n")
        file.write("AND 8csr.node.nid < 5000;\n\n")

        file.write("UPDATE csr.node_field_data SET uid = 1; \n")

        file.write("INSERT INTO csr.")
        file.write("`node_field_revision`")
        file.write("\n SELECT `node_field_revision`.`nid` + 5000, `node_field_revision`.`vid` + 5000 , `node_field_revision`.`langcode`, `status`, `title`, `node_field_revision`.`uid`, `created`, `changed`, `promote`, `sticky`, `revision_translation_affected`, `default_langcode` \n")
        file.write("FROM `8csr`.`node_field_revision` \n")
        file.write("INNER JOIN `8csr`.node \n")
        file.write("ON `8csr`.`node_field_revision`.vid = `8csr`.node.vid\n")
        file.write("AND `8csr`.node.type LIKE '" + type +"' \n")
        file.write("AND 8csr.node.nid < 5000;\n\n")

        file.write("UPDATE csr.node_field_revision SET uid = 1; \n")

    def all_fields(self, type, fields, custom_data):
        for x in range(0, len(fields)):
            table = "node__" + fields[x]
            file.write("INSERT INTO csr.node__" + fields[x] +"\n")
            file.write(" (`bundle`, `deleted`, `entity_id`, `revision_id`, `langcode`, `delta`, " + custom_data[x] +")\n")
            file.write("SELECT `bundle`, `deleted`, `entity_id` + 5000, `revision_id` + 5000, `node`.`langcode`, `delta`, " + custom_data[x] +"\n")
            file.write("FROM `8csr`.`"+ table +"` \n")
            file.write("INNER JOIN `8csr`.node \n")
            file.write("ON `8csr`.`"+ table +"`.revision_id = `8csr`.node.vid\n")
            file.write("AND `8csr`.node.type LIKE '" + type +"' \n")
            file.write("AND 8csr.node.nid < 5000;\n\n")

    def all_fields_rev(self, type, fields, custom_data):
        for x in range(0, len(fields)):
            table = "node_revision__" + fields[x]
            file.write("INSERT INTO csr." + table +"\n")
            file.write(" (`bundle`, `deleted`, `entity_id`, `revision_id`, `langcode`, `delta`, " + custom_data[x] +")\n")
            file.write("SELECT `bundle`, `deleted`, `entity_id` + 5000, `revision_id` + 5000, `node`.`langcode`, `delta`, " + custom_data[x] +"\n")
            file.write("FROM `8csr`.`"+ table +"` \n")
            file.write("INNER JOIN `8csr`.node \n")
            file.write("ON `8csr`.`"+ table +"`.revision_id = `8csr`.node.vid\n")
            file.write("AND `8csr`.node.type LIKE '" + type +"' \n")
            file.write("AND 8csr.node.nid < 5000;\n\n")

    def files_added(self, type):
        file.write("INSERT INTO `csr`.`file_usage` \n")
        file.write("SELECT `fid` + 5000, `module`, `8csr`.`file_usage`.`type`, `id` + 5000, `count` \n")
        file.write("FROM `8csr`.`file_usage` \n")
        file.write("INNER JOIN `8csr`.node \n")
        file.write("ON `8csr`.`file_usage`.id = `8csr`.node.nid\n")
        file.write("AND `8csr`.node.type LIKE '" + type +"' \n")
        file.write("AND 8csr.node.nid < 5000;\n\n")

        file.write("INSERT INTO `csr`.`file_managed` \n")
        file.write("SELECT `fid` + 5000, `8csr`.`file_managed`.`uuid`, `8csr`.`file_managed`.`langcode`, `uid`, `filename`, `uri`, `filemime`, `filesize`, `status`, `created`, `changed`")
        file.write("FROM `8csr`.`file_managed` ;\n\n")
        file.write("UPDATE csr.file_managed SET uid = 1 ; \n ")
        file.write("UPDATE csr.node__field_publication SET field_publication_target_id = field_publication_target_id + 5000 WHERE `bundle` LIKE 'news_item'; \n")
        file.write("UPDATE csr.node__field_photo SET field_photo_target_id = field_photo_target_id + 5000 WHERE `bundle` LIKE 'news_item'; \n")

fields = ["body", "field_publication", "field_photo"]
custom_data = [
"`body_value`, `body_summary`, `body_format` ",
"`field_publication_target_id`,  `field_publication_display`, `field_publication_description` ",
"`field_photo_target_id`, `field_photo_alt`, `field_photo_title`, `field_photo_width`, `field_photo_height` "]

type = "news_item"

file = open('news_items.sql', 'w+')
file.write("begin;\n")

e = News_Item()
e.node(type)
e.node_rev(type)
e.field_data(type)
e.all_fields(type, fields, custom_data)
e.all_fields_rev(type, fields, custom_data)
e.files_added(type)
file.write("commit;\n")

```

What is the drupal way to import content from another source of raw data like an external database or CSV file? Is there a ORM tool like Hibernate that can be used for drupal development?

# Answer
There are couple of things you can do in this scenario.

1. Create a custom module and use the core migrate framework to perform your migration. You may also require the migrate\_plus module for this. This project provides extensions to core migration framework functionality.
2. If you are just migrating CSV data then you can use feeds or Migrate Source CSV module as long as you have the content types properly configured in your Drupal instance.

It is recommended to use tools provided by and created for Drupal for tasks like this.
> 2 votes

# Answer
As others have said use the Drupal 8 Migration API to perform this task.

A good overview of the API and its usage and examples can be found at: https://www.drupal.org/docs/8/api/migrate-api/migrate-api-overview
> 2 votes

---
Tags: 8, nodes, database, migrations
---


title: Targeting Specific Image Templates

text:
# Question
Title: Targeting Specific Image Templates
I'm trying to implement a script for lazy loading images on my site and I'm not sure how to target specific image templates. I need to change the `src` attribute to `data-src` and add a class.

All images are currently using `image.html.twig`. If I change that template it almost works but ends up changing some images it shouldn't.

What would be a good way to modify the attributes of these images based on their use within specific paragraphs across the site?

Thanks

# Answer
> 1 votes
Three approaches (of many that are possible):

A good way would be to use a custom field formatter for images with data-src and configure this field formatter in the paragraph type. This is a module solution, but I think this is a good idea anyway to bundle this feature including the libraries.

A theming solution would be to add an attribute to each image field in a paragraph preprocess hook and then check for this attribute in the image template.

The easiest solution is to create a separate image style for lazy loading and check the style name in the image template.

---
Tags: theming, media
---


title: How to alter variable for ECK entity?

text:
# Question
Title: How to alter variable for ECK entity?
We are using the ECK module where we have created component eck\_highlight (machine name). How would we be able to modify the variable array using a preprocess hook?

Eck\_highlight component has this field:

* Field Reference to content types: basic, article, and event

Goal:

Call the preprocess to store 'info' array to vars (i.e. vars\['info'\]). The info variable will be passed into the Twig template so we can use to output information.

```
mymodule_preprocess_eck_highlight(&$vars) {
    $vars['info'] += [
       'id' => 'some-id',
       'height' => 'some-height',
       'width' => 'some-width',
       'src' => 'src1'
    ];
}

```

We have tried to do the following but cannot alter the variables.

1. mymodule\_preprocess\_eck\_highlight(&$vars)
2. mytheme\_preprocess\_eck\_highlight(&$vars)

# Answer
I am adding an answer so anyone who comes across this that i was able to resolve the issue. I had to use mymodule\_preprocess\_eck\_entity(&$vars).

When i tried to use the machine name in place of eck\_entity, it did not work.
> 3 votes

---
Tags: 8, hooks, entities
---


# Question
Title: Iterate through user custom fields in twig
I'm trying to iterate through a user reference field using twig. I'm able to get the username, but not any of the custom fields that I made for users such as "First Name" and "Last Name".

```
{% for item in items %}
  {{ kint(item.content['#options']) }}
  {{ item.content['#title'] }}
{% endfor %}

```

I'm trying to get the email address as well, but I can't figure out how to get these values.

I thought it would be something like:

```
{{ item.content['#options'].entity.mail }}

```

When I do that, the entire site crashes and I get errors. Am I doing something wrong?

# Answer
> 2 votes
You should never try to display field values by going that deep into structured field properties data within your Twig templates.

Consider using according field displays, or hook\_preprocess\_HOOK() to preprocess your template variables, e.g. by providing a simple array of preprocessed item data the template can iterate over (an abstract example to put into your mytheme.theme file; where you have to replace `mytheme` with the name of your theme and `themehook` with the template's theme registry hook - usually the template name with underscores instead of dashes):

```
/**
 * Implements hook_preprocess_HOOK().
 */
function mytheme_preprocess_themehook(&$variables) {
  // This will be the new list variable to attach to the
  // template.
  $users_list = [];

  // Get the entity object from existing theme variables.
  // This example assumes you have a node entity in
  // your variables array already.
  $entity = $variables['#node'];

  // Load all referenced users from a field named
  // 'field_users_entityreference'.
  $users = $entity->get('field_users_entityreference')->referencedEntities();

  // Iterate through all users found.
  if (!empty($users)) {
    foreach($users as $user) {
      $item = [
        // Add whichever properties you'd like
        // to show within your template.
        'email' => $user->getEmail(),
      ];
      $users_list[] = $item;
    }
  }

  // Attach the new variable to the template.
  $variables['users_list'] = $users_list;
}

```

In your Twig template you can now access the users list by accessing the new `users_list` variable:

```
{% if users_list %}
  {% for item in users_list %}
    {{ item.email }}
  {% endfor %}
{% endif %}

```

EDIT:

According to the template name you provided, you are trying to alter how the entity reference field itself is displayed. Generally you have the following choices:

(1) Using field display: Add an according display to the user entity and change the field display to rendered Entity using this display. You can do so by

* Go to "Admin / Structure / Display modes / View modes".
* Find the User entity (should be somewhere at the bottom) and add a new user view mode.
* Then go to "Admin / Configuration / People / Account settings / Manage display".
* Choose the newly created view mode and add all fields you want to show.
* Within "Admin / Structure", head to the entity using the reference field and find the "Manage display" tab.
* At the field in question change the Format to rendered entity and choose your newly created display mode by clicking the cogwheel at the very right of the row.

This approach usually fits your needs if you don't want to digg too deep into programming. Unfortunately you'd like to show the email address. This field is usually not available in user displays (privacy reasons; re-consider if you really want to show it). If you like to add that field to a regular user view, you'd have to additionally implement hook\_ENTITY\_TYPE\_view().

(2) Alter the additional template variables within a preprocessing hook:

* Within "Admin / Structure", head to the entity using the reference field and find the "Manage display" tab.
* At the field in question change the Format to Entity ID.
* Implement a preprocessing hook as described above.
* Fetch the item IDs from the existing variables and load the user entities.
* Attach your information to the variables and use it within your template:

$users = \Drupal\user\Entity\User::loadMultiple($variables\['items'\]);

---
Tags: 8, theming, entities
---


# Question
Title: How are access permissions prioritized when multiple modules implement them?
I have the Group module setup where I only allow view permission for group content to group members, so I have closed groups. But additionally, I want groups to also make some content public to non-members (but authenticated users) or to anonymous users even.

I have setup the Permissions by Term module for this where I made an "Additional view permissions" vocabulary that has two terms "all authenticated users" and "public". Those two terms I have granted permission to the respective roles. I had hoped that this would override the group permissions, but it doesn't. If I am not logged in, group content that has the "Additional view permissions" set to "public", still is not accessible to anonymous users.

I guess my question is: how does Drupal determine the priority of multiple modules arranging permissions for the same node, and can I influence this? In my case the group permissions seem to take priority, causing view permissions to be denied. But if it would first look at the permissions by term module, it would actually allow access.

# Answer
Have a look at this feature request Allow other modules to alter gnode\_node\_access's forbidden result, especially this part of it:

> If the group node's `gnode_node_access` module doesn't find a reason to return neutral, or to grant access, it returns a `AccessResult::forbidden()`. This prevents any other module from granting access. ...

So to "*determine the priority of multiple modules arranging permissions for the same node*" (as in your question): **if the Group module denies access, then there is no way for any other module to overrule that access**.

Maybe not what you *like* to hear/read, but this is how access is handled via Group module.
> 2 votes

---
Tags: 8, nodes, group
---


# Question
Title: Get link for same page in different language
I want to display a link to the spanish version of a page in my template, but another module is removing the language option on my link function:

```
l('Visit this page in Spanish', "node/{$node->nid}", array( 'language'=>'es' ));

```

I have the general routing set up the way I want; most of the time I want links to target the current language. Except this time - now I really want that link in spanish : )

How do I force `l()` to keep the language I specify? Or should I use another function?

# Answer
It should work when using this function: https://api.drupal.org/api/drupal/modules!translation!translation.module/function/translation\_node\_get\_translations/7

This will return all the translations of a given nid, when an ES translation is given you can print your l().
> 2 votes

# Answer
```
if ($node = menu_get_object()) {
  // Get the tnid
  $tnid = $node->tnid;
  $trans = translation_node_get_translations($tnid);
  print_r($trans);

}

```

And inside $trans array you'll have basic information of all translations (including current language) - title, language, nid, status... But of course, you can use nid to load whole node if you need something more.
> 1 votes

# Answer
If you want to get a specific page URL in a specific language URL use this code:

```
$languages = language_list();
$english_page_url = l(t('About'), 'node/22', array('language' => $languages['en']));
$arabic_page_url = l(t('About'), 'node/22', array('language' => $languages['ar']));

```

For your example you can use:

```
$languages = language_list();
l(t('Visit this page in Spanish'), 'node/' . $node->nid, array('language'=> $languages['es']));

```

Because you have to pass the language object not only the language prefix!
> 0 votes

---
Tags: 7, uri, i18n-l10n, navigation
---


# Question
Title: How do I get a field label in different languages?
In a module (not a template), I need the label of a specific field in multiple languages.

`$entity->getFieldDefinition('myField')->label()` gives me the label in current/active language (let's say, English).

What doesn't work as expected is the following:

`$entity->getTranslation('fr')->getFieldDefinition('myField')->label()`

I would expect the label in French. Instead, I get the label English. How to get the French label?

# Answer
> 4 votes
You can load an entity's translation by using the entity repository service. The field configuration is an entity itself. So you could try this:

```
use Drupal\field\Entity\FieldConfig;

// Override language before loading field configuration.
$language = \Drupal::languageManager()->getLanguage('fr');
\Drupal::languageManager()->setConfigOverrideLanguage($language);

// $entity_type, $bundle, $field.
$field_info = FieldConfig::loadByName('entity_type', 'bundle', 'myField');

$label = $field_info->getLabel();

```

EDIT:

As stated by 4k4 within the comments, config entities don't behave like content entities. So in order to get their translations, you will need to override the language before getting their translatable strings. Adjusted the example accordingly.

---
Tags: 8, entities, i18n-l10n
---


# Question
Title: How can i add WYSIWYG editor for my custom form textarea?
I wrote a custom form module in that I placed one text area:

I've tried in this way:

```
$form['message'] = array(
  '#title' => t('Message'),
  '#type' => 'textarea',
  '#format' => 'full_html',
  '#default_value' => isset($ntemplates->message) ? $ntemplates->message : '',
  '#maxlength' => 255,
  '#attributes' => array(
  'class' => array('field_info'),
  'rows' => '5',
  'cols' => '200',
  ),
  '#wysiwyg' => TRUE,
);

```

But it doesn't work. How can I integrate WYSIWYG editor in to my text area?

**Note**: I'm using wysiwyg-7.22 and ckeditor-3.6.6.2. In the basic page body section it's working. I wrote one custom module for form. In this I am unable to integrate wysiwyg editor.

# Answer
Drupal 7 introduces the form element `#type` `text_format`, which is a text-format-enabled version of a `textarea`.

To integrate WYSIWYG into your custom form, just modify the attribute `#type` of form as:

```
'#type' => 'text_format'

```

<sup>*Note:* Tested it with CKEditor v 7.x.</sup>

In case if it doesn't work for you, please check your WYSIWYG configuration.

To hide format options, see: How to hide Input Format Options and help text under a textarea?

Above text field type works in Drupal 7 and 8.
> 10 votes

# Answer
Note that stored value from field is an array not string. So to set up and use, do:

```
  if (($intro = variable_get('groups_intro', NULL)) == NULL){
    $intro = '';
  }
  $form['groups_intro'] = array(
    '#type' => 'text_format',
    '#title' => t('intro'),
    '#default_value'=> $intro['value'],
    '#format' => $intro['format'],
    '#cols' => 200,
    '#rows' => 10,
    '#required' => TRUE,
  );

```
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Use the trans tag in Twig without escaping HTML
I would like to use variables containing HTML inside a `trans` tag in my Twig template. (The variables contain the start and the end of a link which appears at different positions in the sentence for different languages.)

There is some documentation about "Drupal 8 Twig Templates and Translations" which explains that for variables inside the `trans` tag there is a `|placeholder`-filter and a `|raw`-filter (for older versions: `|passthrough`).

I see no difference in the output using these filters.
Here is my template:

```
{% set string = '<strong>&</strong>' %}
<div>
  {% trans %}
    Escaped: {{ string }}
  {% endtrans %}
</div>
<div>
  {% trans %}
    Pass-through: {{ string|raw }}
  {% endtrans %}
</div>
<div>
  {% trans %}
    Placeholder: {{ string|placeholder }}
  {% endtrans %}
</div>

```

And here ist the output:

```
Escaped: <strong>&</strong>
Pass-through: <strong>&</strong>
Placeholder: <strong>&</strong>

```

Is there any filter that will switch off escaping?

# Answer
AFAIK the Twig trans tag in Drupal 8 was implemented to ease translations to themers that were already familiar with Twig.

Under the hood, it's working with the same kind of translation strings as the regular Drupal translation function t() or the Drupal Twig filter |t, whereas all variables you are using within the trans block are handled as **@variable** or **%variable** placeholder within the translation strings.

These placeholders within the translation function always escape HTML before being inserted to the translation. No matter how you try to not escape the values you pass in, except you pass in a FormattableMarkup object.

Unsanitized variables (`{{ variable|raw }}` in Twig templates or `!variable` in translation strings) are deprecated for Drupal 8 translations and won't work in latest 8.x Drupal versions. The translation API description is a little outdated.

For your use case, you may just add the HTML link tag to your translation string and make the link URL itself the variable. Unfortunately, the Twig trans tag doesn't support that kind of variable yet. (Compare this core issue.) So you should use the t filter instead:

```
{{ 'A <a href=":url">link</a> example in a translation.'|t({ ':url': url }) }}

```

The above example matches the translation strings:

en: `A <a href=":url">link</a> example in a translation.`

de: `Ein Beispiel-<a href=":url">Link</a> in einer Übersetzung.`
> 10 votes

---
Tags: 8, theming, i18n-l10n
---


# Question
Title: How can I render a menu item as a span (or other elements) instead of a <a>?
I'm using Drupal 7 with the Bootstrap base theme, and I'd like to create a second and third level of drop-down. I tried using the special\_menu\_links module but nothing happens. I also tried what suggested on https://www.drupal.org/node/143322, but that doesn't work either.

How can I render a menu item as a span (or other elements) instead of a `<a>`?

# Answer
> 2 votes
You can use Special menu items module.

> User can create a new menu item and place either or to the Path field, without quotes.

Also, you can look at another handy module called Menu attributes which allowed you to have control over menu link attributes.

Both modules use hook\_menu\_alter to adjust the changes to the menu item, you can take look at the module's code to understand how it works exacitly if you are interested.

---
Tags: 7, navigation
---


# Question
Title: Proper way to get the base path when including an image from a module?
When using just drupal\_get\_path() to include an image from a module directory, this produces non-existent urls when using language prefixes.

I've seen a couple of modules prepend base\_path() to deal with this, but on the api page for base\_path() someone comments that you should use the `DRUPAL_ROOT` constant. What is the recommended way?

# Answer
> 8 votes
Drupal core uses `file_create_url()` for internal images like this (eg, the default favicon.ico handling in includes/theme.inc).

This ensures that `hook_file_url_alter()` gets called (the CDN module does this), that the basepath gets set, and that everything is escaped properly.

So, I would use

```
$path = drupal_get_path('module', 'mymodle');
$url = file_create_url($path . '/images/some.jpg');

```

# Answer
> 4 votes
You could use

`theme_image`

e.g:

```
  $variables = array(
    'path' => drupal_get_path('module', 'my_module').'/images/image.jpg',
    'alt' => 'My image',
    'title' => 'My image title',
    'attributes' => array('class' => array('my-image')),
  );
  $img = theme('image', $variables);

```

# Answer
> 1 votes
You should use $base\_url with drupal\_get\_path().

```
global $base_url;
$img_path = $base_url . '/' . drupal_get_path('module', 'YOUR_MODULE') . '/images/your_image.png';

```

In this way the image path won't be affected by i18n site url prefix settings.

# Answer
> 0 votes
Use the System stream wrapper module. It gives you a module://, theme:// and profile:// stream wrapper. These wrappers will (probably) be part of D8 core.

# Answer
> 0 votes
Sometime you may need to pass a NULL langage in the url function.

Example from commerce\_paypal

Not working link (original code)

```
  return url(drupal_get_path('module', 'commerce_paypal_ec') . '/images/paypal-ec-logo.gif', array('absolute' => TRUE));

```

Working link (hacked code)

```
  return url(drupal_get_path('module', 'commerce_paypal_ec') . '/images/paypal-ec-logo.gif', array('absolute' => TRUE, 'language' => ""  ));

```

Note: Hacking contributed modules is never reccomanded, of course.

---
Tags: uri, i18n-l10n
---


# Question
Title: How to hide clientside validation error message
Right now, I am using Clientside Validation. Everything works perfectly. But I would like to remove the error message which I set it showed at the top of the form. In the meantime, I would like to keep the error class which is added to my field input.

I have searched a lot about this but didn't get lucky. I know I might need to modify some code in **sites/all/modules/clientside\_validation/clientside\_validation.js** file, but I don't know which part I should touch.

Here is a sample screenshot:

Does anyone have any idea about this?

# Answer
You can hide error message using CSS or you can use Inline Form Errors which allow you to hide the error message.
> 0 votes

---
Tags: 7, forms, javascript
---


# Question
Title: My PECL uploadprogress bar appears, but why doesn't it show any progress?
I installed the PECL uploadprogress bar in php and this is working fine but when I start uploading a file it ends up getting stuck and dissapearing when the file is uploaded.

This is what i see when i start the upload:

The file is big enough so it doesnt open/close really fast.

But it just ends up being stuck at Starting upload... and not moving the blue bar to the right when its uploading. After a while it just dissapears and says done and i can submit the form fine.

This is how i want it to look like while uploading:

# Answer
Have a look at the (very old) issue # 633862. Even though it's an old issue, it includes quite a few comments that may help you to find "the clue". E.g. that it it doesn't seem to work for the more "exotic" server configurations.

Comment # 41 states this:

> Apparently secure servers also have an issue with it `https://` won't work with this.

Comment # 43 in that issue also suggest the (sandbox for now) upload\_progress module, here is what that comment includes:

> I have created a little module that uses client-side JavaScript instead of server-side code to display the progress. This will finally bring upload progress to more "exotic" server configurations.
> 1 votes

# Answer
Hi all :) About this challenge with PECL uploadprogress bar showing, but not showing any progress, here are two additional options to choose from

**First Option**

Have you tried to first **upgrade your server-side versions, packages, and libraries** to meet PECL upload progress's minimum requirements?

We struggled for months trying to display the progress status using PECL uploadprogress. In our case it turns out the source of the challenge was that the server-side versions, packages, and libraries were too old. As a result they do not support PECL upload progress minimum requirements.

**Second Option**

Until that server is upgraded, to resolve this challenge we found a fantastic alternative. PECL uploadprogress is great. But in some cases and for newcomers it might be challenging to install and configure. Mostly because it depends on server-side libraries and configuration. If you prefer a client-side upload progress, you might be interested in this **File Resumable Upload (file\_resup)** module. The benefits are:

* Easy installation. Because no dependencies, except Drupal core File itself, and no libraries.
* Bypass PHP's upload limits
* Works with both 32bit and 64 bit servers
* Allows to upload large files (over 2 GB)

Thanks to Brad for his discovery. Source, documentation, and details at https://www.drupal.org/node/793264#gen-faq---alternatives
> 1 votes

---
Tags: 7, files
---


# Question
Title: Does Multiversion module need content migration if enabled on running site?
I have Drupal 8 setup with lot of content in it. When I enable Multiversion module all the content gets disappeared. Do I have to migrate the content after installing Multiversion? Why does it deletes the content?

# Answer
As mentioned in the Multiversion description on Drupal.org that it should be enabled on the fresh instance of the drupal. If you are planning to use multiversion on already established database then on enabling this module it will erase all the entities including the custom ones. It will delete all Taxonomy Terms, Menu Items, Content, Config Entities. So that will require content migration on after install. But there is another way, 1. Install a fresh database 2. Enable the Multiversion 3. Sync the configuration. Configration management comes really handy in this case.
> 0 votes

---
Tags: migrations
---


title: Display main menu item based on the URL

text:
# Question
Title: Display main menu item based on the URL
I want to show main menu links in the sidebar. I have placed that menu block in sidebar region from admin side.

But based on the current URL, i need to display that particular menu item.

```
Item1 (item1)
  Item1_Sub1_item1 (item1/sublev1)
     Item1_Sub1_Sub2_item1 (item1/sublev1/subsublev1)
     Item1_Sub1_Sub2_item2 (item1/sublev1/subsublev2)
  Item1_Sub1_item2
     Item1_Sub1_Sub2_item1
     Item1_Sub1_Sub2_item2
Item 2
  Item2_Sub1_item1
     Item2_Sub1_Sub2_item1
     Item2_Sub1_Sub2_item2
  Item2_Sub1_item2
     Item2_Sub1_Sub2_item1
     Item2_Sub1_Sub2_item2

```
1. If the current url is / (home), then my menu should diplay all menu item
2. If the current URL (item1/sublev1) match to menu item (Item1\_Sub1\_item1) then only the parent and child of that menu should be displayed as below

> ```
> Item1 (item1)
>   Item1_Sub1_item1 (item1/sublev1)
>      Item1_Sub1_Sub2_item1 (item1/sublev1/subsublev1)
>      Item1_Sub1_Sub2_item2 (item1/sublev1/subsublev2)
>
> ```

3. If the current URL (item1/sublev1/subsublev1) match to menu item (Item1\_Sub1\_Sub2\_item1) then only the parent and child of that menu should be displayed as below

> ```
> Item1_Sub1_item1 (item1/sublev1)
>   Item1_Sub1_Sub2_item1 (item1/sublev1/subsublev1)
>
> ```

I have overridden the menu--main.html.twig file using theme suggestion and using menu--main-sidebar.html.twig file to design the menu.

Any idea how to achieve this? My guess is,

1. I need to create a block programmatically to do all these operations
2. Display that block in my html.twig.file

If I am right, how to do that in theme? If i am wrong, what else need to do?

For info I am already using Menu\_block module, but I can't place block for each URL. So i want to program it.

# Answer
Yeah, I think your guess is good.

1. Create a block programmatically: Create a custom Block. This means to create an own module with this block.
2. The created block should appear (when the module is activated) in your block settings, there you can add it.
3. The content of your block appears where you added it.

Another option, easier but not so beautiful, could be to hook in your `THEME.theme`. As an example you can add the menu in the `template_preprocess_html`:

```
function template_preprocess_html(&$variables) {
    $variables['my_own_menu'] = $my_own_menu;
}

```

Then you can use the variable `{{ my_own_menu }}` in your `html.html.twig` and do whatever you want to do.
> 2 votes

---
Tags: 8, theming, blocks, navigation
---


# Question
Title: How do I add a date picker that is rendered from most the browsers?
I am migrating from Drupal 7 to Drupal 8. In forms I use `'#type' => 'date_popup'` for date fields, which Drupal 8 replaces by `'#type' => 'date'` and uses HTML 5.

I'm finding it most unsatisfactory because:

1. It has poor browser support; Internet Explorer 11 doesn't provide a popup.
2. I can't find anyway to change the input format from 'm/d/yyyy' to either 'd/m/yyyy' or 'yyyy-mm-dd'.

I have ensured that my browser language setting is English (Australian) which has a default date format of 'd/m/yyyy'.

Does anyone have a solution that provides a date picker for most the browsers and a text input format that can be controlled by the server, not the client?

# Answer
I had a similar issue just recently within a client's intranet application, after Firefox added HTML5 date field support. (FF is their corporate browser of choice.)

You can still use any JavaScript based datepicker that suits your needs. (E.g. jQuery UI's datepicker.)

In your JavaScript bind this datepicker to all input fields of type date and then change the type of the input fields to text. This prevents the browsers from using their own datepickers.

PS.: It's not exactly a Drupal specific question, but tomorrow when back in my office I might add a code example that works for Drupal 8.
> 1 votes

---
Tags: forms, datetime
---


# Question
Title: What is the template file name for a bean block?
My block is called "hero", on the front-end the class is `block-bean-hero`, what is the proper template file name for this block?

# Answer
> 1 votes
As I can infer from the class name, your module name is "bean", so the template name should be `block--bean--hero.tpl.php`. For more information you can check the Template (theme hook) suggestions documentation.

---
Tags: 7, theming, blocks
---


# Question
Title: Loop Custom Content based on the taxonomy term they are in
I created a taxonmy vocabulary, added 3 terms in it Term1, Term2, Term3

Then I created a custom content type, and I associated it with that vocabulary term, so now everytime I create a page I check to which Term they belong to,

What I want to do is Loop the name of the Term + all the pages titles and body that belong to that term

For example:

```
<h1>Term1</h1>
<ul>
 <li>Page 1 title </li>
 <li>Page 2 title </li>
 </ul>
<h1>Term2</h1>

```

Thanks

# Answer
> 0 votes
This was the answer I was looking for

```
<?php
$nodes = node_load_multiple(array(), array('type' => 'analize'));
$listAnalize = [];
foreach ( $nodes as $kNod => $vNod ) {
  $term = taxonomy_term_load( $vNod->field_categoria_analizei['und'][0]['tid'] );

  $listAnalize[$vNod->field_categoria_analizei['und'][0]['tid']]['denumire'] = $term->name;
  $listAnalize[$vNod->field_categoria_analizei['und'][0]['tid']]['analize'][] = $vNod;
}
?>

```

---
Tags: nodes, taxonomy-terms
---


# Question
Title: How to get all pages of a custom content type to be displayed using a custom view?
In Drupal 8, how can I get all pages of a custom content type "MyPage" to be displayed using a custom view "MyView"?

# Answer
> 0 votes
1. Structure -\> Views -\> Add a view (\`/admin/structure/views/add')
2. **View Settings**: Show **Content** of type **MyPage**.

I suggest reading the Views documentation.

# Answer
> 0 votes
1) Go to Structure -\> Views -\> Add a view (\`/admin/structure/views/add')
2) In filter criteria select Content:content type (= MyPage)

---
Tags: views, 8
---


title: Serial vs int schema data type options

text:
# Question
Title: Serial vs int schema data type options
When should serial be chosen over an int when choosing a data type for a table column? Are they separated out for indicating a difference in the data types. If so what type of data should be stored as serial and as int?

Examples would be greatly appreciated.

# Answer
> 1 votes
Serial is used for auto-increment column of the table(so here auto increment is implicit), e.g. for node table nid has a serial data type and int can be any number based on size provided.

> '**type**': The generic datatype: 'varchar', 'char', 'int', 'serial', 'float', 'numeric', 'text', 'blob' or 'datetime'. The types map to the underlying database engine specific datatypes. Use 'serial' for auto incrementing fields.

Reference: https://www.drupal.org/docs/7/api/schema-api/schema-reference

---
Tags: 7, database
---


# Question
Title: language back to default language after Ajax reload
To simplify the question and maybe reproduce the problem, I made a simplier version of what I am doing. I have a form field with ajax. When it triggers it reloads a small piece of html. In it is t('text in one of tree languages'); If I open the page for the first time the same html is loaded and it is in the correct language. But after the reload from the ajax call it is in the website's default language. This only happens when logged in. It is possible that this has to do with the administrator language module. Any help would very much be appreciated.

Ajax Code at `hook_form`

```
function hook_form($form, &$form_state) {
  $form['update'] = array(
    '#value' => t('Update'),
    '#type' => 'button',
    '#ajax' => array(
              'callback' => 'callback_function',
              'wrapper' => 'div-to-replace',
              'method' => 'replace',
              'effect' => 'fade')
  );

  // Other form elements

}

```

Ajax callback function

```
function callback_function($form, $form_state) {
    return t('test string that should get translated');
}

```

# Answer
The `ajax callback` should return the dynamic form element (and not directly the value). I've created some sample code where the translated content / string is correct after an ajax reload.

```
function YOURMODULE_form($form, &$form_state, $file_group)
{
    $form['update'] = array(
        '#value' => t('Update'),
        '#type' => 'button',
        '#ajax' => array(
            'callback' => 'YOURMODULE_form_ajax_cb',
            'wrapper' => 'ajaxWrapper',
            'method' => 'replace',
            'effect' => 'fade'
        )
    );

    $form['ajax'] = array(
        '#type' => 'container',
        '#attributes' => array(
            'id' => 'ajaxWrapper',
        ),
    );

    $form['ajax']['text'] = array(
        '#type' => 'markup',
        '#markup' => t('My translated string'),
    );

    // Rest of the form
}

function YOURMODULE_form_ajax_cb($form, &$form_state)
{
    return $form['ajax'];
}

```
> 1 votes

# Answer
I see in my installations that when i disable the administration language module, the problem is solved :)
> 0 votes

# Answer
$referrer = explode('/', $\_SERVER\['HTTP\_REFERER'\]);

```
$current_lang = $referrer[5];

```

This can solve your problem
> 0 votes

# Answer
Having the same problem. On ajax callback t function is complealty ignored and strings are not even on TI. I can enforce them to appear in TI using locale function, but then I also need to pass language to it. What is the real problem is that I can't pass language to ajax callback, whenever I try to pass it, it goes to default english.
> -1 votes

---
Tags: forms, ajax, i18n-l10n
---


title: How to get taxonomy term name from tid?

text:
# Question
Title: How to get taxonomy term name from tid?
A lot of our stuff has uris formatted like `site/taxonomy/XX`, where XX is an integer.

I found a lot of questions like "*how to get the TID from the name?*", but I'd like to get the name from the `TID`. I'm trying to put together a breadcrumb script and everything is great except for these cases where I'm getting a trail like "`home > term`". Instead I want to have it like "`home > <TERM NAME>`".

How can I do so?

# Answer
> 99 votes
If you're using Drupal 7 you can use `taxonomy_term_load()`

```
$term = taxonomy_term_load($tid);
$name = $term->name;

```

If you've got a bunch of term IDs you can save having to run a single query for each load by using `taxonomy_term_load_multiple()`:

```
$tids = array(1, 2, 3);
$terms = taxonomy_term_load_multiple($tids);

foreach ($terms as $term) {
  $name = $term->name;
}

```

If you're stuck using Drupal 6 you can use `taxonomy_get_term()`:

```
$term = taxonomy_get_term($tid);
$name = $term->name;

```

There's no multiple-load option for Drupal 6 that I know of unfortunately.

# Answer
> 13 votes
In Drupal 8, you can get the name of taxonomy terms this way:

```
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

$name = $term->label();

```

Or to load multiple:

```
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadMultiple($tids);

foreach($terms as $term) {
  $name = $term->label();
}

```

# Answer
> 5 votes
The following function returns the name of a taxonomy term based on its tid:

```
function get_term($tid) {
  return db_select('taxonomy_term_data', 't')
  ->fields('t', array('name'))
  ->condition('tid', $tid)
  ->execute()
  ->fetchField();
}

```

# Answer
> 3 votes
> For D7:

```
$term = taxonomy_get_term_by_name($term_name, $vocab_name);
  foreach($term as $key => $data) {
    $tid = $data->tid;

    dpm($tid);

  }

```

> For D8:

```
$term_name = \Drupal\taxonomy\Entity\Term::load(2)->get('name')->value;
dpm($term_name);

```

# Answer
> 1 votes
It is possible to obtain the name of the term in Drupal 8 in the following way:

```
//Obtain the term.
$tid=1;
$term= taxonomy_term_load($tid);

//get the field name
$term->label();

//or
$term->get('name')->value;

```

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


title: How to refresh include (inc) file

text:
# Question
Title: How to refresh include (inc) file
I updated an include (inc) file. It was a text change. I want my website to show these changes. I cleared the cache. Nothing changed. I restarted the server. Nothing changed. I checked the server. The new include (inc) file is there. Not sure how else to refresh the include (inc) file. It's located at htdocs\sites\all\modules\custom\myMods

Here is the new file: ( I simply changed the text in the of the description )

```
<?php
/**
 * @file
 * siam_team_profile.field_group.inc
 */

/**
 * Implements hook_field_group_info().
 */
function siam_team_profile_field_group_info() {
  $field_groups = array();

  $field_group = new stdClass();
  $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
  $field_group->api_version = 1;
  $field_group->identifier = 'group_parcon|node|team_member|form';
  $field_group->group_name = 'group_parcon';
  $field_group->entity_type = 'node';
  $field_group->bundle = 'team_member';
  $field_group->mode = 'form';
  $field_group->parent_name = '';
  $field_group->data = array(
    'label' => 'Parental Consent',
    'weight' => '7',
    'children' => array(
      0 => 'field_consent',
      1 => 'field_name_of_parent',
      2 => 'field_ethnicity',
    ),
    'format_type' => 'fieldset',
    'format_settings' => array(
      'label' => 'Parental Consent',
      'instance_settings' => array(
        'required_fields' => 1,
        'classes' => 'group-pconsent field-group-fieldset',
        'description' => '<p><strong>The section below is to be filled out by the student’s parent or guardian.</strong></p>

<div>
By agreeing to this Parent/Guardian Consent statement, I give my permission for my son/daughter to participate in  <i>MATLAB Math Modeling Challenge</i>, which is funded by The MathWorks and organized and administered by the Society for Industrial and Applied Mathematics (SIAM). I give my permission to disclose his/her name and likeness in text, still pictures, and in videos, for publication in press releases, on the M3Challenge and MathWorks* websites, and in SIAM News. I also give my permission to release his/her name and likeness to any and all online or print local, regional, or national newspapers, radio and television outlets, and via any other media, including social media platforms, that seek to publicize the Challenge and its participants in any way. <br /><br />

On behalf of myself and my child, I hereby (a) waive any right or cause of action arising as a result of his/her participation in the Challenge and (b) release and discharge MathWorks and SIAM from any and all claims or causes of action (known or unknown) arising out of his/her participation in the Challenge (including, but not limited to, its or their negligence). <br /><br />

I understand that for teams proceeding to the final competition process, the students\' live presentations at the final Challenge event will be photographed and/or videotaped, and these photos and videos may be used for webcast, broadcast, posting to the M3 Challenge website, in news releases, and in the media, as well as in internal or external SIAM or MathWorks publications, online or in print, and on any SIAM or MathWorks Internet websites and digital social media presence, and I consent to any and all such use. <br /><br />

*MathWorks includes The MathWorks, Incany and all of its product lines, affiliates, subsidiaries, and their successors and assigns, and any and all of their past and present directors, officers, representatives, agents and employees, whether as individuals or in their official capacity.
</div>',
      ),
      'formatter' => 'collapsible',
    ),
  );
  $field_groups['group_parcon|node|team_member|form'] = $field_group;

  $field_group = new stdClass();
  $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
  $field_group->api_version = 1;
  $field_group->identifier = 'group_personal|node|team_member|form';
  $field_group->group_name = 'group_personal';
  $field_group->entity_type = 'node';
  $field_group->bundle = 'team_member';
  $field_group->mode = 'form';
  $field_group->parent_name = '';
  $field_group->data = array(
    'label' => 'Personal Information',
    'weight' => '0',
    'children' => array(
      0 => 'field_first_name',
      1 => 'field_gender',
      2 => 'field_grade',
      3 => 'field_teamail',
      4 => 'title',
    ),
    'format_type' => 'fieldset',
    'format_settings' => array(
      'formatter' => 'collapsible',
      'instance_settings' => array(
        'description' => '',
        'classes' => 'group-personal field-group-fieldset',
        'required_fields' => 1,
      ),
    ),
  );
  $field_groups['group_personal|node|team_member|form'] = $field_group;

  // Translatables
  // Included for use with string extractors like potx.
  t('Parental Consent');
  t('Personal Information');

  return $field_groups;
}

```

Old file for reference:

```
            <?php
    /**
     * @file
     * siam_team_profile.field_group.inc
     */

    /**
     * Implements hook_field_group_info().
     */
    function siam_team_profile_field_group_info() {
      $field_groups = array();

      $field_group = new stdClass();
      $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
      $field_group->api_version = 1;
      $field_group->identifier = 'group_parcon|node|team_member|form';
      $field_group->group_name = 'group_parcon';
      $field_group->entity_type = 'node';
      $field_group->bundle = 'team_member';
      $field_group->mode = 'form';
      $field_group->parent_name = '';
      $field_group->data = array(
        'label' => 'Parental Consent',
        'weight' => '7',
        'children' => array(
          0 => 'field_consent',
          1 => 'field_name_of_parent',
          2 => 'field_ethnicity',
        ),
        'format_type' => 'fieldset',
        'format_settings' => array(
          'label' => 'Parental Consent',
          'instance_settings' => array(
            'required_fields' => 1,
            'classes' => 'group-pconsent field-group-fieldset',
            'description' => '<p><strong>The section below is to be filled out by the student’s parent or guardian.</strong></p>

    <div>
    By agreeing to this Parent/Guardian Consent statement, I give my permission for my son/daughter to participate in Moody\'s Mega Math (M<sup>3</sup>) Challenge, which is funded by The Moody\'s Foundation and organized and administered by the Society for Industrial and Applied Mathematics (SIAM). I give my permission to disclose his/her name and likeness in text, still pictures, and in videos, for publication in press releases, on the M<sup>3</sup> Challenge and Moody\'s* websites, and in SIAM News. I also give my permission to release his/her name and likeness to any and all online or print local, regional, or national newspapers, radio and television outlets, and via any other media, including social media platforms, that seek to publicize the Challenge and its participants in any way.<br /><br />

    On behalf of myself and my child, I hereby (a) waive any right or cause of action arising as a result of his/her participation in the Challenge and (b) release and discharge Moody\'s and SIAM from any and all claims or causes of action (known or unknown) arising out of his/her participation in the Challenge (including, but not limited to, its or their negligence).<br /><br />

    I understand that for teams proceeding to the final competition process, the students\' presentations at Moody\'s headquarters in Manhattan will be photographed and/or videotaped, and these photos and videos may be used for webcast, broadcast, posting to the M<sup>3</sup> Challenge website, in news releases, and in the media, as well as in internal or external SIAM or Moody\'s publications, online or in print, and on any SIAM or Moody\'s Internet websites, and I consent to any and all such use.<br /><br />

    *Moody\'s includes Moody\'s Corporation, and any and all of its affiliates, subsidiaries, and their successors and assigns, and any and all of their past and present directors, officers, representatives, agents and employees, whether as individuals or in their official capacity.
    </div>',
          ),
          'formatter' => 'collapsible',
        ),
      );
      $field_groups['group_parcon|node|team_member|form'] = $field_group;

      $field_group = new stdClass();
      $field_group->disabled = FALSE; /* Edit this to true to make a default field_group disabled initially */
      $field_group->api_version = 1;
      $field_group->identifier = 'group_personal|node|team_member|form';
      $field_group->group_name = 'group_personal';
      $field_group->entity_type = 'node';
      $field_group->bundle = 'team_member';
      $field_group->mode = 'form';
      $field_group->parent_name = '';
      $field_group->data = array(
        'label' => 'Personal Information',
        'weight' => '0',
        'children' => array(
          0 => 'field_first_name',
          1 => 'field_gender',
          2 => 'field_grade',
          3 => 'field_teamail',
          4 => 'title',
        ),
        'format_type' => 'fieldset',
        'format_settings' => array(
          'formatter' => 'collapsible',
          'instance_settings' => array(
            'description' => '',
            'classes' => 'group-personal field-group-fieldset',
            'required_fields' => 1,
          ),
        ),
      );
      $field_groups['group_personal|node|team_member|form'] = $field_group;

      // Translatables
      // Included for use with string extractors like potx.
      t('Parental Consent');
      t('Personal Information');

      return $field_groups;
    }

```

# Answer
There is cache somewhere along the stack so if its not drupal cache

try making a small change on the file that includes this file and saving in order to force renewing the timestamp

or you might want to try

```
//after include
clearstatcache();

```

more info here http://php.net/manual/en/function.clearstatcache.php

or if you have opcache enabled can try to setting it `opcache.enable = 0` or

```
//
opcache_invalidate ( string $script [, boolean $force = FALSE ] )

```

or please tell us how your website is accessed all service running on your server that might be intercepting the generation of the site
> 1 votes

---
Tags: 8
---