# Question
Title: Is it possible with one of the template suggestion hooks to also specify a new template location?
In a custom module I'm adding a custom page template suggestion per multi-site like following which would then search for `page--MYSITE.html.twig` in the current theme's `/templates` folder.

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

  $site_path = \Drupal::service('site.path');
  $site_path = explode('/', $site_path);
  $site_name = $site_path[1];

  $suggestions[] = 'page__' . $site_name;
}

```

**Question**: Is it possible to also specify a new location for this template. Like let's say inside my custom module's `/templates` folder?

**Why**: It would let me use a core theme but with my custom template (without the need to add something custom to core or to create a new sub-theme, lazy as I am).

There are 3 suggestion hooks that come into my mind but with none if them it seems possible to also specify a custom location. Is this right? Or is there a way? Is it bad practice to do so?

# Answer
> 1 votes
> *Is it possible with one of the template suggestion hooks to also specify a new template location?*

You can specify a new template location in hook\_theme():

> **path**: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.

---

> *Like let's say inside my custom module's /templates folder?*

This means when using hook\_theme() instead of hook\__theme\_suggestions\_\* the module's template folder is already default and you don't need to specify `path`.

So you can use this answer hook\_theme\_suggestions\_page() provide default template file inside module folder.

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


title: Filtered View gives duplicates

text:
# Question
Title: Filtered View gives duplicates
I'm creating a View that creates a page based on filters.

Filters are:

* Published AND
* Content: Type (= Student Resources) AND
* Content: Resources Tag (Both or Prospective)

In the end, this should retrieve `"Student Resources"` that are `Published` and that have been tagged as either `"Prospective"` or `"Both"`. It does this without problem. However, what it also does is show the output multiple times:

Only one of each of these content exist, but each is showing up 6 times.

Please help me troubleshoot. What other information can I give you?

# Answer
I was able to fix this by installing the Views Distinct Module.

Once installed, I added `Content: Resources Tag (Both or Prospective)` to my fields in the view of interest. Then clicked on that field and under `Views Distinct Settings`, chose `Filter Repeats`.

I got this from this video: How To Remove Views Duplicates (Drupal Tutorial)
> 1 votes

# Answer
You can refer this article Remove Duplicate Views Results. Yo can use second option from that article.

Generally, it is done by the `Enabling Aggregation: Yes` under Views UI. This all has been mentioned at that link. Hope it will help.
> 1 votes

# Answer
In my case, the solutions in this article don't work : Remove Duplicate Views Results.

The duplicate was due to an image field. I found this solution : set `Exclude from display` for the fields and set `REWRITE RESULTS / Override the output of this field` with custom text and use the token for the field `{{ field_my_image }}`

I don’t know exactly why it has solved the issue but there is no more duplicate.
> 0 votes

---
Tags: views
---


# Question
Title: How do I synchronize users and their roles between sites?
I've set up a multi-site Drupal installation. The main site is example.com and we also have a.example.com and b.example.com.

I own example.com, and I rent a.example.com out to Person A, and b.example.com out to Person B. They pay their site rent using the UberCart role-purchase feature on my site. I need a way to set up my site so that Person A and B can log into example.com and pay their site rent, and have the upgraded role transfer over to a.example.com and b.example.com as well, automatically so that after a month if Ubercart downgrades their role I don't have to go in and manually unassign them.

Things I've tried:

1. **Shared users table**. This doesn't work because I don't want Person A to be able to see people who have signed up for b.example.com and a shared user site means everyone can see everything.
2. **Domain Access**. This works ok but is really shaky, and I'm planning on moving up to z.example.com and onward in the future, so unless there's a way to keep things more separate than I was able to, I don't think this is feasible. For example, if each site has an 'about us' page then I would see 26 "About Us" pages from my uid=1 account. Additionally, I didn't see any way of separating the UberCart module as much as I would like. Ubercart Marketplace is a no-go because I'm not taking any commission like it was designed to do, and UC\_Domain hasn't been upgraded to drupal 7 yet.
3. **Account Sync**. This seemed like the closest, but the plugin appears broken, I get tons of XML-RPC errors when I try it, and generally it doesn't work as described, and seems to only sync the first account before breaking. Google searching the errors brings back nothing apart from warnings that XMLRPC is potentially dangerous.
4. **Bakery**. This seems great but it doesn't share roles across subsites unfortunately. I've been trying to add that in, but before I spent the time I wanted to see if there's some other way that I can go about this

If anybody needs clarification on anything let me know, I really want to get this solved and can't find anything online.

# Answer
Hope the question is for Drupal 7 or lesser. If it's for Drupal 8, the solution is close to impossible. And for future Drupal versions, as per the current plan for Drupal 9, multi-site option itself shall not be available, which mean sharing user role using Drupal's default options, is clearly impossible.

In Drupal 7 or lower, in the multi-site setup, it's very easily possible to configure each site to use different databases for their contents, and share the same table (from same database) just for users, roles, sessions, etc. If you don't want to share users, but want to share only roles, even that is possible. For this, the settings.php for site A and site B has to be as below:

settings.php for Site A:

```
/*
 * Database Settings for 'Site A'
 */
$databases['default']['default'] = array (
    'database' => 'site_a_db_name',    // Specify Site A's main database name
    'username' => 'site_a_db_username',
    'password' => 'site_a_db_password',
    'prefix' => array(
        'default' => 'site_a_prefix_',    // Prefix for all tables in Site A's main database (specified above), other than for the tables specified below
        'role' => 'shared_db_name.shared_prefix_',              // Shared database name and prefix for the 'role' table
        'users' => 'shared_db_name.shared_prefix_',             // Shared database name and prefix for the 'users' table
        'authmap' => 'shared_db_name.shared_prefix_',           // Shared database name and prefix for the 'authmap' table
        'sessions' => 'shared_db_name.shared_prefix_',          // Shared database name and prefix for the 'sessions' table
        'profile_fields' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_fields' table
        'profile_values' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_values' table
    ),
    'host' => 'localhost',
    'port' => '3306',
    'driver' => 'mysql',
    'collation' => 'utf8mb4_general_ci',
);

```

settings.php for Site B:

```
/*
 * Database Settings for 'Site B'
 */
$databases['default']['default'] = array (
    'database' => 'site_b_db_name',    // Specify Site B's main database name
    'username' => 'site_b_db_username',
    'password' => 'site_b_db_password',
    'prefix' => array(
        'default' => 'site_b_prefix_',    // Prefix for all tables in Site B's main database (specified above), other than for the tables specified below
        'role' => 'shared_db_name.shared_prefix_',              // Shared database name and prefix for the 'role' table
        'users' => 'shared_db_name.shared_prefix_',             // Shared database name and prefix for the 'users' table
        'authmap' => 'shared_db_name.shared_prefix_',           // Shared database name and prefix for the 'authmap' table
        'sessions' => 'shared_db_name.shared_prefix_',          // Shared database name and prefix for the 'sessions' table
        'profile_fields' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_fields' table
        'profile_values' => 'shared_db_name.shared_prefix_',    // Shared database name and prefix for the 'profile_values' table
    ),
    'host' => 'localhost',
    'port' => '3306',
    'driver' => 'mysql',
    'collation' => 'utf8mb4_general_ci',
);

```

As shown in the above code, under 'prefix' array, we can specify separate database and prefix for each different table used in the site. Other than those tables exclusively specified in the 'prefix' array, for all other tables, the prefix specified as 'default' shall be used.

In Drupal 8, user/role/session sharing is not as easy as in Drupal 7, because in Drupal 8, many of the informations, including the user roles, are part of a shared table (that shared table is meant for storing many different variable values, and roles are just part of that).
> 2 votes

# Answer
You could use a secondary database (or a specific table) for all your sites where you manage each site's user roles. You would then need to:

* Define a cron job for each site (a-z).example.com which looks up the database and updates the roles of the users on the site
* Update the database when people buy on example.com
* Trigger cron from example.com after the UberCart transaction is completed

The other way to do that would be to expose a POST (REST) web service endpoint on the sub-sites which will trigger a function to update the roles based on the data submitted. You then call that endpoint after the UberCart transaction.

In both cases, I'm assuming there's a hook you can use to do things after a UberCart transaction (or maybe something like Rules).
> 0 votes

# Answer
Easiest way if you do not want to develop so much is change a bit about sharing tables:

https://www.drupal.org/node/22267

But if you only want to share roles just sare the roles table.

This is the exaple you can use:

```
$db_prefix = array(
    "default" => "slave1_", // the prefix for tables that are not shared.
    "role" => "master_",
);

```
> 0 votes

# Answer
Create an additional database. Can be an own drupal instance or a php framework like yii, where you can model the database by your own. There you manage the account data. From there you sync the roles via a cronjob (e.g. a REST call). After you have loaded the account credential data, you use this two Drupal API functions to update the account credentials:

This approach will do the job, if you are not just looking for a finished module, which does the job for you. Then you get you better a coder, who helps you out.
> 0 votes

---
Tags: users
---


# Question
Title: Retain content while deleting user using services
I need to delete a user account using services module & does it fine.

I can see that content(forum) created/updated by the user gets deleted.

Is it possible to achieve below screenshot option via services module in drupal 7?

# Answer
> 1 votes
Answering my own question,

I have updated the default account setting of `when cancelling a user account` in the path `/admin/config/people/accounts` to `Delete the account and make its content belong to the Anonymous user`

Resolves my query.

---
Tags: 7, users, services
---


# Question
Title: Can I get Entity Cache Tags from a Route?
If I have a node object I can use `$node->getCacheTags()` to get the cache tags for the node object, and I can do the same for other entities. Is there a way for me to do something similar with a Route object?

```
$cache_tags = $route->getCacheTags();

```

or maybe there's a way for me to do something like this, where $entity is populated with the $user, or $node, or $view, etc. object that is responsible for the current route:

```
$entity = $route->getEntity();
$cache_tags = $entity->getCacheTags();

```

# Answer
> 0 votes
Adding my eventual solution based on @No Sssweat's comment.

I created a method in a service like:

```
public function getEntityFromRoute(RouteMatchInterface $route_match) {
  foreach ($route_match->getParameters() as $param) {
    if ($param instanceof EntityInterface) {
      return $param;
    }
  }

  return FALSE;
}

```

Then I have code like the following where I'm not entirely sure what entity type may be providing the route:

```
$route_entity = $MY_SERVICE->getEntityFromRoute(\Drupal::routeMatch());
$cache_tags = [];
if ($route_entity !== FALSE) {
  $cache_tags = $route_entity->getCacheTags();
}

