title: Admin view/edit content as user

text:
# Question
Title: Admin view/edit content as user
Is it possible to toggle an admin role to see and edit content as a specific user?

I've got a number of entityreferences with contextual filters that are URL dependent, and when I try to edit an entityform submission as admin, I can only see my own data view.

# Answer
I think you are looking for this module Masquerade.

> The Masquerade module allows site administrators (or anyone with enough permissions) to switch users and surf the site as that user (no password required). That person can switch back to their own user account at any time.

There is a module called Role Toggle to handle role toggle.

> This module gives you a page and a block to toggle (switch on and off) any role.
> 0 votes

---
Tags: database, entities, users
---


# Question
Title: Path breadcrumbs Link title for webform submission
I have one Webform field call "Name". I use views to retrieve Webform result and edit link. I am using Path breadcrumbs module.

Example:

UserA - Edit
UserB - Edit
UserC - Edit

User A, B, and C had submitted the form. When I click edit, it will goes to their submission form where they can edit the info again.

When I click on the link, I hope breadcrumb will display "Name"

Example:

home \> UserA
instead of
home \> webform

home \> UserB
instead of
home \> webform

home \> UserC
instead of
home \> webform

Name is text. Link is not needed.

Can I add it to breadcrumb link title? How to do that?

# Answer
> 2 votes
I was going to post something with Crumbs, but maybe you can start with something simpler:

I am trying to make this answer useful to different visitors who might have different ideas about their breadcrumb for webform submission pages.

## Page access considerations

Do your visitors (those this is meant for) have access to pages like

* node/28/submission/1/edit ? (I suppose the answer is yes)
* node/28/submission/1 ? (Please check)

## With hook\_menu\_alter()

I'm not sure what this does on a site without Crumbs enabled, but you can give it a try. This will change the page title / navigation title, which I think is used by core for building the breadcrumb.

This means if you had "Submission #1" as part of your breadcrumb, this will replace it with "Submission #2 by NAME".

Consider this code a stub. Especially the `$submission->data[1][0]`. This just happened to work for me, but might be different for you. devel dpm() is your friend!

```
/**
 * @param array[] $items
 */
function d7light_menu_alter(&$items) {

  if (!empty($items['node/%webform_menu/submission/%webform_menu_submission'])) {
    /* @see _d7light_webform_submission_title() */
    $items['node/%webform_menu/submission/%webform_menu_submission']['title callback'] = '_d7light_webform_submission_title';
  }
}

/**
 * @param object $node
 * @param object $submission
 *
 * @return string
 *
 * @see webform_submission_title()
 */
function _d7light_webform_submission_title($node, $submission) {

  if (empty($submission->data[1][0])) {
    return t('Submission #@serial', array('@serial' => $submission->serial));
  }

  return t(
    'Submission #@serial by @name',
    array(
      '@serial' => $submission->serial,
      // @todo Maybe something more generic than ->data[1][0]?
      '@name' => $submission->data[1][0],
    ));
}

```

## With Easy Breadcrumb + hook\_menu\_alter()

Tbh I have only tested the code above with Crumbs enabled. So I don't know if it works without it.

I am also quite confident that it will work with Easy Breadcrumb, based on my understanding how it works.

## With Crumbs + hook\_menu\_alter()

As said: You could try if enabling Crumbs makes a difference.

If you do, you might want to check admin/structure/crumbs/display and enable the "show current page".

## With the Crumbs API.

This is an alternative to the method above, which does not change the page title but only the name in the breadcrumb.

Here is a starting point.

```
/**
 * A hook to register crumbs plugins.
 *
 * @param crumbs_InjectedAPI_hookCrumbsPlugins $api
 *   An object with methods to register plugins.
 *   See the class definition of crumbs_InjectedAPI_hookCrumbsPlugins, which
 *   methods are available.
 */
function MYMODULE_crumbs_plugins($api) {

  $api->routeTitleCallback(
    'node/%/submission/%',
    'webform_submission',
    function($path, array $item) {
      $node = $item['map'][1];
      $submission = $item['map'][3];
      if (0
        || !is_object($node)
        || !is_object($submission)
        || $node->type !== 'webform'
        || empty($submission->data[1][0])
      ) {
        return NULL;
      }
      $submission_name = $submission->data[1][0];
      return $item['title'] . ' (' . check_plain($submission_name) . ')';
    });
}

```

The same comment applies about `$submission->data[1][0]`.

## Changing the trail

Once you have tried those things, you can ask if you need more. I will then write more in this section.

---
Tags: 7, views, webforms, breadcrumbs
---


# Question
Title: Is there a way to send an email to a mailchimp list on the event of a content type being published?
The title says it all, really.

I want to trigger the dispatch of an email to a list of subscribers on mailchimp every time a certain content type is published.

Using rules I can see that the only mailchimp action available is to sign a user up to a list, so if there is a way of adding a new action to send an email to all users in a list that would be exactly what I need.

Any other methods are welcome too.

Thanks very much.

# Answer
> 1 votes
I don't think you can do that directly from the interface. You need to create a hook function hook\_rules\_action\_info in your custom module's .rules.inc file which will describe what the action actually does. See the link http://www.drupalcontrib.org/api/drupal/contributions!rules!rules.api.php/function/hook\_rules\_action\_info/7 Even I'm looking for some good example or tutorial for this. Cheers!

# Answer
> 0 votes
You can create an RSS-To-Email Campaign in MailChimp. Take a look here: http://blog.mailchimp.com/rss-to-email-tutorial/

---
Tags: rules, emails
---


# Question
Title: Adding the contextual link render element
I have render array like this.

```
$array = [
  '#theme' => 'theme_wrap',
  '#content' => $data,
  '#contextual_links' => [
    'my_module' => [
      'my_module.router.name', $pid
    ]
  ]

```

and theme-wrap.html.twig

```
{%
set classes = [
'contextual-region'
]
%}
<div {{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {{ title_suffix }}
  {{ content }}
</div>

```

and file mymodule.links.contextual.yml

```
mymodule.admin.edit:
  title: 'Edit'
  route_name: my_module.router.name
  group: my_module

```

and route name **my\_module.router.name** exited and working. Render data array working but don't see contextual link.

**Update:** I have a form to user can enter input. After submit i'll show data from user. And simple controller return array above. \- I have insert {{ title\_suffix }},{{ title\_prefix }} class **contextual-region** but don't working.

I was doing something wrong? Please help!

# Answer
After debug function contextual\_preprocess(). I've found the answer. My problem is module contextual will set variable **title\_suffix** to first variable in define function themes. In my case: i have function theme

```
<?php
mymodule_theme($existing, $type, $theme, $path) {
  $theme = [];
  $theme['my_theme'] = [
    'path' => $path . '/templates',
    'variables' => [
      'content' => '',
    ]
  ];
  return $theme;
}

```

when module contextual will be set variable **title\_suffix** in variable **content**. Debug in twig data like this:

```
content[
  $data,
  '#contextual_links'= > [...]
]

```

So want adding the contextual link render element i need add context\_link to variable data like this:

```
//have $data and add new contextua link
$data['#contextual_links'] => [
  'my_module' => [
    'my_module.router.name', $pid
  ]
]

$array = [
  '#theme' => 'theme_wrap',
  '#content' => $data,
]

```

and it't working.
> 2 votes

# Answer
First of, usually you want to handle the contextual links in your preprocess theme function so you don't have to handle it every time you need to render the thing.

The actual contual links is added to `title_suffix`, so you need to do `{{ title_suffix }}` somewhere in your template to actual render the contextual links. You also need to render the attributes or make sure your wrapper html tag has the `contextual-region` class.

In Drupal 8, most of contexual links are used with relationship to an entity. If you have something you can view and edit most likely it should be an entity, meaning you should use the entity view builder to render it etc. Might also make it easier for you to do contextual links, as there are many examples of how this is done in core and contrib, like the node module, user module taxonomy module etc.
> 4 votes

---
Tags: 8, navigation
---


# Question
Title: Redirect basic page to external url when visiting page
I'm attempting to provide a field to users to enable them to enter an external url. If they enter a url I would like that basic page to redirect to the url the user provided instead of actually opening the node. I've made some attempts by using a preprocess node hook in my custom .theme file as seen here:

```
function mytheme_preprocess_node(&$variables){
    $node = Drupal::request()->attributes->get('node');
    $type = $node->getType();
    if($type == 'page'){
        $redirect = $node->get('field_redirect')->value;
        if($redirect != ''){

            $response = new Symfony\Component\HttpFoundation\RedirectResponse($redirect);
            $response->send();
            Drupal::entityManager()->getViewBuilder('node')->resetCache();
            return;
        }
    }
}

```

And I've also tried creating a module to do it and using an entity\_view hook like so

```
<?php

function mymodule_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'page' && !$entity->field_redirect->isEmpty()) {
    $value = $entity->field_redirect->getValue();
    $redirect = $value[0]['value'];
    $response = new Symfony\Component\HttpFoundation\RedirectResponse($redirect);
    $response->send();
    return;
  }
}

```

Each of these solutions work the first time, but don't work the 2nd time or any time after that until I clear the cache. I'm assuming this is a caching issue. I've heard that using cache tags could resolve this issue but I'm not sure how I would use them. Also I'm not married to making any of these solutions work I merely want to implement some way to perform redirects on pages, it doesn't matter to me how.

Is it possible to perform redirects on node pages?

# Answer
> 1 votes
this is a cache problem. You need to set correctly the cache tags and context for the entity and it will work. You need to do something like this to skip the cache:

```
  '#cache' => ['max-age' => 0],

```

you can find more info here: https://www.drupal.org/developing/api/8/cache/tags

**Notes**:

