# Question
Title: Tests for a custom class that load entities
I've managed to write some simple PHPUnit tests, but because the classes within my module have some methods that try to load entities (Content Types built via standard Drupal UI) and then do various thing with them, I am having trouble how to bridge this gap.

Currently when I run my tests most of the assertions pass as they are fairly simply but the one is giving me a warning:

> The data provider specified for Drupal\Tests\lrgContentTypes\Unit\AuctionEventTest::testGetNodeFields is invalid. \Drupal::$container is not initialised yet. \Drupal::setContainer() must be called with a real container.

This has only occurred recently because I have now fleshed out the code for the entity class that the parent is trying to pass in the provider.

I am unsure where to go from here, the Drupal 8 documentation seems to be spotty and gives no clear guidance from a basics point of view.

Are there examples that show how to test methods that try to load a node via `Node::load()` and where entity reference revision objects are expected?

# Answer
> 0 votes
If you are doing Unit tests (and not functional tests), you will need to mock the objects you want to use, in the setup of the test. You can read more here: https://www.drupal.org/docs/8/phpunit/mocking-entities-and-services-with-phpunit-and-mocks

If you are using Drupal functions, you should first try to find out if there is an OOP method that can be used to do the same thing - later versions of Drupal have tried to deprecate such functions, and provide OOP alternatives instead. An example is the Time (datetime.time) service, that replaces things like REQUEST\_TIME.

