# Question
Title: Change a paragraph link field title at runtime
We have a site with numerous paragraphs, one of which is a Call-to-action, comprised of a title, summary and a link field (machine name: field\_link).

The CTA is used so much that to change the word 'Enquire' to 'Inquire' for when we are on a US translation (en-US in url) would require the paragraph been edited manually for every content page that has a us translation would be a monumental task.

As such I've decide to attempt to simply handle this in the paragraph preprocess hook. The original idea was simply to check if we were in a us translation, then check for the word in the field\_linl title and change it if needed, as per my snippet below.

```
/* Translation modifier:
   * The call to action paragraph is used on almost all pages and translations
   * doesn't work with paragraphs at all. So we need to detect if we are in a US
   * translation and change out the spelling of certain words.
   */
  if($paragraph_type == 'call_to_action'){

    if(is_us_translation()){
      $cta_link = $paragraph->get('field_link');
      $cta_link->list[0]->values['title'] = 'Inquire';
      $paragraph->set('field_link', $cta_link);

      // $paragraph->values['field_link']['x-default'][0]['title'] = 'Inquire';
    }
  }

```

The commented out line was my other attempt.

My problem though is nothing I have tried seems to manage to change the title of the field. Is there a specific way to change this?

# Answer
> 1 votes
This worked for me

```
function MYTHEME_preprocess_field(&$variables, $hook){
  $element = $variables['element'];

  /* Translation modifier:
   * The call to action paragraph is used on almost all pages and translations
   * doesn't work with paragraphs at all. So we need to detect if we are in a US
   * translation and change out the spelling of certain words.
   */
  if(is_us_translation()){
    if (isset($element['#field_name'])) {
      if ($element['#field_name'] == 'field_link') {
        $str_to_check = strtolower(trim($variables['items'][0]['content']['#title']));

        if(strpos($str_to_check, 'enquire') !== false){
          $variables['items'][0]['content']['#title'] = 'Inquire';
        }
      }
    }
  }
}

```

---
Tags: 8, hooks
---


# Question
Title: How to send an email on every 10 contents that are waiting for admin approval?
I want to notify admin only if there are 10 nodes in a queue. If 10 such nodes do exist, a single email should be triggered to admin.

How can I do this, any idea?

# Answer
> 1 votes
1. I have get all the users (uid) of particular role from the `users_role` table.

i.e :

```
$query = 'SELECT DISTINCT(ur.uid) FROM {users_roles} AS ur WHERE ur.rid IN (:rids)';
$result = db_query($query, array(':rids' => array(3,8)));

```
2. Next step, I have count nids from `workbench_moderation_node_history` table.

i.e I have made one function like `get_train_users()` in which i have returned the above `$result` array.

```
$trainusers = get_train_users();
foreach ($trainusers as $key => $value) {
   $tresult [] = db_query ('SELECT COUNT(nid) AS con,uid FROM  {workbench_moderation_node_history} WHERE uid = :uid AND state = :state' ,array(':uid' => $value, ':state' => $state))->fetchAll();
}

```
3. Now, In last step, I am counting the count of `con`, Like if it is greater then 10, then i am sending the mail when cron runs.

That's it.

# Answer
> 1 votes
As a variation to what's described in your own answer (using custom code), you can make this work also by using Rules in combination with the Views Bulk Operations module, as further detailed below.

### Step 1

Use the Views Bulk Operations module to create a view of all your nodes that "*are pending, waiting for admin approval*" (as in your question), in which you add a VBO field to it. Simply include a field like `nid` for each node (no need for any other fields). Just make sure you get exactly 1 row for each node (waiting admin approva) you want to take into consideration.

### Step 2

Create a Rules Component with a Rules Condition "***Check number of results returned by a VBO view***". And select the VBO view created in the previous step. If the number of results is 10 or more, then perform a Rules Action (in that Rules Component) to trigger your eMail for the admin.

### Step 3

Create a Rule like so:

* Use some relevant **Rules Event** related to the creation (and possible update also?) of those nodes which are waiting admin approval.
* Don't use any **Rules Conditions** (there is no need for them in this rule).
* Perform a **Rules Action** to execute the Rules Component from Step 2.

***Done!***

PS: I'm assuming this question is about D7.

---
Tags: emails, rules
---


# Question
Title: How can I bootstrap a multi-site instance?
It's possible to bootstrap Drupal 8 and create a new node using answer # 174474.

```
define('DRUPAL_DIR', '/usr/share/nginx/html');

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';

// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);
$em = $kernel->getContainer()->get('entity.manager');

$entity = $em->getStorage('node')->create([
  'type' => "article",
  'title' => "test entity",
  'body' => "body body body",
]);
$entity->save();

```

Is it possible to bootstrap a subsite database when using multisite to create the new node in a specific subsite?

In Drupal 7, this can be done by using the function drupal\_override\_server\_variables, but this function doesn't exist in Drupal 8.

I also tried modifying the $\_SERVER\['HTTP\_HOST'\] and $\_SERVER\['SCRIPT\_NAME'\] variables according to this forum post, with no luck.

# Answer
> 1 votes
I was able to get this working by setting the server variable $\_SERVER\['SCRIPT\_NAME'\] to '/subsite/index.php' (where /subsite/ is the url path to the subsite).

```
$_SERVER['SCRIPT_NAME'] = '/subsite/index.php';

define('DRUPAL_DIR', '/usr/share/nginx/html');
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';

// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);
$em = $kernel->getContainer()->get('entity.manager');

$entity = $em->getStorage('node')->create(
array(
  'type' => "article",
  'title'=> "test entity",
  'body' => "body body body",
));

$entity->save();

```

---
Tags: 8, multi-sites, bootstrapping, external-scripts
---


# Question
Title: Cannot print $variables using template_preprocess_views_view_rss() in readable format
How can I print out $variables from template\_preprocess\_views\_view\_rss() in a readable format? The RSS view page uses a non-rendering format and is impossible to read. I need to manipulate the feed because no D8 RSS module is stable at this point.

# Answer
> 0 votes
My solution was to use `kint()` and `print_r()` with `array_keys()` to locate all the objects for manipulation. In some cases I was debugging with the kint() display and in others just looking at plain text by using the other mentioned functions.

For note the `template_views_view_rss()` and `template_views_view_row_rss()` hooks are located in view.theme.inc (core) and no where in documentation on drupal.org for D8. I believe they are soon to be deprecated.

```
// Specific feed filter
if( $variables['view']->id() == 'blog' && $variables['view']->current_display == 'feed_1') {
  // Iterate rows
  foreach($variables['rows'] as $key_1 => $row) {
    // Do stuff
    foreach($row['#row']->elements as $key_2 =>  $element) {
      // Do stuff
    }
  }
}

```

---
Tags: views, 8, feeds
---


# Question
Title: Information added by Drupal.org on Distribution
Hi am trying to make a Drupal 8 Distribution, all is well, but when I download it from drupal.org I get on all modules this information.

I would like that all contrib modules to have their default information. What do I need to setup in order to remove the profile package from contrib modules?

In the image below Drupal.org comment out the module information and added profile information. I do not want to add the profile information on to the contrib modules.

```
# core: '8.x'
# Information added by Drupal.org packaging script on 2017-08-15
# version: '8.x-1.0'
# core: '8.x'
# project: 'ace_editor'
# datestamp: 1502816349

# Information added by Drupal.org packaging script on 2018-01-18
version: '8.x-1.x-dev'
core: '8.x'
project: 'myprofile'
datestamp: 1516303995

```

So it's not confusing I don't want to remove the information from Drupal.org. Somehow Drupal.org is packaging the modules as part of the profile, and the result is the image below

I want to be able to see it normally like the image below

# Answer
> -1 votes
Whoever is getting the same error it is probably you got some patches and themes that are not from Drupal.org

The 2 links below helped me see what my problem was:

https://www.drupal.org/docs/develop/packaging-a-distribution/how-to-package-a-distribution-on-drupalorg

https://www.drupal.org/docs/develop/packaging-a-distribution/drupalorg-distribution-packaging-requirements

---
Tags: distributions
---


# Question
Title: Display nested relationships on a single view
**Context**