* This needs to be put on `hook_entity_view_alter()` on the entity in your case the node, or if you want in just one field for which you want to set it. This is a work around for your redirect issue!
* Try to add it to the `$entity`, if it doesn't work you need to replace the default '#cache' or you can add it to the `$build` array, this is case dependent.

# Answer
> 1 votes
You could extend the NodeViewController (and invoke it via an own NoteRouteProvider) in your module and return the redirect there instead of the $build array. Feels much cleaner to me.

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


# Question
Title: How to customize the text of "SUBMITTED BY" (article)
I like to customize the output of SUBMITTED BY, e.g. I like to change it to WRITTEN BY.
Where can I do it? Thanks for help

# Answer
I think you need specifically for **ARTICLE Type**, just do apply change in `node.html.twig` template file(Here I am referring Bartik theme's node.html.twig for common understanding) as shown below. So for all other content type it will be `Submitted by` and for Articles it will be `Written By`,

**Original code in node.html.twig,**

```
    <span{{ author_attributes }}>
      {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
    </span>

```

**Replace it with,**

```
    {% if node.getType() == 'article' %}
       <span{{ author_attributes }}>
         {% trans %}Written by {{ author_name }} on {{ date }}{% endtrans %}
       </span>
    {% else %}
       <span{{ author_attributes }}>
         {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
       </span>
    {% endif %}

```
> 3 votes

# Answer
In node.html.twig change the line `SUBMITTED BY` to `WRITTEN BY`

```
  {% if display_submitted %}
    <footer class="node__meta">
      {{ author_picture }}
      <div{{ author_attributes.addClass('node__submitted') }}>
        {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
        {{ metadata }}
      </div>
    </footer>
  {% endif %}

```
> 5 votes

---
Tags: theming, 8
---


# Question
Title: Fetch product data from commerce order on rules check-out completention
This is the scenario :

Designing a automation website, user buys a product of type "EditOption", an EditOption consist of an editor and a task. When a user buy one of these products a new content of type "Project" should be created automatically, containing Editor and the task which must be assigned to him/her. So what I want is to **fetch EditOption's Data from commerce order** so these can be used later creating the new content.

I'm looking for a solution based on rules events.

The problem I faced is I can't get through commerce-line-items to fetch it's data. this is the result I get :

# Answer
> 0 votes
The solution I found:

First of all we need to create a Component which takes commerce-line-item as input,there we add some conditions to check if the item we are processing is of our desired type or not,this is how it configured :

Note that the way conditions are sorted is important.

Now after setting these conditions rules know that the item is definitely of type 'EditOption' so now all fields related to these type is accessible like below :

to create a content of type project I created another component which takes editor and 'EditOption' as inputs and the created my desired entity.(it is called in first component using data fetched from order)

the final step was to add an action of my first component in loop for each commerce-line-item of order.

here is the image :

Everything works fine now.

---
Tags: commerce, rules
---


# Question
Title: Using a field for populating the meta-tags of view pages
I've got taxonomy pages that are emulated by real views. The vocabulary terms have an additional field "field\_meta\_description", where meta-description tags can be added. On the view page of each term, this field should be used to populate the content of the html tag `<meta name="description"/>`. How can this be accomplished? I know there are some modules out there like metatag, but I am looking for a custom way to do it by lightweight self-coding.

# Answer
> 2 votes
Assuming Drupal 7:

You can go for implementing hook\_page\_alter() in your theme's template.php and use drupal\_add\_html\_head() to insert your own metatags. Following the link you will find lots of exmples in the comments.

---
Tags: views, theming, meta-tags
---


# Question
Title: What is the variable/method to address the content type in a template file?
What is the variable/method to address/fetch a particular content type in template files?

What variable/method shall I put at the blank space so my statement/logic will be like `if contentType == 'article'`?

```
{% if ____________ %}
  ......
  ........
{% endif %}

```

# Answer
> 6 votes
call the getType method of the node object, like: `node.getType() == 'article'`

---
Tags: theming, 8
---


# Question
Title: Add dividers for each year on View table
I have a view listing a custom content type by year and quarter (Spring, Summer, Fall, Winter). It's currently listed in a table. I'd like there to be dividers for each year within the table. Simply a row that names the year before going on to the content that fits within that year. Below is an image of the effect I want to achieve.

I've considered creating a twig template for the view, but I'm not sure how I would be able to check whether an item is the first or last item in a year. I've also considered adding a 'custom text' field but again I'm not sure how I'd make a conditional for that, and I'm not sure how I would be able to turn that into a unique row.

Is there a way to create row dividers in a table view once the year changes, or with any field for that matter?

# Answer
Matt, I have done this and giving you exact idea. I did a task for display node under specific location as you need year.

1. I created taxonomy for location like  So if you want to create taxonomy for years and add terms it's upto you.
2. Attach the taxonomy to node as term reference field type.
3. Create a view of that content and add required fields.
4. Check view format setting set the field for grouping .
> 1 votes

# Answer
You can use "Grouping field" option inside view formate settings for year field. Here is example of grouping

# 1. https://stackoverflow.com/questions/13828952/drupal-7-views-list-group-by-field?answertab=active#tab-top

# 2. https://www.drupal.org/node/1578512
> 1 votes

# Answer
the easiest way to achieve this is by using the Settings option from `Format: Table | Settings`.

Please click on the `Settings` and that will allow you to select the field on which you can group the results. But prior to that, you will need to add the respective date field in the fields section of the view.

Add the `Date` field respective to which you need to group the content. Set the `format` of the date to be `year` only, and also select exclude from display. Further, if you need to display the date in the rows also, select the same field again and set the desired format of the date.

Now, all the fields will be available for grouping in the `Settings` tab. You can now identify and select the `date` field which was formatted as `year` only to get the desired result.

If required, please check a simple reference blog or this answer.
> 1 votes

---
Tags: views, 8
---


# Question
Title: Delete entity revision does not delete from field_data table
I created a custom entity, I can edit, save, delete, create revisions and revert. I adapted the code from node module to achieve all this and everything works just fine except the revision deletion.

This code will delete entries from `my_entity_revision` table but not from `my_entity_revision_field_data` table:

```
$this->myEntityStorage->deleteRevision($revision_id)

```

Any ideas why this might happen? Thanks.

Here is my entity annotation:

```
@ContentEntityType(
   id = "my_entity",
   label = @Translation("My entity"),
   bundle_label = @Translation("My Entity type"),
   handlers = {
     "list_builder" = "Drupal\my_entity\Controller\MyEntityListBuilder",
     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
     "access" = "Drupal\website_settings\MyEntityAccessControlHandler",
     "form" = {
       "default" = "Drupal\my_entity\Form\MyEntityForm",
       "add" = "Drupal\my_entity\Form\MyEntityForm",
       "edit" = "Drupal\my_entity\Form\MyEntityForm",
       "delete" = "Drupal\my_entity\Form\MyEntityDeleteForm"
     },
     "views_data" = "Drupal\my_entity\MyEntityViewsData",
   },
   base_table = "my_entity",
   data_table = "my_entity_field_data",
   revision_table = "my_entity_revision",
   revision_data_table = "my_entity_revision_field_data",
   translatable = TRUE,
   entity_revision_parent_id_field = "parent_id",
   entity_keys = {
     "id" = "id",
     "uuid" = "uuid",
     "bundle" = "type",
     "langcode" = "langcode",
     "revision" = "revision_id"
   },
   bundle_entity_type = "my_entity_type",
   field_ui_base_route = "entity.my_entity_type.edit_form",
   links = {
     "canonical" = "/admin/structure/my_entity/{my_entity}",
     "edit-form" = "/admin/structure/my_entity/{my_entity}/edit",
     "delete-form" = "/admin/structure/my_entity/{my_entity}/delete",
     "revision" = "/admin/structure/my_entity/{my_entity}/revision/{my_entity_revision}/view",
     "version-history" = "/admin/structure/my_entity/{my_entity}/revisions"
   }
)

```

And my baseFieldDefinition:

```
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the Website settings entity.'))
      ->setReadOnly(TRUE);

    // Standard field, unique outside of the scope of the current project.
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The UUID of the Website settings entity.'))
      ->setReadOnly(TRUE);

    $fields['revision_id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Revision ID'))
      ->setDescription(t('The paragraphs entity revision ID.'))
      ->setReadOnly(TRUE)
      ->setSetting('unsigned', TRUE);

    $fields['type'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Type'))
      ->setDescription(t('The website settings bundle type.'))
      ->setSetting('target_type', 'website_settings_type')
      ->setReadOnly(TRUE);

    $fields['langcode'] = BaseFieldDefinition::create('language')
      ->setLabel(t('Language code'))
      ->setDescription(t('The paragraphs entity language code.'))
      ->setRevisionable(TRUE);

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of the website settings author.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setDefaultValueCallback('Drupal\website_settings\Entity\WebsiteSettings::getCurrentUserId')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    // We set display options for the view as well as the form.
    // Users with correct privileges can change the view and edit configuration.
    $fields['title'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Title'))
      ->setSettings(array(
        'default_value' => '',
        'max_length' => 255,
        'text_processing' => 0,
      ))
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string',
        'weight' => -6,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'string_textfield',
        'weight' => -6,
      ))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Published'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDefaultValue(TRUE)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setDescription(t('The time that the website settings was created.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', array(
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed on'))
      ->setDescription(t('The time that the website settings was last updated.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', array(
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'hidden',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    $fields['revision_uid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Revision user ID'))
      ->setDescription(t('The user ID of the author of the current revision.'))
      ->setSetting('target_type', 'user')
      ->setQueryable(FALSE)
      ->setRevisionable(TRUE);

    $fields['parent_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Parent ID'))
      ->setDescription(t('The ID of the parent entity of which this entity is referenced.'))
      ->setSetting('target_type', 'my_entity')
      ->setSetting('handler', 'default')
      ->setRevisionable(TRUE);

    $fields['langcode'] = BaseFieldDefinition::create('language')
      ->setLabel(t('Language code'))
      ->setDescription(t('The language code of ContentEntityExample entity.'));

    return $fields;
  }

```

# Answer
> 0 votes
Is your entity extending the RevisionableInterface and RevisionLogInterface or the ContentEntityInterface ?

Otherwise it could be a drupal core issue ..

Other having the same (or is this you ?): https://www.drupal.org/node/2818053

Known issue (only with media): https://www.drupal.org/node/1239558

---
Tags: 8, entities
---


# Question
Title: Is it possible to change the fields' names of the JSON generated by Services module?
I have a mobile app, which calls a legacy system's HTTP REST interface. Now I replaced the legacy system with Drupal and Services module. I forgot setting field machine name to match mobile app client, however, there is no chance to modify the mobile app. So, as I asked in the title: is there a way to change the fields' names of the JSON generated by Services module?

# Answer
You can use `hook_services_request_postprocess_alter()`: http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x

For example, say you wanted to replace the node `title` property with `nodeTitle` when a node is being retrieved, you can do so like this:

```
/**
 * Implements hook_services_request_postprocess_alter().
 */
function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller['callback'] == '_node_resource_retrieve') {
    $result->nodeTitle = $result->title;
    unset($result->title);
  }
}

```
> 1 votes

---
Tags: services
---


# Question
Title: How to configure multisites for the console?
Most of console commands are not listed when using

```
drupal list

```

Drupal Console version 0.11.3

It issues a warning like so:

```
[WARNING] In order to list all of the available commands you should install
       drupal first.

```

Drupal is installed , as multisites.

```
   drupal multi:debug

```

Tells me this error:

```
 [ERROR] There aren't multisites configured

```

How can I configure multisites for the console ?

```
     https://hechoendrupal.gitbooks.io/drupal-console/content/hu/using/how-to-use-drupal-console-in-a-multisite-installation.html

```

EDIT:

a mapping must be done in sites/sites.php for

drupal multisite:debug

to display the list

sites.php

```
 /**
 * Multi-site directory aliasing:
 *
 * Edit the lines below to define directory aliases. Remove the leading hash
 * signs to enable.
 */
$sites = array (
    'my_domain_name.fr'=>'my_folder_name_in_sites?'
);

```

What is the exact format of this array values i dont know

i dont have drupal multi:debug error nomore mais drupal list is still restricted

# Answer
a mapping must be done in sites/sites.php for

```
   drupal multisite:debug

```

to display the list

sites.php

```
 /**
 * Multi-site directory aliasing:
 *
 * Edit the lines below to define directory aliases. Remove the leading hash
 * signs to enable.
 */
$sites = array (
    'my_domain_name.fr'=>'my_folder_name_in_sites?'
);

```

i am not sure for it to be correctly configured

```
my_folder_name_in_sites?

```

must be

```
my_folder_name

```

or

```
sites/my_folder_name

```
> 2 votes

---
Tags: console
---


# Question
Title: Why does Drupal (8) not discover my custom taxonomy term template?
Following the instructions on how to create a custom template for taxonomy terms I managed to add a template suggestion for a particular view mode of the taxonomy term entity by using hook\_theme\_suggestions\_HOOK\_alter:

```
function linkup_theme_suggestions_taxonomy_term_alter(&$suggestions, $vars, $hook) {
  if($vars['elements']['#view_mode'] == 'teaser') {
    $suggestions[] = 'taxonomy-term--teaser';
  }
}

```

(*linkup* is the name of my custom theme)

This seems to work as I can see the template suggestions when I print the twig debug information:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'taxonomy_term' -->
<!-- FILE NAME SUGGESTIONS:
   * taxonomy-term--teaser.html.twig
   * taxonomy-term--15.html.twig
   * taxonomy-term--group.html.twig
   x taxonomy-term.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/content/taxonomy-term.html.twig' -->

```

But for some reason Drupal does not pick up the template which is located in themes/linkup/templates/taxonomy-term--teaser.html.twig

I think the naming is correct (unlike Drupal 7 in 8 you dont need to fiddle with underscores to match dashes in file names)

If I add a template called taxonomy-term.html.twig to the theme then that is discovered.

Am I missing some of Drupal 8's logic to discover the custom template?

# Answer
You need to use underscores in your suggestion (but continue to use dashes in your template file name):

```
/**
 * Implements hook_theme_suggestions_HOOK_alter() for taxonomies.
 *
 * {@inheritdoc}
 */
function HOOK_theme_suggestions_taxonomy_term_alter(&$suggestions, $vars, $hook) {
  if($vars['elements']['#view_mode'] == 'teaser') {
    $suggestions[] = 'taxonomy_term__teaser'; // note underscores
  }
}

```

you could also leave out your condition and do:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter() for taxonomies.
 *
 * {@inheritdoc}
 */
function HOOK_theme_suggestions_taxonomy_term_alter(&$suggestions, $vars, $hook) {
  $suggestions[] = 'taxonomy_term__' . $vars['elements']['#view_mode'];
}

```
> 7 votes

---
Tags: theming, 8
---


# Question
Title: How do I know if I installed latest version?
I am trying to create a cron script which uses Drush, and that does the following (using pseudo-code).

```
if([My Drupal core version] < [The last core version]) {
    [Backup DB]
    [Put the site into maintenance mode]
    [Upgrade core]
    [Remove the site from maintenance mode]
}

```

I don't know, how to implement `[My Drupal core version] < [The last core version]`.

How do I check if the site is using the latest version of Drupal?

# Answer
> 4 votes
You could try `drush pm-updatestatus drupal` and see if you get any results.

# Answer
> 1 votes
See update\_get\_available function. It returns available list updates, including core.

---
Tags: drush, upgrading
---


# Question
Title: Accessing Content: Path field within views_view_unformatted TWIG template
I have a view that has the fields: Content: ID, Content: Title and Content: Path.

In my `views-view-module.html.twig` file I can access the fields via the following:

```
{{ item['#row']._entity.id }}

{{ item['#row']._entity.title[0].value }}

```

But I cannot seem to retrieve the path field using:

```
{{ item['#row']._entity.path[0].value }}

```

Do I do this the same way or am I missing a trick? I've tried to use dump/kint but I keep getting the WSOD.

Can anyone offer me a solution?

Thanks in advance

# Answer
> 0 votes
You access the fields from the entity. That are not the fields from the view. And in the entity there is no field `path`.

Look for the path in the row content. This is a good advice not only for the path, but for all fields, because in the entity the field values are the raw data from the database and not formatted for output. That doesn't make a difference for the id and the title though, because they are plain alphanumeric, but you really should do it for more complex fields. And for computed fields like path you have no other choice, if you don't want to compute the field again yourself.

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


# Question
Title: Add different paragraphs block on translated nodes
Is it possible to add additional paragraph blocks on an translated node?

If yes; How? I've tried messing around with configuration; but cannot get it to work as expected.

If not; How do we go around this behaviour?

# Answer
That is an open issue. At the moment you can only translate the fields inside of paragraphs, not the outside structure of the paragraphs.

See this issue:

\[META\] Support translatable paragraph entity reference revision field
> 1 votes

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


# Question
Title: How do I open a custom module ajax form in colorbox popup?
How do I open a custom module AJAX form in colorbox popup using button click?

# Answer
> 1 votes
If you output your form hidden in the html, you can pop it up with colorbox\_inline.

If your form lives in a menu callback and has a path, you can put a rendered link to your page everywhere and it will open modal with colorbox\_load \- see also ng\_lightbox, if you put your path in it's config.

---
Tags: 8, javascript
---


# Question
Title: How to translate countries in multilingual site?
I have used `country_get_list()` function to render all pre-installed countries in my select list.

When my site is in English, it is showing all country names in English, which is fine. But for French site, **I want all country names should get translated in french**.

For example: in English a country name is `India` but in the French site, it should display like `Inde`.

Is this possible to achieve?

# Answer
* Make sure you have the translated country strings in your database, ready to be used.
* country\_get\_list() calls \_country\_get\_predefined\_list(), and inside this function country names are passed through `t()`. So, if you have country strings translated in your database, translation should work.
> 2 votes

# Answer
It should be fixed by downloading the Drupal Core translation to the language you need from https://localize.drupal.org/download.

Once you have that file downloaded just go to admin/config/regional/translate/import and import the file there in the needed language. That's all.

This will not only translate the country names but all the Drupal Core interface.

You can also use the Localization update module to download translations for enabled languages for Drupal Core and contributed modules.
> 1 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: What is the equivalent of hook_user_view()?
I am basically trying to do what described in How can I let anonymous users view user profiles by role? in Drupal 8. User profiles should only be visible to anonymous users only if those profiles are for users having a certain role; all the other user profiles should not be accessible to anonymous.

The answer there suggests using `hook_user_view()`, but it appears that hook has been removed in Drupal 8. Is there a different/correct way to do this now?

# Answer
> 2 votes
4k4's link is a really good resource for access checking for custom routes.

Another option would be to implement hook\_entity\_access in your own custom module. I just tested this and it does what you originally asked for:

```
/**
 * Implements hook_entity_access().
 */
function  MYMODULE_entity_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account) {
  if ($entity->getEntityType()->id() == 'user' && !$account->id()) {
    if (!$entity->hasRole('administrator')) {
      return \Drupal\Core\Access\AccessResult::forbidden();
    }
  }
}

```

Obviously, change `administrator` with the machine name of the role you are looking to grant access too. You do need to give anonymous users the permsission to view user information also. This just limits the entities (users) they are allowed to view.

# Answer
> 6 votes
`hook_user_view()` is still available in drupal 8, but the hook naming schema has changed, because the hook can now be used for all entity types:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!entity.api.php/function/hook\_ENTITY\_TYPE\_view/8.2.x

A more D8 way to do this could be a custom access check on the route:

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

# Answer
> 0 votes
Anonymous is a default role in Drupal 8. Still if you want to create custom roles and then want all users belongs to that group, view users profile info, following steps can be followed:

1. Login to Admin panel
2. Click on People
3. Click on Roles and create Custom Role
4. Click on Permissions
5. Search for **"View user information"**
6. Assign role for this entry to your custom role.

This link can be helpful

---
Tags: 8, users
---


title: How to implement a new drush topic?

text:
# Question
Title: How to implement a new drush topic?
I just read the Drush Topic - A Wealth of Information article about the topic section in drush commands and I have added this topic to my drush commands:

```
  $items['docs-onlyone'] = array(
    'description' => 'Info about Only One.',
    'hidden' => TRUE,
    'topic' => TRUE,
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'callback' => 'drush_print_file',
    'callback arguments' => array(dirname(__FILE__) . '/README.txt'),
  );

```

The problem is that the only way to see the new topic in the topic list once I use the `drush topic` command is if I place my onlyone.drush.inc file inside the .drush folder.

Is this normal? I can't see the topic if I have my onlyone.drush.inc file inside my module folder.

# Answer
Make sure that you have selected the Drupal site that your module is in (e.g. with an @alias, via --root and --uri, or cd /path/to/drupal/sites/default), and also ensure that the module is enabled. Otherwise, Drush will not find and load the file.
> 2 votes

---
Tags: drush
---


# Question
Title: Deploy to production with git using Acquia like localserver
I'm using Acquia to export my local proyect to production proyect but when I did git push just the code was saved, the changes that I did in UI was not saved for example I created a user in local UI but it did not reflect in production UI, do I have to use drush to do that?

# Answer
You're missing the database. git only handles files.

So export your local database, and import it in production. For that you could use drush sql-sync, but you need to set it up properly.

You could also export the database to an .sql file via phpMyAdmin or your preferred db-tool. and then in aquia devcloud, you import that .sql file.
> 0 votes

---
Tags: drush, version-control, acquia-dev-desktop
---


# Question
Title: Create token with translatable variable in pathauto
I would like to be able to create my own tokens for pathauto. In D7 I was able to create with the variable module some variables to represent a portion of an url. These variables where available as tokens and I had a different per content types and where translatable.

For example I would like to be able to do that:

`[content-type-monthly-theme-base-url]/[node:title]`

I can do that:

`featured/[node:title]` but the word 'featured' is not translatable

Another solution would be able to translate patterns. ATM only the pattern title is translatable! Not usefull...

As a last resort I can add a field `base_url` in my content type Monthly theme and use it as a token. But this means each time someone would create a node of this content type he or she would have to make sure the base\_url field is in the right translation. This should really be configurable else where.

# Answer
There are issues open about making patterns translatable.

And patterns actually can be per-language, so you can have multiple patterns, one for each language.

You could also implement the token yourself but be aware that for example during bulk generation, pathauto might create aliases for different languages in the same request, so you can't rely on the current language.
> 0 votes

---
Tags: 8, path-aliases, tokens
---


# Question
Title: Access EntityEmbedFilter process function in a preprocessor
I'm getting the value of a wysiwyg field in a preprocessor then passing it to Twig in a #markup render array. Everything works as expected with the exception of embedded images. I've modified the list of XSS allowed tags to allow the drupal-entity tag. However, it seems that this is being passed to Twig after the EntityEmbedFilter has opened and closed.

I'd like to use EntityEmbedFilter process function to process the value of my field prior to passing it to Twig. However, when trying to instantiate an instance of EntityEmbedFilter with the new keyword, I get an an error because the constructor requires a configuration array.

# Answer
> 2 votes
Considering letting Drupal do the work for you. Instead of calling things yourself, just let Drupal render it for you using a specific text format, which is configured to use entity embed.

See how check\_markup() works, you could call that, but since you seem to be in a context where you want a render array anyway, just do what it does and use #type processed\_text with #type and #format.

If that is for some reason not possible, then you need to mark the resulting object as a safe string by wrapping it with an object that implements MarkupInterface, for example with Markup::create() although that is marked as internal.

---
Tags: 8, entities
---


# Question
Title: How to set DB log only to log CRON TYPE and SEVERITY NOTICE message?
I want to log only CRON TYPE and SEVERITY NOTICE message in db log , want to exclude all other types like notice, alert, critical, info, debug etc., Is there any way to prevent this, or should i write any custom coding for this? if custom coding for where i can prevent logging other types in DBLOG.

# Answer
> 1 votes
The Drupal error handler `_drupal_error_handler_real()` utilized PHP's `error_reporting()` to determine what gets logged to the DB. By setting the PHP `error_reporting` to `E_ERROR` it will only PHP errors.

This PHP setting can be set in many places: the system **php.ini**, a **php.ini**/**.user.ini** instance in webroot, **.htaccess** in Apache. The Drupal centric way to do this, is to use `ini_set()` function in **settings.php**:

```
ini_set('error_reporting', E_ERROR);

```

See PHPs error constant page for other values to set `error_reporting`.

---
Tags: 8, log-messages
---


title: Multi stage search views

text:
# Question
Title: Multi stage search views
I'm building a website that needs the following functionality -

So two different content types - work type profile and job type.

So work type profile contains a field 'Skillset A' and a 'Skillset B' so I can create this content type and select the different skills the type has.

Job type has lots of different detail about the job, like salary etc.

I want a user to be able to select their work type as stage one, and then select the salary level they require for the the second stage filter.

Then I want a list of jobs to appear that they can do based on the skills within their salary range (so the jobs that match their skillset profile)

And I want the jobs to then be further filterable by the skillset. So they can see all the jobs that match the skillset.

How would I configure something like this with views?

Thanks for your help!

# Answer
> 0 votes
I would see how these projects approached this popular scenario & go from there as opposed to starting from scratch:

https://www.drupal.org/project/recruiter https://www.drupal.org/project/drop\_jobs

\[edit\]...So I decided to try both those out as I was thinking about simple data modeling and how to communicate it best. There's a demo linked on the recruiter distro but decided to use https://simplytest.me/ which is great in case you haven't heard of it.

The drop\_jobs broke but the recruiter distro worked and it provides facets which is probably the way you should go too so people can just refine their search to their needs - the trouble with trying to do it in just views alone is you start with a big list of data and provide options from the boundaries you know, e.g. salary bracket, but if there's nothing in the one they choose then you'll end up with no results.

The benefit of using facets is by default it will only display the available facets, and you can have things like facet counts. You can display all the facets so you get things like $10k-$20k(0) if there aren't any, but at least the user doesn't have a fruitless search.

See http://dgo.to/facets

---
Tags: views
---


# Question
Title: When should I use behaviors? Can I attach them to any DOM node?
I was using Drupal behaviors during a commerce project that ran some simple code after a select list changed product value. In my head though I was thinking how is this any different than a 'change' event.

I went through Google to find out a bit more, but could only come across some things that provided very little insight, including the documentation itself.

So I am curious as to why and when to use Drupal behaviors, and if I could get a practical example. And does it only work on Drupal rendered nodes that have asynchronous functionality attached to them? Or can I attach it to anything like a regular div element? If so what would that look like?

I also noticed in the Drupal behaviors object tree, you can see all the behaviors, and are able to run them if you get all the way down to the attach object ( i.e. Drupal.behaviors.myBehavior.attach() ). Can you manipulate those?

Thanks for the insight in advance.

# Answer
The `attach` function of all registered behaviors (all properties of the `Drupal.behaviors` object) will be invoked when behavior should be added to elements, either when the DOM is ready (ie. page load) and when elements are added to the DOM. The `detach` function will be called when behaviors should be detached from elements: just before elements are removed from the DOM, moved in the DOM or a form is submitted. The `context` parameter will always be a parent of the added/removed/moved/submitted elements, the single added/removed/moved/submitted element itself or the whole document element. The `settings` parameters will be the settings for the context, usually the `Drupal.settings` object as set by calls to `drupal_add_js()` from PHP. For `detach`, the `trigger` parameter will contains the kind of event that triggered the call: '`unload`' (elements removed), '`move`' (elements moved) or '`serialize`' (form is being submitted).

The `attach` (and `detach`) functions of a behavior can be used multiple time over the same portion of the DOM tree. So the same element could be processed multiple time by the same code. It is up to the code itself to avoid processing (ie. binding event handlers, altering CSS styles, etc.) multiple times for the same elements. The easiest solution for this is to use the jQuery Once plugin (which is provided by Drupal 7) like this:

```
$(selector).once('behavior-name').doSomething();
$(selector).once('behavior-name', function(){ /*do something*/ });