If there is no OOP alternative, you can do the following. Imagine you are using db\_query() (which, you shouldn't). Instead of using that function direct in your code, you can create a protected function as follows:

```
protected function dbQuery($query, array $args = [], array $options = []) {
  return db_query($query, $array, $options);
}

```

Next, for your text, you will create a class that extends the original class. In this test class, you override dbQuery() above:

```
protected function dbQuery($query, array $args = [], array $options = []) {
  return ['row1' => ['col1' => 'val1'], 'row2' => ['col2' => 'val2']];
}

```

This mocks a call to db\_query by returning an array of values. The last step is to use this new class in your Unit tests, so that when dbQuery() is called, it uses your extended version that returns the array, instead of calling db\_query() which is not available to the Unit test.

---
Tags: 8, testing
---


# Question
Title: With a custom form, how to sanitize user input before query gets to URL?
I followed this tutorial to create a custom Search form that takes users to the main search page with a query in the URL (meaning it uses a get method). This gives me more flexibility than using an exposed filter, so I'd like this to work. One thing that I want to do, however, is make sure that if someone searched:

```
<script>alert('foo')</script>

```

that the query in the URL would **not** have the tags included. Drupal has plenty of sanitization functions, so I'm not worried about that. But I can't figure out WHERE in the custom form plugin I would actually add the sanitization.

Please help! I've included the code of my plugin below:

```
<?php

namespace Drupal\my_custom_search\Plugin\Form;

use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class MyCustomSearchForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'site_search_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#action'] = '/search';
    $form['#method'] = 'get';
    $form['#attributes']['class'][] = 'usa-search';
    $form['#attributes']['class'][] = 'usa-search-big';

    $form['fulltext_search'] = [
      '#type' => 'search',
      '#attributes' => [
        'id' => array('search-field-big'),
        'size' => '',
        'maxlength' => '',
      ],
      '#prefix' => '',
      '#suffix' => '',
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      '#button_type' => 'search',
      '#attributes' => [
         'class' => ['usa-search-submit-text'],
      ],
      '#name' => '',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

}

```

**UPDATE:** I ended up adding `'pattern' => '[^/><\][\\\x22,;|]+',` in the attributes array, and this at least prevents submission of text with characters I don't want. I may still try to find a JS solution that works better for the user.

# Answer
Drupal's mantra is to sanitise upon output, not input. See Writing secure code for Drupal 8 for more information.

So there's no need to sanitise upon submission, just make sure that if you're rendering that value anywhere, it's done in a secure manner (as explained in the docs above).

If you decide that you still need the solution you've outlined, it's going to have to be implemented in JavaScript. Your form method is `GET` so the browser handles the input -\> URL conversion, not Drupal.
> 5 votes

---
Tags: 8, forms
---


title: Elements not showing in $form object

text:
# Question
Title: Elements not showing in $form object
I have a webform with some fieldsets. Within each fieldset is a set of input elements that are the same for each fieldset, and each set of elements has the same machine name.

One of the elements is a "Select options" as a set of checkboxes. I want to conditionally make some checkboxes readonly or disabled for all of the fieldsets.

My problem is that I have spent hours looking at how to do that, and I cannot find the elements within the `$form` object in order that I may alter them. The form is a multi-page form, so that may cause some problems, as I don't know if all of the elements show up in the submitted array until you have reached a specific page or not. I don't know how that works.

Part of my form has something like this:

```
outer_fieldset
-- count
-- fieldset_1
-- -- name
-- -- date
-- -- group
-- -- checkboxes
-- fieldset_2
-- -- name
-- -- date
-- -- group
-- -- checkboxes
-- fieldset_3
...
```

I used `die('<pre>' . print_r($form['submitted']['outer_fieldset'], TRUE) . '</pre>');` to look at the data. `$form['submitted']['outer_fieldset']['fieldset_1']` exists, but it doesn't have any elements inside it for the checkboxes or anything.

All the existing SE pages I have looked at give basic answers like `$form['submitted']['element_name']['#attributes']['disabled'] = TRUE;`, but I cannot use something like that unless I can find the element objects...

Could the fact that the inner controls all have the same machine name be causing a problem with that? The webform was created using the Drupal interface, and it allows controls to be added this way. I'm relatively new to Drupal. Any help on how to find and alter the attributes of these elements would be great. Thanks.

# Answer
I found the checkboxes. I was printing the `$form` variable in the wrong hook function. I needed to do my modifications to the form in `hook_form_alter`.

I ended up using something like this:

```
unset($form['submitted']['outer_fieldset']['fieldset_1']['checkboxes']['#options'][$option]);

```
> 0 votes

---
Tags: 7, forms, webforms
---


# Question
Title: Didn't we used to be able to type "entity:node/####" in a typeahead field?
When using any Drupal 8 link field to dynamically link to a node, I start typing the title and the typeahead function starts providing options to chose from. These are Drupal field types such as Link or Entity Reference.

For various reasons, sometimes the correct title doesn't appear and I can't choose it using what's in the typeahead choices. In those cases, I always just used:

```
entity:node/[node_id_number]

```

I'm trying to do that now, and Drupal isn't recognizing it as a valid entity. I keep getting the error message:

*There are no entities matching "entity:node/6491".*

I've tried typing it every which way I could think of, figuring I just forgot the correct syntax. I tried:

```
/entity:/node/6491
/entity:node/6491
entity:/node/6491
/entity: node/6491

```

and more.

Can anyone tell me what I'm doing wrong? Or was it all just a fever dream and I was never able to fill in a typeahead link field using 'entity'?

# Answer
Ooooooooookay.

The entity:node/\[node\_id\_number\] *only* works in a Drupal link field. It does NOT work in a Drupal entity reference field.

Although both of those fields feature the typeahead function and link to other nodes, you cannot use entity:node/\[node\_id\_number\] to fill in an entity reference typeahead field.

Thanks @Clive for making me clarify my field types and start down the path to seeing my wrong assumption.
> 2 votes

---
Tags: entities
---


# Question
Title: How to join values of multiple geofields in a view?
I have a content type in which the site of organizations are displayed in a leaflet map with the help of an addressfield. (And all organizations are displayed in a joint map.) But certain organizations don't have convertible postal address, therefore geocoding from addressfield doesn't work. For these organizations I created a second geofiled in which I add latitude/longitude values manually.

The problem is that the display of leaflet map in Views can handle only one field as the source of geodata. Is it possible to combine these two geofields into one?

# Answer
> 0 votes
*Have you tried conditional views? You could have 2 fields, using the first by default, and the second instead if the value of the first is empty. <br>This module has helped me a few times. Just add the module, in your view add a field type "Views conditional", exclude from display your fields and use replacement patterns in your conditional field in one case or the other, depending on the condition (let's say address field is empty, then use latitude/longitude).*

**EDIT:**
What about 3 fields in your content type:

* Address field \[field\_address\]
* Lat/long \[field\_lat\_long\]
* Composed field (type text) with token value \[field\_address\]\[field\_lat\_long\] using field token value or field tokens
In this way the composed field will always have a value from one or another field, and then you can use this field as data source.
Then you may need to manage field dependencies to avoid that both fields are used.

---
Tags: 7, views
---


# Question
Title: How can I make a node like template for a vocabulary?
I have a taxonomy where I want to theme the term pages.

I only want to theme the terms pages in this taxonomy.

No matter what I do I can't see to get it to show a template file that I can then further customise.

I have a node page at /name then I have the terms of the taxonomy using the path pattern /name/term\_name

Can anyone help me figure this out, it seems strangely difficult. To the point where I am begining to wonder if some module might be derailing me.

From what I understand I should be about to make a template named something "taxonomy-term--myTaxonomy\_name.tpl.php" but I can't seem to dislodge the default term view. Even with many cache clearings.

# Answer
> 0 votes
Enable the `Taxonomy term` Views if you haven't already, and look into theme suggestions there.

It seems you have `views-view--taxonomy-term--page.tpl.php` available where you can add some logic that would apply to only a certain Vocabulary.

You can also Clone the Taxonomy term Views twice, Filter to only certain Vocabulary in one Views, and to all the rest in the other Views, then use the template in the first Views for special styles.

You can use the Taxonomy Views Integrator module to assign different Views to output different term pages.

# Answer
> 0 votes
The templat naming should be taxonomy-term--vocabulary-machine-name.tpl.php, as /admin/structure/taxonomy/\[vocabulary-machine-name\]

Also, you could use a preprocess function in your template.php file to be sure:

```
/**
 * Implements hook_preprocess_taxonomy_term()
 *
 * @param $vars
 */
function YOUTHEME_preprocess_taxonomy_term(&$vars) {
  $vars['theme_hook_suggestions'][] = 'taxonomy_term__' . $vars['view_mode'];
  $vars['theme_hook_suggestions'][] = 'taxonomy_term__' . $vars['vocabulary_machine_name'] . '__' . $vars['view_mode'];
}

```

And then name your templates:

* taxonomy-term--vocabularyname.tpl.php,
* taxonomy-term--vocabularyname-full.tpl.php,
* taxonomy-term--vocabularyname-teaser.tpl.php,
* etc.

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


# Question
Title: Customize the appearance of sharing articles to social media
I am new to Drupal and I just added a few buttons for sharing articles to social media (Facebook, Twitter etc.) I want to customize the appearance of sharing posts. After a few "research" I found out that I need to install meta-tags module to customize it...

The problem is that I can t figure it out how to change image or description. I tried but it didn\`t work. This is how it looks like a shared article, banner image instead article image and description with irrelevant details.

# Answer
> 1 votes
Welcome to StackExchange!

Assuming you are using D8, here are some instructions (D7 would be similar but slightly different).

The metatag module has some submodules to help with various metatag usages. You will want to also enable the metatag\_open\_graph module. This will let you set the og\* metatags.

First step in this is to go to the Content Type definition (structure-\>content types) for the page type (article?) you want to have metatag info on. You will need to select the Manage Fields option. Here you need to add a new field. Use the "Use an existing field" option and add the MetaTags field to the content type.

Repeat this for any other content types you want to have Metatag info added to.

Once you have done this, you can go into the configure / search and metadata / metatag screens and define the defaults you want either globally or for the specific content type. You can use "tokens" to indicate items from the node values. E.g. \[current-page:title\] or \[node:field\_featured\_image\] and the like. There is a browse available tokens to give you some guidance here.

Additionally, now that you have the metatag field added to the content type. You can also manually modify the metatags for any single node if you have the rights to modify the metatag info.

This can be done while editing the node and opening the MetaTag tab (generally at the bottom of the form).

To keep facebook and twitter happy I think you generally need the title metatag, og description field and the og image field set.

Good luck.

---
Tags: tokens, meta-tags, social-network
---


title: Does Search API index custom fields?

text:
# Question
Title: Does Search API index custom fields?
I am using search API on my website (Version 1.8), I have a problem with indexing custom fields. In the Configuration -\> Search and metadata -\> Search API I have added the custom fields to be indexed, in the view in the "Fulltext search" the custom fields appeared. In the database I can see that the fields got indexed. But when I test, there is no result. Has anyone had similar troubles with Search API?

Edited: The problem occurs only with the fields of "Entity reference" type

# Answer
> 0 votes
You probably need to index the referenced entity Name\* (assuming you want to search on name) as a field instead of just simply the entity ID (which is what entity reference fields actually store). The pattern should look something like the following on the 'fields' page:

`field_yourfield:entity:name`

---
Tags: 8, search
---


# Question
Title: Development without pulling production DB to your local machine
When you push configuration to production, any configuration that has changed in production that has not been exported into code will either be reset to the values in code or be wiped out entirely if they never existed in code. One out of many examples is changing the site name. If that change didn't go into code (i.e. if a content admin changed it, not a developer), the next deploy would reset that change.

Now the solution we have in place is to **pull the production DB down** and export the configuration against production code. Any differences appearing in the export are configs that have changed on production since last deploy. It's a process that you can easily wrap your head around (`prod config - deployed config = changed config -> you check this in`) and works pretty well so far.

But there are issues with this approach, one in particular is pulling the production database down. The DB may be huge, well into the hundred megabytes. It may contain sensitive info you don't want on your machines. Or it can only be retrieved indirectly (e.g. last night's cron job) and could already be stale by the time you work on it.

I know D8 config management is not perfect, and some things can't be avoided due to the current design of things. But I still would like to ask:

* Is there a better way to do the process of resolving configs on deploy?
* Is there any way to do this *without* pulling down the production database down?
* Is there a Drupal/Drush/third-party module feature that already does what I am describing?
* Is this more of a content workflow issue? i.e. never let content admins touch config?

# Answer
> 1 votes
Install Config Ignore and configure it to ignore those config objects from which you think they are going to be changed in production.

> Ever experienced that your site's configuration was overridden, by the configuration on the filesystem, when doing a `drush cim`?
>
> Not anymore!
>
> This module is a tool to let you keep the configuration you want, in place.
>
> Lets say that you do would like the `system.site` configuration (which contains that sites name, slogan, email, etc) to remain untouched, on your live site, no matter what the configuration, in the config folder, says.
>
> Or maybe you are getting tired of having the `devel.settings` changed every time you import configuration?
>
> Then this module is what you are looking for.

# Answer
> 0 votes
We solve this by using the Features module. It's a bit of a pain to set up with a large site but worth it. Basically, it lets you take the hundreds of config yml file and organize them into smaller logical chunks and then manage what changed.

Our organization is generally, a core feature with field storage (so fields can be used across types), general defaults and settings (e.g. translation settings, image styles, vocabs, menu, text formats, and the like).

Then a feature for each entity bundles (e.g. node types, paragraph types, eck bundles, and the like) These generally have the field instances, entity entry/display forms info, translation settings, local overrides. E.g. use the Feature search for node.type or paragraph.type to see what comes up.

Then we have features for general areas of the site. E.g. an "Views: Products" feature that has all the views and block instances used in the products area of the site.

We don't put every config item in features, just the ones that should be under the control of developers.

All these are checked into the code base.

When it's type to deploy, developers need to update the features with any changes / create new features and check them in. These are pushed to our dev site and the changes captured in features are pulled in. Things are verified that everything is good (or often, got back to the local dev environment and fix missing things). Once we have a good deploy, it's pushed up the chain.

On good thing about features is that it quickly lets you see the diffs between small areas of configs. We also double check on deployment to production if something doesn't look quite right. E.g. someone 'patched' a view to fix something on production but didn't update the feature. This can lead to having to do some head scratching and manual "gui merges". But we feel this is a lesser evil that lets the site admins fix problems quickly while not having too many fixes reverted by the devs. :)

---
Tags: 8, configuration, deployment
---


# Question
Title: Problems with Drupal 7.55 Apache2 Subdomain Virtual Host no CSS
Setting up a fresh Drupal install in the domain root example.com works fine. Removing that and using a copy of the default virtualhost config file for a new virtual host site.example.com with a ServerName site.example.com and a different DocumentRoot, I navigate to site.example.com and css is not applied, I just get the install.php but without css.

All clean install on Debian Jessie - should be easy to replicate.

Any ideas on how to fix this?

# Answer
You need to check and fix this things:

1. File system (admin/config/media/file-system) and setup it on the proper way.
2. Clear all cache
3. add proper permission for apache2 user (chown -R www-data:www-data sitename.com)
4. check settings.php - database name, database user and cookies domain
5. check recent log files and try to find messages for the content with access denied permissions

This is for Drupal 7, also similar, can used for Drupal 8

Thanks, Vladica
> 0 votes

---
Tags: 7
---


# Question
Title: How can override the title markup on a node page?
I've managed to implement a custom page template but it still uses the default title markup.

I'm trying to find out how to replace the markup around the title so I can change it to something like:

```
<h1 class="title" id="page-title">Node title</h1>
<h2>Subtitle</h2>

```

Can I override a template like region--header.tpl.php or something similar?

I'm using an omega based custom theme too btw.

# Answer
> 0 votes
As expected as soon as I posted this question I found the solution..

If you use the template **region--main-heading.tpl.php** you can override title markup.

---
Tags: 7, theming
---


# Question
Title: Error in simplesamlphp_auth.module: no valid attribute set
I'm configuring my application as a saml provider and for this I have used simplesamlauth module. This module (simplesamlphp\_auth) provides the ability to make a Drupal site into a SAML Service Provider (SP).

Now while configuring this module, I'm confused about the values that it will take as inputs.

I used SAML tracer, where I'm getting SAML response. Is it from here I will get any kind of attribute that need to be configure at /admin/config/people/simplesamlphp\_auth/sync page?

Because right now it is giving me error:

> Error in simplesamlphp\_auth.module: no valid \\"nameid\\" attribute set.\\" at /var/www/html/modules/contrib/simplesamlphp\_auth/src/Service/SimplesamlphpAuthManager.php line 165",

What would be the unique identifier for the user and username for the user?

# Answer
> 0 votes
The General values for same will be as follows:

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress

but if these not works you can also check the values in Metadata XML received from your IDP.

---
Tags: 8
---


# Question
Title: How can I load a menu programmatically with an active trail set by a provided URL?
Working on a headless Drupal site, and have come across an issue. We have a REST resource that returns arbitrary menus by menu-id, however they always have "active-trail" set to false on every menu item.

I'd like to be able to specify a URL or route when building the menu and have the active-trail be equivalent to what it would be if the menu was loaded on that route.

At the moment our solution is to loop through every menu item until we find one that corresponds to the provided URL, and then mark it and all its parents as "active-trail", however this seems unnecessarily cumbersome and I'm left wondering if there's a more sensible solution we've overlooked.

Currently we're loading menus like this:

```
$tree = $this->menuTree->load('menu_id', new MenuTreeParameters());

```

Where $this-\>menuTree is an instance of MenuLinkTree being instantiated via Dependency Injection:

```
/**
 * {@inheritdoc}
 */
public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, MenuLinkTreeInterface $menu_tree, EntityTypeManagerInterface $entity_type_manager, Request $current_request) {
  parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

  $this->menuTree = $menu_tree;
  $this->entityTypeManager = $entity_type_manager;
  $this->request = $current_request;
  $this->alias = $this->request->query->get('alias');
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $configuration,
    $plugin_id,
    $plugin_definition,
    $container->getParameter('serializer.formats'),
    $container->get('logger.factory')->get('rest'),
    $container->get('menu.link_tree'),
    $container->get('entity_type.manager'),
    $container->get('request_stack')->getCurrentRequest()
  );
}

```

# Answer
Inject the `menu.active_trail` dependency along with `menu.link_tree`:

```
private $activeTrail;

/**
 * {@inheritdoc}
 */
