# Question
Title: Why is drupal spitting out urls like entity:/node-1474 instead of /node-1474
So for the longest time I was using the following line of code to get urls instead of relying on drupals raw output. The main reason being I need an `<a>` tag to wrap several elements.

```
{{ item.content['#paragraph'].field_home_slider_button_link.0.value.uri }}

```

Inside of a field.

For a quick minute I contemplated just removing the `entity:`, however I'd really like to understand what's happening here and if there's a way to tell drupal I want the actual url in either twig or some setting?

# Answer
You have to use `.url` instead of `.uri`, like this:

```
{{ item.content['#paragraph'].field_home_slider_button_link.0.url }}

```

I don’t think this works on older versions of Drupal 8, so if it doesn’t work you can try this:

```
{{ item.content['#paragraph'].field_home_slider_button_link.0['#url'] }}

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Does "composer remove drupal/module" actually uninstall the module first?
Does `composer remove drupal/module` actually uninstall the module first, especially in multi-site environments?

On the other hand, does `composer require` "enable" the given module for all sites?

# Answer
No, Composer doesn’t install or uninstall modules in the site itself.

It’s a dependency manager; all it does is compute your requirements, then download them.

You might be able to add a post install/update command to automate it, but trying to make it generic would probably be a pain.
> 9 votes

# Answer
In a Drupal site with a Composer workflow you'll need to do the following when you decide to remove a module:

1. From your Drupal Admin, uninstall/disable the module so that Drupal doesn't expect to see it.
2. Edit your composer.json file in the root of your Drupal installation. It should be outside the /web directory. Remove the reference to module module and save the file.
3. run composer update

Composer will remove the module from the file system and will know that it is no longer a package in the installation.
> 4 votes

---
Tags: composer
---


# Question
Title: Deprecated configuration for the temporary files path
After updating to 8.8.1 I get this warning:

> You are using deprecated configuration for the temporary files path. Remove the configuration and add the following to settings.php. $settings\["file\_temp\_path"\] = ".tmp"

But I can not remove the configuration, because the page: "admin/config/media/file-system" is not editable.

# Answer
Starting in 8.8, Drupal no longer allows setting the temp directory on the file system setting form. The form deliberately disables the field to prevent folks from using it. For full info about this change, see Deprecate file\_directory\_temp() and move to FileSystem service on d.o.

All you have to do is set the temp directory path in settings.php as the message indicates.

```
$settings['file_temp_path'] = '/path/to/tmp';

```

**Note:** if your temp directory is not `/tmp`, do this before running database updates. From the d.o issue where this change was implemented:

> If your site is not using /tmp, you must update settings.php before running database updates.

**What if I run database updates before setting the temp path in settings.php?**

Looking at the issue and reviewing the most recent patch (patch #121), it doesn't look like anything terrible happens. The only thing that happens during update.php is it attempts to delete the deprecated config for temp file path from `system.file.path.temporary` (where it's set on the `/admin/config/media/file-system` page). However, it'll only remove the config if it's safe to do so.

```
/**
 * Remove 'path.temporary' config if redundant.
 */
function system_update_8801() {
  // If settings is already being used, or the config is set to the OS default,
  // clear the config value.
  $config = Drupal::configFactory()->getEditable('system.file');
  if (Settings::get('file_temp_path') || $config->get('path.temporary') === FileSystem::getOsTemporaryDirectory()) {
    $config->clear('path.temporary')
      ->save(TRUE);
  }
}

```

While nothing is broken, you will end up with deprecated config just hanging around (forever?). To get your site to a state that matches where it would've been had you made the settings.php update before running updates, make sure you set `$settings['file_temp_path']` in settings.php and then do one of the following:

1. Create a new update hook in a custom module that has the same contents of `system_update_8801()` then run updates again **after** making the update to settings.php.
2. Manually edit the config file in your config directory to remove the configuration, then import.
3. See How do I re-run updates (change module schema version)? to attempt to rerun the original update.
> 3 votes

---
Tags: updating
---


title: How to attach xdebug to drush in docker

text:
# Question
Title: How to attach xdebug to drush in docker
How can I "attach" xdebug to drush in a docker container?

By that I mean, how can I have xdebug show me a history of an import script? And to look at the single variables that are defined and occupied during the import script?

The whole thing runs on: Docker version 2.1.05 (40693), Engine: 19.03.5, running on Mac 10.15.1. Drupal version 8.7.9.
PhpStorm, Version 2019.3

My Config tempter, here the file docker-compose.yml:

```
version: "3.4"

services:
  mariadb:
    image: wodby/mariadb:$MARIADB_TAG
    container_name: "${PROJECT_NAME}_mariadb"
    stop_grace_period: 30s
    environment:
      MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD
      MYSQL_DATABASE: $DB_NAME
      MYSQL_USER: $DB_USER
      MYSQL_PASSWORD: $DB_PASSWORD
    ports:
      - "4306:3306"
  mysql:
    image: wodby/mariadb:$MARIADB_TAG
    container_name: "${PROJECT_NAME}_mariadb_test"
    stop_grace_period: 30s
    environment:
      MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD
      MYSQL_DATABASE: $DB_NAME
      MYSQL_USER: $DB_USER
      MYSQL_PASSWORD: $DB_PASSWORD

  php:
    image: wodby/drupal-php:$PHP_TAG
    container_name: "${PROJECT_NAME}_php"
    environment:
      PHP_SENDMAIL_PATH: /usr/sbin/sendmail -t -i -S mailhog:1025
      DB_HOST: $DB_HOST
      DB_USER: $DB_USER
      DB_PASSWORD: $DB_PASSWORD
      DB_NAME: $DB_NAME
      DB_DRIVER: $DB_DRIVER
      PHP_FPM_USER: wodby
      PHP_FPM_GROUP: wodby
      COLUMNS: 80 # Set 80 columns for docker exec -it.

### From here the config of the Xdebug:
  PHP_XDEBUG: 1
      PHP_XDEBUG_DEFAULT_ENABLE: 1
      PHP_XDEBUG_REMOTE_AUTOSTART: 1
      PHP_XDEBUG_REMOTE_HOST: host.docker.internal # Docker 18.03+ Mac/Win
      PHP_IDE_CONFIG: serverName=Docker
      PHP_XDEBUG_REMOTE_CONNECT_BACK: 1
    volumes:
      - ./:/var/www/html

 nginx:
  image: wodby/nginx:$NGINX_TAG
  container_name: "${PROJECT_NAME}_nginx"
  depends_on:
    - php
  environment:
    NGINX_STATIC_OPEN_FILE_CACHE: "off"
    NGINX_ERROR_LOG_LEVEL: debug
    NGINX_BACKEND_HOST: php
    NGINX_SERVER_ROOT: /var/www/html/docroot
    NGINX_VHOST_PRESET: $NGINX_VHOST_PRESET
  volumes:
    - ./:/var/www/html
  labels:
    - 'traefik.backend=${PROJECT_NAME}_nginx'
    - 'traefik.port=80'
    - 'traefik.frontend.rule=Host:${PROJECT_BASE_URL}'

 selenium-firefox:
  container_name: "${PROJECT_NAME}_firefox"
  image: selenium/standalone-firefox-debug:2.53.1
  volumes:
    # - /dev/shm:/dev/shm
    - ./:/var/www/html
  ports:
    - "5905:5900"
    - "4444:4444"

 mailhog:
  image: mailhog/mailhog
  container_name: "${PROJECT_NAME}_mailhog"
  labels:
    - 'traefik.backend=${PROJECT_NAME}_mailhog'
    - 'traefik.port=8025'
    - 'traefik.frontend.rule=Host:mailhog.${PROJECT_BASE_URL}'

memcached:
  container_name: "${PROJECT_NAME}_memcached"
  image: wodby/memcached:$MEMCACHED_TAG
  command: "sh -c 'memcached -m 1024'"

portainer:
  image: portainer/portainer
  container_name: "${PROJECT_NAME}_portainer"
  command: --no-auth -H unix:///var/run/docker.sock
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  labels:
    - 'traefik.backend=${PROJECT_NAME}_portainer'
    - 'traefik.port=9000'
    - 'traefik.frontend.rule=Host:portainer.${PROJECT_BASE_URL}'

traefik:
  image: traefik:v1.7-alpine
  container_name: "${PROJECT_NAME}_traefik"
  command: -c /dev/null --web --docker --logLevel=INFO
  ports:
    - '80:80'
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock

 php_test:
  container_name: "${PROJECT_NAME}_php_test"
  image: registry.my_projekt.de/drupal-test
  volumes:
    - ./:/var/www/html
  environment:
    CI_PROJECT_DIR : "/var/www/html/"
    DATABASE_PATH: "/root/database.sql"
    SELENIUM_PORT: "4444"
    BROWSER: "firefox"
    WEB_DRIVE: ""
    DISPLAY: ":99"
    UPDATE_ALIAS: "myProjekt:update"
    DB_HOST: 'mysql'
  labels:
    - 'traefik.port=80'
    - 'traefik.frontend.rule=Host:test.${PROJECT_BASE_URL}'

 php_quality:
  image: hussainweb/drupal-code-quality:latest
  command: tail -f /dev/null
  volumes:
    - ./:/var/www/html

```

# Answer
> 1 votes
It can happen if you are using drush launcher (https://github.com/drush-ops/drush-launcher). This tool allows you to type "drush" in your Drupal directory, instead of "./vendor/bin/drush", but it can confuse xdebug. Using "./vendor/bin/drush" may fix the problem.

Additionally, you may also have to set an environment variable in your PHP container:

`export PHP_IDE_CONFIG="serverName=my_server"`

... where my\_server is the name of the server in

`Preferences / Languages & Frameworks / PHP / Servers`

where your path mapping is set in PHP storm.

You may also wish to enable the option: "Break at first line in PHP scripts" and then run your drush commands - as often it can be tricky to set breakpoints in the correct place when running drush.

---
Tags: drush, debugging
---


title: XAMPP and Acquia Dev Desktop

text:
# Question
Title: XAMPP and Acquia Dev Desktop
I installed XAMPP on my local machine to use it for Drupal. But all the navigation between all the localhost websites are really slow, no matter if it's a brand new vanilla Drupal website or if it's a commerce website, drupal 7 and/or drupal 8.

I tried everything from apache config to mysql config to windows config.

I decided to try to either re-install XAMPP or install Acquia Dev Desktop instead.

2 questions: if i want to re-install XAMPP, do i need to uninstall it first or will it reinstall over it just fine? if i want to install Acquia DEV Desktop, do i need to un-install XAMPP first?

Thanks...

# Answer
> if i want to install Acquia DEV Desktop, do i need to un-install XAMPP first?

No, you can run them both at the same time by configuring different ports in Acquia Dev Desktop. Acquia Dev Desktop will also create its own hostname, so you'll access it differently. Eg, http://othersite:8080
> 2 votes

# Answer
I have both Acquia Dev Desktop and XAMPP set up separately on my machine with Windows 10. To my knowledge they function completely independent of one another.

I would play it safe and Uninstall XAMPP and simply install Aquia DevDesktop using its Apache and MySQL. It's a great option if you are on Windows, or if you are not a dev ops ninja. There are some minor quirks along the way but it's super easy once it's set up to spin up sites, or import local sites.

Once Dev Desktop is set up and working well for Drupal 7 sites, you can set up to efficiently manage Drupal 8 sites with Composer. For that you WILL need to re-install XAMPP (or equivalent) **Not for the DevDesktop environment itself**, but simply because you will need a local instance of PHP if you want to install Composer globally. The Composer installer will not recognize a php instance from your Dev Desktop installation.

You can then build Drupal 8 sites using this template via Composer, then import the codebase to Acquia Dev Desktop via `import a local site`. That template has it's own instance of drush and drupal console. There are some quirks with Composer Drush on Aquia, in that you need to set a PATH to get your database connections as described in this article.

Hope this helps!
> 1 votes

---
Tags: configuration, installation
---


# Question
Title: How do I theme the "The website encountered an unexpected error" page?
How do I set the theme to use for the error page showing an unhandled exception like the one shown in this screenshot?

# Answer
The errors in Drupal 7 handled by `includes/errors.inc` file, and the **The website encountered an unexpected error. Please try again later.** error use the *maintenance\_page* theme see from *includes/errors.inc*

```
print theme('maintenance_page', array(
        'content' => t('The website encountered an unexpected error. Please try again later.'),
      ));
      exit;

