# Question
Title: Does memcache allow anonymous users to be served content when the database server is down?
I'm exploring options around keeping my Drupal 7 sites working for anonymous visitors while a database server is being upgraded. The site is already fronted by Cloudflare - but their always on tech is a little hit and miss.

I'd like to understand more about when the database is queried when using the memcache module. My other choice is to use the AutoSlave module and setup a master - slave replication - but if I can get a performance boost from memcache and a little resilience added in - I'd maybe prefer that route.

I'm hoping that the page cache will remain relevant enough to perform the database upgrade. What are the rules around the memcache content going stale?

# Answer
As stated in the comments, memcache is probably not going to help you here.

Since you are using CF as a front end, you *might* be able to get by by creating a page rule to cache everything. See this doc. This assumes that your site is pretty static (e.g. not an e-commerce or has user logins.

I'd suggest creating a script to load all your pages prior to shutting down the sql server. I.e., clear the CF cache then load all the pages into cache using the script. A bunch of CURL statements should work. Make sure to load ALL the content (e.g. images, css, scripts).

That said, I really would not depend on this. Personally, I'd set up a temporary DB server, copy the DB to it, then change the settings.php to point to it when the main DB is being updated. Then swap it back after the update.
> 0 votes

---
Tags: caching
---


# Question
Title: Count the number of UNIQUE values in a TEXT field
I'm creating a View to count the total number of unique values for a text field. This text field has a limit of one during input, so there are no additional values to check. I tried the aggregate and distinct options in the advanced tab, but I can't seem to get it to work properly.

I picked count distinct, but it still shows the duplicates as seen in the screenshot below.

# Answer
Try to do the next thing:

Enable `distinct` option in query settings. Then in field's aggregation settings choose `count DISTINCT` option(not just `count`!).

Hope it'll help. This worked for me.
> 1 votes

# Answer
The drupal zealots will hate me for this for using php in the ui. I used php views and did a custom sql query to output the number of unique values for a field. My field was called campaign.

```
<?php
$campaign_query = db_query('select count(distinct(field_campaign_value)) from field_data_field_campaign');
$campaign_total = $camp_query->fetchAll();

$ctotal = $campaign_total[0]->{'count(distinct(field_campaign_value))'};

echo '<div class="views-php-totals">'. $ctotal .' Campaigns</div>';
?>

```

The "proper" drupal way to do it is the create a new module and inject that code into the views header. But if your just a solo dev or a small team, doing my way would be the quickest.
> 0 votes

---
Tags: views, entities
---


title: Why do old versions exist?

text:
# Question
Title: Why do old versions exist?
In Issues for Drupal core, different versions of Drupal were mentioned. If Drupal 8 is obviously better than Drupal 7 and prior versions, why do the issues for Drupal 7 exist?

# Answer
> the version 8 of drupal exists which is obviously better than drupal 7

Yep Drupal 8 is arguably better, but...so what? When a car manufacturer releases a new version of a model, does everyone throw out the old model immediately and just get a new one? Of course not; if they can, and wish, to upgrade to the latest version, they'll do so in their own time.

In the meantime it would be ridiculous for mechanics to stop fixing the older model, right?

Same story here.
> 7 votes

# Answer
Because still a lot of sites using drupal 7 and drupal 8 still not perfect. For example drupal 7 has more supported modules than drupal 8. As I know there's still drupal 6 sites.
> 2 votes

# Answer
Below is an attempt to give an answer to this part of your question:

> why do the issues for Drupal 7 exist?

Consider a distribution such as Commerce Kickstart, which contains this `.make` file.

Line 17 of this `.make` file looks like so:

```
projects[features][patch][2479803] = "https://www.drupal.org/files/issues/ignore_hidden_modules-2479803-1.patch"

```

In other words, to install Commerce Kickstart, this is one of the patches that needs to be applied also. In this specific case the patch appears to be related to the Features module, as detailed/explained in the issue titled Ignore hidden modules when mapping components. ... a D7 issue, did you notice?!?! More specifically, comment # 1 of that very issue is where that patch (as referred to in the make file) was posted.

So with that, its because that D7 issue (still) exists, that it is (still) possible to install Commerce Kickstart. This is just 1 specific example, but there are zillions of patches that exist throughout drupal.org. And if you really think about it, consider the issue queue as some sort of online storage to not only attach such patches to, but also to get an idea (aka documentation) about what a specific patch is about.

But wait, there is even more: your question is only about D7, the beauty of all this is that it applies to any Drupal version, starting as of Drupal 4.x, and including 5.x and 6.x also. So to continue the "*car manufacturer* metaphor from a previous example: the issue queue is like the (very only!) warehouse to find the spare parts for the old models also ... including the instructions/documentation about them.

PS: the patch example I used here is about a contributed module. Though there are similar patches that are related to Drupal core. Such as what is described in the question about "Patch a module loaded by a distribution".
> 1 votes

---
Tags: 7
---


# Question
Title: How to check if 2 email fields have the same value entered during content creation?
I'm trying to create a *custom signup* content type and I'm wondering if there is a way to check if two email fields have the same value entered. Similar to typing in an email twice to make sure you have the correct email down.

If the two email fields are not the same an error needs to appear upon saving.

I'm not using a webform for this, it's a custom content type.

# Answer
Assuming this question is about D7, you could use the Rules module and create a (rather basic) rule like so:

* Rules Event: Before saving content
* Rules Conditions:
    + Content is of type "custom signup".
    + Entity has field (related to your 1st eMail field).
    + entity has field (related to your 2nd eMail field).
    + Data comparison: the value of the 1st eMail field is NOT equal to the value of the 2nd eMail field.
* Rules Action: Show a message on the site (of type "error").
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: IMCE browse server image upload button not displaying on ckeditor toolbar
I just installed and enabled IMCE for drupal 7 and assigned the IMCE icon in the *full html* input format page, but the icon is not appearing in the ckeditor toolbar. I even set the permissions for the IMCE.

# Answer
> 1 votes
I don't have it fully functioning yet, but I am getting closer...

EDITOR APPEARANCE

* Make sure you Load the sample toolbar more accurate to what you will use when you drag the button up there.
* **Plugins** = check the box "*Plugin for inserting files from IMCE without image dialog*"

Once I added the plugins, it started working.

Now it isn't complete, because I get an error when I click on (an existing image's) "Image Properties" and "Browse Server" that says the requested page (ckfinder.thml?....) could not be found. So I am still working on it but at least it is partially working.

# Answer
> 2 votes
Make sure you scroll down that same page and look for **file browser settings** and make sure its set to IMCE. Mine was on none and after switching that, the file browser upload button showed up in the image dialog popup.

# Answer
> 0 votes
IIRC, there's no "IMCE" button on CKEditor. The "Browse Server" button however should now appear when you press "Insert/Edit Image" or "Insert/Edit Link" buttons, if you enabled IMCE in WYSWIWYG settings.

---
Tags: 7, users, files
---


title: Programatically translate an entity

text:
# Question
Title: Programatically translate an entity
I'm working on a custom solution that leverages the ECK module to handle the entity field creation and display. These custom ECK entities are then attached to nodes via a custom interface.

I'm trying to also build in the ability to translate these entities.

I have a controller that displays the form:

```
namespace Drupal\MODULE\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\content_translation\Controller\ContentTranslationController;

class MODULEController extends ControllerBase {

  public function edit($node) {
    $entity        = MODULE_load_entity($node);
    $entity_form   = [];
    if ($entity) {
      $form_state_additions = [];
      $operation = 'default';

      // Determine if the entity being added/edited is an origin or a
      // translation and handle the translation if applicable. Start by
      // determining the entity language and the current language.
      $languages        = \Drupal::languageManager()->getLanguages();
      $current_langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
      $entity_langcode  = $entity->get('langcode')->getValue();
      $entity_langcode  = $entity_langcode[0]['value'];
      if ($entity_langcode != $current_langcode) {

        // Create the translation elements on the form.
        $manager    = \Drupal::service('content_translation.manager');
        $controller = new ContentTranslationController($manager);
        $controller->prepareTranslation($entity, $languages[$entity_langcode], $languages[$current_langcode]);

        // Use the add form handler, if available, otherwise default.
        $operation = $entity->getEntityType()->hasHandlerClass('form', 'add') ? 'add' : 'default';

        $form_state_additions['langcode'] = $languages[$current_langcode]->getId();
        $form_state_additions['content_translation']['source'] = $languages[$entity_langcode];
        $form_state_additions['content_translation']['target'] = $languages[$current_langcode];
        $form_state_additions['content_translation']['translation_form'] = !$entity->access('update');
      }

      $entity_form = $this->entityFormBuilder()
        ->getForm($entity, $operation, $form_state_additions);
    }

    return $entity_form;
  }
}

```

This allows me to create the default version and the translated version and the data in the tables looks ok. But when I try to edit the translated version I get this exception:

> The website encountered an unexpected error. Please try again later.InvalidArgumentException: Invalid translation language (fr) specified. in Drupal\Core\Entity\ContentEntityBase-\>addTranslation() (line 863 of core/lib/Drupal/Core/Entity/ContentEntityBase.php).
>
> Drupal\content\_translation\Controller\ContentTranslationController-\>prepareTranslation(Object, Object, Object) (Line: 52) Drupal\MODULE\Controller\MODULEController-\>edit('1') call\_user\_func\_array(Array, Array) (Line: 123) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber\\{closure}() (Line: 576) Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 124) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) (Line: 97) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber\\{closure}() call\_user\_func\_array(Object, Array) (Line: 153) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 68) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 99) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 50) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 657) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

Obviously I'm doing something wrong, but I can't seem to figure out what it is. Any insight into fixing these issues would be much appreciated.

**UPDATE4**: issue from the previous update fixes the first issue. I've removed it from the ticket since the second issue still remains.

# Answer
> 0 votes
I was treating the creation of the entity translation the same as the editing of the translation. See the following code change which takes into account both types of form.

