# Question
Title: How to fire a Rule when an image is removed from Image field with unlimited values?
Working with Drupal 7.58 and File Entity 2.19 and Rules 2.10

First I needed to fire a rule when saving a new file and I found a solution (here).

Now I would like to fire a rule when an user removes an image (file) from a content (Image field with multiple values).

I can not find any event to start working after an image is removed?

EDIT 1 :

Following @Pierre.Vriens "check list approach", I have tried to create a simple rule fired when an image is removed :

```
{ "rules_verify_pictures_removed" : {
    "LABEL" : "Verify pictures removed",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "image" ],
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node-unchanged:field-pictures" ] },
          "ITEM" : { "list_item" : "Previous list item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : { "list" : [ "node:field-pictures" ], "item" : [ "list-item" ] } },
                  "DO" : [
                    { "drupal_message" : { "message" : "Picture has been removed.", "type" : "warning" } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

```

Unfortunately, condition is always False and I get the message even if no item has been removed (One message for each item, unchanged, added or removed)

# Answer
> 0 votes
To my knowledge there is no Rules Event like the one you are looking for. However, as illustrated in my answer to the question you linked to, you can use an approach like so:

* iterate over all field values of your field of the ***unchanged*** node.
* within each iteration step, check if the list of items in the ***changed*** node does NOT contain the field value being processed in the current iteration step ... If it is NOT contained in it anymore, it means the values is removed.

**Note**: processing image fields in Rules is a bit special. You may have to use a token like `[node:field-pictures:file:url]` and `[list-item:file:url]`. And if they appear to be empty, then retry by adding a Rules Condition like "content is of type = article"

---
Tags: rules, media, files
---


# Question
Title: Displaying only what's entered on the page
I have created a new field within one of the content types that can be entered on the content pages and placed the block into the layout, but it seems to add all the pages content that was entered in on all the pages within that field. How can I filter it, so it only shows what has been entered on that specific page.

# Answer
> 1 votes
On the far right, Under Advanced, for Contextual Filters click add

Add Content ID, select provide default value, select content ID from URL.

---
Tags: views
---


# Question
Title: Running unit test only for my custom module
Is there any way I can run unit testing only for my modules? I know there is a way to run a specific unit test but I want to run unit test for all tests under certain directory (/modules/custom in my case). Is it even possible? I want to do it so that CI/CD automatically runs unit tests only for my code.

# Answer
Sure, all you need to do is provide a path/file to phpunit and it will be limited to that.

```
vendor/bin/phpunit -c core modules/custom

```
> 4 votes

---
Tags: 8, testing
---


# Question
Title: How do I show the members in a block, contextually filtered by the currently logged in user?
In my project every group member will only ever belong to a group; some group members have the *Group Administrator* role.

I would like to create a view block to satisfy this story: As a user with the Group Administrator role I need to see a list of all members in my group so that I can easily access their information from any page.
Putting it in another way: I need to show a block on every page that lists all members of the group that the currently logged in user is an administrator of.

The permission stuff is simple enough. What I'm struggling with is the contextual filter on the view, and I'm thinking now that I'll need to do some code customization. I can't just add "UID of currently logged in user". Am I missing the right configuration?

I just found this approach of making a custom block. I'll start going down that path but still very curious if I'm missing something.

Based on that link from Drupal.org, I'm currently doing the following:

```
/**
 * {@inheritdoc}
 */
public function access(AccountInterface $account, $return_as_object = FALSE) {
  return $this->groupMembership[0]->hasPermission('view group_membership content') &&
  count($this->groupMembership[0]->getGroup()->getMembers()) > 1;
}

/**
 * {@inheritdoc}
 */
public function build() {
  $build = [];

  //$build['group_member_block']['#markup'] = 'Implement GroupMemberBlock.';
  $build['group_member_block']['item_list'] = [
    '#theme' => 'item_list',
    '#list_type' => 'ul',
    '#wrapper_attributes' => [
      'class' => [
        'group-member-list'
      ]
    ],
    '#items' => $this->getGroupMembersItemList(),
  ];

  return $build;
}

protected function getGroupMembersItemList() {
  $group_members = $this->groupMembership[0]->getGroup()->getMembers();
  $items = [];
  foreach ($group_members as $member) {
    $user = $member->getUser();
    $items[] = [
      '#markup' => $this->getGroupMemberName($user),
    ];
  }

  return $items;
}

```

It is a pretty darn simple way to do it. For some reason, I expected to be able to hop right into views and build it though. Again, maybe I'm missing something simple.

# Answer
One custom solution that is doing the exact same thing in my case is to create a view-block and show `group content` of type `group membership`. Then add the relationship `Group content User`, require this relationship, filter by plugin `Group membership`. Then add a contextual filter `Group content: parent group`. Add all fields you want to show in the view and use the relationship `Group content user` to display name, id, email etc.

Now the "custom" part in my solution is a tiny module that implements the `hook_views_pre_view()` and adds the `gid` of the currently logged in user to the `$args` array of that specific view like this: `$args[0] = $gid;`
> 0 votes

---
Tags: 8, group
---


title: Taxonomy with adjacent cities

text:
# Question
Title: Taxonomy with adjacent cities
I have a `content type 'company'` with a related `tax-term: 'city'`. With a `view` I can search for companies based on 'city' with autocomplete.

Is there a way I can **relate adjacent cities into the same tax-term 'city'**? **If not**, I would have to create a new tax-term into the content type 'company' and select for each company the adjacent cities. That is a lof of work.

**Geo lookup is not an option**, because we want te select which adjacent cities belongs to a specific city.

**For example:** Tax-term: city

```
City A
-- City B // adjacent city of 'city a'
-- City C // adjacent city of 'city a'
-- City D // adjacent city of 'city a'
City B
City C
City D

```

As you can see, **City B, C and D exists in the tax-term but also are children of 'city A'**. It should be an alias, because otherwise the children will have all a different ID, so that won't work.

Hope it is clear ...

# Answer
> 0 votes
I would like to share my own working solution. If you see any improvements, please correct me. That would be helpful. If not I hope this script can be helpful for someone else...

I've created my own module and used this function to alter the query:

```
<?php

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\taxonomy\Entity\Term;

function search_cities_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
    // machine_name of view
    if ($view->id() == 'zoek_een_bedrijf') {
        foreach ($query->where as &$condition_group) {
            foreach ($condition_group['conditions'] as &$condition) {
                // check which field must be changed
                if ($condition['field'] == 'node__field_stad.field_stad_target_id = :node__field_stad_field_stad_target_id') {
                    $value = $condition['value'];
                    // get ID from taxonomy term
                    $city_id = $value[':node__field_stad_field_stad_target_id'];
                    // load taxonomy term info
                    $term = Term::load($city_id);
                    // load reference field with taxonomy term ID's
                    $term_field = $term->get('field_aangrenzende_gemeenten')->getValue();
                    $cities = array();
                    // add ID from parent taxonmy term
                    array_push($cities, $city_id);
                    // add taxonomy terms from reference field (children)
                    //print_r($term_field);
                    foreach ($term_field as $key => $value) {
                        array_push($cities, $value['target_id']);
                    }
                    // update the condition before sending query to database
                    $condition = array(
                        'field' => 'node__field_stad.field_stad_target_id',
                        'value' => $cities,
                        'operator' => 'IN',
                    );
                }
            }
        }
    }
}

```

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


# Question
Title: How to copy current user'id to a custom field when adding a new entity?
I have a custom content entity 'service' created with Drupal Console (drupal generate:entity:content).
I added my own fields to the standard ones created by DC. Of which 'seliste\_id':

```
$fields['seliste_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('SEListe'))
  ->setSetting('target_type', 'person')
  ->setSetting('handler', 'default');

```

By default, the code generated by DC handles the owner of any new entity, owner\_id being the id of the current user.
By design, seliste\_id is the id of the other entity 'person' which is linked 1 \<-\> 1 to Drupal's 'user'.
So when a new 'service' is created, I'd like to "copy" its owner (i.e. the current user's id) to 'seliste\_id'.
I know that I can do that in mymodule\_entity\_presave().
Is there a way to do that in the definition of 'seliste\_id' field?
With `->setDefaultValue()` or `->setDefaultValueCallback()` maybe?
Any idea?

# Answer
Using the advice (thanks @Berdir), I tried this and it worked!

```
// ----------------------------------------------------------------------------
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
// ----------------------------------------------------------------------------
some fields...
// ----------------------------------------------------------------------------
    $fields['seliste_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('SEListe'))
      ->setSetting('target_type', 'person')
      ->setSetting('handler', 'default')
      ->setDefaultValueCallback('Drupal\sel\Entity\Service::getCurrentUserId');
// ----------------------------------------------------------------------------
some other fields...
// ----------------------------------------------------------------------------
    return $fields;
  }

  public static function getCurrentUserId() {
    return [\Drupal::currentUser()->id()];
  }

}

```
> 0 votes

# Answer
From the node entity:

```
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Authored by'))
  ->setDescription(t('The username of the content author.'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'user')
  ->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ])
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => [
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'placeholder' => '',
    ],
  ])
  ->setDisplayConfigurable('form', TRUE);

// ...

public static function getCurrentUserId() {
  return [\Drupal::currentUser()->id()];
}

```
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How do I get the number of rows selected from the query?
In my custom module for Drupal 8, I am using the following code.

```
$query = $this->connection->select('node_field_data', 'nf_data');
$result = $query->execute();

```

I can get the number of rows looping over `$result`.

```
foreach ($result as $row) {
  $num++;
}

```

Is there a way to get the number of rows with a function / class method?

# Answer
> 7 votes
```
$query = $this->connection->select('node_field_data', 'nf_data');
$result = $query->execute();
$records = $result->fetchAll();
$num_results = count($records);

```

This will leave you with `$records` being an array of all records and `$num_results` being the count of that array.

