# Question
Title: Adding a base field definition in an update hook - it's not appearing
I want to add another base field to a Drupal entity. It used to be possible to just change the code for the entity definition and then update it via the Drupal console. But now it has to be done in an update hook.

I've added the following update hook, done `drush updb` and the process completes without errors. I then did `drush cr` to clear the cache, and then opened up the edit form for the entity in question and gave it a hard refresh. But the new field has not appeared. Any idea what I'm doing wrong? Thanks. The code is based on this: https://www.drupal.org/node/3034742, section named "Installing a new field storage definition".

```
function opencase_entities_update_8002() {
  $storage_definition =  \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date and time'))
      ->setDescription(t('When the activity started.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'datetime_type' => 'date'
      ])
      ->setDefaultValue('2000-01-01')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'weight' => -3,
      ]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('activity_date_time', 'oc_activity', 'oc_activity', $storage_definition);
}

```

# Answer
The problem lies in your display options configuration (reference 4k4's answer to #244122).

Try this:

```
function opencase_entities_update_8002() {
  $storage_definition =  \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date and time'))
      ->setDescription(t('When the activity started.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'datetime_type' => 'date'
      ])
      ->setDefaultValue('2000-01-01')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'datetime_default',
        'settings' => [
          'format_type' => 'medium',
        ],
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type' => 'datetime_default',
        'weight' => -3,
      ]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('activity_date_time', 'oc_activity', 'oc_activity', $storage_definition);
}

```

**Edit:** Don't forget to update your Entity definition as well!
> 1 votes

---
Tags: 8, entities, hooks, updating
---


# Question
Title: {{ drupal_view('view1', 'block_2') }} renders only when cache is cleared
I like to output 2 block-views in a template called "block--bar.html.twig", but only when i clear the cache they are printed.

(i installed Twig Tweak 8.x-2.x)

This is the template:

```
<section{{ attributes.addClass(classes) }}>
<div class="foo1">
{{ drupal_view('view1', 'block_2') }}
  </div>
<div class="foo2">
{{ drupal_view('view2', 'block_1') }}
  </div>
</section>

```

Any help is appreciated.

# Answer
> 0 votes
The answer to the issue is to prevent that block to be cached. So first find the "block--bar.html.twig" and substitute in "add-block-id-name".

```
 /**
     * Implements hook_preprocess_HOOK() for block.html.twig.
     */
    function YOUR_TEMPLATE_NAME_preprocess_block(&$vars) {
      if($vars['derivative_plugin_id'] == 'add-block-id-name') {
        //-- This stops the block being cache in drupal 8
        $vars['#cache']['max-age'] = 0;

      }

```

---
Tags: views, 8, theming, blocks, caching
---


# Question
Title: How to reuses page--front.html.twig for multiple pages
I created a page--front.html.twig which allows me to create a distinctive front page.

How would I go about reusing this page to create a *landing page*, a page with an identical layout the front page has?

# Answer
> 1 votes
Implement `hook_theme_suggestions_page_alter()`, and you can suggest the template file used for those land pages.

I assume you are doing it from a theme; if you are doing it from a module, you can implement either `hook_theme_suggestions_page_alter(array &$suggestions, array $variables)` like for themes or `hook_theme_suggestions_page(array $variables)`.

```
function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($your_condition) {
    $suggestions[] = 'page__front';
  }
}

```

The code you write for `$your_condition` depends from how you check which pages are your land pages. The following are some useful snippets you could need.

* To get the internal path for the current page

```
$internal_path = Url::fromRoute('<current>')->getInternalPath();

```

Alternatively, the current path can be obtained with `\Drupal::service('path.current')->getPath()` (Drupal core uses both of those)
* To get the node being viewed

```
if (!empty($variables['elements']['#node'])) {
  $node = $variables['elements']['#node'];
  // Get the content type.
  // $bundle = $node->bundle();
}

```

# Answer
> 0 votes
Have a look at `hook_theme_suggestions_HOOK_alter` with the page HOOK. You should be able to add what ever login you need to add your suggestions to:

```
/**
 * Implements of hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  ...
}

```

If you do this in your theme you should be the last to enter your override suggestion and it should work great.

# Answer
> 0 votes
I think that the other suggestions are good, but incomplete. If you already have the needed theme suggestions and you only need to include the code from one template into another, then the only thing you need to do is this:

```
{% include 'page--front.html.twig' %}

```

In fact, if I was you, I would keep the theme suggestions separate (as opposed to setting all of them to page--front) and just create "template pieces" that can be later joined together are reused using include or template inheritence. This allows you to reuse repetitive templates, but have the flexibility to do adapt them to specific needs.

---
Tags: theming, 8
---


# Question
Title: Limit entity reference options base on taxonomy tag
I have three content types. **Building**, **Department** and **Person**. I connect this contents whit entity reference base on Content types. The problem is that I have a lot of persons and a lot of departments and also multiple buildings. How can I limit selection in edit mode, that I can add persons in department only from particular building wher the department is placed? My first try was to add taxonomy term (building A) to person and department placed in building A and then try to filter this in view but without a success because for building B I will need to create new Content type and add different view for same content structure. I could create Content Type "**Person building A**" and then filter by content type but this does not seems like a good solution.

# Answer
I did something like this recently myself.

Your **Person** content type should have two entity reference fields, one to a **Building**, and a second to a **Department**. A **Department** also has an entity reference to **Building**.

Use a `hook_form_alter` to target the **Person** form. In that function get a list of the Departments and their Building references, and attach it to the form along with a reference to a custom Javascript library. (Note that you'll have to use the proper machine name for your content types and fields.)

```
$departments = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'department']);

$department_data = array_map(function($department){
    return $department->field_ref_building->target_id;
}, $departments);

$form['#attached']['drupalSettings']['dept_bldg_info'] = $department_data;

$form['#attached']['library'][] = 'my_module/my_module.library_name';

```

The library file will look something like this:

```
Drupal.behaviors.chartInfoHierarchicalSelect = {
  attach: function (context, settings) {
    // Apply to the HTML page context & the person forms.
    if (context.location || context.id == 'node-person-edit-form'|| context.id == 'node-person-form') {
      let building_inputs = jQuery('[name$="[field_ref_building]"]'),
        department_inputs = jQuery('[name="[field_ref_department]"]');

      building_inputs.each(function () {
        // Ensure initial load has proper limits.
        updateDepartments(jQuery(this));
        // Update on change.
        jQuery(this).change(function () {
            updateDepartments(jQuery(this))
        });
      });

      function updateDepartments(building_input) {
        var selected_building = building_input.val();

        department_inputs.each(function () {
          var opt_val = jQuery(this).val();
          if (opt_val != '_none' && drupalSettings.dept_bldg_info[opt_val] == selected_building) {
            jQuery(this).prop('disabled', false);
          }
          else {
            jQuery(this).prop('disabled', true);
            jQuery(this).prop('selected', false);
          }
        });
      }
    }
  }
};

```

Then when you select a building, you should see the appropriate departments get enabled/disabled.
> 1 votes

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


# Question
Title: How to check if an entity is referenced before deleting?
Is there a module or a way to use Rules to make sure that a parent node isn't referenced by a child node before deleting the parent?

In my case the children require a parent to be created. However if the parent gets deleted, the children all get screwed up.

# Answer
(Entity)Reference Field Synchronization module should be able to help:

> Having 2 Entity reference fields pointing back at eachothers entities, they can be set to be updated so that if an entity A with field 1 references to an entity B with field 2, entity B automatically points to entity A.
>
> This is very helpful when you need to be able to reference from any entity, and not just be able to perform back reference queries (as provided by Entity reference).

Just add an synchronized reference field to a parent, and on delete test if it has values or not.

Also, see this feature request in Entity reference issue queue.
> 0 votes

# Answer
You can use $entity-\>referencedEntities() to get a list of all entities referenced by $entity. So if you have a list of child nodes, you call referencedEntities() on each of them and see if you find the parent node.
> 0 votes

---
Tags: rules, entities
---


title: drupal 8 modifying the menu items path

text:
# Question
Title: drupal 8 modifying the menu items path
I work on an drupal 8 application that use the `group` module with the restriction of only one group per user. i want to be able to modify the menu items so that the id of the user's group is always in the url. this way i can use `views` with a group id in the url.

I search and i always go to the same pages with the same example that doesn't work for me.

# Answer
this will not work because the menu are build during the cache clearing, thus the url cannot be dynamic.

i instead use an EventSubscriber on Kernel::REQUEST and redirect the user if need be.
> 0 votes

---
Tags: 8, navigation, group
---


# Question
Title: Drupal 7: How can I display nodes of specific author in a taxonomy term?
I've a question about taxonomy terms. In my organization I've actors that work for me and, for each actor I created a taxonomy term containing some information, such as bio, an image etc. Each actor can create content of type "post". I want display all contents of a specific actor in his own term. So, if in actors vocabulary there are "alan", "jack" and "Lucy", whan an user reaches alan term, he can see all posts created by Alan, and so on. For security I don't want the actors select terms when create posts. I hope you can understand my question.

# Answer
> 1 votes
I probably wouldn't have used a taxonomy term to store that info, but that's not a big deal.

It sounds like you want a block containing the information in the taxonomy term to appear on a user's post.

You need an entity reference connecting a user/author with the appropriate taxonomy term.

Create View that is based on the taxonomy vocabulary. Use a "contextual reference" starting with the post's node id in the URL to a relationship to the author of the post to another relationship to the taxonomy term using the entity reference.

---
Tags: taxonomy-terms
---


# Question
Title: How can I have multiple content types pick up the same template?
I want to override the template for 5 content type that they have all the same attributes, but a different name ,so the suggestion is :

```
node--contenttype1.html.twig
node--contenttype2.html.twig
node--contenttype3.html.twig
node--contenttype4.html.twig
node--contenttype5.html.twig

```

how can i implement a same override for all those 5 content type ?

# Answer
> 1 votes
Normally you'd simply use `node.html.twig` and then have different node templates for other node types. But I can imagine that it can make sense to bundle certain node types differently instead of providing distinctive templates for all other node types.

So you can implement `hook_theme_suggestions_alter` or `hook_theme_suggestions_HOOK_alter` to provide an extra template suggestion. The following snippet lets nodes of a given type pick up a `node--foobar.html.twig` template if present.

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_node_alter(array &$suggestions, array $variables) {

  $bundles = [
    'contenttype1',
    'contenttype2',
    'contenttype3',
    'contenttype4',
    'contenttype5',
  ];

  /** @var \Drupal\node\Entity\Node $node */
  $node = $variables['elements']['#node'];

  if (in_array($node->bundle(), $bundles)) {
    $suggestions[] = 'node__foobar';
    $suggestions[] = 'node__foobar__' . $variables['elements']['#view_mode'];
  }
}

```

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


title: Filter by shared reference

text:
# Question
Title: Filter by shared reference
\[!\[enter image description here\]\[1\]\]\[1\]I have a content type of "School." I have a content type of "Event" that contains an entity reference to "School" so that events can be linked to schools. I can create a view block that filters by the school, when the block is placed on the node of the school, using contextual filters.

The problem: Starting with the built-in "Basic Page," I added an entity reference to "School" so that "Basic Pages" can be linked to a "School," and be subpages of the "School." How do I filter a view of "Events" that when placed on a "Basic Page" the "Events" block view will filter based on the entity reference, "Schools," that is shared between the "Event" and "Basic Page?" I am looking to have an "Events" subpage that lists all the events of that individual school. I am trying to avoid having to create separate block views that use filter criteria of each individual school. I was hoping to use contextual filters.

Thank you

# Answer
> 0 votes
You can, at least in D8 use "reverse entity references" in contextual filters and relationships, so what you propose should work.

Have a contextual reference grabbing the node id of the Basic page from the URL. A relationship from the page to the school comes next, then a reverse relationship looking for items that have a relationship to the School. You'll also add a filter on that second relationship, limiting it to Events.

---
Tags: views
---


# Question
Title: How do I clear the cache for a single node?
In my module, I can call `cache_clear_all()` (D7) or `drupal_flush_all_caches()` (D8), and this would clear the cache for all the nodes.

Is there a way to clear the cache for a single node?

What I need to do is setting up a module that, when it selects a story on a list, it changes the value of a node field. Right now, I change the field value by updating the database table containing that value, but I need to clear the cache for the value to be updated across the site.

Is there's a better way to update a node than directly changing the database table?

# Answer
If you have the node object, use

```
use Drupal\Core\Cache\Cache;
...
Cache::invalidateTags($node->getCacheTags());

```

That's better than to assume the cache tag identifier will be `'node:' . $node->id()` forever.
> 15 votes

# Answer
The Drupal cache API can be used to clear specific items. Caching back ends can be switched (to memcache, to flat files, etc.) without having to rewrite any code.

### Drupal 7

You can try use code :

```
cache_clear_all('content:' . $node->nid, 'cache_content', TRUE);

```

Please see document here

**Drupal 8**

The data that Drupal manages fall in 3 categories:

1. entities — these have cache tags of the form `<entity type ID>:<entity ID>`
2. configuration — these have cache tags of the form `config:<configuration name>`
3. custom (for example library\_info)

You can try example:

using Cache::invalidateTags

```
use Drupal\Core\Cache\Cache;

$tags = ['node:' . $node->id()];
Cache::invalidateTags($tags);

```

You can see Cache tags
> 4 votes

# Answer
> Is there's a better way to update a node than directly changing the database table?

Yes, use the `node_load()` and `node_save()` functions as these take care of everything for you including the cache.

Changing the values directly in the database is not advised as any number of modules could have additional handlers added which will not be picked up by altering the database directly.

EDIT: For Drupal 8 use `$node = \Drupal\node\Entity\Node::load()` instead, then just `$node->save()`
> 3 votes

# Answer
If you have the entity and appropriate entity storage you can use the method `resetCache`.

```
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$storage->resetCache([$entity_id]);

```
> 2 votes

# Answer
For Drupal 8 you can use Clear Specific Cache module
> 1 votes

---
Tags: caching
---


# Question
Title: How to hide VBO multipage selector in a view
I want to hide / disable the VBO multipage selector above the table in my view but I don't find where to do it.

Anyone has an idea?

---

---

**EDIT:** I am using the "VBO Export" module and my view is related to a media. Here is a screenshot of the field : "Global: Views bulk operations"

# Answer
> 0 votes
on your views, it should be a field "Content: Node operations bulk form"

if you want totaly remove VBO, hide or remove the field, but if you want to hide specified action use " Only selected actions"

---
Tags: views
---


# Question
Title: Emoji works in a site but not in the other site on the same host
I am trying to enable emojis following Multi-byte UTF-8 support in Drupal 7.

I have added the following to the settings.php file.

```
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',

```

I've converted MySQL tables into utf8mb4 format and set the collate to utf8mb4\_general\_ci.

On the Drupal 8 site emojis work, while on the Drupal 7 I get the following error.

> 4 byte UTF-8 for mysql is activated, but not supported on your system. Please turn this off in settings.php, or ensure that all database-related requirements are met.

What am I missing?

Update

When I try to save a node with an emoji I receive the following error.

```
StatusText: Service unavailable (with message)
ResponseText: PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xF0\x9F\x98\x8A'

```

# Answer
First I SUGGEST to take a look at https://www.drupal.org/project/utf8mb4\_convert module

try to adding `'charset' => 'utf8mb4',
 'collation' => 'utf8mb4_general_ci',` configs to your `settings.php` file.

after adding it should be something like :

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',
);

```

if it does not work for you, probably you need to change MySQL configs. use the following config in your MySQL configuration ( usually `my.cnf` or `my.ini`)

```
# Use UTF8MB4 as the character set
collation-server = utf8mb4_unicode_ci
init-connect='SET NAMES utf8mb4'
character-set-server = utf8mb4

```

another suggestion:

```
ALTER DATABASE dbname CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;
SELECT CONCAT('ALTER TABLE `', TABLE_NAME,'` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;') AS mySQL
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= "dbname"
AND TABLE_TYPE="BASE TABLE"

```

FINAL STEP to make the warning go away and get a clean Status Report:

```
USE YOURDATABASENAME;INSERT INTO variable SET name='drupal_all_databases_are_utf8mb4', value='b:1;';

```

**my.ini or my.cnf** add:

```
[mysqld]
innodb_large_prefix=true
innodb_file_format=barracuda
innodb_file_per_table=true

```

**settings.php**

```
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: Add text message under "Add new comment" title
I would like to add a disclaimer message under "Add new comment" title and above the form in drupal 8 site. I changed the help text on this path /admin/structure/types/manage/article/fields/node.article.comment but nothing changed. Any suggestions please?

# Answer
You can override `field--comment.html.twig` template.

https://api.drupal.org/api/drupal/core%21modules%21comment%21templates%21field--comment.html.twig/8.8.x

```
<section{{ attributes }}>
  {% if comments and not label_hidden %}
    {{ title_prefix }}
    <h2{{ title_attributes }}>{{ label }}</h2>
    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}
    <h2{{ content_attributes }}>{{ 'Add new comment'|t }}</h2>
    // you can add your markup here
    {{ comment_form }}
  {% endif %}

</section>

```

**clear the cache after add new template file**
> 2 votes

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


# Question
Title: How can you separately get the name and the value of a field?
I want to get the key and the value of my row for example I have this:

```
{{ content.field_nom }}

```

but the out put is:

> my field name
>
> my value

My question is how do you get 'my field name' alone and 'my value' alone?

# Answer
> 0 votes
I usually use the node object to render field values and labels seperately.

```
{{ node.field_nom[0].label }}
{{ node.field_nom[0].value }}

```

---
Tags: 8, theming
---


# Question
Title: Creating a custom field with dynamic/virtual computed property value
I’m working on a custom field (Drupal 8) where the author selects a taxonomy term from defined list, but the display is of, or includes, a node that references said term. I already have a service that can retrieve the desired node based on the term id. I started with a custom `FieldFormatter` for entity references, and that does a reasonable job of displaying the node information as desired.

However, what I really need is to get that node information included in a **jsonapi** response. I’ve made a custom `FieldType` extending `EntityReferenceItem` figuring all I would need is to add a computed property value (See https://www.drupal.org/node/2112677, *e.g.*). The examples keep pointing to the use of a specialized class extending `TypedData`, but the `EntityReferenceItem` treats the main property as computed, and doesn’t use that.

I also read How to properly define and return simple array computed field property but I'm not sure it's addressing the same kind of thing nor is there quite enough detail there to help me implement a solution.

```
class MyField extends EntityReferenceItem { ...
    public function getValue() {
        $values = parent::getValue();
        $values['computed'] = 'foobar';
        return $values;
    }
}

```

my\_module/config/schema/my\_module.data\_types.schema.yml -

```
# Schema copied and modified from the configuration of the Entity reference field type
# in docroot/core/config/schema/core.data_types.schema.yml
field.storage_settings.my_field:
  type: mapping
  label: 'My field storage settings'
  mapping:
    target_type:
      type: string
      label: 'Blah blah blah'
field.field_settings.my_field:
  type: mapping
  label: 'Another label'
  mapping:
    handler:
      type: string
      label: 'Reference method'
    handler_settings:
      type: entity_reference_selection.[%parent.handler]
      label: 'Yet another label'
field.value.my_field:
  type: mapping
  label: 'Default value'
  mapping:
    target_id:
      type: string
      label: 'Value'
    target_uuid:
      type: uuid
# This part is new:
field.computed.my_field:
  type: mapping
  label: 'Hello World'
  mapping:
    target_id:
      type: string
      label: 'Computed Value'
    target_uuid:
      type: uuid

```

Any pointers out there?

My understanding is that I can set things up so that the `computed` value shows up in the `$items` parameter passed into my custom Formatter's `viewElements()` method, and, at least as important, will be part of a JSONAPI response when `my_field` is part of the `include` query parameter. As of now, neither of those things occurs.

# Answer
> 0 votes
**UDPATE**

I think the *new part* of your configuration is not necessary. I recall that there is a module called entity\_reference\_uuid which does something like you want: extends from core ER field type, adds an extra column `target_uuid` and uses the `entity` property which is computed from the reference.

In their schema they only have these keys definition:

* `field.storage_settings.entity_reference_uuid`
* `field.field_settings.entity_reference_uuid`
* `field.value.entity_reference_uuid`

If you look here you will see the `entity` is computed (like the one you want to add). Further down you can see they kept sync between the `entity` property during `::setValue` `::getValue` methods and implement `::onChange` to notify any changes on the property. This all are entity lifecycle logic, nothing to do with rendering.

Until here everything is more like your code.

Later on the formmatter they just iterate over the referenced entities which are obtained from the `$items`. The thing is I think that your problem comes from not implementing the `\Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::prepareView`:

```
/**
 * {@inheritdoc}
 *
 * Loads the entities referenced in that field across all the entities being
 * viewed.
 */
public function prepareView(array $entities_items) {
  ...
  // Fragment fromt line 142 and on.
  // For each item, pre-populate the loaded entity in $item->entity, and set
  // the 'loaded' flag.
  foreach ($entities_items as $items) {
    foreach ($items as $item) {
      if (isset($target_entities[$item->target_id])) {
        $item->entity = $target_entities[$item->target_id];
        $item->_loaded = TRUE;
      }
      elseif ($item->hasNewEntity()) {
        $item->_loaded = TRUE;
      }
    }
  }
}

```

As you can see there is where the `entity` key is populated for the formatter to use.

---

**ORIGINAL ANSWER**

By default all (most) pieces of data in Drupal 8 are typed data or get composed by it; means that fields are complex typed data which are like maps or mappings. `EntityReferenceItem` extends from `\Drupal\Core\Field\FieldItemBase` which extends from `\Drupal\Core\TypedData\Plugin\DataType\Map`. As explained in both of your renferences you should override the `::getValue` method from `EntityReferenceItem`. Here is an example

```
/**
 * {@inheritdoc}
 */
public function getValue() {
  $values = parent::getValue();
  $values['computed_value'] = $this->myAwesomeService->getJSONApiData();
  return $values;
}

```

There on your formatters (and view's field) can use the `computed_value` key from your field.

---
Tags: 8
---


# Question
Title: What's the correct way to install Drupal with Composer if I want to work on core issues?
I want to install a local Drupal site in such a way that Drupal core is a git repository so I can work on patches.

Just doing a git clone doesn't work, because I also need tools such as Drush, and installing those in a git clone of core changes the `composer.json` file that belongs to core.

What's the correct way of doing this?

# Answer
I am not sure if there really is a correct, or best way. All of the core devs I have interacted with have their own setup that works best for them.

My general setup is

* directory per remote branch: right now I have drupal-8.8.x, drupal 8.9.x, and drupal 9.0.x
* git branch for each patch that is in the issue-comment form: 3113284-02, 3113284-04)

I do this because I have a bunch of shell scripts for installing, cleaning, diffing, generating patches, running tests, etc. All of these scripts get ignored.

As far as drush goes, I keep a global install and checkout a tag periodically. I then have a .envrc in each branch directory to $PATH everything correctly. This prevents changes to composer.json.

However, there are some things you can try. A while ago, running tests locally with certain PHP versions meant updating phpunit via a post-composer script. You then had to restore composer.json and composer.lock before running a `git diff ...` to generate a patch/interdiff. You can do the something similar with drush:

* git pull origin/8.8.x
* composer require drush/drush:^10
* git checkout composer.json composer.lock

The above approach is on my short-list for updates to my scripts.
> 1 votes

# Answer
I solve this by installing Drush separately (I'm still using Drush 8), then I can run Drush commands on installs of Drupal that are downloaded with git.
> 1 votes

# Answer
I followed the `preferred-install` **source** like I documented for contrib modules which fits my needs.

```
composer create-project --no-install drupal/recommended-project:8.8.x-dev se-291135
cd se-291135/

```

This results in a require of **^8.8** (like 8.8.2) so we need to edit composer.json and change all those occurrences into **8.8.x-dev** and add the `preferred-install`

```
    "config": {
        "preferred-install": {
            "drupal/core": "source",
            "*": "dist"
        },
        ...

```

Not sure why I had to remove the lock file :-/

```
rm composer.lock

```

Installing with these settings we get a `drupal/code` in **web/core** with a detached head. Fix that and we are almost done.

```
composer install
cd web/core
git checkout origin/8.8.x

```

To make sure our patches matches drupal a `git diff` alias would help like

```
alias corediff='git diff --src-prefix=a/core/ --dst-prefix=b/core/'

```
> 1 votes

---
Tags: composer
---


# Question
Title: Render an HTML element before the menu with hook preprocess menu
I want to render an HTML element like `<span>This is my menu</span>` before my menu. I thought the most easy solution is to alter the menu. I already altered my menu to add a class. But how do I add an element before my menu with a hook preprocess function?

I know I can extend `menu.html.twig` to `menu--my-mwnu.html.twig` and add it there but I think it's less overhead to add it with a preprocess function.

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

  if (isset($variables['menu_name'])) {
    if ($variables['menu_name'] === 'my-menu') {

      $variables['attributes']['class'][] = 'my-menu';
    }
  }
}

```

# Answer
In this case you should edit the template. Changes to markup should be done in templates.

> Ok thank you. I will extend the twig file. But just to know. How do I add it within my preprocess function?

Looking into the standard `menu.html.twig` there isn't any place left to preprocess content to have it prefixed with some markup for example. There are just menu items that must be of type URL and attributes.

So your best bet probably is to add the markup to the **block** instead (in case you print your menu in a block).

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_block__footermenu(&$variables) {
  $variables['content']['#prefix'] = '<span>This is my menu</span>';
}

```
> 1 votes

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


# Question
Title: Update packages conflicting with core update
When updating drupal core via composer, you often get problems like:

> Problem 1 \- Installation request for drupal/core 8.8.2 -\> satisfiable by drupal/core\[8.8.2\]. \- Conclusion: remove typo3/phar-stream-wrapper v2.1.4 ... (and so on)

How can you tackle these issues before updating core?

# Answer
> 1 votes
**Update**: Thanks to the comment below from @mpdonadio below, it seems better to follow the official documentation right here: https://www.drupal.org/node/2700999#s-special-considerations-for-upgrading-to-drupal-880-and-later

```
composer update
git add composer.lock; git commit # Save the updates as a separate commit.
composer remove webflo/drupal-core-strict --no-update
composer remove drupal/core --no-update
composer require 'composer/installers:^1.7' --no-update
rm composer.lock
rm -rf vendor # Also helps avoid conflicts.
composer require drupal/core-recommended:^8.8 --update-with-dependencies
git add composer.json composer.lock; git commit -m "Update Drupal to 8.8.0 and use drupal/core-recommended instead of webflo/drupal-core-strict"

```

---

**Old answer**

First, make sure your composer version is not fixed (e.g. drupal/core:8.7.10):

```
composer require drupal/core:^8.7.10

```

This will update to its latest version (e.g. 8.7.11) but also makes sure you can progress later. To see which projects would cause problems, run:

```
composer prohibits drupal/core:8.8.0

```

This will result in a list:

```
typo3/phar-stream-wrapper (^3.1.3)
typo3/phar-stream-wrapper (but v2.1.4 is installed)

```

Then you can make sure you update the package:

```
composer require typo3/phar-stream-wrapper:^3.1.3

```

Then update like this:

```
 composer update drupal/core typo3/phar-stream-wrapper pear/archive_tar

```

---
Tags: 8, composer
---


# Question
Title: Entity Type Manager: How to retrieve webform entries with webform_submission_data conditions
I would like to get the webform entries submitted by a user with a particular webform\_submission\_data field value. E.g. field\_account\_type = "normal"

How can I supply such a condition?

```
$submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $submission_storage->loadByProperties([
  'webform_id' => 'my_form_id',
  'uid' => $uid,
  'field_account_type' => 'normal' // Not found exception!
]);

```

# Answer
Don't think you can query webform fields like entity fields, but it should be possible in an SQL select query:

```
$submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');

$query = \Drupal::database()->select('webform_submission_data')
  ->fields('webform_submission_data', ['sid'])
  ->condition('webform_id', 'my_form_id')
  ->condition('name', 'field_account_type')
  ->condition('value', 'normal')
  ->distinct();

$ids = $query->execute()->fetchCol();

$submissions = $submission_storage->loadMultiple($ids);

```

If you want to query the uid from the main table too, join both tables:

```
$submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');

$query = \Drupal::database()->select('webform_submission_data', 'd');
$query->join('webform_submission', 's', 'd.sid = s.sid');
$query->fields('d', ['sid'])
  ->condition('d.webform_id', 'my_form_id')
  ->condition('s.uid', $uid)
  ->condition('d.name', 'field_account_type')
  ->condition('d.value', 'normal')
  ->distinct();

$ids = $query->execute()->fetchCol();

$submissions = $submission_storage->loadMultiple($ids);

```
> 3 votes

---
Tags: webforms
---


# Question
Title: How to load a internal page content within div?
I have following code in a basic page on drupal 7

```
<h2 id="tabs">Test Title</h2>
<!-- Nav tabs -->
<ul class="nav nav-tabs">
<li class="active"><a href="content/test" data-toggle="tab"><i class="fa fa-home"></i>Test Nav</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">
<p>Content of the above internal link should display here.</p>
</div>
</div>

```

So, when I click "Test Nav", the content of the like which is originating from the same site should load within the div below.

EDIT: The content is from another page is part of a CRM form which gets generated automatically. So what I need to load is the “content” part of that linked page. I have managed to load the page by “object load”, but that loads the entire webpage. I do not need the menu, header, footer. Just the content part of it. Hope this clears the query.

Can anyone suggest a way to do it please?

# Answer
> 2 votes
You can use jQuery $.load() to load a section of a page:

```
(function($, Drupal) {
  function loadContent(context) {
    $(context).find("#the_container_div").once("arbitrary-key", function () {
      // $(this) refers to #the_container_div
      $(this).load("http://example.com #container");
    }
  }

  Drupal.behaviors.someArbitraryButUniqueKey = {
    attach: function (context) {
      loadContent(context);
    }
  };
}(jQuery, Drupal));

```

The function loadContent() loads the content of the #container div at the page example.com into your local container of #the\_container\_div.

---
Tags: 7, javascript
---


# Question
Title: How do I use the Rules module to unpublish content when End Date is hit?
I have a Content type called Event, has a **Start Date** and **End Date**.

How do I use the Rules module (version 8.3.0-alpha1) to:

* Publish the Event on the *Start Date* and
* Unpublish it on the *End Date*?

My priority is to Unpublish the content when the *End Date* is hit.

**Note**: If Rules isn't the way to go, what would be a better way to unpublish a piece of content based on a supplied End Date?

# Answer
> 2 votes
I have this functionality on a D7 site I run, and we use the Scheduler module instead. Looks like there is an alpha release for D8 you could try: https://www.drupal.org/project/scheduler

# Answer
> -1 votes
You may want to look at https://www.drupal.org/project/business\_rules module which seems to be much further along than D8 version of Rules. It, unlike Rules, does have an Unpublish action. The rest, at least in D7, would be to use Views Rules to make a View of all items past their end date and then you could use this View in Rules to loop through all the items and unpublish. Sadly, Views Rules is another module which has not made the D8 cut; but perhaps Business Rules has some sort of Views integration.

---
Tags: 8, rules
---


# Question
Title: How to render inside a paragraph template a specific view mode for that paragragh
You may say that I should just change the display settings but in my use case I need to include 2 view modes inside one template as the mobile and desktop version of the output require very different HTML.

Is there a way to do this or do I require some preprocess function to do this?

Thanks

# Answer
> 2 votes
You could try using Twig Tweak module

`{{ drupal_entity('paragraph', NUMERIC_ID, VIEWMODE_MACHINE_NAME) }}`

Also see the cheat sheet for Twig tweak, it really is a great module for frontend work!

# Answer
> 0 votes
This question is linked from this question. Since that question is closed, I'll answer here since I recently found something that's working (in case someone else is directed here and needs help).

My setup is like this:

Paragraph field \> Paragraph Field \> Some Field

I wanted to get the value of 'Some Field'. Here's how I did that:

```
content.field_paragraph.0['#paragraph'].getFields()['field_content_some_field'].getValue()[0]['value']

```

This code goes in the paragraph--some-paragraph-name.html.twig.

Hope this is able to help someone.

---
Tags: theming, paragraphs
---


# Question
Title: How can I programmatically get the admin theme
Similar question to How can I programmatically get the theme name? and How do I programmatically change the admin theme?.

I want to simply obtain the current admin theme machine name and human name, even when I might not be on a page where the admin theme is enabled as the active theme.

This information doesn't appear to be directly accessible via the ThemeManager class.

# Answer
> 9 votes
This is config and you can get it with the following snippet.

```
$admin_theme = \Drupal::config('system.theme')->get('admin');
$admin_theme_name = \Drupal::service('theme_handler')->getName($admin_theme);

```

Or with Drush:

```
drush cget system.theme admin

```

---
Tags: 8, theming
---


# Question
Title: How to block all users not containing a pattern?
I'm trying to block all users except ones with a specific role, and would love to use something like: `drush user:block !roadie`.

# Answer
> 3 votes
I suggest use drush block

```
drush ublk $(drush sqlq 'SELECT GROUP_CONCAT(ufd.name) FROM users u join user__roles ur on  u.uid = ur.entity_id  join users_field_data ufd on ufd.uid = u.uid where ur.roles_target_id ="YOUR_ROLE_MACHINENAME" and ufd.name like "%PATTERN%"')

```

before that make sure the query is correct and it respond what you want by

```
drush sqlq 'SELECT GROUP_CONCAT(ufd.name) FROM users u join user__roles ur on  u.uid = ur.entity_id  join users_field_data ufd on ufd.uid = u.uid where ur.roles_target_id ="YOUR_ROLE_MACHINENAME" and ufd.name like "%PATTERN%"

```

and finally, make sure they are blocked by checking "User status" column of the result of the following command

```
drush uinf $(drush sqlq 'SELECT GROUP_CONCAT(ufd.name) FROM users u join user__roles ur on  u.uid = ur.entity_id  join users_field_data ufd on ufd.uid = u.uid where ur.roles_target_id ="YOUR_ROLE_MACHINENAME" and ufd.name like "%PATTERN%"')

```

**PS**:

* YOUR\_ROLE\_MACHINENAME: change it with your desired role.
* PATTERN: you can use MySQL LIKE statement

---
Tags: 8, drush
---


# Question
Title: Set datetime timezone when posting data via JSON api
I'm using core JSON api to POST/PATCH data from an Android App to my Drupal 8 site. When I need to fill a datetime field I use the next JSON, for example, 2020-02-20T13:15:00. But with this format, this time is UTC, but I need Europe/Madrid timezone. How should I do it?

# Answer
In `DateTimeNormalizer`, the inferface format is RFC3339, which is `Y-m-d\TH:i:sP` as an input format string. It also accepts the ISO8601 PHP string, which is `Y-m-d\TH:i:sO`

Try using strings like in your request '2020-02-20T13:15:00+01:00'.

What I suspect is happening, is that since you aren't specifying the UTC offset, it is being interpreted as '+00:00'

The denormalizer also allepts a format string with the request to parse the `value`. I believe it is called `format`

See also `DateTimeNormalizerTest` and `EntityTestDatetimeTest` for some more examples.
> 1 votes

---
Tags: 8
---


# Question
Title: twig check if image style or view mode exists
I have a site design the i need to implement. in this design I have a grid and in the grid I can put any content (node/paragraph) that i choose. the image of the content changes size and ratio in relation to its location in the grid. I created display modes for the nodes and i use twig tweak to render it in the right display mode for example:

```
{{ drupal_entity('node', content['#node'].id , 'box_grid_1x2') }}

```

for the paragraphs I add my image style directly in the paragraph template:

```
{{ content.field_image.0 | merge({'#image_style': 'box_grid_1x2'}) }}

```

because its a little more dynamic than this and my 'box\_grid\_1x2' is actually a variable that can be set by the user I want to verify that my image styles of view modes do exist before printing them and if they dont I want to print a fallback display\image style.

how would you do it? Thanks for your help.

# Answer
> 0 votes
You can check image style existence in a preprocess hooks like follows.

```
$variables['image_style_exists'] = (bool) ImageStyle::load($style_name);

```

Though it's better to validate user input instead. Note that configuration entities like image styles or views can be selected through entity reference field which may perform such a validation for you.

---
Tags: 8, theming
---


title: How do I use the administrative theme?

text:
# Question
Title: How do I use the administrative theme?
I'm building a custom Drupal theme and wondering if there is a way to get the modal windows to use the default admin theme. I'm using the Layout builder module with a custom block that uses the Media Library module and it uses jQuery UI classes.

This is also for the modal content like the media modal.

# Answer
> 0 votes
I think Media Library Theme Reset may be what you're looking for. From the module description:

> this module takes on the responsibility of replicating Seven's CSS and attaching it, as a library, in the context of the Media Library, when accessed via Layout Builder.

---
Tags: 8, layout-builder
---


# Question
Title: How do I check radio buttons in Twig template?
In a form, I have this field:

```
$form['payment'] = [
  '#type' => 'radios',
  '#title' => $this->t('Payment Mode'),
  '#options' => [
    'chk' => $this->t('by check'),
    'tfr' => $this->t('by bank transfer'),
    'crd' => $this->t('by card'),
  ],
  '#required' => TRUE,
];

```

In the Twig template associated to the form, I'd like to show the field and some html stuff depending on the selected option. I tried this:

```
<form{{ attributes }}> {{ form.form_build_id }} {{ form.form_token }} {{ form.form_id }}
  <div>
    {{ form.payment }}
    {% if form.payment ==  'chk' %}
      You chose 'Check'
    {% elseif form.payment ==  'tfr' %}
      You chose 'Bank Transfer'
    {% elseif form.payment ==  'crd' %}
      You chose 'Card'
    {% endif %}
  </div>

```

But it is nor working!
Any idea?

# Answer
> 0 votes
That's a task for `#states` not for Twig. I think this also could be ajaxified a little bit more elegantly but using `#states` on some `items` does the job as well.

```
$form['payment'] = [
  '#type' => 'radios',
  '#title' => $this->t('Payment Mode'),
  '#options' => [
    'chk' => $this->t('by check'),
    'tfr' => $this->t('by bank transfer'),
    'crd' => $this->t('by card'),
  ],
  '#required' => TRUE,
];

$form['chk'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Check'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'chk'],
    ],
  ],
];

$form['tfr'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Bank Transfer'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'tfr'],
    ],
  ],
];

$form['crd'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Card'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'crd'],
    ],
  ],
];

```

---
Tags: 8, theming, forms
---


# Question
Title: How to show or hide some content on a node view using Page Manager based on the url destination?
After certain fields have been set on the edit node form and saved, I don't want the node author to change these anymore and therefore I have created a new variant with a response code **"301 permanent redirect**" in Page Manager.

My redirect destination is set to `%node:url?destination=no-edit-permission` And it does redirect the author to the intended node view (node\_view in Page Manager).
But the reason I set this url destination is to be able to inform the user by showing a message at the top of that redirected page that says **"You cannot edit this page any longer**".
So how do I set such a message based on the destination in the URL?

# Answer
> 0 votes
It appears that there is a **visibility rule** that you can set on a particular content using the String: URL path.

## Step 1:

take only the destination parameter: e.g. `*?destination=no-edit-permission` where the (\*) asterisk is the wild card and represents whatever comes in front of that string.

## Step 2:

In the **Configure visibility rule for New custom content**

set the option to:

> Allow access on the following pages

and tick the box:

> Reverse (NOT)

That should hide that content block based on the destination parameter. Yay!

---
Tags: 7, redirection
---


# Question
Title: How to prevent behavior-attached functions from being attached twice?
I have a behavior that adds `on` to some checkboxes.

```
(function($) {
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {

      $('.skip-line', context).on('change', function(){
        // some code
        if ( confirm(Drupal.t('Apply to all languages?')) ) {
          // applying...
        }
      });
    }
  };
})(jQuery);

```

It works very well, but checkboxes are in AJAX-loaded part. If I reload that part of the form, clicking on them makes confirmation popup twice. Now, I know I can test inside function if it's the first time in a row it's called, but I would prefer to make sure it is added to my element only once, and thus called only once. How can I do that?

# Answer
> 26 votes
The `once()` function will help with that,e.g.

```
(function($) {
   Drupal.behaviors.mymodule = {
    attach: function (context, settings) {

      $('.skip-line', context).once('mymodule').on('change', function(){
        // some code
        if ( confirm(Drupal.t('Apply to all languages?')) ) {
          // applying...
        }
      });
    }
  };
})(jQuery);

```

One of the many references

# Answer
> 8 votes
You need to use the once() function to achieve this. From this page

```
Drupal.behaviors.myModule = {
  attach: function (context, settings) {
    $('element', context).once('myModule', function () {
     // any behavior is now applied once
    });
  }
};

```

The string "myModule" passed to the function is set as a marker on the elements matching the jQuery selection, so the next time once is called it ignores them. Do not use the same string if you call the once function multiple times for different purposes, otherwise you may defeat its purpose.

# Answer
> 5 votes
you can also do this too:

```
(function ($, Drupal, drupalSettings) {
    'use strict';
Drupal.behaviors.someThing = {
        attach: function (context) {
            if (context === document) {
               console.log('called inside'); // Once <--
            }
            console.log('called outside'); // can be manny manny  <--
         },
    };
})(jQuery, Drupal, drupalSettings);

```

# Answer
> 4 votes
Here's an example that expands on frazras answer:

```
var searchPagesFoundationAccordionInit = false;
Drupal.behaviors.searchPagesFoundationAccordionInit = {
  attach: function (context, settings) {
    // Attempt to resolve behavior being called multiple times per page load.
    if (context !== document) {
      return;
    }
    if (!searchPagesFoundationAccordionInit) {
      searchPagesFoundationAccordionInit = true;
    }
    else {
      return;
    }

    // Check if component exists.
    if ($('.view-style--search-page .search-section__sidebar .accordion').length > 0) {
     // Code here.
    }
  }
};

```

# Answer
> 2 votes
here is another way to have a function that runs once:

```
(function($, Drupal) {

  var initialized;

  function init() {
    if (!initialized) {
      initialized = true;
      // Add your one-time only code here
    }
  }

  Drupal.behaviors.someKey = {
    attach: function() {
      init();
    }
  };

}(jQuery, Drupal));

```

Source: https://www.drupal.org/forum/support/module-development-and-code-questions/2018-06-15/run-js-funtion-once-not-attach-once#comment-12654121

---
Tags: javascript
---


# Question
Title: Programmatically setting a webform submission to draft in presave
I am trying from within a hook\_webform\_submission\_presave() programmatically set a webform submission to draft. We are creating an event registration system with webforms and some events require approval. The thought is if an event requires approval we would set submissions to draft and admins could then "approve" them by making them no longer drafts.

Maybe there is a better way to handle this functionality and i'm open to ideas though I am not sure why this cleaned up hook below doesn't set submissions to draft mode.

```
function lebow_events_webform_submission_presave(WebformSubmissionInterface $webform_submission) {
  $current_data = $webform_submission->getData();
  $current_data['in_draft'] = TRUE;
  $webform_submission->setData($current_data);
}

```

# Answer
> 4 votes
Turns out I need to do this to save draft, the setData is only used to set element data.

```
$webform_submission->set('in_draft', TRUE);

```

# Answer
> -1 votes
I tried using `$webform_submission->set('in_draft', FALSE);` but the results of the webform keeps saying "DRAFT".

this is the conditional where I'm applying this line of code:

```
if ($response->getStatusCode() == 201 && isset($webform_submission)) {
    $webform_submission->setElementData('state', 2); // state[0]: draft | state[1]: lead enviado | state[2]: enviado a SUR.
    $webform_submission->set('in_draft', FALSE);
    $webform_submission = WebformSubmissionForm::submitWebformSubmission($webform_submission);
}

```

Thanks

---
Tags: 8, hooks, webforms
---


# Question
Title: A custom route to an entity form will not pass the entity
I want a custom route to the normal user form. So, I've added an entry to the routing file that directs my custom route to the canonical form of the `User` entities:

```
my_profile_form:
  path: '/user/{user}/my-profile-form'
  defaults:
    _form: '\Drupal\user\ProfileForm'
    _title: 'My profile form'
  requirements:
    _role: 'administrator'

```

When I try to open `/user/1/my-profile-form` with my browser, I see the following error message:

> Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm-\>getBaseFormId() (line 106 of ...web/core/lib/Drupal/Core/Entity/EntityForm.php)

It seems that with my custom route the form does not know who the user is.

**What magic must happen to inform the form about the user?**

# Answer
> 1 votes
You can try using `_entity_access`

```
my_profile_form:
....
  requirements:
    _role: 'administrator',
    _entity_access: user.update
   user: \d+

```

See EntityAccessCheck

# Answer
> 1 votes
Custom access check is written to check whether the logged in user is same as of user id passed in the parameter

```
my_module.user.profile:
  path: '/user/{user}/profil'
  defaults:
    _entity_form: 'user.profil'
    _title: 'Profil'
  requirements:
    _entity_access: 'user.update'
    _custom_access: '\Drupal\my_module\Access\MyModuleUserAccess::editProfil'
    user: \d+
  options:
    _admin_route: FALSE

```

---
Tags: forms, routes
---


# Question
Title: How do I programmatically create a node with an entity reference (to an user)?
It is kind of strange because my code creates the node with the referenced user uid in node\_field\_data, but when I open this node the user reference isn't working. Then I navigated the database and found that, when I update the user reference field in the interface, it is also written as a new registry in the table node\__field\_user, so I guess I should insert it there too.

But, I don't know how to do this with the API, and I think making it with a SQL query probably means security issues and is probably much more complicated than however it can be done with the API.

This is my code:

```
  $node = Node::create(['type' => 'nodetype']);
  $node->set('title', $username );
  $node->uid->entity = $userId;
  $node->enforceIsNew();
  $node->save();

```

# Answer
> 1 votes
Set owner `$node->setOwnerId($uid);`

Set field reference `$node->field_user[] = $uid;`

---
Tags: 8, nodes, users
---


# Question
Title: How can I get a field in hook_preprocess_views_view_unformatted(&$variables)?
Is there a way to get a field from the view in the `hook_preprocess_views_view_unformatted(&$variables)`?

```
$rows = $variables['rows'];
foreach ($rows as $id => $row) {
  // $row['field_name']?
}

```

# Answer
You find the field handlers you have configured in the Fields list in `$view->field`. A field handler has methods like `getValue()`, `render()` and `advancedRender()`, which accept as argument the row variable:

Example:

```
$view = $variables['view'];
$rows = $variables['rows'];
foreach ($rows as $id => $row) {
  $field_value = $view->field['field_name']->getValue($row);
}

```

See also Get result view with formatter programmattically
> 3 votes

---
Tags: 8, views
---


# Question
Title: Why doesn't hook_preprocess_block() alter the block content?
I'm finding I can't alter block content with hook\_preprocess\_block() in Drupal 8. Should I expect to be able to alter content, such as a block body, using hook\_preprocess\_block()?

For example, this has no effect on my block output:

```
function mysite_preprocess_block(&$variables) {
  $variables['elements']['content']['body'][0]['#text'] = 'alter all block bodies everywhere';
}

```

# Answer
> 1 votes
There were two issues, in my case. For one thing, I was using the wrong key. I needed to use...

```
$variables['content']['body'][0]['#text']

```

...instead of...

```
$variables['elements']['content']['body'][0]['#text']

```

The other issue was that I had nothing saved in the body field, and in some cases setting a value for the body field in hook\_preprocess\_block() has no effect on output unless there is a value saved in the body field. You must at least save some garbage characters to the field or else setting a value in hook\_preprocess\_block() will have no effect on the output.

---
Tags: 8, blocks
---


title: CKEditor doesn't work after updating

text:
# Question
Title: CKEditor doesn't work after updating
I've updated a drupal website to the latest 7.x version, and CKEditor stopped working. I had it originally getting //cdn.ckeditor.com/4.5.4/full-all, I've updated to //cdn.ckeditor.com/4.13.0/full but no luck. I've tried to remove and reinstall the module, clear the website and browser caches, etc. I've also uploaded the version and used it from the local disk rather than the CDN (in case there were network issues with the CDN site, but I didn't see any errors).

I'm short of ideas. Has anyone experienced this and has some more ideas for me to try?

# Answer
> 0 votes
Should anyone be interested, updating to the latest core (7.69) seems to have restored the CKEditor functionality.

---
Tags: 7, wysiwyg
---


# Question
Title: How to set an exposed filter to enable current user to view nodes that he has not commented
On my D7 site I am trying to create an exposed filter where current users would choose whether he wants to see all nodes, or only those that current users have not commented. Tried adding 'Comment: Comments of the node' and 'Comment: Author' relationships, 'Comment: Author uid' contextual filter. I didn't want to set a default value because I want users to switch between all nodes and ones commented by current user. Then I added a filter criteria 'Comment: Author uid' with setting up grouped filter using \[current-user:uid\] token. No success yet.

# Answer
> 2 votes
As I understand it, this is impossible with just the views module by itself.

You can easily filter for nodes that the user **has** commented on, but filtering for nodes the user **hasn't** commented on is difficult for reasons I'll go into later, so you're going to have to install additional modules or write your own code.

First of all, to get the nodes the user **has** commented on, you've already added the correct relationships ("Comment: Comments of the node" and "Comment: Author"). However, the filter you actually need to use is "User: Current" with your author relationship selected and the option "Is the logged in user: Yes". You probably also want to use the "Distinct" option in the view's "Query Settings", otherwise you'll get duplicate rows if the user has commented multiple times on the same node.

Now, the reason you can't easily get the nodes the user **hasn't** commented on is because you can't just change the filter option to "Is the logged in user: No".

Why not?

Because that will go through every comment on the node, and if **any** of the comments are not authored by the current user, the node will be included in the results, even if it has other comments that **were** authored by the current user.

So, what you'd actually need to be able to do is take the list of nodes which the current user **has** commented on, and then **exclude** them from the results of the view, which simply can't be done in the standard views UI.

Without writing your own module to modify this behaviour, the best option seems to be the OtherView Filter module.

With that module, you can create a second view of nodes, which excludes the results of the first view I described above, using a "Content: Other view result" filter. For usability you'd probably want to set this up as a grouped filter to avoid having the operator and view names exposed to the user.

---
Tags: 7, views, tokens
---


# Question
Title: How to move fields into secondary region where Menu Settings are located?
We have a need to move the language selector field to right column in the same section as the Menu Setting (see screenshot). Using Twig Debugging, we found that the template node-edit-form.html.twig can be used, but we could not find a way to selectively move select fields such as the language selector. We did notice a `Secondary Region` in the twig template, but could not see a way to selectively move the field so that if the field exists on the content type.

**Goal:**

1. Add language selector to the `secondary region`.
2. No additional styling is needed, just move the field.

How do we move the fields to the `secondary region` on the `node-edit` page??

# Answer
This can be done in two ways:

## 1) Use the Field group module.

Field Group has added the ability to move items to the right sidebar on the node edit form, via the "Details sidebar" group type in the dropdown.

## 2) Write a hook\_form\_alter() in a custom module.

If you have more complicated needs than what Field Group provides you can do this in custom code.

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Select the desired entity add/edit form.
  if (is_array($form['#theme']) && in_array('node_form', $form['#theme'])) {

    // Ex 1. Move an existing field container wrapper to the sidebar.
    if (!empty($form['field_myfield']) && $form['field_myfield']['#type'] == 'container') {
      $form['field_myfield']['#type'] = 'details';
      $form['field_myfield']['#group'] = 'advanced';
    }

    // Ex 2. Move an existing field to the expanded 'meta' section of the sidebar.
    if (!empty($form['field_myfield'])) {
      $form['field_myfield']['#group'] = 'meta';
    }

    // Ex 3. Move a field group provided by some contrib module to the sidebar.
    $form['somecontrib']['widget'][0]['#group'] = 'advanced';
    $form['somecontrib']['widget'][0]['#open'] = FALSE;

    // Ex 4. Create a custom collapsible container in the sidebar.
    $form['mycontainer'] = [
      '#type' => 'details',
      '#group' => 'advanced', // This line places the container in the sidebar
      '#weight' => 99,  // ensure it displays last or use -10 to show it first.
      '#title' => t('My custom sidebar settings'),
      '#tree' => TRUE,
      '#access' => TRUE,
    ];

    // Ex 4.1 Move a field into the custom container in the sidebar.
    if (!empty($form['field_myfield'])) {
      $form['field_myfield']['#weight'] = -1; // reset weight
      $form['field_myfield']['#group'] = 'mycontainer';
    }

    // Ex 4.2 Some fields have an inner widget that need to be moved instead.
    if (!empty($form['field_myfield']['widget'])) {
      $form['field_myfield']['widget']['#weight'] = -1; // reset weight
      $form['field_myfield']['widget']['#group'] = 'mycontainer';
    }

  }
}

```
> 6 votes

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


# Question
Title: Views field cache tags does not invalidate the views cache
I've implemented `CacheableDependencyInterface` on my ViewsField plugin.

```
  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return ['arbitrary_tag'];
  }

```

I can see the tag on the HEADER and the View configuration object.

However, when that tag is invalidated, the View is not updated.

I've also tried using adding cache tags to the `render` method:

```
return [
  '#markup' => $message,
  '#cache' => [
    'tags' => ['my_list'],
  ],
];

```

Both to the Views field, but also tried directly on the View element using `hook_views_pre_view`

While debugging, I've made sure to try invalidate that specific tag:

```
Cache::invalidateTags(['my_list']);

```

While debugging further it seems like that the ResultRow values are still cached after clearing the tag.

# Answer
Although there are Views plugins which use CacheableDependencyInterface, I'm not sure it is the right way for a field plugin, because a field renders content and a cache tag of rendered content belongs in the render array.

This was discussed in this issue for block plugins. Don't know if this here or in the other issues for blocks is a core issues, because you can see in both core modules the effort to collect plugin cacheable metadata, or Drupal assumes, that all render arrays fulfill the requirements outlined in the docs:

> "It is of the utmost importance that you inform the Render API of the cacheability of a render array"

Anyways, an easy fix is to put the cache tag in the rendered output of the field.
> 2 votes

---
Tags: views, 8
---


title: Breadcrumbs/menu for dynamic pages

text:
# Question
Title: Breadcrumbs/menu for dynamic pages
Im breaking my head around getting the breadcrumbs set properly on views page.

my views' page address is "`teachers/%`" where % is a term-id.

I have a content type called '`program`' with a field taxonomy term reference field "field\_department"

I want to set my breadcrumb for the page '`teachers/%`' to be the breadcrumbs of the program associated with `%` \+ the program itself.

**my site is using also menu\_breadcrumb** which gives the rule for my program breadcrumbs.

**I want the the breadcrumb of '`teachers/7`' will behave as if it is the menu child of `node/22`.**

I tried both hook altering the breadcrumbs or adding the pages to the menu dynamically but I dont manage.

Can this be done? and how?

# Answer
Views breadcrumbs can be tricky. You can create a module and a class that implements `BreadcrumbBuilderInterface` and do:

```
class MyBreadcrumbBuilder implements BreadcrumbBuilderInterface {

  use StringTranslationTrait;

  /**
   * The AdminContext service.
   *
   * @var \Drupal\Core\Routing\AdminContext
   */
  protected $adminContext;

  /**
   * The AliasManager service.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * The EntityTypeManager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    AdminContext $admin_context,
    AliasManagerInterface $alias_manager,
    EntityTypeManagerInterface $entity_type_manager
  ) {
    $this->adminContext = $admin_context;
    $this->aliasManager = $alias_manager;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) : bool {
    if ($this->adminContext->isAdminRoute()) {
      return FALSE;
    }

    // Using route_match, check if the current route is a view and which view id
    // and return true or false
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) : Breadcrumb {
    $breadcrumb = new Breadcrumb();

    // create your breadcrumbs...

    return $breadcrumb;
  }

}

```
> 1 votes

# Answer
Ok finally i did this way:

```
 public function build(RouteMatchInterface $route_match) : Breadcrumb {
    $breadcrumb = new Breadcrumb();
    $this->menu_link_manager = \Drupal::service('plugin.manager.menu.link');
    $node_id = 22; //I use a query to get the entities according to the routeMatch argument
    $results = $this->menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
    foreach ($results as $result){
      if ($result->getMenuName() == "main"){
        $links = $this->_build_links($result,[Link::createFromRoute(t('Home'), '<front>')]);
        //here i use just a string 'Home', ideally this string should be taken from breadcrumbs\site settings.
      }
    }
    $breadcrumb->setLinks($links);
    return $breadcrumb;
  }
  private function _build_links($menu_item, $links){
    if ($menu_item->getParent() && $parent = $this->menu_link_manager->createInstance($menu_item->getParent())) {
     $links = $this->_build_links($parent, $links);
    }
    $title = $menu_item->getTitle();
    $routeName = $menu_item->getRouteName();
    $routeParameters = $menu_item->getRouteParameters();
    $options = $menu_item->getOptions();
    $links[] = Link::createFromRoute($title,$routeName,$routeParameters,$options);

  return $links;
}

```

I was pretty close to hooking up with the code of menu\_breadcrumbs but I think there is an issue with the code there that prevents this kind of use see issues/3026188

My code is still not perfect and I would really still want to find a way to access and chain the breadcrumbs of "parent" node(node/22) in a more general way.
> 0 votes

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


# Question
Title: How do I retain user input in a form after submission?
I am working on a simple form for searching a collection of marriage licenses. It consists of a select box where the user may choose to search last names, first names, or both, and a text field where they type the name they're searching for.

Everything is working fine so far, except that the user input is not retained after the form is submitted. For example, if I choose "Last names" and enter "Olsen", after the form is submitted the search box will be empty and the select box will revert to its default of "Both first and last names".

Here is my `buildForm()` method:

```
public function buildForm(array $form, FormStateInterface $form_state){
    // The select box.
    $form['target'] = [
        '#title' => $this->t('Search'),
        '#type' => 'select',
        '#options' => [
            'both' => $this->t('Both first and last names'),
            'last' => $this->t('Last names'),
            'first' => $this->t('First names'),
        ],
        '#default_value' => $form_state->getValue('target'),
    ];

    // The search box.
    $form['q'] = [
        '#title' => $this->t('for'),
        '#type' => 'textfield',
        '#default_value' => $form_state->getValue('q'),
    ];

    $form['actions'] = ['#type' => 'actions'];

    $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Go'),
    ];

    return $form;
}

```

As you can see, I've tried using `#default_value` to set a default value by calling the form state to get whatever the user picked/entered. But alas, this does not seem to have done it.

How do I get it to display the user input in the form after submission?

# Answer
Try adding `$form_state->setRebuild(TRUE);` to your `submitForm()`. Quoting from here:

> Normally, after the entire form processing is completed and submit handlers have run, a form is considered to be done and \Drupal\Core\Form\FormSubmitterInterface::redirectForm() will redirect the user to a new page using a GET request (so a browser refresh does not re-submit the form). However, if 'rebuild' has been set to TRUE, then a new copy of the form is immediately built and sent to the browser, instead of a redirect.

I think that as you have stubbed a submit handler, but not implemented anything (and so are presumably not calling `parent::submitForm` either), it is not considered "done", so it is not redirecting; but it is not rebuilding based on the new `$form_state` either, because you haven't told it to. So you end up just seeing the original form.

As well as setting rebuild to true you may also need to `$form_state->disableRedirect(TRUE)` to get the desired behaviour of staying on the form, but with inputted values showing.
> 6 votes

---
Tags: 8, forms
---


# Question
Title: Incorrect handling of PHP sessions causes many 503 errors?
I use my personal website to host several images galleries, and for several months now, I've noticed that a lot of the thumbnail images appear broken and aren't loaded by the browser. This seems to be random: sometimes one page will load perfectly fine, other times the same page will appear completely broken.

Obviously this is quite a catastrophic result for an image gallery...

This is not a problem with the images themselves: they've already been generated and are present on the server. In Firefox you can right-click the broken image and choose "reload image", and the image will appear immediately.

This is not a problem with the browser, OS or machine either: I tested it on various machines and with numerous browsers.

Upon inspection, the broken images correspond to **503 errors** sent by the server (Service unavailable).

I checked the server logs for more details and found this kind of error for each "broken" image:

`Rejected, too many connections from this host. (vhost:example.com:/sites/default/files/styles/[etc]) current: 27 limit: 20, referer: https://example.com/galeries`

I contacted my hosting provider and their response was that "your site incorrectly handles PHP sessions. The connection is not closed between pages, and when this limit is reached, the site doesn't load any more."

I'm not sure where I can go from here...

Is this a know issue with Drupal 7? How can I fix it?

# Answer
Images in files/styles are delivered directly via the web server, with no PHP code involved.

Change the hosting provider, it seems like they are not keeping up with browsers configured to use more simultaneous connections. Choose one providing HTTP/2, this protocol is supported by all modern browsers and doesn't have this issue.
> 0 votes

# Answer
I have solved my problem, although I still don't understand exactly what caused it. It's probably a rather rare edge-case, but in case somebody runs into a similar situation, here's what I did.

One thing I didn't mention (because it didn't occur to me that it could be related to my problem) is that my site was configured so that Drupal was stored in a subfolder (/dp) while still being served from the root folder (thanks to some htaccess rewriting magic at root level).

Yesterday I decided to duplicate my site into another subfolder (/dev) *on the same server*, in the hope that I would then be able to try and disable various modules until I found which one caused my problem (without ruining my production site).

To my surprise, I was unable to cause the problem to appear on this new "dev" site, while the same problem was still easily triggered on my production site. At his point, the two sites were completely identical, except for one point: the production site had a "RewriteBase" rule activated in its .htaccess file, which I had to disable on the dev site:

`RewriteBase /dp`

So I made the guess that the problem was somehow related to this rule. I decided to change the way my site was configured and move Drupal directly in the root folder (as is usually the case). I then disabled the RewriteBase rule since it was not needed anymore.

That was enough to make the problem go away.

I'm not saying the rule is the direct or unique cause of the problem: I also had the exact same configuration on my localhost (Windows) machine, and I never encountered the same problem on it. So it's probably a combination of factors. I don't know more.
> 0 votes

---
Tags: 7, sessions
---


# Question
Title: What code should I use, instead of running a query that uses DATA_FORMAT()?
I am converting Drupal 7 code to Drupal 8. In Drupal 7, I am using `db_query()`; in Drupal 8, I am using the following code.

```
\Drupal::database()->select('node_field_data', 'spmw')
  ->fields('spmw', ['id', 'created' => 'DATE_FORMAT(created, "%H:%i")'])
  ->execute()
  ->fetchObject();

```

When I run it, it causes the following error.

> 1054 Unknown column 'spmw.DATE\_FORMATcreatedHi' in 'field list': SELECT spmw.id AS id, spmw.DATE\_FORMATcreatedHi

What code should I instead use to avoid that error?

# Answer
You can try `\Drupal::database()->select->addExpression()`.

For you, below code might be useful.

```
\Drupal::database()
  ->select('node_field_data', 'spmw')
  ->fields('spmw', ['id'])
  ->addExpression("DATE_FORMAT(created,'%H:%i')", "created")
  ->execute()
  ->fetchObject();

```
> 3 votes

# Answer
Although this is an old question, I would like to point out an alternate method. The problem is that Drupal chokes on the parameter of the MySQL `DATE_FORMAT` function specifying how the date should be formatted. Suppose you have this code:

```
$SQL = 'SELECT DATE_FORMAT(NOW(), "%e %b %Y")';

$query = $db->query($SQL);

$query->execute();

```

Executing this in Drupal (as of version 8.8.2) will result in the message "The website encountered an unexpected error. Please try again later." and the following entry in the log:

```
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]:
Column not found: 1054 Unknown column '%e %b %Y' in 'field list':
SELECT DATE_FORMAT(NOW(), "%e %b %Y"); Array ( )

```

To work around that, you can use a bound parameter for the date format. This code will work:

```
$SQL = 'SELECT DATE_FORMAT(NOW(), :dateFormat)';
$terms = [':dateFormat' => '%e %b %Y'];

$query = $db->query($SQL, $terms);

$query->execute($terms);

$result = $query->fetchAll();

```

I suspect the `%` symbols in the `DATE_FORMAT` are what's causing the problem. Moving those to a bound parameter solves the issue because Drupal always passes those directly to the database as a literal string.

Hoping this may help some future sufferer.
> 0 votes

---
Tags: 8, database
---


title: Theme CSS won't load

text:
# Question
Title: Theme CSS won't load
I'm trying to make a Drupal 8 theme and no matter what I do, the stylesheet I have won't render. Here's my libraries.yml file:

```
global-styling:
version: VERSION
css:
theme:
  css/layout.css: {}

```

and here's my info.yml file:

```
name: My Test Blog
type: theme
description: 'My test theme description'
package: Custom
core: 8.x
libraries:
  - MyTestBlog/global-styling
stylesheets-remove:
  - '@classy/css/layout.css'
  - core/assets/vendor/normalize-css/normalize.css

regions:
  header: Header
  content: Content
  stylesheets:
    all:
        - css/style.css

```

Any ideas?

# Answer
> 2 votes
Be aware of indent properly (only 2 spaces, not TAB):

\[theme\_name\].libraries.yml:

```
global-styling:
  version: VERSION
  css:
    theme:
      css/layout.css: {}

```

\[theme\_name\].info.yml

```
name: My Test Blog
type: theme
description: 'My test theme description'
package: Custom
core: 8.x
libraries:
  - MyTestBlog/global-styling
stylesheets-remove:
  - '@classy/css/layout.css'
  - core/assets/vendor/normalize-css/normalize.css

regions:
  header: Header
  content: Content
  stylesheets:
    all:
      - css/style.css

```

# Answer
> 2 votes
TIP: Conflict when Module with same name as Theme!

Just in case someone else runs into this, if you have a module with the same name as your theme (xxx, for example), the xxx.libraries.yml file in your theme folder is ignored. Instead, Drupal looks at the xxx.libraries.yml file in your modules folder. Any files referred to by it (css, js, etc.) are also loaded from the modules folder and its subfolders, not from the themes folder.

# Answer
> 0 votes
The theme block in libraries info should be indented and the MyTestBlog/global-styling should be in lowercase since the "MyTestBlog" is the machine name of your theme and I doubt your files are named MyTestBlog.info.yml ... And the stylesheets part of the regions don't make any sense.

# Answer
> 0 votes
I solved the problem. The problem was that the name of my style directory was not the same as the name of my libraries and info files. What I mean is that before, I was doing something like naming my file "mytestblog.info.yml" and then trying to link to myblogsite/global-styling. Once I changed myblogsite/global-styling to mytestblog/global-styling, my stylesheet rendered.

# Answer
> 0 votes
My Drupal 8 theme CSS was loading on my local MAMP environment, but not on my Ubuntu server... Permissions issue. This was easy to check by trying to view the CSS file listed in the HEAD of the HTML file via the browser URL, which gave me a 403 error.

I needed to chown -R myuser:www-data my CSS file directory, and that fixed it.

---
Tags: 8
---


# Question
Title: How can I get field labels from submission data?
I have created a custom webform handler by extending WebformHandlerBase. And I can get the data from the WebformSubmission. However, I can only get the machine name of the field. I would like to get field label. For instance, I get "fname" machine name as the key, but I want to get "First Name" or what ever label is set in the admin for this webform.

Does anyone know how I might get to that information from a webform submission entity?

# Answer
I assume that you pass `$form`, and `$form_state` into your custom handler function. You can always access your webform field "label" via **$form** variable.

Try **kint()** or **dd()** `$form['elements']` on specific form and go into depth to find your field, then you can easily get `$form['elements']['my_field_name']['#title']` etc.
> 0 votes

---
Tags: 8, webforms
---


# Question
Title: Get field content of all instances of a field
I'm trying to get the content of all instances of certain fields based on their names. I've got a list of fields (which are in nodes/paragraphs and blocks) of which I want to extract the values from.

For example `field_call_to_action_link`. I need values of all the instances of this field.

Each field has it's own database table, like: `node__field_name, paragraph__fieldname, block_content__fieldname.`

I get the field names like this ($configFieldTypes is an array of types I want):

```
foreach ($configFieldTypes as $fieldType) {
  $fieldNamesFiltered[] = $this->entityFieldManager->getFieldMapByFieldType($fieldType);
}

```

Then I filter based on the name starting with 'field\_' and make an array with the fieldname as key and the bundles associated with each field:

```
  private function recursiveKeys($fields, &$fieldNames) {
    foreach ($fields as $key => $field) {
      if ($key === 'parent_field_name'){
        continue;
      }
      if (FALSE !== strpos($key, 'field_')) {
        $fieldNames[$key] = [$field][0]['bundles'];
      }
      if (is_array($field)) {
        $this->recursiveKeys($field, $fieldNames);
      }
    }
  }

```

The endresult is an array like this:

```
  ["field_call_to_action_link"]=>
  array(1) {
    ["call_to_action_button"]=>
    string(21) "call_to_action_button"
  }
  ["field_image_gallery_link"]=>
  array(1) {
    ["image_gallery"]=>
    string(13) "image_gallery"
  }

```

Now I need to know if `field_call_to_action_link` is a node, block, or paragraph.

**How can I determine which database table to query?**

Drupal 8.8.x

# Answer
If i understand correctly you have `field_call_to_action_link` in node, paragraph, block entities. And you would like to get values from this field from all entities which contain this field.

I would use EntityQuery and condition to check if field exists in given Entity.

```
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('field_call_to_action_link', 'NULL', 'IS NOT NULL')
->execute();

```

this should give you all published nodes which contain `field_call_to_action_link`. You can obtain 'block' Entity the same way only change 'node' to 'block'.

---

**Useful links:**
> 1 votes

---
Tags: 8, database
---


title: Twig embedding and field object

text:
# Question
Title: Twig embedding and field object
I'm using Radix and trying to create a Botstrap carousel component with no luck. This is the code so far. Kint shows me that media object is there with its multiple fields but nothing is rendered.

```
themes\custom\newtheme\templates\content\node--article--teaser.html.twig

{% embed '@newtheme/carousel/carousel.html.twig' with {'media': content.field_media } %}{% endembed %}

themes\custom\newtheme\src\components\carousel\carousel.html.twig

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">

    {% for item in media.items %}
        <div{{ item.attributes.addClass(['field__item', 'carousel-item']) }}>{{ item.content }}</div>
    {% endfor %}

  </div>
  <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

```

# Answer
> 0 votes
The only way I achieved something similar was using:

```
{% for key, item in content.field_club_history if key|first != '#' %}
    {{ content.field_club_history['#items'][key].entity.field_games.value }}
{% endfor %}

```

The only difference is that **field\_club\_history** was EntityReference field to Paragraph of concrete type. Paragraph type then has fields like **field\_games**. Try to use following code example and get fields from specific item that you need.

```
{{ content.field_club_history['#items'][key].my_field_name }}

```

---
Tags: 8, theming
---


# Question
Title: Can a content entity type have a bundle which is a configuration entity type as with the contact form?
What is `bundle_entity_type` for `@ContentEntityType` when `id = contact_message` and where `contact_message` is `@ConfigEntityType?` Can a configuration entity Type be a bundle of a content entity type?

core/modules/contact/src/Entity/Message.php

```
/**
 * Defines the contact message entity.
 *
 * @ContentEntityType(
 *   id = "contact_message",
 *   label = @Translation("Contact message"),
 *   label_collection = @Translation("Contact messages"),
 *   label_singular = @Translation("contact message"),
 *   label_plural = @Translation("contact messages"),
 *   label_count = @PluralTranslation(
 *     singular = "@count contact message",
 *     plural = "@count contact messages",
 *   ),
 *   bundle_label = @Translation("Contact form"),
 *   handlers = {
 *     "access" = "Drupal\contact\ContactMessageAccessControlHandler",
 *     "storage" = "Drupal\Core\Entity\ContentEntityNullStorage",
 *     "view_builder" = "Drupal\contact\MessageViewBuilder",
 *     "form" = {
 *       "default" = "Drupal\contact\MessageForm"
 *     }
 *   },
 *   admin_permission = "administer contact forms",
 *   entity_keys = {
 *     "bundle" = "contact_form",
 *     "uuid" = "uuid",
 *     "langcode" = "langcode"
 *   },
 *   bundle_entity_type = "contact_form",
 *   field_ui_base_route = "entity.contact_form.edit_form",
 * )
 */
class Message extends ContentEntityBase implements MessageInterface {

```

core/modules/contact/src/Entity/ContactForm.php which says `bundle_of` ==\> `contact_message`

```
/**
 * Defines the contact form entity.
 *
 * @ConfigEntityType(
 *   id = "contact_form",
 *   label = @Translation("Contact form"),
 *   label_collection = @Translation("Contact forms"),
 *   label_singular = @Translation("contact form"),
 *   label_plural = @Translation("contact forms"),
 *   label_count = @PluralTranslation(
 *     singular = "@count contact form",
 *     plural = "@count contact forms",
 *   ),
 *   handlers = {
 *     "access" = "Drupal\contact\ContactFormAccessControlHandler",
 *     "list_builder" = "Drupal\contact\ContactFormListBuilder",
 *     "form" = {
 *       "add" = "Drupal\contact\ContactFormEditForm",
 *       "edit" = "Drupal\contact\ContactFormEditForm",
 *       "delete" = "Drupal\Core\Entity\EntityDeleteForm"
 *     }
 *   },
 *   config_prefix = "form",
 *   admin_permission = "administer contact forms",
 *   bundle_of = "contact_message",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *   },
 *   links = {
 *     "delete-form" = "/admin/structure/contact/manage/{contact_form}/delete",
 *     "edit-form" = "/admin/structure/contact/manage/{contact_form}",
 *     "collection" = "/admin/structure/contact",
 *     "canonical" = "/contact/{contact_form}",
 *   },
 *   config_export = {
 *     "id",
 *     "label",
 *     "recipients",
 *     "reply",
 *     "weight",
 *     "message",
 *     "redirect",
 *   }
 * )
 */
class ContactForm extends ConfigEntityBundleBase implements ContactFormInterface {

```

# Answer
This may be easier to understand with Nodes, since Nodes have been used by almost every Drupal site builder.

Nodes are a Content Entity. Nodes have bundles (aka content types). For example, a blog. Now, to define the blog type, a new Config Entity is created - the Node Type entity. Config entities have keys. The key for the blog Node type is 'blog'. This key identifies the node type. But the blog bundle is still a Node entity, and therefore is a Content Entity.

The contact form works the same way.

So to answer your question, no, bundles of Content entities cannot be config entities, as bundles are just a subset of the original entity, which is a Content entity. But a Config entity is used to define the bundle (allowing the types to be exported as configuration).

You could almost compare it to the 'type' field on a Content Entity being an Entity Reference to a Config entity that defines the type.
> 1 votes

---
Tags: 8
---


# Question
Title: How do I create a view with some customization?
I like to create a view to display properties information as shown below.

### View

### View page

7676 - SQFT

7 - BR

I created a view and added the fields based on my design. I made progress, but I am not able to create the second column of data (SQFT, BR).

How do I add the second column in this view?

# Answer
> 2 votes
I wouldn't use **Fields** setting for this case.

Try to override template for specific content type and set your view to display your content type in specific 'view mode' for example **teaser**.

In your view change 'Format' to 'unformated list' and change 'Show' setting to 'teaser' for example. This will display your content type in specific view mode, so now you can override your template for this custom content type using:

`node--my_content_type_machine_name--display_mode.html.twig`

be aware of correctly using double dashes, otherwise your template won't be registered by drupal. Then you can code custom HTML template for your content type in this specific view mode and you can customize your layout according to your needs.

---
Tags: views
---


# Question
Title: How do I disable cache in my entityQuery?
I created a preprocess function in my recipe node page, inside that function I want to get 3 random recipes everytime the user accessess the page.

I have this code:

```
function sometheme_preprocess_node__recipe__full(&$variables)
{
    $nids = \Drupal::entityQuery('node')
        ->condition('type', 'recipe')
        ->condition('status', 1)
        ->addTag('sort_by_random')
        ->range(0, 3)
        ->execute();

    $variables['random_recipes'] =  \Drupal\node\Entity\Node::loadMultiple($nids);
}

```

But I notice that the recipes doesn't random because of Drupal cache system.

I don't want to turn off the overall cache system of Drupal for perfomance purposes.

I just want to disable cache programmatically when I get the random recipes.

# Answer
You'll need to make this an **un-cachable block** and place it on your template file, otherwise, you would have to turn off page caching.

But unless this is the only thing on that page, and there isn't something else in here worth caching, then you could alternately **turn off caching for this specific page(s)**.
> 0 votes

---
Tags: 8, caching
---


title: Theme structure for multi-site

text:
# Question
Title: Theme structure for multi-site
I have a multi-site setup with three themes. They look the same, but they are different in colors. What are best practices to setup my theme structure, in themes/custom/site1, site2, and site3, or in sites/site1/themes, sites/site2/themes, and sites/site3/themes?

# Answer
If they only differ in color, you should provide a theme setting for choosing it and setup the theme in `/themes/custom/mymulticolortheme`, so it will become available for all sites. Otherwise you have to maintain multiple nearly identical themes, which is a time killer when you have to fix a bug or add a feature.

If you have different themes for each site you should place each theme in the particular site theme folder like `/sites/site1/themes/custom/myspecialthemeforsite1`, `/sites/site2/themes/custom/mytotalydifferentthemeforsite2` etc., so that they are only available for sites they belong to.
> 4 votes

# Answer
IN this case, where the themes differ only in color, you should create a single theme. And try using theme settings of color module to change the color as required.
> 0 votes

---
Tags: 8, multi-sites
---


# Question
Title: How to translate the month name in a date select list field?
I have created a date field in user account fields. In manage form display, I have selected `Select list` as widget.

I want to translate the month names which is displaying a select list.

I checked it here `admin/config/regional/translate` and in config translation `admin/config/regional/config-translation` but I don't see any option to translate it.

Is there anything I am missing. Is it possible to translate the month names in the date select list?

# Answer
> 0 votes
Enable the "Language" & "Interface Translation" modules. Then download the translation .po file on https://localize.drupal.org and import it in /admin/config/regional/translate/import

---
Tags: 8, i18n-l10n, datetime
---


# Question
Title: How to display date and time picker for base field on custom entity
I've made a base field on a custom entity with type "datetime" using "datetime\_default" for the form display. It's displaying as only a date picker, with no time component, whereas I want it to look like this:

If I create a field in the GUI I can select between "date only" or "date and time". (The image above is the result of picking "date and time"). But I can't work out how to do this programmatically. I've tried creating fields of both types and exporting the config, but there is no difference between them, which is a mystery.

I suspect I need to put something other than "datetime\_default" but I can't find any documentation on how to programmatically refer to the various date and time widgets.

```
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);

$fields['activity_date_time'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Date and time'))
  ->setDescription('')
  ->setRevisionable(TRUE)
  ->setRequired(TRUE)
  ->setSettings([
    'datetime_type' => 'date'
  ])
  ->setDefaultValueCallback('Drupal\opencase_entities\Entity\OCActivity::currentDateTime')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'datetime_default',
    'settings' => [
      'format_type' => 'medium',
    ],
    'weight' => -3,
  ])
  ->setDisplayOptions('form', [
    'type' => 'datetime_default',
    'weight' => -3,
  ]);

```

# Answer
`setSettings(['datetime_type' => 'date'])` \- this seems to be to blame. See the switch in the source here which effectively says if type is 'date' (implemented as a const) then only show the date form element, otherwise show the date + time elements.
> 2 votes

---
Tags: 8, entities, datetime
---


# Question
Title: How can I show the previous step value in next step?
I have created a multistep webform and it has 5 steps. is it possible to get the previous step field value/data in the next step? for example, I have a field select list field (key = select\_your\_data\_type) in step 4 and on step 5 show the selected field value?

# Answer
> 5 votes
Look into the computed twig element of webform You can access the values of data.name\_of\_field with that

# Answer
> 2 votes
Use

```
HOOK_form_alter(array $form,FormStateInterface $form_state, $form_id)

```

check if `$form_id` equals your specific form (form's machine name) and validate if current page is page where you want to display data ('*step\_5*' is wizard's page machine\_name).

```
if ($form['progress']['#current_page'] === 'step_5')

```

get values from **$form\_state**

```
$form_state->getValue('select_your_data_type')

```

and you can set form elements via

```
$form['elements']['page_5']['field_i_want_to_set_in_page_5']

```

or via

```
$form_state->set('field_i_want_to_set_in_page_5', $my_value);

```

or course do not forget to print **field\_i\_want\_to\_set\_in\_page\_5** somewhere on page 5.

---
Tags: 8, webforms
---