```

Then I create my render array using the cache tags.

---
Tags: 8, entities, routes, caching
---


# Question
Title: Show block only on node view page, not in node create or edit form
How can I configure block visibility to show only in node view pages? (not in node edit and create pages)

What should I insert in "Show block on specific pages" \> "Only the listed pages"? current config is:

```
video
node/*

```

# Answer
Use this in your block configurations page "Show block on specific pages" \> "Show if the following PHP code returns TRUE"

```
if(arg(0) == 'node' && is_numeric(arg(1)) && ((arg(2) == "" || arg(2) == 'view'))) {
  return TRUE;
}

```

Hope this will help.

You will need to enable the core module PHP.
> 4 votes

# Answer
I use the Context Module for this. It allows a more fine grained control than the out-of-the-box drupal-options.
> 4 votes

# Answer
Select the block you wish to exclude and add '*/edit' and '*/add/\*' to the 'Pages' tab in the 'Visibility settings'. You can use 'Content types' in combination with these settings to fine tune a bit further.
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: Migrate: Duplicate entries in url_alias after update migrations
I have term and node migrations from wprdpress to drupal 8 (*with pathauto module enabled*). I set the url alias in the migration templates like:

```
process:
  path/alias: source_path
  path/pathauto:
    plugin: default_value
    default_value: 0

```

Setting the path that way works fine on importing content with `drush mi term`. But when I update the terms with `drush mi term --update` a new (the same) path gets inserted into the url\_alias table. For example the term with tid 1 gets imported once and updated 2 times there will be the following aliases in url\_alias table:

```
select * from url_alias where source = '/taxonomy/term/1';
+------+------------------+---------------+----------+
| pid  | source           | alias         | langcode |
+------+------------------+---------------+----------+
| 1514 | /taxonomy/term/1 | /term-1-alias | de       |
| 2731 | /taxonomy/term/1 | /term-1-alias | de       |
| 3632 | /taxonomy/term/1 | /term-1-alias | de       |
+------+------------------+---------------+----------+

```

BTW: I have pathauto module enabled, but uninstalling it results in the same behavior.

# Answer
> 3 votes
Looks like a bug in the core path module: https://www.drupal.org/node/2350135

# Answer
> 3 votes
I made the following workaround to avoid the problem:

create a custom process plugin that checks if an url\_alias record was already inserted for the $value / node combination. If so, it returns NULL and if not it returns $value:

```
<?php
/**
 * @file
 * Contains \Drupal\your_migrate_module\Plugin\migrate\process\EmptyIfUrlAliasExists.
 *
 */

namespace Drupal\your_migrate_module\Plugin\migrate\process;

use Drupal\Core\Database\Database;
use Drupal\migrate\Annotation\MigrateProcessPlugin;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * This process plugin can be used for path/alias fields as long as the following issues are not resolved. It is a workaround for:
 *
 * https://www.drupal.org/node/2350135#comment-9476629
 * https://drupal.stackexchange.com/questions/238393/migrate-duplicate-entries-in-url-alias-after-update-migrations)
 *
 * @MigrateProcessPlugin(
 *   id = "empty_if_url_alias_exists",
 * )
 */
class EmptyIfUrlAliasExists extends ProcessPluginBase
{
    /**
     * {@inheritdoc}
     */
    public function transform(
        $value,
        MigrateExecutableInterface $migrate_executable,
        Row $row,
        $destination_property
    ) {
        // Retrieves a \Drupal\Core\Database\Connection which is a PDO instance
        $db = Database::getConnection();

        $sth = $db->select('url_alias', 'u')
            ->fields('u', ['pid']);
        $and = $sth->andConditionGroup()
            ->condition('u.source', '/node/' . $row->getIdMap()['destid1'])
            ->condition('u.alias', $value);
        $sth->condition($and);
        $data = $sth->execute();

        $results = $data->fetch(\PDO::FETCH_NUM);

        //when no url_alias record found, return the url, so it can be added.
        if ($results === false || count($results) === 0) {
            return $value;
        }
        //when an url_alias record is already present, return null, so the migration does not add it again
        return null;
    }
}

```

Then in the process part of my node migration yml, I use the following:

```
process:
  'path/pathauto':
     plugin: default_value
     default_value: 0 # Disable pathauto.
  'path/alias':
    -
      plugin: empty_if_url_alias_exists
      source: public_url
    -
      plugin: skip_on_empty
      method: process

```

---
Tags: 8, migrations, path-aliases
---


# Question
Title: Using Test Mail Collector to avoid sending emails to users during testing
This page offers some documentation on how to avoid sending emails to actual users during testing or in test environments:

https://www.drupal.org/docs/develop/local-server-setup/managing-mail-handling-for-development-or-testing

The simplest way appears to be modifying your settings.local.php:

```
$config['system.mail']['interface']['default'] = 'test_mail_collector';

```

If you use drush, you can then check the emails sent by running: drush sget system.test\_mail\_collector

However after adding that line to my settings.local.php, I still received the actual emails. They were not "collected".

In looking at the source code in Drupal\Core\Mail\Plugin\Mail\TestMailCollector.php line 24

```
 $captured_emails = \Drupal::state()->get('system.test_mail_collector') ?: [];

```

It seems to me that the correct syntax for setting the test mail collector would be

```
$config['system.test_mail_collector'] = TRUE;

```

But that didn't work either.

I haven't been able to find documentation that helps me reverse-engineer the setting based on the retrievable of the state variable.

# Answer
> 5 votes
After my attempt to use Devel module for DevelMailLog also failed using the configuration setting

```
$config['system.mail']['interface']['default'] = 'devel_mail_log';

```

I concluded there must be something in my environment that is blocking these features.

After uninstalling the module "MailSystem", then either of the two approaches worked as intended while mail was still received when the configuration setting was omitted.

---
Tags: emails
---


title: Theming Profil2 module

text:
# Question
Title: Theming Profil2 module
i'm on **drupal 7**, using a premium theme "**fundedvisual**" and i'm trying to do some templates on a sub theme called "**fundedvisual\_subtheme**".

I'm a noob in this, so maybe i did something wrong...

I have Profil2 module with 2 different profil types here the system names : "**investor**" and "**project\_creator**".

i followed the answer of **jeff\_shamley** in this post : Profile2 Template for edit page

i created a **template.php** file in "**/sites/all/themes/fundedvisual\_subtheme/**" with this in it :

```
function fundedvisual_subtheme_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'user_profile_form') {
if ($form['#user_category'] === 'investor') {
  $form['#theme'] = 'profile2_investor_edit_form';
} else if ($form['#user_category'] === 'project_creator') {
  $form['#theme'] = 'profile2_project_creator_edit_form';
} else if ($form['#user_category'] === 'main') {
  $form['#theme'] = 'profile2_main_edit_form';
}
  }
}

function fundedvisual_subtheme_theme() {
  return array(
'profile2_investor_edit_form' => array(
  'arguments' => array(
    'form' => NULL,
  ),
  'template' => 'profile2-investor-edit',
  'render element' => 'form',
),
'profile2_project_creator_edit_form' => array(
  'arguments' => array(
    'form' => NULL,
  ),
  'template' => 'profile2-project_creator-edit',
  'render element' => 'form'
),
'profile2_main_edit_form' => array(
  'arguments' => array(
    'form' => NULL,
  ),
  'template' => 'profile2-main-edit',
  'render element' => 'form',
),
  );
}

```

Then i made 3 files in "**/sites/all/themes/fundedvisual\_subtheme/templates**" :

```
profile2-investor-edit.tpl.php
profile2-project_creator-edit.tpl.php
profile2-main-edit.tpl.php

```

with this in it :

```
<?php echo "pouet" ?>

```

Then i cleared the cache a million time :'D

Annnnnnnd nothing show up except the default system profile :/

Did i forget something ? Thx in advance !

**Edit : i wonder if i can just embed these forms pages in views it would be nice, instead of creating templates with that i could just modify my style.css**

**Edit2 : one of my comments : to be more precise i have a general page called "my account" and in it i have the header menu on the top, below an image with a title, below another menu bar and below the content of each "button" from that menu bar. Each time i click on a button from my menu i want to keep that template, so if i click on "profile" in my menu bar, it should be exactly the same except the title and the content. Is that possible ?**

# Answer
If the whole point of this is to be able to add wrappers around fields, an alternate option would be to use the field group module. Here is a video tutorial on it.
> 0 votes

---
Tags: theming
---


title: Display HTML field

text:
# Question
Title: Display HTML field
I am using Views Database Connector to display safe data from external database in Drupal 8 within views. Some of the fields include simple html like a list which views encodes in html entities. I am using `{{ fields.myfield.content }}` in views-view-fields--myview.html.twig. I have searched for other solutions about using the raw value on the site but none of them seems to work.

Is there a simple solution without getting involved in preprocess functions?

# Answer
I am not sure if a module exists for this yet, but to do this, you would need to create a field handler for Views that does not escape HTML.

Here is an example I made a year ago to achieve the same thing you are trying to do.

For the field handler, I implemented this hook to change what handled the data:

```
/**
 * Implements hook_views_data_alter().
 *
 * We need to look through and change the field handler for our stored item to
 * our custom handler so HTML is unescaped.
 *
 * @param array $data
 */
function search_api_view_modes_views_data_alter(array &$data) {
  $indices = \Drupal::entityTypeManager()->getStorage('search_api_index')->loadMultiple();
  $views_data_keys = array_keys($data);

  if ($indices) {
    foreach (array_keys($indices) as $index) {
      $views_index_name = 'search_api_index_' . $index;

      if (!in_array($views_index_name, $views_data_keys)) {
        continue;
      }

      foreach (array_keys($data[$views_index_name]) as $item) {
        if (preg_match('/^view_mode_(.*)/', $item)) {
          $data[$views_index_name][$item]['field']['id'] = 'search_api_view_mode';
          $data[$views_index_name][$item]['field']['fallback_handler'] = 'search_api_view_modes';
        }
      }
    }
  }
}

```

Anytime one of my fields was seen in a View, the field handler was set to `search_api_view_mode`, defined below:

```
/**
 * Provides a default handler for rendered entity view modes in Search API Views.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("search_api_view_mode")
 */
class SearchApiViewMode extends FieldPluginBase implements MultiItemsFieldHandlerInterface {

  use SearchApiFieldTrait;

  /**
   * Overrides render_item to return our markup unescaped.
   * @param $count
   * @param $item
   * @return string
   */
  public function render_item($count, $item) {
    return check_markup($item['value'], 'full_html');
  }

}

```

