# Question
Title: How to limit the quantity of a product to 1?
Some stores sell products that can only be purchased once (for example, on iTunes, you can only buy a song for yourself once, or on Steam, you can only buy a game for yourself once).

So for products like this, how can I limit the quantity to 1 in Commerce? (Users should never be able to order 2+ of any individual product of type **myproducttype**.)

There are some answers for doing this in Drupal 7:

Unfortunately, these solutions use Rules, which is still in alpha for D8.

**So how can I programatically restrict the product quantity to 1 for a given product type?**

# Answer
As pointed out in this question, there is an issue on Drupal.org for a "skip cart" feature that will create something similar to a "Buy it now" button, which means that the user will automatically be transferred to the checkout page as soon as the product is clicked.

This is effectively limiting the quantity to one.

Thanks to @Berdir for writing the code for this.

How to use the patch

1. Apply the patch.
2. Go to the Product Types -\> Edit Display page for your product type that you want to skip the cart for (`/admin/commerce/config/product-types/my-product-type/edit/display`).
3. Look for the **Product Variations** field, the format of which should be **Add to cart form**. Click the little gear icon on the right.
4. Check the box for **Skip cart** and press **Update**.
> 2 votes

# Answer
For me, simply skipping to checkout does not address my desired workflow. I still want users to be able to shop around and use a cart.

But some of my products are subscriptions, for which it doesn't make any sense to have multiple. For this purpose, I'm using https://www.drupal.org/project/commerce\_xquantity module.
> 3 votes

---
Tags: 8, commerce
---


title: Prepend custom block body text

text:
# Question
Title: Prepend custom block body text
I have a custom block with text in the body field. I need to prepend some text to this body field, either using php in a theme\_hook function or in a twig file. How can I get just the text of the body field of a custom block so that I can alter it?

# Answer
Here are three possible approaches to achieve your desired effect.

**1. Hardcoding into a twig template for the custom block**

If you don't need to modify the actual content defined within the body field of the custom block, and just want to hardcode the prepended text before the body content, creating a custom twig template for the block itself is probably easier for maintaining in the long run. This way it's easy to find and modify without the need to do any theme\_hook function editing.

* In your theme's template folder, add a block--\[machinename-with-hyphens\].html.twig template.
* Copy the contents of the block.html.twig template that already exists in your theme or from a theme included with Drupal Core such as Bartik or Classy (/core/themes/classy).
* Then in the template, add your markup and desired text before the `{% block content %}` section. If your custom block has more than a body field, you can also render just the body field data using {{ content.body }}, and the other fields as {{ content.\[field\_machinename\] }}

**2. Hardcoding the text into a theme hook preprocess function**

If you would rather avoid setting up a custom one-off twig template for the block and just want to hardcode the prepended text using a preprocess hook, you could:

* Add a \[custom\_theme\]\_preprocess\_block function. If your function doesn't explicitly inlcude the block's machine name in the function name, be sure to check the block machine name before prepending text and setting the content.
* Create a variable for your custom markup/formatted text.
* Concatenate that with the existing block content.
* Set the 'content' variable in the preprocess function

See Drupal.org documentation for template\_preprocess\_block or hook\_preprocess\_block

**3. Recommended Approach: no template or preprocess code required.**

The easiest method to approach this might be to just add a custom field to the custom block type with the default value reflecting the prepended text. To do this:

* Go to Structure \> Block Layout
* Select the Custom Block Library tab
* Select Block Types
* Choose Edit next to your existing custom block type or Add custom block to add a new custom block type.
* In the Manage Fields section, add a field for the predefined text (or markup) to prepend.
* In the Manage Display section, set the desired order for the fields to render.
> 0 votes

---
Tags: 8
---


# Question
Title: How to disable input field but show tekst with hook_form_alter?
In D8 I have a form with several fields. One specific field is a number. Input widget is Integer.

This field is prevalued with hook\_form\_alter like:

```
$nid     = \Drupal::request()->query->get("source"); // query string param
$node    = \Drupal\node\Entity\Node::load($nid);
$pe_punten = $node->get('field_pe_punten')->value;

```

I would like to achieve that the user has no access but can see this value. To disable it I can do:

```
$form['field_pe_punten']['#access'] = FALSE;

```

But how to replace this input widget with a piece of text which says "10 points"

I red several other QA but could not find out how to do this?

# Answer
> 2 votes
use `#disabled` like below:

```
$form['field_pe_punten']['#disabled'] = 'disabled';

```

---
Tags: 8, hooks
---


title: Select data from database

text:
# Question
Title: Select data from database
For the filter block I need to get the data from database. I have three tables "node", "node\__filed\_country" and "taxonomy\_index". So I need to pull only those taxonomies which are realted to the nodes, which field\_country is equal to three particular countries. So I need to provide two joins.

```
$query = $this->connection->select('node', 'node');
$query->join('node__field_country', $nfc, "node.nid=$nfc.entity_id and ($nfc.field_country_target_id=1 or $nfc.field_country_target_id=2 or $nfc.field_country_target_id=3)");
$query->join('taxonomy_index', $id, "$id.nid = node.nid AND $id.tid = $term->tid AND $id.status = 1 ");
$query->execute()->fetchField();

```

But something doesnt work in this code. Could you please help me?

# Answer
You try code

```
$term_id = 1;
  $query = $this->connection->select('node', 'node');
  $query->join('node__field_country', "nfc", "node.nid=nfc.entity_id and (nfc.field_country_target_id=1 or nfc.field_country_target_id=2 or nfc.field_country_target_id=3)");
  $query->join('taxonomy_index', "tid", "tid.nid = node.nid AND tid.tid =".$term_id." AND tid.status = 1 ");
  $query->execute()->fetchField();

```
> 3 votes

# Answer
```
  $query = $this->connection->select('node', 'node');
  $query->join('node__field_country', $nfc, "node.nid=$nfc.entity_id");
  $query->join('taxonomy_index', $id, "$id.nid = node.nid");
  $or_condition = $query->orConditionGroup()
    ->condition("$nfc.field_country_target_id", '1')
    ->condition("$nfc.field_country_target_id", '2')
    ->condition("$nfc.field_country_target_id", '3');
  $and_condition = $query->andConditionGroup()
    ->condition("$id.tid", "$term->tid")
    ->condition("$id.status", '1');
  $query->condition($or_condition);
  $query->condition($and_condition);
  $query->execute()->fetchField();

```

You have to use `or` and `and` conditions separately and append it to query that you are building.
> 1 votes

---
Tags: 8, database
---


title: entityQuery with multivalue date field

text:
# Question
Title: entityQuery with multivalue date field
Is there way to use `entityQuery` in order to select nodes with multiple value date field. For example we have a content type `event` with a field `field_event_date` which may contain unlimited number of dates. Is there any way to select all `event` nodes that occur on a certain day? E.g. we have `field_event_date` equals to

`[
 10.09.2018
 11.09.2018
 13.09.2018
]`