public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, MenuLinkTreeInterface $menu_tree, MenuActiveTrailInterface $active_trail, EntityTypeManagerInterface $entity_type_manager, Request $current_request) {
  parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

  $this->menuTree = $menu_tree;
  $this->activeTrail = $active_trail;
  $this->entityTypeManager = $entity_type_manager;
  $this->request = $current_request;
  $this->alias = $this->request->query->get('alias');
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $configuration,
    $plugin_id,
    $plugin_definition,
    $container->getParameter('serializer.formats'),
    $container->get('logger.factory')->get('rest'),
    $container->get('menu.link_tree'),
    $container->get('menu.active_trail'),
    $container->get('entity_type.manager'),
    $container->get('request_stack')->getCurrentRequest()
  );
}

```

Now instead of:

```
$tree = $this->menuTree->load('menu_id', new MenuTreeParameters());

```

get the active trail ID's just before building your menu and pass it in as part of the parameters:

```
// Change this to menu machine name.
$menu_id = 'menu_id';

// This should return an array.
// Array contains menu link uuid's, keyed by the uuid's iirc.
// For example something like:
//   'menu_link:abcdefg_123' => 'menu_link:abcdefg_123'
$activeTrailIds = $this->activeTrail->getActiveTrailIds($menu_id);

$params = new MenuTreeParameters();
$params->setActiveTrail($activeTrailIds);
$tree = $this->menuTree->load($menu_id, $params);

```

This should return you a menu tree with correct active trails.
> 5 votes

# Answer
I also had this case and, as Drif.io describes in his comment to Beebee's answer, I had to extend the core MenuActiveTrail class.

In my case, I solved it via Patch, but in other use cases it would probably be a better idea to extend the class and create an own service. We use the functionality via patch in a core module where we cannot create a dependency to a custom module.

Until now, the function `getActiveTrailIds` was looking like this:

```
public function getActiveTrailIds($menu_name) {
  return $this->get($menu_name);
}

```

I changed the function to accept an optional `$route_match` parameter. However because of the parameter I had to disable the caching of the active trail, because when a regular breadcrumb from the same (Main-) navigation is being shown without the route match parameter, there is another outcome.

```
public function getActiveTrailIds($menu_name,$route_match = null) {
  unset($this->storage[$menu_name]); //disable caching for this case.
  if ($route_match) {
    $this->routeMatch = $route_match;
  }
  return $this->get($menu_name);
}

```

Now I am able to call the service using

```
\Drupal::service('menu.active_trail')->getActiveTrailIds('main',$route_match);

```
> 1 votes

---
Tags: 8, navigation
---


title: hide image title in slide show

text:
# Question
Title: hide image title in slide show
Trying to show **just** the images in a slideshow '***view***'. Not sure where to turn the title off, I've tried changing it to ***`<none>`***, but it's still printing out over the image. I even changed it under '***manage display***' to hidden field and I'm unchecking the default option of creating a label. Where do I need to adjust this at?

# Answer
Change the FORMAT to **Show: Fields** and then **add** only your image field and configure its formatter to show what you need – original image or image style or URL to image ...
> 1 votes

---
Tags: views
---


# Question
Title: Config changes only propagated via manual form submit
My question is related to the Search API Drupal 8 module. I am modifying my configuration via config file updates. After I am installing my custom module, I can see my config reflected in the search index field settings via the configuration form. However, after I re-index I cannot find content via my newly defined fields. This works only, if I open the search index fields configuration form and submit it manually via webbrowser. No config changes - just hitting the save button.

Tried clearing the cache, entity updates, rebuild tracking information, rebuild the search index - nothing helps.

Can I implement anything into hook\_install() from my custom module to propagate the necessary config changes properly to my database?

# Answer
I think I have solved it by myself. I am re-saving the search index by myself via hook\_install().

```
  $index_storage = \Drupal::entityTypeManager()
    ->getStorage('search_api_index');
  $index = $index_storage->load('search_content');
  $index->save();

```
> 0 votes

---
Tags: 8, search, configuration
---


# Question
Title: How to add a role to specific product type customer?
I'm trying to add a user role (darshan) to customer buying product from a specific product type (darshan\_session), using an EventSubscriber in a custom module.

For now, I'm stuck with the following code, where I need still to check the product type and to load the user from the ID.

```
namespace Drupal\commerce_darshan\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Drupal\user\UserAuthInterface;
use Drupal\user\UserInterface;

class CommerceDarshanEventSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events = ['commerce_order.place.post_transition' => 'onOrderPlace'];
    return $events;
  }

  public function onOrderPlace(WorkflowTransitionEvent $event) {
    $event->getEntity()->getCustomerId();

    $user->addRole('darshan');
  }
}

```

As this is my first custom module on D8, any help would be welcome.

# Answer
You're using $user before setting it. You have a CustomId it looks like, but have not created an instance of User with that Id.

Perhaps something like this:

```
public function onOrderPlace(WorkflowTransitionEvent $event) {
  $userId = $event->getEntity()->getCustomerId();
  $user = \Drupal\user\Entity\User::load($userId);
  $user->addRole('darshan');
  \Drupal::logger('mycustom_module_name')->notice('Role "darshan" added to user ' . $user->getDisplayName());
}

```
> 1 votes

---
Tags: commerce
---


title: Drush migrate-upgrade error

text:
# Question
Title: Drush migrate-upgrade error
I have run `drush migrate-upgrade` successfully previously, but not when I run it, I am getting

> "An option named "Configure-only" already exists."

I get this error regardless of if I have `--configure-only` in the command.

The command is:

```
drush migrate-upgrade --legacy-db-url=mysql://user:password@localhost/db --legacy-root=http://example.com --configure-only

```

Has anyone seen this error? I am not seeing anything on any forums about it.

# Answer
I ended up resolving this by uninstalling and reinstalling all of the migrate-related modules. Not an ideal solution, but it worked.
> 0 votes

---
Tags: drush, migrations
---


title: Trigger a drush @sites cr --yes daily

text:
# Question
Title: Trigger a drush @sites cr --yes daily
Drupal 8.

Title sums up pretty much my question.

I'm wondering what is the best way to rebuild all my site's cache daily.

A cron job with Truncate table cache ? Module who rebuild cache on each site ?

Does a plugin exist?

# Answer
The simplest way is a cron job that calls `drush @alias cr` set for 24 hours. You can do that at the server level.
> 2 votes

# Answer
Since the question focuses on website page caching for anonymous users, the case for Drupal 8 is quite simple:

> Drupal 8 provides an Internal Page Cache module that is recommended for small to medium-sized websites. This core module, which is enabled by default, caches pages for anonymous users.

You don't need to do anything, apart from defining the expire duration of your caches for browsers and (reverse) proxies.

Most importantly:

> The page cache in Drupal 8 is instantly updated when something has changed.

Source: https://www.drupal.org/docs/8/administering-a-drupal-8-site/internal-page-cache

Hope that covers the OP, good luck!
> 0 votes

---
Tags: 8, drush, caching
---


title: Image and Media Best Practices

text:
# Question
Title: Image and Media Best Practices
I am looking for suggestions on Best Practices for D8 and files / media entities. I originally added this as a answer but kiamlaluno evidently felt that it should be a new question in itself so here goes.

I trying to figure out the best way to handle files and media entities. With the increase of development in the file entity module if appears that things are once again getting way over complicated since files can now be a full blown entity. In my opinion this is going to put a lot of people off as to which way is the most practical way to go.

What I would love to see is a tutorial or a write up on best practices of when to use the file field versus the media field and the pros and cons of each. Drupal 8 by default gives us a Article content type which is a file entity. So should we use this for images or delete it and use media fields.

Does anyone know of a recent tutorial or discussion for review?

# Answer
> 15 votes
Use media\_entity. End of discussion.

People are actively working on getting it into core and once that happened, there is no reason to use file\_entity anymore.

We (as in me and @slashrsm/MD Systems) will continue to minimally maintain it, as we have a number of big sites (a distribution actually) that relies on it, but it will most likely never get out of alpha while media\_entity is already stable.

We're actively blogging about the status and progress on getting media into core:

# Answer
> 0 votes
Of course, the topic is still evolving, but as of the latest Drupal core (8.6.x), Media is indeed now included, and has come a long way since its D7 roots.

Although there's still a lot to be added, documentation on it does exist. Another advantage of going with Media is that images, files and other assets are more easily reusable, as well as not tied to specific content nodes, making syndication and content migrations easier. (@Berdir, et.al., please correct me if I'm in error).

As @pthurmond notes, it probably is only good if starting a new site. On that, I can speak from experience, relaunching a D7 site as D8, which was completely rebuilt from the ground up. May be worth it for some cases, but could be a monumental hassle, at least at the moment, if migrating an existing large site to the Media Entity paradigm.

---
Tags: 8, media
---


# Question
Title: Different roles create different amounts of a specific content type
I'm building a job directory where users are allowed to register (selecting a membership type) and create Companies and Jobs.

A membership can be *Simple*, *Business* or *Premium*. The membership type is treated in the similar way as a user role. *See the list of roles*:

**My goal is**:

* if the user selects Simple membership (Authenticated user), he / she is going to be able to create only 1 Company and 1 Job;
* if the user selects Business membership (Business user), he / she is going to be able to create 2 Companies and 3 Jobs.

**How can I do this?**

Through the Permissions section I was only able to define if the user can add, edit, delete content and that's not enough.

# Answer
> 1 votes
Sounds like you should have a look at the Group module, which gives you all the features you are looking for, using the "roles" of the Group module (as explained in "What are the various roles supported by the Group module?"), combined with granting the relevant permissions for each of the groups you'd configure. Refer to some of these questions to get you going with the Group module.

BTW, even though this question is about D8, same is true for D7 ...

# Answer
> 0 votes
I don't think Permissions OOTB will be able to do this for you.

It should be doable through a small bit of custom code. I think what I would do is have a form\_alter on the node edit page. In the form alter, get the current user (\Drupal::currentUser()-\>id()) and using the UID, query for nodes that have that user as the author. If the user is currently at the limit of these node types for their plan, then you can alter the form to not allow access, simply setting #access = FALSE, or overriding the entire form, perhaps display markup for them to upgrade their membership, or whatever. Also, you'd want to add the same sort of logic in a #validate function, which you could add in the same form alter. This custom validate function would perform a similar check - if the user account attempting to create this node is "not allowed" by your business logic, then you return a form error stating this is the case, and this way you won't allow users to create more than their quotient.

Here's some of the data querying stuff to get you started:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
  $user_id = \Drupal::currentUser()->id();
  $roles = \Drupal::currentUser()->getRoles();
  $query = \Drupal::database()->select('node_field_data', 'n');
  $query->fields('n', ['uid']);
  $query->condition('n.uid', $user_id);
  $result = $query->execute()->fetchAll();
  ksm($result);

}

```