`check_markup` is probably not advised anymore, over a Markup object, but nonetheless this is what I had to do to not have the HTML escaped. I am not sure you can reverse this at the twig level.
> 0 votes

# Answer
Probably not a best practice, but I was able to get a field from an external database that contained HTML to print using the markup, instead of printing out the tags by doing the following in twig (in Drupal 8.5.3). I used the raw field contents and wrapped that in autoescape false.

In my case I put it in a views-view-fields-MY\_VIEW\_NAME.html.twig template in my theme using the following:

```
{% autoescape false %}{{ field.raw }}{% endautoescape %}

```

I'm imagining that you could use something like Twig Tweak and Rewrite Results of MY\_FIELD directly in Views to do this, also:

```
{% autoescape false %}{{ MY_FIELD|raw }}{% endautoescape %}

```

I know it's a bit late, but hopefully it'll help other Googlers like me.
> 0 votes

---
Tags: views, theming
---


title: How to correctly get the twig value

text:
# Question
Title: How to correctly get the twig value
I have the following response using `kint`. How can I correctly get the value of the title.

I tried `stream.node_title[0]['#context'].output` but getting `null` result.

# Answer
> 1 votes
Looks like it should be

```
{{ stream.node_title[0][0]['#context'].output }}

```

You can get the other two with

```
{{ stream.node_title[0][1]['#context'].output }}
{{ stream.node_title[0][2]['#context'].output }}

```

But obviously this would be hard coded. To make all of this dynamic, you can loop.

```
{% for title in stream.node_title[0] %}
    {{ title['#context'].output }}
{% endfor %}

```

---
Tags: 8, theming
---


title: hook_ENTITY_TYPE_insert never called

text:
# Question
Title: hook_ENTITY_TYPE_insert never called
Initially I wanted a list of Authors in an exposed filter (as a checkbox) but after looking into BEF (better exposed filters) it seems this isn't possible.

Instead I am trying to create a taxonomy term for each user created but have found regardless of what entity I am trying to create, the hook for insertion is never called.

I am using xdebug and was expecting at least a single breakpoint inside one of the functions to work but it never triggers, I have cleared my cache and other preprocessing functions inside this file (bare.theme).

A few examples of functions I have tried (my theme is called "bare"):

```
function bare_entity_insert(Drupal\Core\Entity\EntityInterface $entity){}

function bare_user_insert(\Drupal\user\UserInterface $user) {}

function bare_entity_create(Drupal\Core\Entity\EntityInterface $entity){}

function bare_user_create(\Drupal\user\Plugin\Core\Entity\User $user){

```

I feel I have missed something very crucial, perhaps I can't call these functions inside a **.theme** file?

# Answer
> 3 votes
Yes if you're trying that in a theme then it won't work and will need to be done in a module (Obviously changing the "bare" to whatever your module name is)

---
Tags: 8, users, entities, hooks
---


title: Load a file entity by URI

text:
# Question
Title: Load a file entity by URI
Is there a way to load a file by URI in Drupal 8?

In Drupal 7, it is possible using the following code.

```
$uri = 'public://file.xyz';

// Take a look at: file.inc::file_load_multiple
$files = file_load_multiple(array(), array('uri' => $uri));
$file = reset($files); // If empty, $file will be false, otherwise will contain the required file

```

Taken from here https://www.drupal.org/forum/support/module-development-and-code-questions/2012-06-06/load-a-file-by-uri#comment-6493610

# Answer
> 35 votes
There is the `loadByProperties` method in the `\Drupal\Core\Entity\EntityStorageInterface` that allows to define required condition in searching the file entity by the given file URI:

```
/** @var \Drupal\file\FileInterface[] $files */
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadByProperties(['uri' => $uri]);
/** @var \Drupal\file\FileInterface|null $file */
$file = reset($files) ?: NULL;

```

---
Tags: 8, files, uri
---


# Question
Title: Changing colors per page through drupal interface
Using Content type: News, I have created pages NewsItem1, NewsItem2

I would like to have a background and color blue to NewsItem1 page and set the pink background to NewsItem2 page through Drupal admin. Is that possible?

I am using Drupal 8.5 version. I think themekey module allowed to do this but it is not available for D8. I couldn't find any other easy way to do this. Any suggestions? Thanks in advance.

# Answer
You will probably have to add a "Background Color" field to the content type with some selections that map to CSS class names.

Then, depending on where you want to add the background (e.g. on the body or on just the main content area), to add a preprocessor function in your theme to add the selected class as a variable that can be used by the twig template.

E.g. for just the main content area, you would use something like:

`function bartik_preprocess_page(&$variables) {
 $node = \Drupal::routeMatch()->getParameter('node');
 if ($node) {
 if (!$node->color->isEmpty()) {
 $variables['bg-class'] = $node->color->getValue();
 }
 }
}`

Copy the page.html.twig file to your theme's templates directory and add the bg-class to the section you want that color. E.g. `class="{{ bg-color }}"`.
> 2 votes

---
Tags: 8, theming
---


# Question
Title: With a standard HTML form in Drupal 8, how can I get the submit message to post in the "Status Message" block?
I have a form that I want to add JS to so that when it is submitted, the confirmation text is fired into the "status messages" block or any block in the help/admin block section.

Basically, here is the form and upon submit, I want the post message to display in a block rather than the user be sent to another page.

```
<form name="email_signup" action="http://example.com">
<input type="text" name="emailAddress" placeholder="Enter email">
<input type="submit" value="Join">
</form>

```

# Answer
> 2 votes
You should create this form through the Form API in a module, then in the form submit handler you can use `Messenger` to do this.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Messenger%21MessengerInterface.php/function/MessengerInterface%3A%3AaddMessage/8.6.x

You can see that `drupal_set_message` now routes through it:

```
function drupal_set_message($message = NULL, $type = 'status', $repeat = FALSE) {
  @trigger_error('drupal_set_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \\Drupal\\Core\\Messenger\\MessengerInterface::addMessage() instead. See https://www.drupal.org/node/2774931', E_USER_DEPRECATED);
  $messenger = \Drupal::messenger();
  if (isset($message)) {
    $messenger
      ->addMessage($message, $type, $repeat);
  }
  return $messenger
    ->all();
}

```

This is how flash/status updates are created.

---
Tags: 8, forms, javascript
---


# Question
Title: How to add anchor link through Link field?
We have a link field (field\_link) on the Basic page content type. We wanted to add the link as an anchor link by putting `current-page#section1` into the Link field, but it is not current.

What can we do to populate a link field such that it take the current URL and add `#section1`?

This is how the link field is used in the twig template

```
{% set cta = content.field_link.0 %}
<a href="{{ cta['#url'] }}'>
  <i class="fa fa-car" aria-hidden="true"></i>
  <div> {{ content.field_name }} </div>
  <div> {{ cta['#title'] }}</div>
</a>

```

Current output

```
<a href="/current/page/path'>
  <i class="fa fa-car" aria-hidden="true"></i>
  <div> Professionally facilitate standardized vortals whereas high-payoff e-business. Distinctively productize high. </div>
  <div> Download </div>
</a>

```

Expected output

```
<a href="/current/page#section1'>
  <i class="fa fa-car" aria-hidden="true"></i>
  <div> Completely brand cross-platform "outside the box" thinking through visionary supply. </div>
  <div> Download</div>
</a>

```

# Answer
> 0 votes
The only way i got this to work is by using an answer found How to get the valid URL of a Link field from within a Twig template?, thanks to @prkos

```
{{ content.field_my_link[0]['#url']|render }}

```

# Answer
> 0 votes
Drupal will automatically do that if you only enter `#section1` into the Link URL.

---
Tags: 8, nodes, entities
---


# Question
Title: How can I do with Views and Drupal 7 what the Views Or module does in Drupal 6?
I'm trying to find a way to do in Drupal 7 what the Views Or module does in Drupal 6. I read that this module (or at least what it does) has been migrated to the core Views 3 module.

How can I do the same thing as on this picture (marked in yellow) within Drupal 7 Views 3?

# Answer
> 4 votes
In your views filter area it is possible, Click re arrange if existing filter there, other wise configure it on adding new.

In the following window you can configure the or or and, between fields and filter group

# Answer
> 0 votes
Yes, as shown above the ViewsOR module's functionality has been PARTIALLY migrated into Views for D7/D8; but sadly, ViewsOR also worked on Contextual Filters and Views in D7/D8 still does not have that ability.

---
Tags: views
---


# Question
Title: Last Comment Name field is not removed after account cancellation
After cancelling the user under(`Delete the account and make its content belong to the Anonymous user`). Forum posted by is changed to "Anonymous" but comment name is still displayed in the forum.

Also i noticed it in the table, `node_comment_statistics`

How can i remove the Last Comment Name while cancelling, because i need to remove entire user information from my database.

**Update 1:**

Last\_Comment\_Name is mapped from the table `Comment` column `name`

# Answer
The forum module doesn't respond to any user deletion activity so you'll have to build your own solution here. You can create a custom module with a `hook_user_cancel` implementation that will:

1. Check that the canceled user account is being anonymized.
2. Look up the username's entries in the `node_comment_statistics` (and other relevant tables).
3. Execute a `UPDATE` DB query that replace the name with "anonymous" (or whatever anonymized name you like).
> 2 votes

---
Tags: 7, comments, nodes
---


# Question
Title: Vocabulary Term Translation Edit/Delete Page Get Access Denied/ Doesn't Function Correctly
I currently have a taxonomy term with multiple translations. When I visit the translate tab for the term it does list all of the languages properly.

However no matter what translation I'm attempting to edit, it takes me to the edit page for English. I found that it seems to automatically send you to the edit page of the translation that matches the user's set Site language.

If I change the site language of the admin user to Spanish no matter what edit link I click it only takes me to the Spanish translation. The admin user has access to all allowed languages so I'm not sure why it would restrict all access to the specified site default language.

Side note if I attempt to delete a specific translation it deletes all translations. If I manually enter this path

```
/taxonomy/term/{taxonomy_term_id}/translations/edit/{language}

```

I get an access denied page. I shouldn't ever get an access denied page because I'm an admin with all permissions enabled. I do believe this path should exist because looking at the routes associated with the taxonomy term entity does contain that path. Here is some of the content of the entity info produced by devel.

