# Question
Title: Installing require-dev dependencies from core/composer.json
I understand the composer-merge-plugin allows the Drupal root composer.json file to load core/composer.json on runtime. I also understand `require-dev` will only pull dependencies for the root composer.json file (see this link).

How can I force one/all core/composer.json dependencies (including the required-dev ones) to be pulled if I want without hacking the root composer.json file e.g. with a `composer require vendor/package`?

# Answer
> 1 votes
By default, Composer will install also the development requirements, if you don't use the `--no-dev` option.
I ran `composer create-project drupal/drupal test 8.3.*@dev`, and in the output of the command I could see the following:

> Installing drupal/drupal (8.3.x-dev 8a84ec5556f354861f1ddc5d7a80081b91ca42df)
> \- Installing drupal/drupal (8.3.x-dev 8a84ec5)
> Cloning 8a84ec5556 from cache
> Created project in test
> Loading composer repositories with package information
> Installing dependencies (including require-dev) from lock file
> Package operations: 76 installs, 0 updates, 0 removals
>
> \[Omissis\]
>
> * Installing drupal/coder (8.2.11) Downloading: 100%
> * Installing phpunit/phpunit (4.8.28) Downloading: 100%

If you downloaded the archived release for example from https://www.drupal.org/project/drupal/releases/8.2.7, which doesn't include the development requirements, you need to run `composer update` from the directory containing core and composer.json.
I tested `composer update --dev` after removing the vendor directory from the test directory created from the previous command, and I got this output:

> You are using the deprecated option "dev". Dev packages are installed by default now.
> Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Package operations: 76 installs, 0 updates, 0 removals

---
Tags: 8, composer
---


title: include social media in view page

text:
# Question
Title: include social media in view page
I'm using the**Social media** module to share in linkedin, facebook. I have installed the **Widgets** module. I want to include this to created field 'Linkedin\_share'(image type).

Shall I need to add separate field for share? How to include this social media in view page.

# Answer
> 0 votes
There is sharethis contrib module. You can use this module to share contents in lots of social media.

Also, this module can be used as block, content field and links area.

So, you can put a sharethis block in a view.

Here's what you need to do.

1. Install & enable module.
2. Under Configuration \> web services, configure sharethis settings. (For the view, you should check block under content at the bottom)
3. In block settings, place sharethis block on content region.
4. Configure the sharethis block to only show it on the view.

---
Tags: 7, views
---


title: How to add a class to a pager?

text:
# Question
Title: How to add a class to a pager?
I would like to add bootstrap classes to a load more pager, with the views load more module. I am currently using javascript to add it on, but the moment I change the view the classes are no longer there. I assume I have to use theme\_preprocess\_item\_list() but I'm not quite sure how to go about this.

# Answer
Nevermind, got it working by using the template\_views\_load\_more\_pager. I was just using the wrong function name. Found it in the views load more module.
> 0 votes

---
Tags: 7, views, paging
---


# Question
Title: Using Docker4Drupal in Production vs. its commercial Wodby solution
I've been playing with https://github.com/wodby/docker4drupal on a DigitalOcean droplet and am utterly amazed at how it all works.

However, it recommends that people use https://wodby.com/ for production and I'm wondering if I have to; it seems like an unnecessary step when my testing has four sites running perfectly in "production mode".

Does anybody know in what way Docker4Drupal is designed to be run in a local environment when it seems so well on a regular server?

This isn't a question of money.. Just effort. I'm a one man show and don't need dev/staging/production for what I'm working on right now.

# Answer
> 10 votes
Disclosure: I'm a Docker4Drupal maintainer and Wodby co-founder.

We do not limit usage of our images, it's MIT licensed, so if you want - go ahead and deploy the images in production. However, you'll have to do some work before that, e.g. set up a router, certificates, cron, etc. Configuring usual stuff with containers is not always obvious especially if you're not proficient with containers. Since we already handle all of this in our platform we've added this recommendation (people asked us about production). Also, stability requirements are higher for production (including freezing the docker version).

Originally, we created docker4drupal just to provide a local environment for our customers (instead of connecting Vagrant) but later it became obvious that it is valuable for many drupalers including those who do not use Wodby. In other words, historically, it was prod \> local transition, not the other way around.

---
Tags: 7
---


title: How to exclude nodes from result?

text:
# Question
Title: How to exclude nodes from result?
I have a view with one field that shows rendered nodes, and a contextual filter (multiple values allowed) that provides the nids that should be used in the view.

Each node (with nid from the context filter) contains a node reference field with multiple values (nids of related products).

My problem is that a number of these related products, are in fact unpublished nodes. So how can I exclude these unpublished nodes from showing up in the views result? Just adding the filter `Published = Yes` does not work since the field in the view always is published. It is some of the rendered nodes, produced by that field, that in their turn are unpublished.

UPDATE: in a custom module I have now added this snippet:

```
function mymodule_views_post_execute(&$view) {
  if ($view->name === 'my_view' && $view->current_display === 'related_products') {
    foreach ($view->result as $result) {

      foreach($result->field_field_add_products as $key => $product){
        if($product['rendered']['#node']->status == 0){
          unset($result->field_field_add_products[$key]);
        }
      }
    }
  }
}

```

...and this does actually exclude the unwanted products. BUT they don't just leave gracefully. They leave a gap in the (repsonsive) grid that I use to show these products. How do I exclude them AND the space they occupy in my views grid?

UPDATE: this is my PHP snippet in the contextual filter:

```
$node = menu_get_object();
$value = null;
if(empty($node->field_lagg_till_givargrupp['und'][0]['nid'])){
    $node->field_lagg_till_givargrupp['und'][0]['nid'] = NULL;
    return FALSE;
} else {
    $groups = $node->field_lagg_till_givargrupp['und'];
    foreach($groups as $group){
        $group_nid = $group['nid']; // hämta node-id
                $value .= $group_nid.",";
    }
    return rtrim($value, ",");
}

```

It works well and supplies the nids wanted (the node ids for the nodes with multiple products grouped in node reference fields).

And this is a partial screenshot of the view:

I use the field `Innehåll: Titel` (Content: Title) to group the result by the title of each product group. The field `Innehåll: Koppla givare` (Content: related products) produces all the nodes present in the node reference fields. If there are 20 products entered in that multiple value field, I will have 20 rendered nodes as a result, of which some are not publised. See the resulting view below. The gaps are unpublished nodes that I succeeded in excluding with my snippet above.

So how do I rebuild the view result so that there are no gaps?

# Answer
Ok, so this was in fact very simple... though it took me a great deal of time to find the solution. I removed the snippet in the custom module above and instead I added the code below in template.php. Hope it helps somebody. I found the solution here: http://agaric.com/blogs/altering-views-results

```
function mytheme_views_pre_render(&$view) {
if ($view->name === 'myview' && $view->current_display === 'mydisplay') {
        foreach($view->result as $index=>$val){
          $product_node = node_load($val->field_data_field_related_product_nid);
          if($product_node->status === '0'){
             unset($view->result[$index]);
          }
        }
    }
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to setup "drush @mysite.env ssh" command?
I am trying to create a custom drush command in which I have to access another remote environment and run some drush commands there. The problem is I am unable to ssh to another environment e.g, "dev" etc. I am able to run

```
drush @mysite.env status

```

but when I try

```
drush @mysite.env ssh

```

then I get this error

```
PTY allocation request failed on channel 0
Command not supported as typed.
An error 255 occurred while running the command `ssh -p 2222 -o AddressFamily inet"

```

"pantheon.aliases.drushrc.php" is placed in "~/.drush" folder.

Please let me know what's missing.

Thanks

# Answer
> 3 votes
Pantheon does not support ssh access to your server. Write your own Drush command, place it in the `drush` folder at your repository root, and call it with `drush @mysite.env mycommand`.

---
Tags: drush, ssh
---


# Question
Title: How do I auto generate products via attribute?
I have a shoe store, as you know, Drupal Commerce allow us to control each Attribute of Shoe like Color and Size.

This is my problem :

I have 2000 shoe styles, each style has sizes from 5-12 (6US to 12US) It mean that everytime I add new style, I have to create 8 products for 8 sizes. Im using Clone Product Module, it's working very well, but how can I save my time :

It mean that when I create New Shoe Style (Node Products Display) --\> node/add/shoe-style --\> the system will auto generate 8 products (Size) for me, it depend on how many value in my attribute field (Size attribute has 8 value and system will create 8 new product), and now what we need to do is update something to each product.

# Answer
Assuming you are using Drupal 7, you've got a couple of options:

1. Commerce Migrate will let you create products as part of a migration. It's a bit more time consuming but it's repeatable and is very powerful.
2. You can use Commerce Bulk Product Creation to create products based off of fields in the UI. This gives the ability to create those products once and isn't repeatable.
> 1 votes

---
Tags: commerce
---


# Question
Title: conceptual question about updating GET url
I am sorry if this question was asked before, but I am getting hard time with a concept of changing url parameters that was created by GET form in Drupal 8. Here what I have done so far and what I want to do.

```
http://example.com/advancedsearchresult?keyword=&title=&description=&author=&location=&from=0&to=0&collection=0&media=all

```

so as you can see media=all and it displays:

It displays my query results with all the media type such as PHOTO,VIDEO,DOCUMENT OR AUDIO.

So here what I want to do, I want my URL to be updated to the specific media type and display that media type results entirely when the user clicks that result number. For instance when the user clicks 42 results next to PHOTO, I would like to update my url to media=photo.

I tried to solve it on template level in twig via:

```
 https://chromatichq.com/blog/creating-links-within-twig-templates-using-path-and-url

```

But I wasn't successful.

Can anyone lead me to a good solution for this?For your information, I am very new to Symfony and Drupal 8(I hope my question is not vague)

Update: Sharing my code On my service I run my query in form with:

```
public function getResults() {

$query = $this->entityQuery->get('node');
$query->condition('type', 'item')
      ->condition('status', NODE_PUBLISHED);

if (!empty($this->getKeywords())) {
  $query->condition('field_keywords.target_id', $this->getKeywords(), 'IN');
}

if (!empty($this->getTitle())) {
  $query->condition('title', '%'.$this->getTitle().'%' ,'LIKE');
}

if (!empty($this->getDescription())) {
  $query->condition('field_physical_description.value', '%'.$this->getDescription().'%' ,'LIKE');
}

if (!empty($this->getAuthor())) {
  $query->condition('field_author_photographer.value', '%'.$this->getAuthor().'%' ,'LIKE');
}

if (!empty($this->getLocation())) {
  $query->condition('field_location.value', '%'.$this->getLocation().'%' ,'LIKE');
}

if ( $this->getFrom() != '0'){
  $query->condition('field_date.value',  $this->getFrom(), '>=');
}

if ( $this->getTo() != '0'){
  $query->condition('field_date.value',  $this->getTo(), '>=');
}

if ( $this->getCollection() != '0') {
  $query->condition('field_collection.target_id', $this->getCollection(),'IN');
}

if ( $this->getMedia() != 'all') {
  $query->condition('field_media_type.value', $this->getMedia());
  $query->pager(32);
}

return $query->execute();

```

}

then call pass these results to my controller here:

```
public function result_page() {
$this->getParameters();
$results = $this->advancedsearchSearchResult->getResults();

$nodes = \Drupal\node\Entity\Node::loadMultiple($results);

$search_result = [];

foreach ($nodes as $key=>$node) {
  $media_value = $node->get('field_media_type')->getValue();
  $media_string = $media_value[0]['value'];
  $search_result[$media_string]['title'] = $media_string;
  $search_result[$media_string]['results'][] = node_view($node, 'teaser');
}

$results = [
  '#theme' => 'advancedsearch',
  '#search_result' => $search_result,
  '#attached' => [
    'library' => [
      'advancedsearch/advancedsearch'
    ],
  ],
];

 return $results;
}

private function getParameters() {
$params = \Drupal::request()->query->all();

$detail_url = Url::fromRoute('advancedsearch.search_result_controller_result_page',$params);

$this->advancedsearchSearchResult->setKeywords($params['keyword']);
$this->advancedsearchSearchResult->setTitle($params['title']);
$this->advancedsearchSearchResult->setDescription($params['description']);
$this->advancedsearchSearchResult->setAuthor($params['author']);
$this->advancedsearchSearchResult->setLocation($params['location']);
$this->advancedsearchSearchResult->setFrom($params['from']);
$this->advancedsearchSearchResult->setTo($params['to']);
$this->advancedsearchSearchResult->setCollection($params['collection']);
$this->advancedsearchSearchResult->setMedia($params['media']);

}

```

then pass that variable into twig template.

# Answer
> 1 votes
In my opinion too much of code.

All you need is just to get parameters from URL `$params = \Drupal::request()->query->all();` . Pass parameters to your `getResults()` function to make query with parameters as conditions. Return results to the Controller and and pass them to twig template.

You don't need setters and getters for parameters here. Just pass them to the query and use in conditions:

```
private function getResults($parameters) {
//...
$query->condition('field_media_type.value', $parameters['media']);
//...

}

public function result_page() {
//...
$parameters = \Drupal::request()->query->all();
$results = $this->getResults($parameters);
//...
}

```

---
Tags: 8, routes
---


# Question
Title: Append image style to an inline image in CKEditor
With views, for example, I'm able to set the image size which is to be loaded (using image styles). Is it in any way possible to do such thing in CKEditor? At the moment, Drupal is loading the original image and scales it down in the browser. I need to set an image style so all the inline images are resized to a width of x pixels.

# Answer
Use insert module

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
>
> This module was previously known as FileField Insert.
>
> Features
>
> ```
> Support for all major WYSIWYG editors, including tinyMCE, CKeditor, the WYSIWYG project (the recommended approach), and plain
>
> ```
>
> text areas. Insert images using ImageCache presets Maximum width setting for inserted images (for combined use with the Image Resize Filter module) Per-field insert configuration

I used that on drupal 7 in several projects and it's what you want.I don't used Drupal 8 version yet,but hope works well.

Hopefully, in **Drupal \>= 8.8** it's on the core.

https://www.drupal.org/docs/8/core/modules/media-library-module/embedding-media-with-ckeditor
> 1 votes

# Answer
There are a lot of modules around:

* You really should use entity\_embed, it's quite out of the box, optionally with the file\_browser or even more sophisticated with the media\_entity. (Could also be used in combination with core's responsive images)
* Layouter let's you insert one file in a layout, choosing the image style .. Insert has a similar approach. (see answer from @zhilevan)

> I'm not so friend with this approach, as it can be messed up by the user while re-editing.
* IMCE is the simpler approach, but not automated, not image styles, so uploaded images, need to be thumb nailed.

---

And a different approach would be to use paragraphs. **Not (only) directly in but combinable with CKeditor**.
> 0 votes

# Answer
In Drupal 8 you can employ the Media module and Entity Embed suite of modules. This makes embedding media more Drupal native in CKEditor - and one of the things you can do is select which view mode to render the media in.

This view mode configuration can set which image style to use on its field formatter display.

Therefore, you can create a couple of view modes for inserting media and have those map to image styles in different use cases. It makes it easy for the user, all they have to do is select an option when embedding.
> 0 votes

---
Tags: 8, wysiwyg, media
---


title: How to get view mode of a node?

text:
# Question
Title: How to get view mode of a node?
So my question is how I can get programmatically in preprocess node hook, the display mode of a node, for example, to check if view mode is a teaser or full?

# Answer
The view mode is in the vars:

```
function MYMODULE_preprocess_node(&$vars) {
    $view_mode = $vars['view_mode'];
}

```

See `template_preprocess_node()` or node.html.twig for more info.
> 8 votes

---
Tags: 8, nodes
---


# Question
Title: How to handle cache metadata in a cacheable response?
I have a custom controller action that returns the HTML for a search result. The action is invoked via AJAX on the search page and the results are inserted into the page body.

The problem is that a dynamic page cache entry is created for this controller action and it's not "busted" when the query string changes, so old results are always returned:

```
  public function basicPeopleSearch(Request $request) {
    $search = $request->query->get('search');
    $build = [];
    if (!empty($search)) {
      // Get search results and add them to the render array.
      $results = \Drupal::getContainer()->get('pu_search.people_search')->basicSearch($search);

      foreach ($results as $result) {
        $build[] = [
          '#theme' => 'pu_search_person',
          '#person' => $result,
        ];
      }
    }

    // The results will differ based on the "search" query string parameter.
    $build['#cache'] = [
      'contexts' => [
        'url.query_args:search',
      ],
    ];

    $rendered = \Drupal::service('renderer')->renderRoot($build);
    return new CacheableResponse($rendered);
  }

```

I suspect this has something to do with how I'm actually returning the response or rendering the output?

# Answer
> 3 votes
You have to add the cacheable metadata from the render array to the response:

```
use Drupal\Core\Cache\CacheableMetadata;

  $rendered = \Drupal::service('renderer')->renderRoot($build);
  $response = new CacheableResponse($rendered);
  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
  return $response;

```

---
Tags: 8, caching
---


# Question
Title: How to check if the current page is a 404 error from a module/template?
How to check, in D7, if the current page is returning a 404 error from a module/template?

# Answer
In Drupal 7, you can use `drupal_get_http_header()`.

In the template.php file, use this code.

```
$status = drupal_get_http_header("status");
if ($status === '404 Not Found'){
  // Do something.
}

```

In Drupal 8, you can use the following code in a hook.

```
$route_name = \Drupal::request()->attributes->get('_route');
if ('system.404' === $route_name) {
  // Do something.
}

```
> 37 votes

# Answer
Drupal 8.2.x:

Unfortunately, drupal\_get\_http\_header("status") doesn't work any more.

Try:

```
$status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
if ($status && $status->getStatusCode() == 404){

}

```

There is a discussion of this here: https://www.drupal.org/node/1969270
> 18 votes

# Answer
This is the simplest way to detect Access Denied (403) and Page Not Found (404) in Drupal 7.

```
// get the menu router item for the current page
$router_item = menu_get_item();

// if there is no router item, this page is not found
$is_page_not_found_404 = empty($router_item);

// if 'access' is empty for the router item, access is denied
$is_access_denied_403 = empty($router_item['access']);

```
> 4 votes

---
Tags: http-request
---


# Question
Title: get taxonomy term aliased path when its a referenced field in a $node entity
what I have is a $node and know how to get its aliased URL but I also have a field `field_category` that I know how to get the name but how do I get the url alias for it

```
$nid = 1;
$node = \Drupal\node\Entity\Node::load($nid);
$options = ['absolute' => TRUE];
$nodeurl = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
$categoryname = $node->field_category[0]->entity->label();

```

# Answer
Sure enough I could use the `tid` or `target_id` in entity reference lingo and use it to find the URL `fromRoute` using as `route_name` `entity.taxonomy_term.canonical`

```
    $tid = $node->field_category[0]->target_id;
    $categoryurl = \Drupal\Core\Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $tid], $options);

```

find other taxonomy route\_names

might also need to see the Url::fromRoute definition
> 5 votes

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


# Question
Title: How to create front page for every language?
My goal is to have three front page versions per language. Browser language detection is enabled. Front page is correctly rendered with a language according to `Accept-Language`, but there is no language indicator in URL, example: `host.com/it`.

Have I missed something in configuration or I have to do this feature (redirect) programmatically (or Rules) ?

# Answer
> 2 votes
You have to use the language detection method "URL" for this. When using other detection methods the language prefix is not used.

Even then a URL without a language prefix still works and uses the default "Selected Language" at the end of the detection methods list or another method you have enabled between those two.

If you want that the homepage is redirected to the language prefixed URL instead, use the module Redirect and set this option:

> GLOBAL REDIRECTS
>
> \[x\] Enforce clean and canonical URLs.
>
> Enabling this will automatically redirect to the canonical URL of any page. That includes redirecting to an alias if existing, removing trainling slashes, ensure the language prefix is set and similar clean-up.

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


# Question
Title: How can I update text_format value in Ajax callback?
I have a Drupal 8 form that includes the following fields:

```
// Comtainer for message fields and preview.
$form['email'] = array(
  '#prefix' => '<div id="email">',
  '#suffix' => '</div>',
);

// Template selection drop-down.
$form['template']['template_select'] = array(
  '#type' => 'select',
  '#title' => $this->t('Select template to use (overwrites message)'),
  '#options' => $options,
  '#default_value' => 1,
  '#ajax' => array(
    'wrapper' => 'email',
    'callback' => array($this, 'updateEmailTemplate'),
    'event' => 'change',
  ),
);

$form['email']['message']['subject'] = array(
  '#type' => 'textfield',
  '#title' => $this->t('Message subject'),
  '#default_value' => $params['subject'],
  '#ajax' => array(
    'wrapper' => 'preview',
    'callback' => array($this, 'updateEmailPreview'),
    'event' => 'change',
  ),
);

$form['email']['message']['body'] = array(
  //'#type' => 'textarea',
  '#type' => 'text_format',
  '#title' => $this->t('Message body'),
  '#description' => $this->t('Text for the email body. you may use the following tokens: @tokens.', ['@tokens' => SimpleConregTokens::tokenHelp()]),
  '#default_value' => $params['body'],
  //'#value' => $params['body'],
  '#format' => $params['format'],
);

```

My Ajax callback function is:

```
  // Callback function for Template drop down - load message fields with template.
  public function updateEmailTemplate(array $form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    $templates = $form_state->get('templates');

    if (!empty($template = $form_values['template']['template_select'])) {
      //Code here to determine new form values.

      $form['email']['message']['subject']['#value'] = $params['subject'];
      //$form['email']['message']['body']['#type'] = "textarea";
      $form['email']['message']['body']['#value'] = $form['email']['message']['body']['#default_value'];
      $form['email']['message']['body']['#format'] = $params['format'];
    }
    return $form['email'];
  }

```

So what's happening?

When the user chosen selects a template from the dropdown, the text\_format doesn't update.

If I change the #type of the field from text\_format to textarea, it will update without any problems, which suggests the callback should work.

I though there might be something in the text editor JavaScript preserving the text\_format field from being updated, but if I explicitly set the #value in the form building function, it starts updating in the callbacks. The problem with this is that it also overrides the value when the form is submitted.

Finally, I've tried adding a line to the callback to set the #type to a textarea, and this is also getting ignored. The callback is still getting called, however, because the supbect textbox does update.

Any ideas where I'm going wrong? I'm particularly confused as to why the textarea version works perfectly but changing to text\_format doesn't.

James

# Answer
Don't change `$form` in an ajax callback. See this documentation for D7:

https://www.drupal.org/docs/7/api/javascript-api/ajax-forms-in-drupal-7

> **Details and Warnings**
>
> Changes to the form must only be made in the form builder function, or validation will fail. The callback function must not alter the form or any other state.

For D8 there is in the moment only documentation for the new syntax, but not for the basics. Use the D7 doc's instead.
> 1 votes

---
Tags: 8, forms, ajax
---


# Question
Title: How to set file field upload path to Taxonomy term url?
I have `article` content type and it has `field_pdf` field and `field_categury` fields.
`field_categury` is a taxonomy term reference field.
I use `File (Field) Paths` module and I want to set `field_file` path to `field_categury` term url.
I try to use Field tokens but i can not set it.

Thank you.

# Answer
I found the solution:
I should use entity token module and use this token in file path:

```
[node:field-categury:0:url:relative]

```
> -1 votes

---
Tags: tokens
---


# Question
Title: How to configure chosen on Form API with an entity_automcomplete widget?
How to configure chosen field on Form API with drupal 8. I have already installed chosen and it's works in User Interface and not in form API.

This peace of code doesn't work:

```
          $form['tags'] = array(
        '#type' => 'entity_autocomplete',
       '#chosen' => TRUE,
        '#target_type' => 'taxonomy_term',
        '#selection_settings' => ['target_bundles' => ['tags']],
        '#title' => ('Tags'),
        '#empty_value' => ''
       ;

```

# Answer
I guess you can't because you are using an autocomplete widget, but the project page states:

> Chosen uses the Chosen jQuery plugin to make your elements more user-friendly.

So you have to refactor your form to use a `select` element, not an autocomplete.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Why is the "webform submission updated" hook not using the correct data?
Created a function in respond to `hook_webform_submission_update` to generate a FillPdf.

```
function my_module_webform_submission_update($node, $submission) {

    if ($submission->nid == 43) {

        $uuid = ($submission->data['975'][0]);
        $sid = ($submission->sid);

        $f = "./sites/default/files/docs/mdx_lh_" . $uuid . "_" . $sid . ".pdf";

        if (file_exists($f)) unlink($f);

        $wf = array(array("nid" => 43, "sid" => $sid));

        fillpdf_merge_pdf(326,NULL,$wf);
    }
}

```

When the event is triggered, after pressing the save button, the FillPdf uses the old data.
Going over the webform a second time without changing anything, just clicking the save button, the FillPdf uses the correct data.

I thought the `hook_webform_submission_presave` was to change data (if needed) but it seems the event `hook_webform_submission_update` is triggered before data is actually saved.

Is there a way to force data save before calling `fillpdf_merge_pdf`, or is there another event to use?

# Answer
> 0 votes
For whatever reason querying the database give the correct data and yet the FillPdf sevice uses the older one, we moved the routine to the point where the results are showed, where its activated with a button. This option works fine.

---
Tags: 7, hooks, webforms
---


# Question
Title: Show webform confirmation on same page as the form
How can I show a confirmation message on the same page as the form instead of redirect? Right now I see a a link for "Go back to form" and I want to see the confirmation and webform.

# Answer
> 0 votes
If this is Drupal 7, you can simply enter the confirmation message (do not enter a URL) on the Webform config. This message will display above the form after completion.

# Answer
> 0 votes
Webform 8.x-5.x supports displaying the confirmation message above the form.

---
Tags: webforms
---


# Question
Title: A page that list all the nodes by views but to have a one CMS controlled banner image on that page
I have created a views page which list maximum of 50 nodes of type 'event'. It works fine but I want have a single image banner on the top that can be uploaded by the logged in user from the admin area for that page. I can't add a banner field on the event content type as it will get pulled 50 times.

The other solution I managed was to create another content type called 'Banner image' and create another view which lists 1 node of event type 'Banner image' and add it to the initial page view but that seems like a really dirty solution. Is there a simpler solution to this problem?

# Answer
> 1 votes
1. Create a admin form that allows the admin user to upload the image file, as you say in your question.
2. Create custom block that renders the image as you want. You can do in a custom module (better, more solid) or crete the block using the GUI and add the HTML code. In both cases, the img should point the file uploaded by the admin form.
3. Place the block over your view in the view's page.

This is good if:

* You only have one view that needs the header image.
* That image is the same for evey user.

# Answer
> 1 votes
> The other solution I managed was to create another content type called 'Banner image' and create another view which lists 1 node of event type 'Banner image' and add it to the initial page view but that seems like a really dirty solution.

If you want your users to be able to change the image easily, and you want to always show the last image (for example), this is a solution.