```
<?php

namespace Drupal\MODULE\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\content_translation\Controller\ContentTranslationController;

class MODULEController extends ControllerBase {

  public function edit($node) {
    $entity        = MODULE_load_entity($node);
    $entity_form   = [];
    if ($entity) {
      $form_state_additions = [];
      $operation = 'default';

      // Determine if the entity being added/edited is an origin or a
      // translation and handle the translation if applicable. Start by
      // determining the entity language and the current language.
      $languages        = \Drupal::languageManager()->getLanguages();
      $current_langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
      $entity_langcode  = $entity->get('langcode')->getValue();
      $entity_langcode  = $entity_langcode[0]['value'];
      if ($entity_langcode != $current_langcode) {

        // Editing an existing translation.
        if ($entity->hasTranslation($current_langcode)) {

          // Use the edit form handler, if available, otherwise default.
          $operation = $entity->getEntityType()->hasHandlerClass('form', 'edit') ? 'edit' : 'default';

          // Set the form state additions.
          $form_state_additions = [];
          $form_state_additions['langcode'] = $languages[$current_langcode]->getId();
          $form_state_additions['content_translation']['translation_form'] = TRUE;
        }

        // Adding a new translation.
        else {

          // Create the translation elements on the form.
          $manager    = \Drupal::service('content_translation.manager');
          $controller = new ContentTranslationController($manager);
          $controller->prepareTranslation($entity, $languages[$entity_langcode], $languages[$current_langcode]);

          // Use the add form handler, if available, otherwise default.
          $operation = $entity->getEntityType()->hasHandlerClass('form', 'add') ? 'add' : 'default';

          // Set the form state additions.
          $form_state_additions['langcode'] = $languages[$current_langcode]->getId();
          $form_state_additions['content_translation']['source'] = $languages[$entity_langcode];
          $form_state_additions['content_translation']['target'] = $languages[$current_langcode];
          $form_state_additions['content_translation']['translation_form'] = !$entity->access('update');
        }
      }

      // Build the entity form.
      $entity_form = $this->entityFormBuilder()
        ->getForm($entity, $operation, $form_state_additions);
    }

    return $entity_form;
  }
}

```

---
Tags: 8, entities
---


# Question
Title: How to convert year to date with Migrate
I try to import a CSV file with Drupal 8 Migrate. One column contains a year value which I want to convert to a Drupal date field.

I try to do that with the following process statement using format\_date plugin from Migrate Plus but something goes wrong:

```
  process:
    field_fecha:
      plugin: format_date
      from_format: 'Y'
      to_format: 'Y-m-d\TH:i:s'
      settings:
        validate_format: false
      source: year

```

I'm not sure if Y is allowed as from\_format value. But I also don't know what standard value uses Drupal 8 date field and what to put as to\_format value.

# Answer
Just found out that *to\_format* value is the problem. Setting it to 'Y-m-d' works fine and imports the year value as date putting month and day to values of today. So actually to get specific day and month added to year value, this code works fine:

```
process:
    field_fecha:
      plugin: format_date
      from_format: 'Y'
      to_format: 'Y-01-01'
      source: year

```

Probably that's because I defined the date field as "date only". For "date and time" fields 'Y-m-d\TH:i:s' should work fine.
> 2 votes

---
Tags: 8, migrations, datetime
---


# Question
Title: How to migrate multiple columns to single field in CSV Migrate
In my CSV file, I am having columns by name `summary_1`,`summary_2` and `summary_3`. I want all of it migrated to a field in Drupal `field_summary`. The field supports multiple values.

```
id: sections_tfr
migration_tags:
  - CSV
migration_group: tfr
label: 'Import sections'
source:
  plugin: csv
  path: /var/www/html/php/tfr/prepared/final/sections.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - s_id
  column_names:
    -
      s_id: Id
    -
      part_no: Part
    -
      sections: Section
    -
      summary_1: Summary
    -
      summary_2: Summary
    -
      summary_3: Summary

process:
  name: sections
  description: heading
  field_summary: summary_1
  field_summary: summary_2
  field_summary: summary_3
  weight: s_id
destination:
  plugin: 'entity:taxonomy_term'
  default_bundle: sections
  migration_dependencies: null

```

# Answer
It took a while for me to solve the issue. However, I was able to manage the same without having to write additional plugin or module. I solved the issues in two steps:

1. First used the plugin `concat` to concatinate all 3 required fields to one.
2. Then used the plugin `explode` to pass the value to the same field.

Yaml Below:

```
id: sections_tfr
migration_tags:
  - CSV
migration_group: tfr
label: 'Import sections'
source:
  plugin: csv
  path: /var/www/html/php/tfr/prepared/final/sections.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - s_id
  column_names:
    -
      s_id: Id
    -
      part_no: Part
    -
      sections: Section
    -
      summary_1: Summary
    -
      summary_2: Summary
    -
      summary_3: Summary

process:
  name: sections
  description: heading
  field_summary:
    -
      plugin: concat
      source:
        - summary_1
        - summary_2
        - summary_3
      delimiter: ','
    -
      plugin: explode
      limit: 100
      delimiter: ','
  weight: s_id
destination:
  plugin: 'entity:taxonomy_term'
  default_bundle: sections
  migration_dependencies: null
migration_dependencies: null

```
> 4 votes

# Answer
I was struggling with this very same issue. Even though the official migration docs suggest that multivalued fields will be handled by the pipeline automatically, it didn't happen for me(at least at the time of writing this). I ended up extending the `entity_generate` plugin provided by migrate\_plus to generate multiple entities. Here's the plugin code:

```
Namespace Drupal\my_module\Plugin\migrate\process;

use Drupal\migrate_plus\Plugin\migrate\process\EntityGenerate;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * This plugin generates entities within the process plugin.
 *
 * @MigrateProcessPlugin(
 *   id = "entity_generate_multiple",
 *   handle_multiples = TRUE
 * )
 *
 */
class EntityGenerateMultiple extends EntityGenerate {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) {
    // Input value should be an array
    if(!is_array($value)) {
        throw new MigrateException('Input should be an array.');
    }
    $result = [];
    foreach($value as $val) {
        $result[] = parent::transform($val, $migrateExecutable, $row, $destinationProperty);
    }

    return $result;
  }
}

```

And here's how I used it,

```
  field_tags:
    -
      plugin: get
      source:
        - tag_1
        - tag_2
        - tag_3
    -
      plugin: entity_generate_multiple
      value_key: name
      bundle_key: vid
      bundle: tags
      entity_type: taxonomy_term

```

Hope that helps.
> 3 votes

---
Tags: migrations, importing-exporting, configuration, 8
---


# Question
Title: How to call a specific library file inside the div
I have declared the external library and calling this library for a particular page using preprocess html.

The Library file has been called for the particular page and showing the script content at the bottom of the page.

Now I want to wrap the script content between the div

How do I wrap the script content between the Div using preprocess html or Any Other ways to wrap the script ?

