# Question
Title: What's the best way to put in a link to a translated node in a D8 template?
There just has to be a better way to insert a link to an alternative translation than this:

```
function THEME_preprocess_node(&$variables) {

  $node = &$variables['node'];

  // Current language
  $current_language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $variables['current_language'] = $current_language;
  $variables['current_language_url'] = $node->toUrl()->toString();

  // If this is a multi-lingual node, get links to alternative language.
  $languages = $node->getTranslationLanguages();
  foreach ($languages AS $langcode => $language) {
    $node_ja = ($langcode == 'ja') ? $node->getTranslation('ja') : null;
    if ($node_ja && is_object($node_ja) && $current_language == 'en') {
      $node_url = $node_ja->toUrl()->toString();
      $variables['node_url_ja'] = $node_url;
      $variables['node_url_ja_translation'] = '<a href="' . $node_url . '">Japanese</a>';
    }

    $node_en = ($langcode == 'en') ? $node->getTranslation('en') : null;
    if ($node_en && is_object($node_en) && $current_language == 'ja') {
      $node_url = $node_en->toUrl()->toString();
      $variables['node_url_en'] = $node_url;
      $variables['node_url_en_translation'] = '<a href="' . $node_url . '">English</a>';
    }

  }

  // Display link to alternate translation.
  $variables['node_url_translation'] = ($current_language == 'en') ? $variables['node_url_ja_translation'] : $variables['node_url_en_translation'];

}

```

It works, but it's just not at all graceful. How should this be written? I just want to put in a link like this into a templates/node.html.twig file:

```
{{ node_url_translation|raw }}

```

# Answer
> 1 votes
The easiest method of providing language switching links would be using the language manager's getLanguageSwitchLinks() method. However, this might - depending on your language settings - also provide fallback links, if the node is not translated to the target language. An abstract example:

```
use Drupal\Core\Language\LanguageInterface;

function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  $language_manager = \Drupal::languageManager();
  $current_language = $language_manager->getCurrentLanguage()->getId();
  $links = $language_manager->getLanguageSwitchLinks(LanguageInterface::TYPE_CONTENT, $node->toUrl());

  $variables['current_language'] = $current_language;
  $variables['translations'] = [
    '#theme' => 'links',
    '#links' => $links,
    '#set_active_class' => TRUE,
  ];
}

```

**For your use case** \- to show links to translated content only -, your approach to using getTranslationLanguages() of the TranslatableInterface is on the right track.

But be aware, that it will return entity translation instances also for **non-published** \- or otherwise limited - content translations, to which the current user may not have view access to. Hence, he will get an "Access denied" error after clicking the links.

Additionally, the code should be generic enough to allow for further languages being added using the admin UI in a later stage of the application's life-cycle, without having to touch your preprocessing/templates anymore.

Therefore some suggested improvements for your solution:

* Check, whether the current user has access to the translation.
* Avoid using hard-coded language identifiers. As I suppose you did so to not add further links for the current language, you should use your `$current_language` variable to do the checks.
* Avoid using hard-coded language link labels. Consider using \Drupal\Core\Language::getName() instead.
* Use a list of language links instead of a dedicated variable for each language, and pass that list to the template. This way you can just iterate over the links.
* Don't return markup (the links) from within your preprocess hook, but allow creating the links within the templates.

This sums up to something like this:

```
use Drupal\Core\Template\Attribute;

function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  $language_manager = \Drupal::languageManager();
  $current_language = $language_manager->getCurrentLanguage()->getId();

  $links = [];
  foreach ($node->getTranslationLanguages() as $langcode => $language) {
    // Skip any translation that cannot be viewed.
    $translation = $node->getTranslation($langcode);
    if (!$translation->access('view', NULL, TRUE)->isAllowed()) {
      continue;
    }
    // Get URL of the translation.
    $url = $node->toUrl('canonical')
      ->setOption('language', $language)
      ->setAbsolute()
      ->toString();
    // Optionally provide an 'active' class.
    $classes = [];
    if ($langcode == $current_language) {
      $classes[] = 'active';
    }
    // Construct information for a link.
    $link = [
      'language' => $langcode,
      'is_current' => $langcode == $current_language,
      'url' => $url,
      'title' => $language->getName(),
      'attributes' => new Attribute(['class' => $classes]),
    ];
    $links[] = $link;
  }

  $variables['current_language'] = $current_language;
  $variables['translations'] = $links;
}

```

In your template, you can then create the links like this:

```
{% if translations %}
  {% for item in translations %}
    {# Optionally skip current language #}
    {% if not item.is_current %}
      <a href="{{ item.url }}"{{ item.attributes }}>{{ item.title }}</a>
    {% endif %}
  {% endfor %}
{% endif %}

```

---
Tags: i18n-l10n
---


title: The block isn't shown on the front page

text:
# Question
Title: The block isn't shown on the front page
I have a view block that shows a sub-set of nodes. In the configuration page, the autopreview section shows content, so I know the filters for the view are set up correctly. I configured the block to show on only the listed pages and entered `<front>` for the page. Unfortunately, the front page shows only the following content and a static block.

> No front page content has been created yet.
> •Add new content

The weird part is that this static block is configured the same way the view is configured to show only on the front page.

Why doesn't the view block appear on the front page?

# Answer
> 0 votes
There is something else you should check. If this is a new site, and you have newly named regions, make sure that the regions have underscores (instead of dashes.) If you need to convert any dashes to underscores, you'll have to reassign and re-enable the blocks on the Structure \> Block Layout page.

# Answer
> -1 votes
Try setting your block to only display on on /node
Thats what I had to do on my Drupal 8 site for things to show up on the front page. Also if you want the:

```
No front page content has been created yet.

 •Add new content

```

To disappear, you'll need to edit the 'Frontpage' view and get rid of those values from the view.

---
Tags: views, blocks
---


# Question
Title: How to instantiate a service inside ServiceProvider?
I need to instantiate a service inside ServiceProvider. At that point the container is not built.

Any ideas or useful links?

```
<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

class MyModuleServiceProvider extends ServiceProviderBase {

  public function register(ContainerBuilder $container) {
    parent::register($container);

    // How to get a service here?
    // Currently container is not built :)

  }

}

```

# Answer
> 0 votes
You can't get services at this point. This interface ServiceProviderInterface is only for registering services, not for retrieving For retrieving service with future altering try to use ServiceModifierInterface

---
Tags: 8, dependency-injection, symfony-services
---


# Question
Title: Exposed Form not showing even in preview of view
I am using a simple view, and exposed filter to let user chose post by content-type. Exposed Form however not appearing, not even in views preview. I am using Bartik as front-end theme and seven as admin theme.

```
$view = new view();
$view->name = 'admin_dashboard';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Admin Dashboard';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Admin Dashboard';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '20';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['default_row_class'] = FALSE;
$handler->display->display_options['style_options']['row_class_special'] = FALSE;
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'type' => 'type',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'type' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['style_options']['override'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Type */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'cpanel';

```

# Answer
Quote from your own comment:

> I had commented out the $title and exposed filter output from views main template file from the module. Problem is fixed now.

So it looks like that is the answer to your question ...
> 1 votes

---
Tags: 7, views
---


# Question
Title: Display parent term based on child term in views
I have a vocabulary with the following structure:

```
Vocabulary
Parent term 1
    Child term 1.1
        Child term 1.1.1
    Child term 1.2
        Child term 1.2.1
Parent term 2
    Child term 2.1
        Child term 2.1.1
    Child term 2.2
        Child term 2.2.1

```

Based on the above structure of taxonomy terms, I have a view of all the terms of last level like,

```
Child term 1.1.1
Child term 1.2.1
Child term 2.1.1
Child term 2.2.1

```

Now, i want to create the view, which list me 2nd level of taxonomy term by passing term id of the 3rd level.

> Example:- If i pass term id of Child term 2.2.1 in contextual filter, i should see the Child term 2.1 as a result of view.

# Answer
> 0 votes
You need to add **Taxonomy term: Parent term** in RELATIONSHIPS of the view.

Then in the field section select the **Relationship**

That's it. Whatever term you enter in the contextual filter it fetches the parent term of it.

Here is entire exported view (example).

```
$view = new view();
$view->name = 'tag_relation';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Tag relation';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Tag relation';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Parent term */
$handler->display->display_options['relationships']['parent']['id'] = 'parent';
$handler->display->display_options['relationships']['parent']['table'] = 'taxonomy_term_hierarchy';
$handler->display->display_options['relationships']['parent']['field'] = 'parent';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'parent';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Contextual filter: Taxonomy term: Name */
$handler->display->display_options['arguments']['name']['id'] = 'name';
$handler->display->display_options['arguments']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['arguments']['name']['field'] = 'name';
$handler->display->display_options['arguments']['name']['default_action'] = 'empty';
$handler->display->display_options['arguments']['name']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['name']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['name']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['name']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['name']['limit'] = '0';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'tags' => 'tags',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'tag-relation';

```

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


# Question
Title: Creating entity fields based on the fields from another entity
I've been trying to create a data structure that resembles something like:

```
            +-----------+-----------+-----------+
            | Service 1 | Service 2 | Service x |
            +-----------+-----------+-----------+
            |  Price 1  |  Price 2  |  Price x  |
+-----------+-----------+-----------+-----------+---------------+
| Feature 1 |    Yes    |    Yes    |    Yes    | Description 1 |
+-----------+-----------+-----------+-----------+---------------+
| Feature 2 |     1     |     6     |    20     | Description 2 |
+-----------+-----------+-----------+-----------+---------------+
| Feature x |    No     |    No     |    Yes    | Description x |
+-----------+-----------+-----------+-----------+---------------+

```