the node with this field should be returned for when "10.09.2018", "11.09.2018", "13.09.2018" is passed, and omitted for any other date (including "12.09.2018).

# Answer
> 1 votes
* Try this Out:

```

use Drupal\node\NodeInterface;

    $query = \Drupal::entityQuery('node')
    ->condition('status', NodeInterface::PUBLISHED)
    ->condition('type', 'event')
    ->condition('field_event_date', ['10.09.2018', '11.09.2018', '13.09.2018' ], 'IN')
    ->range(0, 10);

  $result = $query->execute();

```

---
Tags: 8, database, datetime
---


title: Preserve ajax call status

text:
# Question
Title: Preserve ajax call status
I'm trying to hide/disable field when the user select an option (Example at images).

Image A  Image B

I've tried to used AJAX, JS or #states from Drupal 7, and it works, but when the user press "Submit" and the "Validate" method throws a "form set error", the selected item does not correspond to the status of the fields (Disable/Hide). It takes the default values from $form element definition. Is there any way to do it? Thanks for comment and help!

PD: Ajax callback is associated to the radio group and it change the field states.

Form:

```
// Schedule fieldset.
$form['schedule'] = [
  '#prefix' => '<div class="booking-fieldset-wrapper">',
  '#suffix' => '</div>',
  '#title'  => t('Schedule'),
  '#type'   => 'fieldset',
  '#weight' => $weight++,
];
// Schedule pattern type.
$form['schedule']['pattern_type'] = [
  '#prefix'        => '<div class="row"><div class="col-md-5">',
  '#suffix'        => '</div>',
  '#ajax'          => [
    'callback' => 'w_tpgal_services_bookings_schedule_callback',
  ],
  '#type'          => 'radios',
  '#title'         => t('Select the requested type of schedule'),
  '#options'       => [
    BookingDTO::EVERY_X_DAYS    => t('Every X days (Daily)'),
    BookingDTO::EVERY_X_WEEKS   => t('Every X weeks (Weekly)'),
    BookingDTO::PICK_DATE_RANGE => t('Pick date range'),
  ],
  '#required'      => TRUE,
  '#default_value' => !empty($form_state['values']) && !empty($form_state['values']['pattern_type']) ? $form_state['values']['pattern_type'] : BookingDTO::EVERY_X_DAYS,
];
// Frequency.
$form['schedule']['options']['frequency'] = [
  '#attributes'    => [
    'class' => ['js-select2'],
  ],
  '#prefix'        => '<div class="row"><div class="col-md-6">',
  '#suffix'        => '</div>',
  '#options'       => ['' => t('-- Select --')] + $freq_options,
  '#default_value' => '',
  '#type'          => 'select',
  '#title'         => t('Frequency') . ' ' . theme_form_required_marker([]),
  //      '#states'        => [
  //        'disabled' => [
  //          ':input[name="pattern_type"]' => ['value' => BookingDTO::PICK_DATE_RANGE],
  //        ],
  //        'enabled'  => [
  //          ':input[name="pattern_type"]' => ['!value' => ''],
  //        ],
  //      ],
];
// Pattern days.
$form['schedule']['options']['pattern_days'] = [
  '#attributes' => [
    'class' => ['js-select2'],
  ],
  '#prefix'     => '<div class="col-md-6">',
  '#suffix'     => '</div></div></div></div>',
  '#type'       => 'select',
  '#title'      => t('Day') . ' ' . theme_form_required_marker([]),
  '#options'    => [
    ''                        => t('-- Select --'),
    BookingDTO::DAY_MONDAY    => t('Monday'),
    BookingDTO::DAY_TUESDAY   => t('Tuesday'),
    BookingDTO::DAY_WEDNESDAY => t('Wednesday'),
    BookingDTO::DAY_THURSDAY  => t('Thursday'),
    BookingDTO::DAY_FRIDAY    => t('Friday'),
    BookingDTO::DAY_SATURDAY  => t('Saturday'),
    BookingDTO::DAY_SUNDAY    => t('Sunday'),
  ],
  //      '#states'     => [
  //        'enabled'  => [
  //          ':input[name="pattern_type"]' => ['value' => BookingDTO::EVERY_X_WEEKS],
  //        ],
  //        'disabled' => [
  //          ':input[name="pattern_type"]' => ['!value' => ''],
  //        ],
  //      ],
];

```

Ajax:

```
function w_tpgal_services_bookings_schedule_callback($form, &$form_state) {
  $commands = [];

  // Get selected option.
  if (!empty($form_state['values']['pattern_type'])) {
    $option = $form_state['values']['pattern_type'];

    switch ($option) {
      case BookingDTO::EVERY_X_DAYS:
        $form['schedule']['options']['pattern_days']['#attributes']['disabled'] = TRUE;
        unset($form['schedule']['options']['frequency']['#attributes']['disabled']);
        break;

      case BookingDTO::EVERY_X_WEEKS:
        unset($form['schedule']['options']['pattern_days']['#attributes']['disabled']);
        unset($form['schedule']['options']['frequency']['#attributes']['disabled']);
        break;

      case BookingDTO::PICK_DATE_RANGE:
        $form['schedule']['options']['pattern_days']['#attributes']['disabled'] = TRUE;
        $form['schedule']['options']['frequency']['#attributes']['disabled']    = TRUE;
        break;
    }
  }
  $commands[] = ajax_command_replace('.schedule-fieldset-wrapper', render($form['schedule']['options']));

  return ['#type' => 'ajax', '#commands' => $commands];
}

```

# Answer
> 0 votes
**Disabled fields do not get submitted in form submit.** If you want to mandate field's based on the select list of "pattern\_type" use below code with `required` in `#states`.:

```
// Schedule fieldset.
  $form['schedule'] = [
    '#prefix' => '<div class="booking-fieldset-wrapper">',
    '#suffix' => '</div>',
    '#title' => t('Schedule'),
    '#type' => 'fieldset',
    '#weight' => $weight++,
  ];
// Schedule pattern type.
  $form['schedule']['pattern_type'] = [
    '#type' => 'radios',
    '#title' => t('Select the requested type of schedule'),
    '#options' => [
      BookingDTO::EVERY_X_DAYS => t('Every X days (Daily)'),
      BookingDTO::EVERY_X_WEEKS => t('Every X weeks (Weekly)'),
      BookingDTO::PICK_DATE_RANGE => t('Pick date range'),
    ],
    '#required' => TRUE,
    '#default_value' => !empty($form_state['values']) && !empty($form_state['values']['pattern_type']) ? $form_state['values']['pattern_type'] : BookingDTO::EVERY_X_DAYS,
  ];
// Frequency.
  $form['schedule']['options']['frequency'] = [
    '#attributes' => [
      'class' => ['js-select2'],
    ],
    '#options' => ['' => t('-- Select --')] + $freq_options,
    '#default_value' => '',
    '#type' => 'select',
    '#title' => t('Frequency') . ' ' . theme_form_required_marker([]),
    '#states' => [
      'disabled' => [
        ':input[name="pattern_type"]' => ['value' => BookingDTO::PICK_DATE_RANGE],
      ],
      'required' => [
        ':input[name="pattern_type"]' => [['value' => BookingDTO::EVERY_X_DAYS], ['value' => BookingDTO::EVERY_X_WEEKS]],
      ],
    ],
  ];
// Pattern days.
  $form['schedule']['options']['pattern_days'] = [
    '#attributes' => [
      'class' => ['js-select2'],
    ],
    '#type' => 'select',
    '#title' => t('Day') . ' ' . theme_form_required_marker([]),
    '#options' => [
      '' => t('-- Select --'),
      BookingDTO::DAY_MONDAY => t('Monday'),
      BookingDTO::DAY_TUESDAY => t('Tuesday'),
      BookingDTO::DAY_WEDNESDAY => t('Wednesday'),
      BookingDTO::DAY_THURSDAY => t('Thursday'),
      BookingDTO::DAY_FRIDAY => t('Friday'),
      BookingDTO::DAY_SATURDAY => t('Saturday'),
      BookingDTO::DAY_SUNDAY => t('Sunday'),
    ],
    '#states' => [
      'enabled' => [
        ':input[name="pattern_type"]' => ['value' => BookingDTO::EVERY_X_WEEKS],
      ],
      'required' => [
        ':input[name="pattern_type"]' => ['value' => BookingDTO::EVERY_X_WEEKS],
      ],
    ],
  ];

```

---
Tags: ajax
---


# Question
Title: How to use token [comment:original:url:absolute]
I want to use the token service for `[comment:original:url:absolute]`.

As far as I understand, it should be something like this

```
$message = $token->replace('Hello the comment is: [comment:original:url:absolute]', ['comment' => $comment_entity]);

```

Unfortunately, it doesn't seem to work like this.

I'm not sure what I'm doing wrong here since the documentation is vague when it comes to specific examples.

Any pointing in the right direction is appreciated.

# Answer
`[comment:original]` only exists when a comment is being updated - without context, it will always be empty. And if you had the context to pass it in this case, you wouldn't need to use the token service in the first place, you could just use what you already had to get the URL.

You probably want to use;

```
[comment:url:absolute]

```
> 1 votes

---
Tags: 8
---


# Question
Title: How can I add "data-target" additional attribute in mega menu?
How can I add an additional attribute to menu item I am using mega menu?

On element inspect my current menu url is displaying as :

```
<a class="we-mega-menu-li activeNav" title=""href="/clients/drupal/abc/fr/home#xyz" target="">
 something
</a>

```

I need to create it as :

```
<a class="we-mega-menu-li activeNav" title=""  data-target="xyz" href="/clients/drupal/abc/fr/home#xyz" target="">
 something
</a>

```

I have used **menu links attribute** module but its not working with mega menu any other suggestions by doing some custom code?

# Answer
You can use below code to set attributes. This will add an attribute to all links in the page. But make sure to add the condition check for your URL.

```
/**
 * Implements template_preprocess_menu().
 */
function THEME_preprocess_menu(&$variables) {
  foreach ($variables['items'] as $item) {
    $item['attributes']->setAttribute('data-target', 'YOUR TARGET NAME');
  }
}

```
> 0 votes

# Answer
Finally i found the solution by myself:

I have copied the twig file from **mega menu** module to our theme's directory **we-megamenu-li.html.twig** and make the following changes into it, now data- target values are dynamic .

```
<a class="we-mega-menu-li"   data-target="{{ href | split('#')[1] }}"   title="{{ attribute(attributes, 'description') }}" href="{{ href }}" target="{{ attribute(attributes, 'data-target') }}">something
</a>

```
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: Is there an error in Drupal with hook_views_post_execute?
In D8 I would like to sum a field in a view within a custom module called nvgh. I choose to use a hook for a start. I'm not sure this will be the good hook anyway.

https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/function/hook\_views\_post\_execute/8.6.x

```
function nvgh_views_post_execute(ViewExecutable $view) {

  if ($view->total_rows > 12) {
    \Drupal::messenger()
      ->addStatus(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}

```

I directly get an error:

> The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to nvgh\_views\_post\_execute() must be an instance of ViewExecutable, instance of Drupal\views\ViewExecutable given in nvgh\_views\_post\_execute() (line 96 of modules\custom\nvgh\nvgh.module).

* a) Is this a bug in Drupal 8?
* b) Which hook is common to use for pseudo code like

for each row in view result

+ count a field
    + display a message

# Answer
> 1 votes
You have to define the statement of `ViewExecutable` like `use \Drupal\views\ViewExecutable`

```
use \Drupal\views\ViewExecutable;

function nvgh_views_post_execute(ViewExecutable $view) {
  if ($view->total_rows > 12) {
    \Drupal::messenger()
      ->addStatus(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}

```

---
Tags: views, 8
---


# Question
Title: Rules to remove user from role on node publish
I have tried the following:

* Event: updating an existing content
* condition: NOT node-unchanged published
* remove user role (I'm stuck here)

The last item is my problem. There is no user reference in the data selector field, it just has site and node items and even the node items has nothing related to the node's field. It just has stuff like status, vid, uid, comments, nothing referring to the nodes field items.

What I think I need is to select Romove user role, I select the user from the data selector and then select the role it needs to be removed from.

DETAILS ON CONTENT TYPE The content type provides field for two email addresses to be provided by the node author - the node status at this time is unpublished. The two emails are then used to create new user accounts (with notification to the email owners) which are added to specific roles (these are done with rules). The two new accounts are granted permission (via the field permission module) to provide values to corresponding fields in the same content type. When the two users update the node by providing the values, the admin changes the status of the node to published.

Once unpublished the two new users need to be removed from the respective roles, though they remain authenticated users.

Thank you for looking into this

# Answer
I solved this with the rule on updating node and by setting the following conditions:

1. that the current-user is not an admin nor the node author
2. that updated node status is published
3. that the corresponding form field is not empty

THen the action is set to remove user role of current-user from \[desire\_role\]
> 0 votes

---
Tags: 7, nodes, users, rules
---


# Question
Title: Node add form alter & submit custom field
I have a content type "event" with a field called "field\_pricelist". It's a dropdown with no values, I add the values when I alter the form. The values come from a custom table (install / schema) in my database. I want to save this custom value on insert/update. My code works but I don't think it's the best way to save/update a custom field.. Any suggestions?

```
function TableManager_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'event_node_form') {

global $user;
$query = db_select('pricelist', 'p');
$query->fields('p');
$query->condition('user_id', $user->uid,'=');
$results = $query->execute()->fetchAll();

$query2 = db_select('field_data_field_pricelist', 'd');
$query2->fields('d');
$query2->condition('entity_id', $form['nid']['#value'],'=');
$results2 = $query2->execute()->fetchAll();

$dropdown_array = array();
foreach ($results as $r) {
    $form['field_pricelist']['und']['#options'][$r->pricelist_id] = $r->pricelist_name;
}
$form['field_pricelist']['und']['#default_value']['0'] = $results2['0']->field_pricelist_value;
$form['#submit'][] = "TableManager_form_submit";
}

}

function TableManager_form_submit($form, &$form_state) {

global $user;

$nid = $form_state['values']['nid'];
$pricelist_id = $form_state['values']['field_pricelist']['und']['0']['value'];

$query = db_update('field_data_field_pricelist');// Table name no longer needs {}
$query->fields(array('field_pricelist_value' => $pricelist_id));
$query->condition('entity_id', $nid, '=');
$query->execute();
}

```

# Answer
Try this...

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

  if ($form_id == 'event_node_form') {

    global $user;
    $query = db_select('pricelist', 'p');
    $query->fields('p', array('pricelist_id', 'pricelist_name'));
    $query->condition('user_id', $user->uid);
    $results = $query->execute()->FetchAllKeyed(0,1);

    $results['_none'] = "-Select-";

    $query2 = db_select('field_data_field_pricelist', 'd');
    $query2->fields('d', array('field_pricelist_value'));
    $query2->condition('entity_id', $form['nid']['#value']);
    $results2 = $query2->execute()->fetchField();

    if(empty($results2)) {
      $results2['_none']="-Select-";
    }

    $form['field_pricelist'][LANGUAGE_NONE]['#options'] = $results;
    $form['field_pricelist'][LANGUAGE_NONE]['#default_value'] = $results2;

   // $form['#submit'][] = "TableManager_form_submit";  // No longer need of this function

  }

}