```

So if you want to theme the error page, you theme the `maintenance_page` to do so take a look at Theming the Drupal maintenance page.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to prevent email address from displaying on edit profile page?
I have set up my site so that some users with a specific role can't edit their email address. This works fine - users with role type A can navigate to the edit tab on their profile and edit their email address, and users with role type B are unable to edit their email address. However, these users can still view their email address field on the edit tab, it just appears disabled. I do not want this to be the case.

I used the User Protect and Field Permissions modules to achieve this. For all of the other fields that I prevented users with role type B from editing (e.g. their name), the fields did not appear at all on the edit tab. I have used the same settings in field permissions for these fields and the email field but for some reason the email field appears under the edit tab but the others don't. How can I prevent the email field from displaying when users don't have permission to edit it?

# Answer
You can to this using `hook_form_FORM_ID_alter()`, like this:

```
function MY_MODULE_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (in_array('role_B', \Drupal::currentUser()->getRoles())) {
    // We restrict access if the field is disabled.
    $form['account']['mail']['#access'] = FALSE;
  }
}

```
> 4 votes

---
Tags: 8, users
---


title: Location migration not working

text:
# Question
Title: Location migration not working
I'm trying to convert a d6 location field into a a d8 geolocation field, but when I run it the field does not get updated, and I don't get any messages either.

All of the other node data has been imported already so I am running the migration with the command: drush migrate-import ttf\_location\_migration --update

I am including title because without it I get an mySQL error message.

Here's my migration YML file:

```
id: ttf_location_migration

label: Migrate old location data to geolocation field

source:
  plugin: ttf_location
  key: ttf_migrate

process:
  nid: nid
  title: title
  type: type
  'field_location/bundle': type
  'field_location/deleted':
    plugin: default_value
    default_value: 0
  'field_location/entity_id': nid
  'field_location/revision_id': nid
  'field_location/langcode':
    plugin: default_value
    default_value: 'en'
  'field_location/delta':
    plugin: default_value
    default_value: 0
  'field_location/field_location_lat': latitude
  'field_location/field_location_lng': longitude

destination:
  plugin: entity:node
  overwrite_properties:
    - 'field_location/bundle'
    - 'field_location/deleted'
    - 'field_location/entity_id'
    - 'field_location/revision_id'
    - 'field_location/langcode'
    - 'field_location/delta'
    - 'field_location/field_location_lat'
    - 'field_location/field_location_lng'

migration_dependencies: {}

dependencies:
  enforced:
    module:
      - ttf_migrate

```

and my source plugin:

```
<?php

namespace Drupal\ttf_migrate\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;
use Drupal\migrate\Row;

/**
 * Source plugin for location.
 *
 * @MigrateSource(
 *   id = "ttf_location"
 * )
 */
class TtfLocation extends SqlBase {

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

    $query = $this->select('location', 'l')
      ->fields('l', ['lid', 'latitude', 'longitude']);
    $query->join('location_instance','li','l.lid = li.lid');
    $query->fields('li', ['nid']);
    $query->join('node', 'n', 'li.nid = n.nid');
    $query->fields('n', ['type', 'title']);

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    $fields = [
      'lid' => $this->t('Location ID'),
      'latitude' => $this->t('Latitude'),
      'longitude' => $this->t('longitude'),
      'nid' => $this->t('Content ID'),
      'type' => $this->t('Type'),
      'title'=>$this->t('Title')
    ];

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    return [
      'nid' => [
        'type' => 'integer',
        'alias' => 'nid',
      ],
    ];
  }

}

```

Any help much appreciated

Thank you

# Answer
> 1 votes
Do not repeat the field name for sub columns: Instead of e.g. `field_location/field_location_lat` use only `field_location/lat`, in the `process:` section.

There also is no need to manually set interal keys like `entity_id` or `revision_id`: Only set the destination plugin and the field values, and Migrate module will fill all other internal columns for you.

```
destination:
  plugin: entity:node

process:
  title: title
  type:
    plugin: default_value
    value: NODE_BUNDLE_NAME
  langcode:
    plugin: default_value
    value: 'en'
  field_location/lat: latitude
  field_location/lng: longitude

```

# Answer
> 0 votes
From a code snippet I posted a while ago, you can make up the following structure for a geolocation field:

```
$node = Node::create(
  'type' => 'location',
  'title' => 'My location',
  'geolocation_field' => ['lat'=> 41.264, 'lng' => 45.33]
);
$node->save();

```

Not familiar with migrate module, but this can help.

---
Tags: 8, migrations
---


title: How to customise list (text) field?

text:
# Question
Title: How to customise list (text) field?
On my user registration page, I would like to add a field where users can type in and select specific key words.

It is possible to make such a field using webforms. It would look as below:

However, my user registration form is not a webform, it is a standard Drupal form, provided by the `user` module.

I have managed to add a field to the registration form, of type 'List (text)' and then in the 'Manage form display' section there is an option to display it as radio buttons so the user can select more than one option. This works successfully, but what I would really like to achieve is the look above.

Are the use of webforms the only way to achieve this? I guess if I have to use webforms I would have to replace the whole user registration form with a webform.

# Answer
> 4 votes
This will be a lot easier for you, if you use the taxonomy system.

Create a vocabulary for your keywords, then add the different keywords as terms.

The select2 module has a field widget for entity reference fields which allows you to get the autocomplete widget where you can remove the selected terms with an `X`.

Then you only need to add a little bit of styling, to get it to look like your design.

Hope it makes sense.

---
Tags: 8, entities, forms, webforms
---


# Question
Title: How to pull a record from Salesforce and immediately push the node ID back to Salesforce
I'm using the Salesforce Suite module.

What I'm trying to accomplish:

When a record is created in Salesforce, that record is pulled into Drupal and the new node content ID is pushed back to the Salesforce record (for reference in Salesforce).

I have a mapping set up as such:

**Triggers**

* Drupal create (push)
* Drupal update (push)
* Salesforce create (pull)
* Salesforce update (pull)

**Fields**

* **Title** \- Salesforce to Drupal
* **Content ID** \- Drupal to Salesforce

With this setup, it pulls the record into Drupal but the Content ID doesn't get pushed back to Salesforce. It will, however push when I update (just save) the node but we don't expect these nodes to be saved anytime soon after it's pulled in.

I've tried a few different ways leveraging the events dispatched by the Salesforce module but it always leads me to a race condition or a circle.

# Answer
> 2 votes
Here's how I did it...

Since content is set to push (immediately) on update, I added a hook\_entity\_insert() that responded not to the content insert but the "salesforce\_mapped\_object" entity.

This ensures that not only was the node/user created but a mapping was created.

```
/**
 * Implements hook_entity_insert().
 */
function MYMODULE_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->bundle() == 'salesforce_mapped_object') {
    $entity_info = $entity->get('drupal_entity')->first()->getValue();
    $type = $entity_info['target_type'];
    $id = $entity_info['target_id'];
    switch ($type) {
      case 'node':
        $node = \Drupal\node\Entity\Node::load($id);
        $node->save();
        break;
      case 'user':
        $user = \Drupal\user\Entity\User::load($id);
        $user->save();
        break;
    }
  }
}

```

Thanks to @leymannx in the above comment for the guidance.

---
Tags: 8
---


title: Add title for sections in a view

text:
# Question
Title: Add title for sections in a view
so I am trying to create a view via Drupal 8 Structure-\>Views, and I am setting up this view to display certain shops in certain areas, I would like titles above each type of location of shops, so I would like u.s.a stores to have a title, and canada stores to have a title, is this possible in the view creator? for example:

Or should I create separate views, then sort in the twig files, example stores - can, stores - usa

Please let me know, thanks!

# Answer
> 0 votes
If you want a title for each type of view, I would click the add button for a "header" then click on Global text and enter in the Title you want for that view.

UPDATE:

Also, if you are looking to put in a title for each entry you could look into making that a content type that the view pulls from. It can pull the Title of each entity.

---
Tags: views
---


title: Why does sql-sync fail?

text:
# Question
Title: Why does sql-sync fail?
I'm managing Drupal 7 and Drupal 8 sites, so I'm running Drush 8 as that's the only version that can manage both. The Drupal 8 sites are installed using Composer and my local setup runs on MAMP 5.5.1.
It works fine for the Drupal 7 sites, and rsync works for the Drupal 8 sites as well. However, sql-sync fails. When I run `drush sql-sync @local.dup @prod.dup`, I get the following messages.

> Warning: require(/Users/username/path/to/local/vendor/bin/drush.php): failed to open stream: No such file or directory in /Users/username/path/to/localvendor/bin/drush on line 4
> Fatal error: require(): Failed opening required '/Users/username/path/to/local/vendor/bin/drush.php' (include\_path='.:') in /Users/username/path/to/local/vendor/bin/drush on line 4
> The command could not be executed successfully (returned: \[error\] Warning: require(/Users/username/path/to/local/vendor/bin/drush.php): failed to open stream: No such file or directory in /Users/username/path/to/local/vendor/bin/drush on line 4
> Fatal error: require(): Failed opening required '/Users/username/path/to/local/vendor/bin/drush.php' (include\_path='.:') in /Users/username/path/to/local/vendor/bin/drush on line 4, code: 255)
> The Drush sql-dump command did not report the path to the dump file produced. Try upgrading the version of Drush you are using on the source machine.

I get similar errors when checking `drush @local status` and `drush @remote status` as well as when I try to use the Drush 9 included in each site ( `cd path/to/docroot` \> `vendor/bin/drush @self @remote`).

I've tried removing all Drush instances and installing only the same version that my host (cloudways) uses on the remote server (Drush 8.0.5) with no luck. I've installed Drush using CGR as instructed on Install (alternatives).
I've also checked my alias' file in the global Drush folder multiple times and can't find any issues.

What can I do from here to debug and resolve the issue?

# Answer
> 0 votes
I ended up running two global drush installs as explained here.

I needed to make to use same versions of Drush 9 both globally and on the site-specific installs to not get any errors. Now both Drush 8 and Drush 9 seem to run smoothly alongside each-other.

---
Tags: drush
---


# Question
Title: How to check if a multi value reference field already has a value
I need to check if a multi-valued reference field (referencing other nodes) in a node has a specific value already present to avoid duplicates.

here is the code:

```
$portFolioNode =  \Drupal\node\Entity\Node::load( $form_state->getValues()['portfolios'] );