I've created a content entity `Services`, which has the following fields:

1. Service Name
2. Price
3. Feature 1
4. Feature 2
5. Feature x

This works great, until I realise that I'm not including the descriptions of each feature.

Drawing on my knowledge of database normalisation, I intend to extrapolate the description and feature to its own content entity, `Services Info`. I think that would probably work just fine, with one small exception, I now need to maintain the list of features in two entities, something I'm loathed to do.

Is there any way I can get Drupal to synchronise the fields across two tables? So that if/when I add more features to the `Services` entity, it'll appear in the `Services Info` entity, waiting for me to input a description for it?

Or, if there's a better, more Drupally way to approach this problem, then please feel free to chime in!

**UPDATE**:

I realise that my question might not be clear enough, so I thought I'd explain what I'd do if I weren't using Drupal to make this...

I'd have the following SQL tables:

tbl\_services:

```
SERVICE NAME (FK)
FEATURE NAME (FK)
SERVICE FEATURE VALUE

```

tbl\_services\_info:

```
SERVICE NAME (PK)
PRICE

```

tbl\_services\_features:

```
FEATURE NAME (PK)
FEATURE DESCRIPTION
FEATURE RECOMMENDED

```

... Now I'm looking at it, I guess I'm missing an entity..? Which if I introduced I could have them reference each other correctly?

If I were to implement it this way I'd also have the issue of not being able to REQUIRE that **ALL** `SERVICE NAMEs` have **ALL** `SERVICE FEATURE VALUEs` declared for **ALL** `FEATURE NAMEs`... Could I? Or would I just have to create a custom input form for the entities?

# Answer
Sounds like you want to "listen" for the creation of entities of type `Services`, and upon creation, you want to programmatically create another of type `Services Info`. For that, I'd recommend adding the hook\_ENTITY\_TYPE\_insert hook into your custom module. Replace `hook` and `ENTITY_TYPE` with your custom module name and entity type, of course.

The function signature will include `$entity` as a variable, so you can do any sort of tests you want to do on it (for example, make sure the corresponding Services Info entry hasn't already been created, to avoid a possible infinite loop if you ever decide to write the sync for both entity types).

This method will look something like:

```
function my_module_services_insert($entity) {

  // If desired, add code here to check for pre-existing mathing Services Info; this will depend on your implementation.
  // For example, if name is unique, run an entity query for services_info entities with a matching name.

  $new_entity_fields = [
    'name' => $entity->getName(), // This assumes you want the entry to have the same name as the Services entry; change if desired
    // Other fields as desired
  ];
  $storage = \Drupal::entityTypeManager()->getStorage('services_info'); // replace 'services_info' with your entity type
  $entity_new = $storage[$content_type]->create($new_entity_fields);
  $entity_new->save();
}

```

That should do the trick. Good luck!
> 1 votes

---
Tags: 8, entities
---


title: Minimum schema version

text:
# Question
Title: Minimum schema version
I am updating my site from Drupal 8.2.1 to 8.2.4, while running update.php I encounter this problem

> The installed schema version does not meet the minimum. Your system schema version is -1. Updating directly from a schema version prior to 8000 is not supported. You must migrate your site to Drupal 8 first.

I am unable to proceed any further. What exactly is causing this problem?

# Answer
Use Drush. The following commands worked for me.

```
drush updb -y
drush cr

```
> -1 votes

---
Tags: 8
---


# Question
Title: How do I the add vocabulary name or the ID to the <body> CSS classes?
For theming purpose, I would like to add in body class the vocabulary name (or ID) of the current taxonomy. I know how to add a class based on the taxonomy term ID.

For example, I have the following vocabulary (*Color*).

* red (term id = 1)
* green (term id = 2)
* yellow (term id = 3)

I know how to get `<body class="term-id-1">`. I would like to get `<body class="vocabulary-id-1">` or `<body class="vocabulary-name-color">`.

I've tried the following code.

```
function mytheme_preprocess_html(&$variables) {
  // Works
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $variables['term_id'] = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
  }
  // doesn't work
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_vocabulary.canonical') {
    $variables['vocabulary_id'] = \Drupal::routeMatch()->getRawParameter('taxonomy_vocabulary');
  }
}

```

As said in the comments, it doesn't work, and I am not able to use the vocabulary name, or its ID as CSS class to add to the `<body>` tag.

How can I achieve this?

# Answer
> 7 votes
The vocabulary id is not a route parameter, unless you have a route to view/edit a vocabulary, but these are all admin routes. So you need to get the information from the term:

```
function mytheme_preprocess_html(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    // load the term entity and get the data from there
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['term_id'] = $term->id();
    $variables['vocabulary_id'] = $term->bundle();
  }
}

```

bundle() returns the vocabulary of the term. This is the same as a content type of a node. Or a block type of a custom block. All are fieldable bundles of entities.

So if you use `bundle()` on a node you'll get for example the machine name `article`.

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


# Question
Title: Calling a module function from jQuery and Ajax
I am getting some problems calling a custom module function from jQuery and AJAX.

### ajax\_example.module

```
function ajax_example_init() {
    drupal_add_js(drupal_get_path('module', 'ajax_example') . '/ajax_example.js', array('scope' => 'footer'));
}

function ajax_example_menu() {
  $items['ajax_username'] = array(
    'title' => 'Get Current User Name',
    'page callback' => 'ajax_example_get_username',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function ajax_example_get_username() {
  global $user;
  $user_name = $user->name;
  drupal_json_output($user_name);
}

```

### ajax\_example.js

```
(function ($) {
  Drupal.behaviors.ajax_example = {
    attach: function (context) {
      $.ajax({
        url: '/ajax/username',
        success: function(data) {
          console.log(data);
        }
      });
    }
  }
})(jQuery);

```

I am trying to call JavaScript by a JS Injector module using these commands.

```
(function($) {
  $.ajax({
    url: 'ajax_username',
    type: "GET",
    success: function (data) {
      console.log(data);
    }
  });
})(jQuery);

```

Unfortunately, I get the same 404 error again and again.

What am I doing wrong?

# Answer
> 1 votes
To answer to *The second block of JS code is a test I am trying to do to call the ajax\_username function of ajax\_example.module.* you wrote in your comment, what you can use in JavaScript code like `$.ajax({url: 'ajax_username'})` as `url` is a route exposed in the `hook_menu()` implementation of a module, or the path of a PHP file. It isn't the name of a PHP function implemented from a module, nor the name of a file containing Javascript code (without the *.js* extension).

As concrete example of what Drupal core modules do, see the content of the statistics.js file.

```
(function ($) {
  $(document).ready(function() {
    $.ajax({
      type: "POST",
      cache: false,
      url: Drupal.settings.statistics.url,
      data: Drupal.settings.statistics.data
    });
  });
})(jQuery);

```

What `$.ajax()` gets as `url` is `Drupal.settings.statistics.url`, set from `statistics_node_view()` with the following code.

```
$settings = array('data' => array('nid' => $node->nid), 'url' => url(drupal_get_path('module', 'statistics') . '/statistics.php'));

```

In the test site I am using, the output of `url(drupal_get_path('module', 'statistics') . '/statistics.php')` is /modules/statistics/statistics.php.

So, if you want to call the callback associated to your ajax\_username menu, you need to use `$.ajax({url: '/ajax_username'})` or `$.ajax({url: '/index.php?q=ajax_username'})`, but in both the cases, the module **must** be installed and enabled.

If you don't want to enable a module for that, you cannot use `hook_menu()`, but you could create a PHP file containing the code to use, in the same way the Statistics module does with its statistics.php file.
**Be warned**: Use this only if you know exactly what you are doing, as using the wrong code could be a security risk for your site and its data.

I would rather use `hook_menu()`.

# Answer
> 0 votes
Your first JS example has a URL of /ajax/username, which according to the `hook_menu` implementation you haven't registered, so that explains the 404 for that one.

The second JS example uses an absolute rather than relative URL, which will only work if you're on the first level of the path (/, /foo, /bar, etc).

Assuming your module is installed and enabled, is definitely named `ajax_example`, and Drupal's caches have been cleared, it seems most likely that you're executing that second example on a path that's lower than the root (e.g. /foo/bar), and the fact that the URL is absolute means the browser is looking for /foo/bar/ajax\_username, which doesn't exist.

Changing the URL to /ajax\_username in JS should fix the problem.

---
Tags: javascript, ajax
---


# Question
Title: FieldCondition in an EntityQuery for media is causing a website error
This entityQuery in a theme preprocess function in Drupal 8 is working great:

```
$query = \Drupal::entityQuery('media')
    ->condition('status', 1)
$result = $query->execute();

```

But as soon as I add this fieldCondition for a boolean field, I get a website error:

```
$query = \Drupal::entityQuery('media')
    ->condition('status', 1)
    ->fieldCondition('field_flagged', 'value', '1', '=');
$result = $query->execute();

```

What is wrong in the above code?

# Answer
> 6 votes
There's no `fieldCondition` method, `condition` works for all fields:

```
$query = \Drupal::entityQuery('media')
  ->condition('status', 1)
  ->condition('field_flagged', 1);
$result = $query->execute();

```

---
Tags: entities
---


title: How can I create a breadcrumb?

text:
# Question
Title: How can I create a breadcrumb?
I have to create a breadcrumb so that, if a page has a menu, the breadcrumb should be the menu with its hierarchy. If the node page doesn't have a menu, the page title should be in the breadcrumb.

I tries the Menu breadcrumb module. Menu pages are coming correctly, but other pages are showing the page title in the breadcrumb.

How can I achieve this?

# Answer
> 2 votes
You can do this by creating custom module and creating yourmodule.services.yml

```
services:
  yourmodule.breadcrumb:
    class: Drupal\yourmodule\FwsBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 100 }

```

and creating custom class which should extend **BreadcrumbBuilderInterface** like this

```
class FwsBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  public function applies(RouteMatchInterface $route_match) {
    $route = $route_match->getCurrentRouteMatch();
    // Add conditionals that return TRUE when the current route should have it's
    // breadcrumb handled here.
    return FALSE;
  }

  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addCacheContexts(['route']);

    // Add logic here that builds up the breadcrumbs based on desired behaviour.
    $links[] = Link::createFromRoute(t('Home One'), '<front>');

    $breadcrumb->setLinks($links);

    return $breadcrumb;
  }
}

```

I have also got the above code from http://drupal.stackexchange.com

You can also add new and alter previous breadcrumbs in hook\_preprocess\_HOOK function like this

```
function yourmodule_or_yourtheme_preprocess_breadcrumb(&$variables) {
    // Your Logic Here
}

```

---
Tags: breadcrumbs
---


title: How to nest a field collection?

text:
# Question
Title: How to nest a field collection?
How to nest Field Collections in Drupal 8?

I have *Field Collection* installed and working fine. What I want to achieve is that for example, I'll have a box on the front end which may contain 6 tabs of content, or two boxes each containing 3 tabs.

First part is working: I have a 'tabs' Field Collection with which I can 'add another item' (tab).

For the second option I need a 'box' Field Collection that contains nothing but the 'tabs' Field Collection.

# Answer
Using the Field collection module in Drupal 8 seems to NOT be a good idea anymore. It currently only has an alfa1 release from April 2016). Instead you may want to try to use Paragraphs instead, as suggested also on the Field collection project page, i.e.:

> Paragraphs is likely to replace field collection for Drupal 8. Field collection is on its way to being deprecated. It is recommended to use paragraphs instead of field collection for Drupal 8 projects.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How do I manually update without using Drush nor Composer?
Is it possible to upgrade Drupal from 8.3.7 to 8.4 without Drush or Composer?

Even though I have used composer I am not comfortable with using terminal/console command lines operations. So far used composer to install and remove modules. That's about it.

Looked at manual update options. There are no instructions yet for this method. https://www.drupal.org/docs/8/update/update-core-manually-via-gui-option-1

This is what I am planning on doing.

Download and extract Drupal 8.4 zip.

* Backup database through PHPMyAdmin and website before proceeding.
* Put site in maintenance mode by going to configuration -\> maintenance mode
* Remove ‘core’ and ‘vendor’ directory project dir.
* Upload the core directory from the Drupal 8.4 version downloaded.
* Upload .htaccess,composer.lock and composer.json files from the downloaded Drupal to project.
* Upload vendor directory from the download Drupal version to your project.
* Go to site.com/update

Am I missing something? Or should I figure out the composer route?

# Answer
The official update method is described in UPDATE.txt:

http://cgit.drupalcode.org/drupal/tree/core/UPDATE.txt?h=8.4.x

This is basically what you've described in the question. You don't need composer to update core.

If you want to switch your existing installation to composer a risk free way would be to start a new project, see Updating core with Composer doesn't work.
> 2 votes

---
Tags: updating
---


title: View path variable

text:
# Question
Title: View path variable
How can I programmatically fetch the view path field value?

I am able to fetch title and body, but but I cannot get the path.

```
function view_path_views_pre_render(\Drupal\views\ViewExecutable $view) {
  kint($view->result);
  if ($view->id() == 'view_idea_shots_for_home_page' && $view->current_display == 'block_3') {
    foreach ($view->result as $value) {
      kint($value->_entity->get('title')->value);
      kint($value->_entity->get('body')->value);
    }
  }
}

```

# Answer
> 1 votes
`path` is not a field stored in the entity. It is a computed views field plugin, which can only be outputted by applying Path::render():

```
$path = $view->field['path']->render($value);

```

---
Tags: views
---


# Question
Title: How to handle / cleanup obsolete aggregated css / js?
I'm only using Drupal 7 built in CSS / JS aggregation, however the files folder where the css.gz and js.gz files live are filling up at a fairly rapid pace, and while I'm sure it'll be a while before it starts to totally fill up the drive, nows as good a time as any to get a handle on the situation.

* Current file count in /js is 335
* Current file count in /css is 451

Is there any standard method I should be employing to deal with this situation? I'd prefer a solution that keeps the drupal in the loop.

Additionally, I see that many of the gz files have non-gz counterparts. Is there some reason both .css and .css.gz files are kept? Degredation maybe?

Thanks

# Answer
This is actually by design so that cached pages with older versions of files don't get broken. See this closed issue.

TL;DR: They will be deleted automatically 30 days (or whatever your `drupal_stale_file_threshold` variable is set to) after they were created via `drupal_clear_css_cache()` and `drupal_clear_js_cache()`. So the solution is to modify the `drupal_stale_file_threshold` value to something lower than the default 30 days.

* **When are old files deleted**
> Old cache files are not deleted immediately when the lookup variable is emptied, but are deleted after a set period by drupal\_delete\_file\_if\_stale(). This ensures that files referenced by a cached page will still be available.

`drupal_delete_file_if_stale()` defaults to 30 days - so if a) Cron is running properly and b) you see aggregated files older than 30 days, you have a different problem.

`variable_get('drupal_stale_file_threshold', 2592000)` is the 30 day check. `variable_set('drupal_stale_file_threshold', 172800)` would change the timeout to two days. On a site where cache handling is strictly controlled, the time could be even shorter.

Source: http://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_build\_css\_cache/7
See `drupal_delete_file_if_stale()` for more information.

* **Is there some reason both .css and .css.gz files are kept?**
> If CSS gzip compression is enabled, clean URLs are enabled (which means that rewrite rules are working) and the zlib extension is available then create a gzipped version of this file. This file is served conditionally to browsers that accept gzip using .htaccess rules.

Source: http://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_build\_css\_cache/7 (In the function comments)

Also see `drupal_build_js_cache()` which is nearly identical to `drupal_build_css_cache()`.
> 16 votes

# Answer
After 4 years, I have to disagree with the first answer, where the author states :

> "This ensures that files referenced by a cached page will still be available.".

Maybe certains things have been changed/optimized in the aggregation provisioning of older files, but if I delete an older file manually on the server at files/advagg\_js (which I apparently still use in one of my browsers), the subsequent page reload is regenerating exactly the same file again with recently added javascript source code, as if `drupal_build_js_cache()` was executed on that aggregated file name.

eg. `js__22qMV1d_G25luSFBkuR7bIuKD5FE80eKuXx6ldibEixg__yjA2JTeF2f1LUJ3PMdjMr8k9nOPZQJIcvVw-c5Gz_yc__FY0NTHFBVMd9MIGE5srDXTejEZGP-ccSH7UX2zImN-0.js`

So I am concluding setting a significant lower `drupal_stale_file_threshold` would not cause any problems, and even deleting all aggregated files followed by a cache clear will force a regeneration of aggregates (tested and confirmed working on page reloads)
> 0 votes

# Answer
* Get the Rules module
* Add a new rule that will be executed when the cron is running
* As an action select execute php code.
* Write the php code

Might be something like this:

```
$dir = 'your/directory/';
  foreach(glob($dir.'*.*') as $v){
  unlink($v);
}

```

These php functions might help you to modify the code as you like.

**Be very careful before executing this! If not used right you may delete your site! Before trying this code test it on a localhost**
> -5 votes

---
Tags: 7, javascript, theming, css-js-aggregation
---


title: how to alter view path field plugin

text:
# Question
Title: how to alter view path field plugin
I Fetched the path field from view using views\_pre\_render(\Drupal\views\ViewExecutable $view) now I made some changes on that path field but I want path field use my data instead of drupal default path value how can I do that.

```
 function view_path_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view->id() == 'view_idea_shots_for_home_page' && $view->current_display ==
   'block_3') {
    foreach($view->result as $value){
      $path = $view->field['path']->render($value);
    }
     $path = $path['#markup'];
     $path = get_tiny_url($path);
     kint($path);
  }
}

function get_tiny_url($url)  {
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
  return $data;
}

```

simply I want to alter path field data.

# Answer
You need to extend the class `Drupal\node\Plugin\views\field\Path`, add an annotation with a new plugin name `@ViewsField("my_node_path")` and override `render()` to place the new code.

Then add or change the field plugin name in views data:

```
$data['node']['path'] = [
  'field' => [
    'title' => $this->t('Path'),
    'help' => $this->t('The aliased path to this content.'),
    'id' => 'node_path',    // put here 'my_node_path'
  ],
];

```

See hook\_views\_data\_alter().
> 0 votes

---
Tags: views, entities
---


title: Redirect before 404 page