```
[links:protected] => Array
    (
        [canonical] => /taxonomy/term/{taxonomy_term}
        [delete-form] => /taxonomy/term/{taxonomy_term}/delete
        [edit-form] => /taxonomy/term/{taxonomy_term}/edit
        [create] => /taxonomy/term
        [devel-load] => /devel/taxonomy_term/{taxonomy_term}
        [devel-render] => /devel/taxonomy_term/{taxonomy_term}/render
        [devel-definition] => /devel/taxonomy_term/{taxonomy_term}/definition
        [token-devel] => /taxonomy/term/{taxonomy_term}/devel/token
        [drupal:content-translation-overview] => /taxonomy/term/{taxonomy_term}/translations
        [drupal:content-translation-add] => /taxonomy/term/{taxonomy_term}/translations/add/{source}/{target}
        [drupal:content-translation-edit] => /taxonomy/term/{taxonomy_term}/translations/edit/{language}
        [drupal:content-translation-delete] => /taxonomy/term/{taxonomy_term}/translations/delete/{language}
    )

```

Why can't I access the edit forms for the translations that don't match the users set site language? How can I fix this?

# Answer
> 0 votes
Just check "Content language" under "Content language detection".

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


title: Is a views page an entity?

text:
# Question
Title: Is a views page an entity?
Along with some regular nodes I want to link to a views page with an entity reference field.

Can I reference a views page via an entity reference field?

# Answer
> 2 votes
> Can I reference a views page via an entity reference field?

Not out of the box, but you can use the Views reference field module to get that functionality:

> In Drupal 8, Views are now identified as entities and the core Entity Reference Module is able to reference Views, however not Views displays. This module leverages core entity reference module functionality to add the display ID so that a View can be rendered in a field formatter.

# Answer
> 1 votes
No, the page itself is not an entity, each view is an object of class ViewExecutable which has different display names like page, block, page\_1 and ... so the page itself is not an entity object (each entity has its own table and a unique identifier at least), hence you can use views\_embed\_view to get the result of a specific display of a view.

---
Tags: 8, entities
---


# Question
Title: Get results from content indexed from other site with search api
We are using the Search API module to implement the search pages on the site.

**Current setup**:

1. A custom backend to store the index. It is powered by Lucene. We were able to get a new search API backend plugin to do CRUD on the indexes.
2. This backend also implements the search functionality. It is implemented alright and I am able to retrieve the results in the view of the index.

**Requirement:** The custom backend is used by other sites as well (not necessarily on Drupal) to store their index. I want to display results of these sites as well whenever a user does a search on our site.
However, there seems to a limitation in a way Search API module works.

In the custom backend we created, there are following lines which are responsible for letting the module know about the results

```
$item = $this->getFieldsHelper()->createItem($index, $row->item_id);
$results->addResultItem($item);

```

We took the Database backend as a reference to build this custom functionality from the `search_api_db` module which is a part of the `search_api` module.

**Question**: How do I display results from other sites along with the current Drupal site?

# Answer
> 0 votes
My guess is that you will not be able to do this with the standard search view process. I believe that views does some linking of results to content that exists on the site. So remote content will be filtered out.

That said, you can get what you want if you use the native Solr query requests. These return the raw json (or xml) data from the server. You can use this with custom code to display your results.

See the solr tutorial on how to create queries.

A site I used to manage used this with Angular.js to manage some really complex searches.

---
Tags: 8, search
---


# Question
Title: Need filter on value of a field in a specific node of different content type in Views
I have content type **pick\_topic**, containing an entity ref taxonomy field **topic**. There is one node of this type. It defines the topic of the month. Several views blocks and pages need to only display content nodes with this topic value. Example: taxonomy topics: *dogs, cats, rabbits*.

The user (site manager) edits this node and selects a topic from dropdown. Say it is *dogs*. My view of another content type, **articles**, contains **topic** field. How can I filter the view based on the **pick\_topic** topic value equal to the **article** **topic** field value, in this case *dogs*?

# Answer
> 0 votes
This is a very common request, to display lists of related content that share the same Taxonomy term as the node where the Views Block is displayed.

You can do that by adding a Contextual Filter `Content: Has taxonomy term ID` to your **articles** Views with these settings (only choose **topic** Vocabulary in your case):

Since your Views list a different content type, it's not necessary to also add another contextual filter to remove the current node from the Views block.

If your articles Views don't have a Block display, create one now, by duplicating the one you've been editing above, duplicate as Block. Edit the Block name to something meaningful so you can easily find it on the Block list.

Now you add that Block to a region the usual way. Besides selecting a region you'll also have to choose the Content: ID **Node from URL** on Block settings (this comes from our Contextual filter), and on the Visibility settings (in Vertical tabs) under **Content types** choose **Pick topic** content type (I have Article ticked in image below, but you have to choose the Content type where you want the block to display, which is Pick topic in your case).

This means that the Views Block will list article titles, but the Block will be visible on pick\_topic node pages.

Without the Contextual filter the Views Block will list all articles.

With the Contextual filter (set as above) will restrict that list to only those articles that have the same term as the node where the Block is being displayed.

# Answer
> 0 votes
I don't know of a way to do this all in the interface, but if you add a contextual filter in the view for the topic field on the article content type, you can programmatically set the contextual argument in hook\_views\_pre\_view.

First, load your pick\_topic node like:

```
\Drupal::service('entity_type.manager')->getStorage('node')->load(PICK_TOPIC_NID);

```

Then load the field value. See How do I access a field value for an entity (e.g. node) object?

Then set the view argument.

```
function MY_MODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'MY_VIEW_ID' && $view->current_display == 'MY_VIEW_DISPLAY_ID') {
    // Load your pick topic node.
    // Load your pick topic field value.
    // Set the view argument, term id.
    args[] = $my_pick_topic_field_value_tid;
  }
}

```

---
Tags: 8, views
---


# Question
Title: How hide from menu content type Basic Page and Landing page
In Drupal 8, I tried to remove default **Basic page** and **Landing page** content types, but it have content related to them. So, my quick fix will to only hide those one from some user. I tried with permissions but it didn't work .

/admin/people/permissions   Updated: Same issue

But users with role **Content Publisher** and/or **Content Administrator** still see those CTs in /node/add

There is any other way to hide those ones?

Thanks

Edit: This option was the issue **Create any content on assigned domains**

# Answer
> 0 votes
**SOLUTION**: I just removed for Content publisher or any other role

*Create any content on assigned domains*

I think this permission was added with the module **Domain Access**

---
Tags: 8, nodes, navigation, configuration
---


# Question
Title: How to set the text format of a field in a node object?
When I create a node like this:

```
$nodeSetup = [
  'nid' => NULL,
  'type' => $bundle,
  'uid' => $uid,
  'revision' => 0,
  'status' => 1,
  'body' => ['format' => 'full_html', 'value' => Xss::filter($body)],
];
$_node = Node::create($nodeSetup);

```

the body value and format work fine. But, when I load an existing node, how can I set the body value keeping the format? This didnt work:

```
$_node->body->format = 'full_html';
$_node->body->set('format', 'full_html');
$_node->save();

```

# Answer
The following worked for me,

```
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$node->body->value = 'body';
$node->body->format = 'full_html';//omitting this will retain existing format
$node->save();

```
> 12 votes

# Answer
Kstack's solution works. Another option is to supply the value and format together in an array like so:

```
$node = \Drupal::entityTypeManager()->getStorage('node')->load(1);
$node->body->setValue(['value' => 'body', 'format' => 'full_html']);
$node->save();

```
> 5 votes

---
Tags: 8, nodes, entities
---


# Question
Title: How to add an attribute in an input date field
I want add the attribute *autocomplete="Off"* in the input field of the date field. I've created a modulo with *hook\_form\_alter* but not works. This is my code:

```
function no_input_autocomplete_form_alter(&$form, &$form_state, $form_id) {
    if($form_id === 'prenotazione_node_form'){
        $form['field_periodo_prenotazione_to']['#attributes'] = array('autocomplete' => 'Off');
    }
}

```

I've noticed that with other field type works as I expect.

How can solve it?

# Answer
> 1 votes
Try with

```
$form['field_periodo_prenotazione_to']['widget'][0]['value']['#attributes'] = array('autocomplete' => 'Off');

```

---
Tags: forms, hooks, datetime
---


# Question
Title: How to create a view that display on the same row a field and its translation
Let say I have a content type with 2 fields that can be translated in a 2 languages site (EN-FR): the title and field\_tobe\_translated

I would like to list (in a view) all nodes of this content type with only one row by node and each row should have this format:

Title\_FR -- Title\_EN -- translatable\_field\_FR -- translatable\_field\_EN

The "--" before means a column separator in a table type view.

Added question:

Is it possible to filter this view to show only the row where "Title\_FR != Title\_EN" \[I assusme that the process would be the same for the other translatable field\]

# Answer
I haven't found a way to show translations in the same row as the source, without additional modules that is. Although that would be nice to have.

These modules aren't currently covered by Drupal’s security advisory policy so they might not be a wise choice:

A compromise might be to show your information spread accross two rows instead of one:

1. Create Views showing Title and Field for the two languages
2. Sort by ID (this will list translations close to their sources so you'll end up with pairs of English and French nodes that are translations of the same content)
3. Add another Sort criteria by Language (this way you're sorting inside each pair, so you always get French first, English second, if that's how you prefer it)

So in the end you'd have:

`+----+------------+-------------------------+`
`| ID | Title | Field |`
`+----+------------+-------------------------+`
`| 1 | Title_FR_1 | translatable_field_FR_1 |`
`+----+------------+-------------------------+`
`| 1 | Title_EN_1 | translatable_field_EN_1 |`
`+----+------------+-------------------------+`
`| 2 | Title_FR_2 | translatable_field_FR_2 |`
`+----+------------+-------------------------+`
`| 2 | Title_EN_2 | translatable_field_EN_2 |`
`+----+------------+-------------------------+`
`| 3 | Title_FR_3 | translatable_field_FR_3 |`
`+----+------------+-------------------------+`
`| 3 | Title_EN_3 | translatable_field_EN_3 |`
`+----+------------+-------------------------+`
> 2 votes

# Answer
I knew there was a way, even if it's the old way (I expected it would be possible in D8 out of the box).

## Use Views Field View module

You can do it with the help of Views Field View. It's basically embedding a View into another View to be displayed as a field.

You have to have the Child View created before you can add it to the Parent Views. Parent and Child can be two Displays on the same Views, they don't have to be in two different Views.

In your case your Child View will be filtered to show only fields related to one node (using regular and Contextual Filters), so you can end up with a nicely styled result where one node information is displayed in one table row.

1. Create a Views Display of type **Embed** to serve as your Child Display.
2. Filter it to list your content and also add the Filter `Content: Translation language` and set it to French (Or English)
3. Add Title and the other field you want to see
4. Format `Unformatted list` and under `Fields` Settings set both fields as **Inline**, separator may be something like `|`
5. Add a Contextual Filter `Content: ID` and configure it to:
When the filter value is NOT available
**Provide default value**
**Content ID from URL**
(Optionally specify validation criteria)
6. Create a Page view (you probably have this already) of Table Format
7. Filter it to list your content and also add the Filter `Content: Translation language` and set it to English (Or French, the opposite from the one which you set in Step 2)
8. Add a Field **Content: ID** and **Exclude it from display**. This info will be fed to the Embedded view to filter only translations for that node
9. Add the Title and the other field you need to show
10. Add the field `Global: View` and under View settings select the View name from the first dropdown
11. Apply
12. Save the View
13. Edit the `Global: View` again, this time you'll be able to choose the exact Views Display you created in step 1
14. In the **Contextual filters** enter `{{ raw_fields.nid }}` or whatever makes sense in your case, check under **Replacement patterns**

You should now see the list of nodes with English and French fields on the same row.

The Inline fields might not emulate the Table cell look exactly. You can make this display as table cells exactly with some more elaborate HTML overwrites to make them blend together.
> 1 votes

---
Tags: views, 8, i18n-l10n
---


# Question
Title: Custom route using access check error with arguments
I have a custom route that needs to check if a user can create a certain group\_node:article content inside a group (from the group module 8.x-1.0-rc2). The setting is as follows:

mymod.routing.yml

```
mymod.add:
  path: '/mymod/add/{group}/{plugin_id}'
  defaults:
    _controller: '\Drupal\mymod\Controller\MymodController::addNews'
    _title: 'Add news'
  requirements:
    _group_content_create_access: 'TRUE'

```

The group.services.yml

```
  access_check.group_content.create:
  class: 'Drupal\group\Access\GroupContentCreateAccessCheck'
  arguments: ['@entity.manager']
  tags:
    - { name: 'access_check', applies_to: '_group_content_create_access' }

```

GroupContentCreateAccessCheck.php

```
 /**
* Checks access for group content creation routes.
*
* All routes using this access check should have a group and plugin_id
* parameter and have the _group_content_create_access requirement set
* to either 'TRUE' or 'FALSE'.
*
* @param \Symfony\Component\Routing\Route $route
*   The route to check against.
* @param \Drupal\Core\Session\AccountInterface $account
*   The currently logged in account.
* @param \Drupal\group\Entity\GroupInterface $group
*   The group in which the content should be created.
* @param string $plugin_id
*   The group content enabler ID to use for the group content entity.
*
* @return \Drupal\Core\Access\AccessResultInterface
*   The access result.
*/
public function access(Route $route, AccountInterface $account, GroupInterface $group, $plugin_id) {
  ...
}

```

From my understanding these 3 files should be enough to check `_group_content_create_access`. However, trying to access my route via

`localhost/mysite/mymod/add/57/some-plugin-id`

always results in `RuntimeException: Callable "Drupal\group\Access\GroupContentCreateAccessCheck::access" requires a value for the "$group" argument.`

What am I missing here?

**UPDATE** I tried to investigate this problem in more detail. The full error message is this one:

```
....requires a value for the "$group" argument. in
Drupal\Component\Utility\ArgumentsResolver->handleUnresolvedArgument()
(line 148 of core/lib/Drupal/Component/Utility/ArgumentsResolver.php).
Drupal\Component\Utility\ArgumentsResolver->getArgument(Object) (Line:
54)
Drupal\Component\Utility\ArgumentsResolver->getArguments(Array) (Line:
157)
Drupal\Core\Access\AccessManager-
>performCheck('group_news.custom_access_check', Object) (Line: 135)
Drupal\Core\Access\AccessManager->check(Object, Object, Object, 1)
(Line: 112)
Drupal\Core\Access\AccessManager->checkRequest(Object, Object, 1)
(Line: 107)

```

The point where it fails in `Drupal\Component\Utility\ArgumentsResolver->getArgument(..)` is where `is_object($this->objects[$parameter_name])` returns false, because my route parameter `{group}` that should be of type `GroupInterface` is actually of type `String`.

However, when testing another group module route that is not using a route-access check class, the `{group}` parameter gets noticed as `GroupInterface`. For example in

```
entity.group.leave:
  path: '/group/{group}/leave'

```

So the question points more in the general direction of how my route parameter '57' gets noticed as `GroupInterface` (or more general any specific type), because the same thing also fails when implementing my own little custom access check class (not using the group module at all).

# Answer
Digging deeper into what causes the error message brought me to the drupal docs about Parameter upcasting in routes. When passing entity parameters to an access check function you need to upcast your parameter and tell Drupal of which entity type your argument is. I.e. in my\_mod.routing.yml add options and argument type:

```
mymod.add:
  path: '/mymod/add/{group}/{plugin_id}'
  defaults:
    _controller: '\Drupal\mymod\Controller\MymodController::addNews'
    _title: 'Add news'
  requirements:
    _group_content_create_access: 'TRUE'
  options:
    parameters:
      group:
        type: entity:group

```
> 0 votes

---
Tags: 8, routes, group
---


title: Cannot delete entity

text:
# Question
Title: Cannot delete entity
I'm unable to delete a custom entity. I'm getting the following error

```
$storage_handler = \Drupal::entityTypeManager()->getStorage("notification_storage");
$notification_entities = $storage_handler->loadMultiple($notifications['notification']);
$storage_handler->delete($notification_entities);

```

> Symfony\Component\Routing\Exception\RouteNotFoundException : Route "entity.notification\_storage.canonical" does not exist. dans Drupal\Core\Routing\RouteProvider-\>getRouteByName() (ligne 202 de /var/www/html/docroot/core/lib/Drupal/Core/Routing/RouteProvider.php).

```
/**
 * Define NotificationStorage entity.
 *
 * @package Drupal\notification\Entity
 *
 * @ContentEntityType(
 *   id = "notification_storage",
 *   label = @Translation("Notification Storage"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\notification\Controller\NotificationStorageListBuilder",
 *     "views_data" = "Drupal\notification\NotificationViewsData"
 *   },
 *   base_table = "notification_storage",
 *   entity_keys = {
 *    "id" = "id",
 *    "uuid" = "uuid",
 *    "langcode" = "langcode"
 *   },
 *   fieldable = TRUE,
 *   links = {
 *     "canonical" = "/admin/notification_storage/list"
 *   },
 *   field_ui_base_route = "notification_storage.settings"
 * )
 */

```

# Answer
> 1 votes
You've defined a canonical link in the entity annotations, but this doesn't build a route automatically. If you don't want to do specify the route in a yaml file you need a route provider:

```
 *   handlers = {
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider",

```

If the custom entity should be part of the admin interface use AdminHtmlRouteProvider.

---
Tags: 8, entities
---


# Question
Title: Adding conditional css to view or display type
Hi i have created a view that displays recently viewed items. This displays the 'teaser' display mode of a custom content type. This content type has a field 'favorite'.

What i want is to add a css class to the outer div (on the teaser div or de col-... generated by the view). But only if it is a 'favorite'.

I have created the view in the Drupal backend I could probably do in a custom module. I just want to check if it is possible without any programming.

# Answer
> 1 votes
You could try this but may depend on your 'favourite' field output

If you click on "Format \> settings" when editing your view you'll see a "Row class" field. In there you can put the replacement pattern for your favourite field.

So if its populated it will add the field value as a class to the view-row div. And you can use this to know if the field has content

If that's not going to work because the field content isn't suitable as a class then you could preprocess the node view and add a class yourself in the attributes array

---
Tags: views, 8
---


# Question
Title: Adding links to a menu without re-selecting the menu each time
I am adding links to a (SuperFish) menu in Drupal 8. Each time I add a link it returns me to the list of menus (admin/structure/menu).

How can I add menu links without having to re-select the menu each time?

I think that newly created menus operate the way I want, but I want to add links to an existing menu.

So far my best method is to store the URL for adding a menu item in the clipboard.

> admin/structure/menu/manage/main-ejn-menu/add

# Answer
> 0 votes
So do you want it to go add to the add menu item screen after creating one? What is in the url does it have something like ?destination=/admin/structure/menu

You could change that to

```
admin/structure/menu/manage/main-ejn-menu/add?destination=admin/structure/menu/manage/main-ejn-menu/add

```

---
Tags: 8, navigation
---


# Question
Title: Views Slideshow Cycle doesn't re-initialize properly after an AJAX content update
I have a Views Slideshow on my site that works perfectly until I try to reload only part of the page (containing the slideshow among other stuff) via AJAX (using Ajax links API module). The content itself is reloaded properly but:

If the new content contains different blocks than the old content, I'm getting the following error:

```
Uncaught TypeError: Cannot set property 'targetId' of undefined

```

It's the following lines that cause the error:

```
var fullId = '#' + $(this).attr('id');
var settings = drupalSettings.viewsSlideshowCycle[fullId];
settings.targetId = '#' + $(fullId + " :first").attr('id');

```

An inspection of drupalSettings.viewsSlideshowCycle in Chrome DevTools shows that it doesn't contain the current block id ($(this).attr('id')) but contains the old block id, already gone, so drupalSettings.viewsSlideshowCycle\[fullId\] returns null. In other words, the AJAX-driven content update doesn't seem to update drupalSettings - is it supposed to? I checked the AJAX response and it contains correct settings but for some reason the script doesn't see them and uses the original settings that came with the initial page load.

If the new content has the same structure as the old one (same block name for the Views Slideshow) then I don't get the error and the slideshow sort of works but the slide counter shows funny numbers in funny sequence (like 6 of 2, then 2 of 2) and at funny times (not when the slides change but when they stand still too). It looks like there are two scripts running simultaneously interfering with each other.

I would expect the behaviors mechanism to somehow kill the old scripts and settings and replace them with new ones upon processing an AJAX response but it doesn't seem to happen and I can't find any documentation on this particular aspect.

Sorry for a possibly fuzzy description (must admit I don't know the inner workings of AJAX all too well) - will be happy to provide more info if needed!

# Answer
> 0 votes
This is what I wound up doing:

Issue #1 (Uncaught TypeError): Added the following code to the Ajax links API ajaxAfter function right after pasting the AJAXed content into DOM:

```
$.extend(true, drupalSettings, JSON.parse($(selector).find("script[data-drupal-selector='drupal-settings-json']").html()));

```

This code should have probably been there from the start but who knows - it can break something for someone else.

Issue #2 (counter acting funny): Added the following code to the Ajax links API ajaxBefore function right before wiping the old content:

```
$('#views_slideshow_cycle_teaser_section_photo_slideshow-block_1').cycle('destroy');

```

As opposed to #1 this is a horrible site-specific kludge but will work for me until I find a more elegant and more generic solution.

# Answer
> 0 votes
> I would expect the behaviors mechanism to somehow kill the old scripts and settings and replace them with new ones upon processing an AJAX response but it doesn't seem to happen and I can't find any documentation on this particular aspect.

The D7 Managing Javascript docs explains this well:

> Drupal.behaviors will often be called multiple times on a page. For example, every time a form performs some Ajax operation, all Drupal behaviors will be executed again after page load, in order to attach any relevant JavaScript to the newly loaded elements. This can have the undesired affect of applying JavaScript to elements each time Drupal behaviors are executed, resulting in the same code being applied multiple times. To ensure that the JavaScript is applied only once, we can use the jQuery `$.once()` function. This function will ensure that the code inside the function is not executed if it has already been executed for the given element.

The D8 Javascript Overview docs tells you how to use `$.once()` in D8.

---

If your code is not recognizing the ajaxed in divs, then you need to attach the behaviors to the ajax wrapper, with `drupal.attachBehaviors($('.ajax-wrapper'));`

Ex:

```
$.ajax({
    url: '/some/url',
    type: 'GET',
    success: function (data) {
        var result = $(data).find('.some-wrapper').html();
        $('.ajax-wrapper').html(result);
        Drupal.attachBehaviors($('.ajax-wrapper'));

    }
});

```

---
Tags: 8, javascript, ajax
---


# Question
Title: Create several form in a same module or function in Drupal 7
I want to create several forms from the same page. And these form I am generating from a custom module. I have already generated the function my\_module\_form (), but I can only create a single form. How can I generate more forms?

# Answer
> 1 votes
There's nothing limiting you to a single form, your page callback just needs to return a render array containing all of the ones you need:

```
return [
  'form_1' => drupal_get_form('MYMODULE_form_1'),
  'form_2' => drupal_get_form('MYMODULE_form_2')
  'form_3' => drupal_get_form('MYMODULE_form_3'),
];

```

---
Tags: forms, hooks
---


title: Broken/Missing Handers in View

text:
# Question
Title: Broken/Missing Handers in View
So one of my views has a few broken/missing handlers. It was working fine up until yesterday. I run `composer update --no-dev --with-dependacies` and a lot of files updated. After which i run `drush updb` and `drush entup` .A lot of files were updated. As far as i can tell, only views were affected. This view is an ordinary view, you can see in image bellow.

Those missing hanlders were ordinary fields, two were textfields and last one was a media entity. When i try to remove the handlers, and add those fields again they are not in the list of available fields, **as a matter of fact no custom fields \[over 30\], are available to be added** only the default fields \[Id, title, revision\], not even the Body field is there.

One thing i did find, is that one of my colleagues run a db\_script which was supposed to back up certain db\_tables, but it only emptied the tables \[affected tables were: key\_value, key\_value\_expire, media, router, sessions\].

composer.json:

```
{
"name": "drupal/drupal",
"description": "Drupal is an open source content management platform powering millions of websites and applications.",
"type": "project",
"license": "GPL-2.0+",
"require": {
    "composer/installers": "^1.0.24",
    "wikimedia/composer-merge-plugin": "~1.3",
    "drupal/core": "^8.5",
    "drupal/easy_breadcrumb": "^1.6",
    "drupal/pathauto": "^1.1",
    "drupal/search_api": "^1.7",
    "drupal/adminimal_admin_toolbar": "^1.0",
    "drupal/token": ">=1.0",
    "drupal/rules": "3.0-alpha3",
    "drupal/search_api_solr": "^1.2",
    "drupal/ctools": "3.0",
    "symfony/property-access": "^3.2",
    "drupal/salesforce": "^3.0@RC",
    "drupal/dynamic_entity_reference": "^2.0",
    "drupal/features": "^3.5",
    "drupal/crop": "^2.0",
    "drupal/focal_point": "^1.0@beta",
    "drupal/dropzonejs": "^2.0",
    "drupal/config_ignore": "^2.1",
    "drupal/embed": "^1.0",
    "drupal/entity_browser": "^2.0",
    "drupal/media_entity": "^2.0",
    "drupal/acquia_connector": "^1.14",
    "drupal/field_group": "^3.0",
    "drupal/entity_reference_revisions": "^1.4",
    "drupal/metatag": "^1.4",
    "drupal/reroute_email": "^1.0",
    "drupal/devel": "^1.2",
    "drupal/kint": "^1.2",
    "drupal/twig_xdebug": "^1.0",
    "drupal/better_exposed_filters": "^3.0@alpha",
    "drupal/config_filter": "^1.2",
    "drupal/entity":"^1.0",
    "drupal/entity_block": "^1.0",
    "drupal/entity_embed": "^1.0",
    "drupal/file_browser": "^1.1",
    "drupal/inline_entity_form":"^1.0",
    "drupal/media_entity_image": "^1.2",
    "drupal/smtp":"^1.0",
    "drupal/typed_data":"^1.0",
    "drupal/viewfield":"^3.0",
    "drupal/media_entity_actions":"^1.0"

},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
    "preferred-install": "dist",
    "autoloader-suffix": "Drupal8"
},
"extra": {
    "merge-plugin": {
        "include": [
            "core/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    },
    "installer-paths": {
        "core": ["type:drupal-core"],
        "profiles/schools/modules/contrib/{$name}": ["type:drupal-module"],
        "profiles/contrib/{$name}": ["type:drupal-profile"],
        "profiles/schools/themes/contrib/{$name}": ["type:drupal-theme"],
        "drush/contrib/{$name}": ["type:drupal-drush"],
        "profiles/schools/modules/custom/{$name}": ["type:drupal-custom-module"],
        "profiles/schools/themes/custom/{$name}": ["type:drupal-custom-theme"]
    }
},
"autoload": {
    "psr-4": {
        "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
    }
},
"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": [
      "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
    ],
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
],
"require-dev": {
}

```

}

Drupal 8.5.4 Drupal status: 0 errors, 1 notice \[irrelevant to this\]

Any ideas?

**UPDATE:** fixed \[partially\], i imported the data for the `key_value` & `key_value_expire` tables from another database (my dev db).

# Answer
> 0 votes
Sounds like the fields were removed during the update, but Views' config is still trying to look for them. If you have them in configuration somewhere, just import them. If not, I'd suggest removing the broken fields in Views, creating all the fields you need in the entity and check Views again. When you get it working take a config export!

---
Tags: views
---


title: External URL to internal images

text:
# Question
Title: External URL to internal images
Suppose I have a link field for internal images. `$node->file_image->uri` will for instance return:

```
internal:/sites/default/files/image/image.jpeg

```

I need to convert this into an absolute URL for metadata. I can do this manually, of course, but let's see what the usual functions do:

```
file_create_url() = "https://example.com/internal%3A/sites/default/files/image/image.jpeg"
file_build_uri() = "public://internal:/sites/default/files/image/image.jpeg"
file_create_url(file_build_uri()) = "https://example.com/sites/default/files/internal%3A/sites/default/files/image/image.jpeg"

```

No cigar, not even close. The new functions?

```
Url::fromUri()->toString() = "internal:/sites/default/files/image/image.jpeg"
Url::fromUri()->toUriString() = "base:sites/default/files/image/image.jpeg"

```

So, how to do it without doing it manually, of course? Removing `internal:` and prepending `$base_url` is very simple but still a hack.

# Answer
Found it finally:

```
Url::fromUri($node->field_image->uri)->setAbsolute(TRUE)->toString()

```
> 1 votes

---
Tags: 8
---


title: Contact form doesn't send mail

text:
# Question
Title: Contact form doesn't send mail
I am using the contrib contact module to add a contact form.

I created a category in /admin/structure/contact to add the recipient. I added my person address mail (It's valid).

When I test the form, Drupal returns a confirm notification to say that the mail is send successfully.. But the mail is not received.

In /admin/reports/dblog, any error is reported.

PS: I use in my site other functions to send mail and it's received.

Any idea please?

Thank you..

# Answer
I used the webform to create a contact form and mails are send
> 0 votes

---
Tags: 7, emails
---


# Question
Title: Referencing an existing image in theme settings
In a custom theme (Drupal 8.4.3) I would like to add a theme setting, where I can reference (not upload) an image to use as a background image. Like in a normal reference field, already uploaded images should be choosable; these images are stored in media entities. How can I build such a theme setting? I only found information about Uploading images in theme settings.

# Answer
I haven't been able to find an example of this, either, but here's a simple demo setting a reference to a media/image in theme settings (with the autocomplete widget):

```
use Drupal\Core\Form\FormStateInterface;

function THEME_form_system_theme_settings_alter(&$form, FormStateInterface &$form_state, $form_id = NULL) {
  // Work-around for a core bug affecting admin themes. See issue #943212.
  if (isset($form_id)) {
    return;
  }

  $opts = [
    '#type'          => 'entity_autocomplete',
    '#title'         => t("Call to Action Background"),
    '#description'   => t("Default call to action background media image; may be overridden on individual elements."),
    '#target_type'   => 'media',
    '#selection_settings' => ['target_bundles' => ['image']],
  ];
  if ($default_id = theme_get_setting('call_to_action_background')) {
    // element stores an int ID, but default value has to be the loaded entity
    $image = \Drupal::entityTypeManager()->getStorage('media')->load($default_id);
    $opts['#default_value'] = $image;
  }
  $form['call_to_action_background'] = $opts;

}

```

To retrieve and render, use a THEME\_preprocess hook with parameter &$variables:

```
$media_id = theme_get_setting('call_to_action_background');
$media = \Drupal::entityTypeManager()->getStorage('media')->load($media_id);
$variables['media_build'] = \Drupal::entityTypeManager()->getViewBuilder('media')->view($media, 'some_media_display_mode');

```

The render array is then available in twig:

```
{{ media_build }}

```
> 3 votes

---
Tags: 8, forms
---


# Question
Title: How to numerate drupal views rows in twig?
For css purpuses I want to add custom class name to the first item in view.

```
<article class="myclass"></article>
<article></article>
<article></article>

```

I need the number in views-view-fields--viewname.html.twig to make some logic expression like

```
if(view-num == 1) {
    <article class="myclass"></article>
} else {
    <article></article>
}

```

or maybe in one of the variables I get in fields {{fields.view\_number.content}}

# Answer
The fields template is probably not the best place. Normally you would do this in the views style plugin. `Grid` has such options built in, for `Unformatted` you can add

```
loop.first ? 'views-row-first',

```

to *views-view-unformatted.twig.html*:

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

```
> 2 votes

# Answer
No need for Twig, just do it with CSS:

```
.name_of_your_view_parent_container article:first-child {
  // seome styles here only for first item
}

```
> 0 votes

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


# Question
Title: How can I filter a result set based on a URL filter that affects an API call?
I have a View with a Rest Export display returning entities. I have a custom Normalizer class for it that crafts the object the way I want it in the response.

The node entity in the response has some custom data attached to it coming from an API (think operating hours). I am being asked that if someone clicks on 'Open Now' in the filtering form (not yet created), then anything *not open* should not be shown in the list.

Is there some way I can add a custom filter or hook into Views and look for this URL parameter and exclude a result from the list if it is not open? hook\_views\_pre\_render and hook\_views\_post\_render don't seem to fire, I assume this is because I am using Serializer format.

# Answer
So, I am not 100% confident in this approach, but I got a working solution. The base table is `Node`, I have no join, this data is not stored locally and I use an API call to fetch the operating hours. So I looked at how the Global filter options worked and started from there with `hook_views_data`:

In mymodule.module:

```
/**
 * Implements hook_views_data().
 */
function harlib_restful_normalizer_views_data() {
  $data = [];
  $data['libcal']['table']['group'] = t('LibCal');
  $data['libcal']['table']['join'] = [
    '#global' => [],
  ];

  $data['libcal']['open_now'] = [
    'title' => t('Open Now'),
    'filter' => [
      'id' => 'open_now',
      'title' => t('Currently Open'),
      'help' => t('Filter results by "currently_open" value on results from LibCal Hours API.'),
    ],
  ];

  return $data;
}

```

In my custom OpenNow filter class:

```
namespace Drupal\harlib_restful_normalizer\Plugin\views\filter;

use Drupal\harlib_libcal_api\Client\HoursTodayClient;
use Drupal\views\Plugin\views\filter\BooleanOperator;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Filters nodes based on libcal currently open value.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("open_now")
 */
class OpenNow extends BooleanOperator {

  /**
   * @var \Drupal\harlib_libcal_api\Client\HoursTodayClient
   */
  protected $hoursClient;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, HoursTodayClient $client) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->hoursClient = $client;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function postExecute(&$values) {
    if ($this->value) {
      foreach ($values as $key => $value) {
        $node = $value->_entity;
        $library_id = (int) $node->get('field_library_id')->value;

        if ($library_id === 0) {
          // No times associated with this library.
          unset($values[$key]);
          continue;
        }

        $hours = $this->hoursClient->request($library_id);

        if ($hours['currently_open'] == FALSE) {
          unset($values[$key]);
        }
      }

      $values = array_values($values);
    }

    parent::postExecute($values);
  }

}

```

If the filter is 'checked' or true, the `postExecute` method will loop the result set, check the hours returned and unset the result if the location is not currently open. I am not using pagination or anything, so, I did not test if it works in those conditions.

The better scenario is to filter the JSON list on the front end (since the data is already attached to the entity in the response), but I was asked to do it from the backend.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to index created field in baseFieldDefinition?
because we have a lot of query on created date field on our custom Entity, we looking for a solution to index 'created' field index in Mysql.

this is our baseFieldDefinition :

public static function baseFieldDefinitions(EntityTypeInterface $entity\_type) { $fields = parent::baseFieldDefinitions($entity\_type);

```
$fields['product_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Product Category'))
  ->setDescription(t('Product Category ref'))
  ->setRevisionable(FALSE)
  ->setSetting('target_type', 'taxonomy_term');