//now save location id to reference field.
//$portFolioNode->field_portfolio_locations[] = ['target_id' =>  $form_state->getValues()['location_nid']  ];

// how can I check if location_nid is present already?
$portFolioNode->field_portfolio_locations[]  = $form_state->getValues()['location_nid'] ;

$portFolioNode->save();

```

Any help will be appreciated greatly. Thanks!

# Answer
You can check the field's values before saving:

```
// Id to check if exists.
$query_id = 123;

// Create array of existing ids in field.
$existing_ids = array_column($entity->my_entity_reference_field->getValue(), 'target_id');

// Check if the $query_id is not in the existing ids.
if (!in_array($query_id, $existing_ids)) {
  // In here means your $query_id doesn't already exist in the field's values.
}

```

Your code updated:

```
// Load portfolio node id and new location id from form_state.
$portfolioId = $form_state->getValue('portfolios');
$newLocationId = $form_state->getValue('location_nid');
if (!empty($portfolioId) && !empty($newLocationId)) {
  // Load portfolio node.
  $portfolioNode = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->load($portfolioId);

  // Get existing location ids from portfolio node.
  $existingPortfolioLocationIds = array_column($portfolioNode->field_portfolio_locations->getValue(), 'target_id');
  // If new location id is not an existing location id, add to node and save.
  if (!in_array($newLocationId, $existingPortfolioLocationIds)) {
    $portfolioNode->field_portfolio_locations[] = $newLocationId;
    $portfolioNode->save();
  }
}

```
> 10 votes

---
Tags: 8
---


# Question
Title: How to count the number of comment and flag in a node?
I want to display on my node the number of comment and flag.

What should I add to my TWIG to get this?

How to count the number of comment and flag in a node?

Here is an example :

# Answer
For the comment count you can get it in the node twig by:

```
{{ content.comment['#items'].comment_count }}

```

But the flag count i think there is no way to get it directly in the twig:
There is extension called `flagcount` in the flag module but it requires the flag object which is not available in node twig.
From comment section of `flagcount` callback function in ***flag/src/TwigExtension/FlagCount.php***

> ```
> /**
>    * Gets the number of flaggings for the given flag and flaggable.
>    *
>    * @param \Drupal\flag\FlagInterface $flag
>    *   The flag entity.
>    * @param \Drupal\Core\Entity\EntityInterface $flaggable
>    *   The flaggable entity.
>    *
>    * @return string
>    *   The number of times the flaggings for the given parameters.
>    */
>
> ```

So the only way is to pass by preprocess like the following:

```
/**
 * Implements hook__preprocess_HOOK().
 */
function YOURMODULE_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  // Set your flag id here.
  $flag_id = 'bookmark';
  $variables['flag_count'] = \Drupal::service('flag.count')->getEntityFlagCounts($node)[$flag_id];
}

```

And then in you twig you can do:

```
{{ flag_count }}

```
> 4 votes

---
Tags: 8, theming, nodes, comments, flags
---


# Question
Title: Entity create access based on a custom field
Is there a way to allow/prevent users to create a new entity based on an entity field? Because the `checkCreateAccess() / hook_entity_create_access()` function is not receiving the actual entity as a parameter, just the bundle.

Is is ok to do a check on 'hook\_entity\_presave()' and throw an exception there?

# Answer
Since the method invoking `hook_entity_presave()` already throws an exception, throwing an exception in `hook_entity_presave()` is safe, and it's going to tell Drupal an error is not allowing to save the entity.

```
protected function doPreSave(EntityInterface $entity) {
  $id = $entity->id();

  // Track the original ID.
  if ($entity->getOriginalId() !== NULL) {
    $id = $entity->getOriginalId();
  }

  // Track if this entity exists already.
  $id_exists = $this->has($id, $entity);

  // A new entity should not already exist.
  if ($id_exists && $entity->isNew()) {
    throw new EntityStorageException("'{$this->entityTypeId}' entity with ID '{$id}' already exists.");
  }

  // Load the original entity, if any.
  if ($id_exists && !isset($entity->original)) {
    $entity->original = $this->loadUnchanged($id);
  }

  // Allow code to run before saving.
  $entity->preSave($this);
  $this->invokeHook('presave', $entity);
  return $id;
}

```

It doesn't make sense to use an entity field to decide if a user is allowed to create an entity, though. It would mean that, basing on the value the user chooses for that field, the user is allowed, or not, to create the entity. `hook_entity_presave()` would also show the error message after the users filled the entity creation form and clicked on the \_Save\__ button, which is a way too late to tell them they cannot create an entity. (Users are used to Drupal not showing them a link to which they don't have access, or for an operation they don't have the permission to do.)

If instead of the actual entity field value, you are deciding if the user has the permission to create the entity basing on the default value of the entity field (which could change basing on the entity or its bundle), then `EntityFieldManager::getFieldDefinitions()` returns the list of entity fields (an array of objects implementing `FieldDefinitionInterface`), for which `FieldDefinitionInterface::getDefaultValue()` can be used to retrieve the default value an entity field gets when a new entity is created. (`EntityFieldManager` is the class that implements the \_entity\_field.manager\_ service.)

Alternatively, instead of depending on the default value an entity field has, which has sense when also the current value of the entity field is used in someway, the code could check the value of a configuration entity (linked to the entity itself or its bundles) to decide which users can create the entity.
In this case, `hook_entity_create_access()` can be used, as it just needs to know which entity is going to be created, or which bundle of that entity will be created.
> 0 votes

# Answer
Use the rules module instead? https://www.drupal.org/project/rules

1. Before saving entity of type X
2. Entity has field Y
3. Entity field Y is Z
4. Allow, else deny
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Which tables should be emptied when clearing database-stored cache manually?
Prior to D8 to clear cache manually one could truncate all tables beginning with `cache_`.

In Drupal 8 there are still tables starting with `cache_`, but there's also a `cachetags` table.

Is the advice in D8 still to truncate `cache_*` if you need to clear cache manually? Is it safe/required/recommended to truncate the `cachetags` table along with the `cache_*` tables?

I'm aware there may be contrib modules doing things differently, I'm mostly interested in what core does, and what's considered "best practice" for Drupal 8 in general.

# Answer
In drupal 8 if you are looking for the safe tables that needs to be cleared manually then clear the tables starting with cache\_ and also truncate the cachetags table too.

If you are using drush then use this command for clear cache-

**drush cache-rebuild**
> 8 votes

# Answer
According to this article `cachetags` are set when cache objects are being stored, so it should be safe to truncate this table also. Cachetags identify cache objects and you can get all related objects at once.
> 5 votes

# Answer
You could do this for a one-liner:

```
drush sqlq "TRUNCATE cache_default;TRUNCATE cache_bootstrap;TRUNCATE cache_container;TRUNCATE cache_discovery;TRUNCATE cache_data;" -l <uri> --no-interaction

```

Add as many with cache\_ prefix as you would like.
> 1 votes

# Answer
This is very handy. Replace dbname as needed:

```
DB_NAME="dbname"

mysql -uroot -proot --execute="SELECT concat('TRUNCATE TABLE ', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '${DB_NAME}' AND TABLE_NAME LIKE '%cache%'" | sed 1d | mysql -uroot -proot ${DB_NAME};

```
> 0 votes

---
Tags: 8, caching
---


# Question
Title: How can I give a list_string BaseFieldDefinition in a content entity a default starting value?
I have an entity with a list\_string field in my content entity that outputs to the entity form as a list of checkboxes. IE:

```
$fields['colors'] = BaseFieldDefinition::create("list_string")
  ->setSettings([
    'allowed_values' => ['blue' => 'Blue', 'red' => 'Red', 'green' => 'Green']
  ])
  ->setLabel('Color')
  ->setDescription('Select color')
  ->setRequired(TRUE)
  ->setCardinality(-1)
  ->setDisplayOptions('form', array(
    'type' => 'options_buttons',
    'weight' => 2,
  ))
  ->setDisplayConfigurable('form', TRUE);

```

Is there a way for me to give this field a default *starting* value. IE, when the user creates a new entity, red and green start out selected on the form?

# Answer
> 7 votes
You can use setDefaultValue method:

```
BaseFieldDefinition::setDefaultValue([['value' => 'red'], ['value' => 'green']])

```

That will also work for entities not created in the UI.

# Answer
> 2 votes
From https://api.drupal.org/api/examples/content\_entity\_example%21src%21Entity%21Contact.php/function/Contact%3A%3AbaseFieldDefinitions/8.x-1.x

```
// Role field for the contact.
  // The values shown in options are 'administrator' and 'user'.
  $fields['role'] = BaseFieldDefinition::create('list_string')
    ->setLabel(t('Role'))
    ->setDescription(t('The role of the Contact entity.'))
    ->setSettings([
    'allowed_values' => [
      'administrator' => 'administrator',
      'user' => 'user',
    ],
  ])
    ->setDefaultValue('user')
    ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => -2,
  ])
    ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => -2,
  ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

```

# Answer
> 0 votes
I found that adding this to the entity form file did the trick:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    /* @var $entity \Drupal\mymodule\Entity\MyEntity */
    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;

    if($entity->isNew())
    {
      $form['colors']['widget']['#default_value'] = ['red', 'green'];
    }

```

---
Tags: 8, entities
---


# Question
Title: How to remove CSS files if the page being rendered is a front page in a theme?
I want to remove default Drupal CSS files if it is a front page in Drupal 7 theme.