# Answer
Attaching a library via the `#attached` tag will add it to the header (or bottom of the page if that's the settings). It does not get added into the "content" area. So, wrapping it in a `<div>` is not applicable.

If you are using JS to generate some content that needs to be placed on the page, then it needs to be written to find some selector and insert the content. E.g.

```
jQuery('#my-dynamic-content').html("My new div content");

```

Then just add the `<div id="my-dynamic-content"></div>` to your template/content as needed.
> 2 votes

---
Tags: 8
---


# Question
Title: Foolproof way to prevent email sends from local/dev server
We have had a number of occasions when a new new developer starts working on a project, and when they have it installed the cron runs and sends out a load of emails to users. If the database is fairly old this could send out a lot of unwanted mails. What is the best way to prevent this?

We are currently using Reroute Email which works fine, but obviously this is needs to be enabled. We have set up the settings.php to override the config to enable this, but as it's not included in the GIT repo a new developer might not include this when setting up their local version.

Is there any way to lock this down so it can't happen?

# Answer
You can sanitize the database so that the emails are not "live" before you provide the database to new developer(s).

drush sql-sanitize is one way to do this.

On my site, I have dev/staging/live servers. When the live/test database is cloned to dev, a script is called that automatically changes all email addresses to `uid@mysite.com`. And then all developers pull the database from the dev server. This way, it is impossible to accidentally spam users.

I think the only "foolproof" way to prevent accidentally emailing users is to never give the developer the users' emails in the first place.
> 0 votes

---
Tags: 7, emails, cron
---


title: What does user/1234 mean in #2629286?

text:
# Question
Title: What does user/1234 mean in #2629286?
I was trying to figure out the exact problem of this issue (Use `getDisplayName()` for user names consistently), what does `user/1234` mean in:

> Realname module alters the display name, but at `user/1234` the username is shown. This is incorrect.

# Answer
`user/1234` refers to the path-- the "URL" in Drupal.

In Drupal, by default, each user has his/her own URL at `user/UID`. This `user/1234` is referring to a user account with the UID of `1234`, which is just to be an example, 1-2-3-4.

The problem described in that issue is that Drupal 8 has three functions to get a username:

`getUsername()` and `getAccountName()`: These two functions return the value of the `username` without modification.

`getDisplayName()`: This function returns the value of the `username` after letting modules modify/filter it.

The bug described in the issue explains that when you go to the user path/URL for a user, you see the unmodified, unfiltered username, but you should actually see the filtered version with `getDisplayName()`.

This issue causes serious problems for the Real Name module and any other module that tries to modify how the username is displayed; there are some patches in the issue which "mostly" fix the issue (I have used a few on different sites of mine), but there is no peer-reviewed, all-tests-passing patch yet.
> 3 votes

---
Tags: users
---


# Question
Title: How to create a "go back" or "cancel" button on the node add form?
I'm trying to add a "cancel" button to my content type.

In `hook_form_alter()`, I'm using this code:

```
  if ($form_state->getFormObject()->getOperation() == 'default') { // On node add, make it clear "cancel" deletes any input
    // Do not show cancel button to people who have not completed their profile.
    if ($user->hasPermission('create MYTYPE content')) {
      $form['actions']['submit_cancel'] = array (
        '#type' => 'submit',
        '#weight' => 999,
        '#value' => t('Delete all input and return to previous page'),
        '#submit' => array('MYMODULE_userpageredirect_callback'),
        );
      $form['actions']['submit_cancel']['#attributes']['class'][] = 'btn-danger';
    }
  }

```

....

```
/**
 * Cancel changes and return to previous page
 * @param array $form
 * @param FormStateInterface $form_state
 */
function MYMODULE_userpageredirect_callback(array &$form, FormStateInterface &$form_state) {
  $route_name = 'user.page';
  $form_state->setRedirect($route_name);
}

```

This creates a cancel button that returns the user to the user page when they click cancel.

**Problem**

If a field is marked required, and the user has not input any text in the field, the browser prompts the user to input a value into the field before the cancel button will work.

# Answer
> 8 votes
Adding `'#limit_validation_errors'` will help override validation,

```
$form['actions']['submit_cancel'] = array (
  '#type' => 'submit',
  '#weight' => 999,
  '#value' => t('Delete all input and return to previous page'),
  '#submit' => array('MYMODULE_userpageredirect_callback'),
  '#limit_validation_errors' => [],
);

```

---
Tags: 8, forms
---


# Question
Title: Restrict users to view custom form(s) without complete other formalities
I wrote 3 custom forms using hook\_menu() for resetting password. All forms have these functionalities.

**Form # 1.** On submit, sends OTP (code) after entering mobile number and redirect to form # 2

**From # 2.** On submit, validate OTP and redirect to form # 3

**From # 3.** The last form where user can enter password and confirm password and submit.

How to restrict user from accessing **form#2** without submit **form#1**?

```
                        AND

```

How to restrict user from accessing **form#3** without submit **form#2**?

# Answer
Check the referring page using `$_SERVER['HTTP_REFERER']` if it doesn't match the previous page either throw an error or redirect him to the first page.
> 0 votes

---
Tags: 7, forms, hooks, users
---


# Question
Title: Migration of CSV into paragraphs fails with unexpected error
I try to import CSV files into a Drupal 8 installation but I can't manage to make the relationship to paragraphs appear. I followed the steps of this tutorial but can't figure out how to make it work. I created a simple test case to find the error:

I extended the regular *article* content type with a paragraphs field called *field\_persons* for linking each article to a list of persons with roles. This paragraphs entity has to fields called *field\_name* (for now only text) and *field\_role* (taxonomy\_term).

The yaml file for paragraphs migration looks like that and import processes without error:

```
id: article_persons
label: Import persons for articles

source:
  plugin: csv
  delimiter: '|'
  enclosure: '"'
  path: article_persons.csv
  header_row_count: 1
  keys:
    - id
  column_names:
    0:
      id: 'ID'
    1:
      name: 'Name'
    2:
      rol: 'Role'

process:
  field_nombre: name
  field_para_rol:
    plugin: entity_generate
    source: role
    value_key: name
    bundle_key: vid
    bundle: rol
    entity_type: taxonomy_term
    ignore_case: true

destination:
  plugin: 'entity_reference_revisions:paragraph'
  default_bundle: article_persons

```

The yaml file for article migration looks like that and import processes without error:

```
id: article
label: Import articles

source:
  plugin: csv
  delimiter: '|'
  enclosure: '"'
  path: articles.csv
  header_row_count: 1
  keys:
    - id
  column_names:
    0:
      id: 'ID'
    1:
      title: 'Title'
    2:
      person: 'Persons'

process:
  title: title
  type:
    plugin: default_value
    default_value: article
  field_person/target_id:
    -
      plugin: migration_lookup
      migration: article_persons
      no_stub: true
      source: id
    -
      plugin: extract
      index:
        - '0'
  field_person/target_revision_id:
    -
      plugin: migration_lookup
      migration: article_persons
      no_stub: true
      source: id
    -
      plugin: extract
      index:
        - 1

destination:
  plugin: 'entity:node'
migration_dependencies:
  required:
    - article_persons
  optional: { }

```

But when I try to access the node I get an "unexpected error" with a huge log message:

```
Error: Call to a member function getEnabledBehaviorPlugins() on null en Drupal\paragraphs\ParagraphViewBuilder->buildMultiple() (línea 37 de /var/www/html/sites/all/modules/paragraphs/src/ParagraphViewBuilder.php)
#0 /var/www/html/core/lib/Drupal/Core/Entity/EntityViewBuilder.php(220): Drupal\paragraphs\ParagraphViewBuilder->buildMultiple(Array)
#1 [internal function]: Drupal\Core\Entity\EntityViewBuilder->build(Array)
#2 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(378): call_user_func(Array, Array)
#3 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#4 /var/www/html/core/lib/Drupal/Core/Template/TwigExtension.php(490): Drupal\Core\Render\Renderer->render(Array)
#5 /var/www/html/sites/default/files/php/twig/5a008e9488529_field.html.twig_9MJB5waMfG4Lcal_NDL6EY6rM/NRByUw7bYmwhNIE9WTZfCRjJ3XUAFBB122RdQTC3JsI.php(128): Drupal\Core\Template\TwigExtension->escapeFilter(Object(Drupal\Core\Template\TwigEnvironment), Array, 'html', NULL, true)
#6 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(432): __TwigTemplate_85d8aba47ed6496a0f2e8e6407c9fc1802c03e707a72d9d0c1465c62e125a308->doDisplay(Array, Array)
#7 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(403): Twig_Template->displayWithErrorHandling(Array, Array)
#8 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(411): Twig_Template->display(Array)
#9 /var/www/html/core/themes/engines/twig/twig.engine(64): Twig_Template->render(Array)
#10 /var/www/html/core/lib/Drupal/Core/Theme/ThemeManager.php(384): twig_render_template('sites/all/theme...', Array)
#11 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(437): Drupal\Core\Theme\ThemeManager->render('field', Array)
#12 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(450): Drupal\Core\Render\Renderer->doRender(Array)
#13 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#14 /var/www/html/core/lib/Drupal/Core/Template/TwigExtension.php(490): Drupal\Core\Render\Renderer->render(Array)
#15 /var/www/html/sites/default/files/php/twig/5a008e9488529_node.html.twig_fOU7Z1faeO15YpZRrtd-F9Ksv/yHD4dpGBMlI8SMMqQ5z-QVQGNcCrpCuzsSt1E4ShcEU.php(111): Drupal\Core\Template\TwigExtension->escapeFilter(Object(Drupal\Core\Template\TwigEnvironment), Array, 'html', NULL, true)
#16 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(432): __TwigTemplate_38fa5b6b1f6bdfd56bb4dba5e7d13d0f61126e79c913612089235f94cf12db1f->doDisplay(Array, Array)
#17 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(403): Twig_Template->displayWithErrorHandling(Array, Array)
#18 /var/www/html/vendor/twig/twig/lib/Twig/Template.php(411): Twig_Template->display(Array)
#19 /var/www/html/core/themes/engines/twig/twig.engine(64): Twig_Template->render(Array)
#20 /var/www/html/core/lib/Drupal/Core/Theme/ThemeManager.php(384): twig_render_template('sites/all/theme...', Array)
#21 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(437): Drupal\Core\Theme\ThemeManager->render('node', Array)
#22 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(195): Drupal\Core\Render\Renderer->doRender(Array, false)
#23 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(226): Drupal\Core\Render\Renderer->render(Array, false)
#24 /var/www/html/core/lib/Drupal/Core/Render/Renderer.php(576): Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}()
#25 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(227): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#26 /var/www/html/core/lib/Drupal/Core/Render/MainContent/HtmlRenderer.php(117): Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#27 /var/www/html/core/lib/Drupal/Core/EventSubscriber/MainContentViewSubscriber.php(90): Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\CurrentRouteMatch))
#28 /var/www/html/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(108): Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent), 'kernel.view', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#29 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(158): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object(Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent))
#30 /var/www/html/vendor/symfony/http-kernel/HttpKernel.php(68): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#31 /var/www/html/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#32 /var/www/html/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#33 /var/www/html/core/modules/page_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#34 /var/www/html/core/modules/page_cache/src/StackMiddleware/PageCache.php(78): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#35 /var/www/html/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#36 /var/www/html/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#37 /var/www/html/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#38 /var/www/html/core/lib/Drupal/Core/DrupalKernel.php(657): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#39 /var/www/html/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#40 {main}.

```

This bug report seems to indicate that the paragraphs which is referenced doesn't exist. So it seems to have to do something with the ids, but I can't figure out what.

# Answer
Finally I could make it working fixing two things in my code:

First. Adding the paragraph machine name as type to process statement:

```
process:
  type:
    plugin: default_value
    default_value: persona

```

Second. Changing the source parameter to the column which contains the id of the related paragraph.

After reading the Drupal issue list for Entity Reference Revisions I learned that now there is a more simple way to specify the *target\_id* and *target\_revision\_id*. With the help from this thread I ended up using this process code for node import of *field\_person*:

```
  field_person:
    -
      plugin: skip_on_empty
      method: process
      source: person
    -
      plugin: explode
      delimiter: ,
    -
      plugin: migration_lookup
      migration: article_persons
      no_stub: true
    -
      plugin: iterator
      process:
        target_id: '0'
        target_revision_id: '1'

```
> 0 votes

---
Tags: 8, migrations, importing-exporting, paragraphs
---


# Question
Title: Display Entity Reference field twice, with different display modes
I have a content type (Type A) that has an Entity Reference field to another content type (Type B).

Type B has 3 fields and 2 display modes. Display A shows two of the fields, Display B shows the other field.

In the display settings for Type A, the display mode for the Type B entity is set to Display 1.

On the template for Type A, I can use `{{ content.field_type_b }}` and the two fields are shown.

Now, I want to be able to output the field again, but as Display 2, in a different part of the template.

In a pseudo twig code way, I'd imagine something like `{{ content.field_type_b|display_mode('display_2') }}`

I have heard suggestions for Display Suite, but I tried this and it seems whilst you can clone a field, there is no option to render it as an entity with a display mode.

I also found Twig Tweak, which I *think* might work, however, the documentation is beyond terrible and I cannot see how I'd actually use it (the cheat sheet lacks all manner of help).

If this is not possible in Twig, could this be achieved in a hook? Bearing in mind, the field I want to render in Display 2, is a nicely rendered map, so I don't want to simply get the field value, it has to be using the display mode.

# Answer
How to display a reference field twice with the help of EVA:

1. Install EVA.
2. Add a new View.
3. Add a display "EVA".
4. Add the Entity Reference field to FIELDS and configure the Formatter to "Rendered entity" and set the view mode `Display 2`.
5. The EVA display includes the section ENTITY CONTENT SETTINGS, choose the entity type `Content` and bundle `Type A`.
6. In the ADVANCED section add a contextual filter for `Content: ID`.
7. Save the View.
8. Now the new field is visible in the field UI of the content type `Type A` and you can drag'n'drop it to the final position.
> 0 votes

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


title: Executing drush in a bash script

text:
# Question
Title: Executing drush in a bash script
I'm under MacOSX and I'm struggling for hours trying to figure out how to make drush run from a bash script. So let's say I create a named `build`, then I make it executable. now I begin the script like this:

```
#!/bin/bash
drush cc drush

```

In the terminal if I make `./build`, it brings me result like : `Drush: command not found` So how can I make it work?

Thank you for your answers!

# Answer
> 3 votes
Got it! If you call the script directly it doesn't work, better if ou source it like this: `source build`, then it works. Anyway, I don't know if it's the better way to call this script.

# Answer
> 0 votes
You need to make sure that `drush` command is within your `PATH` environmental variable.

If you're on macOS, place it in `/usr/local/bin` folder, then run this command to check that:

```
$ type -a drush
drush is /usr/local/bin/drush

```

And make sure that `/usr/local/bin` folder is part of your \`PATH variable, e.g. by:

```
$ tr : "\n" <<<$PATH | grep usr.local.bin
/usr/local/bin

```

---
Tags: drush
---


# Question
Title: Render comments in a custom Twig template
I rewrite the article tpl **page--article.html.twig** and I want to render the comments and the comments form.

I add the comments in the content type fields and try to render with `{{ node.comment | render }}`, but it's not work.

Is it possible to render it in a custom tpl?

# Answer
After adding comments as field in your content type

In **node--article.html.twig** :

{{ content.field\_myfieldnamecomments }}
> 3 votes

# Answer
In template files for a content type (eg page--article.html.twig), you have the 'content' variable available. I use this bit of Twig to render the whole comments block:-

```
{{ content.comment }}

```
> 2 votes

---
Tags: 8, comments
---


# Question
Title: No block to display at block settings in any contributed theme
I am trying to use *Simplenews* module for newsletter, but there is no block to display at block setting in any contributed theme after enabling the module.

However it's show when I activate the core theme (Bartik).

My problem is if I use contributed theme, there is no block of *Simplenews* module for enable the block on the front-end (on the block setting page).

What should I do in order the block is displayed?

# Answer
Go to the *Block Layout* page at `/admin/structure/block`, then *Place a Block* in the selected region and select *Simplenews subscription*. Once saved, the block should be available.

Source: Simplenews on Drupal 8 - subscription block.
> 0 votes

---
Tags: 8, blocks, emails
---


# Question
Title: Fetch Link field Label and Link separately in views-view-fields template
How can I fetch label and link field in views-view-fields--VIEW-NAME-HERE.html.twig file

So far I have tried

```
{{ fields.field_action_link.content }} give me the anchor tag prebuilt (html)
{{ fields.field_action_link.0.url }}
{{ content.field_action_link[0]['#url'] }}

```

but none of them seems to work for me. I am able to retrieve all other fields including image field.

# Answer
Just edit the Link field and select these two options (highlighted in screenshot)
> 0 votes

---
Tags: views, theming
---


# Question
Title: How to force a redirect (override the destination query string in the URL)
I have a custom form submit callback to redirect users to a specific page:

```
function MYMODULE_authfrontpageredirect_callback(array &$form, FormStateInterface &$form_state) {
  $url = \Drupal::service('path.validator')->getUrlIfValid('node/16');
  $form_state->setRedirect($url->getRouteName(), $url->getRouteParameters());
}

```

This works correctly unless the url has a `destination` query string, such as `/node/add/mynode?destination=/user`

In this case, the user will be redirected based on the query string (to `/user`) instead of my submit handler destination (`node/16`).

How do I forcibly override the `destination` query string content for this submit handler?

This question is similar to this D7 question but since Drupal 8 has the Symfony routing system the answers there did not help me.

# Answer
> 18 votes
To force a redirect remove the destination query string from the request:

```
\Drupal::request()->query->remove('destination');

```

After this you can also reset the RedirectDestination service, although this seems not to be necessary for a form:

```
\Drupal::destination()->set(NULL);

```

When you have already a URL object set it directly in $form\_state:

```
$form_state->setRedirectUrl($url);

```

---

With the release of Drupal 10.2.0 you can use

```
$form_state->setIgnoreDestination();

```

See https://www.drupal.org/node/3375113

# Answer
> -1 votes
Did you try using the RedirectResponse Class ? I have this kind of callbacks, and it removes URL parameters.

```
use Symfony\Component\HttpFoundation\RedirectResponse;

function MYMODULE_authfrontpageredirect_callback(array &$form, FormStateInterface &$form_state) {
  $response = new RedirectResponse(\Drupal::url('entity.node.canonical', ['node' => '16']));
  $response->send();
}

```

---
Tags: 8, forms, routes
---


# Question
Title: How to declare core requirements in composer.json?
If a module depends on a particular minor release of Drupal (eg 8.4.\*), the best practice is to declare this in info.yml: This blocks installation of the module if core is too old.

However, this just blocks installation, and doesn't help at all with falling back to a compatible version. We can make this much easier by also declaring the compatibility in composer.json.

Requiring drupal/core in the composer.json of a module seems like a *major* change, though. For one thing, it means that your local dev environment pulls in core as well as all its dependencies (about 40 packages), and not their default locked versions either, but the latest supported ones (same effect as running `composer update` in a core checkout). For another, it will cause problems for all environments that use composer for contrib only.

I think `"conflict": {"drupal/core": "<8.4"}` might be a low-impact solution here.

Is there an accepted best practice for this already?

# Answer
> 0 votes
On further experimentation, it appears that it is **unnecessary** to add this to the `composer.json` file. It is enough to add `drupal:system (>=8.3)` to the info.yml requirements. This seems to be automatically interpreted by the drupal.org package repository.

Even when the composer.json file does not specify any dependencies, `composer show drupal/MODULE` will show that it requires `^8.3`, and it will be impossible to install the composer package on an 8.2 site.

---
Tags: 8, composer
---


# Question
Title: Add css class to the container of the action button from a Form
I have a contact form in a Block, using the contact\_block module, now I want to add some bootstrap classes to the div container of the actions buttons (send message).

At the end of the form it I got this wrapper:

```
<div data-drupal-selector="edit-actions" class="form-actions form-group js-form-wrapper form-wrapper" id="edit-actions">
<button class="btn btn-primary btn-xl text-uppercase button button--primary js-form-submit form-submit btn-primary btn" data-drupal-selector="edit-submit" type="submit" id="edit-submit" name="op" value="Send message">Send message</button>
</div>

```

I want to affect the div id="edit-actions".

According to twig debug, I should do a hook of the container, but I don't know how to specify that I want to affect that div.

Inside the themes/bootstrap/templates/system/container.html.twig is the structure of the containers, so I can add some classes there, but I don't know how to specify which container I want to affect. I had tried to change the name to container--contact\_message\_feedback\_form.html.twig, but it doesnt work.

```
{%
  set classes = [
    not attributes.hasClass('toolbar-menu-administration') ? 'form-group',
    has_parent ? 'js-form-wrapper',
    has_parent ? 'form-wrapper',
  ]
%}
<div{{ attributes.addClass(classes) }}>{{ children }}</div>

```

Extra info: Drupal 8.4

Subtheme bootstrap

I have already a hook\_form\_alter() to remove the preview button.

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

  if (strpos($form_id, 'contact_message_feedback_form') !== FALSE) {
    $form['actions']['preview']['#access'] = FALSE;
    $form['actions']['submit']['#attributes']['class'][] = 'btn btn-primary btn-xl text-uppercase';
    // Adding prefix and suffix to the form.
    $form['elements']['edit-actions']['#prefix'] = '<div class="col-md-12 text-center">';
    $form['elements']['edit-actions']['#suffix'] = '</div>';

  }
}

```

# Answer
Thanks to kint for devel options:

There you go:

```
/**
 * Implements hook_form_alter().
 */
function twig_block_form_alter(&$form, $form_state, $form_id) {

  if (strpos($form_id, 'contact_message_feedback_form') !== FALSE) {
    $form['actions']['preview']['#access'] = FALSE;
    $form['actions']['submit']['#attributes']['class'][] = 'btn btn-primary btn-xl text-uppercase';
    // kint($form['actions']['submit']);
    $form['actions']['submit']['#prefix'] = '<div class="col-md-12 text-center">';
    $form['actions']['submit']['#suffix'] = '</div>';
  }
}

```
> 1 votes

---
Tags: hooks, theming
---


# Question
Title: Custom entity - BaseFieldDefinition for entity reference field
I want to create custom content entity, with entity reference field, and display it by views.

Reference field is defined by:

```
  $fields['category'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Category'))
    ->setSetting('target_type', 'taxonomy_term')
    ->setRevisionable(false)
    ->setCardinality(-1);
;

```

How I'm supposed to use this field in view, to display referenced term names ?

# Answer
The easy solution is to create the field via the interface instead of creating it as a base field. Drupal core still have some issues with basefields not working exactly the same way as config fields (fields created as config via interface). Views is missing various integration, the same goes with date fields.

In your case, where you have a multi valued field, it would be store the same way, the only difference is the table name (`ENTITY__FIELDNAME` vs `FIELDPREFIX_FIELDNAME`).

If you really want to use base fields, you can make up from the missing integration by handling it yourself in a custom `EntityViewsData` class for your entity. Having done this in the past, my advice would be to just create a config field, since that is working pretty well, and doesn't change anything on the way the field is store in the database anyways.
> 1 votes

# Answer
As of Drupal 8.4.2 this still an issue.

Here is how I fixed it having a custom Entity Content "itrack\_notification" and an entity reference field "entity\_reference" created with `BaseFieldDefinition` to be able to use this field as a contextual filter.

In `my_module/src/Entity/myEntityViewsData.php`

```
/**
 * {@inheritdoc}
 */
public function getViewsData() {
  $data = parent::getViewsData();

  $reference_field_name = 'receivers';
  $entity_type = 'itrack_notification';

  $handler_values = [
    'field' => "{$reference_field_name}_target_id",
    'table' => "{$entity_type}__{$reference_field_name}",
    'field_name' => $reference_field_name,
    'entity_type' => $entity_type,
    'additional fields' => [
      "field_{$reference_field_name}_target_id",
    ],
  ];
  $data["{$entity_type}__{$reference_field_name}"][$reference_field_name]['relationship']['relationship field'] = "{$reference_field_name}_target_id";
  $data["{$entity_type}__{$reference_field_name}"]["{$reference_field_name}_target_id"] = [
    'group' => $this->t('ITrack Notification'),
    'argument' => [
        'title' => $this->t('Receivers - has User ID'),
        'help' => $this->t('Holds the receiver User ID.'),
        'id' => 'numeric',
      ] + $handler_values,
  ];
  // Unset unusable view data handlers.
  unset($data["{$entity_type}__{$reference_field_name}"][$reference_field_name]['argument']);
  return $data;
}

```

If you need the fix for using the field as a `filter` or `sort` have a look at this patch.
> 0 votes

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


title: Making custom site wide tokens

text:
# Question
Title: Making custom site wide tokens
I'm attempting to add a custom token so I can use it in a view block. Looking at examples I've added this code to my custom .theme file

```
function mytheme_token_info(){
  $types['mytheme_tokens'] = [
    'name' => t('mytheme Tokens'),
    'description' => t('mytheme token type'),
  ];
  $currentnode_token['current_node_title'] = [
    'name' => t('Current Node Title'),
    'description' => t('Title of the current node'),
  ];
  return [
    'types' => $types,
    'tokens' => [
      'mytheme_tokens' => $currentnode_token,
    ],
  ];
}
function mytheme_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata){
  $token_service = \Drupal::token();
  $replacements = array();
  if($type == 'mytheme_tokens') {
    foreach($tokens as $name => $original){
      switch($name){
        case 'current_node_title':
        $node = \Drupal::routeMatch()->getParameter('node');
        $title = (!empty($node)) ? $node->title->value : '';
        $replacements[$original] = $title;
        break;
      }
    }
  }
  return $replacements;
}

```

But in my view in a custom text block I have a header using that token but it spits out

> # \[mytheme\_tokens:current\_node\_title\] Products

And the token isn't replaced. I know for sure the tokenizer is running though because \[site:title\] did work.

How do you create custom globally available tokens?

# Answer
Themes can only implement alter, theme and pre/process hooks.

Re-implement those hooks in a custom module and they should work fine.
> 1 votes

---
Tags: 8, tokens
---


title: Change the "Submitted by" date type?

text:
# Question
Title: Change the "Submitted by" date type?
By default, in Drupal 7, the "Submitted by" date type is set to Medium. I want the "Submitted by" date to be rendered using a different type. How do I do this?

# Answer
It's hard-coded into `template_preprocess_node()` so to override it you'll need to implement your own preprocess function, either in a theme or custom module:

```
function MYTHEME_preprocess_node(&$vars) {
  if (variable_get('node_submitted_' . $vars['node']->type, TRUE)) {
    $date = format_date($vars['node']->created, 'date_type');
    $vars['submitted'] = t('Submitted by !username on !datetime', array('!username' => $vars['name'], '!datetime' => $date));
  }
}

```
> 7 votes

# Answer
also If you wont(or couldn't) do it in theme(for any reason) .You can do it in your custom module.

```
function yourmodule_preprocess_node(&$variables) {

   $variables['date']= format_date($variables['created'] ,'your date format');
   $variables['submitted'] = $variables['date'] . ' — ' . $variables['name'];
  }

```
> 2 votes

# Answer
you can go to admin/config/regional/date-time/formats and add a new format using PHP date formats http://php.net/manual/en/function.date.php

then go to admin/config/regional/date-time and change Medium to your new added format.
> 0 votes

# Answer
The glazed theme does it as such:

```
// BLOG NODES
  if ($vars['type'] == 'blog') {
    $_created_date = format_date($vars['node']->created, 'custom', 'M j, Y');
    $vars['submitted'] = '<em class="text-muted">' . $_created_date . ' ' . t('By') . ' </em> <span class="glazed-util-text-uppercase">' . $vars['node']->name . '</span>';
  }

```
> 0 votes

---
Tags: 7, theming, datetime
---


# Question
Title: Can we use double quotes for strings inside t()?
Is it correct what said in the comment #7 for Usernames allow @ symbol?

> t() value should write in single quotes not in double quotes.

# Answer
> 1 votes
A string is a string... PhP allows strings to be defined four ways, but the two that apply here are 'xxx' and "xxx"... both are valid strings that will be passed to the t() function. The function cannot determine how the string variable was created, it only gets the content between the delimiters. So you can use either one.

That said, some people like the convention of using single quotes for straight constant strings since '$foo' = $foo... while "$foo" = value of $foo. AFAIK, Drupal coding standards do not specify what can be used for a string.

Adendum: Note that the string being passed to the t() function should be a static string in order to be translatable. E.g. if you use "$foo", this would be impossible to translate. That's what the placeholders are for.

# Answer
> 1 votes
The first argument of `t()` needs to be a literal string. Using single quotes or double quotes as string delimiters doesn't make any difference for PHP, but the Drupal coding standards says the following, about using quotes. (Emphasis is mine.)

> Drupal does not have a hard standard for the use of single quotes vs. double quotes. Where possible, keep consistency within each module, and respect the personal style of other developers.
>
> With that caveat in mind, **single quote strings should be used by default**. Their use is recommended **except in two cases**:
>
> 1. Deliberate in-line variable interpolation, e.g. `"<h2>$header</h2>"`.
> 2. **Translated strings** where one **can avoid escaping single quotes by enclosing the string in double quotes**. One such string would be "He's a good person." It would be 'He\\'s a good person.' with single quotes. Such escaping may not be handled properly by .pot file generators for text translation, and it's also somewhat awkward to read.

Since the literal string is `"Several special characters are allowed, including space, period (.), hyphen (-), apostrophe ('), underscore (_), and the @ sign."` and it contains an apostrophe, by the second point it should be delimited by double quotes.

# Answer
> 0 votes
There are several aspects to this question:

1. PHP of course allows allows either quote style, so it doesn't matter to the actual code.
2. The syntax of `t()` calls does matter more than usual in PHP, because they are parsed by static analysers to extract translation strings and generate `.po` files. However, this parser also allows either quote style. (The argument does have to be a single fixed string without variables or concatenation, though.)
3. In this specific case, it's about a core patch, where strict code-style standards come in. Drupal recommends single-quotes wherever possible, with two exceptions, which brings us to:
4. One exception is quotes containing apostrophes/single-quotes, as double quotes let you avoid backslashes. As the particular example *does* contain an apostrophe, the double quotes are justified.

---
Tags: users
---


# Question
Title: Drush not working on Multisite with Shared User Table
I have a Drupal 7 Multisite Environment with sub-directories.

(E.g):

* mainsite.com
* mainsite.com/multisite1
* mainsite.com/multisite2
* mainsite.com/multisite3
* etc.

Each website has its own Database and all are on the same Database Server

I recently configured the multisites to have a Shared User table along with a few shared custom User fields and that aspect works.

However, I am now unable to use Drush within the Multiste directories.

Previously, I would CD into the directory and be able to run Drush commands for that specific multisite like this:

```
cd /var/www/mainsite.com/sites/multisite1
drush cc all

```

Now it tells me that "No Drupal site found".

When I comment out the prefix portion of my settings.php file, Drush works again.

How can I make Drush work for these sites?

Below is what my settings.php file looks like:

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => '[Multisite DB]',
  'username' => '[Database Username]',
  'password' => '[Database Password]',
  'host' => '[DB Server IP]',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',
  'prefix' => array(
        'default'   => '[Multisite DB].',
        'users'     => '[Main Site DB].',
        'sessions'  => '[Main Site DB].',
        'role'      => '[Main Site DB].',
        'authmap'   => '[Main Site DB].',
        'users_roles'   => '[Main Site DB].',
        'field_data_field_first_name'   => '[Main Site DB].',
        'field_data_field_last_name'   => '[Main Site DB].',
        'field_data_field_title'   => '[Main Site DB].',
  ),
);

```

# Answer
> 0 votes
The solution ended up being very simple.

I just had to change one line.

I changed this:

```
        'default'   => '[Multisite DB].',

```

to:

```
        'default'   => '',

```

This is how it looks all together.

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => '[Multisite DB]',
  'username' => '[Database Username]',
  'password' => '[Database Password]',
  'host' => '[DB Server IP]',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',
  'prefix' => array(
        'default'   => '',
        'users'     => '[Main Site DB].',
        'sessions'  => '[Main Site DB].',
        'role'      => '[Main Site DB].',
        'authmap'   => '[Main Site DB].',
        'users_roles'   => '[Main Site DB].',
        'field_data_field_first_name'   => '[Main Site DB].',
        'field_data_field_last_name'   => '[Main Site DB].',
        'field_data_field_title'   => '[Main Site DB].',
  ),
);

```

I know that a lot of people use Bakery or are already on Drupal 8, but I hope this helps anyone still on Drupal 7 looking to share a User table across multiple websites with different databases.

---
Tags: users, drush
---


# Question
Title: How to Lazyload any src object in node body
Currently using Blazy on Drupal 8. What I am trying to do is figure out how to lazyload any image, iframe, mp4 found in the body.

I think I have found a good solution as seen here: https://www.drupal.org/project/blazy/issues/2912992

But how do I implement it. I am stuck at step 4.

# Answer
> 1 votes
I think he means to add this to **mytheme.theme**

```
/**
 * Implements hook_page_attachments_alter()
 */

function MYTHEME_page_attachments_alter(array &$attachments) {
    $attachments['#attached']['library'][] = 'blazy/load';
}

```

---
Tags: theming, hooks, media
---


title: How do I capture a page as HTML?

text:
# Question
Title: How do I capture a page as HTML?
I have a controller that generates a custom 500 page. I have set up a route at the path: '/500'. I would like to capture this as HTML and save as a static file, so that I don't need to bootstrap Drupal and run that controller when I return a custom 500 page.

I have been using this code:

```
  global $base_url;

  $contents = file_get_contents($base_url . "/500");

```

This works for me locally, but we have a lot of restrictions on our QA site so that file\_get\_contents is blocked.

Is there another way to render the entire page that this controller would return? For example, with the render service?

Also, I would want it in a logged-out context. I wouldn't want the admin toolbars, etc. to show up.

I found some code about subroutines. Is that a good way? I'm sure there's a way to use the Drupal render service to render a render array with the entire page. That sounds maybe the best way to do this?

Does anyone know how I might render the entire page programmatically?

I'm thinking in order to render the metadata and page classes based on a route, you're pretty much required to make a request.

There is another question about rendering parts of the page, but not the entire page.

# Answer
If you bootstrap Drupal, you can just tell it to serve a particular page. Consider the content of `index.php`:

```
<?php
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

```

If you replace the Request::createFromGlobals with a `new Request(...)`, you can pass explicit values for the `$_GET` etc parameters. The function signature copied from Symfony is as follows:

```
/**
 * Constructor.
 *
 * @param array           $query      The GET parameters
 * @param array           $request    The POST parameters
 * @param array           $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
 * @param array           $cookies    The COOKIE parameters
 * @param array           $files      The FILES parameters
 * @param array           $server     The SERVER parameters
 * @param string|resource $content    The raw body data
 */
public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
    $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
}

```

So your custom script could require the autoloader, bootstrap Drupal, create a fake Request object, tell Drupal to handle it, then save `$response->getContent()` to a file.
> 0 votes

---
Tags: theming, 8, page-controller
---


# Question
Title: Notification of new comments for author and comment writers
I'm trying to implement a rule (in D7) that will automatically (no check box or opting out):

1. send an email to the author of node if new comments
2. send email to all users who have commented on that node
3. **not send** email to author of own comment

I did find instructions for one of the above, but not for all of them in the same rules. And this is where I failed.

Any help?

# Answer
Have a look at this rule (in Rules export format), which does what you're asking for:

```
{ "rules_notify_users_about_new_comment" : {
    "LABEL" : "Notify users about new comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "comment" ],
    "ON" : { "comment_insert" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E" },
          "PROVIDE" : { "variable_added" : { "users_to_notify" : "Users to notify" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "comment:node:comments" ] },
          "ITEM" : { "current_comment_item" : "Current comment item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT data_is" : {
                      "data" : [ "current-comment-item:author" ],
                      "value" : [ "comment:author" ]
                    }
                  },
                  "DO" : [
                    { "list_add" : {
                        "list" : [ "users-to-notify" ],
                        "item" : [ "current-comment-item:author" ],
                        "unique" : "1"
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "comment:author" ], "value" : [ "comment:node:author" ] } },
            "DO" : [
              { "list_add" : {
                  "list" : [ "users-to-notify" ],
                  "item" : [ "comment:node:author" ],
                  "unique" : "1"
                }
              }
            ]
          }
        ]
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users-to-notify" ] },
          "ITEM" : { "current_user_to_notify" : "Current user to notify" },
          "DO" : [
            { "mail" : {
                "to" : [ "current-user-to-notify:mail" ],
                "subject" : "New comment to node with id [comment:node:nid]",
                "message" : "There is a new comment added to the node with id [comment:node:nid]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

I translate the "... *in the same rules* ..."-part of your question like "I want it to be a single (monolitic) rule". For that you'll need an additional module, i.e. the Conditional Rules module, while the above rule does use a few of the more advanced techniques available in the Rules module.

If you're familiar with reading/digesting Rules in Rules export format, I'd hope the rule is self explaining. If not here is a summary of the above rule:

* Rules Event: obvious ... After saving a new comment.
* Rules Conditions: feel free to add whatever fits (eg limit to selected content types only).
* Rules Actions:

1. Add a variable "`users_to_notify`" (= a list of users).
    2. Loop over all existing comments, and for each comment author, check that it is not the user who just created the comment (which you can check if you have the Conditional Rules module enabled). If that's the case, then add that user to the list of users (= `users_to_notify`).
    3. If the comment author differs from the node author (which you can check if you have the Conditional Rules module enabled), then also add the node author to the list of users (= `users_to_notify`).
    4. Loop over the list of users (= `users_to_notify`) ... again, which we just created and populated). And for each user in that list, do your thing, in this case "send an eMail". The "To" value is crucial here, the body, the from, the title, etc is up to your own imagination.

If you don't want to use the Conditional Rules module, you could also rework the Rules Actions that require this module to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?").

If you want, just import the above rule in your own site (using the Rules UI, which should be enabled to do so), but only after you enabled the Conditional Rules module.

That's really all it takes ... a Rules variable, Rules lists and loops, and Conditional Rules.

Note that the above rule does actually more as compared to what is asked here:

* As per the "`unique`" in Rules Action nr 2, it will not create duplicates in that list of users, to avoid the same user would receive duplicate eMails (i.e. **if a user commented multiple times**).
* As per the "`unique`" in Rules Action nr 3, it will not create duplicates in that list of users, to avoid the node author would get duplicate eMails (i.e. **if the node author also commented already**).
* This rule will NOT send an eMail if the comment was posted by ... the node author (which seems to me like a contradiction in item 1. and 3. of the question ...). If you disagree on that (i.e. that it should send an eMail anyway: just delete Rules Action nr 3.

### Unit testing the rule

If you want to (unit) test the above rule, you may want to add another Rules Action within Rules Action nr 4. I.e. add some sort of "Show a message on the site" (located within Rules group "System"), to produce a message for each user included the list of users (= `users_to_notify`).

That way, if for some reason your site has not been correctly configured yet to send eMails, those messages will help you confirm that the rule itself is not the cause of that.

### Video tutorials

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. Especially these tutorials, which are related to subject of this question:
> 1 votes

---
Tags: rules, comments, notifications
---


title: Why am I getting this error?

text:
# Question
Title: Why am I getting this error?
I am getting this error.

> Call to undefined function feeds\_node\_prepare() in dkan\_datastore\_node\_update() (line 307 of /dkan/dkan/profiles/dkan/modules/dkan/dkan\_datastore/dkan\_datastore.module).

What could be causing the error? Could it be a module interfering with function?

# Answer
> 1 votes
This issue is referenced in Dkan developpers Google group.

You probably have updated Feeds modules in Dkan profiles folder? Read the above post carefully and consider trying proposed solution :

* Keep the Dkan profile original code in place
* Download Feeds 7.x-2.0-beta4 to sites/all/modules/contrib
* Rebuild registry

**EDIT :** I browsed both Feeds and Dkan feeds.module history. I couldn't find any implementation of `feeds_node_prepare()` in Feeds, while Dkan contrib feeds.module does implement it.

Seems that Feeds in DKAN profile contrib modules directory is a fork, not official release.

---
Tags: 7
---


# Question
Title: Why is my migrate source plugin (d7_file) not found for my migration?
I'm trying to write a migration for files from an old D7 site to a new D8 site, roughly following the instructions at https://www.previousnext.com.au/blog/migrating-drupal-7-file-entities-drupal-8-media-entities.

I have a myproject\_migration module which includes the migration in its install folder.

myproject\_migration.info.yml:

```
name: MyProject Migration
description: Migrations for existing MyProject content.
package: myproject
type: module
core: '8.x'
dependencies:
  - file
  - migrate
  - migrate_plus
  - migrate_source_csv
  - migrate_tools

```

config/install/migrate\_plus.migration.furniture\_files.yml:

```
id: files
label: Files from the old D7 site.
migration_group: myproject
dependencies:
  enforced:
    module:
      - myproject_migration
      - file
source:
  plugin: d7_file
  scheme: public
  constants:
    source_base_path: /
process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
  #uid: uid
destination:
  plugin: 'entity:file'

```

I enable the module; run `drush migrate-status` and get:

```
exception 'Drupal\Component\Plugin\Exception\PluginNotFoundException'
...with message 'The "d7_file" plugin does not exist.'
...in /var/www/myproject/docroot/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php:52
Stack trace:
#0 /var/www/myproject/docroot/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryCachedTrait.php(25):
Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition(Array, 'd7_file', true)
#1 /var/www/myproject/docroot/core/modules/migrate/src/Plugin/MigratePluginManager.php(53):
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('d7_file')
#2 /var/www/myproject/docroot/core/modules/migrate/src/Plugin/Migration.php(335):
Drupal\migrate\Plugin\MigratePluginManager->createInstance('d7_file', Array, Object(Drupal\migrate\Plugin\Migration))
#3 /var/www/myproject/docroot/modules/contrib/migrate_tools/migrate_tools.drush.inc(471): Drupal\migrate\Plugin\Migration->getSourcePlugin()
...

```

I've been importing updates to this config with `drush config-import --partial -y --source=modules/custom/myproject_migration/config/install/`.

I can see the plugin in core\modules\file\src\Plugin\migrate\source\d7\File.php, with the id "d7\_file". Running through the checklist at https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins \- it implements MigrateSourceInterface; it's annotated with @MigrateSource; it's in in the namespace subdir Plugin\migrate\source under the "file" namespace. So it's definitely there, and everything looks right, it's just not found.

# Answer
> 5 votes
Make sure the `migrate_drupal` module is enabled. (I can't be sure that's the reason, but it's the first one I stumbled over when I reproduced this locally.)

The reason this isn't easy to see:

Migrate plugins have multiple providers (which must all be enabled to use the plugin), and the relevant plugin managers actually use their own discovery which automatically infers providers from the parent class namespace. So the d7\_file plugin has the providers "file" and "migrate\_drupal" as it is provided by the file module but extends a class from the migrate\_drupal module.

In effect, migrate's multi-provider thing adds "invisible" dependencies which silently remove the plugin when the required modules aren't installed.

---
Tags: 8, migrations
---


title: Does db_query support UNION?

text:
# Question
Title: Does db_query support UNION?
I have a query that contains a UNION operator. If I ran my query it runs perfectly straight on the database but I am getting an empty result in Drupal.

Here is a simplified version of the query:

```
$result = db_query("
    SELECT *
    FROM (
    SELECT
    agent_number
    FROM table1
    WHERE agent_number IN (':agent_numbers')
    UNION
    SELECT
    agent_number
    FROM table2
    WHERE agent_number IN (':agent_numbers')) t", array(
      ':agent_numbers' => $agent_ids,
    )
  )->fetchAll();