```

Since a behavior is being attached/detached to/from a context, the context object can be used to restrict your jQuery queries to only the affected element or DOM subtree, like this:

```
$(selector, context).doSomething();

```

Putting all this together means the base pattern to process and add behaviors to elements on the page should looks like this:

```
(function($) {
  Drupal.behaviors.doSomething = {
    attach: function(context, settings) {
      $('div.something', context).once('do-something').doSomething({
        param1: settings.something.param,
        param2: 'something else'
      });
    }
  }
})(jQuery);

```

You can manipulate thhe `Drupal.behaviors` object tree, but be careful to avoid breaking other behaviors. I common usage is to use your behavior object (ie. `Drupal.behaviors.myBehavior`) to store information extracted from the elements during `attach` and consumed by event handlers.

If you write code that dynamically add or remove elements to the DOM, you should invoke `Drupal.attachBehaviors` or `Drupal.detachBehavior` on the (closet) parent element of the added/removed elements.
> 3 votes

---
Tags: 7, javascript
---


# Question
Title: Local install of live site looks different
Localhost site looks different than live site.

Drupal 7.37 \> 7.5 (Commons), viewed in Chrome on Mac OS X.

**Prep Steps:**

1. installed a clone of the website from an outdated repository on my local machine
2. reconciled the code differences between the live site and the slightly outdated repository site
3. imported a current copy of the database from the live site.
4. featurized database configurations
5. updated most of the modules as well as Drupal core.
6. checked default theme and settings to make sure they are the same between sites

**After noticing the problem:**

* downloaded theme files into respective locations
* installed stage\_file\_proxy on local dev to load any files I ignored

**Thematic Differences**

From the moment I imported the database, until now, after all updates have been performed, there is a thematic difference between the live site and my local version. (The difference is slight, but annoying.)

* live site is centered and contained, local stretches all the way across in some places but stays left aligned in others
* some fonts are larger on local site
* navigation menu splits itself to a new line early
* live site has blocks on the right, local has one column with blocked content at bottom

**Summary of Question**

Is this a commonly known problem when certain steps are forgotten and is there another place to address configuration besides in the codebase and the database or is this probably not a theming issue but something else?

Update: I pushed the site up to my remote dev server anyways, to see if the problem was environmental or database and codebase. The remote dev looks perfect. There is definitely an issue with my local dev environment causing this somehow.

# Answer
> 1 votes
Sounds like some CSS files are not loaded on the local site. Or some additional or other CSS files are loaded on the local site.

### Clear caches

First thing to start troubleshooting the local site is to clear the caches. Not only CSS/JS caches but all caches.

If the site has the Advagg caching module installed, then sometimes it is not enough to clear its cache by clicking the Administration menu link. Advagg cache might also need to be cleared by clicking the `Flush AdvAgg Cache` button on this path: `/admin/config/development/performance/advagg/operations`

If the above does not help then on the same Advagg page there are more buttons to click, hidden behind the headings containing 'Clear' and 'Delete'.

### Look at CSS with Firebug

Firebug is an addon for Firefox. Instead of this you can also use the browsers built in inspector by pressing F12(maybe another key on Mac).

See what CSS is different and if the CSS is taken from different files on live site vs local site.

### Panels Page layout

Having blocks on the right vs bottom could also be affected by Panels Page layout. Check for that if the blocks are still wrong after you got all other thematic right by getting all CSS right.

---
Tags: 7, migrations
---


# Question
Title: Loading dependencies from the vendor directory in a module using composer
I am using composer for managing dependencies in my drupal module. I specified my dependency in the composer.json file placed in my module's root directory. After running the `composer install` comand it installs all the dependencies correctly; however, the autoloading does not seem to work.

I have checked several threads here that deal with the problem and found that most of them suggest using the **composer manager** module that's available even though on the module's page on drupal.org it says that it's deprecated due to Drupal's improved use of composer since version 8.1

Here's my composer.json file in my module's root diretory:

```
{
"name": "activit/facebook_ratings",
"description": "Display a feed of your Facebook fanpage's ratings on your website.",
"type": "drupal-module",
"require": {
    "facebook/graph-sdk": "^5.4"
},
"license": "MIT",
"authors": [
    {
        "name": "Robert Balasko",
        "email": "rbalasko@activit.sk"
    }
]
}