text:
# Question
Title: Redirect before 404 page
I'm currently migrating a site to Drupal. The old site has thousands of dynamic URLs for which I cannot use a regular expression to handle them. Those URLs exist in a slightly different form in the Drupal site.
Unfortunately the URL structure is too complicated for being processed directly in a .htaccess file.

I want all the old URLs to return a 301 redirect to the new URL.

This is what I tried.

* I implemented `hook_page_preprocess()` and sent a `RedirectResponse` to the new URL when the incoming URL matches the regular expression for the old URLs
* I implemented an event subscriber that does basically the same on the *onRequest* event

In both the cases, the redirect response is sent with the following code.

```
$respond = new TrustedRedirectResponse($url,301);
$respond->send();
die();

```

Both solutions do work when the user is logged-in. In my local developing site, it works also when the user is not logged-in. On the live server, it doesn't work for anonymous users.

The funny thing is that, even when the redirection works for logged-in users, the log shows a *Page not found* entry for that URL. So it seems that even with the event subscriber solution, Drupal handles the 404 part first, and then executes my code.

What am I doing wrong?
Should I implement this differently?

# Answer
I stumbled upon the same issue with Drupal 8.2.6: A 404 error was recorded even though my custom event subscriber was called.

Following what suggested in comments I read about the *Redirect* module, I set the event subscriber priority using the following code.

```
public static function getSubscribedEvents() {
  // This needs to run before RouterListener::onKernelRequest(), which has
  // a priority of 32. Otherwise, that aborts the request if no matching
  // route is found.
  $events[KernelEvents::REQUEST][] = array('onKernelRequest', 34);

  return $events;
}

```

This fixed the issue I was having.
> 1 votes

---
Tags: 8, redirection
---


# Question
Title: Remove clearfix from section class in custom theme
I'm attempting to edit the template for my pages to allow it to show the content with a block beside it rather than beneath it. I'm currently using bootstrap to lay out my grid.

In my page.tpl.php I have

```
<div class="container">
<div class="col-lg-9">
    <?php print render($page['content']); ?>
</div>
<div class="col-lg-3">
    <?php print render($page['sideblock']); ?>
</div>
</div>

```

I want the content block and the sideblock to be side by side. However when the page renders it wraps the content block in

```
<section id="block-system-main" class="block block-system clearfix">

```

I noticed that when I removed the clearfix class to the section tag I was able to display it side by side. But I don't see any method to remove the clearfix class from this.

# Answer
This could easily be solved with jQuery, but I too would prefer to simply stop it from rendering.

Jquery: $('#block-system-main').removeClass('clearfix');

Rendering: Of course, you could rename the modules/system/region.tpl.php file to 'region--content.tpl.php' and put it in your sites/all/themes/YOURTHEME folder, then remove the "$classes" variable.
> 2 votes

# Answer
For Drupal 8, the best approach for this is to just copy the **bootstrap/block/block.html.twig** template from the bootstrap theme into your custom themes folder, and just remove the **'clearfix'** class from the twig classes block.
> 3 votes

# Answer
It's hard to tell without a link to the specific page. But try this, a CSS only solution:

```
#block-system-main.clearfix:after {
    display: inline;
    clear: none;
}

```
> 2 votes

---
Tags: theming, blocks
---


# Question
Title: How to include IP address Token with Rules?
I would like to track IP address and User Agent when Rules sends out a email. How can I include the `[current-user:ip-address]` token and %server\[HTTP\_USER\_AGENT\] in „Send email“ rule?

Unfortunately Rules (7.x-2.10) ignores both tokens.

```
IP Address: [current-user:ip-address]
User-Agent: %server[HTTP_USER_AGENT]

```
* I’ve tried to create a rules Replacement tokens, however I am not able to create a new entity with Data selector site:current-user:ip-address How can I create a Replacement tokens to show the current-user ip address?

# Answer
> 2 votes
### Option 1: Create new Rules variables

Have a look at this prototype of a custom rule (in Rules export format):

```
{ "rules_send_email_with_user_agent_and_ip_address" : {
    "LABEL" : "Send email with User Agent and IP Address",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "\u003C?php print ip_address(); ?\u003E" },
          "PROVIDE" : { "variable_added" : { "useripaddress" : "User IP address" } }
        }
      },
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003C?php print $_SERVER[\u0027HTTP_USER_AGENT\u0027]; ?\u003E"
          },
          "PROVIDE" : { "variable_added" : { "useragent" : "User Agent" } }
        }
      },
      { "drupal_message" : { "message" : "User Ip Address is [useripaddress:value] and User Agent is [useragent:value]" } },
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "User [account:name] performed a login from Ip Address [useripaddress:value]",
          "message" : "User [account:name] performed a login from Ip Address [useripaddress:value] (User Agent is [useragent:value]).",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Some details about this rule:

* Rules Event: User has logged in (replace with whatever event fits for you).
* Rules Conditions: none (add whatever conditions you want).
* Rules Actions:
    + `Add a variable`, with label "*User IP address*", machine name `useripaddress` and with initial value the result of this PHP evaluation: `<?php print ip_address(); ?>`.
    + `Add a variable`, with label "*User Agent*", machine name `useragent` and with initial value the result of this PHP evaluation: `<?php print $_SERVER['HTTP_USER_AGENT']; ?>`.
    + `Show a message on the site`, with a message value like `User Ip Address is [useripaddress:value] and User Agent is [useragent:value]` (just for QA testing, remove this Rules Action after you're convinced it works OK).
    + `Send email`, with an eMail body like `User [account:name] performed a login from Ip Address [useripaddress:value] (User Agent is [useragent:value]).`, and a similar eMail subject (replace with whatever eMail subject/body that fits for you).

If you have the Rules UI enabled (and the dangerous PHP filter ...) you should be able to import it in your own site also.

Attention: this rule requires the dangerous PHP filter to be enabled (which personally I try to avoid at any cost ...). But if anything else fails, this is "a" solution to get it to work. As an alternative, you could create a custom module in which you create your custom Rules Actions for creating such eMail, and in which you'd include some PHP code similar to the PHP code in the rules Actions shown in the above Rules Actions. Refer to my answer to "How to create custom rules action event conditions?" for more details about that. Or refer to this part of the Commerce Google Analytics module which adds 2 Rules Actions related to *User Agent* and *User IP address*.

### Option 2: Use the Message module

If you're willing to also use the Message module (and have sufficient experience in using it ...), you could implement a rule like so:

* Create an appropriate message entity, which refers to a "message type" in which you can refer to token `[current-user:ip-address]` (= The IP address of the current user). This token comes, out of the box, with the Message module.
* Include some type of pointer/reference to the created message in your eMail, or use the Message Notify module to get the created message entity delivered as an eMail.
* For your User-agent token their *might* be a similar token available already in the Message module also. Though so far I've not found / discovered that one. However, using the technique of "*replacement tokens*", you should be able to create such token (via Rules), and then include that in your Message type also. For an example to see those *replacement tokens* at work, refer to my answer to "Which user related token(s) can be used to create a Rule for setting up a message type?".

Refer to this question for a zillion of other samples/cases about the amazing Message module.

---
Tags: 7, rules
---


# Question
Title: When you have multilingual content not in the Original language
Bilingual content is fine, but what do you do in Drupal 8 when you have content only in a secondary language. I've got a site in English & Japanese, with pages mostly in English (Original language), but some pages only in Japanese.

# Answer
> 0 votes
How to create content in a secondary language:

Go to the language settings of a content type and change it from "Site's default language (English)" to a secondary language or enable

> \[x\] Show language selector on create and edit pages

so that the editor can select a different language for each piece of content. As long as you don't add a translation to this content it stays monolingual (in the secondary language). You can even restrict a content type to this by disabling:

> \[ \] Enable translation

---
Tags: i18n-l10n
---


title: Unit testig on multisite

text:
# Question
Title: Unit testig on multisite
I am trying to simulate a multi-site environment in an integration test with phpunit. I know how to init a new database connection with `Database::addConnectionInfo` but how can I cleanly switch the database used by the current environment?

`Database::setActiveConnection` will only work for SQL queries but I would like to use the entity\_type.manager service and the only way I found is to replace the database service in the container and call `KernelTest::setUp`. Switching back an forth between the databases is still pretty buggy and complex.

Any ideas?

# Answer
"Unit testing" and "multi-site" are in direct conflict with each other. Multi-site is definitely an integration/functional testing concern.

What you *can* do in a unit test to help guarantee that things are working correctly for a multi-site setup is to unit test *only* the logic that is computing different results for each site in the multi-site setup. Use a `@dataProvider` to test the input for different sites in a multi-site setup.

The result of that logic should vary by the `url.site` cache context. You can assert the presence of that cache context in the `X-Drupal-Cache-Contexts` response header in your integration/functional test.

IOW: \- unit test for testing various inputs, with a `@dataProvider` \- functional test that asserts the presence of `url.site` cache context

Together, they guarantee things work correctly.
> 1 votes

---
Tags: 8, entities, database, multi-sites, testing
---


title: How to invalidate cache contexts?

text:
# Question
Title: How to invalidate cache contexts?
When updating my module from Drupal 7 to 8 I bumped into the concept of cache tags and cache contexts. After reading both documentation pages, I have come to the following conclusions:

A cache tag is used to tell Drupal 'what is in the cache', so the cache can be invalidated once something in the cache is updated. This is mainly used for entities and configurations.

Cache contexts provide... context (duh), so the exact same set of tags (entities) can exist under multiple circumstances with a different cache. Examples for contexts are languages and themes, where the same set of entities need to be rendered differently.

Now I did find how to invalidate cache tags:

> Cache tags are invalidated using cache\_tags.invalidator:invalidateTags() (or, when you cannot inject the cache\_tags.invalidator service: Cache::invalidateTags()), which accepts a set of cache tags (string\[\]).

But I cannot find how to invalidate cache contexts...

The reason for asking this is because I am in the process of converting the white label module to Drupal 8. (This module allows the site name, logo and color scheme to be overridden initially based on a url token, but a session variable for subsequent pages.) So I thought such a whitelabel token would make up for an excellent cache context. However (probably on very low frequency) the parameters (name, logo, etc) could change. Thus I should invalidate the cache context.

Can I invalidate cache contexts? Or are there other options? I have thought of using a combination of both tags and contexts, but I am afraid the amount of combination will go through the roof...

# Answer
> 4 votes
What you describe in your question doesn't look like you need a custom context. If you are thinking about to invalidate something, for example if the site logo is changed in configuration, then this is a tag, it can't be a context.

You can have multiple tags and you can combine tags and context, this is not a problem at all. But you run into trouble if you have too many contexts, because for each combination of contexts you get a cache entry and you will run out of database space quickly. This would be the case if you have too many combinations of name, logo, etc. and would try to use this in a context.

# Answer
> 8 votes
Cache contexts cannot be invalidated.

Cache tags describe *data dependencies*. Data can change. When data changes, the associated cache tag(s) are invalidated, causing the cached results to get invalidated and then recomputed.

Cache contexts describe *context dependencies*, which means they describe *variations*. It's very much like HTTP's `Vary` header. Cache contexts usually describe input from the request (such as the URL or parts thereof, the requestor's IP address, the associated user, the associated session, or even the matched route), but could also describe some global state such as which day of the week.

You *could* create a custom cache context for your use case, but it'd be the combination of the `url.query_args:whitelabel` (assuming `?whitelabel=foo` is what you meant) and `session` cache contexts. But it'd be much simpler to instead just associate those two existing cache contexts!

(Note that using the `session` cache context makes things extremely uncacheable, because it causes a unique variation *per* session!)

---
Tags: 8, caching
---


# Question
Title: Is there a way to stop Order checkout in Commerce 2.x?
Is there a way to stop an Order checkout process in Commerce 2.x when a product is out of stock?

**Requirement:**

* I have a product with quantity in stock available as zero
* A user/customer logs in
* Customer clicks `Add to cart` button
* Product must not be added to cart since it is unavailable in stock

I have used `getSubscribedEvents()` with Commerce order event `commerce_order.commerce_order_item.insert`. But the following code just won't work. I suspect it has something to do with the order of execution of Symfony events but really don't understand where am I missing out. My code :

```
  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events['commerce_order.commerce_order_item.insert'] = ['stopOrderExecutionOnStockUnavailability', 100];

    return $events;
  }

  /*
    -----
    -----
    -----
    -----
    -----
  */

  /**
   *
   * @param \Drupal\commerce_order\Event\OrderItemEvent $order_item
   *   OrderItemEvent object.
   */
   public function stopOrderExecutionOnStockUnavailability(OrderItemEvent $order_item) {

    $ordered_quantity = $order_item->getOrderItem()->getQuantity();
    $purchased_entity = $order_item->getOrderItem()->getPurchasedEntity();
    $stock_entities = $purchased_entity->get('field_stock_management')->getValue();

    // Check for available quantity in stock - in total.
    $available_quantity = 0;
    foreach ($stock_entities as $stock_entity) {
      /*
        Get total available stock quantity here.
      */
    }

    if ($ordered_quantity > $available_quantity) {
      $order_item->stopPropagation();
      drupal_set_message(t('Ordered quantity is not available in stock.'), 'error');
    }
  }