```

Is it that `db_query()` doesn't support UNION?

# Answer
Yes, db\_query() does support UNION. I had a problem with my query:

```
WHERE agent_number IN (':agent_numbers')

```

Should be:

```
WHERE agent_number IN (:agent_numbers)

```
> 0 votes

---
Tags: database
---


title: Is there a notification api module?

text:
# Question
Title: Is there a notification api module?
I like to have a general api for sending notification. I am not sure if there is out there somewhere for Drupal.

For instance, is should be possible to provide a node id and some criterias for which users to send notifications to. The options could be something like "not to the node author", "all who has commented on the node except specific ones (perhaps a comments that has just been written), true/false on sending notification to user who already got a notification about new comments, etc.

There are probably other notification scenarios that could be supported. It would be nice with a general notification framework for Drupal. It seems to be lacking right now (I have looked at subscription and notification). However, I am new to Drupal and might have missed something.

# Answer
> 4 votes
There is a Notifications module for Drupal that creates a framework for sending out notifications. There are already many modules using the framework. There's a development version of an extension module called Notifications Rules for integrating this with the Rules module if needed.

# Answer
> 3 votes
If you want to build an automated notification system, you can tap into the Rules module integrated with Notifications.

It has a simple, friendly and flexible UI that enables you to build complex workflows. There's several useful tutorials and use cases in http://dev.nodeone.se/node/634.

# Answer
> 0 votes
Have a look at the Message Stack (available for both D7 and D8), these are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

* Message:

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

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

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

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.

If you'd rather look at an existing module as an example, then checkout the 7.x-4.x version of the Answers module (disclosure: I'm a co-maintainer) and its **Answers Notification** sub-module. This sub-module allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

Since your question is asking for an "API", you should also have a look at the Message\_example module (a submodule of Message). The prezentation "Message Stack in Drupal" may help to get you going with it also.

---
Tags: notifications
---


title: Can kint be used to debug templates?

text:
# Question
Title: Can kint be used to debug templates?
Normally, I can use `kint()` in the place of `dump()` to debug my twig templates. The theming manual agrees.

However, this doesn't work for me in Commerce 2.

In `commerce-product.html.twig`, I added

`{{ kint(product) }}`

And rebuilt the cache.

This caused me to be redirected to the "install" url, with the message "Drupal is already installed".

If I use `{{ dump(product) }}`, I get the expected output, but this array is enormous and hard to read so I want to use kint. Is there something different about variables in Commerce?

If I use `{{ kint(links) }}` and the like in a template copied from core I see the kint output correctly.

# Answer
The object/array is too big for your server resources to handle the default kint settings.

Edit **modules/devel/kint/kint/config.default.php** and set `$_kintSettings['maxLevels']` to a lower number to reduce recursion and the memory needed for dumping variables. The default is 7, I have mine set to 4. If 4 still doesn't work for you, keep lowering the number.
> 5 votes

# Answer
For debug big array, i use first :

```
{{kint($array|keys)}}