See: https://www.drupal.org/docs/8/api/database-api/result-sets

Also: Select documentation and StatementInterface (the return val of $query-\>execute) documentation

You may want to look into using entity queries, though I'm not sure what your goal is.

# Answer
> 9 votes
`$query->countQuery()->execute()->fetchField()` is faster.

```
$number = $this->connection->select(static::TABLE_NAME, 'f')
  ->condition('event', $name)
  ->condition('identifier', $identifier)
  ->condition('timestamp', REQUEST_TIME - $window, '>')
  ->countQuery()
  ->execute()
  ->fetchField();

```

---
Tags: 8, database
---


# Question
Title: What version is the CKEditor in the CKEditor module?
I have installed the CKEditor module for Drupal 7 version 1.14. This version of the module comes with CKEditor already integrated with the module, so I am not sure how to find out exactly which version of the CKEditor this module comes with by default. I need to know this because when adding plugins from the CKEditor website only certain versions of the plugin are compatible with certain versions of the CKEditor. So how can I find this out? I have looked through the different module and JS files but I cannot find this information anywhere.

# Answer
> 2 votes
The library files are linked to directly via CKEditor's own CDN, so the answer can change depending on what their CDN is currently serving.

You can use `ckeditor_get_version()` to check which version is currently being used:

```
$current_version = ckeditor_get_version();
// e.g. 4.3.2

```

# Answer
> 3 votes
In your browser with an open Drupal site:

* press the F12 key to open the console (or right click anywhere on the page and select "inspect")
* select "console" tab if not already selected
* type this command and press enter: `CKEDITOR.version`

# Answer
> 1 votes
I was able to find it in the status report (/admin/reports/status) on my drupal 7.58 site:

# Answer
> -1 votes
You can go to Ckeditor module in your contrib module list and open the readme.txt file. At the section "Requirement" you can see the compatible version of ckeditor library that you can download. the section look like this :

```
Requirements
------------
  - Drupal 7.x,
  - PHP 5.2 or greater,
  - CKEditor 3.4 or greater.
    You will need to download CKEditor from the official download site: http://ckeditor.com/download.
    It is recommended to always use the latest CKEditor version available.

```

---
Tags: wysiwyg
---


# Question
Title: Creating a simple Drupal 8 custom service - argument should be an instance of a class, recognised as an array
I'm kind of new to Drupal 8 development and object-oriented PHP in general. I've been trying to make a simple custom block module, which includes a service with simple dependency injection. However, I can't seem to figure out why the construct method does not receive an appropriate parameter - been staring at the code for hours. My code:

**event\_countdown.services.yml**

```
services:
  event_countdown.date_calculator:
    class: Drupal\event_countdown\DateCalculator

```

**event\_countdown.routing.yml**

```
event_countdown.content:
  defaults:
    _title: 'Event Countdown'
  requirements:
    _permission: 'access content'
  options:
    no_cache: 'TRUE'

```

**src/DateCalculator.php**

```
<?php

namespace Drupal\event_countdown;

class DateCalculator {

  // forms the block's output based on given date
  public function daysUntilEventStarts($date) {
    // get difference in days between now and the given date
    $difference = $this->getDifferenceInDaysFromCurrentDate($date);
      // if event date is in the future
      if($difference >= 1) {
        return "Days left until the event starts: " . $difference;
      // if event date and current date are on the same day
      } else if($difference == 0) {
        return "The event is in progress.";
      // if event date is in the past
      } else {
        return "The event has already ended.";
      }
  }

  // calculates difference in days between now and given date
  public function getDifferenceInDaysFromCurrentDate($date) {
    // current time
    $now = time();
    // event datetime field converted to timestamp
    $event_date = strtotime($date);
    // timestamp difference
    $difference = $event_date - $now;
    // timestamp difference rounded down to days
    return round($difference / (60 * 60 * 24));
  }

}

```

**src/Plugin/Block/EventCountdownBlock.php**

```
<?php

namespace Drupal\event_countdown\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\event_countdown\DateCalculator;

/**
 * Provides an event countdown block.
 *
 * @Block(
 *   id = "event_countdown_block",
 *   admin_label = @Translation("Event countdown block"),
 *   category = @Translation("Event countdown block"),
 * )
 */

class EventCountdownBlock extends BlockBase {

  protected $dateCalculator;

   public function __construct(DateCalculator $dateCalculator) {
     $this->dateCalculator = $dateCalculator;
   }

   public static function create(ContainerInterface $container) {
     return new static($container->get('event_countdown.date_calculator'));
   }

   public function build() {

      // get current node based on route
      $node = \Drupal::routeMatch()->getParameter('node');

      //check whether node type equals 'event' - if it does, get text output, otherwise display an error message
      if($node->getType() == "event") {
        // get datetime value from node
        $date = $node->field_event_date->value;
        // call service method to calculate difference in days
        $output = $this->dateCalculator->daysUntilEventStarts($date);
      } else {
        // display error
        $output = "Woops! This block is intended only for event pages.";
      }

      return array(
        // output
        '#markup' => $output,
        // prevent block caching
        '#cache' => [
          'max-age' => 0,
          ],
      );
  }

}

```

**The error I get in Drupal logs is:**

`Recoverable fatal error: Argument 1 passed to Drupal\event_countdown\Plugin\Block\EventCountdownBlock::__construct() must be an instance of Drupal\event_countdown\DateCalculator, array given, called in D:\drupal8\devdesktop\drupal-8.5.1\core\lib\Drupal\Core\Plugin\Factory\ContainerFactory.php on line 25 and defined in Drupal\event_countdown\Plugin\Block\EventCountdownBlock->__construct() (line 24 of D:\drupal8\devdesktop\drupal-8.5.1\modules\custom\event_countdown\src\Plugin\Block\EventCountdownBlock.php) #0 D:\drupal8\devdesktop\drupal-8.5.1\core\includes\bootstrap.inc(582): _drupal_error_handler_real(4096, 'Argument 1 pass...', 'D:\\drupal8\\devd...', 24, Array) #1`

I would appreciate any sort of help. Thank you!

# Answer
> 2 votes
Plugins aren't naturally container-aware, so your `create` method is never called. The default plugin factory passes a configuration array as the first argument to your constructor, hence the error.

You can make the plugin container-aware by implementing `ContainerFactoryPluginInterface`. For example:

```
class EventCountdownBlock extends BlockBase implements ContainerFactoryPluginInterface {

  public function __construct(array $configuration, $plugin_id, $plugin_definition, DateCalculator $dateCalculator) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->dateCalculator = $dateCalculator;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('event_countdown.date_calculator')
    );
  }

```

---
Tags: services, debugging, dependency-injection
---


# Question
Title: Drupal 8 ajax form load error, context.querySelectorAll is not a function
I have created a custom module with ajax call, which are sending render form data that I receive in my ajax prototype in a js file like below.

```
Drupal.AjaxCommands.prototype.loadCommentFormCommand = function (ajax, response, status) {
    if ($('#comment-form-wrapper').length === 0) {
        $('.wall-posts').prepend(response.html);
          Drupal.attachBehaviors(response.html);
        }
      };

```

But it's showing me

```
context.querySelectorAll is not a function

```

Error. Does anyone face similar error or have some solutions for this?

# Answer
The first argument to `Drupal.attachBehaviors` is an object representing a DOM element, `context`. You're currently providing it with a string.

In your case the correct code will probably be something like:

```
Drupal.attachBehaviors($('#comment-form-wrapper').get(0));

```

You don't pass data to behaviours through the `attachBehaviors` method, instead stash it somewhere in a global scope and pick it up later.

For example you might choose the `window`, `drupalSettings`, or some other object, depending on your general requirements and any other required uses of that HTML data.
> 4 votes

---
Tags: 8, ajax
---


# Question
Title: How do I filter a menu to only show menu items translated into current language?
In my Drupal 8 project I have a menu containing menu items in english. Some of the items have a german translation. How do I filter the menu to only show the german items when viewing the site in german?

I'm currently using `MenuLinkTree` to fetch my menu and I have created my own `MenuLinkTreeManipulator` transform where I try to filter out MenuLinkContent items that does not have a translation in the current language. But the method for getting an entity from a `MenuLinkContent` object is protected, so I cannot access the language property of the underlying entity!

Is there some other way of finding out the language of a MenuLinkContent object? Or another way of filtering a menu by current language?

**Edit:**

Here is the method I'm currently using (as a transform) when getting the menu via the `MenuLinkTree` service:

```
public function currentLanguage($tree) {
  $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();

  return array_filter($tree, function($item) use($lang) {
    return $item->link->getEntity()->language()->getId() === $lang;
  });
}

```

`$item->link` above is an instance of `\Drupal\menu_link_content\Plugin\Menu\MenuLinkContent`. The above code does not work since `$item->link->getEntity()` is a protected method. If make it public the code above works. I see no way of accessing the underlying entity here without hacking core. Is it possible in any way? Is it possible to "swap" out this class for my own implementation in a custom module?

# Answer
I found another way of solving this which is much simpler and allows my to bypass the whole `MenuLinkTree` manipulators thing. Instead I simply add a `hook_node_access` and restrict access to the node if it isn't translated in the currently viewed language with `$node->language()`. This hides the menu items since the `MenuLinkTree` service checks the node access when getting each menu item.

Note: this only works for content menu items connected to a node. In my case that is just what I needed.

I got the idea from this answer by @Berdir: How do I filter entity reference fields based on language?

Here is a gist of my solution, which also includes filtering paragraphs and my custom inline\_entity by language. https://gist.github.com/reekris/e6f64de799df75d724c2
> 0 votes

# Answer
I managed to hide non translated menu items with the following code:

```
use Drupal\Core\Menu\MenuLinkInterface;
use Drupal\menu_link_content\Plugin\Menu\MenuLinkContent;

/**
* Implements hook_preprocess_menu().
*/
function MY_MODULE_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
   $language = Drupal::languageManager()->getCurrentLanguage()->getId();

    foreach ($variables['items'] as $key => &$item) {
      $menuLinkEntity = MY_MODULE_load_link_entity_by_link($item['original_link']);

      if ($menuLinkEntity != NULL) {
        $languages = $menuLinkEntity->getTranslationLanguages();
        // Remove links which is not translated to current language.
        if (!array_key_exists($language, $languages)) {
          unset($variables['items'][$key]);
        }
      }
    }
  }
}

function MY_MODULE_load_link_entity_by_link(MenuLinkInterface $menuLinkContentPlugin) {
  $entity = NULL;

  if ($menuLinkContentPlugin instanceof MenuLinkContent) {
    list($entity_type, $uuid) = explode(':', $menuLinkContentPlugin->getPluginId(), 2);
    $entity = \Drupal::entityManager()->loadEntityByUuid($entity_type, $uuid);
  }
  return $entity;
}

```

There is probably a better way but this worked for me. Got the inspiration from here: http://www.agoradesign.at/blog/add-custom-menu-item-attributes-drupal-8
> 8 votes

# Answer
Short answer is that you can't.

The longer answer is that you can, but it depends.

### Background information

The tricky thing with menu items is that some are created via .yml files, some are created via Views and some are created as content entities.

This means that the way menu items are translated are very different, as it uses

* interface translation
* configuration translation
* content translation