```

# Answer
> 1 votes
Use Commerce's AvailabilityManager service.

See https://www.drupal.org/node/2511266 and https://www.drupal.org/node/2710107 for more information.

# Answer
> 0 votes
commerce\_order.commerce\_order\_item.insert is fire after saving a new order item while you have to check before saving a new order item. So use commerce\_order.commerce\_order\_item.create event instead of commerce\_order.commerce\_order\_item.insert, its fire before saving an order item

---
Tags: 8, commerce
---


# Question
Title: How to generate absolute URL for breadcrumbs?
I am use Easy Breadcrumb module for a D8 site. I have everything I need with this module as it alters the existing Breadcrumb block, but it outputs relative URLs.

How can I change the relative URLs to absolute?

Current issue (Breadcrumb Output):

```
<ol>
<li>
    <a href="/level-one">level One</a>
</li>
<li>
    <a href="/level-one/level-two">level two</a>
</li>
<li>
    <a href="/level-one/level-two/level-three">level three</a>
</li>
<li>
Current Level
</li>
</ol>

```

Expected output:

```
<ol>
<li>
    <a href="https://www.domain.com/level-one">level One</a>
</li>
<li>
    <a href="https://www.domain.com/level-one/level-two">level two</a>
</li>
<li>
    <a href="https://www.domain.com/level-one/level-two/level-three">level three</a>
</li>
<li>
Current Level
</li>
</ol>

```

# Answer
You can alter the breadcrumbs of other bread crumb builders (core or contrib) in a hook\_system\_breadcrumb\_alter():

```
/**
 * Implements hook_system_breadcrumb_alter().
 */
function mymodule_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  $links = $breadcrumb->getLinks();
  foreach ($links as $link) {
    $url = $link->getUrl();
    $url->setAbsolute();
  }
}

```
> 0 votes

---
Tags: 8, blocks, navigation, breadcrumbs
---


title: PO files inside contrib modules

text:
# Question
Title: PO files inside contrib modules
Situation is that inside contrib modules folder I found out that each module has /translations and inside a .po file which is not cool when it comes to modules update. I want to take out these translations out of each module folder and place them in single location.
My questions is any idea why they were placed there in first place, is this some kinda of convention or?
Also if I extract them to another folder what type of configuration must be provided ?
And last question is I assume that simply removing/moving them wont affect translation at all as they were already import into the database?

# Answer
After research in drupal.org I found out that best way is to place translations in /sites/all/translations. Naming convention is module\_name-version-language.po

Moving them out did not affected the current translations as they are already imported into the database.
> 0 votes

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


# Question
Title: Cant figure out what's wrong with my image style generation code
The code outputs and does exactly what I intend it to do, but it throws the following notices:

> Warning: Illegal string offset 'effects' in image\_style\_create\_derivative() (line 928 of /var/www/html/modules/image/image.module). Warning: Invalid argument supplied for foreach() in image\_style\_create\_derivative() (line 928 of /var/www/html/modules/image/image.module).

The code I am using is so:

(Builds the actual image style from base uri if the file doesn't currently exist)

```
/**
 * Check for and generate image derivatives if none exist.
 *
 * @param string $style
 *   Image style to check.
 * @param string $uri
 *   URI of the base image.
 *
 * @return false|string
 *   Returns uri for the image that should now exist.
 */
function _srv_image_derivitives($style, $uri) {

  // So I have something to return.
  $final_uri = image_style_path($style, $uri);

  // Gets the absolute file name to the file to check for.
  $filename = drupal_realpath($final_uri);

  // If it's not there, make it there.
  if (!file_exists($filename)) {
    $style_load = image_style_load($style);

    if (count($style_load)) {
      image_style_create_derivative(
        $style,
        $uri,
        image_style_path(
          $style,
          $uri
        )
      );
    }
  }
  return $final_uri;
}

```

(Builds an array of images that will be converted to a json array for an rest post)

```
/**
 * Build derivatives array from base image uri.
 *
 * @param string $image_uri
 *   The base image to construct.
 *
 * @return array
 *   Array of image derivatives.
 */
function _srv_build_derivative_array($image_uri) {
  // Set up the image styles to be used.
  $image_styles = array(
    'carousel',
    'rotator',
    'leadlandscape',
    'focus',
    'linkthumbnail',
    'topstorythumbnail',
    'topnavthumbnail',
    'lateststoriesthumbnail',
    'headline',
    'subcategorylead',
    'opinionlead',
    'entertainmentlead',
    'entertainmentlatestthumbnail',
    'gallerylandscape',
    'gallerythumbnail',
    'reporterstory',
    'galleryportrait',
  );
  $images_array = array();

  foreach ($image_styles as $key_one => $style) {
    $image_style_uri = _srv_image_derivitives($style, $image_uri);

    // EFS path instead of public:// uri.
    $images_array[$style] = str_replace("public://", "/data/sites_default_files/", $image_style_uri);
  }
  return $images_array;
}