```

and a factory class in the root of **src** directory that tries to load a class from the graph-sdk.

```
<?php namespace Drupal\facebook_ratings;

use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Facebook\Facebook;

class FacebookConnectorFactory {

  private $logger_factory;

  public function __construct(LoggerChannelFactoryInterface $logger_factory) {
    $this->logger_factory = $logger_factory;
  }

  public function getFacebookService($app_id, $app_secret) {
    if (!$app_id || !$app_secret) {
      $this->logger_factory
        ->get('facebook_ratings')
        ->error('Undefined App ID or App secret');

      return FALSE;
    }

    return new Facebook([
      'app_id' => $app_id,
      'app_secret' => $app_secret,
      'default_graph_version' => 'v2.6',
    ]);
  }

}

```

The result is a `class not found` error when I run my code. Shouldn't the dependency be autoloaded or am I doing anything wrong?

Thanks a lot.

# Answer
> 7 votes
Composer Manager is just a small wrapper around the Merge Plugin which we have in core nowadays.

Register your module in the root `composer.json` of your project, look for extra \> merge-plugin \> include. It should look like this:

```
"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php."
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/facebook_ratings/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }
}

```

`modules/facebook_ratings/composer.json` is the path to your `composer.json`. It depends on where you have your module.

Run `composer install` afterwards.

---
Tags: 8, composer
---


# Question
Title: Disable taxonomy terms in certain contexts or split into different vocabularies?
I have created a taxonomy of regions, with the intent of multiple uses:

1. Users select their region in their profile
2. Events include a region field.

This should make it rather easy to show users events in their region.

Each of these use cases requires one or two extra terms:

* Users might be from "outside New Zealand".
* Events might be "Nationwide", "Worldwide" or indeed "online".

But we don't want events outside NZ submitted, and the latter three terms are not appropriate for users to choose as their location. So I want to disable them from the listed options in each case.

I thought there might be a CSS solution as there are ample distinctive selectors available in the parent elements, but Drupal does not assign any classes to option elements - they only have a value, and the numeric id of the taxonomy term at that.

Is there a way to do this using Rules or Context?

# Answer
# Alternative 1

Create two different taxonomy vocabularies:

* Events
* Users

since the use cases for each are different.

To create another taxonomy vocabulary easy and fast, you could export your existing terms and then import them into a new vocabulary. This could be done with some taxonomy bulk import/export module, maybe with https://www.drupal.org/project/taxonomy\_csv or with https://www.drupal.org/project/taxonomy\_manager

# Alternative 2

Added to this answer after OP's first comment.

1. Keep the Events and Users together in one vocabulary, *EventsUsers*.
2. Create another vocabulary, *EventUserType*. Add two terms: *Events* and *Users*.
3. Add a *Term reference* field with *Check boxes/radio buttons* to the *EventsUsers*, save. In the next configuration pages choose vocabulary *EventUserType*. Also change the *Number of values* from *1* to *Unlimited*.

Now all the terms in the main vocabulary can be tagged as *Event*, *User* or both.

---

The filtering could be done using the Views module, but I guess that would be a separate question here on Drupal Answers.
> 1 votes

---
Tags: taxonomy-terms, rules
---


# Question
Title: defining relationships between terms in a taxonomy
Is there a module which allows you to define a relationship between some terms in a taxonomy? Specifically, being adjacent? The taxonomy is flat. So that Auckland has Northland and Waikato as neighbours (the use case would be to build a view of events in nearby regions)

My searching can't have used the right names for this - I'm not finding anything :-)

# Answer
> 0 votes
The relationship functionality exists in Drupal core - no need for a contributed module.

Go to `/admin/structure/taxonomy/YOUR_VOCABULARY/fields` and add a new field of type **Term reference**, click *Save*.

On the next screen

1. change **Number of values** from *1* to **Unlimited**
2. choose the same vocabulary you added the field to in the **Vocabulary** dropdown.

Then edit each term and add the neighbouring regions to it.

---
Tags: taxonomy-terms
---


# Question
Title: Creating Multifield Search with Apache Solr Search
I'm using Apache Solr Search on Pantheon and trying to figure out how I can create an "advanced" multifield search.

For example if I have a content type called Location, with "city" and "state" fields, how can I make those fields part of the search form, similar to an exposed filter in Views?

I successfully installed and setup Facets using Facets API module, but those just add clickable links. I'm looking for the user to be able to search by multiple fields.

I also tried the Apache Solr Views Integration module, but that only allows text fields as exposed filters.

If anyone has suggestions, documentation, or a tutorial on how to do this that'd be great. Obviously I could do it with Views but I do not want these searches hitting the Drupal database.

# Answer
> 1 votes
You can use Custom Search module. Create a search block with your custom filters (taxonomy list). And enable "Allow user input using the URL" in your Apache-solr settings page (ADVANCED SEARCH PAGE OPTIONS section).

---
Tags: search
---


title: How to create dummy fields

text:
# Question
Title: How to create dummy fields
I use Drupal7. I want to create some dozens of dummy fields in my test node quickly. But, it will take long if I do at "manage fields page"(admin/structure/types/manage/CONTENT\_TYPE).

Unfortunately, I couldn't find any modules to do it(Devel Generat can create contents, but not fields). Any suggestions to do it? Thank you.

# Answer
You could use this module: https://www.drupal.org/project/bundle\_copy

1. Create a field
2. Export the bundle/content type
3. Copy the field in the exported text, paste several times, changing stuff for each field that you want to change for each new field
4. Import the same bundle/content type
> 2 votes

---
Tags: 7
---


# Question
Title: How can get path of image (src) in twig template of a module?
How can I get access to image path (source/url) in twig template of a module?
I try to render an image that's located in my module folder in module template, this image is a static image that's not assigned to a field.
I try several methods to achieve this demands for eg:

```
<img src="{{ directory }}/image/icons/my-image.svg" />