```

after i got key i can kint the array with the key. With this method i don’t have memory error.
> 3 votes

---
Tags: 8, commerce, debugging
---


# Question
Title: How to display user related content in views?
I use drupal 7 and views 3. I have a view that display list of users. I want to display for each user related content.

What is the related content? - related content is content (node) that it's field 'field\_uid' value is equal to the user uid.

How can I do it? Thanks in advance

# Answer
It's **not possible** to have relation with a view based on a text field.

I order to achieve that you need to use entityreference module to create reference field, then it would be possible to use it in view relation.

If you have a custom entity and in hook\_schemah you create 'foreign key' then views will identify that in relation.
> 1 votes

# Answer
1. Create a view listing Content(not User entities);
2. Add your "field\_uid" as a relationship;
3. Add "Content: Title" and a "User: Name" marked as a field from the relationship you created earlier check the "Exclude from display".
4. Click on "Settings" in the "Format" section and choose from "Grouping field" your User field added previously.

You should see now your Node title grouped by your User name.
> 0 votes

---
Tags: views
---


# Question
Title: How may I simplify the registration process
I Try to use RNG to allow student user to registrer for company interviews (the events). I set up a View on my event to allow student to register for an interview.

It seems a bit complex because they had to click on a link (register) to a page where they have to click on a create button under a select Identity where there is only one mandatory "My account" radio ?

Is there a better way to do that with RNG, or maybe a more suitable module, I am indeed trying to create a n,n relationship between user and event.

I give a try to basicCart module, but I don't need the order part.

# Answer
> 2 votes
You could do it using Flag and Views.

Once you create a **node flag**, then all the user needs to do is click on the node flag to register to the event/interview.

If you need to know which users have registered for an event, in Views, simply add a relationship of flag (can't remember the exact relationship name, but I am sure you can figure it out, might be "users who flagged").

# Answer
> 1 votes
RNG Quick may be a suitable solution. It adds a block which is visible on the event page, so you don't need to click the 'Register' tab.

# Answer
> 0 votes
The Flag method does work but it bypasses the built-in RNG settings, Those being Limit the number of registrations, Limit the number of registrants and allow duplicate registrations.

Quick Registration Block also works, but some may say it still falls within the "complex" process area.

---
Tags: 8, rng
---


# Question
Title: How to get the translated term name by tid?
I'm looking for a *working method* to **get the translated term name** by `tid`.

The following code returns the original term name *but* not the translation.

```
global $language;