Following is the code (got from http://www.grahamgilchrist.com/blog/25) that I am trying to put in the template.php for barktik1 theme. How do I check if rendering page is a front page or not? Only $css variable is passed as an argument to the theme\_css\_alter() function while for other *process* functions $variables is passed from which it is easy to determine if it is a front page or not.

```
function bartik1_css_alter(&$css) {

//do something to check if it is a front page
if ($is_front){
    //make a list of module css to remove
    $css_to_remove = array();
    $css_to_remove[] = drupal_get_path('module','system').'/system.base.css';
    $css_to_remove[] = drupal_get_path('module','system').'/system.menus.css';

    // now we can remove the contribs from the array
    foreach ($css_to_remove as $index => $css_file) {
      unset($css[$css_file]);
    }
    }
}

```

Thanks!

# Answer
> 6 votes
The function you're looking for is `drupal_is_front_page()`.

# Answer
> 0 votes
In both Drupal 7 and 8 you have `hook_css_alter` for altering CSS files before output on the page.

If you want to remove some default css file from your Drupal 7 home page you can go with:

```
function YOUR_THEME_css_alter(&$css) {
  if (drupal_is_front_page() == TRUE  )  {
    unset($css['/'.drupal_get_path('theme', 'YOUR_THEME').'/css/removeme.css'] );
  }
}

```

---
Tags: 7, theming
---


# Question
Title: How to create a workflow state field programmatically?
I have my custom entity created, workflow module installed and now I would like to create a workflow state field on my entity. I know I have to do it in the `src/Entity/MyEntity.php` class in my module, but where do I get all those field settings for this particular field type for the `BaseFieldDefinition::create` method?

I have somehow managed to put this field definition in my entity class:

```
$field['workflow'] = BaseFieldDefinition::create('workflow')
  ->setLabel(t('Workflow'))
  ->setDescription('Workflow entity')
  ->setSetting('workflow_type', 'test_workflow');

```

But it does not add a field to my entity. Thanks.

EDIT: `test_workflow` is existing workflow.

# Answer
You should do it with entity\_reference and target\_type to be workflow, it should work like that. And with handler\_settings you can set your type of workflow.
> 0 votes

---
Tags: 8
---


title: domready is not defined

text:
# Question
Title: domready is not defined
I'm building my own theme to be used with Angular 4 and can't tell where/why Drupal is deciding to import jQuery.

Here's the code for my theme, loosely based off this Angular 1 theme:

**ng.info.yml**

```
name: ng
type: theme
libraries:
  - ng/base
description: 'An theme that makes Angular do all the work'
core: 8.x

```

**ng.libraries.yml**

```
base:
  version: 8.x
  js:
    js/inline.bundle.js: {}
    js/polyfills.bundle.js: {}
    js/styles.bundle.js: {}
    js/vendor.bundle.js: {}
    js/main.bundle.js: {}

```

**ng.module**

```
<?php
function ng_theme() {
  return array(
    'ng_view' => array(
      'template' => 'view',
      'variables' => array('title' => NULL),
    ),
  );
}

```

**ng.routing.yml**

```
ng.view:
  path: 'ng'
  defaults:
    _title: 'Drupal Angular'
    _controller: '\Drupal\ng\Controller\DrupalNgController::viewDrupalNg'
  requirements:
    _permission: 'access content'

```

**src/Controller/DrupalNgController**

```
namespace Drupal\ng\Controller;
use Drupal\Core\Controller\ControllerBase;
class DrupalNgController extends ControllerBase {
  public function viewDrupalNg() {
    $build['myelement'] = array(
      '#theme' => 'ng_view',
    );
    $build['myelement']['#attached']['library'][] = 'ng/inline.bundle';
    $build['myelement']['#attached']['library'][] = 'ng/polyfills.bundle';
    $build['myelement']['#attached']['library'][] = 'ng/styles.bundle';
    $build['myelement']['#attached']['library'][] = 'ng/vendor.bundle';
    $build['myelement']['#attached']['library'][] = 'ng/main.bundle';
    return $build;
  }
}

```

**templates/view.html.twig**

```
<html{{ html_attributes }}>
  <head>
    <title>Angular app</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="HandheldFriendly" content="true" />
    <meta name="apple-touch-fullscreen" content="YES" />
  </head>
  <body>
    <app-root></app-root>
  </body>
</html>

```

# Answer
> 0 votes
Given you didn't install any contrib modules nor themes, dozens of Drupal core modules requires Jquery to function. You'll have to check what modules lists JQuery as a dependency. Search in `core/modules` and `core/themes` directories for `core/jquery` and you'll find out what module/theme is adding it and disable it.

For example "contextual" module needs it.

# Answer
> -1 votes
Just add `core/domready` library to dependencies part of your theme libraries file: my\_theme.libraries.yml

```
...
script:
  ...
  dependencies:
     - core/jquery
     - core/jquery.once
     - core/drupal
     - core/domready

```

---
Tags: 8, javascript
---


# Question
Title: Database general error: 2006 MySQL server has gone away
Recently I started getting an error every time I try and add a content no matter what type. This is the error that shows up in the browser:

> Additional uncaught exception thrown while handling exception.
>
> Original PDOException: SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: SELECT COUNT(cid) FROM {comment} WHERE status = :status; Array ( \[:status\] =\> 0 ) in comment\_count\_unpublished() (line 313 of /Applications/MAMP/htdocs/modules/comment/comment.module).
>
> Additional
>
> PDOException: SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9); Array ( \[:db\_insert\_placeholder\_0\] =\> 1 \[:db\_insert\_placeholder\_1\] =\> php \[:db\_insert\_placeholder\_2\] =\> %type: !message in %function (line %line of %file). \[:db\_insert\_placeholder\_3\] =\> a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:154:"SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: SELECT COUNT(cid) FROM {comment} WHERE status = :status; Array ( \[:status\] => 0 ) ";s:9:"%function";s:27:"comment\_count\_unpublished()";s:5:"%file";s:56:"/Applications/MAMP/htdocs/modules/comment/comment.module";s:5:"%line";i:313;s:14:"severity\_level";i:3;} \[:db\_insert\_placeholder\_4\] =\> 3 \[:db\_insert\_placeholder\_5\] =\> \[:db\_insert\_placeholder\_6\] =\> http://localhost:8888/?q=node%2Fadd%2Farcade-project& \[:db\_insert\_placeholder\_7\] =\> http://localhost:8888/ \[:db\_insert\_placeholder\_8\] =\> 127.0.0.1 \[:db\_insert\_placeholder\_9\] =\> 1338336955 ) in dblog\_watchdog() (line 154 of /Applications/MAMP/htdocs/modules/dblog/dblog.module).

I also get the following error in my php error file:

> PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away' in /Applications/MAMP/htdocs/includes/database/database.inc:2136
>
> Stack trace:
> 0 /Applications/MAMP/htdocs/includes/database/database.inc(2136): PDOStatement-\>execute(Array)
> 1 /Applications/MAMP/htdocs/includes/database/database.inc(664): DatabaseStatementBase-\>execute(Array, Array)
> 2 /Applications/MAMP/htdocs/includes/database/database.inc(2315): DatabaseConnection-\>query('SELECT expire, ...', Array, Array)
> 3 /Applications/MAMP/htdocs/includes/lock.inc(167): db\_query('SELECT expire, ...', Array)
> 4 /Applications/MAMP/htdocs/includes/lock.inc(146): lock\_may\_be\_available('theme\_registry:...')
> 5 /Applications/MAMP/htdocs/includes/theme.inc(447): lock\_acquire('theme\_registry:...')
> 6 /Applications/MAMP/htdocs/includes/bootstrap.inc(427): ThemeRegistry-\>set(Array)
> 7 \[internal function\]: DrupalCacheArray-\>\__destruct()
> 8 {main} thrown in /Applications/MAMP/htdocs/includes/database/database.inc on line 2136

I am having a little trouble deciphering these error messages. Could anyone help me understand what's going on here?

# Answer
9 times out of 10 this error is caused by an insufficiently large `max_allowed_packet` setting in your MySQL server's my.cnf file.

The standard default for MAMP in my experience is 1M, which isn't usually enough for Drupal (especially considering the size of some of the cache strings it generates).

Try increasing that setting gradually to see if the error disappears. I'm sure a quick google search will tell you how to do that in MAMP.
> 39 votes

# Answer
This MySQL/MariaDB error:

> Error: 2006 (`CR_SERVER_GONE_ERROR`) - MySQL server has gone away

means basically that **the client couldn't send a question to the server**.

This could happen either by temporary glitch, too big or invalid SQL query, misconfiguration of your server or limitation of your hosting provider.

In general this error could be result of several things, such as:

* a query to the server is incorrect or too large,

Solution: **Increase `max_allowed_packet` variable**.

Note: Make sure the variable is under `[mysqld]` section, not `[mysql]`.

Note: Don't forget to restart the MySQL/MariaDB server.
* You got a timeout from the TCP/IP connection on the client side.

Solution: **Increase `wait_timeout` variable**.
* You tried to run a query after the connection to the server has been closed.

Solution: A logic error in the application should be corrected.
* Host name lookups failed (e.g. DNS server issue), or server has been started with `--skip-networking` option.

Another possibility is that your firewall blocks the MySQL port (e.g. 3306 by default).
* The running thread has been killed, so retry again.
* You have encountered a bug where the server died while executing the query.
* A client running on a different host does not have the necessary privileges to connect.
* And many more, so learn more at: B.5.2.9 MySQL server has gone away.

For further details, please check your MySQL or system logs (e.g. `/var/log/messages`).

To debug MySQL server or client, please check: 26.5 Debugging and Porting MySQL.

---

In case you're trying to import the database from the file using `drush` or `mysql` command, you can:

* Add a force option (`-f`) for `mysql` to proceed and execute rest of the queries.

This is useful if the database has some large queries related to cache which are large, but not relevant anyway.

Using `drush`, try: `cat foo.sql | $(drush sqlconnect) -f`
* Try applying `--max-allowed-packet` option for `mysql` with smaller values.
* **Increase `max_allowed_packet` and `wait_timeout`** in your server config (e.g. `~/.my.cnf`).
* Dump the original database again by using `--skip-extended-insert` option to break down the large queries. Then import the file again.

---

See also: ERROR 2006 (HY000): MySQL server has gone away
> 7 votes

# Answer
The answer that @Clive gives normally is the case, but there can be an additional cause, especially with node add forms.

Node add forms typically are big, and processing them can use a lot of memory (especially if there is any image processing during the save, like with the cropping modules). If the server runs out of memory, the mysqld process may get killed off which results in the same "gone away" message.

The clue is to look in the server logs. On a CentOS machine, you may see the following entry in /var/log/messages

> Jan 1 00:00:00 servername kernel: Out of memory: Kill process XXXX (mysqld) score XXX or sacrifice child
> Jan 1 00:00:00 servername kernel: Killed process XXXX, UID XX, (mysqld) total-vm:XXXkB, anon-rss:XXXkB, file-rss:XXkB

The solution here is to either add more RAM, or add/increase swap.
> 3 votes

# Answer
I've had great success in fixing the *2006 MySQL server has gone away* error with the following Drupal module:

Asynchronous Prefetch Database Query Cache