I looked at this issue around beta 6-8 and talked with Gabór about it (the translation initiative lead). There is an open ticket for it (https://www.drupal.org/node/2466553) but no work has been done. I'm not sure it's actually possible to fix this.

### Possible solution / workaround

If you make sure your menu only exist of content menu items (menu items created in your interface) you can make a solution. Basically what you need to do, is to use views to display the menu items. In views interface you can make a filter on the language, to filter out untranslated menu items. I'm not sure how well it works, if you need to menu to expand. But for some use cases this can be an easy solutions.

If you need your menu items to expand, you can probably also do this with views, but my guess is that it will require more work and maybe some custom code to fetch the menu items under the active menu item.
> 1 votes

# Answer
Updated code snippet from @Sockiplast to remove depricated function entityManager(). Improvement has also been made to remove menu items from the entire tree and not only first level menu depth.

```
use Drupal\Core\Menu\MenuLinkInterface;
use Drupal\menu_link_content\Plugin\Menu\MenuLinkContent;

/**
* Implements hook_preprocess_menu().
*/
function MY_MODULE_preprocess_menu(&$variables) {

  if ($variables['menu_name'] == 'main') {
    // Get context language.
    $language = Drupal::languageManager()->getCurrentLanguage()->getId();

    if (isset($variables['items'])) {
      MY_MODULE_menu_item_cleanup($variables['items'], $language);
    }
  }
}

/**
 * Recursive function to remove menu items with different language
 * than context language.
 *
 * @param $items
 *   Menu items for current menu depth.
 * @param $language
 *   The context language.
 */
function MY_MODULE_menu_item_cleanup(&$items, $language) {

  // Check language for current menu depth.
  foreach ($items as $key => &$item) {
    $menuLinkEntity = MY_MODULE_load_link_entity_by_link($item['original_link']);

    // Ignore if we don´t have a menu object.
    if ($menuLinkEntity != NULL) {
      $languages = $menuLinkEntity->getTranslationLanguages();

      // Remove links with different language than context.
      if (!array_key_exists($language, $languages)) {
        unset($items[$key]);
      }
      // Recursive call until no more below items exists.
      else if (isset($items[$key]['below'])) {
        MY_MODULE_menu_item_cleanup($items[$key]['below'], $language);
      }
    }
  }
}

function MY_MODULE_load_link_entity_by_link(MenuLinkInterface $menuLinkContentPlugin) {
  $entity = NULL;

  if ($menuLinkContentPlugin instanceof MenuLinkContent) {
    list($entity_type, $uuid) = explode(':', $menuLinkContentPlugin->getPluginId(), 2);
    $entity = \Drupal::service('entity.repository')->loadEntityByUuid($entity_type, $uuid);
  }
  return $entity;
}

```
> 1 votes

# Answer
Another solution which I use at the moment is the module Menu Multilingual. You get multilingual options on each menu block:

And with the selected option the menus only consist items with translations in the current language or with neutral language settings.
> 0 votes

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


title: How do I update custom form Data

text:
# Question
Title: How do I update custom form Data
I have built a custom form in Drupal 7 it has three fields nid, uName, Email. When I submit my form it stores all the details in a database. And also all the submissions of form I have displayed on the different page. Now I want to update data of each row as according to the user, which row he selects. Can anyone help me?

# Answer
> 0 votes
No code provided... but you would need to pass the record id to the form builder as an argument and fetch the record from the database.

At a basic level:

```
// the caller
$form = drupal_get_form('myform', $record_id);

// in the form builder...
function myform($form, &$form_state, $record_id) {
  // db query the table for that record id
  // populate form default values if record found

  // example
  $form['email']['#default_value'] = $query_result ? $query_result['email'] : NULL;
}

```

Although, if you have no unique primary key, this could be next to impossible to select the proper row (knowing nothing more about your requirements).

How are you preventing duplicates? How would you know what row to select? Are you preventing more than one email per nid submission? That would be up to you to figure out, I suppose.

You could also pass the record id as a URL argument and pass that along to the form builder callback, but this would not limit it to the user who *should* be able to edit it (unless you build in access checks etc). That means anyone could just change the url argument and load up another record.

In any case, the code above should get you started.

---
Tags: 7, forms
---


# Question
Title: Installing D8 using composer, with LAMPP destination is unclear
Documentation is unclear about the final destination of site. XAMPP looks for site in opt/lampp/htdocs, do I run composer from here? If so will it then create a dir called web with drupal inside that dir? -OR- Do I simply run composer and use the created web dir to hold the files and then manually copy the data to htdocs dir? (this seems wrong) -OR- Do I tweak xampp to look elsewhere for the drupal dir

Previously I unzipped, copied drupal folder to htdocs dir.

# Answer
> 1 votes
Run your composer install command from opt/lampp/htdocs and put a . at the end to tell it to install in the current directory and that should do the trick e.g.

```
composer install drupal/drupal .

```

---
Tags: installation, composer
---


# Question
Title: How to clear CSS and Javascript with a bookmark?
I would like to clear the CSS and javascript in D7 with the help of a bookmark.

Currently this is:

```
<domein>/admin_menu/flush-cache/assets?token=<tokenid>

```

This is working however the tokenid is changing all the time. It there a easy solution for this so I don't have to change the tokenid in the bookmark every time?

# Answer
In a custom module add a menu item (Using hook\_menu) to function with this code:

```
drupal_clear_css_cache();
drupal_clear_js_cache();

```

Then you can just bookmark your custom page url. Or set a cron job to call that page at regular intervals if thats what you're after
> 1 votes

---
Tags: caching
---


# Question
Title: Trigger views exposed filter on custom select box
I have this view which contains an exposed filter to filter out a simple content type listing page. The problem is about theming and keeping the view functional. I succeeded in theming the view with a select filter, as provided to me in a static html file.

The filter is select box but the theming have it's proper tags that works similar to a select box model. For example:

```
<!-- Basic select box in Drupal -->
<select data-drupal-selector="edit-filterone" id="edit-filterone" name="filterone" class="form-select">
  <option value="All" selected="selected">- Any -</option>
  <option value="13">term 1</option>
  <option value="15">term 2</option>
  <option value="16">term 3</option>
</select>

<!-- Our themer select box model -->
<custom-select label="Filter label" name="filterone">
  <custom-option label="- Any -" name="filterone" value="All" selected></custom-option>
  <custom-option label="term 1" name="filterone" value="13"></custom-option>
  <custom-option label="term 2" name="filterone" value="15"></custom-option>
  <custom-option label="term 3" name="filterone" value="16"></custom-option>
</custom-select>

```

Then the value selected get stored in a JS object.

In this view I use BEF (Better exposed forms) module and autosubmit is activated with a hidden apply button.

Using twig suggestions I can populate the select list with the filter values but there is no action trigged when I change the item.

The view is not applied and it act just like a static html. I need a way to keep the filter functional as normal.

I can get the values with js when a select list change but I don't know (or have a clue) how to send these values by ajax and alter the view and get back the results as normal views do.

My first thought is to keep the select boxes provided by drupal and just hide them from display and when the user changes value in the 'fake' select box, have them copied to the hidden one; and then just trigger the click on the (hidden) apply button.

Any suggestions please? (I don't know if my explication is that clear but I can be more specific if needed, thank you)

# Answer
I managed to achieve that result I had thought of. Adding same filter in hidden display and just assign new values to it when the fake select box changed; then trigger the apply button. I had little problems with 'all' value because I was parsing the selected values before reassign them.
> 0 votes

---
Tags: 8, views
---


title: Rendering node fields in another region

text:
# Question
Title: Rendering node fields in another region
my content type contains several fields; body, field\_meta\_tags, field\_image, field\_date, etc.

In node.html.twig, using the without filter, I can replace the standard rendering of `{{ content }}` with `{{ content|without('field_image') }}` and all of the content, less the image, will display.

How can I expose this variable to another region and render the image through a different template, perhaps region--hero-image.html.twig?

Thanks!

# Answer
> 6 votes
Easiest way to do this is create a View with a block display, and set the node ID as the contextual filter. The output of the View should be "Content" and a view mode - this view mode can be set with its own twig template in the theme. You can add a view mode at `Admin > Structure > Display Modes > View Modes`, then go to whatever content type you need it for and configure the display. On the view mode, you can pick and chose what fields should display and what formatters they use.

Here is a good write up detailing it, and a YouTube video walking through view modes and what they are.

Once the View is created, you can place the block in the block admin, and set its visibility settings to only show on your content type(s) that you configured.

# Answer
> 1 votes
I found some code here: What's the best practice to show a node's fields in different regions? Placed this in my `[theme_name].theme` file:

```
function THEME_preprocess_region(&$variables) {
  //TODO: change for you region name
  if ($variables['region'] == 'sidebar_right') {
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      //TODO: change for you node type
      if ($node->getType() == 'article') {
        //If you need a flag for this type
        $variables['is_article'] = TRUE;
        //Here is your field
        $variables['node_field'] = $node->get('field_descricao')->view();
      }
    }
  }
}

```

With

```
{% if node_field %}
  {{ node_field }}
{% endif %}

```

Placed in `region--footer.html.twig` (or the equivalent for whatever region you declared above). Obviously, `field_descricao` is the field you are rendering and `node_field` is whatever you wish your new variable to be.

This returns a link to my content (which is no longer an image but a node reference). I'm still looking for a way to render the full content, but this is closer than I was.

Any additional insight greatly appreciated!

# Answer
> 1 votes
Check out the experimental "Chaos Tools blocks" module, part of Drupal 8.3+. There is no documentation for it at all right now, but it's pretty easy.

* Enable Chaos Tools blocks module
* Create a display mode as discussed above. Set it to show only the field you want.
* In Block Layout -\> Place Block, choose Entity View and configure as desired.
* I had to add a little custom css to keep the title from showing up. Something like .node--view-mode-display\_mode\_name { header {display: none;" }

---
Tags: theming, 8, entities
---


# Question
Title: In Behat How to Stage Link References in Table Nodes
I have a Link field on an article that allows both internal paths and external URLs. How can I stage that type of content in the table node for the article?

(machine name: field\_url)

I tried to use:

```
| field_url:title | field_url:uri |
| Test            | http://a.com  |

```

But the link Handler throws an error because when you use that format the array keys are 'title' and 'uri' instead of numbers based. (If I change LinkHandler to use the keys it actually works, but obviously breaks other things.)

As for the internal content, I've done entity reference before and they've worked on regular entity reference fields. But when I do something like:

```
Given "article" content:
| title                  | body       |
| Test Reference Article | Test body. |
And "event" content:
| field_url              |
| Test Reference Article |

```

The database gets populated with: field\_url\_uri = e field\_url\_title = T

Has anyone made this work?

# Answer
This article from nuvole.org helped me resolve the same issue you describe. From the article:

> A Link field in Drupal offers quite a wide range of options, such as an optional link title or internal/external URLs. We can use the following notation to work with links in our test scenarios:
>
> ```
> When I am viewing a "post" content:
> | title       | Post title                                              |
> | field_link1 | http://nuvole.org                                       |
> | field_link2 | Link 1 - http://nuvole.org                              |
> | field_link3 | Link 1 - http://nuvole.org, Link 2 - http://example.com |
>
> ```
>
> As you can see we use always the same pattern: a dash - to separate parts of the same field value and a comma , to separate multiple field values.

The one note that I would add to the article is how to handle a link that has a URL, but not a title. To handle that scenario, I used the following format:

```
When I am viewing a "post" content:
| link_with_text    | My link text - http://url.com |
| link_without_text | '' - https://google.com    |

```
> 1 votes

---
Tags: testing
---


# Question
Title: How to check user has permission special node
I following topic https://atendesigngroup.com/blog/custom-permissions-node-access-grants-drupal-8-and-drupal-7 to create custom permissions for node. It's working ok. Example I can edited node 1 with url: example.com/node/1/edit/. I wan't check user have permission edit node by code eg:

```
node_access('view', $node);

```

and Drupal 8

```
$node = Node::load(1);
$account = User::load(1);
$check = $node->access('edit', $account);

```

But It don't working. So how can check permission of special node?

# Answer
Just tested this and `$node->access('update');` works for me. I let the optional $account parameter out so that it would check the currently logged in user.

The only difference was that I loaded my node with:

```
\Drupal\node\Entity\Node::load($nid);

```

To just use `Node::load($nid);` Make sure to include:

```
use Drupal\node\Entity\Node;

```

at the top of your file.
> 1 votes

# Answer
As Rubix05 mentions, the issue is that you are testing "edit" access when you should be testing "update" access.

```
$node = Node::load(1);
$account = User::load(1);
$check = $node->access('update', $account);

```
> 0 votes

---
Tags: 8, users
---


# Question
Title: On content edit, how can I check/select a bool field based on which tab is active?
I have a content type with a paragraph that has two fields, each field inside its own tab controlled by the form display like so:

Here is what the set of tabbed fields looks like when editing a piece of content of the content type:

The paragraph also has a bool field called field\_active\_callout\_tab with two values: 'Single' and 'Multi', same as the tabs.

If the 'Single' tab is clicked, I want the bool to be checked. If the 'Multi' tab is selected, I want the bool to be unchecked.

I tried to use the Conditional Fields module, but it will not allow control by tab label. How can I establish this dependency between the tab and the bool?

# Answer
You can do it with jQuery, something like this should do it:

```
$('.single-class').click(function () {
    $('.bool-class').prop('checked', true);
});
$('.multi-class').click(function () {
  $('.bool-class').prop('checked', false);
});

```
> 1 votes

---
Tags: 8, theming, entities, javascript
---


# Question
Title: Can I control the weight of a library loaded through a theme preprocess function?
I have a base theme that loads several libraries, some through the libraries.yml file and some loaded conditionally in a preprocess function. I also have a base theme with its own library loaded through libraries.yml.

This is the order they are loading in:

1. Libraries loaded in base theme's libraries.yml
2. Libraries loaded in sub theme's libraries.yml
3. Libraries loaded in base theme's preprocess function

This is a problem because I need to override some CSS from the libraries loaded in the base theme's preprocess function in my subtheme. I want it to load like this:

1. Libraries loaded in base theme's libraries.yml
2. Libraries loaded in base theme's preprocess function
3. Libraries loaded in sub theme's libraries.yml

They are loading in that order regardless of the CSS weights defined in the libraries file (base, theme etc.).

Is there anything I can do about this? This is the relevant code from the base theme, used in hook\_preprocess\_html().

```
  if (\Drupal::moduleHandler()->moduleExists('module')) {
    $variables['#attached']['library'][] = 'basetheme/library';
  }

```

Will libraries loaded through a preprocess function always load later than the libraries loaded through libraries.yml? Are there any resources that explain this? And as an aside, where would libraries loaded through twig go?

# Answer
> 3 votes
Can you define your subtheme's library as extending or overriding your base theme's library. You'd have to do that in your subtheme's `.info.yml`. I think that should work. I think if you went this route you would just have a `.css` file in your subtheme that entends -- gets added whenever -- your basetheme's library is loaded. In this case you're override wouldn't be a "library" in your subtheme. Drupal should be smart enough to load your css file whenever the basetheme's library is loaded.

---
Tags: theming
---


# Question
Title: Calling ajax function from jquery on change event
Would appreciate help on a design strategy.

On a form I have an auto complete text field that I would like to populate with two separate values based on a radio button selection.

Currently the first radio button is loaded via an ajax call on load via hook\_menu.

```
function hook_menu() {
$items = array();

$items['module/state_autocomplete'] = array(
        'page callback' => 'state_autocomplete',
        'access arguments' => array('create states'),
        'type' => MENU_CALLBACK,);

```

Can I attach an ajax call to an on change event that will reload the text field without reloading the page?

For example:

# Answer
> Can I attach an ajax call to an on change event that will reload the text field without reloading the page?

If that's your question, then the answer is yes, you can.

If you meant to ask how to do that, then please refer to Ajax Forms documentation for Drupal 8 or Drupal 7.

If you hit any problem when implementing it, then come back giving us the details of specific issue as provided information does not describe what the problem is.
> 1 votes

---
Tags: javascript, ajax
---


title: How to view the user's status?

text:
# Question
Title: How to view the user's status?
I copied the twig file from the user view in my theme.

I want to display:

* "Online" if the user is logged in.
* "Absent" if the user has not had any activity for more than 15 minutes.
* "Offline" if the user is disconnected.

How to do this with twig ?

```
{#
/**
 * @file
 * Default theme implementation to present all user data.
 *
 * This template is used when viewing a registered user's page,
 * e.g., example.com/user/123. 123 being the user's ID.
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 *   print a subset such as 'content.field_example'. Fields attached to a user
 *   such as 'user_picture' are available as 'content.user_picture'.
 * - attributes: HTML attributes for the container element.
 * - user: A Drupal User entity.
 *
 * @see template_preprocess_user()
 *
 * @ingroup themeable
 */
#}
<article{{ attributes.addClass('user--comment') }}>

  <div class="row">

    {{ content.user_picture }}
    {{ user.label }}

    {% if logged_in %}
      <i class="user-online fa fa-circle fa-lg"></i> En ligne
    {% else %}
      <i class="user-offline fa fa-circle fa-lg"></i> Hors ligne
    {% endif %}

    <div class="bs-field-link">
      <a href="/profile/{{ content.personnel_profiles.0 }}" title="{{ user.label }}"></a>
    </div>

  </div>

</article>

```

The preceding code displays the status of the current user.

For example for comments I want to display the status of the author of the comment (not the node). I have this line of code in the comments twig file.

Can I reuse the code to obtain the status of the author of the comment ?

```
{{ drupal_entity('user', comment.uid.target_id, 'comment') }}

```

# Answer
You can't know if the person is behind its pc, reading the website but you can know the last access of the user (last time he done an http request to the site I suppose, load a page, submit a comment, etc, but I'm not totally sure about that). You need to look the property "access" of the UserSession.

For example, for the current user, the code is:

```
$session_current_user = \Drupal::currentUser()->getAccount();
$last_access = $session_current_user->getLastAccessedTime();

```

The property is a timestamp. You need convert if you want display it on you're site. So, you can now calculate when you considere your user Absent and determine after how many time you considere your user Offline. You can do all these calculation in your template.php file and used your results in your twig file.
> 1 votes

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


# Question
Title: How come there are different UUIDs for multiple environments?
We have D8 site where we use Configuration Management to export and deploy to multiple environments. We recently created a new content type, Blogs where we added a few fields (field\_url, field\_country). When we export this in our local development environment it all exports to yml files.

When we push these configurations to our Dev and Test environment we are seeing that they are out of sync even after running `drush @env cim`. Doing further analysis we found that the UUID is different and causing the issue.

However even if we were to export the configuration from Dev environment into our local ones, we still see that the UUID is different.

The settings.php already contains `$config_directories['sync'] = 'path/to/config-folder';`

How can we get the UUIDs to be in sync? We don't have this issue with other content types nor fields.

# Answer
> 2 votes
The right way to do it is to create a `config_sync` folder, you can set it like this in the settings.php file.

```
$config_directories['sync'] = 'path/to/config-folder';

```

Then you can run `drush cex` to export current configuration, and run `drush cim` to import. I am doing this on all my drupal sites and have never ran into any issues.

You shall commit the config files if you are using git so you can import them on production.

UPDATE: As it is described on drupal.org the full export, on the config page is only to use if you move from one copy of a site to another.

> Or the full site configuration can also be dumped as yml files to a tar.gz file. This only works if you're moving configuration between two copies of the same site (e.g. development and production) and for that reason the sites UUIDs must match.

Try to use the drush cex command instead.

---
Tags: 8, configuration, entities
---


# Question
Title: Setup on GoDaddy / Addon Domain "403 Forbidden Access Error"
I currently have a working Drupal Commerce site up and running. This site is on a godaddy / cpanel server. This site is on an addon domain and sits in the following server directory:

```
home/.../public_html/siteX.com

```

I have the modules / configuration working well and want to use this base code to operate a second Commerce site, primarily to reduce my base code maintenance. (I am fairly new to Drupal and have built two sites for our family's small business. Pretty fun :)

I read a ton about setting up multi-sites that convinced me it would be fairly straightforward. Here's what I have done:

* Created a new database on the server. Assigned my "user" to that database with all admin privledges
* Created a new directory under the working Drupal Commerce site home/.../public\_html/xxxxx.com/sites/siteY.com
* Pointed my "addon" domain to the Document Root above
* Copied my default.settings.php into /public\_html/xxxxx.com/sites/siteY.com
* Renamed to settings.php with the database login information
* Set my /siteY.com directory and settings.php to "777" permissions

When I navigate to "siteY.com", I keep getting a 403 error:

> Forbidden You don't have permission to access / on this server. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

If I navigate to "siteY.com/install.php, I get a different permissions error msg:

> Internal Server Error
>
> The server encountered an internal error or misconfiguration and was unable to complete your request.
>
> Please contact the server administrator at webmaster@ to inform them of the time this error occurred, and the actions you performed just before this error.
>
> More information about this error may be available in the server error log.
>
> Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

Is it an issue to create a multisite from an add-on domain? What am I missing here? Should I jump ship and use the "Domain Access" module?

# Answer
> 0 votes
## Solved## Successful installation completed :)

When setting the Directory Root for the "multisite" SiteY.com addon domain, I got it wrong.

```
Incorrect: home/.../public_html/xxxxx.com/sites/siteY.com

Correct: home/.../public_html/xxxxx.com/

```

With the correct option, you point to the site that contains the code based you want to pull from, as well as the index.php file.

I don't fully get the mechanics at play here, but am thankful to be on the other side.

# Answer
> 0 votes
After migrating my site from an old hosting account to Linux cPanel hosting with GoDaddy, the site was working temporarily and then suddenly throwing 403 error the next morning. I had not made any changes to the files. After reading Alfred Armstrong's comment below, I checked the Drupal root directory for the index.php file ... somehow it had been changed to index.htm. No idea what happened here unless someone on the GoDaddy side opened and re-saved the file. I renamed to .php and site is up again. Very strange but thanks for pointing me to the solution!

---
Tags: commerce, multi-sites, subsites
---


title: Running Drush Launcher on Windows

text:
# Question
Title: Running Drush Launcher on Windows
When I run Drush in the command line on my Windows 10 computer or Windows Server 2016 servers, I get the following error:

```
drush : The term 'drush' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ drush
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (drush:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

```

I've downloaded drush launcher and made sure that it was located in my PATH. Why is this error message showing and how do I get passed it?

# Answer
The error message occurs because the command must be `drush.phar` and prefaced by the `php` command. In the same folder as Drush Launcher, you'd have to run `php drush.phar` to get it to work. Elsewhere, you'd have to run `php /path/to/drush.phar` (which can be just as, if not more, annoying that `vendor/bin/drush`).

To get it to work, create a folder called `drush.bat` in the same folder as `drush.phar` and include the following two lines of code:

```
@echo off
php %~dp0\drush.phar %*

```

This file is executed by the command `drush` since it is in your PATH and will then execute the proper `php` command passing the correct parameters. You'll then be able to run drush from anywhere on your computer.
> 3 votes

# Answer
Did you change the file name of drush.phar to just drush? After that put it in your path.

I just got it working for me on windows 10. I downloaded drush.phar from: https://github.com/drush-ops/drush-launcher/releases/tag/0.6.0

Then I changed the name of the file to just drush and put it in my system and user path and now I can call drush from composer built drupal site.
> 0 votes

---
Tags: drush
---


# Question
Title: How to get Drush in my path in Windows 10?
I have Drush 9 installed on Windows 10. I installed it via Composer using Lando.

**I want to put this drush in my system path so that I can use it from cmd.exe, Powershell, and so on.** I want to do this because I am trying to run Drupal Behat Extension tests with the Drush driver, which requires drush to be in the path.

**What I tried**

Windows 10 Control Panel -\> System -\> Edit environment variables

Under "User variables for MYUSERNAME", I added:

* Variable: LANDO\_FRIENDS
* Value: C:\pathtowebsiteinstalledbycomposer\vendor\bin

Then I rebooted and tried to run drush:

> drush : The term 'drush' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

So then, from PowerShell, I changed to the `\vendor\bin` directory and ran `./drush`. This opened up a prompt **How do you want to open this file?**

I don't understand why this is happening.

Here's what does work:

* I can run drush from Powershell using lando, i.e., `lando drush status`.
* I can open up a bash shell with the Windows Linux Subsystem and go to `/vendor/bin` and enter `./drush`, which causes drush to load normally.

So drush is definitely installed, but how do I use it from Powershell/cmd.exe?

# Answer
> 1 votes
The variable will be "Path". Just select that one and edit it then add new line.

You have to download the drush.phar file from here: https://github.com/drush-ops/drush-launcher/releases/tag/0.6.0

Then you have to change the file name from 'drush.phar' to just 'drush' and put that file somewhere and that location needs to be in your path. I put mine in both my system path and user path. Once that is done you shoud be able to call drush from your drupal directory if it was installed with composer.

---
Tags: drush
---


# Question
Title: How restrict a constraints to a content type?
I would like to create validation for a several fields on a content type to check if they each have unique values from each other. The part I'm struggling with is how to add the constraint for just my content type, and not all node entities. So far I'm using `hook_entity_type_build()` to add: `$entity_types['node']->addConstraint('UniqueSizes', []);` Is there a way to restrict this to only my content type?

# Answer
No, it's not directly possibly when adding the constraint.

But you can always check the bundle or existence of certain fields (in some places preferable, if you ever need another node type with those fields and the same logic) within your constraint when it is run.
> 1 votes

# Answer
This is how I'm doing the content type validation:

In the hook\_entity\_type\_alter I add the constrain.

```
/**
 * Implements hook_entity_type_alter().
 */
function onlyone_entity_type_alter(array &$entity_types) {
  $entity_types['node']->addConstraint('LockedLanguages');
}

```

And in the Validator I check the content type.

```
/**
 * Validates the LockedLanguages constraint.
 */
class LockedLanguagesConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($node, Constraint $constraint) {
    // Getting the configured content types.
    if (in_array($node->getType(), ['page', 'article']) {
      // Some code is removed to do this easy to read.
      $this->context->addViolation($constraint->nodeExists, $values);
    }
  }

}

```
> 1 votes

# Answer
If you need to add constraints to fields added to a bundle, you can implement `hook_entity_bundle_field_info_alter()`, which gets the bundle as last parameter.

Keep in mind that, once the changes in Finalize API for creating, overriding, and altering code-defined bundle fields are committed, code implementing `hook_entity_bundle_field_info_alter()` would probably need to be changed.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Why a unnamed <div> is added to a specific region?
I have 2 blocks in a region (*headline*). Drupal 8 seems to add these 2 blocks into an unnamed div and thus their `display:flex` CSS layout is cancelled. (You can't scatter 2 container items if these are wrapped into one `<div>`.)

I might need to note that the template markup also doesn't contain such HTML element.

The markup for the region is the following one.

```
<div id="headline">
<div class="container">
{% if page.headline %}
     {{ page.headline }}
{% endif %}
</div>
</div>

```

The CSS code I used is the following.

```
#headline . container {
  display: flex; flex-direction: column; align-items: center
}

@media screen and (min-width: 1080px) {
  #headline .container {
    display: flex; flex-direction: row; justify-content: space-between; align-content: flex-start; flex: 1; margin: 0 auto
  }
}

```

>

# Answer
> 3 votes
Checkout **Twig Debug** to see where the template is coming from.

https://www.drupal.org/docs/8/theming/twig/locating-template-files-with-debugging

https://sqndr.github.io/d8-theming-guide/twig/twig-debug.html

It will wrap the template with HTML comments telling you where to find it relative to the website root.

Some of the `<div>` tags provide containers for applying attributes to for things like **contextual links** and **quick edit**, so be cognizant of that when removing them when they have `{{ attributes }}` printed in them. Those CSS class attributes and data attributes are only are filled when those modules are enabled.

# Answer
> 4 votes
It could be coming from region.html.twig:

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21region.html.twig/8.2.x

# Answer
> -2 votes
```
{% if content %}
  <div{{ attributes }}>
    {{ content }}
  </div>
{% endif %}

```

```
{% if content %}
  <div{{ attributes != '' }}>
    {{ content }}
  </div>
{% endif %}

```

---
Tags: theming, 8
---


# Question
Title: How do I include JavaScript on a single page in a way that is amenable to scale
I've read through a bunch of material about using JS in Drupal 8 theming and module development, but did not come away with an understanding of the most straightforward way to routinely add things likes GSAP animations and interactive D3 charts to individual nodes.

Each piece of custom JS will only ever be needed on one page. Over time the site may grow to include 10s or even 100s of such pages.

From reading the module development documentation, creating a custom module and adding each JS file to the myModule.libraries.yml with logic to load each on only one page based on id would work, but before I start down that path I thought I'd ask if there is some other way to do this.

# Answer
Following Steps will make working with External JavaScript libraries in Drupal 8 absolutely clear (including how to conditionally load it in specific pages):

**Step 1:** Place the JavaScript file in your theme or module inside a folder called js. After this step your folder structure must look like :

```
my-theme/js/my-script.js

```

**Step 2:** If your theme already has a my-theme.libraries.yml file open it, if not create it.

In Drupal 8 Libraries are simply collections of CSS or JS files bundled together under a uniquely identified library name.

In this step we need to include the JS file that we created in step 1 in our library. we do it by adding following lines of code in our my-theme.libraries.yml file.

```
my-library:
  js:
    js/my-script.js: {}

```

Now we have an asset library called `my-theme/my-library` which can be loaded to our site in several ways.

**Step 3:** Final step is to load the library in our site. This can be done in 4 specific ways:

*Way 1:* Attach library globally via theme-name.info.yml file

Libraries can be specified in the theme-name.info.yml file by adding it to the libraries property, like this:

```
name: my-theme
type: theme
description: my theme
package: other
core: 8.x
libraries:
  - my-theme/global-effects
  - my-theme/my-library

base theme: stable

```

Any libraries specified here in the themename.info.yml file will be made available on evey page.

*Way 2:* Using hook\_page\_attachments\_alter in theme-name.theme file.

Following lines of code will attach our library only to the node listing page.

```
function mytheme_page_attachments_alter(&$page){
  $path = $current_path = \Drupal::service('path.current')->getPath();
  if($path == '/node') {
    $page['#attached']['library'][] = 'my-theme/my-library';
  }
}

```

*Way 3:* Another useful way to conditionally add a library is by using a preprocess function like hook\_preprocess\_page().

Here's another example of restricting our asset libray to the front page

```
function mytheme_preprocess_page(&$variables){
  if ($variables['is_front'] == TRUE) {
    $variables['#attached']['library'][] = 'my-theme/my-library';
  }
}

```

*Way 4:* Asset libraries can also be attached from within a Twig template using the attach\_library function. Anytime that template is used the corresponding library will be attached in accordance with any template-specific conditions.

In order to see this in action, we need to create or modify a template in our theme. In this example let us modify node.html.twig template to attach our library only if node.id == 1 with following lines of code

```
{% if node.id == 1 %}
  {{ attach_library('my-theme/my-library') }}
{% endif %}

```

With this in place, visiting node 1 in our site, we will be able to see our library in action.
> 39 votes

# Answer
See: https://www.drupal.org/developing/api/8/assets

Quote from page:

> **Attaching a library to page(s)**
>
> Depending on which assets you need to have loaded, you'll want to attach the corresponding asset library in a different way. After all, some asset libraries are needed on all pages, others only very rarely, and yet others on most, but not quite all.
>
> But what matters most is that we don't decide whether to attach a library based on which page we're on (i.e. which URL or route), but based on which things are visible on the page: if a page contains a '#type' =\> 'table', a '#type' =\> 'dropbutton' and a '#type' =\> 'foobar', then we'll only load the libraries associated with each of those '#type's. But we're not limited to '#type' only: perhaps we want to load a certain asset library only for a certain instance of a '#type'. In that case, we just attach it to the render array of that instance.
>
> Of course, very rarely, there is a valid reason to actually load a certain asset on all pages (e.g. some analytics JavaScript that tracks page loads), regardless of the "things" on a page.
> 3 votes

---
Tags: 8, javascript
---


# Question
Title: How to change the value of a row in views
I've views formatted as table with a pager of 10 items pr page, in which I've a field called type, depending on that type, I need to modify the other field, show text.

I've tried using PHP global field, but when I put that it is not showing the checkboxes from the second page.

I've tried hook\_views\_pre\_render, but did'nt see any good example to change the field.

# Answer
> 0 votes
You could try using Views Conditional

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> * Equal To
> * Not Equal To
> * Greater Than
> * Less Than
> * Empty
> * Not Empty
>
> Views conditional allows you to output text based on the result of the condition.

As per the readme.txt

> How to use Views Conditional:
>
> 1. Create a view. Add some fields under "FIELDS".
> 2. Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list.
> 3. Add and configure fields...
> 4. Choose a field to run a condition against, and provide values accordingly.
> 5. Save, views conditional handles the logic and returns as specified.

---
Tags: views
---


title: hook_node_validate doesn't work

text:
# Question
Title: hook_node_validate doesn't work
I have a new type of content **project**.

I allowed an anonymous user to add project content in /node/add/project.

I want to add a test before saving node (like the **hook\_form\_validate** of webform)

I use **hook\_node\_validate** but it's not working

```
function projects_node_validate($node, $form)
{
  die 'in hook';
}

```

If this is the right hook, how can I use it?

Thank you

# Answer
> 1 votes
Should work fine as long as your module name is "projects"

Did you clear all the site caches after adding the code. Drupal won't detect and start using that hook until you have

---
Tags: 7, nodes, hooks
---


title: Dependency injection to load node data

text:
# Question
Title: Dependency injection to load node data
When I checked the code I wrote with `phpcs --standard=DrupalPractice /path/to/myController`, I got the following warning.

> WARNING | Node::load calls should be avoided in classes, use dependency injection instead.

The code I use to load the node is the following.

```
use Drupal\node\Entity\Node;

public function content_load($node = NULL) {
 $noad_data = Node::load($node, NULL, TRUE);
}

```

How should I use dependency injection to load a node?

# Answer
The controller base class provides the method `entityTypeManager()` which gets the service with the same name from the container the first time you use it. You can use this service to get the node storage:

```
  $node_storage = $this->entityTypeManager()->getStorage('node');

```

and then load the node:

```
  $node = $node_storage->load($nid);

```
> 22 votes

# Answer
This is how I injected the entity type manager to load nodes into a block (where the nodes to load didn't come from the block context):

```
<?php

namespace Drupal\MYMODULE\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Provides a 'My Block' Block.
 *
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block"),
 * )
 */
class MyBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new MyBlock.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    $node_storage = $this->entityTypeManager->getStorage('node');

    $node = $node_storage->load(1);

    return [
      '#markup' => $node->getTitle(),
    ];
  }

}

```
> 16 votes

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


# Question
Title: Feeds: How to import images using Xpath Parser for XML?
I am using the Feeds module for XML import. I have created entity type with the Image as a text field. I need to import an image from XML and have it shown on the page. My XML is like this:

`<Auditor>
 <Ref>RIP.jpg</Ref>
</Auditor>`

I imported the name from XML using Xpath Parser, but I'm unable to display it on the page because of a path that is not mentioned.

How should I set absolute path or display image on the front?

Thanks in advance.

# Answer
Importing images into a multi-valued image field using image URLs from an XML file is not working for me. The debug output shows the image URLs being parsed correctly, but the images don't get imported.

The XML structure is:

http://www.example.com/files/content/villa-102-1.jpg http://www.example.com/files/content/villa-102-2.jpg

The context is: //unit The Xpath query for the image field is: unit\_details/images/image/uri

I played around with the image grabber module for feeds, but it failed also.

I was able to import images using the CSV importer and the image URL, so this appears to be a problem with Xpath Parser, not Feeds.
> 0 votes

---
Tags: 8, feeds
---


# Question
Title: Drupal 8 - taxonomy term field without "title" attribute
I have a simple view block with exposed the taxonomy term linked to the taxonomy page, but I have noticed that the attribute is missing, I tried to rewrite the term but every attempt went wrong.

What I need is simple, this is the view generated field:

```
<a href="/category/events" tabindex="-1">Events</a>

```

I want to add `title="Events"`, like this:

```
<a href="/category/events" tabindex="-1" title="Events">Events</a>

```

But I can't find any solutions in Drupal 8 view!

# Answer
> 0 votes
You should be able to use template\_preprocess\_views\_view\_field to accomplish this. Create that hook in your custom theme like:

```
/**
 * Alter field_MY_TAX_FIELD link to add title attribute.
 *
 * Implements template_preprocess_views_view_field().
 */
function MY_THEME_preprocess_views_view_field(&$vars) {
  if ($vars['field']->field == 'field_MY_TAX_FIELD') {
    // Add title attribute to link.
  }
}

```

Alternatively you could create a new field formatter that extends Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceLabelFormatter. Override the `viewElements` method. First call `$elements = parent::viewElements($items, $langcode);`, then traverse `$elements` and add your title attribute when appropriate. After you create the formatter, clear cache and then go back to your view and select your new formatter as formatter for the taxonomy field.

---
Tags: views, theming
---


# Question
Title: I can't get hook_form_alter or hook_form_FORM_ID_alter to add placeholder text to the search input
I know this has been asked but so far none of the accepted answers for this issue are working for me. I am attempting to add placeholder text to the default search form block. I am using a theme we'll call MyTheme, which is a copy of Bartik and is otherwise working exactly as expected.

I have tried adding the following functions to MyTheme.theme:

```
function MyTheme_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['edit-keys']['#attributes']['placeholder'][] = t('Search');
}

```

And

```
function MyTheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        // Add placeholder text
        $form['keys']['#attributes']['placeholder'] = t('Search');
    }
}

```

And many, many variations on those. I have tried both functions with and without "\Drupal\Core|form..." included. I have tried both with 'keys' and 'edit-keys'. I have tried both with and without the empty '\[\]' after placeholder. Nothing has worked.

In every case, using hook\_form\_FORM\_ID\_alter simply fails to do anything at all, while using hook\_form\_alter causes a 'white screen of death'.

I don't understand what I'm doing wrong.

UPDATE: Now out of the blue Drupal has decided to change the id for the form input to 'edit-keys--2' for some reason. I've tried using that in the functions as well.

# Answer
> 2 votes
This is what eventually worked for me. Posting because other people seem to be having the same issue.

I placed this at the very end of the MyTheme.theme file.

```
/**
 * Add placeholder text to the search forms.
 */
function MyTheme_form_search_block_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['keys']['#attributes']['placeholder'] = t('Search this site...');
}

```

Hopefully this will be helpful for some.

# Answer
> 1 votes
So, I've tried this on my local install and had the exact same issue.

Please try changing `$form['keys']['#attributes']['placeholder']` to `$form['keys']['#title']`

Your function would be -

```
function MyTheme_form_search_block_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['keys']['#title'] = t("Search");
}

```

---
Tags: 8, forms, hooks
---


# Question
Title: Prevent path based breadcrumb in theme, or, don't show breadcrumbs for 403/404 responses?
I am looking to do one of these solutions for a users 'contact' page. When a user has unchecked "Personal Contact Form", and someone accesses that URL (user/id/contact), the breadcrumb displays the users username in the breadcrumb.

The username in the breadcrumb is not desirable, because some people make their email address their username, so:

* How can I disable the breadcrumb from displaying on 403/404 responses, or
* How can I disable the path based breadcrumb service outright?

# Answer
> 5 votes
You could add a visibility condition to the breadcrumb block. For 404 there is this module block\_in\_page\_not\_found and if you negate the condition the block is displayed on all pages other than 404's:

If you want to exclude 403 pages as well you can extend this module and add a check for

```
$status->getStatusCode() == 403

```

to Drupal\block\_in\_page\_not\_found\Plugin\Condition\PageNotFoundRequest::evaluate.

Or use the patch from this issue Allow blocks to be configured to show/hide on 403/404 pages, when it applies again.

---
Tags: 8, breadcrumbs
---


# Question
Title: How to translate a custom Constraint message?
I have a custom constraint in the Allow a content type only once (Only One) module that is working and is defined as:

```
<?php

namespace Drupal\onlyone\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that Only One node of locked languages exists.
 *
 * @Constraint(
 *   id = "LockedLanguages",
 *   label = @Translation("Locked Languages Constraint", context = "Validation"),
 *   type = { "entity" }
 * )
 */
class LockedLanguagesConstraint extends Constraint {

  /**
   * Message shown when a node of a locked language exists on a content type.
   *
   * @var string
   */
  public $nodeExists = "The content type %content_type is configured to have Only One node per language but the node <a href=':href'>@title</a> exists for the %language language.";

}

```

And I want to be able to translate the message, the problem is that you can't use the `t()` function in the property definition. How can I accomplish this?

# Answer
> 8 votes
The constraint system is one of the few places where string literals aren't directly wrapped in `t()`. One reason for this is probably because the variables which form the "context" and string replacements for the messages aren't directly available when defining the constraint. @see `\Drupal\Core\Validation\DrupalTranslator`.

So the answer is: core does this for you. You can see exactly where this happens in: `\Drupal\Core\TypedData\Validation\ExecutionContext::addViolation`.

# Answer
> 3 votes
The mystery is solved thanks to @dawehner on Slack.

Drupal handle this, in my case the problem was simple as see the site in another language and trigger the error, maybe I was a little tired to think in this possibility :-)

# Answer
> 1 votes
You're right, can't access the `t()` here.

Looking at an example from core:

*/core/modules/forum/src/Plugin/Validation/Constraint/ForumLeafConstraint.php*

```
class ForumLeafConstraint extends Constraint {

  public $selectForum = 'Select a forum.';
  public $noLeafMessage = 'The item %forum is a forum container, not a forum. Select one of the forums below instead.';

}

```

In */admin/config/regional/translate* I was able to find the `$noLeafMessage` was translated:

But nothing for `$selectForum`

This makes me believe that the only way is to add it directly to a .po file and then import at */admin/config/regional/translate/import*

### UPDATE:

If it's new, turns out the string will not show up for translation until you switch to another language. Which explains why `$selectForum` was not showing up.

# Answer
> 0 votes
Add the string translation trait to your class:

```
<?php

namespace Drupal\onlyone\Plugin\Validation\Constraint;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\Validator\Constraint;

/**
 * Checks that Only One node of locked languages exists.
 *
 * @Constraint(
 *   id = "LockedLanguages",
 *   label = @Translation("Locked Languages Constraint", context = "Validation"),
 *   type = { "entity" }
 * )
 */
class LockedLanguagesConstraint extends Constraint {

  use StringTranslationTrait;

  /**
   * Message shown when a node of a locked language exists on a content type.
   *
   * @var string
   */
  public $nodeExists;

  // Set the value of $nodeExists somewhere in your code

}

```

Also see this note from the string translation trait:

```
   * If the class is capable of injecting services from the container, it should
   * inject the 'string_translation' service and assign it to
   * $this->stringTranslation.

```

Which means you should implement ContainerInjectionInterface and have create and \__construct functions to do that injection, like this:

```
<?php

namespace Drupal\onlyone\Plugin\Validation\Constraint;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;

/**
 * Checks that Only One node of locked languages exists.
 *
 * @Constraint(
 *   id = "LockedLanguages",
 *   label = @Translation("Locked Languages Constraint", context = "Validation"),
 *   type = { "entity" }
 * )
 */
class LockedLanguagesConstraint extends Constraint implements ContainerInjectionInterface {

  use StringTranslationTrait;

  /**
   * The string translation service.
   *
   * @var \Drupal\Core\StringTranslation\TranslationInterface
   */
  protected $stringTranslation;

  /**
   * Message shown when a node of a locked language exists on a content type.
   *
   * @var string
   */
  public $nodeExists;

  public function __construct($options = NULL, TranslationInterface $string_translation) {
    parent::__construct($options);
    $this->stringTranslation = $string_translation;

    // You can set the value of $nodeExists here if you want.
    $this->nodeExists = $this->t("The content type %content_type is configured to have Only One node per language but the node <a href=':href'>@title</a> exists for the %language language.");
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('string_translation')
    );
  }

}

```

---
Tags: 8, entities
---


# Question
Title: How to set default values for daterange widget in baseFieldDefinitions
Everything is working in my code except the default values...

```
$rangedefaults['value'] = DrupalDateTime::createFromTimestamp(time());
$rangedefaults['end_value'] = DrupalDateTime::createFromTimestamp(time());

$fields['date'] = BaseFieldDefinition::create('daterange')
  ->setLabel(t('Date and time'))
  ->setDescription(t('When the activity takes place.'))
  ->setRequired(false)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'daterange_default',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setDefaultValue($rangedefaults);

```

What is the proper way to set default values for this widget?

# Answer
> 1 votes
I think the problem is just the date format. If you look at the `DateRangeItem` class's `generateSample` method, it uses the `DateTimeItemInterface::DATETIME_STORAGE_FORMAT` format to prepare both `value` and `end_value`. You probably just need to do the same:

```
$rangedefaults['value'] = $rangedefaults['end_value'] = (new DrupalDateTime())->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);

```

As an aside, since you're using the current time it feels like you might want the default value to be the time at which the entity is created. By setting it in the field definition, the default will always be the time you installed the field.

That might be what you want, but in case not, use `setDefaultValueCallback` instead, and add a method to the entity class which returns the default value.

---
Tags: forms, entities, datetime
---


# Question
Title: How do I modify a custom entity delete form?
I have a custom entity (*Possession*) which has a non-standard edit form. The route for the edit form is the following.

```
entity.possession.edit:
path: '/individual/{individual}/possession/{possession}/edit'
defaults:
  _entity_form: 'possession.edit'
  _title: 'Edit Possession'
requirements:
  _permission: 'access administration pages'
options:
  _admin_route: FALSE
  parameters:
    individual:
      type: entity:individual
    possession:
      type: entity:possession

```

That seems to work fine. Instead, the delete form doesn't work. When I click on *delete*, I get the following exception.

> Symfony\Component\Routing\ExceptionMissingMandatoryParametersException: Some mandatory parameters are missing ("individual") to generate a URL for route "entity.possession.edit\_form". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 182 of core/lib/Drupal/Core/Routing/UrlGenerator.php).

After a little bit of digging, I noticed that the *cancel* link on the delete form redirects users to the edit form, which needs those parameters. I ran into this problem with the List Builder page, but I just fixed it in the code for that page.

I tried to edit the PossessionDeleteForm.php file that was generated from Drupal Console. I added a `buildForm()` method.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildForm($form, $form_state);
  $entity = $this->entity;

  $form['actions']['cancel']['#url'] =  Url::fromRoute('entity.possession.edit_form', [
  'possession' => $entity->id(),
  'individual' => $entity->get('individual_id')->target_id,
  ]);
  return $form;
}

```

If I use `ksm()` to inspect the form, it seems it's setup correctly, but it doesn't change the thrown exception. I also tried adding the `getCancelURL()` method to the class with a basic URL, but it didn't fix the error.

```
public function getCancelURL() {
  return new Url('system.admin_content');
}

```

Next I tried the `urlRouteParamters()` method in the entity class.

```
protected function urlRouteParameters($rel) {
  $uri_route_parameters = parent::urlRouteParameters($rel);

  if ($rel === 'edit_form') {
    $uri_route_parameters['individual'] = $this->get('individual_id')->target_id;
  }

  return $uri_route_parameters;
}

```

That also didn't work. I have no idea what else to do here.

What is the correct way to redirect users to the edit form, when deleting the entity is cancelled?

# Answer
The relationship is the key of the url relationships, aka edit-form, not edit\_form. Try that in urlRouteParameters() and what you are doing should work.
> 0 votes

---
Tags: entities, forms
---


# Question
Title: How to use field variable (a term) from node in field.html.twig for page title
When viewing a node I want to display an associated vocab term field inline with the node. The vocab is called "field\_related". If I add {{ node.field\_related.entity.label }} to node.html.twig and view the node it outputs the term, but if I add the same print tag to my custom twig template field--node--title--topic.html.twig ("topic" is the content type name) it doesn't output anything. What do I need to do to get it so I can print node.field\_related.entity.label in field--node--title--topic.html.twig?

I've been trying various combinations of how to write the tag and fiddling with theme\_preprocess\_field but so far all I've gotten is a headache.

# Answer
> 2 votes
In a field template the parent entity of the field is stored in `element['#object']`, so you can access the taxonomy field of the node like this:

```
{{ element['#object'].field_related.entity.label }}

```

---
Tags: theming
---


# Question
Title: How does one see the specific structure of some variable?
I'd normally use `dpm($variableName)`, to drill down to the desired data, but I'm currently working on the `webform-mail.tpl.php` template file, which doesn't exactly allow that.

Most of the Drupal devs I've met seem to have this magical knowledge of how variable structures work, and I want to figure out how they found these things in the first place.

For example, I see people talk about structures like this: `$node->webform['components'][$key]['form_key']` all the time.

How do they find out what's contained inside $node-\>webform? Is it some functionality in the devel module, or is there an amazing piece of Drupal's documentation that I'm missing somewhere?

# Answer
Turns out there's a basic-level solution to this one (posting for future php-novices).

PHP has a function called `print_r()` which outputs a human readable version of a variable. If it's a giant array/datastructure like most of the objects in Drupal,

eg: `print_r($node->webform);` returns:

```
Array
(
[nid] => 7
[confirmation] =>
We'll be getting back to you as soon as we can. We're excited about the
possibilities and eager to find the solutions you need.

Looking forward to it!

[confirmation_format] => full_html
[redirect_url] => node/29
[status] => 1
...
)

```

and `print_r($submission);` returns:

```
stdClass Object
(
[sid] => 643
[nid] => 7
[uid] => 1
[is_draft] => 0
[submitted] => 1524082096
[remote_addr] => 172.68.142.158
[serial] => 282
...
)

```

It's not as fancy as using a real debugger, but it gives access to what I assumed was off-limits. I suppose I should give PHP more credit sometimes.
> 0 votes

# Answer
You can use kint in a template. Enable the devel and kint modules and you can call it right from your template: `{{ kint(node) }}`
> 0 votes

---
Tags: theming, webforms
---


# Question
Title: Composer update Drupal core, 8.5.1 to 8.5.2 Nothing to Install
I am running Drupal 8.5.1, with `php 7.2` and a new security update 8.5.2 was just released. Per the documentation, I should be able to update Drupal core with composer.

I ran the following command:

```
composer update drupal/core --with-dependencies

```

I keep getting :

> Nothing to install or update Generating autoload files Drupal\Core\Composer\Composer::preAutoloadDump Drupal\Core\Composer\Composer::ensureHtaccess

Has anyone have any luck updating a drupal site with composer? I usually update my Drupal sites manually but this is getting tiring. I do not trust drush for my updates.

# Answer
You can try to delete the `vendor` directory and the `composer.lock` file, and then run the update again.

UPDATE:

* You need to add the line "drupal/core": "~8.5.2" to the 'require' statement (or update it to whatever version you require).
* Then remove the drupal/core line from the 'replace' statement.
* Add the following line somewhere (at the end? I believe this should replace the existing repositories statement):

"repositories": { "drupal": { "type": "composer", "url": "https://packages.drupal.org/8" } }

Then delete the vendor and composer.lock, and try again.

It should work.
> 5 votes

---
Tags: 8, composer
---


# Question
Title: Apply conditionally an image style on an User Profile page
At the moment the module “Image Styles Rules” is only available for drupal 7, is there another way to apply conditionally an image style depending on the aspect ratio of the image (portrait or landscape) in Drupal 8? Specifically to be applied to the image profile of an user, on his/hers respective profile page.

# Answer
> 1 votes
This module auto image style, is also available for drupal 8.

It describes:

> Allows to apply an image style depending on whether the orientation of original image is portrait or landscape.

So it might be what you want.

---
Tags: 8, media
---


# Question
Title: PDOException: Incorrect decimal value for a field which is legitimately null
I am creating a new composite field type that represents financial debt information. Each field consists of several sub-fields for values such as *Amount owed, Interest rate, Repayment amount* etc. This field is added to a content type as a multiple-instance field and users can add an unlimited number of these items.

I have built the settings forms, widgets, validators and formatters and it all works great when I fill out all the fields and submit the node. The data is written into the custom field table OK and the values persist when the node is edited again. The multi-instance field creation works as it should.

The problem is that some of the sub-fields are optional, but if they are left empty then I get a PDO error when the node is submitted:

> PDOException: SQLSTATE\[HY000\]: General error: 1366 Incorrect decimal value: '' for column 'field\_cc\_repayment\_amount'

`repayment_amount` is an optional numeric sub-field. It is declared in the .install file like this:

```
    'repayment_amount' => array(
       'type' => 'numeric',
       'precision' => 11,
       'scale' => 2,
       'not null' => FALSE,
    ),

```

When I look at the database schema in my SQL editor I can see that `field_cc_repayment_amount` is declared as type `DECIMAL` with length `11,2`, the `Allow Null` checkbox is checked and the `Default` value is set to `NULL`.

I can run a manual SQL insert with the optional fields explicitly set to NULL and that works fine. So it doesn't seem to be an issue with the database table itself.

I can set the optional fields to have a default value of `0` which works but is really not ideal. First, I would prefer an unused value to be `NULL` rather than `0` since `0` is not a valid value for some of these fields - if they have a value it has to be between a preset minimum and maximum which I'm validating against, and if the value is `0` it fails validation. But if the value is `NULL` then it passes validation on the grounds that it is not being used at all.

Second, using `0` affects the UI for adding a new instance of the field - if all the sub-fields are blank then Drupal does not attempt to create a new field when the node is submitted. But if a default value is used then it assumes the user is submitting a new field instance and it triggers validation on all the other sub-fields making it impossible for a user to edit the node without creating a new field entry each time.

So the question seems to be: **How do I allow Drupal to accept NULL values when NULL values are a valid option?**

**UPDATE 2011-11-28 in response to *testinni***

I believe the field system is handling the actual saving of the data for me. The form for the field elements is defined in `hook_field_widget_form()` and include definitions like this:

```
$element['repayment_amount'] = array(
   '#type' => 'textfield',
   '#title' => 'Repayment amount',
   '#default_value' => $values['repayment_amount'],
   '#size' => 12,
   '#maxlength' => 10,
   '#number_type' => 'integer',
   '#min' => 1,
   '#max' => 10000,
   '#field_prefix' => '$',
   '#element_validate' => array('number_field_widget_validate', 'combofield_range_validate'),
   '#weight' => 35,
) + $element_base;

```

where `$element_base` is the prepopulated `$element` array that gets passed into `hook_field_widget_form()` which has field properties like `#field_name`, `#description`, `#title`, and `#required` filled in, and is used as a base for all sub-fields.

`#default_value` takes on any previously set value for a saved field, and will naturally default to NULL if it doesn't exist. I have also tried making an explicit check here and supplying NULL or '' as a fallback.

The `#element_validate` functions work, and once these have passed there is only one more hook before Drupal saves the field: `hook_field_presave()`. I'm using this to round the decimal value of the main `value` field. I copied this (along with much of the settings and widget forms) from `number.module` which provides the standard Drupal numerical input field types.

So for the sake of completeness, here are `hook_field_presave` and `hook_field_is_empty`:

```
function combofield_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if ($field['type'] == 'combofield_expense' || $field['type'] == 'combofield_debt') {
    // Let PHP round the value to ensure consistent behavior across storage backends.
    foreach ($items as $delta => $item) {
      if (isset($item['value']) && isset($field['settings']['scale'])) {
        $items[$delta]['value'] = round($item['value'], $field['settings']['scale']);
      }
    }
  }
}

function combofield_field_is_empty($item, $field) {
  switch ($field['type']) {
    case 'combofield_expense':
      $empty_check = array('name', 'value');
    break;
    case 'combofield_debt':
      $empty_check = array('value', 'interest_rate');
    break;
    case 'combofield_goal':
      $empty_check = array('name', 'date');
    break;
  }

  if ($empty_check) {
    foreach ($empty_check as $subfield) {
      if (!empty($item[$subfield])) return FALSE;
    }
    return TRUE;
  }
  return FALSE;
}

```

I wonder if I have to catch the submitted results in `hook_field_presave` and convert any empty strings to NULLs? I'll give that a go and report back.

# Answer
Can you post the code you use to fill-out the values of your columns ?
I suspect you're passing `''` (empty string) which, for MySQL, is different from `NULL` and is incompatible with the numeric format you set up for your column.
> 1 votes

# Answer
I had to loop over all the values in `hook_field_presave()` and convert all the empty strings to NULLs.

Odd that the Field API doesn't do that as a matter of course.

@Scott
> 0 votes

# Answer
I had to loop over all the values in hook\_field\_presave() and convert all the empty strings to NULLs.

Odd that the Field API doesn't do that as a matter of course.
> 0 votes

---
Tags: 7, entities
---