```

# Answer
> 0 votes
The first argument should be array in the image\_style\_create\_derivative() function, so the error is in the caller code.

> Parameters
>
> $style: An image style array.
>
> $source: Path of the source file.
>
> $destination: Path or URI of the destination file.

https://api.drupal.org/api/drupal/modules%21image%21image.module/function/image\_style\_create\_derivative/7.x

There is a incorrect sample in the comments at api.drupal.org.

---
Tags: 7, media
---


# Question
Title: Error after updating Webform from 8.x-5.0-beta15 to 8.x-5.0-rc1
A Drupal 8 site hosted on Pantheon gives this error message after updating Webform from 8.x-5.0-beta15 to 8.x-5.0-rc1:

The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to Drupal\webform\WebformTokenManager::\__construct() must implement interface Drupal\Core\Config\ConfigFactoryInterface, instance of Drupal\Core\Extension\ModuleHandler given, called in /srv/bindings/261ff5c4a9e04814be06a20de36ae33a/code/core/lib/Drupal/Component/DependencyInjection/Container.php on line 266 in Drupal\webform\WebformTokenManager-\>\__construct() (line 46 of modules/webform/src/WebformTokenManager.php).

The site is completely down at that point and we have to revert to a backup. Any suggestions?

# Answer
Yes, flushing the cache via Drush should solve the problem.

If you can't use Drush, you must put your site in maintenance mode, set $update\_free\_access=TRUE, and run the pending updates via /update.php.

Also see

http://www.zymphonies.com/blog/update-drupal8-core https://www.drupal.org/project/webform/issues/2907960
> 1 votes

---
Tags: 8, webforms, updating
---


# Question
Title: There is data for the field - On uninstalling module
Given I have a module that defines a new field on an entity. How can I delete that data on uninstalling? There is a requirement:

> There is data for the field X on entity type Y

which means I cannot delete the data on the `hook_uninstall` since it cannot be called.

# Answer
> 0 votes
This is a known limitation to Drupals Core and this finally gets resolved for Drupal 8.5.x, see this issue: https://www.drupal.org/project/drupal/issues/2282119

But for versions earlier there is an option to workaround this, by creating a form that handles the cleaning of added data to make the uninstall validation pass. This is a UI solution but you still need to add a not somewhere that users know how to find the form. See how the Flag module handled it: https://www.drupal.org/node/2409673

There are other options like creating a drush command, but what you basically need to do is to clean the added data from the database to make the validation for uninstall pass and allow users to uninstall the module.

---
Tags: 8
---


# Question
Title: Is there any way to view dpm() data other than printing it on page?
I have an issue with dpm() in that it never seems to return data (and before anyone asks:

* Yes devel is installed
* Yes I am logged in as admin
* Yes print $messages is set
* Yes the permissions are correctly set
* No the data set is not empty ( dpm($node) and dpm($content) return an empty field)
* Yes it did work previously / on ocassion

it does return a message field, but it is just empty).

Is there any other way to view dpm() data, like using Drush or something? I know I should really 'fix the dpm issue' but I have asked around and there does not seem to be an answer.

# Answer
I know you say you are logged in as admin but even so just check the permission "Access developer information" is checked for the admin role just in case that makes a difference.

I've also heard of dpm not working as a result of modules not being uninstalled before they are deleted. Maybe try this module to see if that helps.

Another option would be to see if kpr() works instead.
> 1 votes

# Answer
To answer the question "Is there any way to view `dpm()` data other than printing it on page?": I've found Object log useful for times when I can't get a `dpm()` printout (for example, when testing web services).

> The Object Log module allows developers to store objects, arrays and other variables to a log table so that they may be inspected later. Multiple stored variables may be displayed side-by-side in the Object log under admin/reports.
>
> The usage is similar to Devel module's dpm() or kprint\_r() functions, but is particularly suited for debugging server-to-server requests, such as cron runs and web services, or for requests from anonymous and other unprivileged users.
> 0 votes

# Answer
It is possible to display the output of dpm() and other debug helpers like kint from drush also. Just make sure to add --debug to your drush command.

So instead of `drush migrate-import mymigration`

, use `drush migrate-import mymigration`**`--debug`**

Your debug code does of course need to be run during the drush command, so make sure you pick a command that uses you code. I used this to work with the migrate\_spreadsheet module, so running a migration was enough for me to get my feedback.
> 0 votes

---
Tags: debugging
---


# Question
Title: How to read testbot feedback / get more info
I have created a patch for migrate\_spreadsheet, unfortunately it will not pass the testbot. Instead that gives me this (to me cryptic / uninformative) message:

> fail: \[run-tests.sh check\] Line 0 of : FATAL Drupal\Tests\migrate\_spreadsheet\Unit\SpreadsheetIteratorTest: test runner returned a non-zero error code (255).

Where/what is line 0? My first change compared to the original file was on line 7, where I corrected a class name. The only other two changes in that file where in the docs.

So what does this fail mean? How can I get more info from the testbot?

# Answer
> 2 votes
If you click the colored patch result (above), you will get to a detailed page. On the top of that page there is a link 'View results on dispatcher'. That will get you to the test. Then go to the 'Console output' (on the left) (direct link).

The actual error appears to be:

> 13:56:12 PHP Fatal error: Class 'PhpOffice\PhpSpreadsheet\Worksheet\Worksheet' not found in /var/www/html/modules/contrib/migrate\_spreadsheet/tests/src/Unit/SpreadsheetIteratorTest.php on line 187

---
Tags: 8, testing, version-control
---


title: Inline images are broken

text:
# Question
Title: Inline images are broken
I'm running Drupal 8.4.3 on PHP 7.0.22 atop Ubuntu 16.04LTS, Nginx 1.10.3 and MySQL 5.7.20, using the OpenSocial distribution. Whenever I try to add an inline image into a basic page using CKeditor, I get broken image displayed. The image i'm trying to load appears in Chrome Developer Tools as being collected from `<img alt="Angela Luker" data-entity-type="file" data-entity-uuid="f6af8f2e-3450-440d-a154-f45d4a552a7f" src="/system/files/inline-images/Angela-Luker-Then.JPG"`.

This file is appearing in the file system (not the database) as /var/www/html/private:/inline-images/Angela-Luker-Then.JPG.

So I'm guessing I have an issue with my Nginx rewrites. I've based the Nginx configuration on the suggested Nginx settings for Drupal 8, and several enhancements down the years suggested as workarounds, but still no joy.

The public file base URL is http://www.software-enabled.eu/sites/default/files; the private file system path is /var/www/html/sites/default/files/private; the temporary directory is /tmp.

The above directories are present, owned by www-data:www-data with file permissions set to 770. The default download method is set to *Public local files served by the webserver*.

Is there a rewrite in the Apache versions for Drupal 8 that I'm missing in my Nginx setup?

```
server {
  listen 80;
  listen 443 ssl http2;

  server_name software-enabled.eu www.software-enabled.eu 138.68.143.231;

  root /var/www/html;

  # Redirect to https if user has come in on http

  # if ( $scheme = "http") {
  #    return 301 https://$server_name$request_uri;
  # }

  # Add index.php to the list if you are using PHP

  index index.php index.html index.htm index.nginx-debian.html;

  location = /favicon.ico {
    log_not_found off;
    access_log off;
  }

  location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
  }

  # Very rarely should these ever be accessed outside of your lan
  location ~* \.(txt|log)$ {
    allow 192.168.0.0/16;
    deny all;
  }

  location ~ \..*/.*\.php$ {
    return 403;
  }

  # location ~ ^/sites/.*/private/ {
  #   return 403;
  # }

  # Allow "Well-Known URIs" as per RFC 5785
  location ~* ^/.well-known/ {
    allow all;
  }

  # Block access to "hidden" files and directories whose names begin with a
  # period. This includes directories used by version control systems such
  # as Subversion or Git to store control files.
  location ~ (^|/)\. {
    return 403;
  }

  location / {
    root /var/www/html;
    index index.php;
    error_page 404 = @drupal;
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    # try_files $uri /index.php?query_string; # For Drupal >= 7
  }

  location @drupal {
    rewrite ^(.*)$ /index.php?q=$1;
  }

  # Don't allow direct access to PHP files in the vendor directory.
  location ~ /vendor/.*\.php$ {
    deny all;
    return 404;
  }

  #
  # Pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  #
  # In Drupal 8, we must also match new paths where the '.php' appears in
  # the middle, such as update.php/selection. The rule we use is strict,
  # and only allows this pattern with the update.php front controller.
  # This allows legacy path aliases in the form of
  # blog/index.php/legacy-path to continue to route to Drupal nodes. If
  # you do not have any paths like that, then you might prefer to use a
  # laxer rule, such as:
  #   location ~ \.php(/|$) {
  # The laxer rule will continue to work if Drupal uses this new URL
  # pattern with front controllers other than update.php in a future
  # release. (Note: $ removed as .php extension may not be at end of
  # URL in Drupal 8.
  location ~ '\.php|^/update.php' {
    include snippets/fastcgi-php.conf;
    #
    # With php7.0-cgi alone:
    # fastcgi_pass 127.0.0.1:9000;
    # With php7.0-fpm:
    fastcgi_split_path_info ^(.+?\.php)(|/.*)$;

    # Security note: If you're running a version of PHP older than the
    # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
    # See http://serverfault.com/q/627903/94922 for details.
    include fastcgi_params;

    # Block httpoxy attacks. See https://httpoxy.org/.
    fastcgi_param HTTP_PROXY "";
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param QUERY_STRING $query_string;
    fastcgi_intercept_errors on;

    # PHP 5 socket location.
    #fastcgi_pass unix:/var/run/php5-fpm.sock;

    # PHP 7 socket location.
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
  }

  # Fighting with Styles? This little gem is amazing.
  # location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
  location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
    try_files $uri @rewrite;
  }

  # Handle private files through Drupal. Private file's path can come
  # with a language prefix.
  location ~ ^/sites/default/files/private/ {
    rewrite ^/sites/default/files/private/(.*) /system/files/$1 last;
  }

  location ~ ^(/[a-z\-]+)?/system/files/ { # For Drupal >= 7
    try_files $uri /index.php?$query_string;
  }

  location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    try_files $uri @rewrite;
    expires max;
    log_not_found off;
  }

  # Deny access to .htaccess files, if Apache's document root
  # concurs with nginx's one
  #
  location ~ /\.ht {
    deny all;
  }

  ssl_certificate /etc/letsencrypt/live/software-enabled.eu/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/software-enabled.eu/privkey.pem; # managed by Certbot
}