$fields['site_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Site ID Ref'))
  ->setDescription(t('Site Category ref'))
  ->setRevisionable(FALSE)
  ->setSetting('target_type', 'taxonomy_term');

$fields['price'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('Price'))
  ->setDescription(t('The Price of the Crawl entity entity.'))
  ->setDefaultValue(0);

$fields['created'] = BaseFieldDefinition::create('created')
  ->setLabel(t('Created'))
  ->setDescription(t('The time that the entity was created.'));

return $fields;

```

}

is there any setting or method in ContentEntityBase to set a field indexable in Mysql?

**NOTE:** we can index it with a simple migration in our module installer but first of it I'm curious about it, is there any solution to achieve it in BaseFieldDefinition?

# Answer
> 3 votes
The way to do that at the moment is a custom storage schema handler, see NodeStorageSchema for example:

```
protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
  $schema = parent::getEntitySchema($entity_type, $reset);

  $schema['node_field_data']['indexes'] += [
    'node__frontpage' => ['promote', 'status', 'sticky', 'created'],
    'node__title_type' => ['title', ['type', 4]],
  ];

  return $schema;
}

```

And then you register it with:

```
"storage_schema" = "Drupal\node\NodeStorageSchema",

```

as a handler.

To update existing installations, you need to drun drush entup or write an update function.

---
Tags: 8, entities
---


# Question
Title: How to generate more than one pdf from a node?
I need to generate two or more PDF from the same node with different templates. e.g.: from a reservation page of a accomodations site I would generate a PDF for client, a PDF for owner and a PDF for agent

I'm currently using Print module.

How can I do?

# Answer
> 1 votes
Print module doesn't support choosing multiple templates and content from the page. You'd have to create a custom module for that which isn't a trivial task.

If you can't code, maybe you can restructure your Reservation page in a way to use different Content types that reference each other (Entity reference). One CT for client info, the other for owner info and a third one for agent info.

You can use Views to display all that info on one page, all together. But Print module would apply to each node separately, so you'd be able to have that separate.

It may be that info you want to show overlaps between PDFs. You'd have to come up with a custom solution for anything more complicated like that.

Maybe you can combine different solutions for different PDFs.

Check out Entity Print, Printing any Drupal Entity to PDF.

---
Tags: 7, theming, nodes
---


title: Preprocess language switcher block

text:
# Question
Title: Preprocess language switcher block
I'm trying to modify the output of the language switcher block to make the output more inline with other menu styles on my site. However, I can't figure out how to modify the output.

I'm attempting to use the following:

```
function my_module_preprocess_block(&$variables) {
  var_dump($variables['elements']['#id'];
}

```

This gets every block on the page except for the language switcher.

How can I preprocess or modify this?

# Answer
We added a filter to drop the languages that did not have translations from the language switcher. Here's the code from that:

```
/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function mymodule_block_view_language_block_alter(array &$build, BlockPluginInterface $block) {
  $build['#pre_render'][] = '_mymodule_language_block_prerender';
}

```

FYI - Used pre\_render because I was removing links from the \[content\]\[\[#links\] element.
> 1 votes

---
Tags: 8, blocks, i18n-l10n
---


# Question
Title: Some nodes served headless Drupal and some nodes served with Drupal
We are building a site that will be built and served via Drupal. We want to have microsites that we want to share SOME of the content between the main site and the microsite. We are thinking to build the microsites via Headless Drupal and use API from the main site.

The problems I see:

For example, node/2 should only be accessible on the microsite. How would the main site which is not headless know that it can't access node/2? Basically, some nodes will be served headless and some will be regular Drupal.

Would it make things easier to just have the main site be headless as well?

# Answer
Take a look at the Permissions by Term module. You can add a term field that defines the site(s) the node is accessible by and limit access to content authors on the main site.

Your API for the microsites can use this to limit access by site as well.

If that one doesn't work, it's description lists another module that might work.
> 2 votes

---
Tags: 8
---


# Question
Title: How to display all terms for specific taxonomy in views incl. ones without content?
How to set up a view that displays **all terms for a specific taxonomy** including the ones that have **no content** assigned?

I just can't figure it out to do it with a view:CONTENT and mainly found posts about hiding them.

In the results table, I also want to show a count of # nodes for each term (which I managed to do with Aggregation \> Count).

I also tried creating as a View:TERM which does list all terms associated but then I can't display a count of nodes for it.

# Answer
> 0 votes
If the goal is to also show terms that have no content related to them, it doesn't make sense to start with the Content Views. How could you get terms information from non-existing relations? You could code a custom solution for that, logic that pulls out all terms and if no nodes are tagged display zero.

But there are ways to go forward with core Views.

## Display node count on Terms nodes

1. Create Views of type **Taxonomy term** displaying terms for the Vocabulary you want
2. Add a Relationship **Content using field\_yourtaxreffield**
3. You should already have the Taxonomy field, now add a new Field **Title** (or NID) and set it to use the Relationship from the previous step (to show nodes titles)
4. Turn **Aggregation on**
5. Edit the Aggregation settings on the Title field, change it to **Count DISTINCT**. Now you should be able to see the counts, next to all the terms from your chosen vocabulary, including the one with 0 nodes.
6. (Optional) you can `Override the output of this field with custom text` to place the count in brackets. The Text might be something like `({{ title }})`, check under `Replacement patterns`

The problem here is extending this result to list node titles. Adding another content related field messes up the Aggregation results because it breaks them into separate rows and count becomes meaningless in that context.

I don't know if there is a clever way to solve it without an additional module. Maybe someone else can come in with the solution.

If using more modules is ok you can look into Views Field View (instructions on how to use it are in Readme file, you could create Embed display with your content and a term contextual filter, then embed it as the third field in the above Views), Views Aggregator Plus has more aggreagator options, Views Distinct (D7 only, might be used to create a new view with its "Aggregate Repeats" and then use regular Aggregation on it).

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


# Question
Title: Show block menu links only on certain pages
I've built a menu with 20 links aprox. Then I put the block drupal creates for my menu on a region. Thing is I want some of the links to show for some pages, while others are hidden, like the option called "visibility options" on admin/structure/block/manage/block/nodenumber/

i.e.: links 1,2 and 3 should be visible on page node/1 links 1,3 and 5 should be visible on page node/2 links 3,5 and 6 should be visible on page node/3

Any advice on how can I make it possible?

NOTE: Sorry for my english but it's not my native tongue.

# Answer
> 0 votes
Without any additional information about the links inside your menu, it seems the easiest way to structure this is to create 3 separate menus, even if some of the links inside them are repeated.

What sort of links are those? Maybe you can use Views to create a Block that reacts to the page it's on to filter out the relevant links.

---
Tags: navigation
---


# Question
Title: Fatal error: Cannot redeclare casa_views_post_execute
I understand this to be two declarations of the same function, which is not allowed. But how to fix this?

Everything was fine until I started to enable the MailChimp module, then the backend has this fatal error:

Fatal error: Cannot redeclare casa\_views\_post\_execute() (previously declared in /home/kansascasa/public\_html/sites/all/themes/casa/template.php:26) in /home/kansascasa/public\_html/sites/all/themes/casa\_m/template.php on line 80

This is the code:

```
    function casa_views_post_execute(&$view) {
    watchdog('theme', print_r($view->result[0], true));
  if ($view->name == 'programs2' && !empty($view->result)) {
    //drupal_goto('node/' . $view->result[0]->nid);
  }
}

```

Second one:

```
function casa_views_post_execute(&$view) {

```

}

What is the fix for this? Appreciate your help in advance.

# Answer
I'm assuming you have two separate themes. Perhaps the theme in the casa\_m directory is a subtheme?

If the machine name of the theme in the /case\_m/ directory is casa\_m , then change the function name to casa\_m\_views\_post\_execute(&$view)
> 0 votes

---
Tags: debugging, emails
---


# Question
Title: Commerce - delete products that do not reference a node
I want to delete commerce products that are not referencing nodes. Either a delete process or report that shows which commerce products are not referencing nodes.

# Answer
> 0 votes
Try the Views Bulk Operations module.

You can create a View that lists Commerce Products

Use the Table format, showing fields.

Add a filter for the reference field and for the operator choose "Is empty (NULL)".

Add a field to the View, look for "Bulk operations: Commerce Product"

When the field settings come up, in the "Selected bulk operations" field set, check the "Delete Item" checkbox. Arrange this field to be the first one in the list.

Save the view.

Now you will see all products that do not have a value for your reference field. The Bulk Operations: Commerce Product field will make a checkbox display for each row, and you can select one or more products to delete.

You can also check the text box in the table header, and that will "select all" products listed on the page. If you have more than one page worth of products, a button will appear that will let you select all products in the view.

Choose the "Delete Item" option from the drop down above the view and hit the button, and it will start the delete process, after a confirmation.

---
Tags: 7, commerce
---


# Question
Title: Send email to all users with specific role (updated privacy policy)
We want to send an email to all users of a given role, to let them know about an updated privacy policy.

The filter by role allows to send different versions of the email to different roles.. not sure this is needed, but it will be useful to know.

Since this is a legal notice, it does not make sense to provide an unsubscribe link.

The email should be a somewhat decent looking HTML. Perhaps we want to add some user-specific tokens, e.t. to link to the user profile.

So there needs to be some kind of authoring UI, e.g. by creating a node or something.

## What I looked at so far

I installed mass\_contact, but it seemed to add unnecessary complication with its categories.

In some other questions, people suggest to use rules. But in my understanding those are mostly meant for repeated email-sending, not for a one-off. Also I don't really know where I would find the authoring UI.

Simplenews might be another option. In my understanding, this is designed for consent-based newsletters.

Perhaps all these solutions can be used for the purpose I intend, but perhaps there is something more specialized for this specific task?

# Answer
> 1 votes
Mass contact is probably the way to go for you, if it has to be a solution integrated into the site. Categories are really easy to configure.

Automated and integrated solutions are always recommended over hacks, but if you're really doing this only once, the fastest way would be to export email addresses and use an email campaigning service or design and send manually in batches (sending bulk emails are limited per hour for spam reasons) from your site email address but that is difficult to test.

Setting up the HTML styling for your email is what you'll spend most of your time (through Mime mail module). If you plan on testing it on various email clients that is. Many services (Gmail for example) strip styling from emails, so you have to be careful what you style and how. Usually you use a tool that takes your email CSS and applies it all inline, because that is the most reliable way most of the styles will "survive" various email client filtering.

Simplenews is a very comprehensive solution, much much more to configure and understand there than Mass contact.

I can't see configuring Rules to be triggered would be easier than using Mass contact.

In the future you may consider using a module like Legal.

# Answer
> 1 votes
You might try the Views Send module, https://www.drupal.org/project/views\_send

You can build a View listing users, filter by the role you want to send emails to.

The module will provide a field you can add to the View, "Global: Send e-mail"

There are various configuration options.

Then when you look at the View, you'll have checkboxes, and a "select all" checkbox you can use to select all in the page.

Follow the steps, and sending an email is easy!

---
Tags: 7, emails
---


title: Change default on login url

text:
# Question
Title: Change default on login url
How do I change Drupal's default on login url from `/user/<uid>` to `/user/<uid>/edit` so that a user gets to there right after they log in?

**EDITED:** Tried Rules:

> Events: User has logged in.
>
> Condition: User has role.
>
> Actions: Page redirect to user/\[current-user:uid\]/edit

For some reason it doesn't work.

Tried Login Destination. Redirects work, but the module doesn't support tokens.

# Answer
> 0 votes
Managed to do this with Rules:

> Events: User has logged in.
>
> Condition: -
>
> Actions: Page redirect to user/\[account:uid\]/edit

---
Tags: 7, users
---


# Question
Title: Custom form Edit, populate form field value by ajax (NOT dependent fields)
I created a views page show the submission rec from custom form. The **SAME page**, I embed a form block(add rec) after the views.

What I try to do is when I click the views row/record `edit` link. it will populate the the field value to the form block WITHOUT refresh the form. The "submit" value will change to update of course.

I find many examples on ajax just trigger event within same form. Not by click the link outside the form, any idea ? Some direction please ?

# Answer
You're going to have to trigger a javascript function, or a javascript event in your ajax callback There are several different ways you can do that, some number of ways here: How can I trigger a javascript function when a Drupal ajax call is complete?
> 0 votes

---
Tags: 7, forms, ajax
---


title: Drupal AJAX fires only once

text:
# Question
Title: Drupal AJAX fires only once
In Drupal 7, I have a form where I would like to do the following:

* Display a list of options in a simple two column table
* Selecting an action from a drop down list fires AJAX and replaces options in the table

I have code written and Drupal only posts values to the AJAX on the first time you pick a select. Does this just not work on form 'item' types? Note, there are also other forms on the page, but the form IDs are unique as are the form fields.

```
$form['new_date'] = array(
            '#type' => 'select',
            '#title' => 'Delivery Date',
            '#options' => $date,
            '#ajax' => array(
                'callback' => 'delivery_date_weekends',
                'wrapper' => 'dates-ajax',
                'method' => 'replace',
                'effect' => 'fade',
            ),
        );

$form['date_weekend'] = array(
                '#type' => 'item',
                '#prefix' => '<div id="dates-ajax">',
                '#suffix' => '</div>',
                '#markup' => '',
          );

```

Then in the AJAX callback, data is returned with #markup set to theme('table') of the results. It only works the first time around, I see the POST data in the Firebug console. Pick another drop down option, my table does not update.

Did I do something wrong here?

Edit: seems like the POST is making it, but the response is empty, but should not be.

Edit 2: Ajax Callback:

```
function delivery_date_weekends($form, $form_state) {

    $query = new EntityFieldQuery();
    $result = $query->entityCondition('entity_type', 'field_collection_item')
        ->propertyCondition('item_id', $form_state['values']['rates'])
        ->fieldCondition('field_delivery_basis', 'value', 'Weekly', '=');

    $startmonth = strtotime(date('m', $form_state['values']['new_date']).'/01/'.date('Y'));
    $endmonth = strtotime('+1 month', $startmonth);

    $query->fieldCondition('field_delivery_date_period', 'value', $startmonth, '>=')
                ->fieldCondition('field_delivery_date_period', 'value', $endmonth, '<=');

    $result = $query->execute();

    if ($result) {
        $headers = array(
            array('data' => 'Weekend', 'class' => 'tableHeader-processed'),
            array('data' => '', 'class' => 'tableHeader-processed'),
        );

        $rates = entity_load('field_collection_item', array_keys($result['field_collection_item']));

        foreach ($rates as $key => $rate) {
            if ($rate->field_delivery_available['und'][0]['value']) {
                $rows[] = array('data' => array(date('M j, Y', $rate->field_delivery_date_period['und'][0]['value']), array('data' => 'delivery link', 'class' => array('fee'))));
            } else {
                $rows[] = array('data' => array(date('M j, Y', $rate->field_delivery_date_period['und'][0]['value']), array('data' => 'Not Available!')));
            }
        }

        $form['booking_weekend']['#markup'] = theme('table', array('header' => $headers, 'rows' => $rows, 'sticky' => FALSE));
    } else {
        $form['booking_weekend']['#markup'] = 'No delivery weekends exist for this month. Please select another date.';
    }

    return $form['booking_weekend'];
}

```

Basically when a month/year is selected, I am querying for dates (inside a field collection).

# Answer
It's hard to say without actually running those queries but I think the problem is just because of a disparity in the names of your form elements.

In your form the element is defined as `$form['date_weekend']` but in your callback you set an element called `$form['booking_weekend']`.

This would probably be fine except that `$form['booking_weekend']` doesn't have the `#prefix` and `#suffix` that `$form['date_weekend']` does. Drupal replaces the entire wrapper element when it does an AJAX replace so if the new element doesn't have a wrapper with the same ID around it the next AJAX call won't work (as no element would exist with the correct ID).

I'd recommend changing the element names to match as this should solve the problem, but if you really need it to be a different element just add the wrapper around the new element in your callback:

```
// The rest of delivery_date_weekends() comes before this as normal...

  $form['booking_weekend']['#markup'] = theme('table', array('header' => $headers, 'rows' => $rows, 'sticky' => FALSE));
} else {
    $form['booking_weekend']['#markup'] = 'No delivery weekends exist for this month. Please select another date.';
}

$form['booking_weekend']['#prefix'] = '<div id="dates-ajax">';
$form['booking_weekend']['#suffix'] = '</div>';

return $form['booking_weekend'];

```
> 5 votes

# Answer
I was struggling with similar issue, and finally found solution here:

> Drupal replaces the entire wrapper element when it does an AJAX replace so if the new element doesn't have a wrapper with the same ID around it the next AJAX call won't work (as no element would exist with the correct ID).

Very simple, but I've forgot about it. After correcting div-id problem disappeared :) Thanks, Clive!
> 0 votes

---
Tags: 7, forms, ajax
---