That `ksm()` statement will require you to enable the `kint` module, but if you haven't already been aware of and using this, I think you'll see the value as a debugging tool.

This should be enough to get you started. If you get stuck, post some code samples so we could further assess the situation!

---
Tags: users, rules
---


# Question
Title: How to render a custom user field in comments?
I want to render a custom user field from the commentator's profile in comment.twig programatically. How to realize that?

# Answer
Try with this:

```
/**
 * Implements hook_preprocess_comment().
 */
function mytheme_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $commentOwner = $comment->getOwner();
  if ($commentOwner){
    $variables['twitter'] = $commentOwner->get('field_twitter')->getValue()[0]['value'];
    $variables['facebook'] = $commentOwner->get('field_facebook')->getValue()[0]['value'];
  }
}

```
> 1 votes

---
Tags: 8, theming, users
---


# Question
Title: How to add reply link under every comment?
I using standart Drupal 8 module for comments. Can I add reply link under comments or I have to install another module?

I'm log in **as administrator**, but i dont see edit/delete/reple link

Help please!

# Answer
Go to *admin/structure/comment/manage/comment/display* and make sure that **Links** not **Disabled** .
> 1 votes

---
Tags: 8, theming, comments
---


# Question
Title: Render entity fields retrieved by EntityQuery
I'm building a table with TableSort retrieved by EntityQuery like explained in this post.

The result fields vary a lot and I have a hard time to figure out how to render the results of the different field types, like dates, arrays of entities, taxnomomies, etc.

The most simple way to format the rows is just outputting the field values:

```
$row = [
    'data' => [
        $node->title->value,
        $node->field_date->value,
        $node->field_persons->value,
        $node->field_tags->value,
];

```

Now I want to output every column in a different way:

* *titles* linked to the node
* *dates* formatted and not as timestamps
* *persons* as list with every person name linked to his node
* *tags* as list with every tag linked to it's taxonomy

I managed to get titles and dates outputted like I wanted, but I can't figure out to do that for persons and tags:

```
foreach ($nids as $nid) {
    $node = \Drupal\node\Entity\NODE::load($nid);
    $link['#markup'] = '<a href="/node/'.$nid.'">'.$node->title->value.'<a>';

    kint($node);

    $row = [
        'data' => [
            \Drupal::service('renderer')->render($link),
            format_date((int)$node->field_date->value,'custom','Y-m-d'),
            $node->field_persons->value,
            $node->field_tags->value,
        ],
    ];
    $rows[] = $row;
}

```

Is there a more elegant way to output content of individual fields? Or do I have to find out for every field how to output it investigating it's field type and building the result on my own?

How would I do that for persons or tags outputting the list of result with links to their nodes?

# Answer
> 5 votes
Fields have a view() method that accept either a view mode or an array with formatter/display settings (same format as stored in a view display config entity or passed to a base field).

$entity-\>get('field\_date')-\>view('teaser').

That returns a render array that you can then display.

If you also use #type table then you can make each row a numeric child key and you can directly use the render array.

---
Tags: 8, entities, database
---


# Question
Title: How to display label and field output inline
I want to display same line label and fields in drupal 8. But by default it's showing field down and label up.

I'm using suffix and prefix it works. How can I display it without suffix and prefix?

```
 $form['doc_date'] = array(
'#type' => 'date',
'#required' => TRUE,
'#date_date_format' => 'd-m-Y',
'#default_value' => (isset($record['doc_date']) && $_GET['num']) ? $d_date:'',
  '#attributes' => array('type'=> 'date', 'min'=> '-180 days', 'max' => date('d-m-Y') ),
  '#prefix' => '<tr><td><table><tr><td class="tdtext_form_cre">Document Date : <span class="mand">*</span><td>',
'#suffix' => '</td></tr></table></td></tr>',
);

```

# Answer
According to default field.html.twig file template which is use to render fields, you have to set `#label_display => 'inline'` and `#title => 'Your label'` Most of themes render inline label and content when class field--label-inline exist, but it is possible that you remove this css style from your theme.
> 1 votes

# Answer
In the views page, field settings, style settings change HTML element to `span`.
> 0 votes

---
Tags: views, theming, forms
---


title: nav arrows AROUND the blog view?

text:
# Question
Title: nav arrows AROUND the blog view?
# nav arrows AROUND the blog view?

I've finally gotten pretty close to what I was aiming for on the recent blog entries ***view.***. I've posted my version above and what I'm aiming for next.. I still need to change the page numbers below for nav arrows on the sides. Is there still something in the views settings I need to be looking for. I saw a place for arrows, but they are always above or below. Is it CSS to push them to either side and let the blogs settle between them?

### css

```
 #views_slideshow_controls_text_previous_slide_show_of_members-block_1_1 {
    background: url(../sites/all/themes/twodrop/images/comment-arrow.gif);
    /* shows image */

    /* Hide the text. */
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
}
 #block-views-the-blog-block h2 {
    text-align: center;
}

```

I did find this thread under similar questions, but it seems a bit excessive.. surely a better answer has bubbled up in 4 years?

.. additional question, so it may warant a seperate thread, but I'm also trying to aling each section. Should I look at moving the title into the header and the date into the footer? Or is this better handled in CSS?

# Answer
> 0 votes
You could create the effect you're after with some clever CSS applied to the default Views pager but it doesn't seem you're very proficient at CSS, and there is a way that may help you get further without coding.

## Carousel Views Format through an additional module

There are some modules that you can use to change your Views `Format` to output views results in a way that resembles what you want, basically a carousel navigation for your views results:

## Better Pager through an additional module

If you don't think that the carousel solution is good for your case you can change the Pager directly with an additional module.

Pagerer is probably your best choice, but there are others if you want to search on your own and compare. Here is a tutorial about how to use it: How to Create Fancy Pagers in your Drupal Views with Pagerer.

## Additional CSS

It's not clear which header and footer you're talking about - the HTML elements? This is CSS related and best solved by using Flexbox or Grid to get the layout with equal column heights but without limiting the column height so you're covered for all content "sizes".

---
Tags: views
---


# Question
Title: How do I add a link to the #title property of a checkbox?
I created a custom module for Drupal 8.6, and I want to post a link to my terms and conditions.

This is the code I am using.

```
namespace Drupal\commerce_agree_cgv\Plugin\Commerce\CheckoutPane;

use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\commerce_cart\Controller\CartController;
use Drupal\node\Entity\Node;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "agree_cgv",
 *   label = @Translation("Agree CGV"),
 *   default_step = "review",
 * )
 */
class AgreeCGV extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $link = Link::createFromRoute($this->t('my terms'), 'entity.node.canonical', ['node' => 1], ['attributes' => ['target' => '_blank']])->toString();
    $pane_form['cgv'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept', ['the general terms and conditions of business' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

}

```

The link does not work. When I go to my page, the link is missing.

>

The server runs on PHP 7.2.

How do I display the link?

# Answer
With `$this->t('I have read and accept', ['the general terms and conditions of business' => $link])` the code would just show *I have read and accept* or its translation in the language set for the currently logged-in user, before Drupal 9.1.0. Starting from Drupal 9.1.0, it would also trigger the following error (visible in the server log).

> Support for keys without a placeholder prefix is deprecated in Drupal 9.1.0 and will be removed in Drupal 10.0.0.

The correct code to show the complete message, including the link, is the following one, which uses placeholders.

```
$pane_form['cgv'] = [
  '#type' => 'checkbox',
  '#default_value' => FALSE,
  '#title' => $this->t('I have read and accept <a href=":general-terms">the general terms and conditions of business</a>', [':general-terms' => Url::fromRoute('entity.node.canonical', ['node' => 1], ['attributes' => ['target' => '_blank']])->toString()]),
  '#required' => TRUE,
  '#weight' => $this->getWeight(),
];

```

To be correctly used, the *:general-terms* placeholder must be put between quotes, as the documentation for `FormattableMarkup::placeholderFormat()` says.

> Use this when using the "href" attribute, ensuring the attribute value is always wrapped in quotes:
>
> ```
>  // Secure (with quotes):
> $this->placeholderFormat('<a href=":url">@variable</a>', [
>  ':url' => $url,
>  '@variable' => $variable,
> ]);
>
> // Insecure (without quotes):
> $this->placeholderFormat('<a href=:url>@variable</a>', [
>  ':url' => $url,
>  '@variable' => $variable,
> ]);
>
> ```
> 1 votes

---
Tags: 8, navigation
---


# Question
Title: How can I set up a "many to many" relation with an entity
How do I set up n:m database relation in a custom Drupal 8 module?

I want to create task entities that may be related to different users (a task may have multiple related users and a user may have different tasks). Using the database directly I would create two tables(as the user table already exists), a tasks table and a task\_users table which contains the relations (User IDs and Task ID)s. How do provide something like this in Drupal 8?

I only find a way to handle 1:n relations in setting up a user reference field (entity\_reference) as a base field definition.

```
$fields['user'] = BaseFieldDefinition::create('entity_reference')

```

But how do I provide a relationship table?

# Answer
> 4 votes
You can set unlimit cardinality, some like this:

`->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)`

This create a intermediate table to reference two entities.

Check api documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21BaseFieldDefinition.php/function/BaseFieldDefinition%3A%3AsetCardinality/8.6.x