```

# Answer
> 0 votes
I've fixed my inline image load issues, albeit in the most draconian way. I zeroed out the site completely and rather than using Nginx and the Open Social distribution, I installed raw Drupal 8.4.3 on top of Apache instead - and did the web based install. Everything is working perfectly now.

---
Tags: media
---


# Question
Title: How do I add menu-entry to the admin menu with node reference?
Task: I want to add an `edit` option in the admin menu that would only appear while viewing a node while logged in as admin. The link of the edit item can be like `node\%\edit` so that clicking on the link would take the user to its edit page.

# Answer
You could use the Menu Token module to achieve the same:

1. Install the module and its dependency, i.e. the Token module.
2. Create a new menu item with path `node/[node:nid]/edit`.
3. Place the menu block which contains the menu item in any region of your choice.
4. Drupal menu system takes care of showing the menus as per the access; which means that only users which have permission to edit the node should see it.

The image below is an example shown on the project page. You could use it as a guide.
> 1 votes

---
Tags: 7
---


# Question
Title: How to get friendly URLs to work in a headless implementation?
I'm planning to implement a headless Drupal 8 with a SPA using React. I've been looking through articles on this subject but have found that most of them are just describing how I can pull data off from Drupal's API services.

In a regular Drupal site, when I create a blog post, the system will create a friendly URL like "www.mydomain.com/articles/my-post-title". When I'm creating the frontend through a view library such as React, that URL is likely not going to work because that will route the user away from my SPA site but to the Drupal page instead.

I understand that the routing part in React is usually handled by a library such as react-router. However, I don't understand how should the friendly links of pages and blog posts created by Drupal be mapped over in react-router.

If I want the friendly links Drupal create to work with my React frontend, how should I approach this in my headless implementation?

# Answer
if you use drupal headless its mostly up to the front end framework to implement friendly urls

for react you will probably use routes but since this is beyond the scope of this forum the question might also be deemed as irrelevant
> 1 votes

---
Tags: 8
---


# Question
Title: IP Restricting admin pages with whitelist in custom module
This needs to be done within Drupal as my architecture does not allow for htaccess restriction.

I'm coming over from wordpress here so I've sort've Frankensteined this together from my wordpress code. Any thoughts or help on why this wouldn't be working?

Or maybe there is a much better way of doing this in code somewhere else? Or with some other function?

I'm on drupal 7.

```
function hook_init() {
if (path_is_admin(current_path()))
{
    // Whitelist
    $whitelist = array(
        'SOME IP ADDRESS',
    );

    // Check if current user IP is out of the whitelist, then redirect to home
    if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist))
    {
        drupal_goto('frontpage', 302);
        drupal_exit();
    }
}
}

```

# Answer
> 0 votes
This does not.need to be done in code. I.would use https://www.drupal.org/project/restrict\_by\_ip and set a role for specific IP that would have the specific permissions that you need.

---
Tags: hooks
---


# Question
Title: Having trouble getting mega menu to work responsively
I'm using Drupal 7 and bootrap theme, but I've tried other themes as well and I can't get it to work responsively.

What it does is drop down, but it doesn't scroll, having a hard time to troubleshoot with Chrome dev tool because of media queries.

Any idea what is causing this? Megamenu is supposed to be responsive out of the box?

URL is :

http://www.dev.wearelao.com

# Answer
> 0 votes
No, that module doesn’t claim to provide responsive menus.

Quite the opposite, in fact; its mission is to provide you with the tools you need to build your *own* styles, which can of course be responsive if you desire:

> The module provides classes and ID's that allow for a full-range of styling customization, from more traditional (but multi-level) drop-downs to full width slide out menus.
>
> **A couple demo skins are supplied, but these are purely for instructional purpose to help get you started with theming your mega menu.** Currently, you should have an understanding of how Drupal overrides module CSS files and how to add CSS to themes, in order to provide your own styles in your particular theme.

So the module just gives you a framework to start from, you need to provide your own CSS.

# Answer
> 0 votes
Ok, got this solved, here is the answer.

Enable Bootstrap menu in backend settings, then set it menu to display none, on ALL media queries.

The Megamenu will then feed from the native bootstrap that is enabled but non displayed, works perfectly.

---
Tags: 7, theming, navigation
---


# Question
Title: db_select query for given sql query with equi join
I'm trying to do a equi join but it isn't working. I have 2 tables: Table 1 - taxonomy\_term\_data with fields "tid,vid,name,description,format,weight etc"

Table -2 -taxonomy\_term\_hierarchy with fields "tid and parent"

I have sql query with me it is working fine. This is the query "select t1. \*,t2.vid,t2.name from taxonomy\_term\_hierarchy t1, taxonomy\_term\_data t2 where t1.tid = t2.tid AND vid=2 limit 5;"

I just want to get tid,name,vid from taxonomy\_term\_data table and parent from taxonomy\_hierarchy table in db\_select query format

# Answer
> 0 votes
You can built any type of select query using db\_select, you can see in detail on following url https://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_select/7.x

# Answer
> 0 votes
You can change query based on you requirement.

```
$query = db_select('taxonomy_term_hierarchy', 't1');
    $query->join('taxonomy_term_data', 't2', 't1.tid = t2.tid');
    $result = $query
      ->fields('t1', array('tid', 'field1', 'field2'))
      ->fields('t2', array('tid', 'vid', 'name'))
      ->condition('t2.vid', '2')
      ->range(0,5);
      ->execute();

    foreach ($result as $row) {
      // Do something with $row.
    }

```

---
Tags: 7
---


title: How to add field to menu

text:
# Question
Title: How to add field to menu
I want to add a description field to my menu and and use it in front.

I managed to have a text\_format field for my description (in /admin/structure/menu/manage/main) but when I click on save, that field is empty.

```
function HOOK_form_alter(&$form, $form_state, $form_id) {
  if ($form_id != 'menu_edit_form') {
    return false;
  }
  $form['field_menu_content'] = array(
   '#type' => 'text_format',
   '#title' => t('Description'),
   '#format' => 'full_html',
  );
}

```

# Answer
> 2 votes
Here is the complete working solution from @4k4 answer:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id != 'menu_edit_form') {
    return false;
  }
  $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
  $field_menu_content = $config->get('field_menu_content');
  $form['field_menu_content'] = array(
   '#type' => 'text_format',
   '#title' => t('Description'),
   '#default_value' => $field_menu_content['value'],
   '#format' => 'full_html',
  );
  $form['actions']['submit']['#submit'][] = 'mymodule_menu_edit_submit';
}

function mymodule_menu_edit_submit($form, $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
  $config->set('field_menu_content', $form_state->getValue('field_menu_content'))->save();
}

```

# Answer
> 2 votes
This question is similar to https://stackoverflow.com/q/39288049/4629065

Try out Menu Item Extras module for Drupal 8 from Drupal.org projects site https://www.drupal.org/project/menu\_item\_extras.

For more info take a look the next answer https://stackoverflow.com/a/46728856/4629065

# Answer
> 1 votes
In hook\_form\_alter() add a submit function:

```
$form['#submit'][] = 'my_module_menu_edit_submit';

```

Where you store the field:

```
function my_module_menu_edit_submit($form, FormStateInterface $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
  $config->set('main_content', $form_state->getValue('field_menu_content'))
    ->save();
}

```

The main menu is hard coded in the settings name. If you want this to work for all menus, you can try to get the menu name from the form. I did not investigate where you can get it.

When you build the form field you also need to get the field value from config. More information: https://www.drupal.org/docs/8/api/configuration-api/simple-configuration-api

---
Tags: 8, forms
---


# Question
Title: Send "Request new password" email for individual users
I'm looking for a way for the administrator users to quickly send out a password reset for a specific user. Ideally, this would be a link/check on the account edit.

I have seen and made use of the Mass Password Reset module which works per role, but I need it for individuals too.

At the moment my thought is to make a "reset password" role then have a rule along the lines of: after saving user, if user has "reset password" role, send account recovery email, remove "reset password" role, but that seems pretty convoluted. Am I missing an easy solution?

I am using Drupal 7.

# Answer
If you'd create an appropriate view (using Views) of your users, wit whatever filter criteria you'd want, you could use that view to combine it with the Rules Link module. And with that you have the full power of the Rules module available also to implement whatever logic you'd want.

Refer to the accepted answer to "How to show authorized users a link for relevant Views results using the Rules Link module?" for an in depth explanation about using the Rules Link module, related to a scenario which is a variation of your question here (i.e. show a link to unblock blocked users).
> 0 votes

---
Tags: users
---


title: Image Field Browser Option

text:
# Question
Title: Image Field Browser Option
Is there any way to alter the default Drupal 7 image fields to allow a browse server option along with the default upload file option? Kind of like *imce* or *ckfinder* but for image fields instead of content (text) fields.