Just follow the installation instructions, which requires adding a few lines of code to `settings.php` and then visit `admin/reports/status` and apply advice given.

Most times, just by enabling the module and adding code to `settings.php` the error goes away straight away.
> 0 votes

---
Tags: database
---


# Question
Title: Unable to send e-mail. Contact the site administrator if the problem persists (in my localmachine)
I am using drupal on local machine .I am getting this error as Error : Unable to send email

The below is the report.

# Answer
> 2 votes
I guess negative because the post lack of details. Including Drupal Core version (6, 7, 8, 9 ?), name of the modules used to send mails (and it's version), which are required to provide some help/assistance, excpectally if you're not very familliar with Drupal :)

You're saying running the site under local environment, does it provide a mail-sender ? If not, mails can't be sent, then Drupal tell you "Mails can't be send". Nothing more.

If your env is providing a sender, please check if that one is properly configured to send mails (you can found various one-line-commands to check that point)

And then, if both of previous tests were successful, check under Drupal settings if you haven't misspelled a port or a service name (postfix, sendmail ...)

---
Tags: 8, emails
---


title: Different forms per user role

text:
# Question
Title: Different forms per user role
I need to hide the *description* field from regular users when entering data, but the field should be visible to administrator users, which also can edit it. I used the Display Suite module to hide that field by using different view modes, but I could not figure it out how to hide the field on forms. Any guidance would be appreciated!

>

# Answer
> 0 votes
Display Suite is not what you need, `field_permissions` is, check out the screen.

DS is mostly used to change the global look and the availability of some fields and labels (like Teaser, Product, Fullpage ...)

---
Tags: 7, display-suite
---


title: Ajax Effects using Ajax #commands

text:
# Question
Title: Ajax Effects using Ajax #commands
Assuming I have the following PHP. I want to add different effects to each of the ajax commands

```
function my_ajax_callback($form, $form_state) {
  $result = array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace($selector1, $html1),
      ajax_command_replace($selector2, $html2),
    ),
  );
  return $result;
}

```

I understand the default is something along the lines of:

```
ajax_command_replace($selector, $html, $settings = NULL)

```

However I do not know what to do with the $settings = NULL for a fade or slide to work. I've tried all combinations, but to no avail.

e.g.

```
ajax_command_replace($selector, $html, array('effect' => 'slide'),
ajax_command_replace($selector, $html, array('#effect' => 'slide'),
ajax_command_replace($selector, $html, 'slide')

```

# Answer
I found the best solution to this was using ajax\_command\_invoke() and layering the required ajax effects together.

For example, you won't be able to directly fade in an element, but you can use replace or prepend, etc., then hide the element, then fade it in.

```
function my_ajax_callback($form, $form_state) {
  $result = array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace($selector1, $html1), //add your element
      ajax_command_invoke($html1, 'hide'), //hide it
      ajax_command_invoke($html1, 'fadeIn'), //now use the effect you're after
      ajax_command_replace($selector2, $html2), //add your other element
      ajax_command_invoke($html2, 'hide'), //hide it
      ajax_command_invoke($html2, 'show'), //use the other effect
    ),
  );
  return $result;
}

```
> 1 votes

# Answer
You can add effects to command like this:

```
$command = ajax_command_replace($selector, $html);
$command['effect'] = 'fade';
$command['speed'] = 2000; // Speed in ms.

```
> 0 votes

---
Tags: ajax
---


title: Access uploaded file by ID

text:
# Question
Title: Access uploaded file by ID
I have a webform that allows users to upload their CV/Resume's. The webform is sending me the file ID. I know that the URL for accessing those files is https:// example.com/sites/default/files/webform/myfilename.

Can I access the file using the file ID instead of its name, for example https:// example.com/sites/default/files/webform?fileid=1502?

# Answer
If you're looking to do this in code, I believe that this question has already been answered:

Given a File ID (fid) how can I get the HTML that represents that fid?

You can also access the file's page at yoursiteurl/file/fid, but this isn't a direct link to the file.
> 1 votes

# Answer
Yes. You can use the drupal `file_load()` function to load the uploaded file.

```
<?php

$fid= 1502;
$file = file_load($fid);

?>

```

It will return the details of a file in the form of an array.

Hope it works for you!
> 0 votes

# Answer
`file_load()` has been deprecated

Instead, in a custom module you can use the function `Drupal\file\Entity\file::load($fid)` to load a file with the file ID that is present in the webform submission values

Here is an example :

```
  use Drupal\file\Entity;

  function student_support_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state){

     $values = $form_state->getValues();

       if(!empty($values['file'])){
         $file = Entity\File::load($values['file']);
         $values['file'] = $file->getFileUri();
       }
     ...
    }

```

Here 'file' is the key of your webform fileUpload element and $values\['file'\] would be an integer.
> 0 votes

---
Tags: webforms, files
---


# Question
Title: How to set up Drupal behind a proxy correctly?
I have a Drupal 7 website on the domain *hiddendomain.be:3200*. Users visiting *publicdomain.be* are proxied to the hidden domain. My home page is rendered just fine, but when I log in with the existing account *TestUser*, I get a "You don't have access rights to this page" message. It seems that Drupal still handles the user as anonymous, because going to *publicdomain.be/user* immediately afterwards returns the login form again. However, in the log report, a new session has been created for *TestUser*. Why does this happen?

I have been browsing the web for answers, but the only thing I found was to edit the `settings.php` file in the default directory (in my case that is `settings.local.php`) by adding

```
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('IP');

```

where IP is the IP address of the *publicdomain.be* server. Unfortunately, this does not work. What am I doing wrong?

# Answer
The problem has to do with how cookies are associated with domains. After you log into a Drupal site, Drupal sends a cookie to the browser that it uses in future requests to show it has been authenticated. Drupal associates that cookie with the domain that the login occurred on. Since your proxy sends requests to your Drupal site using the `hiddendomain.be` domain, that is the domain that Drupal associates the cookie with. However, the visitor's browser sends requests to `publicdomain.be`, and so considers the cookie it received from your Drupal site to belong to that domain. It is this discrepancy that is causing the problem.

To fix this, you need to configure Drupal to associate its cookies with the `publicdomain.be` domain. In your `settings.php` add, or update, the following line: `$cookie_domain='publicdomain.be';`

If your public and private domains share a root, then you can use the domain root as the `cookie_domain`. For example, if the public domain was `www.example.com`, and the private domain was `private.example.com`, then in `settings.php` you would have `$cookie_domain='.example.com';` (note that there is a dot before the domain).
> 3 votes

---
Tags: 7, proxies
---


# Question
Title: I cannot delete Devel generated content because I get an error about a not existing table
I'm trying to delete some generated content but I get an unhandled exception in the log.

> Drupal\Core\Entity\EntityStorageException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'databasename.url\_alias' doesn't exist: SELECT u.pid AS pid FROM {url\_alias} u WHERE (source = :db\_condition\_placeholder\_0) OR (source LIKE :db\_condition\_placeholder\_1 ESCAPE '\\'); Array ( \[:db\_condition\_placeholder\_0\] =\> /node/178 \[:db\_condition\_placeholder\_1\] =\> /node/178/% ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>delete() (line 794 of /var/www/html/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

The site is running on Drupal 8.8.0, and I installed the Pathauto module version 8.x-1.3.

How can I fix this issue?

# Answer
> 1 votes
Solved the issue by updating module Pathauto to 1.6 apparently the version I was using (1.3) had a compatibility issue with Drupal 8.8.0 on how path aliases are being handled now.

---
Tags: 8, database
---


title: Clean URLs caused site to break?

text:
# Question
Title: Clean URLs caused site to break?
I'm installing a new Drupal site using Red Hat... Getting Clean URLs to work was a pain in the you-know-what. I followed all the steps in the official drupal.org helpguide, but ended up needing extra help for a guide specific to RHEL users here: https://www.tecmint.com/install-drupal-in-centos-rhel-fedora/

I went into my httpd.conf file and made AllowOveride All as shown here: https://www.tecmint.com/wp-content/uploads/2013/07/Enable-Clean-URL-in-Drupal.png

I then fixed all of my directory issues in .htaccess (because my .htaccess file is in sites/web), and then all my admin links work perfectly. So Clean URLs is definitely enabled, but the issue now is the site is broken.

This was probably caused by enabling Clean URLs through the httpd.conf issue, but I'm not sure. I ran drush cr and it did nothing. Help?

# Answer
As leymannx and Kevin mention it is probably a misconfigured tmp/files directory

**Uncheck aggregate css** is something that you would not want on your live site as the performance will suffer.

Check in *Reports \> status report* (/admin/reports/status) and try to fix or report on the errors that you see.

Also go into *configuration \> media \> file system* (/admin/config/media/file-system) and correct any file system problems reported when saving the settings.

The most probable cause of what you are seeing is wrong permissions.

There is a lot of guides on the net about setting those permissions. You can start from the official guide on the subject or on one support thread that started as a drupal 7 thread but has Drupal 8 answers.
> 1 votes

---
Tags: 8
---


# Question
Title: EntityQuery condition for multivalue fields
I need to select some entities that have a certain field (user reference) empty or that field does not contain the current user as a reference.

I tried this. It works fine if the field is empty or if the field contains exactly one value. For multiple values, it displays the wrong value.

```
$query = $this->entityTypeManager()
  ->getStorage('my_entity_type')->getQuery();
$group = $query->orConditionGroup()
  ->notExists("my_field")
  ->condition("my_field", \Drupal::currentUser()->id(), "<>");
$query->condition($group);
$query->condition("type", "my_bundle_id");

```

What changes should I do to my code to make it work with a multi-value field?

# Answer
Use `NOT IN` instead of `<>`.

```
$query = $this->entityTypeManager()
  ->getStorage('my_entity_type')
  ->getQuery();
$group = $query->orConditionGroup()
  ->notExists("my_field")
  ->condition("my_field", \Drupal::currentUser()->id(), "<>");
$query->condition($group);
$query->condition("type", "my_bundle_id");

```
> 0 votes

---
Tags: 8
---


title: How to debug EntityMalformedException?

text:
# Question
Title: How to debug EntityMalformedException?
I've got fatal error *EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7700 of .\includes\common.inc)* **when trying to access user/xyz**.

I tried to retrieve info about the malformed node at line 7700, where the error message is built, thinks like :

```
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
 dpm($info);// or dpm($entity);
 throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

```

`dpm($entity)` returns an unexpected user object, and $info a huge qty of things.

Could somebody put me on the right way ?

I already read whatever I could find about *Missing bundle property* errors, but none helped solving.

`dpm($entity)` returns