I have three custom node types (Batch, Item, Order) that I use to track orders (I don't need the power of full-blown Commerce). These are linked through the following entity reference fields:

Batch-\>Item through field\_items on Batch

Order-\>Item through field\_items on Order

I have a table view set up which shows Items by Batch.

**The Question**

Is there a way I can display, on the same view, the Order name (if any) that each Item is allocated to?

# Answer
Okay, so I've largely solved this one as follows:

* The View is set to a table showing content of type Batch
* I've added two relationships. The first is to items referenced by the content which are of type = Item (and which does not use any relationship). The second is to items having a reference to the content, are of type Order, and use the first relationship
* I've then added fields from all three content types (using the appropriate relationships) to create the flat table I'm looking for.
> 0 votes

---
Tags: 8, views
---


# Question
Title: Adding multiple links to the same table cell
I am struggling to add multiple links to the same table cell, my current code looks like:

```
use Drupal\Core\Link;

$row[] = [
  'data' => Link::createFromRoute(...),
  'class' => 'middle',
];
$row[] = [
  'data' => Link::createFromRoute(...),
  'class' => 'middle',
];
$rows[] = ['data' => $row, 'no_striping' => TRUE];

return [
  '#theme' => 'table',
  '#header' => [..],
  '#rows' => $rows,
];

```

I've cut down the code to the relevant parts each element of the `$row` variable is a new cell and each element of the `$rows` variable is a new row. I need to use the data attribute as I have additional attributes on the cell.

At present this works perfectly fine, but my links are rendered in separate cells and I would like them rendered in the same cell. If I just to concatenate the 2 `Link::createFromRoute` I get the following error:

`Recoverable fatal error: Object of class Drupal\Core\Link could not be converted to string`

I've tried using the `toString()` and the `toRenderable()` functions and neither work as I want. Surely it can't be that hard?

# Answer
> 2 votes
I think you can do it as Clive alluded to with render array:

```
  $link_1 = Link::createFromRoute('Link 1', 'route_1')->toString();
  $link_2 = Link::createFromRoute('Link 2', 'route_2')->toString();
  $link_concat = ['#markup' => $link_1 . ' - ' . $link_2];

  $header = [ ... ];
  $row = [];
  $row[] = [
    'data' => \Drupal::service('renderer')->render($link_concat),
    'class' => 'middle',
  ];
return [
  '#theme' => 'table',
  '#header' => [..],
  '#rows' => $row,
];

```

This is just one method of doing it, there are a lot of ways you could potentially work this scenario. This way just puts the two links with a dash in between. But hopefully this will help guide you towards a solution.

---
Tags: 8
---


# Question
Title: How can I create a view that shows image file fields which do not have any data?
I'm using Drupal 7 and I have a content type, **Picture**, which includes an image field. Users use this to add image to the site.

Sometimes, however, there is no data on the server. For example, if I copy the database from my production to my testing server, the image files will be registered in the db but they don't actually exist on the testing server, so the pictures cannot be displayed.

I would like to create a view that shows these images-- the data is in the DB, but the file does not actually exist.

I created a view for my content type **Picture** and added the following **Filter Criteria**

* Image: fid- empty
* OR File size- empty (Through *File Usage: File* relationship)

However, this does not show pics that exist in the DB but not in the filesystem.

Is there a way to do this in views, or is there no way to test if the file actually exists?

# Answer
> 1 votes
It's never a good idea to put PHP code in the database, period. You should consider using a custom views handler. It's a somewhat involved process, but worth it in the end because your code can be version controlled, and you won't wind up with mysterious errors that are a result of PHP code being executed from the DB. There are a lot of great tutorials out there on how to do this, here's one that I used with great success - https://kalamuna.atlassian.net/wiki/spaces/KALA/pages/20512879/Custom+Views+Field+Handler.

Your custom handler in this case could return either the image, or a placeholder if none was found. You'll have full control over the query logic and what is returned. And you won't make a future developer miserable who inherits your codebase and can't find some potentially deprecated or no longer needed PHP code.

# Answer
> 2 votes
One way of going about this is using Views PHP. Add your file path as a field and exclude it from display. Add a Global: PHP filter with `return file_exists($row->uri);` as your filter code. This should return TRUE for files that do exist, and will remove those from the results, showing only files in your database that do not exist. Your current filter criteria are only checking the file\_managed table in the database and are not going to be aware if the file exists.

---
Tags: views
---


title: Pathauto and forum paths

text:
# Question
Title: Pathauto and forum paths
I can generate urls to forum topics fine, but pathauto appears to be stubbornly refusing to generate urls for Forums and containers no matter what patterns I try to use.

I even tried to alias them in core alias - as suggested for Drupal 7 here \- but aside from the fact that the pages then returned 404 results I will probably have users adding forums in the future so really need to be in a position to generate them.

I want my forum urls to be of the form `/private/discussion/forum-name` and I would like to be able to have my container point to `/private/discussion` and see a list of the available forums there. Or at least alias the main forum output page.

# Answer
> 2 votes
I believe this is due to the issue reported here: https://www.drupal.org/project/drupal/issues/2010132. See the patch in comment #107 for a patch.

I've confirmed that the patch applies to the current Drupal 8.4 branch, the tests pass, and the aliases get generated as expected.

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


title: List(integer) from and to / Min and Max

text:
# Question
Title: List(integer) from and to / Min and Max
I have a field as a List(integer) which collects the users height.

```
0|4ft 4in - 132cm
1|4ft 5in - 134cm
2|4ft 6in - 137cm
3|4ft 7in - 139cm
4|4ft 8in - 142cm
5|4ft 9in - 144cm
6|4ft 10in - 147cm
7|4ft 11in - 149cm
etc....

```

But now I am looking to filter users with a from and to in views, which in principle should be simple, but the views option is not there. I would expect to see the normal "Is greater than or equal to" operators normally associated with an integer, but this is not the case with a list(integer).

Below is the screenshot for the operators of a normal integer:

How do I setup a From and To for height?
Either using the existing List(integer) field or by another means.

# Answer
> 0 votes
It looks like list fields use the "Many to One" views filter, not really sure what the reasoning is, maybe due to having labels the integer values were maybe assumed to not be useful for comparative purposes? I dunno.

Anyway, using the hook\_field\_views\_data\_alter() in a custom module, you could swap the filter ID used for your specific field. Example below, you'd need to replace "FIELDNAME\_value" with something like "field\_int\_list\_value" if your field name was "field\_int\_list"

```
use Drupal\field\FieldStorageConfigInterface;

/**
 * Implements hook_field_views_data_alter().
 */
function MYMODULE_field_views_data_alter(array &$data, FieldStorageConfigInterface $field_storage) {
  foreach ($data as $table_name => $table_data) {
    foreach ($table_data as $field_name => $field_data) {
      if (isset($field_data['filter']) && $field_name === 'FIELDNAME_value') {
        $data[$table_name][$field_name]['filter']['id'] = 'numeric';
      }
    }
  }
}

```

---
Tags: views
---


# Question
Title: Show items not linked by a view relationship
I have two content types: Item and Order.

There is a link from Order -\> Item through field\_items.

I have a view showing content of type Item and any related order data in a table. I have set up a non-required relationship to Content using field\_items to reference the Items.

I have a filter on the view to ensure that the content type on this relationship = Order. This is because I have another content type which is not shown on this view that uses field\_items.

The view functions largely as required. However, it only shows Items that are linked to an order via field\_items whereas I would also like it to show items for which this link doesn't yet exist.

I have tried adding a second condition for content type on the relationship is EMPTY and putting the two filters into a filter group with the OR operator. However, when I do this, nothing shows up in the view.

How do I get the view to show all Items (linked or not) with linked Order data where this exists?

# Answer
> 0 votes
This looks like the answer:

https://www.drupal.org/project/drupal/issues/2744777

There is a known bug in Drupal 8 whereby filter groups in views are not saved. The two filters (content type is empty and content type) Order are being AND-ed rather than OR-ed so therefore nothing is displayed as content type cannot both be empty and = Order.

The issue arises because I am using the same field to reference Items from both Order and from Batch, and using both links on the same view. Without any filters, the view displays the details of the first matched record for each Item. Where an Order exist, the order is chosen but where no order exists, the Batch will be displayed instead.

Until filter groups are working in D8, I've resolved this by creating a second entity reference field which I use to store the link from Order to Items. Now I have two fields (field\_items and field\_allocated\_items) as follows:

Batch -\> Items via field\_items Order -\> Items via field\_allocated\_items

Therefore, no filter is needed and the view displays as expected.

# Answer
> 0 votes
This looks like the answer:

https://www.drupal.org/project/drupal/issues/2744777

There is a known bug in Drupal 8 whereby filter groups in views are not saved. The two filters (content type is empty and content type) Order are being AND-ed rather than OR-ed so therefore nothing is displayed as content type cannot both be empty and = Order.

---
Tags: 8, views
---


# Question
Title: How can I use drupal_add_js() to include the following script?
How can I use `drupal_add_js()` to include the following script?

```
<script src="http://example.net/script.js" data-config="{'skin':'skins/black/skin.css','volume':50,'autoplay':true,'shuffle':true,'repeat':1,'placement':'bottom','showplaylist':false,'playlist':[{'title':'','url':'https://soundcloud.com/fosterthepeoplemusic/pumpedupkicks'}]}" ></script>

```

# Answer
I recently came across this issue and was able to work around the limitations of `drupal_add_js()` with the following hack:

```
//this can be any string of js that's already wrapped in <script> elements
$my_script = '<script ...[all the things]... ></script>';

drupal_add_js('</script>' . $my_script . '<script>', array(
  'type' => 'inline',
  'scope' => 'header', //or 'footer'
  //...any other options you want to add
));

```

You end up with two empty `<script>` elements in your markup, which I find annoying, but they don't actually do any harm.
> 1 votes

# Answer
You can do the same with drupal\_add\_html\_head like below:

```
$data_config = "{'skin':'skins/black/skin.css','volume':50,'autoplay':true,'shuffle':true,'repeat':1,'placement':'bottom','showplaylist':false,'playlist':[{'title':'','url':'https://soundcloud.com/fosterthepeoplemusic/pumpedupkicks'}]}";
$my_script = array(
    '#tag' => 'script',
    '#attributes' => array(
        'src' => 'http://example.net/script.js',
        'type' => 'text/javascript',
        'data-config' => $data_config,
    )
);
drupal_add_html_head($my_script, 'mymodule');

```
> 0 votes

# Answer
AdvAgg can do it as it supports the attributes key.

```
drupal_add_js("http://example.net/script.js", array(
  'attributes' => array(
    'data-config' => "{'skin':'skins/black/skin.css','volume':50,'autoplay':true,'shuffle':true,'repeat':1,'placement':'bottom','showplaylist':false,'playlist':[{'title':'','url':'https://soundcloud.com/fosterthepeoplemusic/pumpedupkicks'}]}",
  ),
));

```

If you want to target a specific location for the js, advagg also allows for this; on "admin/config/development/performance/advagg" check the "Allow for JS to be added to blocks and views" button at the bottom.

```
drupal_add_js("http://example.net/script.js", array(
  'scope' => 'page_top:prefix',
  'attributes' => array(
    'data-config' => "{'skin':'skins/black/skin.css','volume':50,'autoplay':true,'shuffle':true,'repeat':1,'placement':'bottom','showplaylist':false,'playlist':[{'title':'','url':'https://soundcloud.com/fosterthepeoplemusic/pumpedupkicks'}]}",
  ),
));

```

Set `$conf['theme_debug'] = TRUE;` in your settings.php file to see all possible scopes; simply look for `<!-- AdvAgg page_top:prefix tag -->` in the page source code and know the JS will land there.
> 0 votes

---
Tags: javascript
---


# Question
Title: Display entity reference field in a views block
I have two content types, "Contributor" and "Story".

Contributor has the following fields
1. Default title/label
2. Job title
3. Email address

Story has many fields, but includes an Entity Reference field that accepts multiple Contributor nodes.

When viewing a Story node webpage, I would like to have the "contributors" entity reference field to be displayed within the right sidebar using a views block. It should output all contributors that have been related to this Story node.

I have attempted to create a views block of Contributor nodes using Contextual Filters, but have not been able to output the contributors related to that story node. Are contextual filters the right method or should I have Relationships configured as well? If I have not set any contextual filters, all of the Contributor nodes are listed, but I can't seem to figure out which contextual filter and settings to use.

# Answer
Just coming from memory I would recommend something like this:

1. Create a view of what you want to show. (In your case, a view of content-type="contributors")
2. Create a relationship in that view to the content that contains the reference field. (Just click on add a relationship, and search for the name of your reference field)
3. Create a contextual filter to filter by ID. This filter will also be the reference field name. (choose "Provide default value" then "Content ID from URL") This contextual filter will use your relationship.
4. Restrict that Views block to only show on that content type (in block settings of course).

What you're doing is adding a relationship to that reference field. Then it is available as a contextual filter, where you can then provide a default value to filter by content ID.

Note: keep in mind if ever your reference field is not available as a relationship in your view, you may need to first add a content or node based relationship.
> 2 votes

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


title: Problem with taxonomy

text:
# Question
Title: Problem with taxonomy
I created a "Science" category, which shows up at the bottom of the add content page. But I also created a "History" category and that doesn't show up. Any ideas?

# Answer
> 1 votes
The best I can interpret your question:

A "category" in this context is typically a Taxonomy. If you see the "Science" category when creating a node, that would mean there is a "term reference" field added to that content type.

If you do not see the "History" taxonomy options when adding new content, I would assume there is no term reference field on that content type to this taxonomy.

Add a new "Term Reference" field to this content type. Ensuring it is associated with the "History" vocabulary. Then when creating a new node of this type, you should see this field.

If this field is added to this content type, then I would double check your "form display" settings on the content type to ensure this field is available.

---
Tags: taxonomy-terms
---


# Question
Title: How do I allow full HTML while rendering a view?
Some HTML code like `<iframe>` is stripped out. How can I allow full HTML in a view?

```
    $options = array(
        'id' => 'area_text_custom',
        'table' => 'views',
        'field' => 'area_text_custom',
        'relationship' => 'none',
        'group_type' => 'none',
        'admin_label' => '',
        'empty' => TRUE,
        'tokenize' => FALSE,
        'content' => "My HTML Code with <iframe ... >",
        'plugin_id' => 'text_custom',

    );
    $view->setHandler('page_1', 'footer', 'area_text_custom', $options);

```

# Answer
I've run into this same problem in the past, and I think your best option is to take care of this from a template.

Create an applicable template for your view (field, row, etc) and define your html in there. The template options/naming conventions aren't as clearly outlined in D8 as they were in D7, but here is the documentation page for Views templates. The comments have some helpful links and naming conventions for different types of templates depending on your needs.

Since it seems like you're trying to add your iFrame to the View's footer, you'd probably want to use the `views-view.html.twig` template. Naming conventions for this template are:

```
views-view--foobar--page.html.twig
views-view--page.html.twig
views-view--foobar.html.twig
views-view.html.twig

```

You'll want to copy `/your_site_root/core/modules/views/templates/views-view.html.twig` into the `templates` (or `templates/views`) folder of your theme. You'll then want to print your custom code inside the `<footer></footer>` tags of the template.

If you need more flexibility with what gets printed in the template, you can send variables into your template using `template_preprocess_views_view`.
> 1 votes

# Answer
I would suggest having your view display "content" of type "teaser" which would then allow you to use a twig template file such as node--content-type--teaser.html.twig.

This way you can add whatever markup you want to the twig file... even iFrames.

If you must have fields, for instance in exposed filters combine, remember you can "force" use fields in views :)
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to create a group page when creating a new group?
When I create a new group (using the Organic groups module), I want to use the Rules module to create a new group referenced page.