---
Tags: entities
---


# Question
Title: How to use drush config:set for translations?
https://drushcommands.com/drush-9x/config/config:set/

For one language site the command is:

```
drush config:set system.site name "Drupal 8 English sitename"

```

But how to be, if the site is multilanguage, at example two languages? Example:

* English site name: "Drupal 8 English sitename"
* Italian site name: "Drupal 8 Italian sitename"

At example for site settings in web interface I can translate it in tab "Translate system information" http://take.ms/i9jUN. But how to set translated config value with drush? It is possible?

# Answer
> 8 votes
For getting the site name in Spanish for example it's

```
drush config:get language.es:system.site name

```

Unfortunately the following doesn't work and I wonder if this is a bug or what's missing.

```
drush -y config:set language.es:system.site name "Hello World"

```

This just gives me

> `Invalid character in Config object name language.es:system.site.`

Will update answer later.

---

Created an issue on drupal.org: drush config:set for other than default collections raises exception. Where I also provided a patch you may use if you are really in need right now.

---
Tags: 8, drush
---


title: How to display the path without alias?

text:
# Question
Title: How to display the path without alias?
With Drupal 8 and Commerce 2.10

I created a php code to display the link of my store.

When I go to the link, it displays:

```
https://www.domaine.com/shop/name

```

I want to display without alias:

```
https://www.domaine.com/store/id

```

How to do ?

```
$link = Link::createFromRoute($this->t('my business'), 'entity.commerce_store.canonical', ['commerce_store' => $store_id], ['attributes' => ['target' => '_blank']])->toString();

```

# Answer
You have to set the option `alias`:

```
$link = Link::createFromRoute(
  $this->t('my business'),
  'entity.commerce_store.canonical',
  ['commerce_store' => $store_id],
  ['alias' => TRUE, 'attributes' => ['target' => '_blank']]
)->toString();

```
> 5 votes

---
Tags: 8, forms, commerce, uri, path-aliases
---


# Question
Title: Views Link Display Settings Is Not Accepting External URL
I want to add an external URL to the Views More Link Display Settings. It is also mentioned in the guide lines as well ("A Drupal path or external URL the more link will point to. Note that this will override the link display setting above."). But it is validating the URL using internal path component.

Error:- InvalidArgumentException: The internal path component 'https://www.google.com' is external. You are not allowed to specify an external URL together with internal:/. in Drupal\Core\Url::fromInternalUri() (line 410 of /var/www/drupal/web/core/lib/Drupal/Core/Url.php).

Please refer to this screenshot.

Please share if there is a way to alter the link display settings. Thanks in advance!

# Answer
You must be using an older version of Drupal because this has been fixed: Views throws InvalidArgumentException in More Link with external URLs.

I tried it on the latest Drupal 8.6.2 and it accepts external urls (your example) without any errors.

You should update to the latest version, even more so for security fixes.
> 0 votes

---
Tags: views, 8, uri
---


# Question
Title: How to get user.field value in node--teaser.twig
That's how I getting user.field value for node--full.twig but this code does not work for node--teaser.twig

```
function MYTHEME_preprocess_node(&$variables) {
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
              $variables['author'] = $node->getOwner()->field_name->value;
    }
}

```

}

Any ideas?

# Answer
This bit's the problem:

```
$node = \Drupal::routeMatch()->getParameter('node')

```

Even if that returned a value, it would probably be the wrong one; it's not common to render the node as a teaser on its own view page.

As it happens, you don't need to load it yourself for any of the view modes. The node is already in `$variables`:

```
function MYTHEME_preprocess_node(&$variables) {
  $variables['author'] = $variables['node']->getOwner()->field_name->value;
}

```

You may need to add a further check of `$variables['node']->getType()` if the field is only available to certain content types.
> 2 votes

---
Tags: 8, theming, nodes
---


title: Use EntityFieldQuery to load by node ID

text:
# Question
Title: Use EntityFieldQuery to load by node ID
How to use `EntityFieldQuery` to load the nodes based on `available` ***nids***. I tried,

```
$query->propertyCondition('nid', $nid);

```

and

```
$query->entityCondition('nid', $nid);

```

Both of the above didn't work. What would be the right way?

# Answer
There's no point doing that, use `node_load()` or `node_load_multiple()` instead (or `entity_load()`). EFQ exists to return you the IDs of entities, essentially so you can use them in an entity load function. If you already know the ID beforehand, then using EFQ is a waste of a database query.

To illustrate, if you were to add a `nid` condition to your query, then these:

```
->entityCondition('bundle', 'article') // ex. article
->propertyCondition('uid', $uid) // node written by a specific user
->propertyCondition('status', 1);

```

are all redundant, your query will just be:

```
$query->entityCondition('entity_type', 'node')->propertyCondition('nid', $nid);

```

and the only useful data you'll get is the node ID, which you already have.
> 5 votes

# Answer
Probably $query-\>propertyCondition('nid',$nid); will work for you. I use same to fetch node like.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article') // ex. article
      ->propertyCondition('uid', $uid) // node written by a specific user
      ->propertyCondition('status', 1); // published nodes
$result = $query->execute();

```
> 2 votes

# Answer
I think it depends. If your entity field query is only using entity property conditions (the columns in the node table), then you can use nid.

If you add a field condition, entity field query will change it's base table (e.g. the table referenced in the FROM part of the from part of the query to that table). In which case, since most fields are generalized between entities, and refer to ids as "entity\_id" instead of "nid" or "uid", you will need to use that column name instead.

I have not tested this with just accessing entity properties, but I'm looking at an EFQ right now that's failing because I use "nid" instead of "entity\_id".
> 0 votes

# Answer
You can use it like

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type','node');
$query->propertyCondition('status', 1);
$query->propertyOrderBy('title', 'ASC');
$query->entityCondition('bundle','committee_tenure');
$query->propertyCondition('nid',$member_com_ids,'IN');
$result = $query->execute();

```
> 0 votes

# Answer
You only need to pass a node ID to `propertyCondition`.

```
$query->propertyCondition('nid', 886);

```
> -1 votes

---
Tags: 7, database
---


# Question
Title: How do I verify a block can be shown in the current page?
I created a normal block and configured it using the following settings.

>

I don't want to show the block on node/2 and node/3, for example. I want to get the block render, but verify first the block can be shown on the current page.

```
// 1 is the block ID.
$block = block_load('block', 1);
// I want to verify if the block can be shown on the current page before getting the renderable array.
$renderable_block = _block_get_renderable_array(_block_render_blocks(array($block)));

```

I can verify `$block->pages` contains the path for the current page, but I think there is a proper way to do that. I am sure there is a core function to which I can pass the block object and the current path.

What core function should I use to verify the block is visible in the current page?

# Answer
With the help of the answer on this question, Here is a helper function to check block visibility in case someone needs it:

```
/**
 * Helper function to remove blocks from list who can not show in the current path:
 * based on , pages, user, roles ..
 * @see: block_block_list_alter().
 * @return mixed
 */
function _check_block_list_visibility_on_current_path(&$blocks) {
  global $user;

  // Build an array of roles for each block.
  $block_roles = array();

  $result = db_query('SELECT module, delta, rid FROM {block_role}');

  foreach ($result as $record) {
    $block_roles[$record->module][$record->delta][] = $record->rid;
  }

  foreach ($blocks as $key => $block) {

    // If a block has no roles associated, it is displayed for every role.
    // For blocks with roles associated, if none of the user's roles matches
    // the settings from this block, remove it from the block list.
    if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
      // No match.
      unset($blocks[$key]);
      continue;
    }

    // Use the user's block visibility setting, if necessary.
    if ($block->custom != BLOCK_CUSTOM_FIXED) {
      if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
        $enabled = $user->data['block'][$block->module][$block->delta];
      }
      else {
        $enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);
      }
    }
    else {
      $enabled = TRUE;
    }

    // Limited visibility blocks must list at least one page.
    if ($block->visibility == BLOCK_VISIBILITY_LISTED && empty($block->pages)) {
      $enabled = FALSE;
    }

    if (!$enabled) {
      unset($blocks[$key]);
      continue;
    }

    // Match path if necessary.
    if ($block->pages) {
      // Convert path to lowercase. This allows comparison of the same path
      // with different case. Ex: /Page, /page, /PAGE.
      $pages = drupal_strtolower($block->pages);
      if ($block->visibility < BLOCK_VISIBILITY_PHP) {
        // Convert the Drupal path to lowercase.
        $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
        // Compare the lowercase internal and lowercase path alias (if any).
        $page_match = drupal_match_path($path, $pages);
        if ($path != $_GET['q']) {
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
        }
        // When $block->visibility has a value of 0
        // (BLOCK_VISIBILITY_NOTLISTED), the block is displayed on all pages
        // except those listed in $block->pages. When set to 1
        // (BLOCK_VISIBILITY_LISTED), it is displayed only on those pages
        // listed in $block->pages.
        $page_match = !($block->visibility xor $page_match);
      }
      elseif (module_exists('php')) {
        $page_match = php_eval($block->pages);
      }
      else {
        $page_match = FALSE;
      }
    }
    else {
      $page_match = TRUE;
    }

    if (!$page_match) {
      unset($blocks[$key]);
    }
  }
}

```

Thank you No Sssweat for pointing me to right direction.
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: What's the difference between drupalSettings and settings parameter in behaviors?
When having the need to pass settings or parameters from PHP to JavaScript, i always used to do so according to a blog post from Acquia - create a dependency to `drupalSettings`, attach the settings on the PHP side and use the `drupalSettings` variable on the JS side.

my\_module.libraries.yml:

```
my_lib:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

my\_module.module:

```
function my_module_page_attachments(&$attachments) {
    $attachments['#attached']['drupalSettings']['my_module']['my_property'] = 'abc';
}

```

Finally my\_javascript.js:

```
(function ($,Drupal,drupalSettings) {
  Drupal.behaviors.test = {
    attach: function(context,settings) {
      console.log(drupalSettings.my_module.my_property); // would output 'abc';
    }
  }
})(jQuery,Drupal,drupalSettings);