```
> 0 votes

# Answer
You were done well node form alter but for submitting you need to use hook\_node\_submit() this is the best way.

https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_submit/7.x

(i.e)

```
function hook_node_submit($node, $form, &$form_state) {

    if($node->type == 'node_machine_name') {
        //your code..
    }
}

```

Thank You.
> 0 votes

# Answer
I'd use `allowed_values_function` property, rather than feeding it in hook\_form\_alter. So, select field comes with this special property known as `'allowed_values_function'`. This property can't be assigned through Drupal UI, but it can be assigned programmatically. What you need to do is to:

Declare hook\_update function in your install module file (TableManager.install):

```
function TableManager_update_7001() {
  // Get the field info
  $field = field_info_field('field_pricelist');
  $field['settings']['allowed_values'] = '';
  $field['settings']['allowed_values_function'] = 'TableManager_field_pricelist_allowed_values';

  // Save the field
  field_update_field($field);
}

```

Write up your custom code that's going to return an array of values that field should have. Within your TableManager.module file it'd be that easy:

```
function TableManager_field_pricelist_allowed_values() {
  $list = array();
  // your logic to get the values
  // example list that needs to be returned
  // $list = array(
  //   'pc1' => t('Pricelist 1'),
  //   'pc2' => t('Pricelist 2'),
  //   'pc3' => t('Pricelist 3'),
  // );
  return $list;
}

```

After that you'll need to run update.php or drush updb (if you're using) and you should be good to go. Your field is going to be updated, so it's gonna use your function.
> 0 votes

---
Tags: forms, nodes, 7
---


title: 8.5.6 Update not being recognized

text:
# Question
Title: 8.5.6 Update not being recognized
I converted a Drupal 7.xx site to Drupal 8.x manually. Updated it to 8.4.5 and tried to use composer to update it to 8.5.6 (Latest stable release). I have the original site as the public\_html/drupal site and the 8.4.5 site is at public\_html/drupal8/drupal-8.4.5. Composer, then drush seemed to work, but when I take the site out of maintenance mode, log in as admin, "Reports" still say it is at 8.4.5. Commands: `composer update --with-dependencies` and `drush updatedb` (I actually use vendor/drush/drush/drush updatedb) `drush cr` `drush sset system.maintenance_mode 0` `drush cr`

I searched the docs, found a few suggestions elsewhere, but can't fix this. The bot on StackOverflow, where I have not gotten any response, suggested I post it here.

# Answer
Unless you created your site using `composer create-project drupal-composer/drupal-project`, Drupal core is not actually a dependency of your project; instead your composer.json file likely contains the line `"name": "drupal/drupal"`. Effectively, your root composer file *is* the Drupal core package.

In this case you can only upgrade by manually downloading the new release.

See also: Why does "composer update drupal/drupal" not work?

Edit:

If you want to convert an existing D8 site to the composer-based workflow, the following steps should get you most of the way.

* In a different location, use `composer create-project drupal-composer/drupal-project:8.x-dev <my-new-site>` to create the new project. (Confirm the removal of the existing git history, and if you are using version control, use `git init; git add .; git commit` to initialize the new repository.)
* Look at the contrib modules installed in your current site's `modules/` folder, go into the new project, and use `composer require drupal/module1 drupal/module2 [...]` to install them. (Any custom modules should be copied into the folder `./web/modules/custom/` in the new project.)
* Copy the contents of your `sites/` folder into the `./web/sites/` folder of the new project.
* After backing up your database, go into your new project folder, and use `vendor/bin/drush updatedb` or `vendor/bin/drupal upex` to update your database with Drush or Drupal Console (both are installed by default).

At this point, your new project should be ready to serve the site; change your webserver configuration or symlinks to point at `<my-new-site>/web` (the web subdirectory, not the project folder itself).
> 1 votes

# Answer
I had the same issue, i found the answer in this discussion Update Core Using Composer Here is the 6 steps, works for me.

1. Removed `drupal/console` package (if it already installed) `composer remove drupal/console`
2. Removed `drupal/console-*` packages (if it already installed) `composer remove drupal/console-core drupal/console-en drupal/console-extend-plugin`.
3. Removed `vendor` folder and `composer.lock` file.
4. Edit `composer.json` : Add `"drupal/core": "8.5.6"` to require section, and remove `replace` section.
5. Execute command `composer update drupal/core --with-dependencies` .
6. Update database by Go to `/update.php` or `drush updb -y`.
> 0 votes

---
Tags: updating, composer
---


title: Render field values in node template

text:
# Question
Title: Render field values in node template
Hello I'm working on a module, I currently have an array with Node objects (custom content types), I am passing this array to a custom template (twig) but I can not render it with the values of its fields.

For example:

The dump object of the data that is coming to the template

```
array:2 [▼
  0 => Node {#564 ▼
    +in_preview: null
    #values: array:24 [▶]
    #fields: array:2 [▶]
    #fieldDefinitions: array:32 [▶]
    #languages: null
    #langcodeKey: "langcode"
    #defaultLangcodeKey: "default_langcode"
    #activeLangcode: "x-default"
    #defaultLangcode: "es"
    #translations: array:1 [▶]
    #translationInitialize: false
    #newRevision: false
    #isDefaultRevision: "1"
    #entityKeys: array:4 [▶]
    #translatableEntityKeys: array:7 [▶]
    #validated: false
    #validationRequired: false
    #loadedRevisionId: "9"
    #revisionTranslationAffectedKey: "revision_translation_affected"
    #enforceRevisionTranslationAffected: []
    #entityTypeId: "node"
    #enforceIsNew: null
    #typedData: EntityAdapter {#1065 ▶}
    #cacheContexts: []
    #cacheTags: []
    #cacheMaxAge: -1
    #_serviceIds: []
  }
  1 => Node {#562 ▼
    +in_preview: null
    #values: array:24 [▶]
    #fields: array:2 [▶]
    #fieldDefinitions: array:32 [▶]
    #languages: null
    #langcodeKey: "langcode"
    #defaultLangcodeKey: "default_langcode"
    #activeLangcode: "x-default"
    #defaultLangcode: "es"
    #translations: array:1 [▶]
    #translationInitialize: false
    #newRevision: false
    #isDefaultRevision: "1"
    #entityKeys: array:4 [▶]
    #translatableEntityKeys: array:7 [▶]
    #validated: false
    #validationRequired: false
    #loadedRevisionId: "10"
    #revisionTranslationAffectedKey: "revision_translation_affected"
    #enforceRevisionTranslationAffected: []
    #entityTypeId: "node"
    #enforceIsNew: null
    #typedData: EntityAdapter {#1198 ▶}
    #cacheContexts: []
    #cacheTags: []
    #cacheMaxAge: -1
    #_serviceIds: []
  }
]

```

As you can see, the data is inside the key #values

```
#values: array:24 [▼
      "vid" => array:1 [▶]
      "langcode" => array:1 [▶]
      "revision_uid" => array:1 [▶]
      "revision_timestamp" => array:1 [▶]
      "revision_log" => array:1 [▶]
      "revision_default" => array:1 [▶]
      "nid" => array:1 [▶]
      "type" => array:1 [▶]
      "uuid" => array:1 [▶]
      "isDefaultRevision" => array:1 [▶]
      "status" => array:1 [▶]
      "title" => array:1 [▶]
      "uid" => array:1 [▶]
      "created" => array:1 [▶]
      "changed" => array:1 [▶]
      "promote" => array:1 [▶]
      "sticky" => array:1 [▶]
      "default_langcode" => array:1 [▶]
      "revision_translation_affected" => array:1 [▶]
      "field_custom_title" => array:1 [▶]

    ]

```

The twig template:

```
<ul>
    {% for node in nodos %}
        <li>{{ node.field_custom_title}}</li> #not work
    {% endfor %}
</ul>

```

How do I get the values of the fields from twig?

# Answer
The solution was simpler than I thought, it was simply using

```
{{ node.field_custom_title.value }}

```
> 0 votes

---
Tags: 8
---


# Question
Title: How do I integrate a Media library to Image Field?
I have a image upload element field in my content type. I need to open a media library when I click on browse. My expectation is to select an image which I have already uploaded before. So I don't have to upload the same image again and again.

I've searched but I couldn't find a module for media library in Drupal 8. They are saying it is in the core of Drupal 8. I couldn't find it too. Is there an easy way to do this? Simply what I wanted is a library like in the image.(this is the media library in wordpress)

# Answer
> 0 votes
You are looking for entity\_browser.

Setup isn't that easy, so you may want to use an existing browser like media\_entity\_browser as a starting point.

The media library as shown in your image can be found at `admin/content/media`, but it's not that helpful when it comes to reusing images on a node.

# Answer
> 0 votes
Use the Module: https://www.drupal.org/project/file\_browser and its require modules and libraries.

--\> Add image field inside any content type and select widget type = **Entity Browser**

you can also add this inside the editor to enable the button from configuration

---
Tags: 8, media
---


# Question
Title: Git cloning a project asks for git@git.drupal.org password
I'm trying to switch to SSH keys as the password authentication is now deprecated and I am having an issue. I've created a new key pair and entered the public key in my account and setup my Git Bash to use the private key.

When I try to clone one of my projects, I get a password prompt asking for "git@git.drupal.org' password.

However, when I run `ssh git@git.drupal.org -v`, it asks for my private key password and the output log says that I was authenticated.

> debug1: Authentication succeeded (publickey).
> Authenticated to git.drupal.org (\[140.211.10.43\]:22).

Why does the above appear to authenticate but running something like the following does not?

```
git clone --branch 8.x-1.x git@git.drupal.org:project/MY_PROJECT.git

```

EDIT: I'm using Git Bash on Windows.

# Answer
I was finally able to solve the issue by removing all git programs from my computer and then reinstalling only Git (bash). I think Tortoise Git was interfering somehow and causing the issue.

After removals and clean install, my clone worked right away. Simple.
> 0 votes

---
Tags: community-official-site
---


# Question
Title: Adding an 'All' option to a views exposed filter
I have a Views exposed filter, that allows multiple items to be selected. It's based on the 'Allowed values' for a multiselect CCK field.

The exposed filter comes out looking like this:

```
Option 1
Option 2
Option 3