$lang_name = $language->language; // en

$term_id = 788;

$term = i18n_taxonomy_term_get_translation($term_id, $lang_name);

```

Most examples provided in "how to get the translated taxonomy term programmatically?" seem not work for Drupal 7.

# Answer
I managed to make it work! This is my code

```
$tree = taxonomy_get_tree(9); // Your taxonomy id

foreach ($tree as $term) {
  if (module_exists('i18n_taxonomy')) { //To not break your site if module is not installed
    $term = i18n_taxonomy_localize_terms($term); // The important part!
  }
  print l($term->name, 'taxonomy/term/' . $term->tid); //print the terms
}

```

That sould do it! Diadeuf!
> 17 votes

# Answer
You should use the i18n\_taxonomy\_localize\_terms() function. This is the working code for me:

```
$tid = 10;
$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_localize_terms($term);
print $translated_term->name;

```
> 12 votes

# Answer
I had the same problem with localized taxonomy term translations. If you have your "Multilingual options" translation mode set to "Localize", then it's pretty straightforward.

Let's say your term id is 788 like the OP's, then just do something along these lines:

```
  $i18n_object = i18n_get_object('taxonomy_term', 788);
  $target_langcode = 'de';
  $translated_term = $i18n_object->localize($target_langcode);

```
> 12 votes

# Answer
Knibals code shows how to translate a full vocabulary tree. This code snippet shows how to translate one specific term.

```
$term = taxonomy_term_load($tid);
$translated_term = i18n_taxonomy_term_get_translation($term, $langcode);