```

However, I came to a sudden realization that the `settings` variable of my `attach` function already contains exactly the same variable:

```
(function ($,Drupal) {
  Drupal.behaviors.test = {
    attach: function(context,settings) {
      console.log(settings.my_module.my_property); // would also output 'abc';
    }
  }
})(jQuery,Drupal);

```

So why is there even a separate way to load drupalSettings and it's proposed in every guide I found, when in fact we already have a variable containing our settings, so we don't need to mention the global drupalSettings variable?

Thanks for your clarification!

## Update 1

I found out in my test behavior that the variable `settings` is a reference to drupalSettings, so if you modify one of the two, the other also has the direct changes, and they are therefore equal.

```
Drupal.behaviors.anotherTest = {
  attach: function(context,settings) {
    console.log(settings == drupalSettings); // outputs true
    drupalSettings.testproperty = 'abc';
    console.log(settings == drupalSettings); // still true
    console.log(settings.testproperty); //  outputs 'abc'
    // works also the other way around
    settings.testproperty = 'def';
    console.log(drupalSettings.testproperty); // outputs 'def' now
  }
}

```

This applies to every call of my behavior. On my rather complex project, the behavior gets called 12 times, and while the context variable changes on every call, `settings` is always equal to `drupalSettings`.

# Answer
> 2 votes
The thing to remember is that behaviors can fire both on page load and on AJAX requests.

Upon page load, the global and the parameter passed to the behavior should be identical.

During the course of page interaction, and depending on the AJAX commands, the settings parameter may be different when it fires.

When writing behaviors in Javascript, always use both the jQuery context to scope selectors, and the settings variable that get passed in to be safe and future proof your code even if you aren't using AJAX.

---
Tags: javascript
---


# Question
Title: ERR_EMPTY_RESPONSE during installation with PHP 7.3
I'm trying to install Drupal 8 with PHP version `7.3.0RC4`.

When I go to `http://localhost` it redirects me to `http://localhost/core/install.php` with the empty response error.

I checked the Apache error log, nothing, edited the PHP config (`php.ini`) to display all errors but nothing shows up.

However, when I downgrade to PHP 5.6 it works. Is Drupal ready for PHP 7.3?

# Answer
> 4 votes
Drupal doesn’t officially (or unofficially as far as I’m aware) support PHP 7.3 at time of writing.

You should downgrade to PHP 7.2, and probably consider revising your operating procedures so you don’t end up using pre-release versions of PHP.

If you still see a problem, you probably haven’t configured Apache and mod\_php correctly for the new version.

---
Tags: 8, installation
---


# Question
Title: My Site goes to Maintenance spontaneously
My site goes to maintenance mode **spontaneously** almost every day. I am advised by users.

Everything works fine when I put it out of maintenance mode.

Any explanation is welcome

(Drupal 7.59)

# Answer
> 1 votes
The error came from the Backup & Migrate Module : I had an error when I wanted to access the "Schedule" folder.

When I unstalled the Module, the error disappeared.

# Answer
> 0 votes
This can have a lot of reasons but I try to help to investigate:

1. Be sure only you can have the permission to put the site into maintenance mode
2. You should search for the "state" variable name of the maintenance mode, if am not mistaken it's called `maintenance_mode`. Based on the results you should have a clear view which code parts may change it's state.

# Answer
> 0 votes
If you're having both live and staging instances, and using caching (memcache for example) check your caching configuration.

If your staging configuration is (by error) set to the same key it may be interfering with the live site, where the live site is reading the configuration from cached staging data, or something of the sorts...

---
Tags: maintenance-mode
---


title: Migrate track last imported time

text:
# Question
Title: Migrate track last imported time
Which property should I set to save the last imported time in the migration map (SQL)?

I've seen that adding:

```
source:
  track_changes: true

```

https://www.drupal.org/docs/8/api/migrate-api/migrate-source

The hash is been calculated but no idea how to set the calculation of the time.

Thanks!

# Answer
You have to set setTrackLastImported to `TRUE`.

What I've done is create a new source plugin that extends the source plugin that I was using and set to true the last imported property.

```
/**
 * Source plugin that extends "url" source plugin and saves the last imported
 * date.
 *
 * @MigrateSource(
 *   id = "url_last_import"
 * )
 */
class UrlLastImport extends Url {

public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
    $migration->setTrackLastImported(TRUE);
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
  }
}

```

I don't know if it's the best solution, but it works.
> 1 votes

# Answer
The last import date for a migration is stored in the key\_value store.

See `Drupal\migrate_tools\Controller\MigrationListBuilder.php` for an example on how to get the timestamp of the last import for a given migration:

```
  $migrate_last_imported_store = \Drupal::keyValue('migrate_last_imported');
  $last_imported = $migrate_last_imported_store->get($migration->id(), FALSE);

```

Next to the last imported timestamp it's also possible to get a timestamp for each row (with setTrackLastImported(), see `Drupal\migrate\Plugin\migrate\id_map\Sql`).
> 0 votes

---
Tags: 8, migrations
---


# Question
Title: PHP Warning SplObjectStorage::offsetExists() expects parameter 1 to be object, null given
Updating to 8.5.1 today from 8.4.5, and after a successful update, I start getting the following warnings on every page:

```
Warning: SplObjectStorage::offsetExists() expects parameter 1 to be object, null given in /var/www/docroot/core/lib/Drupal/Core/Render/Renderer.php on line 602

Warning: SplObjectStorage::offsetSet() expects parameter 1 to be object, null given in /var/www/docroot/core/lib/Drupal/Core/Render/Renderer.php on line 616

Warning: SplObjectStorage::offsetExists() expects parameter 1 to be object, null given in /var/www/docroot/core/lib/Drupal/Core/Render/Renderer.php on line 602

```

`core/lib/Drupal/Core/Render/Renderer.php` lines 594 - 618:

```
/**
   * Returns the current render context.
   *
   * @return \Drupal\Core\Render\RenderContext
   *   The current render context.
   */
  protected function getCurrentRenderContext() {
    $request = $this->requestStack->getCurrentRequest();
    return isset(static::$contextCollection[$request]) ? static::$contextCollection[$request] : NULL;
  }

  /**
   * Sets the current render context.
   *
   * @param \Drupal\Core\Render\RenderContext|null $context
   *   The render context. This can be NULL for instance when restoring the
   *   original render context, which is in fact NULL.
   *
   * @return $this
   */
  protected function setCurrentRenderContext(RenderContext $context = NULL) {
    $request = $this->requestStack->getCurrentRequest();
    static::$contextCollection[$request] = $context;
    return $this;
  }

```

`docroot/vendor/symfony/http-foundation/RequestStack.php` line 56 - 62:

```
/**
 * @return Request|null
 */
public function getCurrentRequest()
{
    return end($this->requests) ?: null;
}

```

If I dump `$this->requests` it is an empty array at this point that is causing the SplObjectStorage errors. I am brand new to Symfony and I do not know how to proceed with troubleshooting. Any suggestions would be welcome.

**EDIT 1:**

It looks like it might be an issue with the Shield module.

```
PHP message: Failed to log error:
Notice: Undefined variable: user in Drupal\\shield\\ShieldMiddleware->handle()
(line 79 of /var/www/docroot/modules/contrib/shield/src/ShieldMiddleware.php).

  #0 /var/www/docroot/core/includes/bootstrap.inc(582): _drupal_error_handler_real(8, 'Undefined varia...', '/var/www/docroo...', 79, Array)

  #1 /var/www/docroot/modules/contrib/shield/src/ShieldMiddleware.php(79): _drupal_error_handler(8, 'Undefined varia...', '/var/www/docroo...', 79, Array)

  #2 /var/www/docroot/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\\shield\\ShieldMiddleware->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)

  #3 /var/www/docroot/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\\Core\\StackMiddleware\\ReverseProxyMiddleware->handle(Object(Symfony\\Component\\HttpFoundation\\Request), 1, true)

  #4 /var/www/docroot/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\\Core\\StackMiddleware\\NegotiationMiddleware->handle(Object(Sy...',

```

# Answer
> 0 votes
I got the same error after updating to Drupal 8.4.0, but only after importing the split configuration for my development environment.

After seeing the note above about a possible issue with the **shield** module, I checked the configuration page for the module and found that not all the shield module configuration fields were showing. I then uninstalled and then reinstalled the **shield** module.

New error messages have not appeared in the log nor on the screen after doing this.

Note: I have three configuration splits and had to uninstall and reinstall on the dev and test splits to fix this. The live split was OK. I also exported the update configuration for the shield module to each configuration split.

One other note: It could be that the configuration for the shield module did not get save to some of my configuration splits. If the shield module (and possibly other modules) cannot handle these values not being set it could be what is leading to these errors.

# Answer
> 0 votes
I was able to get this error to go away by deleting my entire project and rebuilding from scratch. Was not ever able to identify the source for the warnings, so if you come here looking for answers, best of luck. If you find any, please share!

# Answer
> 0 votes
I received this today on my test server (XAMPP with composer)
It allowed me to 'Clear Cache' and after clearing the Cache the error is gone. Apparently my updating and/or removing a module needed me to clear the cache.

---
Tags: 8, routes
---


# Question
Title: View output add a class to first and last rows
I'm trying to output views and i'm using 960gs as well.

It possible to enable views processing so views knows if it this is the last one of the row and that way i can add a class "alpha" to the first view out put and "omega" to the 4th item and last item?

Update: Looking for primarly a php solution; not a jquery one; as it's not best practice to utilize javascript to manipulate layouts (IMHO).

# Answer
> 0 votes
Discovered that this is answer is still being worked on by the community. It's been a long-standing problem with views.

There's a issue queue node here: http://drupal.org/node/1188216

Hopefully, there will be a patch for this eventually.

As for now; I've found refuge in display suite for certain contexts and semantic views plugin

# Answer
> 2 votes
The contributed Semantic Views module has the option of adding first and/or last class attributes. Pretty snazzy solution since you can also use it to specify better html elements at the same time!

# Answer
> 1 votes
if you does not recieve answers that help from backend perspective, I am sure that you can solve this from jquery perspective:

**Jquery select first and last divs from a list of items**: https://stackoverflow.com/questions/3328076/jquery-select-first-and-last-divs-from-a-list-of-items

For instance this set of divs (also is possible with `li`, `a`, etc..):

```
<div class="item">qwe</div>
<div class="item">asd</div>
<div class="item">zxc</div>
<div class="item">ghj</div>
<div class="item">bnm</div>

```

with Jquery you can select first and last item, in this case, to add a class to first/last target elements (put this in the end of your view results template):

```
<script>
$('.item')
    .eq(0).addClass('first').end()
    .eq(-1).addClass('last').end();
</script>

```

of course you must have respective class to this different elements, for instance:

```
<style type="text/css">
.first, .last{
background-color:#0099FF;
}
</style>

```

and here is the result:

this is another example: **Addressing first/last item in an ul, li**: https://stackoverflow.com/questions/5680032/addressing-first-last-item-in-an-ul-li

I hope information be useful.

---
Tags: 7, views, theming
---


# Question
Title: Why is my JSON looking like this and what can I do about it?
On Drupal 8, I enabled the serialization and restful web services and I created a restful view in order to create a map. The format is WKT. However, the output looks like the below.

Can/should I do something about it? Can this be parsed as is?

# Answer
> 2 votes
I'm assuming you're talking about the presence of `\u003Ca` and similar...

It's like that because `Json::encode` uses the `JSON_HEX_TAG`/`JSON_HEX_QUOT`/etc flags. It's done to ensure that all strings in the document are RFC4627 compliant.

You shouldn't need to worry about this, any compliant parser will happily translate the hex back to the original characters.

---
Tags: views, 8
---


title: Auto translate content of nodes

text:
# Question
Title: Auto translate content of nodes
I am developing a Drupal 7 site, where i store the content of a cotent type(with several fields). So by default, i enter the English text for the content and save it.

Is it possible in Drupal to automatically translate the content in English to other languages like French, Spanish, German, etc? I have been experimenting with several modules like Content Translation, which provide the option to enter content manually in other languages. But i don't like to enter the content separately for each language, rather i like to automatically translate it with the click of a button. Is there such a module or feature in Drupal 7 ?

As a final alternative, i thought to use an API like Google Translator in the background, when saving my node content, but i hope there is a module available for automatic content translation.

Note: I am not interested in using any widget on the front end, for content translation. Instead, i prefer admin to translate content with one click in the backend.

# Answer
> 3 votes
**It will never be good.** Human languages are not something perfectly unambiguous and logical\*, so no computer software will ever be able to translate them perfectly. **You need a human to properly translate human languages**.

Google Translate is bad, but I haven't seen anything better. Sadly, Translate API got deprecated in 2011. This means that modules using it may work for now, but may stop working without notice. See GTranslate and i18n auto translate.

You can always use some code from above modules, and try another machine translator. See Comparison of machine translation applications article - deciding which one to implement is outside the scope of Drupal Answers, just remember that you want GPL software if you want to mix it with contrib modules' code without fees or legal risk.

---

* OK, there is Lojban, but that's an exception.

# Answer
> 2 votes
It's 2018 and a lot has changed in machine translation since this question was asked. My testing shows, that for example Google Translate is surprisingly usable also for such translation pairs as Slovak \<-\> English, which just couple of years ago was terrible. Additionally, there is the Translation Management Tool module for Drupal 7 and 8 that supports both - manual as well as machine translations for entities or even strings. A number of "human" and a couple of machine translation service providers can be utilized for the actual text translation in that module.

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


# Question
Title: Edit custom field using user_presave hook during account creation
I have made a custom field for user `field_custom_xyz` from the admin GUI. Now after i saved it i got two tables into the database : one for data and one for revisions.
I already have a huge database into which a lot of users are already there.

I have two questions :

1. How can i make sure that i can assign default value to each user at the time of creation of this field?
2. Let's say if i have to assign a default value of `0` (or null in case i don't follow step 1).
how can i change that value at the time of new registration using **hook\_user\_presave** ?

I want to override the default value of this field using `user_presave` hook in some custom module lets say 'abc' module

so far i have tried :

`$account->field_custom_abc['und'][0]['value'] = 0;`

but that doesn't work, any suggestions. thanks in advance.

# Answer
> 1 votes
Try this out:

```
/**
 * Implements hook_user_presave().
 */
function mymodule_user_presave(&$edit, $account, $category) {
  $edit['field_custom_xyz'][LANGUAGE_NONE][0]['value'] = 0;
}

```

---
Tags: 7, hooks
---


title: Get raw value of a block content

text:
# Question
Title: Get raw value of a block content
I have created several views. These views have a block display. If I use these blocks in my template, the views are rendered with all the wrappers / divs. In my block template, can I alter the output of the "content" variable to get only the values? I tried to use different twig filters (striptags, trim, raw), without success. With these filters I get nothing.

Thanks.

# Answer
A lot of templates are used to output a single Views display. It depends on your particular case which level you want to override. These templates are probably the best way to control the output of the views where ever you want to print them.

One template outputs the outer views divs, another is for particular format options, others are for controlling rows output. So you have to investigate and override the templates where you want to change the HTML for that particular view.

You can strip each individual Field of its wrapper and even field HTML in its `Style settings` directly in Views.

You can see the template suggestions under `Theme: information` in D7 Views, and in D8 you have to turn on the debugging mode to see the suggestions in page output.
> 0 votes

---
Tags: theming, blocks
---


# Question
Title: Get all the text fields type and alter value after save
I'm trying to alter the value of entity text fields upon node save, even the custom-made fields

so far I've managed to do that with the title and default body field but not with a custom field, I'm trying to target any field that might be a text field, here's my code:

```
function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $replacement_pattern = array("/a/", "/b/");
  $replacement = array("c", "d");

  /* Check whether it's a node */
  if ($entity instanceof \Drupal\node\NodeInterface) {
    // Node title
    $nodeTitle = $entity->getTitle();
    $entity->setTitle(preg_replace($replacement_pattern, $replacement , $nodeTitle));

    // Body main
    if(!empty($entity->body->value)) {
      $entity->body->value = preg_replace($replacement_pattern, $replacement , $entity->body->value);
    }

    // Body Summary
    if(!empty($entity->body->summary)) {
      $entity->body->summary = preg_replace($replacement_pattern, $replacement , $entity->body->summary);
    }
  }
}

```

# Answer
Another approach by checking *field name*. I think this will get you the "custom" field part, but not the "all" fields part:

MYMODULE.module:

```
use Drupal\Core\Entity\EntityInterface;

function MYMODULE_node_presave(EntityInterface $entity) {
  if ($entity->hasField('field_name')) {
    $entity->get('field_name')->value = preg_replace(
      $toReplace,
      $newText,
      $entity->get('field_name')->value
    );
  }
}

```

But this only checks for fields of that name. I am also looking for a way to alter the value of a ckeditor/text field by testing *field type* instead of *field name*.

I would have hoped setting the *field name* value to something like `text_long` would have worked. This is a base field hook suggestion, but I am not having any luck at this time.

To add to the use case, it would be nice to alter ckeditor/text fields whether attached directly to the node, or via a Paragraph type.

The answer in the comment link above is helpful, but I have not succeeded in implementation.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Custom submission handler doesn't save the node
I have two form submission buttons: the normal one and one added via `hook_form_alter`.

I'm currently using the normal default one as a save button which updates the node content as normal.

The second one which is called submit does the same thing, but will be changing a checkbox via `$form_state` prior to saving the node content.

The code I'm using is the following one:

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

  if ($form_id == 'example_node_form') {

    //dpm($form);
    $form['actions']['finishbutton'] = [
      '#type'   => 'submit',
      '#value'  => t('Submit'),
      '#submit' => array_merge($form['actions']['submit']['#submit'], ['custom_submit']),
      '#weight' => 99,
    ];
  }
}

function custom_submit($form, &$form_state) {

  drupal_set_message(t('This works, but shows up after the node submit message'));

  // Shows after the node save message.
  dpm($form_state);

  // Doesn't update.
  $form_state['values']['field_nomination_submitted'][LANGUAGE_NONE][0]['value'] = 1;
}

```

My submission works, but the custom handler appears to be firing after the standard submission handler. Do I need to switch the array\_merge order? Do I need to break this into separate functions? Do I potentially need to add a submit function inside of custom\_submit?

# Answer
Use `[]` syntax instead of `Array()` and switch the order ... that should work.

Credits: Shawn Matthews.
> 1 votes

---
Tags: 7, forms
---


title: Show all tags for a views query?

text:
# Question
Title: Show all tags for a views query?
I am trying to write a views\_query\_alter hook and I want to identify the query I'm interested in. I have found the methods `hasTag()`, `hasAllTags()`, and `hasAnyTag()`, but I don't already know which tags I'm looking for. How can I get Drupal to tell me what tags already exist on queries? I didn't see any `getTags()` method.

# Answer
> 3 votes
I believe you mean hook\_query\_alter() here by mentioning `hasTag()`, `hasAllTags()`, and `hasAnyTag()` not hook\_views\_query\_alter().

You can understand more about these methods from this documentation.

By help of these methods you can specify the targeted query, when you apply this in your module. A example code has been given in answer at Stackoverflow question, which helped me long ago to modify a query of views.

```
function MY_MODULE_query_alter(QueryAlterableInterface $query) {
  if ($query->hasAllTags('views', '[MY VIEW NAME]')) {
    $query->addJoin('INNER', 'taxonomy_index', 'ti', 'node.nid = ti.nid');
    $query->condition('ti.tid', '2,3', 'IN');
  }
}

```

If you are looking for the tags which you can use, just try to print `$query` inside the `hook` & see the result on the page where you are working. You will get what query you can target & the tags which you can use.

I hope it helps :)

# Answer
> 0 votes
Actually, `hook_views_query_alter` takes the view object and its query as arguments, so to identify the query I want to modify, I actually will look at the view object to see if it's the one I want.

# Answer
> 0 votes
The right way to get all tags from a query is:

```
dpm($query->alterTags);