```

I need to add an 'All' option to the top, so that it would be:

```
All
Option 1
Option 2
Option 3

```

Clicking the All option should have the same effect as holding Ctrl and clicking on Options 1, 2 and 3. ie. return all nodes that have a value of Option 1, Option 2 or Option 3 for this field.

How can I add such an option to my widget? I'm sure it could be done through form\_alter somehow, but I can't suss out how.

# Answer
OK... I think I may have cracked it.

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['myfield']['#options'] = array("-ALL-" => t("- All -")) + $form['myfield']['#options'];
    array_unshift($form['#submit'], 'mymodule_exposed_form_submit');
  }
}

function mymodule_exposed_form_submit(&$form, &$form_state) {
  if (!empty($form_state['values']['myfield']['-ALL-'])) {
    $options = $form['myfield']['#options'];
    unset($options['-ALL-']);
    $form_state['values']['myfield'] = $options;
  }
}

```

So basically I add in my 'All' item at the top of the select. Then I add my own custom submit handler before Views' one.

In my submit handler, I check for the presence of the All option, and if its found, I adjust the selected options so that all options are selected except for the All option.

Seem to work :)
> 11 votes

# Answer
You could simply add same not exposed filter with your options:

```
Option 1
Option 2
Option 3

```

Then "All" option in exposed filter will show results only for those three options.
> 2 votes

# Answer
In my case (Views exposed filter of taxonomy terms) I had to unselect all options in order to get -All-. Not sure why it works that way for me.

```
function mymodule_exposed_form_submit(&$form, &$form_state) {
  if (!empty($form_state['values']['myfield']['-ALL-'])) {
    $form_state['values']['myfield'] = array();
  }
}

```
> 2 votes

# Answer
I think that you cannot do this by default, however, you can use a module that was created specifically for to improved the exposed filters. It is called Better Exposed Filters.
> 1 votes

# Answer
I have done two very ugly solutions.

Assuming you have a default to print out all values, you can hack in the option in your display output template (the one based on `views-view.tpl.php`). An example

```
<?php if ($attachment_before): ?>
  <div class="attachment attachment-before">
  <?php $attachment_before = str_replace('<div class="view-content">',
   '<div class="view-content"><div class="views-summary views-summary-unformatted"><a href="/glossary/all">All</a></div>', $attachment_before); ?>

    <?php print $attachment_before; ?>
  </div>
<?php endif; ?>

```

The other method essentially does the same thing with jQuery.
> 1 votes

# Answer
When an exposed filter is designated as multiple and not-optional, selecting all or none of the options gives the same results. One option would be to mention that in the filter help text. Another option is to install Better Exposed Filters and enable the select all/none link which, while not changing the functionality of the filter, will give your users a more intuitive interface.
> 1 votes

# Answer
Tom Kirkpatrick was correct, however, instead of adding all the options, you can also remove all the options so the form state value is empty. This also shows all values by default and is a bit cleaner:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['myfield']['#options'] = array("-ALL-" => t("- All -")) + $form['myfield']['#options'];
    array_unshift($form['#submit'], 'mymodule_exposed_form_submit');
  }
}

function mymodule_exposed_form_submit(&$form, &$form_state) {
  $myfield_values = $form_state->getValue('myfield');
  if (!empty($myfield_values) && isset($myfield_values['-ALL-'])) {
    $form_state->set('myfield', []);
    $form_state->setValue('myfield', []);
  }
}

```
> 1 votes

# Answer
At least for Drupal 8 (I don't know if it applies for D7 also), Better Exposed Filters gives you the possibility to "Add select all/none links" to your exposed filter. BEF's Version I'm using: 8.x-3.0

To add this option to your exposed filter, go to your View, access the Advanced panel \> Better Exposed Filters \> Settings and under each exposed filter you will find a collapsed pannel labeled "MORE OPTIONS FOR "\[FIELD\_NAME\]" (FILTER LABEL: "\[LABEL\]")".

Select the checkbox labeled "Add a "Select All/None" to:

"Add a "Select All/None" link when rendering the exposed filter using checkboxes. If this option is disabled, edit the filter and check the "Allow multiple selections"."

**!The issue I have noticed with this "All" option selected is that it keeps refreshing the page when the form has Auto Submit on. But, if you don't need that functionality, seems to be working like a charm.**
> 0 votes

---
Tags: 7, views
---


title: How do I override TwigEnvironment?

text:
# Question
Title: How do I override TwigEnvironment?
I have been trying for a few hours to beautify the output that twig generates, such a way that will be properly indented with tabs. For example, I would like the following output:

```
<html>
<head>
</head>
<body>
</body>
</html>

```

To become something like: For example, I would like the following output:

```
<html>
  <head>
  </head>
  <body>
  </body>
</html>

```

I would like for this "autoindentation" to happen for all tags, because it makes the markup clean and easier to debug. So I found this question: https://stackoverflow.com/questions/11878728/rendering-clean-tidy-html-with-twig-templates And since I have been trying to make drupal load that twig indent extension and that twig lexer extension.

My code so far:

**root.info.yml**

```
name: Root
type: module
description: ‘Provides basic cosmetic functionality that should be in core.’
core: 8.x
version: 0.0.1

```

**root.services.yml**

```
services:
  # Override the default Twig Environment so we can add our custom Twig Lexer.
  twig:
    class: Drupal\root\TwigEnvironment
    arguments: ['@app.root', '@cache.default', '%twig_extension_hash%', '@state', '@twig.loader', '%twig.config%']
    tags:
      - { name: service_collector, tag: 'twig.extension', call: addExtension }
  root.twig.Indent:
    class: Drupal\root\Indent
    tags:
      - {name: twig.extension}
  root.twig.Lexer:
    class: Drupal\root\Lexer
    tags:
      - {name: twig.lexer}

```

and the Indent.php and Lexer.php as provided in that answer. The problem is that the lexer wold not load because the tag twig.lexer does not exist.

So I tried to add the following code:

```
namespace Drupal\root;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Template\TwigEnvironment as CoreTwigEnvironment;
use Drupal\root\Indent;

/**
 * Twig environment that uses temporary file storage.
 */
class TwigEnvironment extends CoreTwigEnvironment {

  public function __construct($root, CacheBackendInterface $cache, $twig_extension_hash, StateInterface $state, \Twig_LoaderInterface $loader = NULL, $options = []) {
    parent::__construct($root, $cache, $twig_extension_hash, $state, $loader, $options);
    // Set our own lexer to the Twig environment.
    $this->setLexer(new Lexer($this));
  }

}

```

and drupal does not let me replace the Twig Environment and comes with the following complaint:

```
<em class="placeholder">LogicException</em>: Unable to register extension "drupal_core" as extensions have already been initialized. in <em class="placeholder">Twig_Environment->addExtension()</em> (line <em class="placeholder">941</em> of <em class="placeholder">/var/www/konquer.technology/vendor/twig/twig/lib/Twig/Environment.php</em>). <pre class="backtrace">call_user_func_array(Array, Array) (Line: 322)

```

Is there a way to do this? I can't find any documentation on this topic. Or maybe another way to achieve my goal of indented twig output

# Answer
You're using an undefined twig.lexer tag there.

It *looks* as though you want that tag to work as a service\_collector like twig.extension, but calling setLexer instead of addExtension.

For that, you probably need to add a line to your twig service definition, below the other tag:

```
- { name: service_collector, tag: 'twig.lexer', call: setLexer }

```

(Note: I don't know if this is actually good architecture. The service\_collector tag is normally used when there can be multiple extensions, and multiple lexers would just replace each other. But it should work.)
> 0 votes

---
Tags: 8
---


# Question
Title: How to define a menu with and without url arguments in hook_menu?
```
 $items['jobs/%'] = array(
    'page callback' => 'custom_changes_jobs_interface_create_update',
    'access callback' => TRUE,
    'page arguments' => array(1),
  );