I can create a new page using the *Create new entity* action, but I haven't been able to set the group reference/audience. I've tried using both *Add entity to Group* and *Set a data value*, but I can't figure out how to set the parameters.

```
{ "rules_create_1st_story_page" : {
"LABEL" : "Create 1st Story Page",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "og" ],
"ON" : { "node_insert--story" : { "bundle" : "story" } },
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "story_page",
        "param_title" : "Page 1 - Start here",
        "param_author" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "og_group_content_add" : { "entity" : [ "node" ], "group" : [ "node" ] } }
] }}

```

# Answer
Have a look at the exported rule below, which is a variation of the (exported) rule in your question:

```
{ "rules_create_1st_group_page" : {
    "LABEL" : "Create 1st Group Page",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "group" : "group" } } } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "post",
            "param_title" : "Page 1 - Start here",
            "param_author" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "grouppage_created" : "Created GroupPage" } }
        }
      },
      { "list_add" : { "list" : [ "grouppage-created:og-group-ref" ], "item" : [ "node" ] } },
      { "entity_save" : { "data" : [ "grouppage-created" ], "immediate" : 1 } }
    ]
  }
}

```

Some more details about "my" variation, about the content types involved:

* "`Group`" is the content type I'm using for my OG groups.
* "`Post`" is the content type which has an *Entity reference* field with machine name `og_group_ref` (and widget = OG reference), so that I can assign nodes of content type "Post" to the appropriate field. Be aware however, this field allows for unlimited values (not sure if that's your case also).

Some more details about the actual rule:

* Rules Event: After saving new content.
* Rules Condition: Content is of type `Group`.
* Rules Actions:

+ **`Create a new entity`**, of type `Post` (note the `grouppage_created` variable name I've used, instead of just the default `entity_created` ...).
    + **`Add an item to a list`**, whereas the list is `grouppage-created:og-group-ref` (a multi value field, remember, so you cannot/should not use "set a data value, a common mistake when creating custom rules ...), and the item to be added is ... you probably guessed it: the node (of type `Group`), that just got saved.
    + **`Save entity`**, for the `grouppage_created` (not sure if this Rules Action is really needed, but IMO it's a kind of safe (best?) practise to be sure that this newly created `grouppage_created`-entity also gets saved).

And yes I actually tested this rule in my own environment ... Sure enough, in my case a new node (of type `Post`) got created, after I created a new `Group`.

Your turn to adapt your rule (with your content types), to make it similar to my rule here (assuming you also allow *multiple values* for your `og-group-ref` field. If yours is single value, then probably all you need to change is to replace the Rules Action **`Add an item to a list`** by an action to **`Set a data value`** (using similar variables).

PS: I'm assuming your question is about D7.
> 2 votes

---
Tags: nodes, rules, organic-groups
---


# Question
Title: Disable Internal Page Cache And Enable Dynamic Page Caching
Can some one let me know how to disable internal page cache and enable dynamic page cache. And also how to enable and configure varnish or memcache in drupal. Can we enable and use both varnish and memcache ? Does enabling of varnish or memcache will disable drupal's default dynamic page caching ?

# Answer
There are two different topics involved here.

1. You can disable the *Internal Page Cache* if you want to replace it with *Varnish* (both are reverse proxies for anonymous traffic, delivering content before the request reaches Drupal, and you don't need two of them).
2. *Memcached* on the other hand is a memory based cache backend, that sits behind Drupal caches (you can configure which ones, this can also be the *Internal Page Cache* if it is still enabled).

> Can we enable and use both varnish and memcache?

Yes, they work independently from each other, one in front and one behind of Drupal.

> Does enabling of varnish or memcache will disable drupal's default dynamic page caching?

No, it doesn't make a difference for the *Dynamic Page Cache*, because it won't see any traffic served by *Varnish* or the *Internal Page Cache* and *Memcached* only makes it faster, but doesn't change how it works.

> And also how to enable and configure varnish or memcache in drupal.

There are modules to configure them. For *Varnish* to make it invalidate cache tags and for *Memcached* to set up the cache backend.
> 2 votes

---
Tags: 8, caching
---


# Question
Title: How can i set different language for 2 different domain?
How can i set different language for 2 different domain? I have 2 different domain for single drupal installation
**www.example.en <br>www.example.fr**
i want to display 2 different language based on the user coming from any domain?

# Answer
> 0 votes
Keep configuring it all.

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


title: datetime field default gets truncated

text:
# Question
Title: datetime field default gets truncated
I have a datetime field on a custom entity defined in baseFieldDefinitions(). This has set a default, which should be now. But when saving the entity, i get following error:

> Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[22001\]: String data, right truncated: 1406 Data too long for column 'date' at row 1: INSERT INTO {sale} (uuid, langcode, user\_id, name, status, created, changed, date, price, party) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9); Array ( \[:db\_insert\_placeholder\_0\] =\> 3e25c5cb-0092-42dd-914b-4e4b91bdcf19 \[:db\_insert\_placeholder\_1\] =\> en \[:db\_insert\_placeholder\_2\] =\> 1 \[:db\_insert\_placeholder\_3\] =\> Jupiler \[:db\_insert\_placeholder\_4\] =\> 1 \[:db\_insert\_placeholder\_5\] =\> 1516504047 \[:db\_insert\_placeholder\_6\] =\> 1516504047 \[:db\_insert\_placeholder\_7\] =\> 2018-01-21 04:07:06 Europe/Brussels \[:db\_insert\_placeholder\_8\] =\> 2 \[:db\_insert\_placeholder\_9\] =\> 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>doSaveFieldItems() (line 878 of /var/www/drupalvm/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

This is my field definition:

```
$fields['date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Sale date'))
  ->setDescription(t('The date that the sale took place.'))
  ->setRequired(true)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'date',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setDefaultValue(DrupalDateTime::createFromTimestamp(time()));

```

How are datetime fields supposed to get a default value? If you look at the error, the value it tries to save is '2018-01-21 04:07:06 Europe/Brussels'.

# Answer
As the BaseFieldDefenitions are cached, this won't work I believe.

I think you would be better off by using SetDefaultValueCallback:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21BaseFieldDefinition.php/function/BaseFieldDefinition%3A%3AsetDefaultValueCallback/8.2.x
> 1 votes

---
Tags: 8
---


title: Compare views field to String

text:
# Question
Title: Compare views field to String
I have the following code in the views-view-fields--\[VIEW NAME\].html.twig template:

```
{% if fields.field_category.content == "Compare to this String" %}
    Conditional content here.
{% endif %}

```

This "category" field is an entity reference (Taxonomy) being output as plain text. If I replace the field in the code with the same string on the right side of the comparison operator, the conditional content is output correctly. When I try to compare this field to the string on the right side, Drupal outputs "The website encountered an unexpected error. Please try again later.".

What is the correct way to compare a views field with a String value using Twig and Drupal?

# Answer
> 0 votes
You can't compare rendered output to a string. In conditions use database values, which you get from the row entity:

```
row._entity.field_name.value

```

For a reference field get the referenced entity and the label, if you want to compare the name of the taxonomy term:

```
row._entity.field_category.entity.label

```

---
Tags: theming
---


# Question
Title: How to run custom .php file after click run cron button?
I have create one custom\_cron.php file in root director. But I want to run file after click on Run cron button from admin site.

# Answer
> 0 votes
What you'd need to do is use hook\_cron() https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_cron/7.x

And then use wget or curl or something similar to call your file directly. But that seems quite pointless and you might as will move all the php code from your custom file and put it in your hook\_cron() function

Alternatively you could use crontab on linux to set your own regular cron run to your file. But by dooing "run cron" from within drupal would have no effect for you file

---
Tags: 7, cron
---


# Question
Title: How to use node field tokens as a value in Metatags module?
I am trying to optimise SEO on my site by ensuring that each page has a unique value for descriptive metatags.

I am trying to achieve this using the Token and Metatags modules, and am using Drupal 8.

To do this, I have added a field called "Description" to both the basic page and article content types.

I would then like to use the \[node:field\_description\] token as the value for any relevant metatags in the Metatags module.

However, when I view available tokens in the Metatags module the \[node\] token is not available and the \[current-page\] token doesn't appear to have any way to reference the main node displayed within that page.

I know this issue has been discussed extensively for D7 and this issue appears to provide what I'm looking for:

https://www.drupal.org/project/token/issues/919760

Is there an equivalent solution for D8? Alternatively, what's the best way of achieving this?

# Answer
> -1 votes
This from Mario Steinitz (in comments) answered the question:

"I'm not at my desk anymore for today, but I'm pretty sure you have the \[node\] token available for content meta tags and can access field content as well. We're using these tokens regularly for all D8 sites we're working on. Where did you try to add them?"

---
Tags: 8, tokens, meta-tags
---


title: How to tell if a site is using Drupal 7

text:
# Question
Title: How to tell if a site is using Drupal 7
I know how to check if a site is built with Drupal, but is there a way to tell if a site is built with Drupal 7?

# Answer
> 20 votes
Some obvious giveaways to the site being drupal 7:

* RDF in the `<head>` section in the HTML
* Meta tag of `<meta name="Generator" content="Drupal 7 (http://drupal.org)" />`
* Executing `jQuery.fn.jquery;` reveals the jQuery version to be 1.4.4 or 1.5.2 (with jQuery update)
* Only a single `<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />` \- this is a famous drupal 6 bug (it has two in the `<head>` section
* HTTP response header of `X-Generator: Drupal 7 (http://drupal.org)`

Other options include using 'sniffers', my favourite being 'Whatweb' - https://github.com/urbanadventurer/WhatWeb. Whatweb is a (ruby) command line tool that can sniff not only the fact that the site is using drupal, but often the major and minor version as well

# Answer
> 6 votes
Unless someone has taken it out, you could look for the tag below

```
<meta name="generator" content="Drupal 7 (http://drupal.org)" />

```

Syntactically though, I just too a look for a way to be sure and can't really see anything. Jquery now requires being wrapped

```
(function ($) {

})(jQuery);

```

but some older Drupal sites may also do things that way if they had been customised.

I think the answer is that you can't be 100% sure.

# Answer
> 6 votes
One quick way is to try hitting the http://example.com/CHANGELOG.txt URL, to see what the changelog reports as the version being used. For example, this happens to be true for Drupal.org: http://drupal.org/CHANGELOG.txt.

# Answer
> 6 votes
You could also check the HTTP headers (in Drupal 7) for something like "X-Generator Drupal 7." This is a link to a page explaining how to remove that, if anyone would be interested: http://drupal.org/node/982034.

# Answer
> 4 votes
Another way is to look a the Javascript `Drupal.behaviors` object. In Drupal 6, init functions are attached like

```
Drupal.behaviors.foo = function () {
  // ...
}

```

In Drupal 7, it is like

```
Drupal.behaviors.foo = {
  attach: function () {
    // ...
  }
}

```

# Answer
> 2 votes
You could look what css files are loaded. On first glance, Drupal 6 loads modules/system/system.css while Drupal 7 loads modules/system/system.base.css.

# Answer
> 2 votes
Someone in IRC suggested to look at the jQuery version: if it's 1.3.2, you can be pretty sure it's a Drupal 6 site. That said, this method is not infallible either.

# Answer
> 2 votes
I usually look at the massive "blurp" of javascript in the header in the `jQuery.extend(Drupal.settings,...`
A typical Drupal 6 has a very small string there while every Drupal 7 have a massive one.

# Answer
> 2 votes
A Plugin for firefox, named "Wappalyzer", tells you what CMS a site is using. In my opinion the plugin works really good. According to this post on drupal.org there exists a similar plugin for Chrome as well, named chrome sniffer

# Answer
> 0 votes
I am always use Wappalyzer to detect the technology of website,The `Wappalyzer` website also is based on Drupal 7.

> Wappalyzer is a browser extension that uncovers the technologies used on websites. It detects content management systems, eCommerce platforms, web servers, JavaScript frameworks, analytics tools and many more.

# Answer
> 0 votes
You can find the version information at `CHANGELOG.txt` file in Drupal folder.

All you need to do is display this file.

---
Tags: 7
---


# Question
Title: How to send a Group email based on date field using Rules?
I'm using the Group module and I have a Group content type called Events with a date field. I am having trouble figuring out how use Rules to send an Email on the same day as the date field to all the members of the Group.

I've tried creating a rule but it's just wrong:

* Event: runs on cron
* Condition: group content, datefield equals, is node type Event
* Action: get group members from group audience, loop group members, send email

Most of what keeps showing up in my searches to answer my question, are not for Group content.

Any help?

# Answer
This is typically something you can get to work using the Rules module, together with `Rules Scheduler` (a sub-module of it), as explained in the steps below.

### Step 1: Enable the Rules Scheduler

Enable the `Rules Scheduler` (a sub-module of Rules). And make sure your cron jobs are running (to ensure that scheduled rules actually start executing.

### Step 2: Create a Rules "Component"

Create a Rules Component labeled something like **Notify all members of a Group**, which looks like so (in Rules export format):

```
{ "rules_notify_all_members_of_a_group" : {
    "LABEL" : "Notify all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "group" : { "label" : "Group", "type" : "group" },
      "event_node" : { "label" : "Event node", "type" : "node" }
    },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail Id \u0022[member-of-group:user:mail]\u0022 is a member of the \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and group id \u0022[group:gid]\u0022, related to the node with id [event-node:nid] and title [event-node:title] (and date [event-node:field-expiration-date])." } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail as a friendly reminder related to the node with id [event-node:nid] and title [event-node:title] (and date [event-node:field-expiration-date]).\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

Some more details about this Rules Component:

* The type of this Rules Component is an "Action Set" (no need for any conditions).
* ***Action 1*** is to build a list of all the members of the group. It uses "Fetch entity by property", with these additional specs:
    + Entity type value = Group Membership.
    + Property value = Group.
    + Value of the data selector = Group.
    + Limit result count = blank (we do not want to limit the nr of results).
    + Provided variables = "Group members" (variable label) and "`group_members`" (variable name).
* ***Action 2*** is to iterate (= loop) over each of the members of the group. It uses "Add a (Rules) loop", with these additional specs:
    + The list to loop over = `group-members`
    + Current list item = "Member of group" (variable label) and "`member_of_group`" (variable name).
    + Sub-action (i) of this Action 2 is to just "Show a message on the site" (while QA-testing this Rules Component), with message type = Status and with an appropriate message using various tokens which might be interesting.
    + Sub-action (ii) of this Action 2 is to actually send an eMail to the "`member_of_group`" being processed in the loop, using various tokens similar to those in Sub-action (i).

If you have the Rules UI enabled , as well as the Group module, you can simply import the above rule in your own site, no need to tweak anything in it. Though you may want to tune the Subject and Message content of the actual eMail (just remember the various tokens you may want to use), while you might also want to use some other ***From*** eMail ID. And after QA-testing it, you probably want to remove the Rules Action "Show a message on the site".

### Step 3: Create a "Rule" using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste):

```
{ "rules_schedule_group_notification" : {
    "LABEL" : "Schedule Group notification",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_event_date" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_notify_all_members_of_a_group",
          "task" : "[node:nid]"
        }
      },
      { "schedule" : {
          "component" : "rules_notify_all_members_of_a_group",
          "date" : [ "node:field-event-date" ],
          "identifier" : "[node:nid]",
          "param_group" : [ "node:group" ],
          "param_event_node" : [ "node" ]
        }
      }
    ]
  }
}

```

The above rule refers to the *Rules Component* from the previous step. And is based on these assumptions:

* The content type of the event node is has machine name `article` (adapt prior to import to fit your case).
* The field "Event date" has machine name `field_event_date` (adapt prior to import to fit your case).

The `schedule_delete` that is part of this rule is to ensure that previously "scheduled" notifications will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recently entered date).

**Attention**: whatever gets updated in such node, will each time trigger this rule. Even if the actual date itself is not updated. If that's not what you want, just add additional Rules Conditions so that the rules Actions are only performed if the date is updated.

PS: I'm assuming this question is about D7.
> 0 votes

---
Tags: rules, emails
---


# Question
Title: In webforms, how do I send the current user an email automatically?
I'm trying to send an email to the logged in user who filled out the form without having them enter their email.

The form is made with webforms 8.x-5.x which has a lot of functionality.

I've only tried doing it non-programmatically through the interface by adding an email and using the "custom to email address" where i attempted to use the token: \[current-user:mail\] which did not work.

I've made a separate email handler for anonymous users, which just uses the email they fill in.

# Answer
> 2 votes
As @huelfe recommended, the token \[webform-authenticated-user:mail\] actually works for this purpose in the custom to email address.

---
Tags: 8, webforms, tokens
---


# Question
Title: How can I import fields into Drupal 8.4 user profile from a csv file that has identical values in the key row?
I'm using Migrate Tools, Migrate Plus and Migrate Source CSV. My CSV file looks like that:

```
"Stg";"Color";"Fruit"
"user1";"red";"apple"
"user1";"blue";"pear"
"user2";"green";"banana"
"user2";"black";"rotten banana"

```

I'm using the Profile Module (https://www.drupal.org/project/profile)

I have a migration within my migration group that looks like this (migrate\_plus.migration.user\_vorlesungen.yml):

```
id: user_vorlesungen
langcode: de
status: true
dependencies:
    enforced:
        module:
            - user_migrate
migration_group: hoevwa
label: 'HoeVWA Vorlesungen Import'
source:
    plugin: csv
    track_changes: true
    path: /config/Vorlesungsverzeichnis.csv
    # Column delimiter. Comma (,) by default.
    delimiter: ';'
    # Field enclosure. Double quotation marks (") by default.
    enclosure: '"'
    header_row_count: 1
    keys:
        - Stg
destination:
    plugin: entity:profile
process:
    type:
        plugin: default_value
        default_value: 'vorlesungen'
    uid:
        plugin: migration_lookup
        no_stub: true
        # previous user migration
        migration: user__hoerer
        # property in the source data
        source: Stg
    # These field have multiple values in D8
    field_color: Color
    field_fruit: Fruit

migration_dependencies:
    required: {  }
    optional: {  }

```

In my YAML file the content is printed like that:

```
...
<table>
  <tr>
    <td>{{ content.field_color }}</td>
    <td>{{ content.field_fruit }}</td>
  </tr>
</table>
...

```

When I run drush mim --group=hoevwa only the last values of user1 (blue, pear) are imported. How can I get running a process plugin to loop through the CSV and get all values imported. And finally how can I loop through all values in my TWIG Template?

# Answer
The solution will be to create a custom Migration Source Plugin and do some magic in the `fetchNextRow()` method. Depending on the source of your data, you might also use some other approach.
> 0 votes

---
Tags: migrations
---


# Question
Title: 8.4.4 CKEditor Link & Unlink Buttons suddenly missing
In Drupal 8.4.4 the CKEditor is suddenly missing the Link and Unlink buttons for all content types, for the Basic Editor and the Full HTML Editor as well. My users and I can no longer add links to anything, and if I edit articles any link html disappears in the editor altogether (I noticed the issue after editing and saving an article and then noticing the links that were there moments before were suddenly gone).

I went to admin/config/content/formats to configure the editors to add the buttons back, but when I click the Configure button for Basic HTML I get the dreaded "The website encountered an unexpected error. Please try again later." message. Drupal error log shows the following:

> TypeError: Argument 1 passed to Drupal\Core\Render\Element::children() must be of the type array, null given, called in /core/modules/ckeditor/src/Plugin/Editor/CKEditor.php on line 177 in Drupal\Core\Render\Element::children() (line 71 of core/lib/Drupal/Core/Render/Element.php).
>
> Drupal\Core\Render\Element::children(NULL) (Line: 177) Drupal\ckeditor\Plugin\Editor\CKEditor-\>settingsForm(Array, Object, Object) (Line: 64) Drupal\editor\Plugin\EditorBase-\>buildConfigurationForm(Array, Object) (Line: 175) editor\_form\_filter\_format\_form\_alter(Array, Object, 'filter\_format\_edit\_form') (Line: 501) Drupal\Core\Extension\ModuleHandler-\>alter('form', Array, Object, 'filter\_format\_edit\_form') (Line: 830) Drupal\Core\Form\FormBuilder-\>prepareForm('filter\_format\_edit\_form', Array, Object) (Line: 272) Drupal\Core\Form\FormBuilder-\>buildForm('filter\_format\_edit\_form', Object) (Line: 74) Drupal\Core\Controller\FormController-\>getContentResult(Object, Object) call\_user\_func\_array(Array, Array) (Line: 123) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() (Line: 582) Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 124) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) (Line: 97) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() call\_user\_func\_array(Object, Array) (Line: 153) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 68) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 99) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 50) Drupal\ban\BanMiddleware-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 50) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 657) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

I don't know if this is related to recently updating Drupal to 8.4.4, but I was not encountering this issue before as I've made many articles in the past month with links that still work. I have no idea how to debug or fix this issue, or if it's a known bug, please any help is appreciated.

# Answer
I figured out the issue. Apparently something changed in the Drupal 8.4.4 update that caused the scripts related to the link/unlink buttons to work longer than usual, which was causing a PHP timeout exception (when checking the browser console it gave an HTTP Result Code: 200 error, which apparently happens regularly with Drupal). So in my settings.php file I increased the timeout by adding the line:

ini\_set('MAX\_EXECUTION\_TIME', 7200);

You can also configure this in your host settings.
> 0 votes

---
Tags: wysiwyg
---


title: How can I create internal links?

text:
# Question
Title: How can I create internal links?
Can someone please explain how site internal links work in Drupal? What is the most reliable way to display a link so that it goes to the same location every time?

I'm working on a preliminary website and right now, the only reliable way I can get a link to work the same way on all pages is to use absolute links (starting with `http://`and including the domain name for the host) for each link. Since this website is currently local, this is not practical because I'll need to change all the links in the website when it goes live.

Eventually, I'd like to put these links in a menu I've got displayed at the top of all pages in my site.

# Answer
In HTTP, links starting with `http://` and including a domain name (e.g. `http://example.com/foo/bar`) is known as *absolute* paths. On a Drupal site, they should only be used for off-site links. Links not starting with `http://` (e.g. `/foo/bar`) is known as *relative* paths. Relative paths should be used for *internal* links on your site. When a relative path starts with a slash (`/`) it is relative to the Drupal *site root*. When it does not, it is relative to the location where it is embedded.

By making sure all internal links are specified using relative paths, they will not have to be changed when you move your site from one server to another.

For example, to link to `/node/42`, (provided you've clean URLs enabled) you can use the following markup:

```
 <a href="/node/42">Link to node 42</a>

```

(For menu items, as described bellow, you should omit the initial `/`, as menu items are always relative to the Drupal root.)

> Eventually, I'd like to put these links in a menu I've got displayed at the top of all pages in my site.

Support for this use case is already in place in Drupal.

Navigate to: *Administration » Structure » Menus* and click on the link "List links" for the *Main menu*. Then click on *Add link*. In the field "Path" type in the *relative path* to the location (e.g. node path) in your site you want this menu item to point. Also provide meaningful "Menu link title" and "Description" strings. End by clicking *Save*. Now the link will appear in your main menu, which in most (including the default "Bartik") themes are displayed at the top of all pages on the site.
> 2 votes

# Answer
# Drupal 6 (obsoleted)

Path Filter rewrote *internal:node/123* links to e.g. http://example.com/en/content/my-node-alias

# Drupal 7

Pathologic offers the same feature (though only minimally documented)

# Drupal 8

Pathologic is currently (2018-01) not yet usable.

Internally drupal has uri schemes like *base:robots.txt*, *entity:node/1*, *route:myroute/arg1/arg2* that you can use in e.g. menu links. But there seem not to be a text filter that leverages these.
> 1 votes

# Answer
If you're still fairly new to Drupal and haven't seen it yet, you might want to add in ckeditor and ckeditor\_link modules. This will provide your users with an easy way of adding internal links within your site without having to worry about paths and links with any markup.
> 0 votes

---
Tags: navigation, files
---


# Question
Title: Services PATCH multiple target_id values for entity (node)
I'm trying to pass multiple nids to my node to match this structure:

```
[field_sac_testts] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [target_id] => 168
                            )

                        [1] => Array
                            (
                                [target_id] => 175
                            )

                    )

            )

```

I've tried this:

{"\_links":{"type": {"href":"http://mywebsite.com/rest/type/node/subject"}},"type":\[{"target\_id":"subject"}\],"field\_sac\_testts":\[{"0": {"target\_id":"702}},{"1": {"target\_id":"729"}}\]}

And a bunch of other combinations and I can't seem to get it to PATCH successfully. I keep getting a syntax error.

If anyone could help that would be great. Thanks.

# Answer
OK. So figured it out. If you have an unlimited number of entry field for a entity type field (e.g. a node) on a content type you'll need to format the target\_id with the nids like this for Drupal 8:

"field\_sac\_testts":\[{"target\_id":"830"},{"target\_id":"837"}\]
> 0 votes

---
Tags: services
---


# Question
Title: Add trailing slash to taxonomy term. Issue with relative URL
We were trying to create relative links by using href="Link" or href="./Link"

This works on all browsers, but in Drupal we are running into a problem becasue Drupal removes trailing slash from existing URL.

For example if we are at page or taxonomy term page

domain.com/term1/child1A

and in there have a link such as a href="Link" it will point to domain.com/term1/Link

becasue child1A does not have a trailing slash.

Is there any way to fix this issue. Technically we are not trying to add trailing slashes to all url. Tried setting base URL but that didn't work either. Or maybe I did something wrong.

Any suggestions on a workaround?

Drupal 8.4

# Answer
> 0 votes
The key to this answere is that the URL needs to end with a slash.

I turns out Redirect modules will remove trailing slashes.

You can disable clean URLs if you want trailing slash. Which is not ideal.

A workaround would be to use this code for particular links:

```
<p><a href="home" id="relurl" target="_blank" title="This is a relative link!">link</a>

```

var x = window.location.href; // Current page URL var link = document.getElementById("relurl"); // store the element var curHref = link.getAttribute('href'); // Get HREF paramter link.setAttribute('href', x + "/"+ curHref);

---
Tags: views, uri, taxonomy-terms
---


# Question
Title: Migrating Only DRUPAL7 DATABASE from Microsoft SQL to MYSQL
I have Drupal7 site which is running on Microsoft database,

My current requirement is to migrate from microsoft database to mysql database.

if we can migrate will there be no breakage in the present working site,

Any help on this?

# Answer
A possible approach for this is to use the Drupal-to-Drupal data migration module (aka "migrate\_d2d") for this. Quote from its project page:

> ... provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed.
> 1 votes

---
Tags: database
---


# Question
Title: After installing Drush on Mac it only downloads drupal 6x
I am having issues installing Drush on Mac OSX 10.9.5. I have tried a variety of methods. The most successful have been;

Using homebrew

Drush 7 using composer

Each method had produced a version of Drush, however each appears old and `drush dl drupal` downloads the 6.x version, as does `drush dl drupal 7.x`.

Can you please suggest:

1) How to ensure old versions of drush are removed to ensure that a new installation goes smoothly.

2) The recommended method for installing the latest stable Drush version on Mac OSX 10.9.5

I had tried to delete the old drush version manually by removing folders. Now the composer installation method seems to fail as I get:

```
Pauls-iMac:~ Trotter$ composer global require drush/drush:dev-master
Changed current directory to /Users/Trotter/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing drush/drush (dev-master 78b1538)
    Cloning 78b15385ba97890dc3431790494f26d6be99ede9
    Failed to download drush/drush from source: The process "git clone --no-checkout 'git://github.com/drush-ops/drush.git' '/Users/Trotter/.composer/vendor/drush/drush' && cd '/Users/Trotter/.composer/vendor/drush/drush' && git remote add composer 'git://github.com/drush-ops/drush.git' && git fetch composer" exceeded the timeout of 300 seconds.
    Now trying to download from dist
  - Installing drush/drush (dev-master 78b1538)
    Loading from cache

    Skipped installation of bin drush for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.php for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.bat for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.complete.sh for package drush/drush: name conflicts with an existing file

```

I can see that I don't have drush installed as `what drush` gives `No such file or directory` and `drush info` gives `-bash: drush: command not found`

# Answer
Drush 7.x doesn't only download Drupal 7 of course. Drush 5 will download Drupal 7 too. Drush 7 is required for Drupal 8 and needs to be selected when installing with `composer global require drush/drush:dev-master`. Ps the recommended method is the composer method. This what I use on OS X 10.9.

Find old versions of drush with `which drush`. Check where they live with`ls -l [path from which drush]`. Rinse and repeat until the only one left is in your home folder inside the hidden composer directory.

Check the version of the installed drush with `drush --version`

Make sure you don't have a `.drushrc` somewhere with a default core version specified.
> 1 votes

# Answer
> Skipped installation of bin `drush` for package `drush/drush`: name conflicts with an existing file

Make sure to `unset COMPOSER_BIN_DIR` shell variable before running Composer command as it may conflict with `bin-dir` defined in your `composer.json` file. To check your current value of `bin-dir`, run `composer config bin-dir` (where your Drush may be present).
> 0 votes

---
Tags: drush
---


title: Freshly installed Drush is unresponsive

text:
# Question
Title: Freshly installed Drush is unresponsive
I'm on an Amazon Linux machine.

I ran:

```
$ composer global require drush/drush
Changed current directory to /home/ec2-user/.composer
Using version ^8.1 for drush/drush
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files

```

Then I added composer into the PATH so it reads like this:

```
$ echo $PATH
/home/ec2-user/.composer/vendor/bin:/home/ec2-user/.composer/vendor/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/aws/bin:/home/ec2-user/.local/bin:/home/ec2-user/bin

```

Then if I try this I get an error:

```
$ composer show drush/drush

  [InvalidArgumentException]
  Package drush/drush not found

show [--all] [-i|--installed] [-p|--platform] [-a|--available] [-s|--self] [-N|--name-only] [-P|--path] [-t|--tree] [-l|--latest] [-o|--outdated] [-D|--direct] [--] [<package>] [<version>]

```

And if I run the drush command the cursor stays there waiting:

```
$ drush

```

What did I miss?

# Answer
So after a little investigation I realised I had a folder called drush in my home directory as well as something added by composed inside my home directory/.composer/vendor/bin/. I deleted these drush directories and ran composer again after which drush works fine.

```
[ec2-user@ip-... ~]$ ls
composer.json  drush  vendor
[ec2-user@ip-... ~]$ sudo rm drush
[ec2-user@ip-... ~]$ cd .composer/
[ec2-user@ip-... .composer]$ ls
cache  composer.json  composer.lock  vendor
[ec2-user@ip-... .composer]$ cd vendor/
[ec2-user@ip-... vendor]$ ls
autoload.php  composer  drush          nikic  psr  symfony
bin           dnoegel   jakub-onderka  pear   psy
[ec2-user@ip-... vendor]$ ls -la
total 52
drwxrwxr-x 12 ec2-user ec2-user 4096 May 12 07:25 .
drwxrwxr-x  4 ec2-user ec2-user 4096 May 11 20:59 ..
-rw-rw-r--  1 ec2-user ec2-user  183 May 12 07:25 autoload.php
drwxrwxr-x  2 ec2-user ec2-user 4096 May 11 20:59 bin
drwxrwxr-x  2 ec2-user ec2-user 4096 May 11 20:59 composer
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 dnoegel
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 drush
drwxrwxr-x  4 ec2-user ec2-user 4096 May 11 20:59 jakub-onderka
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 nikic
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:58 pear
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 psr
drwxrwxr-x  3 ec2-user ec2-user 4096 May 11 20:59 psy
drwxrwxr-x  6 ec2-user ec2-user 4096 May 11 20:59 symfony
[ec2-user@ip-... vendor]$ sudo rm -rf drush
[ec2-user@ip-... vendor]$ cd ../
[ec2-user@ip-... .composer]$ cd ../
[ec2-user@ip-... ~]$ composer global require drush/drush
Changed current directory to /home/ec2-user/.composer
Using version ^8.1 for drush/drush
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing drush/drush (8.1.2)
    Loading from cache

    Skipped installation of bin drush for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.launcher for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.php for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.bat for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.complete.sh for package drush/drush: name conflicts with an existing file
drush/drush suggests installing drush/config-extra (Provides configuration workflow commands, such as config-merge.)
Generating autoload files
[ec2-user@ip-... ~]$ drush
Execute a drush command. Run `drush help [command]` to view command-specific help.  Run
`drush topic` to read even more documentation. ......rest of output ommited

```
> 1 votes

# Answer
Dunno if this helps but in my **.bashrc** I had to have

```
export PATH="$PATH:/root/.cache/composer/files/drush/drush"

```

Otherwise no workie at all. Running on opensuse

```
export PATH="~/.composer/vendor/bin:$PATH"

#(assuming you run Drush under that root user account), or
export PATH="/Users/<username>/.composer/vendor/bin:$PATH".

```

Make sure you source **~/.bash\_profile** or **.bashrc** after making changes unless you start a new terminal session.
> 0 votes

# Answer
> Skipped installation of bin drush for package drush/drush: name conflicts with an existing file

If Drush is not installed due to name conflicts, please check the value of your `bin-dir` by running `composer config bin-dir` command where your Drush may be present.

If you expect different location, make sure to `unset COMPOSER_BIN_DIR` shell variable before running Composer command as it may conflict with `bin-dir` defined in your `composer.json` file.
> 0 votes

---
Tags: drush, composer
---


# Question
Title: How do I manage a mix of menu and custom breadcrumbs?
I have a site where I need breadcrumbs to be generated in a couple of different ways:

* Based on the menu path (Menu Breadcrumb)
* Based on custom rules (was thinking Custom Breadcrumb but it doesnt exist anymore)

How can I effectively enable breadcrumb rules for nodes that I *don't* want Menu Breadcrumb to control? Do I have to create my own Breadcrumb builder class? Can I blow away `$breadcrumb` in `hook_system_breadcrumb_alter` and do `new Breadcrumb()` to do exactly what I want?

# Answer
> 3 votes
> Do I have to create my own Breadcrumb builder class?

Yes, there are many places where you can modify breadcrumbs, but this is the only straightforward way. The custom breadcrumbs should have a priority higher than 1010 (the priority of the breadcrumb builder of Menu Breadcrumbs), so that nodes that follow rules you put in `applies()` of the BreadCrumbBuilder class can't be controlled by Menu Breadcrumbs.

> How do I set the priority (asked in the comments)?

The priority is set in the service definition, example from the Menu Breadcrumb module:

*menu\_breadcrumb.services.yml:*

```
services:
  menu_breadcrumb.breadcrumb.default:
    class: Drupal\menu_breadcrumb\MenuBasedBreadcrumbBuilder
    arguments: ['@config.factory', '@menu.active_trail', '@plugin.manager.menu.link', '@router.admin_context', '@title_resolver', '@request_stack', '@language_manager', '@entity_type.manager']
    tags:
      # The priority must be higher than core taxonomy builder (priority: 1002)
      # see https://www.drupal.org/node/1495510
      - { name: breadcrumb_builder, priority: 1010 }

```

(which is also where you have to look when you want to override an existing breadcrumb builder, you can see here what was considered concerning the taxonomy breadcrumbs)

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


# Question
Title: How to implement a button with different redirections?
I'm setting up a job directory using Drupal 8, together with a team. It is possible to see it here.

As you can see below, in a screenshot of the site, there's a button called "Add new job":

In a more visual way, this is what I would like to implement:

1. If the user doesn't have login:

* User clicks button
    * User goes to create account
2. Else:

* User clicks button
    * User goes to a specific / different page / view

Something is triggering me that we can achieve this like that using Rules, setting on action events, but I'm not sure how.

It can be that I am totally wrong and there's a more straightforward way to do this.

For example, if I was to implement this just with PHP, would redirect a button to one page and in that page, using user sessions sessions and if conditions, would define the content showing up.

I'm not an expert in Drupal neither I'm aware of all of its possibilities. So, any help is appreciated.

# Answer
I've noticed when the user is logged in, the template adds a class called `user-logged-in` in the body.

So, in the custom block of the button "Add New Job", added a script to validate if the class is found within the document an, when clicking the button, redirect to different places whether it exist or not.

The script is the following:

```
<script type"text/javascript">

function checkPage () {

    if (jQuery('.user-logged-in').length > 0) {

         window.location.replace("https://www.google.pt");

    } else {

          window.location.replace("/user/register");

    }

}

</script>

```

The complete custom block code is:

```
<style type="text/css">.button {
    background-color: #56739B;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
</style>
<script type"text/javascript">
function checkPage () {
if (jQuery('.user-logged-in').length > 0) {
    window.location.replace("https://www.google.pt");
} else {
    window.location.replace("/user/register");
}
}

</script>
<p><button class="button" href="#" onclick="checkPage()">Add a New Job</button></p>

```
> 1 votes

# Answer
Point the button to a custom controller:

```
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class ExampleController extends ControllerBase {

  /**
   * Controller for action button.
   */
  public function action() {

    // if user is not logged in, redirect to create a new account
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect('user.register');
    }

    // else return content or redirect to content
    return ...;
  }

}

```
> 1 votes

# Answer
My approach would be to follow the way that Drupal handles login versus logout: to have two links, one for logged-in users and one for anonymous users.

If the permissions on the two routes are correct, then only one will be visible at a time. Both can look exactly the same, but the destination will differ depending on whether the user is logged in or not.

You can create these as custom menu items, or by any other mechanism where Drupal checks access to the route (so eg. using twig route functions https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates, but not hard-coding links).
> 1 votes

---
Tags: 8, rules, redirection, sessions
---


# Question
Title: How to show more terms in the "Parent terms" select list when adding taxonomy term?
When adding terms to a taxonomy vocabulary, the "Parent terms" scrolling selector list in the "RELATIONS" section only displays 4 items. When dealing with large, complex, hierarchical taxonomies, this makes it difficult and slow to find the parent (a similar complaint and another).

I would love to be able to use something like the Simple hierarchical select or Client-side hierarchical select widget there, but assuming that's not currently possible, how can I simply display a longer list to make the selection a bit easier?

I am guessing there is a file somewhere containing a setting of "4" (unless that's a default) that I would able to increase to "20" for example. I hunted but couldn't find it.

I'd be interested in an answer, even if it would be a core hack that I would have to redo with each update.

Edit: It seems, from this link, that one solution may involve adding code such as this:

```
<?php
function MyModuleName_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $form['relations']['parent']['#size'] = '20';
  }
}

```

But where to add it? Or perhaps in a custom module (called MyModuleName)? Perhaps in MyTheme.theme? Or perhaps in a twig file such as html--admin--structure--taxonomy--manage--MyVocabularyName--add.html.twig?

# Answer
> 2 votes
OK Nick, you need to add the 'hook' into a custom module.. so for drupal 8 if you do not have a custom module follow the documentation here https://www.drupal8.ovh/.../create-a-simple-module-for... https://www.drupal8.ovh/.../create-a-simple-module-to-use...

In 'modules' folder create a custom folder 'custom' to hold your custom modules. path should be ...modules/custom inside this create a folder folder to hold your custom module my\_custom\_module ( orwhatever you want to call it ) path should be ...modules/custom/my\_custom\_module

inside this folder (my\_custom\_module) add a 'my\_custom\_module.info.yml' file in this file add

```
name: My custom module
description: My custom module description
package: Custom

type: module
core: 8.x

```

run drush en my\_custom\_module -y or in admin/modules enable the module

once enabled add a .module file to the my\_custom\_module folder, called my\_custom\_module.module (or whatever you have called it)

in this file you can add the hooks you want to use for your one it will be

```
<?php
function my_custom_module_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'taxonomy_term_vocabulary_name_form') {
$form['relations']['parent']['#size'] = '15';
}
}

```

change the my\_custom\_module to whatever you have called your module change the section of the form id == vocabulary name to the name of the vocab you have created, you may need to inspect this and find it the form id! mine matched the vocab

clear the cache, go to your vocabulary and add a new term ! fingers crossed the size of the selct box has changed

think this covers it all, good luck

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


# Question
Title: Display Auto Generated Youtube Thumbnails with 'Video Embed Field' Module in Views
I added some videos to my site and I'm using views to display them. I followed a tutorial and i used the **rewrite the output** option of the view with allowed **replacement patterns** to display videos in lightbox in this way.

```
<a href="[field_video-video-url]" rel="lightvideo"><img src="[field_vthumb]"
height="120" width="180"></a>

```

Here when i clicked on the a image, the video will played in the lightbox and that was great. In the above link added a custom the image field as thumbnail but that doesn't work well, because when i add more than one video all will have the same thumbnail.

But then i also came to know, that the **Video Embed Module** when used to add videos, auto generates the thumbails of the added youtube videos in a public directory. So again i worked on the replacement patterns and got the raw thumbnail field generated by the Video Embed Module.

Again i rewrote the output with the raw thumbnail as image

```
 <a href="[field_video-video-url]" rel="lightvideo"><img src="[field_video-thumbnail_path]"
 height="120" width="180"></a>

```

But the thumbnail image is broken and the image path is shown as `public://video_embed_field_thumbnails/youtube/RQieoqCLWDo.jpg` which i guess is not recognized by drupal.

So my point here is, Is there a way to access the **raw thumbnail** in the **rewrite patterns** so that every youtube video gets its own thumbnail without manually adding image as thumbnail.

# Answer
> 1 votes
I only use the video embed field in views and have set the formatter to colorbox. I get the auto-generated thumbnails by default and on click of it, the video opens in a colorbox. You don't need to do anything else then this.

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


# Question
Title: Creating a Youtube block using Views for Embedded media field module
I created a content type called Videos.

In it there is a file field with a Embedded Media Field widget, and using the Media: YouTube module to post Youtube videos.

I created a block showing links to the latest 10 nodes of content type Videos.

This works fine. However now I want to create another block showing a thumbnail of the latest video and if a user clicks on it, it will take the user to the node of that video. I have played around in Views and there doesn't seem to be a way to expose the thumbnail of a video.

Any suggestions?

# Answer
You should use the formatter, that's how it works. You just change the Option of the field to Image Thumbnail.
> 2 votes

# Answer
In the new block view, add the video field and set it to display thumbnail in formatter. Then, select link to content to goto content page. Apart from that to show latest videos, add sort criteria to post date in descending order
> 0 votes

---
Tags: 7, views, media, files
---


title: Add field(s) to menu link?

text:
# Question
Title: Add field(s) to menu link?
Is there a way to add field(s) to menu links in Drupal 8? Like an image field to output above certain links?

# Answer
> 1 votes
Add this code to your custom module:

```
function my_module_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['menu_link_image'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Menu link image'))
      ->setDescription(t('Upload the image related to this menu item'))
      ->setDisplayOptions('form', array('type' => 'string', 'weight' => 0));

    return $fields;
  }
}

```

Then use `hook_update_n` to update the schema of the `menu_link_content_data` table. Run `update.php`, flush caches and the new field should appear on all the Add/Edit menu item form.

---

In case someone wants to simply add a text field, boolean etc, simply edit `BaseFieldDefinition::create('image')` and change it to `BaseFieldDefinition::create('string')` or `BaseFieldDefinition::create('boolean')` etc

---
Tags: 8, entities, navigation
---


# Question
Title: How can I dynamically get the fields on an image media bundle?
What’s the correct way to get all of the key/values for a bundle on a media entity?

I am trying to create a media entity programmatically and I need to get all of the fields on the image bundle. I am not sure how to get the image bundle ID either.

In other words, I’d like the module I'm working on to be a bit more generic and reusable as I’ve seen the image bundle have different names depending on the installation.

Here’s what I have so far but the two main problems I see are that the image bundle ID can change and the field names on the bundle can be different.

```
   $entity = $this->createFile(
      $uri,
      $file[0]['filename'],
      $file[0]['filesize'],
      $this->currentUser
    );
    $entity->setPermanent();
    $entity->save();
    // Save media entity
    $media = [
      'bundle' => 'image',
      'uid' => $this->currentUser->id(),
      'status' => 1,
      'image' => [
        'target_id' => $entity->id(),
        'alt' => t(basename($file[0]['filename'])),
        'title' => t(basename($file[0]['filename'])),
      ],
    ];
    $image = $this->entityTypeManager->getStorage('media')->create($media);
    $image->save();

```

I'd like to be able to get the `image` bundle and dynamically figure out whichever field has the `target_id` and then assign the previously created file entity to that. I do not know how to get the image bundle schema, array signature, in order to traverse the key/values to find the target\_id

# Answer
> 2 votes
You can traverse the field definitions of the media bundle `image` and look for a field with the type `image`:

```
$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('media', 'image');
foreach ($fields as $key => $field) {
  if ($field->getType() === 'image') {
    // found image field $key
  }
}

```

To get all media bundles:

```
$bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('media');

```

---
Tags: 8, media
---


title: Tabs redirect to different page

text:
# Question
Title: Tabs redirect to different page
I'm building a job directory.

This will allow users to register, create Companies and Jobs associated with those companies.

A Job can be from one of the following types: Full-time, Part-time, Freelance and Internship.

The current Jobs View can be seen here:  It was created using Views, just like in this video and looks like this on the back:  **My current problem is** anytime a tab is clicked, the user goes to a completely different page, requiring the page to load again. I don't want the user to go to a different page anytime they select a type of job...

Unsure how to do this using Drupal but I were to do this manually, would use Ajax and PHP so that the data could be retrieved from the DB and the page wouldn't require to load again.

Drupal Legoland builds tabs using Field Group Module. This looked like a good technique and easy to implement, but for my case doesn't really work as I don't have a specific field in the content type Jobs just with the Full-time Jobs Data and not sure how to create it.

# Answer
There's a module called Quick Tabs, which allows to create Ajax loaded tabs. We need to flush all caches after creating the new tab in order to be seen as a normal block. It fixed the problem.
> 2 votes

---
Tags: views, 8
---


title: webform form's field not aligned

text:
# Question
Title: webform form's field not aligned
Hello,

My problem is the following : I created a simple form using the webform module with 2 fields which are : email and message. However the field titles are not aligned properly, and I would like to have each both field,s textarea and email input field, below each title. I've been playing with css and even the hook\_form\_alter() function module to fix this, but it is not working. any help will be really appreciated for this. Thanks

# Answer
You should try `Element > edit > General > Form display > Title Display > Before`
> 0 votes

---
Tags: webforms
---


title: Apply Image styles for migrated images

text:
# Question
Title: Apply Image styles for migrated images
I've done a drupal migration from drupal 6 to drupal 8. While all files are migrated well, image styles are not applying on migrated images.

Image styles are applied to the newly added images.

I think I should have force drupal to generate image styles for migrated images, but I don't know how.

any help one that is appreciated.

PS. I read some information about Flushing image styles in drupal 7 but I couldn't find a proper way to use it in drupal 8 as a custom module.

# Answer
> 1 votes
To solve the problem I used the code below to force Drupal to create the image styles for my nodes:

```
if ($entity->hasField('field_image') && $entity->get('field_image')->getValue() != null) {
  $image = \Drupal::service('image.factory')->get($entity->get('field_image')->entity->getFileUri());
  if ($image->isValid()) {
    $styles = \Drupal::entityTypeManager()->getStorage('image_style')->loadMultiple();
    $image_uri = $entity->get('field_image')->entity->getFileUri();
    foreach ($styles as $style) {
      $destination = $style->buildUri($image_uri);
      $style->createDerivative($image_uri, $destination);
    }
  }
}

```

Here is the description, for each node ($entity variable) , first it checks if the node type has a field with machine name "field\_image" and if this field has a value, then it checks if fileUri is a valid image, then if all conditions met, the code iterates on all image styles available and build that style for given image manually.

This code can be used as a cron job function, so on every cron job image styles of given nodes are created.

---
Tags: 8, migrations, media
---


title: Custom JQuery code does not load

text:
# Question
Title: Custom JQuery code does not load
Iam trying to call custom JQuery code but its just not working

new HtmlCommand() and InvokeCommand(method:css) is just working fine, just my custom script is not executed:

Controller:

```
    <?php
    /** * @file * Contains Drupal\ajax_example\AjaxExampleForm */

    namespace Drupal\ajax_example\Form;

    use Drupal\ajax_example\Ajax\AjaxExampleCommand; use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Ajax\CommandInterface;
    use Drupal\Core\Ajax\ChangedCommand;
    use Drupal\Core\Ajax\CssCommand;
    use Drupal\Core\Ajax\HtmlCommand;
    use Drupal\Core\Ajax\InvokeCommand;
    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;

    class AjaxExampleForm extends FormBase{

    /**
     * @param array $form
     * @param FormStateInterface $form_state
     *
     * @return array
     */
    public function buildForm(array $form, FormStateInterface $form_state) {

        $form['submit'] = array(
            '#type' => 'button',
            '#value' => 'Login',
            '#attached' => array(
              'library' => array(
                'ajax_example/ajaxCustom','core/jquery')),
            '#ajax' => array(
                'callback' => 'Drupal\ajax_example\Form\AjaxExampleForm::ajaxCallOwn',
                'event' => 'click',
                'progress' => array(
                    'type' => 'throbber',
                    'message' => 'ajaxOwn',
                ),
        ));
    }

public function ajaxCallOwn(array &$form, FormStateInterface $form_state)
  {
    $ajax_response = new AjaxResponse();

    //$ajax_response->addCommand(new HtmlCommand('#edit-user-name2--description', "changedDessrition!!!!"));

    $ajax_response->addCommand(new InvokeCommand(NULL,'changeDescription'));
    return $ajax_response;
  }

```

Command:

```
<?php

/**
 * @file
 * Contains Drupal\ajax_example\Ajax\AjaxExampleCommand
 */

namespace Drupal\ajax_example\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class AjaxExampleCommand implements CommandInterface{

  /**
   * @var string
   */
  protected $blub;
  // Constructs a SystemBlubCommand object.

  /**
   * Constructs an SlideDownCommand object.
   * @param string $blub
   */

  public function __construct() {
    $this->blub = "changed!!!!";
  }

  public function render() {
    return array(
      'command' => 'changeDescription',
      'method' => NULL,
      'blub' => $this->blub,
    );
  }
}

```

ajaxCustom.js

```
(function ($, Drupal) {

    /**
     * Command to Slide Down page elements before removing them.
     *
     * @param {Drupal.Ajax} [ajax]
     * @param {object} response
     * @param {string} response.blub
     * @param {number} [status]
     */

    Drupal.AjaxCommands.prototype.changeDescription = function (ajax, response, status) {

        alert("asdfasdgf");
        $("#edit-user-name--description").remove();
        $("#edit-user-name--description").html(response.blub);

    };

})(jQuery, Drupal);

```

ajax\_example.libraries.yml:

```
ajax_example:
  version: 1.x
  js:
    js/ajaxCustom.js: {}
  dependencies:
    - core/drupal
    - core/drupal.ajax
    - core/jquery

```

Tried so many things like : this with no success

This is the error I get in the Browser:

```
    Uncaught TypeError: Cannot read property 'apply' of undefined
    at Drupal.AjaxCommands.invoke (ajax.js?v=8.4.4:569)
    at Drupal.Ajax.success (ajax.js?v=8.4.4:407)
    at Object.success (ajax.js?v=8.4.4:222)
    at Object.t.success (jquery.form.min.js?v=3.51:11)
    at i (jquery.min.js?v=3.2.1:2)
    at Object.fireWith [as resolveWith] (jquery.min.js?v=3.2.1:2)
    at A (jquery.min.js?v=3.2.1:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js?v=3.2.1:4)
invoke @ ajax.js?v=8.4.4:569
Drupal.Ajax.success @ ajax.js?v=8.4.4:407
success @ ajax.js?v=8.4.4:222
t.success @ jquery.form.min.js?v=3.51:11
i @ jquery.min.js?v=3.2.1:2
fireWith @ jquery.min.js?v=3.2.1:2
A @ jquery.min.js?v=3.2.1:4
(anonymous) @ jquery.min.js?v=3.2.1:4
XMLHttpRequest.send (async)
send @ jquery.min.js?v=3.2.1:4
ajax @ jquery.min.js?v=3.2.1:4
e.fn.ajaxSubmit @ jquery.form.min.js?v=3.51:11
Drupal.Ajax.eventResponse @ ajax.js?v=8.4.4:316
(anonymous) @ ajax.js?v=8.4.4:255
dispatch @ jquery.min.js?v=3.2.1:3
q.handle @ jquery.min.js?v=3.2.1:3

```

If I use InvokeCommand error in recent logs:

```
Deprecated function: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Drupal\ajax_example\Form\AjaxExampleForm2::ajaxCallOwn() should not be called statically in Drupal\Core\Form\FormAjaxResponseBuilder->buildResponse() (line 69 of /Applications/MAMP/htdocs/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php) #0

```

# Answer
> 0 votes
Thanks to *No Sssweat*, that was the problem!

I thought it should be:

```
'library' => array('module_name/nameOfJSFile'));

```

Thanks to Kevin as well, your module sweetalert gave me the right hint.

---
Tags: views, javascript
---


title: Add Unique ID to Menu Item

text:
# Question
Title: Add Unique ID to Menu Item
Is it possible to add a unique id or class to each li element in a menu, perhaps using a preprocess function? I want to be able to target each menu item individually with CSS.

I could probably use css rules like `li:nth-child(1)` etc, but I would rather add a unique ID or class to the element.

# Answer
I use this module https://www.drupal.org/project/link\_attributes

It allows you to add classes/ids to menu items by editing them through Drupal's core menu admin screens
> 1 votes

# Answer
You can use menus\_attribute to add MANUALLY unique ids to each menu. I understand this is not practical if you have a big menu but sometimes just setting 1 or 2 unique ids is enough for CSS design purposes.

The alternative would be to use a `THEMENAME_preprocess_menu` in your `THEMENAME.theme` file. Drupal 8 is not easy to get `mlid` which is unique and don't change with reordering of menu items but I don't know an easy way to do it. So presenting a few options inside comments in the function itself.

```
function THEMENAME_preprocess_menu(array &$variables) {
  $id = 0;
  foreach ($variables['items'] as $key => $item) {
    $attribute = &$variables['items'][$key]['attributes'];

    //$key might change if the link is pointing to another place
    //but is also a very ugly id and some times very big
    //$attribute->setAttribute('id', $key);

    //so to get a smaller id from previous key
    //use http://php.net/manual/en/function.hash.php
    $key_hash = hash('crc32b', $key);
    $attribute->setAttribute('id', $key_hash);

    //id will change once the order of menu items changes
    //or when items are added or deleted
    //$attribute->setAttribute('id', "id-" . ++$id);

    //how does one get them mlid from the database which would stay the same no matter what
    //probably using a function call that uses
    //https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3AentityQuery/8.2.x

    // can this be used ?
    //http://www.drupalcontrib.org/api/drupal/drupal%21core%21includes%21menu.inc/function/menu_tree_all_data/8
  }
}

```
> 0 votes

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


# Question
Title: How to check if a field has more than one value
I am working on a field template to display images in a carousel (I'm using BootStrap). My field is named “galerie”
I copied field.html.twig from the core and saved it as field--field-galerie.html.twig
I managed successfuly to add the necessary markup for BootStrap carousel to work.

The wrapping markup displaying the carousel and its control shows up when there is only one image. I thought it would not. It opens after a `{% if multiple %}` condition and closes before the `{% else %}`.
My understanding is that `{% if multiple %}` only checks if the field is set to accept multiple values.

I don't know how to write an condition in twig checking if the field contains one image or more, to trigger (or not) the carousel thingee.

# Answer
> 3 votes
Use the length filter, which also works on arrays:

```
{% if items|length > 1 %}
  field contains more than 1 item
{% endif %}

```

---
Tags: 8, theming
---