```

and below method:

**MyModule.module**

```
function MyModule_preprocess(&$variables, $hook) {
    $variables['base_path'] = base_path();
}

```

and then in template:

```
<img src="{{ base_path ~ directory }}image/icons/my-image.svg" />

```

And i try solution that's written in this article too: Using images in custom module
But both of them refer to my theme directory instead of module directory and seems none of them work in module template.
Thanks for any solution.

# Answer
> 6 votes
You need to use `file_create_url` much like Drupal 7 to transform a file path to file url. To get the path to the module, you should use `drupal_get_path`, combined it could look like this:

```
function my_module_preprocess(&$variables, $hook) {
  $variables['img_path'] = file_create_url(drupal_get_path('module', 'my_module') . '/image/icons/my-image.svg');
}

```

---
Tags: 8, media
---


# Question
Title: How can I suggest a template file specific for a content type?
In Drupal 8, is there a way to get html.html.twig to only show on a content type like html--blog.html.twig? The suggestions in the debug don't seem to give me that option.

```
<!-- FILE NAME SUGGESTIONS:
   * html--node--1222.html.twig
   * html--node--%.html.twig
   * html--node.html.twig
   x html.html.twig
-->

```

# Answer
> 1 votes
You can do this with a theme suggestions alter hook:

```
/**
 * Implements THEME_theme_suggestions_html_alter().
 */