```

---
Tags: views
---


# Question
Title: How do I update the CKEditor text widget using CKEditor API
I am using Drupal 8's Ajax API to update form fields in a form depending on the input in another field. One of the fields I want to update is a text\_format field that uses Drupal's ckeditor.

If I understand the CKEditor API correctly, I should be able to update the text in the ckeditor widget using the setData() method (https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR\_editor.html#method-setData). The ckeditor instance should be the textarea id - and that I can easily identify in my AjaxResponse function.

However, I am not sure how to use Drupal's invokeCommand() to make use of the CKEditor API?

# Answer
> 1 votes
In the end I was able to solve this using a custom Ajax command:

1. In our custom module (called b47\_custom\_authors) we created a custom ajax command in `src/Ajax/B47CustomAjax.php`

```
/**
 * @file
 * Contains \Drupal\b47_custom_authors\Ajax\B47CustomAjax.
 */

namespace Drupal\b47_custom_authors\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class B47CustomAjax implements CommandInterface
{

  /**
   * A CSS selector string.
   *
   * If the command is a response to a request from an #ajax form element then
   * this value can be NULL.
   *
   * @var string
   */
  protected $selector;

  /**
   * An optional list of arguments to pass to the method.
   *
   * @var array
   */
  protected $arguments;

  /**
   * Constructs an b47customajax object.
   *
   * @param string $selector
   *   A jQuery selector.
   * @param array $arguments
   *   An optional array of arguments to pass to the method.
   */
  public function __construct($selector, array $arguments = []) {
    $this->selector = $selector;
    $this->arguments = $arguments;
  }

  public function render(){
    return [
      'command' => 'b47customajax',
      'selector' => $this->selector,
      'args' => $this->arguments,
    ];
  }
}

```
2. The custom js (in `js/b47customajax.js`) is as follows:

```
Drupal.AjaxCommands.prototype.b47customajax = function (ajax, response) {

// response is an array with the keys
// response.command: the command called (b47customajax)
// response.selector: the selector to be used (NULL)
// response.args: the arguments to be passed as an array: 0: the ckeditor instance, 1: the text (data) to be passed

var ajaxckeditorinstance = response.args[0];
var ajaxckeditordata = response.args[1];
var editor;

var instance = CKEDITOR.instances[ajaxckeditorinstance];

if (instance) {
   // Trying to call setData method: https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-setData
   editor = instance.setData( ajaxckeditordata , {
          callback: function() {
                      this.checkDirty(); // true
                  }
          });

};

```

};
3. In my ajax callback function I call my custom ajax via:

`$response->addCommand(new \Drupal\b47_custom_authors\Ajax\B47CustomAjax('textarea'.$fieldid,[$fieldid, $texttobeinserted]));`

The `$fieldid` is the id of the textarea, and `@texttobeinserted` is the full html of the text I want in ckeditor.

This now allows me to update the ckeditor based on the text dynamically via my AjaxResponse. The textfield is hidden by default and depending on the input in another field I fetch the text that needs to be placed in the textarea/ckeditor. The form field is then also displayed.

This now works.

---
Tags: 8, ajax, wysiwyg
---


title: How to execute a migration?

text:
# Question
Title: How to execute a migration?
I'm trying to use the Migrate API module to implement an ETL for some of the content of my Drupal 8 website, but the documentation doesn't explain how to execute the migration once everything has been set up. It only explains how to execute the migration using some contributed modules but not how to execute it using the Drupal API.

How do I programmatically execute migrations from a module?

# Answer
> 7 votes
Drupal 8 Migrations are plugins. So you can create instance and execute like this:

```
<?php

use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateMessage;

$migration_id = 'MIGRATION_ID';
$migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
$executable = new MigrateExecutable($migration, new MigrateMessage());
$executable->import();

```

---
Tags: 8, migrations
---


# Question
Title: Arranging tab menus created by views module
I've created 3 different view and added them to a tab menu.

now these 3 menu items are sorted alphabetically and the default tab menu is printed as middle item .

I wanted to sort them using menus but tab items doesn't exist there .

> How can I reorder tab items created by views module?

# Answer
You can provide a weight while editing the Views tab: . Higher weights will be moved to the back of the order. But since you cannot see the weights of the other tabs this can take quite a while to get right.

Better is to have a look at Tab Tamer

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
> 4 votes

# Answer
You can adjust the weight in hook\_menu\_local\_tasks\_alter:

```
/**
* Implements hook_menu_local_tasks_alter()
*
* @param $data
* @param $router_item
* @param $root_path
*/
function HOOK_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if ($root_path == 'admin/content') {
    // You add #weight here on item level not link level
    $data['tabs'][0]['output'][0]['#weight'] = '1000';
  }
}

```

For more code you can also look here: Altering menu local task title
> 1 votes

# Answer
I know that this is 2 years ago, but this will help somebody looking for similar problem.

here you can see full code for creating menu tabs with weight. (just put weight in $items array under key)

```
$items['processing'] = array(
    //'title' => t('Create Menu Tab'),
    'access callback' => TRUE,
    'access arguments' => array('dn_release'),
    'page callback' => 'drupal_get_form',
    'page arguments'  => array('dn_wawi_release_form'),
  );

  $items['processing/order/release'] = array(
    'title' => 'Release orders',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'access arguments' => array('dn_release'),
    'page callback' => 'drupal_get_form',
    'page arguments'  => array('dn_wawi_release_form'),
    'weight' => 1,
  );

  $items['processing/order/labels'] = array(
    'title' => 'Print labels',
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('dn_wawi'),
    'page callback' => 'drupal_get_form',
    'page arguments'  => array('dn_wawi_generate_tracking_form'),
    'weight' => 2,
  );

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Exporting and Importing configuration setting only
I have a development and a production site. Both are working in an offline environment, Drush and Composer are not installed.

The plan is to make all changes always on the development and during each "release" to simply synchronize the changes on the production site.

Currently this is working fine via UI "Configuration Synchronization -\> Import/Export " feature.

But I would like to execute this on the command level ( Linux ) and as it was mentioned, no drush is installed.

**Question:** Is it possible to export just the CONFIG Table from MySQL database and import this on the production site? Would this be similar to the Import/Export mentioned above?

# Answer
> 2 votes
Importing configuration in SQL alone is not possible, you need to run PHP code.

From the command line, if you don't have Drush installed, you can download Drush on the fly and execute the import command:

```
wget https://github.com/drush-ops/drush/releases/download/8.1.17/drush.phar
php drush.phar config-import

```

---
Tags: 8, configuration
---


# Question
Title: Drush hangs out on dl commerce_kickstart
in recent days new version of Commerce Kickstart 2 was introduced (v2.55). I tried upgrading my current installation (v2.54) using drush:

```
drush --debug dl commerce_kickstart

```

unfortunately after this line:

```
Verifying signature for bzr version control engine. [3.27 sec, 42.21 MB]
Executing: bzr root profiles

```

I'm stuck with this , please give any some tips. I'm using 7.4.0 drush version.

# Answer
> 0 votes
I'm using drupal 7.60 with Commerce kickstart 2.55 now. I've figured it out. The problem was with the missing command line prompt asking to continue the installation in the current directory. After debugging drush I noticed that i needed to type "y" than the process started to continue. Anyways it was very strange but finally it worked.

---
Tags: commerce, drush, upgrading
---


title: Different Templates for Same Field

text:
# Question
Title: Different Templates for Same Field
I want to have two different templates for the same field on a node template.

For example:

```
<div class="navigation>{{ content.field_section }}</div>

    // uses paragraph--section.html.twig
    // Only want to print the titles from paragraph sections

<section>{{ content.field_section }}</section>
    // uses paragraph--section2.html.twig
    // Want to print the body and titles from paragraph sections

```

How can I do this? Is there a way to flag one instance or force a specific template?

# Answer
> -1 votes
You can override existing twig file in preprocess hook. You may check the link https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates.

---
Tags: 8, theming, paragraphs
---


title: Remove index.php from imported urls

text:
# Question
Title: Remove index.php from imported urls
I made some migration of pretty old website to d8. And urls ported fine from latest WP version:

```
/user1/article-name1
/user2/2009/article-about-something
/user3/2017/11/06/article-something

```

But from what I see in google many articles would be linked with index.php at the end i.e.:

```
/user1/article-name1/index.php
/user2/2009/article-about-something/index.php
/user3/2017/11/06/article-something/index.php

```

etc etc. Somehow WP could handle it (no traces of overrides in htaccess), but Drupal would not.

Puzzled how to fix it with htaccess, preferably with 301 redirect.

Thanks for your ideas!

# Answer
> 0 votes
Solved thanks to https://stackoverflow.com/questions/27907044/htaccess-rule-to-remove-index-php-from-the-end-of-my-urls

Modified part of Drupal's .htaccess. Important to add new rule before standard index rewrite:

```
# Remove trailing /index.php that comes from external links.
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^(.*?)index\.php$ /$1 [L,R=302,NC,NE]

# Pass all requests not referring directly to files in the filesystem to
# index.php.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

---
Tags: 8, redirection, .htaccess
---


# Question
Title: Show last node of every term in one Views
How to show the last node of every term using only one View? That's what I want to get:

`news/football` \- last node of the football term

`news/boxing` \- last node of boxing term.

How can I do it?

# Answer
The answer is:

1. Contextual Filter -\> Content: Has taxonomy term ID
2. When the filter value is not in the URL -\> Provide value -\> Type: Taxonomy item ID from URL
3. Relatoinships -\> does not necessarily.

Works perfect: Drupal core 8.6.1
> 0 votes

# Answer
1. Create a view to show content
2. Add page display and set path setting to *news/%*
3. Add contextual filter "Has taxonomy term ID"
4. Add sort criteria "Authored on (desc)"
5. In pager settings check "Display a specified number of items" and set "Items per page" setting to 1.

Note that this will produce URLs with numeric term IDs (i.e. *news/123*). To make use of term names you need to configure a relationship to the term so you get the information about the term into view, then use term name contextual filter.
> 3 votes

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