```
uid (String, 2 characters ) 70
name (String, 9 characters ) John
pass (String, 55 characters ) $S$DUwPuOuDPiDL4nRTYXqc7a5uOfMKey7pyhOFUEKka1XM...
mail (String, 30 characters ) john@example.com
theme (String, 0 characters )
signature (String, 0 characters )
signature_format (String, 13 characters ) filtered_html
created (String, 10 characters ) 1396286331
access (String, 10 characters ) 1397146661
login (String, 10 characters ) 1396513460
status (String, 1 characters ) 1
timezone (NULL)
language (String, 2 characters ) fr
picture (NULL)
init (String, 30 characters ) john@example.com
data (Array, 5 elements)
roles (Array, 1 element)
og_user_node (Array, 0 elements)
message_subscribe_email (Array, 1 element)
field_bio (Array, 0 elements)
field_name_first (Array, 1 element)
field_name_last (Array, 1 element)
field_facebook_url (Array, 0 elements)
field_linkedin_url (Array, 0 elements)
field_twitter_url (Array, 0 elements)
user_trusted_contacts (Array, 1 element)
group_group (Array, 1 element)
group_access (Array, 1 element)
metatags (Array, 0 elements)
rdf_mapping (Array, 3 elements)
realname (String, 13 characters ) John Doe
content (Array, 13 elements)
entity_view_prepared (Boolean) TRUE
privatemsg_disabled (Boolean) FALSE

```

# Answer
> 8 votes
Thanks to Clive comments, I solved the issue as following.

Added `ddebug_backtrace()` where error occured (*entity\_extract\_ids(), line 7700 of .\includes\common.inc* ) to print the function call stack.

Then looking for anything unexpected in output, I found that a **pane visibility rule** might be the problem.

```
19: ctools_entity_field_value_ctools_access_check() (Array, 2 elements)
  file (String, 81 characters ) profiles\commons\modules\contrib\ctools\plugins...
  $...['19: ctools_entity_field_value_ctools_access_check()']['file']
    profiles\commons\modules\contrib\ctools\plugins\access\entity_field_value.inc:213
  args (Array, 3 elements)
    0 (Array, 2 elements)
      field_theme (Array, 1 element)
      //...

```

I had applied a patch on `entity_field_value.inc` a few days ago just to solve a visibility rule notice... and created a test visibility rule with a field\_theme condition.

Now reverting patch or removing any pane visibility rule solved current EntityMalformedException bug... Powerful `ddebug_backtrace()` !

# Answer
> 37 votes
The error:

> EntityMalformedException: Missing bundle property on entity of type node.

happens, because your bundle property is malformed either on load or save, so Drupal can't find what type of bundle is it.

The logic of that Exception is:

```
// Explicitly fail for malformed entities missing the bundle property.
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  // var_dump(debug_backtrace()); exit; // You may want this line to debug.
  throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

```

So basically value of `$info['entity keys']['bundle']` (for node it's: `type`) can't be found in `$entity` object (`$node->type` for the node), therefore Drupal doesn't know with what kind of entity it's dealing with. So most likely your entity is invalid (e.g. you're loading something else instead) or it is just empty (`$entity` is `NULL`).

---

If you haven't modified any Drupal code, this potentially can be caused by variety of things (most likely by specific Drupal module bug), such as:

Here is the responsible code which is thrown by Drupal core (file: `common.inc`):

```
 if (!empty($info['entity keys']['bundle'])) {
    // Explicitly fail for malformed entities missing the bundle property.
    if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
      throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
    }
    $bundle = $entity->{$info['entity keys']['bundle']};
  }

```

---

### Debugging

If you don't recognise anything above, the easiest thing to debug that kind of error is by placing `var_dump(debug_backtrace());` or `dd(debug_backtrace());` (when Devel is on) before the actual `throw new EntityMalformedException` on the affected line in `common.inc`.

Note: Using `dd()` function from Devel will generate the debugging info to the file in your Drupal temp folder (`temporary://drupal_debug.txt`) with backtrace dump, otherwise could be too big and difficult to read when dumping on the screen. When using `var_dump()`, it's easier to call `die();` after the call and check the dump in the view-source mode of the page.

If this is happening on node save, check this EntityMalformedException post at SO for more detailed instructions.

---

See also the following Drupal issue: #1778572 for more ideas.

# Answer
> 0 votes
This issue comes up when there are orphaned nodes, simply get rid of them and cron will run without any error. Search indexing will finally get to 100%. Backup your database before proceeding.

Assuming you have access to phpMyAdmin, run this SQL code to identify the nodes then delete them. Replace my **question** content type machine name with your specific content type machine name one after the other till you get no result, that's after deleting.

`SELECT n.nid, n.title, n.vid, nr.vid FROM drcm_node n LEFT JOIN drcm_node_revision nr ON nr.nid = n.nid WHERE n.type = 'question' AND nr.vid IS NULL ORDER BY n.nid ASC`

You can delete the orphaned nodes by using the SQL code below. Replace the numbers in the bracket with your specific node IDs

`DELETE from node where nid IN (12779,12780,12781,12782)`

---
Tags: entities, debugging
---


# Question
Title: Get the ID that for the node that has been just created
I am trying to get the node ID that I have just created. If I do the following code from this answer.

```
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

```

I implemented `hook_ENTITY_TYPE_view()` (just to test the code), but it gets the ID for all the nodes, while I want the ID of the node that has been created to modify a field value for that node. Is this possible?

Should I use the code I shown in a `hook_form_alter()` implementation or maybe inside a form submission handler?

# Answer
If you need to alter the value of a node field right after the node has been created, you don't need that code. You just need to implement `hook_ENTITY_TYPE_presave()` and verify the node is new.

```
function mymodule_node_presave(EntityInterface $entity) {
  if ($entity->isNew()) {
    // The node has been created.
    // Access the node field using $entity.
  }
}

```

If then, for any reason, you need the node ID, you can access it with `$entity->id()`.

I used `hook_ENTITY_TYPE_presave()`, assuming the node needs to be saved with the new field value.
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: Hide the header of a view block when there is no content
On a page, a views block should show some text on top of the view when the block doesn't hide and there is content to show: `<h4>Title <span class="dot white">•</span></h4>`. Now, when there is no content in the block, this text should be hidden. I've tried to do this with putting the header in the view as 'unfiltered text' in 'header' and then setting the view to hide when there's no content. This doesn't work or could it be that I'm doing something wrong?

Update, I got it to work, and think the following is happening: It is possible to just put this text in the header of the view as 'unfiltered text' in 'header' and it will hide when there are no results. However, when the view is based on a taxonomy relationship as it was with mine, and 'require this relationship' is not set, there will always be a result, so the header will show eventhough those results are filtered away.

# Answer
> 2 votes
Well I think you are asking how to hide a **block view** completely when it is inserted as a `global: view area` in the header of another view.

> **For the parent view:**

When inserting the **block view** into the header of another view, make sure you leave the box **unchecked** that says: `Display even if view has no result`

> **For the block view that is being inserted check these 3 things:**

**1:** If you are displaying fields in the **block view**, you want first make sure you are hiding any empty fields under `Show: Fields | Settings`

**2:** Then you want make sure you you have the `Hide block if the view output is empty:` set to `yes` under the **advanced** tab in the **block view**.

**3:** You also want to add a contextual filter for the **block view** that defines the context you want. Then set the **WHEN THE FILTER VALUE IS *NOT* AVAILABLE** setting to `hide view`. (For the image below, my context needed was taxonomy term ID.)

Hope this helps!

---
Tags: views, 8
---


# Question
Title: How to dynamically make a field visible?
I'm trying to render a field based on a select value. However I couldn't succeed for now, so here is what I tried:

I created a content type with a select field (field\_type)

```
var_dump($form['field_type']['und']['#options']);

```

gives

```
array (size=5)
  '_none' => string '- Select a value -' (length=18)
  'externe' => string 'externe' (length=7)
  'interne' => string 'interne' (length=7)
  'carroussel' => string 'carroussel' (length=10)
  'vitrine' => string 'vitrine' (length=7)

```

I noticed 'und' by printing my field and reading the first comment on this page Drupal process states 7.x

and my field that should be visible (or not)

```
$form['field_target_text'] = array(
        '#type' => 'textfield',
        '#default_value' => '',
        '#states' => array(
          'visible' => array(
            'input[name="field_type[und]"' => array('value'=>'interne')
          ),
        ),
      );

```

I tried to replace input with select, to remove \[und\] but nothing did the job until I replaced the field like this

```
$form['field_type'] = [
        '#type' => 'select',
        '#title' => ('TYPE TPE'),
        '#description' => ('TEST.'),
        '#options' => $form['field_type']['und']['#options']
      ];

```

Seems like he doesn't like my field not having an \['#options'\] but \['und'\]\['#options'\]. However by doing so, when I save my node, the field\_type is empty.

Any help or advise would be appreciated.

# Answer
You miss `]` in the selector `':input[name="field_type[und]"'` code test with the following it will work.

```
':input[name="field_type[und]"]' => ['value' => 'interne'],

```

**Update:**
The state work with any valid JQuery selector, so if you looking to target it with `select` selector instead of `:input` you can use this:

```
 'select[name="field_type[und]"]' => ['value' => 'interne'],

```
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How can I add styles attribute to Global Custom field markup?
I have created a view to display my articles and I would like the article thumbnails to be used as background. So I added the different fields I've hidden.

I added a relationship to the image field to get the thumbnail URI. Then I added the following code in the custom global field.

```
<div class="post-datas" style="background-image: url('{{ uri }}')">
<span class="category-art">{{ field_categorie }}</span>
<h3 class="title-art">{{ title }}</h3>
<span class="date-art">{{ created }}</span>
</div>

```

But on display, the style is ignored.

Instead of `<div class="post-datas" style="background-image: url('http://adresse">`, I have `<div class="post-datas">`.

How can I make Views to print the style attribute to let me put a dynamic background image URI?

# Answer
> 0 votes
Drupal 8 views will strip away any markup it thinks it is dangerous

you have to rely on a custom theme solution here is a general overview of how this can be done

1. if you don't have a custom theme you have to create one (more info)
2. Enable Twig debugging (more info)
3. Inspect your page in browser to find the appropriate templates to override. In the html comments you will find which .twig template is responsible to output a specific piece of html markup (More info)
4. Copy required template into your CUSTOM\_THEME/theme folder
5. Add or modify the markup in the twig template

Alternatively you might want to give https://www.drupal.org/project/viewscss a try which promises to allow viewscss but it does not have a stable release.

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


# Question
Title: js file in custom module's library is not attached when big pipe is running
I have a custom module, filter\_component, that provides a form. In the form I have:

```
$form['#attached']['library'][] = 'filter_component/filter-component';

```

In filter\_component.libraries.yml I have:

```
filter-component:
  version: 1.x
  js:
    js/filter_component.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

```

filter\_component.js begins with:

```
(function ($, Drupal) {
    Drupal.behaviors.filterComponent = {
        attach: function (context, settings) {
            $('.block-filter-component', context).once('filterComponent').each(function() {

```

Everything works fine, but only if big\_pipe is disabled. When it is enabled, the code is not attached and the js file is not listed in page source or in browser tools as a source.

# Answer
So it turns out that it was big pipe, but unrelated to my module. Elsewhere on the page a profile image is loaded to appear next to the user name, and if the user has none, a default image. It seems that if a 404 is returned (in this case because part of the oath did not yet exist to match the path supplied for the image), when big pipe goes to load it and gets the 404, downstream js is not loaded.
> 0 votes

---
Tags: javascript
---


# Question
Title: Using feeds_ex to import content to drupal using 2 steps API calls
I am trying to import data to Drupal 8 website using Feeds and Feeds\_ex module and here is my scenario:

* I need to make a call to the first JSON API and extract the IDs from it, here is a sample of the API

```
{
"rm": [{
    "mn": "Friday",
    "id": 3003,
    "ra": "JEB  ",
    "md": "2019-11-01 00:00:00.0"
}, {
    "mn": "Saturday",
    "id": 3014,
    "ra": "SHJ  ",
    "md": "2019-11-02 00:00:00.0"
}]

```

}
* Then I want to use the extracted IDs to construct custom URLs to get the actual data that I want to import.

http:/somewebsite/api/index.php?id=1234

I looked to Feeds documentation to create a custom fetcher with no luck.Any advice?

# Answer
> 1 votes
The trick is to create a new parser, not a new fetcher. I created a new module and a new parser at the following: New files at MY\_MODULE/src/Feeds/Parser/MymoduleJsonPathParser.php

I wanted to build on top of the feeds\_ex module so I used their interfaces as the following:

```
use RuntimeException;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\feeds\FeedInterface;
use Drupal\feeds\Result\FetcherResultInterface;
use Drupal\feeds\Result\ParserResultInterface;
use Drupal\feeds\StateInterface;
use Peekmo\JsonPath\JsonStore;
use Drupal\feeds_ex\feeds\Parser\JsonParserBase;
use Drupal\feeds_ex\feeds\Parser\ParserBase;
use Drupal\Core\Form\FormStateInterface;

```

If you would like to add custom options that appear at the feeds UI add your custom form at the following:

```
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);

$form['FIELD'] = [ .....];
return $form;

```

}