function MYTHEME_theme_suggestions_html_alter(&$suggestions, $vars, $hook) {

  // Check to see if you are on a node.
  if ($node = \Drupal::routeMatch()->getParameter('node')) {

    // Get the node type.
    $type = $node->getType();

    // Create the theme hook suggestions.
    $suggestions[] = 'html__' . $type;
    $suggestions[] = 'html__node_' . $type;
  }
}

```

Of course, change "MYTHEME to your theme name. I tested this on a blog content type for example and the new template suggestions printed out after creating this hook and clearing cache.

```
<!-- THEME HOOK: 'html' -->
<!-- FILE NAME SUGGESTIONS:
   * html--node-blog.html.twig
   * html--blog.html.twig
   * html--node--15.html.twig
   * html--node--%.html.twig
   * html--node.html.twig
   x html.html.twig
-->

```

The new theme hooks here are:

```
  * html--node-blog.html.twig
  * html--blog.html.twig

```

The content type name will change accordingly in the naming suggestion.

To test, I copied `html.html.twig` and named as `html--node-blog.html.twig` and it worked great.

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


# Question
Title: How to make sticky articles show up first in a list of articles?
I have a view showing a list of articles, sorted by date. I tried enabling the *sticky article* option in the publishing options. This made an article I had jump to the top of the list, but then a new article I added pushed the sticky article to second place.

I want a sticky article (pinned) to be first in the list even if I add new articles.

How can I achieve this?

# Answer
> 0 votes
Enable of the "sticky" option within publishing options (for 1 or more nodes) is only part of the solution: within the "Sort criteria" of your view, you also have to add "***Node: Sticky***" as your primary sort criterium (using the Views UI).

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

---
Tags: views, 6
---


title: BrowserTest gives wrong connection

text:
# Question
Title: BrowserTest gives wrong connection
I am running a test that extends a BrowserTestBase and indicated a custom module as a dependency. The module has a `mymodule_module_preinstal()` that is supposed to perform a DB query using `Drupal::database()`.

After wasting some time on figuring out why it does not work I realized that the query is run against the main databse of the installation, not that which I had set up in phpunit.xml.

That's really confusing - why is it working like that and why on earth would I want to work with the main database while running a test which is supposed to be run in an isolated database?

And, most importantly, how do I run the query against the test database?

Excerpt from documentation:

> It's terribly important to realize that each test runs in a completely new Drupal instance, which is created from scratch for the test. In other words, none of your configuration and none of your users exists!

Here's code of my test:

```
class FormTest extends BrowserTestBase
{
    public static $modules = ['mymodule', 'mymodule2'];

    public function testFormPage()
    {
        $response = $this->drupalGet('/mymodule/register');
    }
}

```

I've also copied phpunit.xml.dist to phpunit.xml and set up this line:

```
<env name="SIMPLETEST_DB" value="mysql://mydb_tests:password@localhost/mydb_tests"/>

```

I run my test like this:

```
cd core
phpunit ../modules/mymodule/tests/src/MyTest.php

```

I have installed the version of phpunit from core/composer.json globally.

The preinstall hook looks like this:

```
/**
 * Module preinstall hook
 * @param $module_name
 */
function mymodule_module_preinstall($module_name)
{
    var_dump($module_name);

    print_r(Drupal::database()->query("SHOW TABLES")->fetchAll());
    exit();
}

```

# Answer
> 1 votes
Show tables doesn't work like that. I doesn't know anything about prefixes, it lists all tables in the database.

The schema API has an API method to list tables, which is DB agnostic and respects the prefix.

---
Tags: 8, database, testing
---


# Question
Title: Vocabulary set by another hierarchy and combinations
I have to create a new taxonomy term that has no name field.

I created one master vocabulary. Then I created another vocabulary and term having only entity reference field. Default description field was deleted. I would like to change hierarchy and combination of any terms from reference master vocabulary.

Normally, term has a mandatory name field and description field. I'd like to change the name field type in the entity reference, but it is impossible. After adding a different entity reference field, it is an error to disable the existing name field. Perhaps, the reason for the name field is probably because it is mandatory.

Name field of term, rather than being arbitrarily input, want to specification referenced by the fields of the other taxonomy terms. Description field is same case. All field are refarence field from master vocabrary or others. In other words, we want to make the vocabulary set by another hierarchy and combinations.

Do you have any idea?

# Answer
It's a required part of the entity. The **name** field for a Drupal 7 taxonomy term is defined in the taxonomy's module:

* `hook_entity_info()` invocation to designate **name** as the label (a human readable field that's required for displaying entity).
* `hook_field_extra_fields()` invocation to define the name field within the taxonomy term for the admin UI.

The Drupal API does expose `hook_entity_info_alter()` & `hook_field_extra_fields_alter()`. You can use these function to redefine how you'd like specify your taxonomy term label field.
> 1 votes

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


# Question
Title: Is it possible to make site_email an i18n variable?
We have multilingual site pointing to 2 domain according to site language.

> www.example.com (Swedish)
>
> www.other.com (English)

Now when some user post content from Swedish domain we want to send notification of content submission to user from info@example.com and if from English domain then from info@other.com

Is that possible ?

I have attempted like below in custom module whose weight is 1000:

```
function custom_overrides_init() {

  global $language;

  if($language->language == "sv"){
    variable_set('site_mail', "info@example.com");
  }else if($language->language == "en"){
    variable_set('site_mail', "info@other.com");
  }
}

```

When I see in maillog it shows correct from email addresse but its not working and use same email address which is set on site configuration.

**i18n\_variable** also does not provide site\_email as variable.

Please suggest !

# Answer
Your current solution is actually a very bad practice, as you will be rebuilding the variable cache on every page request, which is a big hit.

You can set the site\_mail variable as translatable by installing the Variable module (http://dgo.to/variable), then implementing hook\_variable\_info() and declaring the site\_mail variable.

```
function hook_variable()
{
  $variables['site_mail'] = array
  (
    'title' => t('Site Email'),
    'description' => t('The email addresses site mails are sent from'),
    'type' => 'string',
  );

  return $variables;
}

```

You then need to go to Admin -\> Configuration -\> Regional and Language -\> Mutilingual settings -\> Variables, and set site\_mail as being translatable. You will then be able to visit the site information page and set a different value for the site mail in each language.
> 1 votes

# Answer
Two different questions are asked,

1. One question in the header:

> Is it possible to make site\_email an i18n variable?

This is probably not what you want.

2. Another question in the text body:

> Now when some user post content from Swedish domain we want to send notification of content submission to user from info@example.com and if from English domain then from info@other.com
>
> Is that possible ?

Yes, it is possible and it is about *domains* as you state in this question (not *languages*).

The Domain Variable module should be used together with the Domain Access module. These modules make the site\_email as a variable per each domain. No custom coding needed.

You could then have these site emails:

* noreply@sweden.com (as sender for all languages on www.sweden.com)
* noreply@worldwide.com (as sender for all languages on www.worldwide.com)
> 0 votes

---
Tags: 7, i18n-l10n, emails
---


# Question
Title: How to make page.html.twig based on Vocabulary?
I want to make different page.html.twig according to different Vocabulary. I found this code:

```
function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

```

in How do I theme a taxonomy term page?. Code does not work:

> Fatal error: Class 'Term' not found in...

Excuse me, what is the reason, I really need to customize the page.html.twig according to the vocabulary, you can help me？

# Answer
Because you have not included the PHP code that contains the Class.

See Namespacing in PHP.

According to term.php the name space is `Drupal\taxonomy\Entity`.

So you need to add `use [name space]\[class name];` at the top.

Therefore, it would be `use Drupal\taxonomy\Entity\Term;`.

**Example:**

```
<?php

use Drupal\taxonomy\Entity\Term;

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

```
> 2 votes

---
Tags: 8, theming
---


title: Why doesn't 'drush cc all' work?

text:
# Question
Title: Why doesn't 'drush cc all' work?
I installed Drush, but most of the commands doesn't work, I guess. I tried `drush cc all` and got the following output:

> Command cache-clear needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment to run this command.
> The drush command 'cc all' could not be executed.
> A Drupal installation directory could not be found

`drush status` outputs the following:

> PHP configuration : /etc/php5/cli/php.ini
> Drush version : 4.5
> Drush configuration :
> Drush alias files :

# Answer
> 14 votes
You need to **rebuild** cache with Drupal 8, rather than clear it:

```
drush cr