```

I need to use `jobs` for POST request and `jobs/%` for put and delete request where the argument would be string but if its not passed I want to make sure it works.

# Answer
> 2 votes
You have two options:

1) Define both paths, jobs and jobs/%.

2) Define only the first path

```
$menu['jobs'] = array(
  'page callback' => 'my_page_callback',
  ...

```

Then make the argument optional:

```
function my_page_callback($job_id = FALSE) {
  ...

```

This callback will be called for both paths.

---
Tags: 7, hooks
---


# Question
Title: Bootstrap form input size is not respected
**For example:** At /user/login both the username and password input fields include an HTML attribute size="60".

In Bartik, the fields have a fixed width.

In Bootstrap, the fields are stretched to fill the entire screen width.

**Requested behavior:** I would like to make Bootstrap obey the size attribute - on /user/login, and on every single other page in the website. I am not able to generate a list of all the affected pages as there are many and it will change over time.

It seems that something in Bootstrap SCSS is messing up the widths on input fields. I would like to delete that something, or override it. However I didn't yet manage to work out how to do that.

**What I've found so far:** There is already an issue on Drupal.org, where module maintainer markcarver says

> The reason they're "stretched" full width is that they both have a form-control class. This is part of Bootstrap's design and I'm not going to fight that out-of-the-box. There are several ways to alter this form as you see fit, in a sub-theme.

**What partly works but not 100% right:** It would be possible to write CSS to set a new width on all inputs with form-control class of type text. That's good, but it sets the width to a fixed value such as 15em. I would like to get back the original width, which will be different on each input.

# Answer
The standard way to fix this is to use css in your Bootstrap-based sub-theme. For the username and password login fields:

```
#edit-name,
#edit-pass {
  width: 15em;
}

```

> NB I'm looking for a solution that covers every form of input, not just user login as a special case.

You can use this method (css) for every text input field where you want to override Bootstrap's default behaviour. Obviously, you need to use the right css-selector for the field you want to override.
> 0 votes

# Answer
I had hoped for an answer from and expert and would still welcome that - I would be happy to set accept another answer instead of mine.

Here's my best attempt so far. It seems to work for the login page and search block. However I still feel like I'm fighting a system I don't fully understand.

```
.form-control,
.input-group .form-control,
.input-group-btn {
  width: auto;
}

```
> 0 votes

---
Tags: 8, bootstrap-theme
---


title: Price display on node-product .tpl

text:
# Question
Title: Price display on node-product .tpl
I have one product with 5 variations

book: paperback, hard cover; audio; ebook(epub, mobi)

How do i display the individual prices per item on node

# Answer
> 0 votes
Since you have `Product Referenced` field hanged on your content type you can access your `Product ID` in content 's `$product_id = $vars['node']['field_product']` then you can get commerce product item with `commerce_product_load($product_id)` and then access `field_price`.

---
Tags: commerce
---


title: Clear all "pages" cache

text:
# Question
Title: Clear all "pages" cache
Is there a way on Drupal 8 to clear all "pages" cache or all "nodes" pages?

I was thinking about a custom drush command but I don't understand how to do this.

# Answer
> 2 votes
If you enable the settings documented in example.settings.local.php then you can easily see the cache tags that are present on a page.

What you will see then is that each rendered node has the `node_view` cache tag, so you only need to invalidate that.

There's also the 'rendered' cache tag which as added to any render cached item.

I don't quite understand why your cache warmer needs to invalidate the cache first, shouldn't be a problem if it's already warm? Drupal will automatically invalidate something if it is no longer valid.

The internal page cache also has no time limit by default.

---
Tags: 8, caching
---


title: Run Drush command with Gulp

text:
# Question
Title: Run Drush command with Gulp
I would to know how I can run a drush command like `drush @alias cc all` with a gulp workflow ?

This is my starting code:

```
var plugins = require('gulp-load-plugins')();
    gulp.task('drush:cc', function () {

      return gulp.src(source)
        .pipe(plugins.shell([
          'drush @vmdevd6mg cc all'
        ]))
        .pipe(plugins.notify({
          title: "Caches cleared",
          message: "Drush Drupal CSS/JS caches cleared.",
          onLast: true
        }));
    });

```

Thanks EDIt: another way to run drush but seem not to work too,no error message given.

```
// Run drush to clear the theme registry.
gulp.task('drush', plugins.shell.task([
   'drush @vmdevd6mg cc all'
]));

```

both tasks give:

```
gulp drush
Error: spawn drush @vmdevd6mg cc all ENOENT

```

EDIT1: New test

My new task and the result:

```
//Vidage de cache Drupal avec Drush
gulp.task('drush', function() {
  return gulp.src(basePaths.drushscript, {
      read: false
    })

    .pipe(plugins.shell([
      'drush @vmdevd6pf cron && drush @vmdevd6pf cc all'

    ]))
    .pipe(plugins.notify({
      title: "Vidage de Cache",
      message: "Cache Drupal vidé complètement.",
      onLast: true
    }));
});

```

Part of the global launch task:

gulp.watch(folderPaths.js.jsd68, \['drush'\]);

Give:

```
 /bin/sh: 1: drush: Permission denied

    events.js:160
          throw er; // Unhandled 'error' event
          ^
    Error: Command `drush @vmdevd6pf cron && drush @vmdevd6pf cc all` failed with exit code 127

```

EDIT: final gulp task work like //Vidage de cache Drupal avec child\_process - 2020-06

```
gulp.task('drush-cp', function(done) {
  return cp.spawn('drush', ['cache-rebuild'], {stdio: 'inherit'})
  .on('close', done)
   /*  .pipe(plugins.notify({
    title: "Vidage de Cache avec Drush",
    message: "Cache Drupal vidé complètement.",
    onLast: true
  })); */
  ;
});

```

# Answer
> 2 votes
# Try:

The first thing you’ll need is to import the dependency for “child process.” Next, you’ll want to set up an array variable containing all the paths to files you want auto-cache clearing setup for. This will basically be any Drupal template file. I would start with the main template directories you know you need it set up for and then add the additional paths along the way. Once we have our variables set, we then build our “clearcache” task using the “child\_process” dependency that is shown below. Once we have all the pieces setup, we combine them in a watch task and let the magic happen! Using this task in your workflow will save you so much time, and even more importantly, save you the headache of clearing your cache every 2 minutes.

If you do run into some issues having your task running, make sure your Drush is setup and working in your command line as these Gulp task relies on Drush to complete its work.

# code:

```
var cp = require('child_process');
var drupal_files = "paths/to/your/drupal/files/you/want/auto-cache-clearing";

// Clearcache Task
gulp.task('clearcache', function(done) {
  return cp.spawn('drush', ['cache-rebuild'], {stdio: 'inherit'})
  .on('close', done);
});

gulp.watch(drupal_files, ['clearcache']);

```

Source: http://serversideguy.com/2018/02/05/how-can-i-automatically-clear-cache-for-drupal-using-gulp/

---
Tags: drush
---


# Question
Title: How to prevent dynamic library definition from being cached?
I have a use case where i want to dynamic add library , Attributes of library will vary with page. In my case the $callback will be different depending on the page. `$libraries['sample.my-lib'] = [
 'js' => [
 '//maps.googleapis.com/maps/api/js?'.$key.'&callback='.$callback
 => [
'type' => 'external',
 'attributes' => [
 'async' => "true",
 'defer'=> 'true'
 ],
 ],
 ],
 'weight' => '2200',
 ];`

The above code works but when i navigate to different page i have to clear the cache to get updated value of $callback.

I have tried hook\_library\_info\_alter but library definition is still cached.

How can i work around it to make my use case work.

# Answer
> 3 votes
You could trigger `Drupal::service('library.discovery')->clearCachedDefinitions()` every time, but that seems like a painful workaround performance-wise. All library definitions for a particular theme seem to be stored in a single cache entry `library_info:$activeTheme`, which doesn't allow any more finely grained invalidation.

Would the range of values of "callback" allow you to loop through them and define a separate library for each one you use, and then attach the specific one you need? The JS gets loaded on demand, so only the attached library would appear on each page.

```
foreach (static::CALLBACKS as $name) {
  $libraries['sample.my-lib.' . $name] = [
    //...
  ];
}

```

Or maybe it would be possible to call the appropriate callback from a single main function (possibly setting the callback via a drupalSettings attachment), allowing you to put a fixed value in the Google Maps API URL?

# Answer
> 1 votes
Don't make the library dynamic, instead provide dynamic `drupalSettings`.

---
Tags: 8, caching
---


# Question
Title: Parent term doesn't show child term entities
My website has two taxonomies school and city, are connected. Here's city term list

```
Newyork(parent)
-Yonkers(sub-term)
-Albany(sub-term)
-New Rochelle(sub-term)
-Utica(sub-term)

```

And school term has a city\_field connected (with term referenced) to city taxonomy. I can list schools according to city terms(eg:newyork schools)

**Problem:** All city terms show schools. That's ok. But parent term(newyork) doesn't show subterm(Yonker, Albany, New Rochelle,Utica) schools.

Newyork (parent term) shows schools if only newyork selected. It should show other city schools under newyork.

**What I did:**

I've tried to add parent relationship, no result. I've tried to add parent relationship to contextual field, taxonomy term:name field and criteria and many combinations. No result...

**Here's view structure:** I've done with prkos help term to term relationship view . You may check here if you want to see how it'shandled.

Any help or article guide with this would be awesome . Thanks

# Answer
I was able to solve it, although there may be a more elegant solution. I had to use two additional modules: Views arg parent term and Views Contextual Filters OR. There are a lot of `LEFT JOIN`s so it's not very performance friendly.

The problem actually lies in listing the children terms (Yonkers, Albany, etc) of the term page you're currently viewing (Newyork), along with the term of the page itself (Newyork). Once you solve that it's simple to pull information about the terms from School term vocabulary that reference your City terms (through a Relationship).

## List the term and its children on the term page

1. Start with Taxonomy Term View type (Block Display), filter to list only City vocabulary. Add Fields for Term ID or Term name to display Cities just to test that all are there (you should see all Cities listed).

You can add the relevant School terms (that reference the term listed) although it's not yet necessary, we can take care of it when we get the correct contextual filtering.
2. Add a Contextual filter **Term ID** from `Taxonomy term` Category, and configure it with these options:
`When the filter value is NOT available`
**Provide default value**
**Taxonomy term ID from URL**
**Load default filter from term page**
`When the filter value IS available or a default is provided`
**Specify validation criteria**
**Taxonomy term**
**City**
`Filter value type`: **Term ID**

You can now test this filter by entering a City term ID into the Preview field, it should limit the results list to show only that City views row. (You can see all of the results by entering `all` into Preview.)
3. To list child City terms add a **Relationship `Parent term`** from `Taxonomy term` Category, don't require it or it will limit the results beyond what is useful to this case
4. Add another Contextual filter **Term ID** from `Taxonomy term` Category, make it use the Parent Relationship from the previous step and configure it similarly to the last one, only change one option: filter `Type`:
Taxonomy **parent** term ID from URL
5. Under Views `Query settings` tick **Contextual filters OR**, best to apply it only to this Block so it doesn't interfere with your other Displays if you have them.

This will make all Contextual filters work with an `OR` operator instead of `AND`. In your case it will allow Views to filter by term ID of the page you're viewing OR it's child, so both options will be valid.

You can now enter a city term ID twice into Preview and you'll see both that term and its children. For example, let's say your Newyork term ID is 18, if you enter `18/18` into Preview you'll see all the terms from your City vocabulary.

## Show which terms reference the ones listed
6. To show the School terms that reference City terms add a **Relationship Taxonomy term using City**. You can require it, this will exclude all City terms from the list that aren't referenced by any School terms. Since it's a School terms list we want in the end it doesn't make sense to allow any "empty" rows.
7. Add a **Field Taxonomy term: Name** and make it use the Relationship from the previous step (field\_city).

You can now see the relevant School terms in your results! You can now remove the City TID and Name fields, if you don't need them for the testing, so you only end up with School terms.
8. Place the Block on your City term pages and it will list School terms that reference that term or its children. You'll probably only want to place it on first level term pages (Newyork) because it doesn't work in reverse, it won't display parent terms when you're viewing child term pages, it will only list their own related ones.

## Add the third Taxonomy level
9. Just in case someone needs it, if the Vocabulary has the third level, to show grandchildren on parent pages you have to add another **Relationship Parent term**, make it use the earlier Parent Relationship, don't require it.
10. Add another **Term ID** Contextual filter and configure it like the second one, with `Taxonomy **parent** term ID from URL`, only make it use the second `Parent` Relationship.

You'll now have to enter the parent TID thrice to make the Preview work `18/18/18`. (This doesn't affect the Block, arguments are handled automatically.)
> 0 votes

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


# Question
Title: CKEditor custom plugin to add richcombo select list
I am building a CKEditor plugin for Drupal 8. I've done plugins that show a button in the editor toolbar, but this one should render a select list. The list is not showing up in the configuration page (*admin/config/content/formats/manage/basic\_html*), so I cannot add it to the toolbar. I can't see what I am missing.

This code works fine on a standalone CKEditor setup (outside of Drupal):

```
'use strict';

CKEDITOR.plugins.add( 'widgets', {
  requires : ['richcombo'],

  init: function( editor ) {
    console.log('In CKEDITOR.plugins init()');
    var config = editor.config;

    editor.ui.addRichCombo('widgets', {
      label : "Widgets", // label displayed in toolbar
      title : 'Insert Widget', // tooltip text when hovering over the dropdown
      multiSelect : false,

      // use the same style as the font/style dropdowns
      panel : {
        css: [ CKEDITOR.skin.getPath( 'editor' ) ].concat( config.contentsCss ),
      },

      init : function() {
        // dropdown options:
        // this.add( VALUE, HTML, TEXT );
        // VALUE - The value we get when the row is clicked
        // HTML - html/plain text that should be displayed in the dropdown
        // TEXT - displayed in popup when hovered over the row.
        this.add( "<p>Widget 1</p>", "Widget 1", "Widget 1" );
        this.add( "<p>Widget 2</p>", "Widget 2", "Widget 2" );
      },

      // this function is called when a row is clicked
      onClick: function(value) {
        editor.insertHtml(value);
        console.log(value);
      },
    });
  }
});

```

The above code was placed in */modules/custom\_widgets/js/plugins/widgets/plugin.js*

Besides, */modules/custom\_widgets/custom\_widgets.module* is empty, */modules/custom\_widgets/custom\_widgets.info.yml* sets "ckeditor" as a module dependency, and this is the code of my D8 plugin, in */modules/custom\_widgets/src/Plugin/CKEditorPlugin/Widgets.php*:

```
<?php

/**
 * @file
 * Definition of \Drupal\custom_widgets\Plugin\CKEditorPlugin\Widgets.
 */

namespace Drupal\custom_widgets\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "Widgets" plugin.
 *
 * @CKEditorPlugin(
 *   id = "widgets",
 *   label = @Translation("Widgets")
 * )
 */
class Widgets extends PluginBase implements CKEditorPluginInterface {

  /**
   * {@inheritdoc}
   */
  function getDependencies(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  function getLibraries(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  function isInternal() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  function getFile() {
    return drupal_get_path('module', 'custom_widgets') . '/js/plugins/widgets/plugin.js';
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    return [];
  }
}

```

Any help is greatly appreciated, as all examples I could find were about adding a custom button or a custom contextual menu entry, but nothing about combo lists.

# Answer
> 1 votes
You should really be extending CKEditorPluginBase and implement `getButtons` method. This is likely why you don't see it in the administrative interface, but in a vanilla CKEditor test, you do.

https://api.drupal.org/api/drupal/core!modules!ckeditor!src!CKEditorPluginButtonsInterface.php/function/CKEditorPluginButtonsInterface%3A%3AgetButtons/8.2.x

# Answer
> 1 votes
Drupal's CKEditor toolbar configuration UI only knows about buttons for which metadata is provided, you can do this by implementing `CKEditorPluginButtonsInterface`. See the "plugins" section at https://www.drupal.org/docs/8/api/ckeditor-api/overview.

---
Tags: 8, wysiwyg, plugins
---


# Question
Title: Weird behaviour when customising views-view-unformatted.html.twig with grouping
I'm trying to override the views-view-unformatted.html.twig template by an unformatted view that includes a hidden Grouping field.

The default template includes this code:

```
{% if title %}
  <h3 class="group-title">{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
  </div>
{% endfor %}

```

When I copy the default template into my theme, this generates the results I would expect:

When I try to modify the code by wrapping a div around the loop that fetches the rows, like this:

```
{% if title %}
  <h3 class="group-title">{{ title }}</h3>
{% endif %}
<div class="group-content">
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
  </div>
{% endfor %}
</div>

```

I get this output instead:

Note that the first two rows are wrapped in the **group-content** div, whilst the third row is now wrapped in a *separate* group-content div. There should obviously be only one group-content div, with all rows inside it.

My goal in overriding the default template is to put them all in a separate div, which I can't do from within the views settings, so the fact that overriding the template isn't working defeats the object of the exercise.

Any ideas why this is happening, and how to get around it?

# Answer
count opening and closing tag `div`
> 2 votes

# Answer
Problem solved. Thanks to everyone who commented. Turns out the issue was that one node being returned in the view didn't have the grouping field set. This only became a problem once I added the extra div around the rows output.
> 0 votes

---
Tags: views, theming
---


title: Why is it so abstract?

text:
# Question
Title: Why is it so abstract?
Please forgive me for asking an open ended question.

Are there various resources that explain WHY different changes were made? I'm getting used to the idea of YAML and TWIG files. I'm just struggling to understand WHY they moved. I'm supportive of learning a new way.

To me, it seems like they took the old TPL files which were decently easy to understand and replaced them with the alternate syntax from TWIG.

What is the functional/practical benefit? is there something I can read or watch to get it?

# Answer
> 5 votes
From what I understand there are two primary reasons this was done. The first was because people were using templates incorrectly - they are supposed to be templates, not logic files. People were putting lots of logic into the tpl.php files, when any logic should be in a preprocess function. The other reason is that TWIG escapes data, preventing people from putting bad code into a template, making Drupal sites more secure overall.

---
Tags: theming
---


# Question
Title: How to properly define and return simple array computed field property
We created a custom field type featuring a computed `classes` property that returns a simple array of generated CSS classes. The field itself allows content editors to define styling options depending on responsive breakpoints. Given the content editors choices, the CSS classes will be generated using a CSS class pattern defined within the field storage settings. For now, the property is generated and added to the field value within the `getValue()` method of our field item:

**src/Plugin/Field/FieldItem/ResponsiveClassItem.php**

```
/**
 * Field item of type 'responsive_class'.
 *
 * @FieldType(
 *   id = "responsive_class",
 *   label = @Translation("Responsive class"),
 *   module = "responsive_class_field",
 *   default_widget = "responsive_class_widget",
 *   default_formatter = "responsive_class_formatter",
 *   cardinality = 1,
 *   translatable = FALSE,
 * )
 */
class ResponsiveClassItem extends FieldItemBase implements FieldItemInterface {
  [...]

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'value' => [
          'description' => 'The selected responsive styles.',
          'type' => 'blob',
          'not null' => TRUE,
          'serialize' => TRUE,
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = [];
    $properties['value'] = DataDefinition::create('responsive_class')
      ->setLabel(new TranslatableMarkup('Responsive class settings'))
      ->setRequired(FALSE);;

    $properties['classes'] = DataDefinition::create('responsive_class_classes')
      ->setLabel(new TranslatableMarkup('Generated responsive classes'))
      ->setComputed(TRUE)
      ->setReadOnly(TRUE);

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function getValue() {
    $values = parent::getValue();
    $values['classes'] = $this->getClasses($values['value']);
    return $values;
  }

  /**
   * Generate and return responsive classes.
   *
   * Uses the 'pattern' field storage setting to generate a class for every
   * breakpoint and return them as classes array. The pattern may contain
   * the placeholders {breakpoint} and {value} that will be replaced by the
   * configured breakpoint values.
   *
   * @param array $breakpoints
   *   Array of breakpoint values, whereas every breakpoint value is an
   *   associative array with the following keys:
   *   - breakpoint_id: ID of the breakpoint in the breakpoints definition.
   *   - breakpoint: Replacement value for the {breakpoint} token.
   *   - value: Replacement value for the {value} token.
   *
   * @return array
   *   Array of generated classes.
   */
  protected function getClasses(array $breakpoints) {
    $pattern = $this->getSetting('pattern');
    $classes = [];
    foreach ($breakpoints as $value) {
      $class = str_replace('{breakpoint}', $value['breakpoint'], $pattern);
      $class = str_replace('{value}', $value['value'], $class);
      $class = Html::getClass($class);
      $classes[] = $class;
    }
    return $classes;
  }

}

```

**src/Plugin/DataType/ResponsiveClassClassesData.php**

```
/**
 * Data type for responsive class field classes.
 *
 * @DataType(
 *   id = "responsive_class_classes",
 *   label = @Translation("Responsive Class Classes"),
 *   description = @Translation("Generated classes of the responsive class field."),
 * )
 */
class ResponsiveClassClassesData extends TypedData {

}

```

It lets us access the generated classes of the field via the value array and attach it to it's parent entities attribute classes like so:

**responsive\_class\_field.module**

```
/**
 * Implements hook_entity_display_build_alter().
 */
function responsive_class_field_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  if (!$entity instanceof FieldableEntityInterface) {
    return;
  }

  $field_definitions = $entity->getFieldDefinitions();
  foreach ($field_definitions as $field_name => $field_definition) {
    if ($field_definition->getType() != 'responsive_class') {
      continue;
    }

    $field = $entity->get($field_name);
    if ($field->isEmpty()) {
      continue;
    }

    $classes = $field->getValue()[0]['classes'];
    foreach ($classes as $class) {
      $build['#attributes']['class'][] = $class;
    }
  }
}

```

**And now coming to the real question**

While the above approach is working, I have the strong feeling that computed properties aren't intended to just being attached in the `getValue()` method. So I'm seeking to improve the source code.

Spending decent hours diving into core source code and field API documentation left me without a better solution. What is the 'Drupal way' to providing such a property?

# Answer
If you set a property to computed this only says the property is not saved or loaded. You can then populate the values at runtime with any method, but the proper Drupal way would be to use TypedData::getValue, so in your case `ResponsiveClassClassesData::getValue()`. At the moment your data type class is useless, see the documentation of TypedData:

```
/**
 * The abstract base class for typed data.
 *
 * Classes deriving from this base class have to declare $value
 * or override getValue() or setValue().

```
> 1 votes

# Answer
Following the advice of @4k4, the final solution includes overriding TypedData::setValue and TypedData::getValue within our `ResponsiveClassClassesData` class. Furthermore, we don't attach the values of the computed property within our field's `getValue` method, but set them within the field's `setValue` method and define the property as non-internal. This way, the processed value can be accessed by simply using `$field->classes`.

The resulting classes:

**src/Plugin/Field/FieldItem/ResponsiveClassItem.php**

```
/**
 * Field item of type 'responsive_class'.
 *
 * @FieldType(
 *   id = "responsive_class",
 *   label = @Translation("Responsive class"),
 *   module = "responsive_class_field",
 *   default_widget = "responsive_class_widget",
 *   default_formatter = "responsive_class_formatter",
 *   cardinality = 1,
 *   translatable = false,
 * )
 */
class ResponsiveClassItem extends FieldItemBase implements FieldItemInterface {
  [...]

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'value' => [
          'description' => 'The selected responsive styles.',
          'type' => 'blob',
          'not null' => TRUE,
          'serialize' => TRUE,
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = [];
    $properties['value'] = DataDefinition::create('responsive_class')
      ->setLabel(new TranslatableMarkup('Responsive class settings'))
      ->setRequired(FALSE);;

    $properties['classes'] = DataDefinition::create('responsive_class_classes')
      ->setLabel(new TranslatableMarkup('Generated responsive classes'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\responsive_class_field\Plugin\DataType\ResponsiveClassClassesData')
      ->setInternal(FALSE);

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function setValue($values, $notify = TRUE) {
    if (isset($values['value'])) {
      // Single serialized values on shared tables for base fields are not
      // always unserialized. https://www.drupal.org/node/2788637
      if (is_string($values['value'])) {
        $values['value'] = unserialize($values['value']);
      }

      // Only include values that differ from the empty_value.
      $breakpoints_to_save = $this->getNonEmptyValues($values['value']);

      $values['value'] = $breakpoints_to_save;
      $values['classes'] = $this->getClasses($breakpoints_to_save);
    }

    parent::setValue($values, $notify);
  }

  /**
   * Generate and return responsive classes.
   *
   * Uses the 'pattern' field storage setting to generate a class for every
   * breakpoint and return them as classes array. The pattern may contain
   * the placeholders {breakpoint} and {value} that will be replaced by the
   * configured breakpoint values.
   *
   * @param array $breakpoints
   *   Array of breakpoint values, whereas every breakpoint value is an
   *   associative array with the following keys:
   *   - breakpoint_id: ID of the breakpoint in the breakpoints definition.
   *   - breakpoint: Replacement value for the {breakpoint} token.
   *   - value: Replacement value for the {value} token.
   *
   * @return array
   *   Array of generated classes.
   */
  protected function getClasses(array $breakpoints) {
    $pattern = $this->getSetting('pattern');
    $classes = [];
    foreach ($breakpoints as $value) {
      $class = str_replace('{breakpoint}', $value['breakpoint'], $pattern);
      $class = str_replace('{value}', $value['value'], $class);
      $class = Html::getClass($class);
      $classes[] = $class;
    }
    return $classes;
  }

}

```

**src/Plugin/DataType/ResponsiveClassClassesData.php**

```
/**
 * A computed property for generated CSS classes.
 *
 * @DataType(
 *   id = "responsive_class_classes",
 *   label = @Translation("Responsive Class Classes"),
 *   description = @Translation("Generated classes of the responsive class field."),
 * )
 */
class ResponsiveClassClassesData extends TypedData {

  /**
   * Array of generated classes.
   *
   * @var array
   */
  protected $classes;

  /**
   * {@inheritdoc}
   */
  public function getValue() {
    return isset($this->classes) ? $this->classes : [];
  }

  /**
   * {@inheritdoc}
   */
  public function setValue($value, $notify = TRUE) {
    $this->classes = $value;

    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getString() {
    return implode(' ', $this->getValue());
  }

}

```
> 3 votes

---
Tags: 8
---


# Question
Title: How to retrieve value of start date with format end date?
I D8 installed the module Optional End Date in order to add an optional end date within a date field.

When I had a single date field value I could get the value by using:

```
 $datum_deelname = $node->get('field_normaldate')->value;

```

If I change this in the new field name:

```
 $datum_deelname = $node->get('field_optional_enddate')->value;

```

I get back NULL.

How should I get this value?

# Answer
> 3 votes
Try using:

```
 $datum_deelname = $node->get('field_optional_enddate')->end_value;

```

This will give the `optional end date`.

If you want to get the normal date as you mentioned you can use as:

```
 $datum_deelname = $node->get('field_optional_enddate')->value;

```

---
Tags: 8, datetime
---


# Question
Title: For a customer database table, do I have other options, beside creating a custom module?
I'm upgrading my site to Drupal 8.

Currently, I have a custom module with a custom database table and I query that to provide historical data that is in the table. The data is really purely tabular and has thousands upon thousands of records.

If there were fewer pieces of data, I would just create a custom content type. However, I'm not sure that creating thousands upon thousands of nodes would make sense.

The database table includes the following fields.

* Person
* Product Sold
* Revenue Generated
* Month Sold

Let's say I generate a few records per month.

How should I handle this? Should I make another custom module to output the data?

# Answer
> 3 votes
Since you already have a module, I would rather not convert all the data in nodes.
I would not use nodes to store arbitrary data, since that is not the purpose of nodes, especially when I don't need to show all the data I store, or when I show a table with a pager only to the users with a specific permission. Nodes are by default readable by every registered user; making them visible only to users with a specific permission is not hard, but requires extra modules, and changing configuration.

With Drupal 8, there are few alternatives, but a custom database table is the easier solution, especially if you don't want to write migration code.

* If the data is linked to user accounts (which means, that *person* field is a username or the user ID), you could use the *user.data* service.
That service, though, loads all the data for the specified user ID, module, and key. You cannot tell to the service to load just the first, or the last, N records, for the fact the service doesn't have a concept of record. You could assign the data to different keys (for example, a key for June, one for July, etc), but that means making the code more complex.
* If the data is only pertinent to a site, and you don't want to export it to other sites, you could use the *state* service, but this still load all the data associated to a key (not module, user ID, and key) at once. The workaround is the same for the *user.data* module, with the same cons.
* If the data needs to be exportable to different sites, you could use the configuration API, but with much data, it's probable you would get some performance issues. (Yet, creating different, but related, records is not that immediate.)
* You could create a configuration entity for your data. In Drupal 8, configurations entities are used for user roles, content types, image styles, and much more.

The first three methods I described would not allow you to easily search for data as a SQL query would. The last one would allows you to get data using an API similar to the one used to query data from a database table.

If I wanted to quickly convert the code to Drupal 8, I would rather use the database approach I was using for Drupal 7. In that way, the data stored in the custom database table won't need any conversion when updating the site to Drupal 8, and you could easily control the users who access the data using a custom permission (in the same way you would do in Drupal 7).

If I wanted to make the code more "Drupal 8 code," I would use configuration entities. It requires to write code to migrate the data, but it's worth the effort.

---
Tags: 8, database
---


# Question
Title: How do I add recaptcha to a custom form programatically?
I'm using the following contrib module: https://www.drupal.org/project/google\_recaptcha

How do I add a recaptcha to my form programatically, since the form I'm using isn't listed under forms on the config page of the module?

The following doesn't seem to work:

```
$form['recaptcha'] = array(
  '#type' => 'recaptcha'
);

```

# Answer
The module doesn't implement `hook_element_info`, so it doesn't define a new element type. The code you're using looks like it's borrowed from the traditional captcha module, which does things a bit better and provides the element type.

Looking at the code, this is all you need in your form alter hook:

```
g_add_captcha($form, $form_id);

```
> 5 votes

# Answer
For Drupal 8, use the following (after installing the reCaptcha module):

```
$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How do I add reCaptcha to a form programmatically?
I have a custom form on my site, and I want to attach a reCaptcha to it. I wasn't successful using the Drupal 7 code for this. Suggestions? This is the Drupal 7 code I'm using:

```
$form['recaptcha'] = array(
  '#type' => 'recaptcha'
);

```

# Answer
Use the following (after installing the reCaptcha module):

```
$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);

```
> 2 votes

---
Tags: 8, forms
---


# Question
Title: Hide block if content is empty not working
I want to hide an entiere block is it has not result.

I went into my view, then I add "Contextual filter", "Empty", "Hide view".

But my view is always hidden if I do this, and I don't understand why... (I have content in this view, but it could be empty).

Do display my view, I'm using this : https://drupal-bootstrap.org/api/bootstrap/templates%21system%21region.html.twig/8

See my config :

# Answer
Up solution :

In views, go to "advanced". At the very bottom, see "hide block if view is empty". Change it to yes and it will work.
> 2 votes

---
Tags: blocks, theming
---


# Question
Title: on('load') is not working with jQuery 3?
I used to use the following function to load a video in the background (jquery 2.2.4):

```
function getVideo() {
    if ( $('video').length ) {
        $('video').each(function() {
            if (Modernizr.mq('(min-width: 1024px)') && $(this).children().attr('src') === undefined ) {
                var src =  $(this).children().attr("data-src");
                $(this).children().attr('src',src);
                $('video').load();
            }
        });
    }
}

```

After updating to 8.5.6, I must use jquery 3.2.1. So, I had to change the line `$('video').load()` to `$('video').on('load', function(){});`. However, the video is not loading anymore. I have tested the code, and each line gets executed until it comes to `$('video').on('load', function(){});`. I don't know why it is not loading. Is it because `.on('load', function(){})` is only accessible by `window`properties? If so, then how can I load the video using `document` properties?

The markup in the theme of that specific block would be: `$variables['video_markup'] = '<video autoplay loop muted id="bgvid"><source data-src="'.$video_link.'" type="video/mp4"></video>';`

Which roughly translates to:

`<video autoplay="" loop="" muted="" id="bgvid" data-video="0"><source data-src="https://somevideo" type="video/mp4"></video>`

I have been targeting this `video` element here. ANy suggestions will be appreciated.

Also, is there any way to force Drupal 8.5 to use Jquery 2.x? I tried this How do I use a jQuery version different from the default one used by core?, but it didn't work for me.

# Answer
With Drupal, you don't (need to) use $.on(). It is handled through a combination of Drupal.behaviors, $.once(), and Drupal.attachBehaviors().

First you create a function using $.once() that will add your handler the same as you would with $.on(), but use $.once() to ensure that the handler is only applied a single time:

```
function addVideoHandler(context) {
  $(context).find(".video").once("add-video-handler").each(function() {
    $(this).load(function() {
      alert("video loaded");
    });
  });
}

```

Next, this function is called in Drupal.behaviors:

```
Drupal.behaviors.someArbitraryButUniqueKey = {
  attach: function (context) {
    addVideoHandler()
  }
};

```

This will be executed on page load, which will add the handler to all .video elements on the page. However, unlike other onload handlers (JS, jQuery), this is also called every time after an Ajax Call is executed, with any new loaded content passed as context. Therefore any newly loaded .video elements will have the handler applied to them - same as with $.on().

Generally, this is all you will need to do. However, if you are loading any content through Ajax in one of your own functions, you will need to pass the newly loaded content through Drupal.attachBehaviors():

```
$.ajax({
  url: "http://example.com/callback",
  success: function (data) {
    var targetElement = $("some_div");
    // Insert the returned HTML into the DOM, casting it as HTML.
    targetElement.html(data.response);
    // Finally pass the new content through Drupal.attachBehaviors().
    // Note - pass through the HTML, NOT a jQuery object. This can be done
    // by passing the [0]th element of the jQuery object.
    Drupal.attachBehaviors(targetElement[0]);
  }
});

```

This will call every Drupal.behaviors element, passing it the newly loaded content, which in turn will have the handlers attached. Using $.once() ensures that handlers are not accidentally applied multiple times, for example if someone calls Drupal.attachBehaviors() without passing a value, which in turn will pass the entire document.
> 3 votes

---
Tags: theming, javascript
---


# Question
Title: Trying to use variable to pass a view argument/parameter
I'm currently in the middle of trying to figure out a way to pass the value from a variable to be used as parameter/argument for my drupal view.

I have a contextual filter that currently configured on my drupal view to output only nodes based on the taxonomy term/ID. Instead of explicitly manually setting the parameters below.

```
{{drupal_view('view_one', 'block_1', 212, 210)}}

```

Is there a way I could use a variable to pass the parameters to my drupal view

```
 % for tags in node.field_filter_tags %}

    {% set tagid = tags.entity.id %}

{% endfor %}

{{drupal_view('view_one', 'block_1', tagid)}}

```

I tried it but it seems to show duplicates.

# Answer
the first you install module Twig Tweak

In file `yourtheme.theme`

```
/**
 * Implements hook_preprocess_HOOK()
 */
function yourtheme_preprocess_node(&$variables) {
  $terms=[];
  foreach($variables['node']->field_tags->getValue() as $term){
    $terms[] = $term['target_id'];
  }
  $variables['node_terms'] = implode(',',$terms);
}

```

In file `node.html.twig`

```
{{ drupal_view('custom_view','article_block',node_terms) }}

```

Config Views `CONTEXTUAL FILTERS` in your views
> 2 votes

---
Tags: views, theming
---


title: Theme filter for a view

text:
# Question
Title: Theme filter for a view
How can I theme filters for a view in drupal 8? I would like to place the filters to the sidebar menu, and rather than having standard either dropdown or autocomplete field, I would like to have something like a rendered block, so that a user could see all options at a glance.

# Answer
> 1 votes
You need install module Better Exposed Filters

# Answer
> 1 votes
Install Better Exposed Filters and if you want to have a filter as a rendered block you can edit view and see `Exposed form in block:` option under `EXPOSED FORM`. Enable it as `Yes` and place block in any page as you like.

---
Tags: views, 8
---


# Question
Title: How to change the value of the publishing status checkbox to false by default?
I want that checkbox to be unchecked by default, because currently it's always checked.

And I want this result:

The structure of my content is as follows:

# Answer
> 1 votes
With a form alter this should work:

```
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (isset($form['#entity_type']) && $form['#entity_type'] == 'MY_ENTITY_TYPE') {
    $form['status']['widget']['value']['#default_value'] = 0;
  }
}

```

# Answer
> 4 votes
Simply edit your content type's default publishing options under example.com/admin/structure/types/manage/MYCONTENTTYPE (Structure \> Content types \> MYCONTENTTYPE \> Edit).

---
Tags: forms
---


title: User Created Slideshow

text:
# Question
Title: User Created Slideshow
I am new to Drupal and I'm looking for a slideshow of user uploaded images on a user uploaded project. Basically, I want the user uploaded images to be shown on the content page, in addition to text, ratings, comments, etc. I downloaded Views Slideshow and dependencies, then added a field on the content type the images go on, so users can add any number (actually it's capped at 10, but that shouldn't really matter) of images.

After that, I found myself stuck. Every single result on Google was somewhere along the lines of "Create a View and Use it" without enough detail on either.

How do I get a user created slideshow of images on content the user made?

# Answer
Download field\_slideshow module and enable it. After enabling go-to this link and download as `jquery.cycle.all.js`, place it under `sites/all/libraries/jquery.cycle`. Clear cache after this.

After enabling go-to `manage display` and in your image format select as `Slideshow`.

Attaching screenshots.
> 0 votes

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


# Question
Title: How to reorganise files location without updating each node manually?
In my file system, I have different folders where are stored the files linked to the nodes (either pictures in the body of the node or pictures in a 'Gallery' field I added to custom content type).

I'd like to reorganize all these folders in a more structured way.
How can I do that without editing each of these nodes?

Is there a way to update the database, e.g. change `mydomainname/sites/default/files/mypicture.png` (or whatever) to `mydomainname/sites/default/files/pictures/yyyymmdd/mypicture.png` where yyyymmdd is related to an event, for example?

My version of Drupal is 8.5.6.

# Answer
> 0 votes
Yes there is a way to fo this, I have the same situation in my previous project and I have achieved this by using below code:

```
    $field_name = 'FIELD_MACHINE_NAME';
    $entity_type = 'ENTITY_TYPE'; // Node or user
    $bundle = 'BUNDLE'; // Content Type.
    $table_field = $field_name . '_target_id';
    $table = $entity_type . '__' . $field_name;
    $db_conn = \Drupal::database();
    $query = $db_conn->select($table, 'th');
    $query->leftJoin('file_managed', 'fm', 'fm.fid = th.' . $table_field);
    $query->fields('th', ['entity_id', $table_field]);
    $query->fields('fm', ['filename']);
    $query->condition('bundle', $bundle);
    $entity_results = $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
    foreach ($entity_results as $result) {
      $fid = $result[$table_field];
      $file_load = File::load($fid);
      if ($file_load) {
        $new_directory = 'NEW DIRECTORY PATH';
        $new_uri = "public://" . $new_directory . "/" . $file_load->getFilename();
        $db_conn->update('file_managed')
          ->fields([
            'uri' => $new_uri,
          ])
          ->condition('filename', $file_load->getFilename())
          ->condition('fid', $fid)
          ->execute();
        drupal_set_message('File path changes successfully for for node id ' . $result['entity_id']);
      }
      else {
        drupal_set_message('Unable to load file for node id ' . $result['entity_id'], 'warning');
      }
    }

```

Here you have to be very careful while moving this to production. Backup DB and files before running this code.

And `drush cr` or `clear cache` after running this code for every field.

---
Tags: 8
---


# Question
Title: How do I load CSS files to a custom theme?
I understand this question has been asked many times. However, I still can't figure out why the CSS files of my custom Drupal 8 theme are not loading.

Edited (more info): The CSS files are not being defined at all (they do not show up in the HTML).

Here is my `test.info.yml` file:

```
name: "test"
type: theme
description: "Theme by ..."
package: custom
core: 8.x

libraries:
  - test/global-styling
  - test/global-scripts

regions:
  headline: Headline
  header: Header
  content_special: 'Content special'
  content: Content
  sidebar: Sidebar
  footer: Footer

```

And here is my `test.libraries.yml` file

```
global-styling:
  version: 1.0
  css:
    theme:
      css/bootstrap-4.0.0.css: {}
      css/content.css: {}
      css/footer.css: {}
      css/header.css: {}
      css/IE.css: {}
      css/lista.css: {}
      css/navigation.css: {}
      css/style.css: {}
      css/taulukko.css: {}

global-scripts:
  version: 1.0
  js:
    js/scripts.js: {}
  dependencies:
    - core/jquery

```

**Note**: The CSS files are not being defined at all (they do not show up in the HTML). So the console is not showing any errors about this issue. The css files are accessible if you manually type the path in the browser window.

# Answer
After trying a lot of different things I found the problem in `page.html.twig` file. I had misspelled one region name (a "-" instead of a "\_"). Fixing the misspelled region name just got the CSS working.

Thank you all that helped me by commenting on the question.
> 0 votes

---
Tags: 8, theming
---


title: Save as unpulished role

text:
# Question
Title: Save as unpulished role
I want to give a role the possibility to create new articles and save them as unpublished. Only the administrators can save articles as unpublished, and I want to give this possibility to another role. How can I do that?

I only have Save and publish for the other roles.

# Answer
Looking around, it would appear that users with the *Administer Content* permissions can do what you want to accomplish. However, this permission has the following warning: `Give to trusted roles only; this permission has security implications. Promote, change ownership, edit revisions, and perform other tasks across all content types.` If this is a limited permission that you want to give and to trusted users only (as suggested by the warning provided by Drupal), you should be fine.

However, if you want many (possibly untrusted) users to be able to do this, the best suggestion I have at the moment is to add a field to the node itself asking the user if they want it to be published or not and to write a hook that checks the value of that field and publishes it based on that information. There are many variations of this - you can make the field appear only for certain roles, etc.

**Edit:** Another option you have, instead of writing a hook, is to use the Workflow module. You can set various access permissions from within the module itself to replicate published/unpublished behavior (i.e. make it so that only the author can see nodes published under a certain workflow state). This is probably a better option in the long run since these can be saved in configuration. I'm sure there are other benefits as well.
> 3 votes

# Answer
You can do this with override\_node\_options

When installed it will give you `Override CONTENT TYPE published option` for each content type.

NOTE this problem is a Drupal 8 shortcoming which is also part of this issue
> 0 votes

---
Tags: 8
---


# Question
Title: Field collection does not show on the page
I've installed filed collection on drupal 8 version. Now I'm trying to add field collection named "field\_ingredients\_second" to a content type. And then I've added fields to this newly created field collections. After that I've added values in edit mode. However, when I open it in a view mode it does not show anything there.

I've also configured view for it and also placed it block layout. Inside block layout I've configured my mustache file.

Inside my mustache file I've

```
It shows here
{{#field_ingredients_second}}
it does not show anything
{{/field_ingredients_second}}
& It shows here also

```

In the output "It shows here & It shows here also " is displayed but not the values from the tags inside. Can anyone help me with this. Why field collection is not displayed on the page

# Answer
Unless you are leaving out some details, neither Drupal 7 or 8 us Mustache templates, they use TPL and Twig respectively.

If this is Drupal 7, you should be doing:

```
print $content['field_ingredients_second'];

```

In Drupal 8, you would do this:

```
{{ content.field_ingredients_second }}

```

Other than that, you would need to use a debugger to figure out what variables are being sent into the template.

edit: 4k4 is right though, if this is Drupal 8, don't use Field Collection. Use Paragraphs.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Upload multiple files through a single file dialog?
In a Webform, I want to let the user upload multiple files via one call of the file dialog. I found the following modules.

With either of them, I cannot open the file dialog once and select all the files. Instead, I need to open the file dialog again for every file.

Is there a way to allow file uploads in one go for Webform forms?

# Answer
Can you try Multiupload Filefield Widget and or Multiupload Imagefield Widget

I think those modules can help you.
> 1 votes

---
Tags: 7, webforms, files
---


# Question
Title: Commerce Product listing View with category contextual filter, How to show items of (selected term and its child terms)
I have a the view 'Browse Products by Category'

with the path: /taxonomy/term/%

and a contextual filter: Product: Category (field\_category)

and let's say I have these categories:

* Sensors

--- Accelerometers

--- Current Sensors

--- Direction Sensors

* Robotics & Motors

--- Dc Geared Motors

--- Digital Servo

--- Motor Drivers

then if I selected 'Sensors', I get no products, although there are products tagged with 'Accelerometers'

Is there anyway that I can configure view to show products in sub categories.

That could be done easily when showing contents but not commerce products, case content offers a contextual filter that supports depth out-of-box.

# Answer
> 0 votes
There are two approaches to solving this problem:

1. Use the product\_taxonomy\_filter module to add the missing filter. Note that the performance impact of this module is unclear (it adds a subquery since it can't rely on the taxonomy\_index table).
2. Build your product catalog the recommended way, using Search API. The official docs cover this use case (via adding the "Index hierarchy") processor.

---
Tags: views, 8, commerce, taxonomy-terms
---