Now you can build on your custom parser:

```
    protected function executeContext(FeedInterface $feed, FetcherResultInterface $fetcher_result, StateInterface $state) {
    $raw = $this->prepareRaw($fetcher_result);
    $parsed = $this->utility->decodeJsonArray($raw);
    // Your code gose here.
  }

```

I am writing a custom module and I will share it here when it's finished.

---
Tags: feeds, 8
---


# Question
Title: Error guzzlehttp/guzzle ^6.3 -> no matching package found when update from 8.7.9 to 8.8.1
When i tried to update my project using composer from `8.7.9` to `8.8.1` i get the following error:

Command:

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

```

> \[Composer\DependencyResolver\SolverProblemsException\] Problem 1 \- Installation request for drupal/core 8.8.1 -\> satisfiable by drupal/core\[8.8.1\].
> \- drupal/core 8.8.1 requires guzzlehttp/guzzle ^6.3 -\> no matching package found. Problem 2 .
> \- drupal/core 8.8.1 requires guzzlehttp/guzzle ^6.3 -\> no matching package found.
> \- drupal/ultimate\_cron 2.x-dev requires drupal/core ^8.5 -\> satisfiable by drupal/core\[8.8.1\].
> \- Installation request for drupal/ultimate\_cron ^2.0 -\> satisfiable by drupal/ultimate\_cron\[2.x-dev\].
>
> Potential causes:
> \- A typo in the package name .
> \- The package is not available in a stable-enough version according to your minimum-stability setting . see https://getcomposer.org/doc/04-schema.md#minimum-stability for more details.
> \- It's a private package and you forgot to add a custom repository to find it

Any ideas ?

# Answer
I have just to remove the `vendor` Folder it works now:
For the complete steps see 8.5.6 Update not being recognized .
> 0 votes

---
Tags: 8, updating, composer
---


# Question
Title: How do I add extra cost with cash on delivery?
I have implemented and eshop with commerce module in drupal 8. How can I add extra cost in case the customer chooses the cash on delivery method? I use payment module. Is there any solution or some other alternative? I tried rules also, but there is not any event that is triggered on payment method selection.

# Answer
It's been a long time since this has been asked, but I'm adding my input here since I bumped into this while looking for the exact same thing for one of my projects. The way I found as the cleanest and most straight forward, while reading through the documentation, is the use of an order processor class that would check the current order for the use of the payment method in question and add an adjustment accordingly. You can have a look here on information as to how to setup an order processor https://docs.drupalcommerce.org/commerce2/developer-guide/orders/order-refresh-and-process. The class has to implement the \Drupal\commerce\_order\OrderProcessorInterface and it has to provide an implementation of the process method.

```
class MyCustomProcessor implements OrderProcessorInterface {

    public function process(OrderInterface $order) {
        $payment = $order->get('payment_method')->first()->entity;
//   or
        $payment = $order->get('payment_gateway')->first()->entity;

//... your logic here depending on what you'd like to do

        $order->addAdjustment(new Adjustment([
            'type' => 'fee',
            'label' => 'Payment method fee',
            'amount' => new Price($fee, 'EUR')
        ]));

    }
}

```

Based on the instructions above have created this example module https://github.com/GiorgosK/commerce\_custom\_fees
> 3 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: How do I dynamically populate a select field?
this question comes quite often but I couldn't make it work to that point. My problem is simple, I have a 2 level taxonomy, I have 2 select fields, one is populated with the parent taxonomy and the second should be populated by its children when one parent is selected.

But I'm a bit confused. I followed the developer example with the check-boxes, but still. Also, this happens in `hook_form_alter()` and since I'm quite new to Drupal 7, I have to set the options with the `['und']` prefix, but that also troubles my mind because when I omit the `['und']` part when I try to save the node, an error says *Illegal choice*.

This is my first select field.

```
  //Field TYPE
  $form['field_type']['und']['#options'] = std_to_array($vocabulary_nudge_all);
  $form['field_type']['#ajax'] = array(
    'callback' => 'ajax_nudge_taxonomy_selected_callback',
    'wrapper' => 'select-target-div',
    'method' => 'replace',
    'effect' => 'fade',
  );

```

This is the AJAX callback function where I tried to get the *field\_type* value, but I read somewhere that I couldn't use `$form_state` in a form hook.

```
function ajax_nudge_taxonomy_selected_callback($form, $form_state) {
  return $form['field_target_select'];
}

```

Using `$form`, all I could think of was using `#delta`.

```
$selected = $form['field_type']['und']['#delta']

```

In the second select with a prefix, a suffix, and a visible condition, I am using the following code.

```
//Field Target SELECT
$form['field_target_select']['#weight'] = '0';
$form['field_target_select']['#prefix'] = '<div id="select-target-div">';
$form['field_target_select']['#suffix'] = '</div>';
$form['field_target_select']['und']['#options'] = std_to_array($vocabulary_nudge_all);
$form['field_target_select']['#states'] = array(
  'visible' => array(
    ':input[name="field_type[und]"]' => array(
      array('value' => 'carroussel'),
      array('value' => 'vitrine'),
    ),
  ),
);

```

I know there would be a solution by creating several select fields with visible conditions, but later more taxonomy fields could be added.

Right now it's not even doing the AJAX call anymore, and I can't manage to fix this, so any help would be appreciated.

# Answer
> I read somewhere that I couldn't use $form\_state in a form hook

Not quite. If `hook_form_alter()` is being executed for the first time, then yes, `$form_state` can't be used to get a field's value because `$form_state['values']` will not be set.

However, if `hook_form_alter()` is being **re-executed**, like from an `#ajax` callback, then `$form_state['values']` will be set with the current form values, just like it would be in `#submit[]` and `#validate[]` functions. By the way, the `$form['#validate'][]` functions are also executed during an `#ajax` callback.

In your case, I believe you would get the current value of `field_type` from `$form_state['values']['field_type'][LANGUAGE_NONE][0]` (best to use the constant `LANGUAGE_NONE` instead of the string `'und'`). Wherever you build the `#options` array for `field_target_select` during the execution of `hook_form_alter()`, you would do something like this:

```
$selected = 'some_default_value';
if (!empty($form_state['values']['field_type'][LANGUAGE_NONE][0])) {
  $selected = $form_state['values']['field_type'][LANGUAGE_NONE][0];
}
$child_options = my_function_to_get_child_options($selected);
$form['field_target_select'][LANGUAGE_NONE]['#options'] = $child_options;

```

What you have as your ajax callback function in your question looks correct:

```
function ajax_nudge_taxonomy_selected_callback($form, $form_state) {
  return $form['field_target_select'];
}

```
> 0 votes

---
Tags: 7, ajax, taxonomy-terms
---


# Question
Title: How do I override the date filter to filter by years instead of exact date?
I want to add another option to `Date` filter to filter with only years not the exacte date.
So i want to add another radio option here:
**Like:**

The above options added by Date Filter.
I have tried two ways:

1. Add new filter like date filter:
**modules/custom/my\_module/src/Plugin/views/filter/DateYear.php**

```

namespace Drupal\my_module\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\filter\NumericFilter;

/**
 * Filter to handle dates stored as a timestamp.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("date_year")
 */
class DateYear extends NumericFilter {
  // Same Code Date class with a little changes.
}

```
2. I tried to extend `Date` class and alter date filter plugin.
    * I create Class DateYear extending Date filter class:

```

namespace Drupal\my_module\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\filter\Date;
/**
 * Filter to handle dates stored as a timestamp.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("date_year")
 */
class DateYear extends Date {
  // Override valueForm method..
}

```
* Then i implement `hook_views_plugins_filter_alter` to override class.

```

   /**
 * Implements hook_views_plugins_filter_alter().
 */
function cam_views_views_plugins_filter_alter(array &$plugins) {
  if ($plugins['date']) {
    $plugins['date']['class'] = 'Drupal\my_module\Plugin\views\filter\DateYear';
  }
}

```

But none of the above works ?

# Answer
I contribute a module for this check it out here:

> This module add views filter by year exact, instead of full date like mm-dd-yyyy you can use date year like yyyy.

https://www.drupal.org/project/views\_year\_filter
> 0 votes

---
Tags: views, 8
---


title: Button act as submit button in form API

text:
# Question
Title: Button act as submit button in form API
I have a button element in form builder as follows

```
$form['fieldset']['add_new_event_btn'] = array(
  '#value' => t('Add new event trigger'),
  '#type' => 'button',
  '#attributes' => array(
    'style' => 'margin-top:20px;width:200px;margin-right:275px;float:right',
  ),
  '#ajax' => array(
    // Function to call when event on form element triggered.
    'callback' => '::enable_event_trigger',
    // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
    'effect' => 'fade',
    // Javascript event to trigger Ajax. Currently for: 'onchange'.
    'event' => 'click',
    'progress' => array(
      // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
      'type' => 'throbber',
      // Message to show along progress graphic. Default: 'Please wait...'.
      'message' => 'loading',
    ),
  ),
);

```