```

# Answer
> 5 votes

# Answer
> 2 votes
You can even try:

* drupal 7 :drush cache-clear all
* drupal 8 : drush cache-rebuild

Refer two articles you can have some more idea on clearing and rebuilding cache:

1. http://www.metaltoad.com/blog/drupal-8-first-impressions-back-end-developer
2. https://www.drupal.org/documentation/clearing-rebuilding-cache

# Answer
> 0 votes
Shouldn't you be using Drush 8.\* for Drupal 8? I believe your version is just outdated. (And you need `drush cr` as Clive pointed out.)

# Answer
> 0 votes
If your drush status does not say anything about the database then it is not connecting to the database and thinks your site is effectively dead. This is very VERY common for new sites. Possible fixes:

1. Make sure your in the same directory that the index.php file is in for drupal.

or if in multisite setup then.

2. Make sure you are in the $rootdir/sites/yoursitename/ subdirectory when you execute "drush st".

or

3. Make sure you supply the --uri="myawesomesite.local" to tell drush which settings.php file to try to find and use.
4. Make sure you can load your site in your browser first.

See sample screenshot

# Answer
> 0 votes
This happens to me on ever single D7 installation and I solve it by changing the host setting for the DB in my settings.php file from "localhost" to "127.0.0.1"

---
Tags: 8, drush
---


# Question
Title: How to make profile2 completely replace or override the core profile?
I have installed the Profile 2 module. I want to make it replace or override the core profile module for the entire website but I don't know how to achieve this. I have searched a lot, but have not found a solution. This is a new website, so I would not need to migrate existing profiles to profile2.

Can this be done using the Panels and Page Manager modules?

Is it a good idea to keep using the core profile module?

Any help is highly appreciated.

# Answer
I wouldn't recommend doing this as profile2 is designed to compliment the core profile module.

The simplest way of explaining this is that the core profile module handles your account while profile2 handles all the extra information not required in order to be a Drupal user.

On a large sports team website that I run we use profile2. When users go their user page they see in order:

* Their picture (a field of the core profile module)
* Their email settings (core profile module)
* A heading titled "Personal Information" (profile2 module)
* All their personal information (First Name, Last Name, DOB, Address, Contact Number) (profile2 module)
* Another heading title "Medical Information" (profile2 module)
* All their medical info (Injuries, Allergies, Medications, Emergency Contact) (profile2 module)

When they go to edit their profile, the main tab is titled "Account" and allows them to change their username, email address, password, email settings, and profile picture. Profile2 adds "Personal" and "Medical" tabs where users go to complete the other two profiles.

Our club contact list gives all users access to the main profile which contains the username, picture, and email address. Only club executives and coaches have access to the personal information profile and only coaches have access to the medical information profile.
> 2 votes

---
Tags: 7, views, users, panels
---


# Question
Title: User Points Rules: Remove points (based on content type)
I currently am using the User Points Rules module to grant points (both moderated and unmoderated) to users for signing up for content using the Signup module. However, for cases where the user cancels the signup, it doesn't seem possible to remove (through another transaction) the points.

The points aren't static (i.e. 1 point per signup and thus -1 point per cancellation), but are dependent on the integer value entered for the Events content type.

Suggestions?

Issue on d.o: https://www.drupal.org/node/2419721

# Answer
> 0 votes
Your question seems to be a variation (not a duplicate) of the question "How to grant user User Points equal to certain field's value / calculated value?".

Similar to the accepted answer to that question, use the Rules module and try to create a rule with these Rules Actions:

* Calculate a variable that corresponds to "*the integer value entered for the Events content type*" (similar to what you wrote in your question).
* Convert the data type of that variable (to *integer*).
* Grant points to user (using the calculated + converted variable.

With that, the only thing left to do is to find an appropriate Rules Event to get this rule triggered.

PS: such "convert data type" is simply a matter of how Rules works (by design), so it's not to be considered as a bug either.

---
Tags: 7, rules, userpoints
---


# Question
Title: How to check a user's current userpoints balance with Rules?
I am interested in creating a rule that checks a user's userpoints and then the rule performs an action.

Currently the Rules module doesn't have such condition. I read that this is possible to do with a Rules Component, that is used as a Rules Condition.

Could someone help me on this please?

# Answer
I finally found a solution: I created a rule set,where I add two rules: 1)Load the user points 2)Data comparison of user points

After creation of the Rule set,I created the main rule where I added as an action the Rule Set.Done!
> 0 votes

# Answer
You're right, there is no Rules *Condition* to ***check a user's current userpoints balance***.

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

```
{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "20" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have sufficient points (you still have [total-points:value] ...)." } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "You DO NOT have sufficient points (you only have [total-points:value] ...)." } }
            ]
          }
        ]
      }
    ]
  }
}

```

It does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 20, it will display a message starting with "You have sufficient points ...", otherwise the message starts with "You DO NOT have sufficient points ...".

In this example I'm using the Conditional Rules module, though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module.

So the clue to make this rule work is the very first Rules Action "***Load user points of a user***".
> 0 votes

---
Tags: rules, userpoints
---


# Question
Title: Drupal 8, override User Class for a custom added field
I am not a great POO specialist, maybe my ask will seems stupid x)

When I create new field from the user UI administration, I would like find quickly this field when I work from my IDE in customs modules.

So, I think I need add a custom method for the User Class, like :

```
public function mycustomfield_value($user){
    return $user->mycustomfield->value;
}

```

From my IDE, if I type "$user-\>" the IDE auto-complete must show me "$user-\>mycustomfield\_value(..." method.

My ask is : how can I add this method ? I must create a new Class implement/extends User Drupal 8 Class ? I don't know how can I do that..

# Answer
Don't. The field system doesn't work like that, there is currently no useful way to get autocomplete.

You could replace the entity class with your own and add methods for your fields, but it's not worth the trouble IMHO as you might get into trouble of some other module wants to replace the class as well.

You could add helper method or functions somewhere else and pass in the entity.
> 1 votes

---
Tags: users, 8
---


# Question
Title: No submit button available when using Display Suite Forms to render a node add form
I've created a Display Suite layout and assigned it to my content type.

Everything else is rendered just fine on the form but there's just a "small" problem: **no submit button.**

Do I need to use some special variables in template file to render submit button?

Current template is(nothign):

```
  <div class="row">
    <div class="well-success well-sm well col col-sm-12 col-md-2 bg-success text-center">
      <h1>1</h1>
    </div>
    <div class="col col-md-10 well-sm well">
      <div class="container-fluid">

        <div class="col col-md-4">

          <?php print $row_first_col_first; ?>
        </div>

        <div class="col col-md-4">

          <?php print $row_first_col_second; ?>
        </div>

        <div class="col col-md-4">

          <?php print $row_first_col_third; ?>
        </div>

      </div>
    </div>
  </div>
  <div class="row">
    <div class="well-success well-sm well col col-sm-12 col-md-2 bg-success text-center">
      <h1>2</h1>

    </div>
    <div class="col col-md-10 well-sm well">
      <div class="container-fluid">
        <div class="col col-md-7">

          <?php print $row_second_col_first; ?>
        </div>

        <div class="col col-md-4">
          <?php print $row_second_col_second; ?>

          <?php print $row_second_col_third; ?>
        </div>

      </div>
    </div>
  </div>

  <div class="row">
    <div class="well-success well-sm well col col-sm-12 col-md-2 bg-success text-center">
      <h1>3</h1>

    </div>
    <div class="col col-md-10 well-sm well">
      <div class="container-fluid">
        <div class="col col-md-4">

          <?php print $row_third_col_first; ?></div>

          <div class="col col-md-4">

            <?php print $row_third_col_second; ?></div>
            <div class="col col-md-4">

              <?php print $row_third_col_third; ?>
            </div>
          </div>
        </div>

      </div>

```

# Answer
Just in time. Went through the ds form source code and found a variable drupal\_render\_children which holds the so far "unrendered" part of form.

So instead of using regular drupal\_render\_children as function and passing form etc for it you use it just as an variable.
> 0 votes

---
Tags: theming, forms, display-suite
---


title: Slideshow on the pages

text:
# Question
Title: Slideshow on the pages
I am looking for a method to put différents slideshows on different pages. I mean every pages must have his own slideshow. Is it possible?

# Answer
Assuming you're using the Views Slideshow module, for each slideshow you create, you also get a corresponding *block* that you need to position in an appropriate region.

So say you have 3 slideshows, ie ShowA, ShowB and ShowC, and you want to show them like so:

* Show A on page with node id = X.
* Show B on page with node id = Y.
* Show C on page with node id = Z.

In this case, all you need to do is to adapt the "Visibility settings" (pages) for each *block* like so:

* For the block related to ShowA, only show this block on page node/X.
* For the block related to ShowB, only show this block on page node/Y.
* For the block related to ShowC, only show this block on page node/Z.

### Possible enhancements

Even though the above should be sufficient to answer your question, there are all sorts of enhancements to the above approach you may want to consider:

* Use a content type (eg "Slide"), to create slides that you want to be shown in a slideshow. And optionally also add an extra field to that content type to identify in which slideshow (ShowA, ShowB, etc) you want an extra slide to be shown. And/or add another field to indicate some type of sequence (like slide nr) of those slides to be shown.
* Use the Rules block visibility module to make the visibility of the blocks more dynamic, by using some Rules logic to yes/no show a specific slideshow-block. Refer to "How to stop a Views block from displaying to admins, such as user/1?" for way more details about how to use Rules block visibility.
> 1 votes

# Answer
You can use Flex Slider module you can find the configuration for module in description and you can watch youtube video for configuration.

Now you can create slide shows blocks using views flexslider formatter here you can find various settings for slideshow in block.

Now you can see the blocks created by views in admin \> structure \> blocks.

Add this blocks on different page by adding "Visibility settings" to each block in block settings. By choosing only the listed pages at "Show block on specific page" option you can type URL of page on which you want this block (slide show) to display.
> 0 votes

---
Tags: media, views, javascript
---


# Question
Title: How to add text as page variable to node add form? Or in other works print explanation/guideline text
I want to include my content type's explanation/submission guideline text on node add form/page.

I need to insert it into header element and therefore a variable would be suitable.

I would assume it should already be available on page--node--add--special-content-type.tpl.php but I think it isn't.

Also, this text is automatically appended on the end of the page which is silly and why I wan't to change it.

And to mention following doesn't print it:

```
  <?php print render($page['help']); ?>