```

This question was already answered here: how to get the translated taxonomy term programmatically?
> 1 votes

# Answer
If you want to use it as Function..

```
function _get_term_name_translate($tid) {
  $term = i18n_taxonomy_localize_terms(taxonomy_term_load($tid));
  return $term->name;
}

```
> 0 votes

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


# Question
Title: (Field type) Link autocompletion for media entities
How can I enable autocompletion for media entities in Link fields? The Link field seems to "know" only nodes, but no media entities.

### Use case:

I've got a paragraph for a "card style" link consisting of 4 fields for an image, a title, a short description and a link. The paragraph must work for internal and external links, so I'm using a Link field and not an entity reference.

A common task is that editors upload a PDF to the media library, and provide a nice download link to the PDF on multiple nodes, using the paragraph mentioned above.

### Tried this, doesn't work good enough:

I know that it technically would be possible to manually enter a path like `/media/<media_entity_id>`. But this so bad UX that I need to find a better solution.

I also have LinkIt installed, but sadly I can't use LinkIt for Link/URL fields.

(I'm using Drupal v8.4 core media)

# Answer
The short answer: Currently not supported, unfortunately:

```
  // @todo Support entity types other than 'node'. Will be fixed in
  //    https://www.drupal.org/node/2423093.

```

Until https://www.drupal.org/node/2423093 is done, the link field widget can only support a single entity type; so you can have a widget for linking to nodes or to media entities, but not both.

Worse, until https://www.drupal.org/node/2427803 is done, the entity type is hardcoded as `node` and not configurable.

The good news: It's still possible, if you're prepared to write a bit of code.

Other than three lines in LinkWidget that contain a hardcoded reference to `node`, nothing stops the code from working with a different entity type in principle. So as a workaround, you could duplicate the core LinkWidget in a custom module, change the relevant lines to `media` (I made a patch for this at https://gist.github.com/cburschka/b214a52bdb1fdf7349ef3b0afe56b950), and thus create an alternate widget for media links.

This still means you have to choose between either a Node or Media link field, unfortunately. If you don't want to create two different fields, you could use the Paragraphs module in order to create a single Paragraph field that can be filled with one of two paragraph types (one of which exposes the link field with the original widget, and the other with your custom Media widget). It's a bit more complex, but should still provide a decent user experience.

Edit: Alternatively, instead of using the Link module you could use a Dynamic Entity Reference field: https://www.drupal.org/project/dynamic\_entity\_reference

The downside is that this field could then *only* reference entities; external links and non-entity links wouldn't be possible anymore.
> 7 votes

---
Tags: 8, media
---


title: Unit/Kernel tests are not completing

text:
# Question
Title: Unit/Kernel tests are not completing
I am currently unable to run my Kernel tests on my server. I am running the test from within the Drupal UI but they error out with:

```
"PHPunit Test failed to complete; Error:"