But **this button is act as the submit button** , and there for **the validation for other elements works and shows the error message on the next reload when i leave the page as it is**, How can i rectify this problem ??

# Answer
> 1 votes
As mentioned in the comments, this is not supported yet but it might at some point: https://www.drupal.org/project/drupal/issues/1671190

What you can do is `return false` in the onclick event. For example:

```
$form[button] = array(
  '#type' => 'button',
  '#name' => 'button',
  '#value' => "Do some JS",
  "#attributes" => array(
    "onclick" => "doJs(); return false;",
  ),
);

```

---
Tags: forms, 8
---


# Question
Title: Best practice caching a variable between page loads
In Drupal 7...

In the case of a value that is only set through a module's settings page, and then remains unchanged until an administrator changes it (or the module is updated).

The value is checked each page load to perform a specific action. I'd prefer to prevent a DB read on each page load, for obvious reasons.

I can, of course, use variable\_set and cache\_get, but I was wondering...

A) Performance and behaviour wise, what is the actual difference between the two (both need database tables as far as I can see)?

B) Is there an equivalent to SESSION variable that this would be better in?

C) Would this be better off in a singleton class / global static value instead?

# Answer
A) I highly recommend to measure your assumptions. Database might not be as bad as you think. The answer also depends on whether you ask for a sites that you control or whether you are writing a public module that has to play well with the whole ecosystem.

The main difference between `variable_set` and `cache_set` is how important the value is. Cache is intended for things that can be generated. Another difference is how modules interact with in. There are alternative cache backends, which won't write the value to the default database but typically some type of key-value store.

B) The `$_SESSION` variable from PHP can certainly be used by a Drupal 7 module. By default, PHP saves the session as a file in the local file system.

You can also use key-value stores such as Redis or APCu.

C) A class sounds much better from the perspective of testability via PHPUnit, but singletons don't play well with testing either.
> 2 votes

---
Tags: 7, caching
---


title: How can I alter Easy Breadcrumb?

text:
# Question
Title: How can I alter Easy Breadcrumb?
I want to remove certain element of breadcrumb on certain condition. I tried `theme_preprocess_breadcrumb($variables)`. The condition and logic works fine here but doesn't reflect on viewing page. I tried this `module_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb)` – same issue. Code here doesn't reflect on viewing page, though printing variables in both methods gives me expected result but not on viewing page. I need help.

```
function theme_preprocess_breadcrumb($variables) {
// Removing last element of breadcrumb
if ( $variables['breadcrumb'] ) {
$currentUrl = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$key = 'find this';
$countElements = count($variables['breadcrumb']);
if (strpos($currentUrl, $key) == true) {
  unset($variables['links'][$countElements-1]);
  unset($variables['breadcrumb'][$countElements-1]);
  kint($variables['breadcrumb']);kint($variables);die;
}
}
return $variables;
}

```

# Answer
> 4 votes
As it mentioned in the comment section the `$variables` should passed by reference take a look at `hook_preprocess_HOOK` documentation page.
And also read about strpos to adapt your condition, here is an example of code to remove the last breadcrumb element in case url contain the word ***article*** for instance.

```
/**
 * Implements hook__preprocess_HOOK().
 */
function YOURTHEMENAME_preprocess_breadcrumb(&$variables) {
  // Removing the last element of the breadcrumb
  if ($variables['breadcrumb']) {
    $current_path = \Drupal::service('path.current')->getPath();
    // Get the real path even if it has an alias.
    $real_path = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
    $key = 'article';
    if (strpos($real_path, $key)) {
      // Remove the last element.
      array_pop($variables['breadcrumb']);
    }
  }
}

```

---
Tags: 8, breadcrumbs
---


# Question
Title: How do I prevent delimiters in a URL from being URL encoded?
I need to know how to get a `+`-delimited string to be appended to the end of the URL path without the `+` character being URL encoded.

Why: I'm trying to pass arguments to a View. I'm working on a custom module to conditionally route webform confirmations to a View. The view will take multiple arguments, returning all nodes matching the arguments (currently trying to do this with Views 3.0).

I've done proof-of-concept tests on the view that demonstrate that for a view with a path of, say, `cbos/name1+name2` it will produce the desired result (i.e., displays nodes name1 and name2). So I know that this can be done from the Views side. (I'm pretty certain at this point Views has nothing to do with it, I just need to make clear why I need to do this.)

The problem is on the custom module / webform side.

I'm creating the URL path using the following code:

```
while ($cbo_short_name = db_fetch_array($result)) {
if ($count > 0) $delim = '+';
$cbo_short_names_arg .= $delim.$cbo_short_name['cbo_short_name'];
$count = $count + 1;
}
$redirecturl = "cbos/".$cbo_short_names_arg;
$node->webform['confirmation'] = drupal_urlencode($redirecturl); // ... have also tried setting this via the form settings page using tokens

```

... where `$cbo_short_name` is an array of short names (usually initials) for organizations. (There's usually only 1, but in about 15% of cases there will be 2 or 3 short names. The visitor has to be shown all of them. Hence, the View)

What this should do is produce a URL path of the form given above; what's happening is that '+' is getting URL encoded as %2B (e.g. `cbos/name1%2Bname2`), which breaks the Views argument string -- only the first result is returned.

If I could somehow force '+' to be passed intact, without URL encoding, this would work. But I'm at a loss for how to do that.

What I've tried so far:

* Setting the confirmation URL on the form settings page (preferred, since I don't have to hard code it).
* Setting the redirect URL programmatically (what you see above).

Both work to set a value, but in both cases the delimiters are URL encoded in the resulting URL path.

# Answer
> 0 votes
I am sure I am missing a or the point here, but, could you do something like this:

```
while ($cbo_short_name = db_fetch_array($result)) {
  if ($count > 0) $delim = '+';
  $cbo_short_names_arg .= $delim . drupal_urlencode($cbo_short_name['cbo_short_name']);
}
$redirecturl = 'cbos/' . $cbo_short_names_arg;
$node->webform['confirmation'] = $redirecturl;

```

eg, sanitize your arguments but then glue them together with the `+` (that isn't encoded) ?

# Answer
> 0 votes
I don't think there is any build in Drupal helper function to do so, there is `drupal_http_build_query` to build query but it support only `&`as separator.

I think you should get your hand dirty a little bit and implement something for your use case take a look at this discussion about ***how to prevent drupal\_goto from encoding plus and comma characters?***
for your use case there is this ***`suggestion`*** and also this ***`suggestion`***.

But first try with something like, add a function in your module like :

```
function custom_drupal_encode_path($path) {
  return str_replace(['%2F', '%2B'], ['/', '+'], rawurlencode($path));
}

```

and test with:

```
$node->webform['confirmation'] = custom_drupal_encode_path($redirecturl);

```

---
Tags: uri
---


title: Change "Custom Text" field value

text:
# Question
Title: Change "Custom Text" field value
In Drupal 8, I created a view containing a *Custom Text* field. I want to alter/change its content for each row I get after running some code. I tried implementing `hook_views_pre_render()` and `template_preprocess_views_view_fields()`, but I wasn't able to access this field.

I also would like to learn when this *nothing* field is added to the view output, and after which hook.

# Answer
> 3 votes
To extend and clarify Saud Alfadhli's answer for others (I'm not allowed to comment yet), hook\_preprocess\_views\_view\_field (hook\_preprocess\_views\_view\_fields with the "s" exists as well) works great for this. Both the view ID, display ID, and field ID can be easily inferred from this hook, and the field output can easily get overwritten (as both a string or render array). Here's a quick example replacing all occurrences of my second custom text field with a simple string:

```
/**
 * Implements hook_preprocess_views_view_field().
 */
function hook_preprocess_views_view_field(&$variables) {
  if ($variables['view']->id() === 'my_view_id' && $variables['field']->options['id'] === 'nothing_2') {
    $variables['output'] = 'Hi Mom!';
  }
}

```

Hope this helps!

# Answer
> 1 votes
I tried to do this with a lot of (Views) hooks, but with no luck because of the (nothing) field seems not part of the entity data.

Finally I managed to alter that value by implementing theme `template_preprocess_views_view_fields()` in my module.

```
/**
 * Implements template_preprocess_views_view_fields().
 */
function MODULENAME_preprocess_views_view_field(&$vars) {
  // Print all available fields.
  foreach ($vars['view']->field as $key => $field) {
    // We will print the field name.
    print $key . '<HR>';
  }
  exit;

  // To access current row entity.
  $entity = $vars['row']->_entity;
  $entity_id = $entity->id();

  // To access entities from relationship.
  $entities = $vars['row']->_relationship_entities;

  // When you find your field key use this code below.
  if(isset($vars['view']) && ($vars['view']->id() == 'VIEW_MACHINE_NAME') && ($vars['view']->current_display == 'DISPLAY_MACHINE_NAME')) {
    if (isset($vars['view']->field) && (count($vars['view']->field) > 0)) {
      // if ($vars['field']->field == 'YOUR_FIELD_NAME')
      if ($vars['field']->field == 'nothing') {
        $vars['output'] =  [
          '#markup' => 'WRITE_NEW_VALUE_HERE_OR_CHANGE_THIS_RENDERABLE_ARRAY_TO_RENDERABLE_IMAGE_OR_WHATEVERY_YOU_WANT',
        ];
      }
    }
  }
}

```

---
Tags: views, 8
---


title: Align embedded Media Images

text:
# Question
Title: Align embedded Media Images
When I embed an image into CKEditor text I can choose alignment options. When I embed a Media Image I cannot choose alignment, but a Media View. A media View allows me to specify image size (via image style) but not alignment

Embedding an Image does not add the image to the Media Library and it would be nice to *only* use Media Image embedding so as to manage the site's media library of images.

What is the preferred way of specifying the alignment of embedded Media?

**Background**

I am switching over to simply using core Media modules in Drupal 8.8. I have ditched what I was previously using:
* Embed
* Entity Embed
* DropzoneJS entity browser widget
* Entity Browser
* Entity Browser IEF

# Answer
> 2 votes
The easiest to resolve (and most likely) issue is:

You are limiting the allowed HTML tags for the text format you're using and you haven't allowed the align (and also caption, if you want captions) attributes for the `drupal-entity` HTML element. (I'm assuming you do have the `Align images` and `Caption images` filters enabled because you said those features were working for non-media embeds. If they're not enabled, enable them.)

**Solution:**

In the "Limit allowed HTML tags and correct faulty HTML" section (`/admin/config/content/formats/manage/MY_FORMAT#edit-filters-filter-html-settings`), make sure the `drupal-entity` has at least the `data-align` (and `data-caption` for captions) attributes. E.g. `<drupal-entity data-align data-caption data-etc...>`.

---
Tags: 8, media
---