It seems like this could be pretty useful and I don't really see any modules that offer this kind of functionality.

# Answer
> 4 votes
You could use the FileField Sources module. To browse the server it looks like you need to use this with IMCE. From the FileField Sources project page:

> The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:
>
> * Re-use files by an auto-complete textfield
> * Attach server-side files uploaded via FTP
> * Transfer files from a remote server (cURL required)
> * Select existing files through the IMCE file browser

# Answer
> 0 votes
Laxman answer is correct for file fields, but as per this topic, FileField Sources is not working with drupal default image field(as per jan 2 2018). For default drupal 7 image field, you should use IMCE for FileField instead: after installed the module, go to configuration page of your image field, and check "Allow users to select files from IMCE File Browser for this field" checkbox.

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


# Question
Title: Where is the base domain stored in database D7
Is there an equivalent row to the Wordpress "Home" and "Site"? In otherwords, where can I look in the database to figure out what the domain the site is on? I'm using mysql

# Answer
It can be one or more of the following:

```
<?php
print $GLOBALS['base_url'];    // Set by drupal_settings_initialize() or settings.php.
print $_SERVER['HTTP_HOST'];   // Set by apache.
print $_SERVER['SERVER_NAME']; // Set by apache.

```

You can also check the database with this query

```
SELECT * FROM variable WHERE value LIKE '%example.com%'

```

where example.com is the domain; this is not guaranteed to be correct though.
> 4 votes

# Answer
I think you're looking for $base\_url in `/sites/default/settings.php`. As far as I know everything in the database works off this value, and it is not explicitly set in the DB
> 5 votes

# Answer
There really isn't a perfect analog to `wp_options.siteurl` & `wp_options.home` in Drupal. The closest thing is `variable.site_frontpage` for home path & `$base_url` in **settings.php** that contains the site domain URL root.
> 3 votes

# Answer
This can be easily evaluated from the code in `drupal_settings_initialize()` in file `includes/bootstrap.inc`

As seen in the code below, Drupal first tries to get it from `$base_url`, if not set then Drupal reads it from `$_SERVER['HTTP_HOST']`

```
function drupal_settings_initialize() {

    if (isset($base_url)) {
        // Parse fixed base URL from settings.php.
        $parts = parse_url($base_url);
        ...
    }
    else {
        // Create base URL.
        $http_protocol = $is_https ? 'https' : 'http';
        $base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];
        ...
    }

```

WARNING: Since `$_SERVER['HTTP_HOST']` could be easily spoofed using an http request header "`Host: something.com`", this means you should, I repeat, you should assign a value to `$base_url` in the `settings.php` file to avoid the }else{ condition above.
> 1 votes

---
Tags: uri, database
---


# Question
Title: "list" plugin does not exist after upgrading from Drupal 8.3.x to 8.4.2
How can I tell exactly what is missing and from which module? (I assume it's `draggableviews`)

How can I remedy this error - or is it in the hands of a contrib module developer or where can I go to see how to contribute the missing plugin?

This is the output of `drush @badev updb`.

```
 ---------------- --------------------------------- --------------- -------------------------------------------------------------------------
  Module           Update ID                         Type            Description
 ---------------- --------------------------------- --------------- -------------------------------------------------------------------------
  draggableviews   8104                              hook_update_n   Implements hook_update().
  comment          enable_comment_admin_view         post-update     Enable the comment admin view.
  dblog            convert_recent_messages_to_view   post-update     Replace 'Recent log messages' with a view.
  field            remove_handler_submit_setting     post-update     Remove the stale 'handler_submit' setting for entity_reference fields.
  node             configure_status_field_widget     post-update     Load all form displays for nodes, add status with these settings, save.
  system           classy_message_library            post-update     Clear caches to ensure Classy's message library is always added.
  system           field_type_plugins                post-update     Force field type plugin definitions to be cleared.   @see
                                                                     https:www.drupal.orgnode2403703
  views            revision_metadata_fields          post-update     Fix table names for revision metadata fields.
 ---------------- --------------------------------- --------------- -------------------------------------------------------------------------

 Do you wish to run the specified pending updates? (yes/no) [yes]:
 > yes

 [notice] Executing draggableviews_update_8104
 [error]  The "list" plugin does not exist.
 [ok] Performing draggableviews_update_8104
Array   Array
 [success] Cache rebuild complete.
 [success] Finished performing updates.
Connection to drupal8vm.dev closed.

```

# Answer
> 0 votes
This is solved now. I think that there was a mismatch between the PHP/ Drush / Drupal 8.4.3 versions.

This confused me so I include a table below of what is now working for me. I used it as a checklist to ensure that I had both a dev Drupal 8.3.7 and a dev Drupal 8.4.3 running in parallel.

Despite what the documentation says I think Drush 8.1.15 is not suitable for Drupal 8.4.3 and yes, there are some Drush 9.0.0-rc1 commands that don't work as expected - like dumping SQL and redirecting SQL files to `drush sqlc` \- but it is workable.

Bits and pieces in each of existing and future Drupal

```
               iMac               MacBook
PHP VM         7.1.12             7.1.12
PHP Host       7.1.12             7.1.12
Drush VM       8.1.16-dev         ~9.0
Drush Host     8.1.15             ~9.0
Drupal Core    8.3.7              8.4.3
MySQL          5.7.20             5.7.20   (Required MySQL 5.5.3/MariaDB 5.5.20)

```

---
Tags: 8
---


# Question
Title: When using custom twig expressions to rewrite view title, the breadcrumb shows the twig expression without replacing it
In some of the views, I needed to customize the title using twig. For example `{{ title }}` which would read the title of the first row in the view result and place it in the page title. This works fine.

The problem is with the breadcrumb. It shows as `Some Parent page > {{ title }}` without replacing the {{ title }} with its actual value.

I guess a solution could be something along the lines of placing some code in `THEME_preprocess_breadcrumb`, but I am not sure what to write there exactly. But shouldn't this functionality be something out of the box?

P.S. Not all my views are using {{ title }}, actually some of them are a little more complex, and some views are parents of other views path-wise. So solutions like in this Q doesn't help.

# Answer
> 1 votes
I had a similar issue where I needed my view title to be `{{ field_first_name }} {{ field_last_name }}`. The head title tag and page title were correct, but the twig variable's value wasn't being rendered for the breadcrumb.

I ended up writing a tiny module in which I get the title then set the title to the title. Somehow, doing this in post\_render makes the twig get rendered correctly in the breadcrumb. Hopefully someone will come along and tell us why this works or why it was needed.

```
?php
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_render().
 */
function peopleview_views_post_render(ViewExecutable $view) {
 if ($view->id() == 'people') {
  $title = $view->getTitle();
  // Set the view title.
  $view->setTitle($title);
  // Set the route title.
  $route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
  $route->setDefault('_title', $title);
 }
}

```

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


# Question
Title: How do I programmatically send MIME HTML emails without using the Rules module?
In the past, I have used the Rules module to send MIME HTML emails, creating a component and invoking it in my code with `rules_invoke_component('rules_send_html_email', $parameters)`.

How can I programmatically do this without using the Rules module?

I am using Drupal 7.

# Answer
> 1 votes
After a lot of experimentation, it looked like the drupal\_mail() function worked as long as the Mime Mail and Mail System modules were configured.

So you will simply execute the drupal\_mail() function and also use hook\_mail in your custom module (send\_html\_email is the module name in this example).

You can use the following code in a re-usable function, after a form is submitted, or anywhere else that you would like an email to be sent:

```
  // Parameters passed to Drupal Mail Function
  $params = array(
    'subject' => $subject,
    'body' => $body,
  );

  // Send the Email!
  drupal_mail($module, $key, $to, language_default(), $params, $from);

```

Now you will need to use hook\_mail:

```
// hook_mail()
function send_html_email_mail($key, &$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

```

Doing this will successfully send an HTML Mime Mail email from your code.

---
Tags: emails
---


# Question
Title: Saving a field of type 'text_format' as a theme settings variable
I try to add a text area with wysiwyg editor in the theme setting.

If i use `'#type' => 'textfield'`, it works :

If I use `'#type' => 'text_format'`, the text is saved but i don’t see it as default value :

If I revert back to `'#type' => 'textfield'`, i can see this :

I guess it is related to the text\_format form which is stored as an array ?

How can I use `text_format` in theme settings ?

Full code in mytheme.theme

```
function MYTHEME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {

  $form['mytheme_texte_presentation'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Test theme settings'),
    '#default_value' => theme_get_setting('mytheme_texte_presentation'),
    '#description'   => t("lorem ipsum"),
  );
}

```

# Answer
Text format fields are considered to be a compound field (meaning that multiple values are stored for the one field -- the value and the format).

If you inspect the value of `mytheme_texte_presentation`, you'll find an array that looks something like this `array => ['value' => '<val>', 'format' => 'html_restreint']`.

If you look at the docs for text\_format, you'll see that there is a `#format` attribute.

Your code should look something like this:

```
$texte_presentation = theme_get_setting('mytheme_texte_presentation');
$form['mytheme_texte_presentation'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Test theme settings'),
    '#default_value' => $texte_presentation['value'],
    '#format'        => $texte_presentation['format'],
    '#description'   => t("lorem ipsum"),
  );

```

**Note:** *This is untested code. You may need to tweak this a bit to make it functional.*
> 4 votes

---
Tags: 8, forms
---