Another solution is adding the view as a block to the content type image. Or vice versa (which is @sanzante's answer)

You can look into Entity Views Attachment module, https://www.drupal.org/project/eva.

You can modify the view template files and add the image there.

There are many ways. It depends ultimately on flexibility and what you need.

---
Tags: 7, views
---


# Question
Title: Relation: add button to create node related to current node
I have 2 Content types called **Schools** and **School News** and i want to add a **add News** Button to those School pages, so editors can create a new post for this specific school. I thought about using relation module as i am using it already for other things.

Would it be possible to create such a button that adds a hidden field with the ID of the specific school into the news form? That way i could add this relation while saving the node. Is there any other way to get this kind of functionality with relation?

# Answer
The Node Reference URL module works with the References module to accomplish this feature. When you add a node reference field, you can specify `Reference From URL` widget which will auto fill the field from a value in the URL. You can also specify (in the field settings) to display a link on the referenceable node.

In your case, you would create a node reference field on **School News** that references **Shools**. Just select the `Reference From URL` widget and configure as necessary.

There's an older lullabot video about creating image galleries in Drupal 6 that demonstrates how it works. The Drupal 7 version has the same features and works the same way.
> 2 votes

# Answer
Maybe this help you: Relation autoconnect
> 0 votes

---
Tags: 7, nodes, entities
---


title: How can I "outsmart" caching?

text:
# Question
Title: How can I "outsmart" caching?
A view returns an event, which occurs on the current day, in a block. If there is no current event in the database (empty result), a second view is started, which then outputs events from the past.

It is working, when I am logged in. As long as I am logged in, I see correct results, even in the view preview.

If I look at the next day as anonymous user, I don't see the current event; the block displays the view result of the previous day. Only with a registration attempt the output is updated, no matter whether I logged in, or a registration attempt is started.

In the views I have changed under -\> ADVANCED -\> cache: „tag based" to "time-based" with duration of 1 hour for query results and output format.

Unfortunately, the result is the same: the output block is not updated according to the new day. Now I have deactivated the data caching of the view module, in the hope that tomorrow the display is now updated independently.

If this does not work, only to log in once the day to force an update?

Admin/performance:

Modules:

views/settings/advanced:

The View:

The View (extended)

# Answer
> 4 votes
The issue you have is with the module *Internal Page Cache* for anonymous users. You have several options:

If you want to serve for anonymous users a newly built page on each request the same way as for logged in users, then uninstall the *Internal Page Cache* module. The dynamic page cache will still cache pages, but does respect the cache contexts and max-age you set on the page elements.

Performance wise it is not a good idea to do this, so it might be better to configure a max-age for the Internal Page Cache, see this answer https://drupal.stackexchange.com/a/196557/47547, where you use an event subscriber to set an Expires time in the response.

If this is only for Views, another option is to modify the route definition of the view by setting a `no_cache` option, see this answer https://drupal.stackexchange.com/a/230242/47547

In all cases you need to configure `/admin/config/development/performance` for external caches like the browser cache.

# Answer
> 0 votes
**My solution:**

* View: -\> Advanced -\> Query settings -\> Disable SQL rewriting: Yes.
* Views Caching: Time-based (2 hours/2 hours

Works as expected.

Tanks to all.

---
Tags: views, 8
---


# Question
Title: Add description to each entity reference
I'm using Drupal 8 to build a new web app. I am allowing the user to add connections to other content on the site using taxonomy entity references. I'd like them to be able to add a description to each reference - i.e. select 'Node X', and add a description about the relation to 'Node X'.

Is this possible?

Thanks!

# Answer
If you are looking for a code solution, you can do this in a custom field type, see this answer https://drupal.stackexchange.com/a/231162/47547.

If you want to do this in UI, you can use Field Collection or Paragraphs to bundle the two fields entity reference and description.
> 2 votes

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


# Question
Title: Integration of Excel File Viewer or Editor?
I'm looking for a solution of my problem and I'm not sure if mine is the best put it will do the job for now. I want the have a basic page with embed excel file iframe from google docs after user login.I have done that and it works fine but the problem comes when I have for example 50 users and each has to see his file.How can I deliver exact file for the user? Here is an example: User 1 logs in and a menu button shows after log in, he presses it and the basic page with his embed excel sheet shows up...thats all

iframe contains the link like this:

```
<iframe src="docs.google.com/spreadsheets/d/…; width="600" height="400"</iframe>

```

If we have 50 users we will have 50 different links (Google generates different links to different files from Google Drive and we will know them already), each link for user will be the same over the time and it will not change , so we don't need to calculate anything, yeah...and each user will have his link in his iframe loaded as soon as he logs in to his account.

I'm still not good enough at codding so an example would be appreciated.

# Answer
Use the Iframe module (available for Drupal 7 and 8).

> A custom field, which lets you add a complete iframe to your content types; including Src-URL, setting width and height, optionally a title above, and optionally a target attribute.

Add an iframe field on each user profile with their Google Docs URL. Depending on who is reponsible of adding he field to the user profile (admin or the user itself) you adjust permissions.

Then use that field to render it.
> 0 votes

---
Tags: users
---


title: Create a distribution

text:
# Question
Title: Create a distribution
How is it possible to create a new Drupal distribution based on site that I already built? I've already exported the content types using

`drupal config:export:content:type MYCONTENTTYPE --module MYMODULE`

Drupal console has the following function which may be useful.

https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/generate-profile.html

This following link leads to the current drupal.org documentation on creating a Drupal 8 distribution. It looks like it only shows how to create a distribution manually though.

https://www.drupal.org/docs/8/creating-distributions/how-to-write-a-drupal-8-installation-profile

I was hoping that there was something in Drupal console or Composer that would take all the information in my current database and create an installation profile out of it.

**EDIT**

The Drupal Profile Builder seems wonderful but current only supports D7.

# Answer
> 2 votes
Actually, the drupal.org link above will work. At the bottom of the page there is a section that discusses bringing configuration files into the install directory. You can use Drupal Console (DC) to create the configuration files like this:

```
drupal config:export

```

It will put all the configurations in the public folder unless you specifiy a directory.

https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/config-export.html

https://www.drupal.org/docs/8/creating-distributions/how-to-write-a-drupal-8-installation-profile

**EDIT**

Also, I've added a Drupal.org page has a lot of resources for creating a distribution. On the sidebar it lists common `make` errors and other useful links.

If you check the release download page of your distribution, you can find the Drupal packager error messages if you send a distribution for packaging.

A lot of this needs to be learned by trial and error. I've spent a fair amount of time on this and still haven't gotten the hang of things.

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

**EDIT**

Also, there appears to be something called drupalorg\_drush. It's a drush extension that helps build a replica of what drupal.org would do with your distribution files should you upload them to your project's Git repository. However, at the time of this writing, Drupal 8 version is not available.

---
Tags: 8, distributions, console
---


# Question
Title: how to get the region (the menu is rendered in) or block name/ID in hook_preprocess_menu
I have a menu that want to behave differently based on the region its displayed in.

By default there is no file suggestion that differentiates which twig file to be used for a menu based on the region. Even if there was I think for the purpose of adding/removing a class it is more convinient to modify a variable in a preprocess function than keeping to versions of a twig template.

here is what I have

```
function THEMENAME_preprocess_menu(&$vars) {
    $test = "";
    if ($vars['menu_name'] == 'main') {
        if (!isset($vars['attributes']['class'])) {
            $vars['attributes']['class'] = [];
        }
        //test region or block name before merging
        $vars['attributes']['class'] = array_merge($vars['attributes']['class'], ['main-menu-regionA']);
    }
}

```

I need a way to test the region or the block name to add a specific class to the parent UL element

my 2nd choice would be to explore the `hook_theme_suggestions_alter`

# Answer
`hook_preprocess_menu` is missing a lot of variables that other preprocessors have so I finally solved my problem using `hook_preprocess_block` (which I think would not have been possible in earlier versions of drupal)

**New solution** since people have been reporting that `$vars['configuration']['region']` is empty

```
function THEMENAME_preprocess_block(&$vars){
    if($vars['base_plugin_id'] == "system_menu_block"){
        if($vars['derivative_plugin_id'] == "main"){
            $block = \Drupal\block\Entity\Block::load($vars["elements"]["#id"]);
            if( $block->getRegion() == "navbar")
                $vars['content']['#attributes']['class'][] = 'in-navbar';
                $vars['content']['#attributes']['class'][] = 'nav';
            }
            elseif($vars['configuration']['region'] == "footer"){
                $vars['content']['#attributes']['class'][] = 'in-footer';
            }
        }
    }
}

```

**NOTE** if using in a recursive function/twig MACRO (which probably you are) you should `removeClass` all the classes you don't want in inner `UL` tags in a way similar to this

```
{{ menus.menu_links(item.below, attributes.removeClass('nav','in-navbar'), menu_level + 1) }}

```

**old solution**

```
function THEMENAME_preprocess_block(&$vars){
    if($vars['base_plugin_id'] == "system_menu_block"){
        if($vars['derivative_plugin_id'] == "main"){
            if($vars['configuration']['region'] == "navbar"){
                $vars['content']['#attributes']['class'][] = 'in-navbar';
                $vars['content']['#attributes']['class'][] = 'nav';
            }
            elseif($vars['configuration']['region'] == "footer"){
                $vars['content']['#attributes']['class'][] = 'in-footer';
            }
        }
    }
}

```
> 3 votes

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


# Question
Title: Overriding menu.html.twig just for the primary menu
Drupal 8 Beta 1 has a lot of nice templates to use which can be brought into a custom theme and then customized. I brought in core's menu.html.twig into my custom theme and indeed I can customize markup in there. However, this template overrides all Drupal menus, not just the primary menu which is the one I want to override.

I tried the *Devel module* for Drupal 8 figuring I might get some insight about what's going on under the hood. However, the module still looks like it's in a state of flux and I got massive errors. My goto module for template suggestions for Drupal 7 is *Devel Themer (Theme Developer)* but alas no Drupal 8 version.

I also tried getting specific with the template name and tried `menu--primary.html.twig` but that did not work either.

I then tried within the template wrapping an if around the part that I want to modify as such:

```
{% if primary_menu %}
   <ul{{ attributes.addClass('foobar-menu') }}>
{% endif %}

```

... but no joy there either. so I am out of ideas on how to do this.

# Answer
> 13 votes
Answering my own question here, this will probably be useful for those looking to debug twig.

1. Activate devel Kint (part of the Devel module) on the modules page or with Drush
2. In your `site /sites/default/services.yml` change the following settings:

`parameters:
 twig.config:
 debug: true
cache: false
auto_reload: true`
3. Then in the template you want to debug, place this code in it:

`{{ kint() }}`

Now you get a nice tree of variables that prints out similar to what you would get if you did an old style `kpr(get_defined_vars());` in Drupal 7.

4. I see from the debug printout that the name of the menu is simply `main`.
5. Now I change the overridden template in my custom theme's template folder to `menu--main.html.twig`
6. Voila, the template is only specific for the primary main menu now
7. Customize as a themer to your hearts content.
8. Throughout this process, don't forget to clear cache and change / remove any debug code when you are done.

In addition to this, with debugging active, Chrome prints out possible template suggestions a la *devel\_themer* so you don't necessarily have to use Kint.

# Answer
> 1 votes
Just in case the OP meant the primary menu and not the main menu, we need to remember regions can have any menu assigned to them, or even multiple menus.

So if you're trying to theme whatever menu(s) are placed in specific regions, you need to add a theme hook suggestion. Here's how I did it:

In your .theme or .module file:

```

use \Drupal\block\Entity\Block;

/**
 * Implements hook_theme_suggestions_HOOK_alter() for block templates.
 */
function TEMPLATE_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  $base_plugin_id = $variables['elements']['#base_plugin_id'];
  $system_menu_block = $base_plugin_id == 'system_menu_block';

  if ($system_menu_block) {
    $id = $variables['elements']['#id'];
    $block = Block::load($id);
    $region = $block->get('region');
    $suggestions[] = 'block__' . $region . '__menu';
  }
}

```

You now have new theme hook suggestions for all system menu blocks:

`TEMPLATE_preprocess_block__REGION__menu()`

Use the theme hook suggestions like so:

```

/**
 * Implements template_preprocess_block() for the primary menu region.
 */
function TEMPLATE_preprocess_block__primary_menu__menu(&$variables) {
  $variables['content']['#theme'] = 'menu__primary';
}

```

Finally, create the template file using the `#theme` variable you assigned above:

`menu--primary.html.twig`

So if you have a `sidebar_first` region, use:

```

/**
 * Implements template_preprocess_block() for the sidebar_first region.
 */
function TEMPLATE_preprocess_block__sidebar_first__menu(&$variables) {
  $variables['content']['#theme'] = 'menu__sidebar_first';
}

```

and:

`menu--sidebar-first.html.twig`

---
Tags: routes, 8, theming
---


# Question
Title: How to set images path on libraries JS file in Drupal 8?
I would like your kind help to point the correct path of images from JS. I'm trying to change a DIV background using CSS and JS. Quite simple, right? Well, not for me in Drupal 8.

My div loads the background defined in the CSS (my\_module.libraries.yml) The JS also works for changing positions of the layers (or DIVs, sorry, I'm from the Netscape times, old school). But it doesn't work for setting the background because cannot find the images. That means that there is no problems regarding routing neither configuration of the module.

So, the question is: How can I set the path for the CSS images in the JS libraries?

Here goes some codes:

*My\_module.libraries.yml*

```
box-simulador:
  version: 1.x
  css:
    theme:
      css/box-simulador.css: {}
  js:
    js/box-simulador.js: {}

```

*Excert from the CSS file*

```
#SimHolder {
    background: url(img/pillow.png) left top no-repeat; /* << WORKS FINE! */

```

*Excert from the JS file*

```
function setTowel() {
 document.getElementById('SimHolder').style.backgroundImage='url(img/towel.png)'; // DOESNT WORK :(
 document.getElementById('textHolder').style.top='30%'; // IT WORKS!

```

I'm sure the answer would be quite simple ;) Thanks in advance!

# Answer
> 1 votes
Weel, I found s solution, quite simple: just use {{directory}} on the template. ;)

---
Tags: 8, theming
---


# Question
Title: Translation does not work for promoted to front page nodes
I've been trying to figure out how to have a translated node promoted on the front page to be displayed according to the visitor chosen language. So basically I have one article promoted on the front page. It has a french translation (which I also set as promoted on the front page).

* I want my visitor to only see the english version of my article (node/1) when on mysite.com/en
* I want my visitor to only see the french version of my article (node/3) when on mysite.com/fr

The problem:

The source node (en, node/1) has a translated version (fr, node/3). Both are set to be promoted on front page. But they are both showing up on the homepage whereas I would like to have the nodes being only displayed once on the related language (mysite.com/fr or mysite.com/en).

Everything has been set up using Internationalization.

# UPDATE

You will think I was posting without googling first but I can ensure you I've been struggling with this for hours. Finally found the solution here: https://stackoverflow.com/questions/5168289/multiple-frontpages-in-mutiple-languages/6803625#6803625

# Answer
I'm assuming this question is about D7 ...

The relative URL to display as the front page is specified within `admin/config/system/site-information`. If you want to be able to specify a value for it that is different for each of the site's languages, make sure you have made it a "multilingual" variable (it should say "This is a multilingual variable.") in the description of that variable on that page.

Refer to the community documentation about Variable translation for details about how to translate text and settings that are stored in Drupal as variables. Here is a quote from that page:

> The Variable translation module, part of the Internationalization (i18n) package, allows you to translate text and settings that are stored in Drupal as variables. These variables include text such as 'site name' and 'site slogan', as well as settings like 'Default front page' and 'Default 404 page'.

The Variable translation module has a dependency on the Variable module.

And these are the specific steps required to make a variable multilangual (mentioned on that community page):

1. Enable the Variable translation module included with the Internationalization package
2. Go to Administration \> Configuration \> Regional and language \> Multilingual settings
3. Click on the Variables tab
4. Select the variables that will be multilingual
5. Click Save configuration button

Obviously, in this case in step 4 the variable to be selected is "Default front frontpage", within "Site information".

Finally, this is what remains to be done (another quote from that same page):

> Once you have the correct settings, they'll be marked with "This is a multilingual variable" when you go to the corresponding administration pages (Figure 2). You must switch the site language while in the administration pages to set the variables for each language. A language switcher link will appear at the top of each administrative page that has multilingual variables.

"That's all" what's needed to specify a language specific value for the frontpage of your site ...
> 1 votes

---
Tags: i18n-l10n
---


title: Scrolling display module

text:
# Question
Title: Scrolling display module
I'd like to make a scroll display for sponsor's logo like this demo.

Is there any module for Drupal 7? if there is no one how can i achieve this?

# Answer
You could modify http://drupal.org/project/jcarousel to do this. Since the link you provided already provides a guide (http://valums.com/scroll-menu-jquery/) to implement this why don't you put the code in a drupal block and display it.
> 1 votes

# Answer
There is a module just for that https://www.drupal.org/project/views\_ticker

Its a views style plugin. Setup your view to collect all the text that will be scrolled and choose from among 5 different display options (scroll styles)

I believe views\_slideshow can also be used as a ticker or you can take a look at a comparison of all ticker/slideshow modules available for drupal
> 0 votes

---
Tags: 7
---


# Question
Title: How does Drupal verify sessions from the cookie value?
Sorry, I know it's weird, but I'm trying to integrate another php application with Drupal. I want to know if the user is currently logged in to the Drupal site, even though the request is going elsewhere. I'm getting the cookie out of a Guzzle request object. As far as the application is concerned (because of Nginx proxying), the origin is the same, and the cookie is getting passed successfully.

Here's what I'm getting out of the Guzzle request object:

```
array(1) {
  ["SSESSdbf18a05343cfb88719ee68ff6159a52"]=>
  string(43) "5eW8YPdDPjojAjuokObuD5R2L7cyOfffmBuVAdHzWwU"
}

```

The above value is also what the browser reports.

But, in my `sessions` table in the DB, there is no session that resembles this, either in the `sid` or the `session` column.

How does Drupal check the DB for a valid session cookie, and where should I be looking in core to copy this?

# Answer
I figured it out, but if someone posts a more in-depth answer, I'll accept it.

Drupal has a SessionHandler with a read function:

```
public function read($sid) {
    $data = '';
    if (!empty($sid)) {
      // Read the session data from the database.
      $query = $this->connection
        ->queryRange('SELECT session FROM {sessions} WHERE sid = :sid', 0, 1, [':sid' => Crypt::hashBase64($sid)]);
      $data = (string) $query->fetchField();
    }
    return $data;
  }

```

And, if you bootstrap Drupal, or call an external Drush script, you can do this:

```
$session_handler = \Drupal::getContainer()->get('session_handler.storage');
$logged_in = (bool) $session_handler->read($session);

```

Here's how I got the cookie out of the Guzzle object:

```
$request->getCookies();
//var_dump($cookies);
foreach($cookies as $cookie){
  if(strpos($cookie, "SESS") == 0){
    $session = $cookie;
  }
}

```

If you actually want the UID, you're going to have to not do the (bool) cast and de-blob the thing, because it returns the raw MySQL data.
> 7 votes

---
Tags: 8, sessions
---


# Question
Title: How do priorities work in the *.services.yml YAML file?
In `system.services.yml` and many other services files, one can find priorities like this:

```
services:

  ...

  path_processor.files:
    class: Drupal\system\PathProcessor\PathProcessorFiles
    tags:
      - { name: path_processor_inbound, priority: 200 }

  ...

```

Are these priorities similar to the weight-system we know from Drupal 7, where a low weight means earlier in the processing order. Or do priorities work the other way around, where the items with the highest priority are processed first?

I am asking because I could not find a source explaining this.

# Answer
Drupal uses the EventDispatcher from Symfony and there the priority is used to control in which order the event listeners are triggered:

> An optional priority integer (higher equals more important and therefore that the listener will be triggered earlier) that determines when a listener is triggered versus other listeners (defaults to 0). If two listeners have the same priority, they are executed in the order that they were added to the dispatcher.

So the priority in D8 is exactly the opposite of the weight in D7.

The example you used in the question is not an event subscriber, but it uses the same concept of priorities.
> 11 votes

---
Tags: 8
---


# Question
Title: Drupal 8 \Drupal calls should be avoided in classes, use | | dependency injection instead
I used Drupal 8 and written a module. in my form page I called.

```
\Drupal::service('library.discovery')->clearCachedDefinitions();
$cache = \Drupal::cache('discovery');
      $cache->delete('block_plugins');

```

It's worked, but I always see the warning.

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

I have the similar with File::load(), too. I used:

```
use Drupal\file\Entity\file;
class BXBlock extends BlockBase {
public function build() {
...
$file = File::load($value);
...
}
}

```

Anybody can help me, please? Thanks so much.

# Answer
> 5 votes
You can check how the dependency injection works in general in this documentation. https://www.drupal.org/docs/8/api/services-and-dependency-injection/dependency-injection-for-a-form

The parts that you need are:

Use statement -

```
 use Symfony\Component\DependencyInjection\ContainerInterface;

```

Class property - here we are going to store the whole `\Drupal::service('current_user')` object.

```
 protected $account;

```

The `__construct` magic method. This is called upon instantiating the class. The dependency injection bit here is providing all the data required in a later stage as input.

```
function __construct(AccountInterface $account) {

```

Built in method that has a dependency injection create(ContainerInterface $container)

```
return new static(
  // Load the service required to construct this class.
  $container->get('current_user')
);

```

Eventually we are using the whole construction like that:

```
$uid = $this->account->id();

```

where `$this->account` is the same like `\Drupal::service('current_user');`

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


# Question
Title: How to resolve configuration objects lang code differences?
The default language for my site is Arabic, but the administration bits are in English. This means that for now, the only needed translations are those of labels and the interface.

Earlier I tried to translate some of my content types and found most of them configured like this:

> English
> Arabic
> None (original) Edit

With this message above:

> The configuration objects have different language codes so they cannot be translated:
>
> * node.type.person: en
> * core.base\_field\_override.node.person.title: ar

I tried changing the language settings for the content type but the language remained set to 'None'. Any idea about how to fix this?

# Answer
I'm not sure I can help but I had a similar issue. After enabling translation for pages, I got a similar error in admin/structure/types/manage/page/translate:

```
The configuration objects have different language codes so they cannot be translated:

node.type.page: en
core.base_field_override.node.page.title: pt

```

I think this happened because I was by mistake in /pt/admin (?).

Anyway, I fixed this (in my case, I always want en), by running the command:

```
$ drush cset core.base_field_override.node.page.title langcode en

```
> 12 votes

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


# Question
Title: How to alter a custom text field in a block with AJAX
We have a `block` on a `basic form` listing several items and each item has a number of PDF files on the server to show by a users request.
Each item has an Id (nnn) which is displayed in a text field wrapped as
`<div id='it_nnn'><a href='call_ajax/nnn'>item nnn</a></div>`
the object is when a user clicks the link, the `div` should be replaced by a list showing the links to the corresponding PDF files to download.
There are lots of Ajax examples that create their own form, but none so far that comes close to our application in replacing a `div` in a `block`.
We could do the Ajax request in a direct way but prefer to use the Drupal api's for stability and manageability, the only question remains is how to.. so examples or ideas are appreciated.

# Answer
> 0 votes
You have some examples in "Examples for Developers" https://www.drupal.org/project/examples

If you see in ajax\_example module, you have "Ajax Link" which points to the url ajax\_link\_callback, (defined by menu hook ajax\_link\_callback in file ajax\_example.module, line 181). This menu hook has a callback function (see file ajax\_example\_misc.inc, line 102), which does the magic.

You can see that the ajax response is made with a few components. First the $commands array with the target div and the content to output. Then this array is wrapped in another array ($page), and delivered by the function: ajax\_deliver.

Note that the original link ( which is produced by the menu callback ajax\_example\_render\_link() in file ajax\_example\_misc.inc, line 22), has a use-ajax class attribute and previously the drupal.ajax library is added to the page.

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


# Question
Title: Start form as modal, from the controller
I see a lot of examples of modal forms. But in all these example the modal is started from a current form. There is always a link-button involved. I would like to start a form as a modal from the controller by using:

`$form = \Drupal::formBuilder()->getForm($formId);
return $form;`

Can someone give me an example of which extra code is needed to show the form ($formId) as a modal??

# Answer
I solved my own problem: in stead of a modal I use an overlay which reports a message.

My question seemed a bit theoretical, but in the Mediator Design Pattern I use, I want to solve my problems generically. In the main program I can decode when a form takes long time, before I render the form I attach extra JS which is coupled to the submit button.
> 1 votes

# Answer
I did an example of this a while ago. Basically I defined a route, and that controller returned an AjaxResponse:

```
mymodule.growl:
  path: '/mymodule/growl'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::growl'
  requirements:
    _permission: 'access content'

```

Basic controller:

```
namespace Drupal\mymodule\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\igrowl\Ajax\GrowlCommand;

class MyModuleController extends ControllerBase {
  public function growl() {
    $options = GrowlCommand::defaultOptions();
    $options['message'] = 'This is a message.';
    $options['title'] = 'Hello';
    $options['icon'] = 'feather-check';
    $options['type'] = 'success';

    $response = new AjaxResponse();
    $response->addCommand(new GrowlCommand($options));
    return $response;
  }
}

```

Any link hitting that route fired that Command. So, anytime someone clicks a link going to your defined route, it should create a modal.

You basically want to return a form (use the form builder service provided by ControllerBase instead of the static container) and at a basic level, use OpenModalDialogCommand (or supply your own modal js with custom Command). AjaxResponse will take care of the rest.
> 1 votes

# Answer
You can force any link to open in a modal dialog. Just add the class `use-ajax` and the attribute `data-dialog="modal"` to a link.

```
<a href="/node" class="use-ajax" data-dialog="modal">node list</a>

```

P.S. Drupal uses JavaScript to apply this behavior, so make sure set the class and attribute in the server side (template/preproces/pre-render...)
> 0 votes

---
Tags: 8, forms, ajax
---


# Question
Title: How to embed and play on same page like popup?
I'm learning web development with Drupal 7.

I can embed youtube video using CKEditor on a node. I like to play embedded video looks like on YIFY and IMDB as popup/overlay. It means when I click on play button it will open as popup on the same page and on click outside the youtube player or whatever, it will stop and display nodes' content.

How this can be possible, JS/JQuery will be used? If yes then how and please suggest me the other ways as well.

# Answer
> 0 votes
You can easily achieve this functionality by using something like colorbox. This will allow you to open videos in popup. Since you've just started learning drupal, I would recommend that you thoroughly follow documentation for this module.

Another alternative is using modules video\_embed\_field along with colorbox. This will allow you to use colorbox as field formatter.

---
Tags: 7, wysiwyg
---


title: Translating paths in routing.yml

text:
# Question
Title: Translating paths in routing.yml
How do you translate the path portion of a module route?

For instance you have:

```
module_name.my_route_name:
  path: '/path/to/content'
  defaults:
    _controller: \Drupal\module_name\Controller\MyController

```

How do I get **/es/ruta-de-acceso/a/contenido** to point to the same route name?

# Answer
> 7 votes
As far as I know (anyone, correct me if I'm wrong!) this is not possible in the routing system. You can however add a path alias, and make "/ruta-de-acceso/a/contenido" an alias in the Spanish language for '/path/to/content'.

Now the problem with path aliases, compared to routes, it that they are considered content, not core or configuration. As a result there is (again: AFAIK) currently no way to export them and deploy them to a server. For a recent project, I solved that with some custom code in the .install file of a custom module. You can see the code in this Github gist: Drupal 8: Custom path aliases exported to code.

# Answer
> 1 votes
I think it's the other way around, it's the route that points to a path. Ideally you could have just one route that would be used for every language and I suppose that works with node/{id} . But when using aliases, the only way I got this working was by defining one route per language. Not pretty at all.

By the way, then in Twig I've used `{{ path('module_name.my_route_name.' ~ language) }}` . Also not pretty at all.

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


title: Is Drush abandoned?

text:
# Question
Title: Is Drush abandoned?
I installed Drush via Composer (like the Drush site recommends). Every time I run `drush dl drupal-7.x`, I get a message telling me that I should use Composer.

> \[notice\] dl has been deprecated. Please build your site using Composer. Add new projects with composer require drupal/\[project-name\]. Use https://www.drupal.org/project/composer\_generate to build a composer.json which represents the the enabled modules on your site.

I downloaded Drupal 8 following these instructions for installing Drupal via Composer, but when I run `drush dl devel` in that project I get this message.

> This codebase is assembled with Composer instead of Drush. Use `composer update` and `composer require` instead of `drush pm-updatecode` and `drush pm-download`. You may override this error by using the `--pm-force` option.

Is there something wrong with my local env, or is Drush a thing of the past now?

# Answer
> 22 votes
You have installed the development `master` branch of Drush. To continue using commands such as `drush dl`, `drush pm-update` and so on, you should install the 8.x branch of Drush.

However, your basic supposition is correct. The Drupal community is moving towards Composer and away from `drush make` and the drush `pm-*` commands. The reason for this is that more and more Drupal modules are depending on code that is distributed via Composer libraries. When using modules with Composer dependencies, the most convenient way to manage your Drupal site is through Composer. See drupal-composer/drupal-project for an example of this.

All of the other Drush commands are still relevant and remain useful.

---
Tags: 8, drush, composer
---


title: Drush Core Update Failed in Docker

text:
# Question
Title: Drush Core Update Failed in Docker
I'm running a local dev Drupal 8 install in Docker using the Docker4Drupal project. I tried to run drush up to update my core from Drupal 8.2.4 to Drupal 8.2.6 and got the following errors:

```
rmdir(/var/www/html/aadlorg/drupal-8.2.6/core/lib): Directory not empty filesystem.inc:150                [warning]
Destination directory /var/www/html/aadlorg/drupal-8.2.6 already exists.                                    [error]
Updating project drupal failed. Attempting to roll back to previously installed version.                    [error]
rmdir(/var/www/html/aadlorg/drupal-8.2.6/core/modules): Directory not empty filesystem.inc:150            [warning]
Destination directory /var/www/html/aadlorg/drupal-8.2.6 already exists.                                    [error]
Unable to move /home/www-data/drush-backups/drupal/20170303142739/drupal to                                 [error]
/var/www/html/aadlorg/drupal-8.2.6.
Could not restore backup and rollback from failed upgrade. You will need to resolve manually.               [error]
Backups were restored successfully.                                                                            [ok]
Backups were restored successfully.                                                                            [ok]
require_once(/var/www/html/aadlorg/core/includes/errors.inc): failed to open stream: No such file or      [warning]
directory bootstrap.inc:562
[03-Mar-2017 14:32:40 UTC] PHP Fatal error:  require_once(): Failed opening required '/var/www/html/aadlorg/core/includes/errors.inc' (include_path='.:') in /var/www/html/aadlorg/core/includes/bootstrap.inc on line 562
Fatal error: require_once(): Failed opening required '/var/www/html/aadlorg/core/includes/errors.inc' (include_path='.:') in /var/www/html/aadlorg/core/includes/bootstrap.inc on line 562
Drush command terminated abnormally due to an unrecoverable error.                                          [error]
Error: require_once(): Failed opening required '/var/www/html/aadlorg/core/includes/errors.inc'
(include_path='.:') in /var/www/html/aadlorg/core/includes/bootstrap.inc, line 562

```

Now my Drupal install is totally broken:

```
Warning: require_once(autoload.php): failed to open stream: No such file or directory in /var/www/html/aadlorg/index.php on line 14

Fatal error: require_once(): Failed opening required 'autoload.php' (include_path='.:') in /var/www/html/aadlorg/index.php on line 14

```

I'm logged into the container as the www-data user and all the directories are owned by that user. So did I do something wrong? Should I try to run drush as root? Just not use drush to update core?

# Answer
> 1 votes
Try using 2.0 version of docker4drupal, in the new version drush installed globally for www-data user to avoid potentials problems with permissions.

---
Tags: drush
---


# Question
Title: How to set a term reference field value from a text field with Rules?
In the user entity, there are 2 fields: a single-valued field\_department\_text A (a text field) and a multi-valued term reference field\_department B. Now, I need to use Rules to append A's value to B when a user was created. I tried, but failed.

# Answer
Looks like you could just use the "add to list" Rules Action.

For multi value fields you should not use "Set a data value" (which is possibly what you've tried, a common mistake when using Rules for such fields).

Refer to the answer to "How to set multiple values to an unlimited Term Refence field with Rules" for "some" more details ...
> 1 votes

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


# Question
Title: Cloudflare country code for language negotiation
Cloudflare.com provides CF\_IPCountry http header. This can be retrieved in php with

```
$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];

```

as they say. It'll return XX if the country cannot be determined.

How can this header be used to negotiate language? (I want to use it so that if users come for example from France, then to be redirected t www.site.com/fr/ homepage, and if they come for any other country in the world go to www.site.com/en/ homepage?)

My research: There are 2 modules for Drupal 7, but I don't think they can do what I want.

One module is http://drupal.org/project/ip2locale, which is dev version and not updated for a year, and the other is http://drupal.org/project/smart\_ip, which says it breaks caching because it adds session variable. They both don't use cloudflare as source of ip.

Is there any php snippet that I can add somewhere, so that $\_SERVER\["HTTP\_CF\_IPCOUNTRY"\] takes me to the locale I want?

If you ask me why I want to use cloudflare header, I suppose that maybe it's faster to determine country and more updated with ips, than other free solutions.

Thanks

# Answer
Drupal provides a hook for those module that implements a new method for detecting the language to use: hook\_language\_negotiation\_info(). This hook gets information about some callbacks, including the one that returns the language ID.
As example of hook, you can look at locale\_language\_negotiation\_info(), and to the three callbacks used for the first provider: locale\_language\_from\_url(), locale\_language\_switcher\_url(), and locale\_language\_url\_rewrite\_url().

Any provider the modules implement are listed on admin/config/regional/language/configure, where the administration user can enable each of them.

The providers that are enabled are called to provide a language ID. For what I can understand code similar to the following one should work.

```
function mymodule_language_negotiation_info() {
  $providers = array();

  $providers['mymodule_cloudflare_provider'] = array(
    'callbacks' => array('language' => 'mymodule_language_from_cloudflare'),
    'weight' => -4,
    'name' => t('Cloudflare'),
    'description' => t("Use Cloudflare to detect the language used where the user is actually located."),
  );

  return $providers;
}

function mymodule_language_from_cloudflare($languages) {
  if (isset($_SERVER["HTTP_CF_IPCOUNTRY"])) {
    $langcode = mymodule_get_langcode($_SERVER["HTTP_CF_IPCOUNTRY"]);
    if (isset($languages[$langcode])) {
      return $langcode;
    }
  }

  return FALSE;
}

```

`mymodule_get_langcode()`, the function for which I didn't write the code, should return the language code from the country code returned from Cloudflare.com.
> 3 votes

# Answer
This module looks to provide some of that functionality: https://www.drupal.org/project/language\_header

It doesn't do the mapping between country code -\> language code however :(
> 0 votes

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


# Question
Title: {{ directory }} not available in parts of menu--main.html.twig
Printing {{ directory }} at the start of the file works fine. But a bit further it's no longer availble:

```
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
    **{{ directory }} {# THIS WORKS #}**
    {% import _self as menus %}
    {% if items %}
        {% if menu_level == 0 %}
            <ul{{ attributes }}>
        {% else %}
            <ul id="navigation">
        {% endif %}
        {% for item in items %}
        <li class="active">
            <a href="{{ item.url }}">
                **{{ directory }} {# THIS DOESN'T WORK #}**
                <img src="{{ directory }}/images/menuicon.png" alt="" />
                {{ item.title }}
            </a>
        </li>
        {% endfor %}
        </ul>
    {% endif %}
{% endmacro %}

```

Any idea why this happens and how to fix it?

# Answer
> 1 votes
The second occurrence of `{{ directory }}` is within a Twig macro. As the Twig documentation mentions, you cannot access the outer variables in a macro:

> But as with PHP functions, macros don't have access to the current template variables.

You can however pass `_context` through a macro parameter and access `directory` that way, or pass it explicitly.

---
Tags: theming, 8
---


# Question
Title: Proper debugging of REST Resource due to cache
I'm creating some REST routes for my custom resources and I'm having some trouble with the debugging aspect of development.

Every time I change the resource's code, should I need to XDebug it, I need to clear Drupal's cache (`drush cr`) for the debug to work.

I have successfully disabled the `ResourceResponse` cache mechanism, so that when the data has changed in Drupal, it is reflected on the response.

Although, I think that maybe due to the annotation mechanism, it's caching the **function** of my REST Resource, and, subsequently, when I change it, those changes don't propagate and Xdebug doesn't pick them up.

I also noticed that `git` signals that the resource plugin file has changed every time I clear the cache, which I think might be related.

Does anyone have some pointers they can share to overcome this?

# Answer
> 1 votes
As per @4k4 's suggestion, I'll try to put into and answer what he helped me figure out (though some details are still a bit murky).

When developing in a local environment, we can override the `settings.php` file with a `settings.local.php` file. In this `local` file, we can setup several settings regarding disabling Drupal's cache functionality.

At the time of writing, the instructions in this link were pretty straightforward and sufficient, but I would like to point out a few aspects that I felt weren't very explicit:

* In my specific case, while developing custom REST Resources, both the *response* and the *function* of my resource were being cached. This is something I want to work like this in production. Although, for development, caching the *function* of my REST Resource meant that everytime I changed it, I had to clear the cache to allow for XDebug to see the changes in my Resource file. I overcame this by following the instructions in the **Find cache bins** section of the above link. Regarding my use case, I think the relevant cache bins should be the `discovery` and `rest`.
* I think (though not sure), that having these bins not cached results in having to clear the cache if you add new discoverable code to your installation, ie, modules, REST resources, maybe themes. As these operations aren't as frequent in my case as the debugging procedure, it's a tradeoff I'm willing to make, but YMMV.
* If you are using `git`to version your code base, be sure to `.gitignore` the `sites/default/settings.local.php` file, otherwise it might end up in your production server, making it substantially slower.
* I also tried following the procedure using Drupal Console as the link above suggested, but apparently since version 1.0.0-rc12 the `drupal site:mode dev` command isn't supported because it proved unstable. Maybe that will change soon.

---
Tags: caching, debugging, 8
---


# Question
Title: How can I distinguish the first image in an image field in a Twig template?
I have a custom field formatter for an image field. The Twig template for the image field is the following:

```
{% for item in items %}
  {{ item.content }}
{% endfor %}

```

Each image is then formatted by the following template:

```
<li data-src={{ fullimage }}><img src="{{ thumbnail }}" /></li>

```

But what I want to do is to format the first image of the field in a different way. I found how I could change the for loop in the template and use `loop.first` to treat the first image differently. But the formatting I want to change is in the inner template that formats each image, the one I call with `item.content`. In the outer template for the entire image field I can distinguish the first image, in the inner template I have no idea how to check for that or how to transfer that information from the outer to the inner template.

Any idea on how I can solve this and format only the first image in a different way?

# Answer
> 5 votes
This code in a `node.html.twig` template will display only the *first* value of an image field that has multiple values:

```
{{ content.field_yourfieldname.0 }}

```

This will only display the *second* value:

```
{{ content.field_yourfieldname.1 }}

```

Source

*Edit: apparently that wasn't really the question, my apologies.*

# Answer
> 0 votes
What you want to do, is to add a suggestion for the image field, based of the delta value of the field item.

Drupal has extensive documentation on working with suggestions in Drupal 8.

---
Tags: 8, media, theming
---


# Question
Title: Ultimate Cron. Invoke a cron from a cron. Set a cron enabled status to TRUE till its queue gets empty. Then set it to FALSE
I am using Ultimate Cron for running individual cron runs and I see Ultimate Cron provide hook\_cronapi() to create own cron task runs and provide enabled key as either TRUE or FALSE.

My objective is create two cron task one cron will run at specified time say 01:00pm and will update the enabled statues of second cron to TRUE so that it will run until it achieved certain condition during each 1 min interval of this second cron task and after this condition is met, will be shut down the second cron task status by setting disabled status to FALSE so that it stop processing uselessly.

So, how do I set that enabled status to TRUE/FALSE during its run time.

# Answer
> 1 votes
Answering my own question.

In your .info file first define ultimate\_cron as dependencies

```
dependencies[] = ultimate_cron

```

Next, in your .module use hook\_cronapi() and define two cron attributes.

```
/**
 * Implements hook_cronapi().
 */
function mymodule_cronapi() {
  $items = array();
  // This launches at specified time once a day.
  $items['custom_cron_1'] = array(
    'title' => t('This will run once every day'),
    'scheduler' => array(
      'name' => 'crontab',
      'crontab' => array(
        'rules' => array('* 2 * * *'),
    ),
  );
  // Run only when invoked and until & unless condition is met so we are not left for tomorrow
  $items['custom_cron_2'] = array(
    'title' => t('Run when invoked'),
    'enabled' => FALSE,
    'scheduler' => array(
     'name' => 'crontab',
     'crontab' => array(
       'rules' => array('*/1 * * * *'),
     ),
  );
  return $items;
}

```

Next step is to define the cron job callback and here in first callback we will schedule to run second cron job.

```
function custom_cron_1() {
  $job = _ultimate_cron_job_load('custom_cron_2');
  // Enable the job.
  $job->enable();
}

```

Next we will define callback for second cron and continue this cron process each minute until condition is met.

```
function custom_cron_2($job) {
  // Check for condition.
  if(...) {
    $job->disable();
  }
  else {
    // Continue the process
  }
}

```

---
Tags: 7, cron, queue
---


# Question
Title: How to set shorter caching time for a paragraph
I have made a paragraph that shows social media wall (based on PHP Social Stream-module). The problem is that the wall isn't updated except when the global cache is recycled.

I have tried (in vain so far) to find out what is the correct way to make the caching "more agile" for that paragraph.

The paragraph is only using the paragraph twig and a a small MYTHEME\_preprocess\_paragraph\__PARAGRAPH\_NAME-function.

As it is placed on the front page on a site under quite a heavy load, I would prefer it not to be un-caching the whole page (not even talking about whole site).

Any suggestions?

wbr

hank

# Answer
> 0 votes
Reload that paragraph block via AJAX.

---
Tags: caching, paragraphs
---


title: What is node_access table?

text:
# Question
Title: What is node_access table?
For granular node access, TAC, TAC lite, Content Access or ACL can be used, but because of some technical limitations and issues, I can not use them.

While implementing the **node access** part of my module, I've realized there are 2 type of hooks, total of 3. I've watched hours of videos, read many articles and I am still confused which one does what:

For granular access control over each node with an specific nid, I can implement hook\_node\_access and see if the user has permission to view/update/delete the requested node.
I will also disable any other kind of node access system (roles permissions to access nodes, TAC, ACL,...) so only my module decides who has access to what.

This should work fine but the question is: what is node\_access table used for? ACL and other fellas use it. But what is it? does it direcrly concern me too?

# Answer
hook\_node\_access() is a standalone hook and has nothing to do with the node\_access table.

hook\_node\_access\_records() and hook\_node\_grants() go together and are different to hook\_node\_access(). These hooks use the node\_access table.

Basically, the node\_access table stores all the access grants for nodes. These grants can then be queried and joined to other queries to check the access rules for a node.

hook\_node\_access\_records() is invoked when writing access rules to the node\_access table and hook\_node\_grants() is invoked when reading them out again.

To give you a better idea of how the hooks work, look at the code where they get invoked from.

For hook\_node\_access\_records() this is node\_access\_acquire\_grants(). It invokes the hook and then writes all the returned grants to the node\_access table.

hook\_node\_grants() is called from a few places, but generally via the node\_access\_grants() function, which is called from a few places. Take a look at the node\_access() function as an example.

It queries the node\_access table, adding to the query conditions any access grants returned by modules that implement hook\_node\_access\_grants(). Note that grants are also alterable via hook\_node\_grants\_alter().

While you are looking at the node\_access() function you can also see how hook\_node\_access() is called and you'll see how it is different and why it's not as flexible a solution to access control.

In case you haven't seen it, this is a good article on the topic: http://www.phase2technology.com/blog/drupal-7-node-access-grants-locks-and-keys/
> 7 votes

# Answer
nid - node id
gid - userid if realm is "workflow\_access\_owner". role\_id if realm is workflow\_access
realm - enum (all, workflow\_access\_owner, workflow\_access)
grant\_view - has view privileges?
grant\_update - has update privileges?
grant\_delete - has delete privileges?
> -1 votes

---
Tags: users
---


# Question
Title: Display thumbnailPhoto from Active Directory - Open atrium and LDAP modelude
I am using Open Atrium for my intranet. I got LDAP module installed, the server is configured, same as User, Authentication, and Authorization.
The communication with my Active Directory is successful, I have all my fields and properties populated correctly, but THUMBNAILPHOTO

Do I need to configure something else?? What I am missing? My active Directory uses CodeTwo.

Thanks,

Sofia

# Answer
You need to configure your ldap server

> 1. Go to admin/config/people/ldap/servers
> 2. Click edit
> 3. Go to "LDAP User to Drupal User Relationship" tab
> 4. Under "Thumbnail attribute" add "thumbnailphoto" (without quotes)
> 5. Save your settings

Now your ldap server is configured to automatically copy user thumbnail from ldap (Active Directory) to Drupal.
> 1 votes

---
Tags: authentication-authorization, distributions
---


# Question
Title: Get the last revision id of any given entity?
Is there a single, unified method in Drupal 7 to get the last revision id for any given entity object? If so, what is that method?

# Answer
I think `entity_extract_ids()` is the quickest you'll get:

> Helper function to extract id, vid, and bundle name from an entity.

e.g.

```
list($nid, $vid, $bundle) = entity_extract_ids('node', $some_node);

```
> 6 votes

# Answer
Calling {entity\_type}\_load for any entity will load the most recent version **(caution - see comment below)**

For example for a node calling `node_load(1)` will load the most recent version of that node.

The revision id will be found in the vid property.

```
$node = node_load(1); // load the most recent version of node with id 1
$most_recent_version_id = $node->vid; // this is where you find the version id

```

Or for a user:

```
$user = user_load(1);
$most_recent_version_id = $user->vid; // this users version id

```
> 0 votes

# Answer
```
$nid = 1;
$vid = db_query('SELECT vid FROM {node_revision} WHERE nid = :nid ORDER BY vid DESC LIMIT 0,1', array(':nid' => $nid))->fetchField();
$oNode = node_load($nid, $vid);

```

The above code will load the latest revision for NID 1 ($nid = 1, in this case) by finding the highest node\_revision.vid. It then loads that revision into $oNode.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Alter content translation page access based on content's field value
I have a content type: `Test` I want to alter the permission to translate it based on one of it's field value. Take the following use-case (field type, and role doesn't matter):

If `field_test == '1'` then the `Translate` link task should not be displayed (because the current user role does not have permission to view it).

What do you suggest?

# Answer
For me this official link helped:

**About route alteration:** https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones

**About access check:** https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes

@Oleg Videnov: The first link you provided in your answer is good as well!
> 2 votes

# Answer
I think something like that already has been answered before:

Could you take a look and tell us if that helps you ?

https://drupal.stackexchange.com/a/208817/8375

Other outside resources: https://www.previousnext.com.au/blog/controlling-access-drupal-8-routes-access-checks
> 3 votes

---
Tags: 8, users, i18n-l10n, nodes
---


title: merging content types

text:
# Question
Title: merging content types
I have used Drupal to build a helpdesk site, this site allows employees to submit a ticket to the IT department. Within the site is all of the computer assets that are managed. I want to be able to allow the IT technician to attach the ticket submitted to the asset that is in the system. For example I have a printer with asset #12345 and someone submits a ticket saying it is working. The IT technician assigned to the ticket then competes the ticket and comments on what he/she did to fix it within the content type for the ticket. I need the comments from the helpdesk ticket to be attached to asset #12345.

Hope this makes sense.

# Answer
If I understand your question correctly, you want your 'IT technician' user to be able to relate a 'ticket' (content type) to one (or more) 'assets' (also a content type).

You can use the Entity reference module and provide a field on the 'ticket' content type that references to a node of the type 'assets'. The module has been integrated in Drupal 8 core, so no need to download the contributed module for that version.

This should be a good starting point in order to get the functionality that you want.
> 0 votes

---
Tags: nodes
---


# Question
Title: D8: The same content type, but different url path aliases pattern based on paragraphs. Possible?
I have several paragraphs nested into one content type. Users can add only one type of paragraph. Is it possible to create a url alias pattern based on paragraphs? For instance, I have paragraphs "car", "bike", and "boat" in one content type "garage". If the user adds a "car" paragraph the url alias should be garage/car/etc, and for boat garage/boat/etc etc. Possible? It is generating the same url pattern for now.

# Answer
> 3 votes
Since you mention that you only have a single allowed paragraph, something like \[node:paragraph\_field:entity:type:target\_id\] *might* work, but untested. That will use the machine name of the referenced paragrap type.

If not, you can always implement a custom token on nodes and then do whatever you want using hook\_token\_info() and hook\_tokens().

I also agree with others that this seems like a somewhat strange architecture and usually list/term fields are used for such a categorization, this will most likely also work better if you ever need to do something like an exposed filter in a view and so on.

# Answer
> 2 votes
With pathauto there are some tokens available for any field of a node, including paragraphs.

I think @Kevin is right though, paragraphs connected with terms.

---
Tags: 8, path-aliases, paragraphs
---


# Question
Title: How to add Callback function for delete operation?
I want to add a custom callback function for my delete operation.

```
$form['table'][$entity->id()] = [
        'title' => [
          '#type' => 'textfield',
          '#default_value' => $title,
        ],
        'status' => [
          '#type' => 'checkbox',
          '#default_value' => 1,
          '#disabled' => ($delta == 0),
        ],
        'weight' => [
          '#type' => 'weight',
          '#default_value' => $delta,
          '#attributes' => array('class' => array('mytable-order-weight')),
        ],
        'operations' => [
          '#type' => 'operations',
          '#links' => [
            'view' => [
              'title' => $this->t('View'),
              'url' => $entity->toUrl(),
            ],
            'edit' => [
              'title' => $this->t('Edit'),
              'url' => $entity->toUrl('edit-form'),
            ],
            'delete' => [
              'title' => $this->t('Delete'),
              // add callback function.
            ],
          ],
        ],
      ];

```

How do I do this?

What I tried so far was

```
'delete' => [
              'title' => $this->t('Delete'),
              '#callback' => 'myDeleteFunction'
            ],

```

# Answer
> 4 votes
The operations are a list of links. If you want to delete a different entity see this example from the core workflows module how to build a delete link:

*WorkflowStateEditForm::Form()*

```
  $links['delete'] = [
    'title' => t('Delete'),
    'url' => Url::fromRoute('entity.workflow.delete_transition_form', [
      'workflow' => $workflow->id(),
      'workflow_transition' => $transition->id()
    ]),
  ];

```

# Answer
> 2 votes
As @4k4 said, operations are just links. You can not have a callback on an operation. If you want to have just a callback, you need to make it a #type submit and display it separately from operations.

Otherwise you can make a route that does its thing and then redirects back to your list. Make sure to use a csrf\_token then however, to protect against CSRF attacks.

---
Tags: 8, forms
---


# Question
Title: CKEditor: *During* WYSIWYG edit, how to show caption beneath image?
When editing a body field with image and caption, the caption does not *display* during editing. Once saved it is visible - when the content is viewed.

Implementation-wise, I've added a caption field to the Image entity via the Entity View Mode config pages - admin/structure/file-types/manage/image/fields

Any thoughts on how to get the caption to show during edit?

CKEditor 4.3 supports captions but there would need to be support for the Drupal side of the implementation.

# Answer
> 1 votes
As of CKEditor 4.3, they now have widgets in the CKEditor side. They have introduced the Image2 plugin/widget, which supports image captions. The problem I've seen here is that Drupal has not caught up with this, so if you're using the media module for a file browser, it looks like that functionality is not yet ported to this newer version. However, if you just care about captions, it works.

See: http://ckeditor.com/addon/image2 for the plugin. I've been using it with the CKEditor Module, but it should work just as fine with WYSIWYG + Ckeditor Library.

# Answer
> 0 votes
After discussing with my colleagues (thanks folks!), their idea for a solution is to write a filter for the JSON generated by the WYSIWYG.

The caption text is present in the JSON. So, extending the existing filter ought to be the solution.

# Answer
> 0 votes
I've been doing some more research and I gather you have gone down the Media/File Entity/Entity View Modes route as described at http://www.58bits.com/blog/2013/03/06/how-to-add-captions-to-images-in-drupal.

That seems a heck of a lot of work to go to in order to write a caption under an image and it is still not wysiwyg.

So here is another answer using Wysiwyg/TinyMCE and the dev version of Caption Filter. See discussion at https://drupal.org/node/696734. (Edit. There was some work done on integrating with CKEditor too but I don't think this has been committed although there are some patches, should it be important for you to stick with CKEditor.)

The upshot is as shown below. I was pleased to find I could put html in the caption.

# Answer
> 0 votes
There are conflicts between the CKeditor Image2 plugin and Media module. If you're looking to align + caption your images while maintaining the media tag in your WYSIWYG, the most current recipe can be found here: https://www.drupal.org/node/2843391

---
Tags: 7, entities, media, wysiwyg
---


title: Get taxonomy fields on node.tpl.php

text:
# Question
Title: Get taxonomy fields on node.tpl.php
I have a taxonomy attached to my nodes. The taxonomy has an extra image field attached to it. I can find the taxonomy title field at:

```
$content['field_news_outlet'][0]['#title']

```

but I can't seem to find the image field I attached to this taxonomy.

If I check with kpr() or dpm():

```
$term=taxonomy_term_load($tid);
$value=field_get_items('taxonomy_term',$term,'field_news_outlet_logo');

```

I can see the field name there but the image uri doesn't seem to appear anywhere in there. The only image uri I can find is the one for the site's logo.

# Answer
I found the problem. I hardcoded $tid as 1 in my template file.
> 1 votes

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


# Question
Title: How do I display page numbers in a book?
I have my nodes organized using the book module. I would like to be able to display the page number at the bottom of the page. The pages would be numbered according to the order in the book outline. Is this possible? I even tried looking for a PHP code snippet I could put in book-navigation.tpl.php or similar.

# Answer
> 0 votes
You can add simple PHP code in your node.tpl.php

```
    <?php
      $allbook = book_toc($node->book['bid'],3);
     $allbook_chapter = array_search($node->book['mlid'], array_keys($allbook));
print $allbook_chapter;
            ?>

```

This code prints page number of current node. This in't better way of course. Moving this logic to template.php is better solution.

---
Tags: nodes
---