```

# Answer
The core **page.tpl.php** template doesn't know anything about any current node object or help information from its node type. The snippet you're using is for printing a region named `help`, not a node type's help test.

That help information is retrieved by the System help block and is placed in whatever theme region you've configured in the block admin UI (**/admin/structure/block**). You're better off utilizing that block with your theme regions rather inserting a variable into your page template.

However, if you're really wanting to push this information into your template you can evoke `node_help()` to retrieve the information for your template variable and push in your template.php's `template_preprocess_page()` function:

```
/**
 * Override or insert variables into the page template.
 */
function MYTHEME_process_page(&$vars) {
  // $help_text will be available as printable markup with page.tpl.php
  $vars['help_text'] = node_help(current_path(), arg());
}

```
> 2 votes

---
Tags: theming, nodes, forms
---


title: How to add a custom language?

text:
# Question
Title: How to add a custom language?
In Drupal 7 there is a section to add a custom language

But in Drupal 8 that section does not exist,

How can I add my custom language in Drupal 8?

# Answer
There is,just open *Language name* select list and choose last item **Custom language ...** .
> 7 votes

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


# Question
Title: Custom Block Class with custom Template, cache issue
I need add a custom block in my website, this block must show some users values (from customs fields).

I can show all user variables I want but if a user value change for some reason, I must clear all caches for get the news values from the page where is showed my custom block.

I checked the drupal 8 cache API and try find some example, but I don't find how I do for my variables aren't cached. (or cached but refresh when datas user change)

My code is very simple, I have this hook theme (in my .module) :

```
function main_menu_theme($existing, $type, $theme, $path)
{
  $theme=array();
  $theme['block__main_menu_quick_stat_block'] = array(
    'base hook' => 'block',
    // 'render element' => 'block', // I tried with and without this line..
  );
  return $theme;
}

```

This is the build method from my Block Class:

```
class MainMenuQuickStatBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    // Get the currect Drupal User
    $user = _getCurrentUser();

//I tried this...
//  $build['main_menu_quick_stat_block'] = array(
//    '#one' => $user->customfieldone->value,
//    '#two' => $user->customfieldtwo->value,
//  );
//  return $build;

//I tried this...
//    return array(
//      'main_menu_quick_stat_block' => array(
//        '#cache' => array('max-age' => 0),
//        '#one' => $user->customfieldone->value,
//        '#two' => $user->customfieldtwo->value,
//      ),
//    );

//Last try..
    return array(
        '#one' => $user->customfieldone->value,
        '#two' => $user->customfieldtwo->value,
        '#cache' => [
          'max-age' => 0,
          // 'contexts' => ['user',], // I tried this
          // 'contexts' => 'user', // I tried this
        ],
    );
  }
}

```

For my custom template, I copied the default block.html.twig template from the theme directory. I can show variables "one" and "two" from the webpage thanks to the custom template. But impossible to configure theses variables for they become uncacheable !

I also try with cache tags but no success..

**EDIT 1** (after 4k4 detailed answer !)

This is my last try : From my custom Block Class :

```
class MainMenuQuickStatBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    //$user = \Drupal::currentUser(); // If I use this way, I get this error in the "'tags' => $user->getCacheTags()," below : "Error: Call to undefined method Drupal\Core\Session\AccountProxy::getCacheTags() in Drupal\main_menu\Plugin\Block\MainMenuQuickStatBlock->build() (line 52 of modules/custom/main_menu/src/Plugin/Block/MainMenuQuickStatBlock.php)."

    $var1 = $user->field_field1->value; //If a log var1, I get a value here ($var1 = 7 by example)
    $var2 = 42; //its a test

    return [
        '#theme' => 'block__main_menu_quick_stat_block',
        '#test' => 42,
        '#var1' => $var1,
        '#cache' => [
          'contexts' => ['user'],
          'tags' => $user->getCacheTags(),
        ],
    ];
  }
}

```

From my .module file :

```
...
function main_menu_theme($existing, $type, $theme, $path)
{
  $theme=array();
  $theme['block__main_menu_quick_stat_block'] = array(
    'variables' => [
      'var1' => NULL,
      'test' => NULL,
    ],
  );

  return $theme;
}

```

I cleared caches (drush cr)

My custom template block is called when I load the page, but variables 'var1' and 'test' are null. Below, I log variables array with "{{ kint() }}" in my custom template :

I'm going to find drupal guide for know why my vars are null...

# Answer
> 5 votes
The problem is not your choice of cache parameters. If you set cache max-age to 0 you don't need any other cache setting to disable the cache.

The problem is how you use the block template. You probably render only the single variables you've added and not the default `{{ content }}` variable. This is the reason the cache info gets lost.

Better use a custom twig template for the custom variables:

**hook\_theme() in mymodule.module:**

```
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'mytemplate' => [
      'variables' => [
        'var1' => NULL,
        'var2' => NULL,
      ],
    ],
  ];
}

```

**build() in block class:**

```
  public function build() {

    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $var1 = $user->field_field1->value;
    $var2 = $user->field_field2->value;

    return [
      '#theme' => 'mytemplate',
      '#var1' => $var1,
      '#var2' => $var2,
      '#cache' => [
        'contexts' =>  ['user'],
        'tags' => $user->getCacheTags(),
      ],
    ];
  };

```

**mytemplate.html.twig:**

```
<h2>Additional user info</h2>
<p>Field 1: {{ var1 }}</p>
<p>Field 2: {{ var2 }}</p>

```

The template `mytemplate` will be nested inside of the block template, which then, if you change it back to default, can merge the cache data to the block level and page elements on higher levels.

# Answer
> 2 votes
What you have should work by disabling cache completely.

'tags' =\> $user-\>getCacheTags() would allow you to invalidate, and while you want that too, it still means the block will by default be cached for the first user that accesses it. So what you additionally need is 'contexts'\] =\> \['user'\] to indicate that each user needs his own cache.

You could also implement the methods getCacheTags(), getCacheMaxAge() and getCacheContexts() on the block But that shouldn't change anything.

PS: Do not define global functions like \_getCurrentUser(), always prefix with a module like main\_menu\_get\_current\_user() or make them part of your class (e.g. with a trait if you want to re-use)

---
Tags: 8, blocks, caching
---


title: Pager doesn't work

text:
# Question
Title: Pager doesn't work
I have the following view what also is rendered as a block.

This view has a mini pager with default 3 items to show.

When i check configuration of the block of this view it looks like this :

I render this block in region 'content' on the frontpage.

When i check this it shows more than 3 items.

How to fix this?

Screenshot of the homepage (Zoomed out, shows 10 items):

Screenshot pager (Is shown after 10 items instead of 3:

# Answer
After some search on this site i have found the solutions.

The solution is to enable ajax in the advanced views settings of the specific view.
> 0 votes

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


# Question
Title: Drupal 7 returning empty array because of the database connection
I am able to connect to the remote database and fetch the results when I am using `core PHP-MySQL connection`.

But Drupal 7 returns empty array when I am using the same remote database connection. The local database is working fine.

Below is my database connection in settings.php

```
$databases['default']['default'] = array (
      'driver' => 'mysql',
      'database' => 'test',
      'username' => 'test',
      'password' => 'test',
      'host' => '*****',
      'port' => '3316',
      'prefix' => '',
);

```

When I am accessing my site, it is just returning `Array`as output. Is it a problem with my database user permissions or should I make any changes in Drupal database settings with port?

# Answer
I resolved it. The problem is not in the database connection. I **cleared the cache table in the database** and it started working fine.

Earlier, I set the option **'Cache pages for anonymous users'**. May be because of this, it didn't give the output.

Thanks for your answer.
> 0 votes

---
Tags: 7, database, configuration
---


# Question
Title: How to do field validation during migration?
I've a user migration class as shown here.

However for some reason users are created with empty required fields (such as e-mail).

How do I implement custom validation of the field during migration?

So I can fail the validation for specific row and **continue** the migration? So the specific rows won't be migrated and they will appear in the list of the one which has error in it.

Is there any method for that?

# Answer
You can accomplish this using the `::prepareRow()` method on your migration class. You'll have access to the source field values in the $row variable. This method is called once for each record being imported, and returning FALSE will skip the row in question.

Example:

```
function prepareRow($row) {
  if (!validate_my_field($row->my_custom_field)) {
    return FALSE;
  }
}

```

More info https://www.drupal.org/node/1132582

For Drupal 8 you could accomplish the same by either implementing a custom source plugin with a `prepareRow()` method. Or by implementing `hook_migrate_prepare_row()` and performing your validation there.
> 2 votes

# Answer
Here is another example of row validation using `prepareRow()` method (using CSV import):

```
  /**
   * Modifies the row to be imported.
   *
   * @inheritdoc
   */
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }

    // Loop through all the columns in this row and do some validation.
    $error_messages = '';
    foreach ($row as $column_key => $column_value) {
      if ($column_key == 'csvrownum') {
        continue;
      }

      // Validate email address.
      if ($column_key == 'Email' && !valid_email_address($column_value)) {
        $error_messages .= t('Invalid email address. ');
      }

      // Check for character limits.
      if ($column_key != 'Contact preference' && _engage_migrate_character_limit_exceeded($column_key, $column_value)) {
        $error_messages .= t('@column_key is too long. ', array('@column_key' => $column_key));
      }

      // Check for mandatory columns.
      $mandatory_columns = array('Firstname', 'Lastname', 'Email');
      if (empty($column_value) && in_array($column_key, $mandatory_columns)) {
        $error_messages .= t('@column_key can not be empty. ', array('@column_key' => $column_key));
      }
    }

    // Save the messages for this row.
    if (!empty($error_messages)) {
      $this->queueMessage($error_messages);
      return FALSE;
    }

    // All good, import the row.
    return TRUE;
  }

```

So basically in order to fail the field validation, you should return `FALSE` for `prepareRow()` and optionally queue the error message using `queueMessage()` method.
> 0 votes

---
Tags: 7, entities, migrations
---