```

with a log messages of

```
Notice: Undefined index: error in Drupal\simpletest\Form\SimpletestResultsForm::addResultForm()

```

and

```
The file public://simpletest/verbose was not deleted because it does not exist.

```

# Answer
> 1 votes
I saw this error when phpunit was missing executable permission.

It also failed from the command line, but the error message was clear

> sh: 1: XXX/web/vendor/phpunit/phpunit/phpunit: Permission denied

---
Tags: testing
---


# Question
Title: How to get the operation Links in my own EntityListBuilder
I use the Symfony framework the first time and goes through several tutorials to create an own entity type. https://www.daggerhart.com/drupal-8-custom-entities-bundles/ or https://www.daggerhart.com/drupal-8-custom-entities-bundles/

Now runs all very well, but I didn\`t get the operation links(edit/delete) in every row for the saved content. There is only a devel link. If I moved directly to the content like www.exapmle/mytest/{id}/edit or www.exapmle/mytest/{id}/delete I can saw the content, edit the content, delete the content and the tabs are shown. So I think I have the permission for that.

Any ideas?

mytest.routing.yml:

```
entity.mytest.delete_test:
  path: '/tested/{mytest}/delete'
  defaults:
    _entity_form: mytest.delete
    _title: 'Delete Test'
  requirements:
    _entity_access: 'mytest.delete'

```

mytest.php in src/Entity

```
* @ContentEntityType(
*   id = "mytest",
*   links = {
*     "canonical" = "/tested/{mytest}",
*     "delete-shop" = "/tested/{mytest}/delete",
*     "collection" = "/tested"
*   },
* )

```

# Answer
> 1 votes
Ok, after I found the documentation at drupal documentation I get it! The naming of the link list must be:

```
* @ContentEntityType(
*   id = "mytest",
*   links = {
*     "canonical" = "/tested/{mytest}",
*     "delete-form" = "/tested/{mytest}/delete", // EDIT!
*     "collection" = "/tested"
*   },
* )

```

That's all!

---
Tags: 8, entities
---


# Question
Title: Where is the "add to cart" configuration?
I'm trying to find the **Add to cart** form configuration for a product type in the UI.

When I export configuration, `core.entity_form_display.commerce_order_item.TYPE.add_to_cart.yml` contains the configuration for the **Add to cart** form, such as this (hiding quantity, creation date, and unit price):

```
content:
  purchased_entity:
    type: commerce_product_variation_attributes
    weight: 0
    settings: {  }
    region: content
    third_party_settings: {  }
hidden:
  created: true
  quantity: true
  unit_price: true

```

Where is the configuration page for this in the UI? I keep clicking around and I cannot find it.

# Answer
> 1 votes
Go to the 'Order item types' page and click the "Manage form display" link for your order item type. You will then see a tab for the "Add to cart" form display.

For the 'default' order item type the url will be: /admin/commerce/config/order-item-types/default/edit/form-display/add\_to\_cart

There is an open issue for finding a more discoverable way to expose these settings.

---
Tags: 8, commerce
---


# Question
Title: Form has a div within it. How can I add classes to this div?
There's a div called `.description` in a form in the site I've inherited. I want to add a another class to the div.

The div's content is created within `hook_form_FORM_ID_alter()`, eg:

```
$form['#description'] = 'Please enter your full name';

```

I've tried adding a classed to it like:

```
$form['#description'] = [
    '#markup' => '<div class="my-class">Please enter your full name</div>',
  ];

```

But this just results in "Array" being printed.

Would anyone know what I could do add a class to this element?

# Answer
> 0 votes
That's not what you want. What you want to do is add it to the form structure like this:

```
$form['#attributes']['class'][] = 'my-class';

```

Since you didn't list an element on the form, I can only assume you want the class on the form itself. If you want to wrap an element with a div with a class on it, you can do:

```
$form['element']['#prefix'] = '<div class="my-class">';
$form['element']['#suffix'] = '</div>';

```

That will wrap the entire element.

---
Tags: 7, forms
---


# Question
Title: Is there a way to create a Rules component programmatically?
Is there a way to programmatically create a Rules component?

I mean a component like the ones listed on `/admin/config/workflow/rules/components`.

# Answer
Rule components can be programmatically created- although they can be quite cumbersome to code from scratch. I'd recommend building a component with some conditions, actions, and rulesets and exporting it. Then you can analyze the exported php to determine how to define your custom component set.

You'll most likely want to reference:

1. A list of the hooks available for the D7 version of the Rules module can be found here: http://www.drupalcontrib.org/api/drupal/contributions%21rules%21rules.api.php/group/rules\_hooks/7
2. A good set of Developer Documentation for custom rules (albeit an old set of documentation for the D6 version of Rules) can be found here: https://www.drupal.org/node/298486
> 0 votes

---
Tags: 7, rules
---


# Question
Title: What does it mean "Rebuilding" in a feature? Can it be resolved?
I did some changes in my local environment, then I updated the 'feature'.

When I try to deploy the change to another environment, but before I can start the 'revert' operation, some parts of the feature are marked as 'Rebuilding'.

The feature components are: \- Field bases \- Field instances \- Strongarm

Additional details

* I cannot use drush in the deployment environment.
* This happened once in the past and it resolved itself after clearing the caches.

# Answer
Drupal's "Features" reflect a status of:

* rebuild when rebuilding database for latest code for unoverriden features
* revert when rebuilding database for latest code for any state features

Rebuilding updates features that are not deliberately overridden for latest code changes. It works during cache clear but can be slow if there are several features enabled on the site, and if there is a lot to clear in Drupal's caches.

If the server/cache clear and rebuild process are interrupted and freeze up, you may need to reset the lock on the feature state. See https://www.drupal.org/node/928730

If you find this happens frequently, try increasing the mysql timeout and php memory limits.

You may also want to refer to this troubleshooting post about "overridden" features: https://www.drupal.org/docs/7/modules/features/troubleshooting-reasons-features-may-be-stuck-as-overridden
> 1 votes

---
Tags: 7, features
---


# Question
Title: Fatal error while editing and deleting menu items
Facing one issue in deleting the menu items on my Drupal 8 Site.

**Steps to reproduce:**

Add a link to main menu.

Create Child terms under one link.

Delete the parent term.

After deleting the parent link child links stays they don't get deleted automatically.

If you want to edit/manually delete those links then a Fatal error is
coming.

**Error Message : Drupal\Component\Plugin\Exception\PluginNotFoundException: Plugin ID 'menu\_link\_content:adad91f8-19c7-48c7-a88e-67aae4edd21e' was not found. in Drupal\Core\Menu\MenuLinkManager-\>getDefinition() (line 207 of /var/www/crain-platform/docroot/core/lib/Drupal/Core/Menu/MenuLinkManager.php).**

After doing some debugging i see the menu data missing from menu\_link\_content table.Anyone have any idea why this is coming and how to fix this issue?

# Answer
> 0 votes
This error was coming because of responsive menu module.Responsive menu was fetching the parent links using

```
\Drupal::service('plugin.manager.menu.link')->createInstance($parent);

```

Adding the condition before calling createInstance will fix this issue.

```
\Drupal::service('plugin.manager.menu.link')->hasDefinition($parent)

```

Created a issue on D.o also

https://www.drupal.org/project/1786786/issues/2924229

---
Tags: 8, navigation
---


# Question
Title: How do I update a field value in hook_entity_insert()?
I want to update an field in `hook_entity_insert()`. The following code doesn't work.

```
$entity->field_range->value = 'test';
$entity->save();

```

I also tried loading from node object, but still it doesn't work.

```
$node = \Drupal::entityManager()->getStorage('node')->load($entity->id());
$node->set('field_range', 'test');
$node->save();

```

After inserting the node only I will get the text "test" dynamically and it won't work in `hook_entity_presave()`.

Any help on how to update an field on hook\_entity\_insert will be nice. Thanks in advance.

# Answer
> 4 votes
From this solution we can able to do like below to update an field on hook\_entity\_insert

```
$entity->field_range->value = 'test';
drupal_register_shutdown_function('_cc_custom_post_insert',$entity);

function _cc_custom_post_insert($entity) {
    if($entity) {
        $entity->save();
    }
}

```

# Answer
> 2 votes
You can use hook\_ENTITY\_TYPE\_presave as in hook\_ENTITY\_TYPE\_update

When saving existing entities, the entity is assumed to be complete, partial updates of entities are not supported.

```
use Drupal\node\NodeInterface;

function mymodule_node_presave(NodeInterface $node) {
  switch ($node->getType()) {
    case "article":
      $node->set('field_range', 'test');
      break;
  }
}

```

Here no need to load node.

---
Tags: 8, hooks
---


# Question
Title: Display "uncaught exception" page as content-type text/html
When there is an uncaught exception, Drupal 8 displays a simple dump of the exception.

I find that the page is served as 'Content-Type' = 'text/plain', yet it contains HTML:

It looks better to me when I change the code to serve as 'text/html':

I already found the code to change - it's in FinalExceptionSubscriber.php, which outputs

> Formats a string for HTML display by replacing variable placeholders.

My question is:

1. Does anyone know a reason why the error page is text/plain given that it contains HTML.
2. Shall I raise an issue and patch?

# Answer
Thanks @4k4, so it seems that this is a minor bug, but the obvious fix would revert the "Standardize handling" issue.

I have raised this issue and linked it to the other issue. I don't really understand the code here and would welcome any help to improve the issue text.
> 0 votes

---
Tags: 8
---