# Question
Title: Strange behaviour with hook_entity_field_access
I've implemented hook\_entity\_field\_access like this:

```
function opencase_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, $account, $items = NULL) {
  if ($field_definition->getName() == 'field_linked_opencase_actor' && $operation == 'edit') {
    error_log($account->hasPermission('administer users'));
    return AccessResult::allowedIfHasPermission($account, 'administer users');
  }
  return AccessResult::neutral();
}

```

When I log is as a user without the "administer users" permission and I go to the edit page containing that field, I get a `'PHP message: \n'`, in the error log showing that the if-block has been reached and that the user does not have the permission. But the field still appears! If I return an `AccessResult::forbidden`, however, it works as expected. Any ideas why `allowedIfHasPermission` doesn't?

# Answer
**AccessResult::allowedIfHasPermission:**

> Creates an allowed access result if the permission is present, neutral otherwise.

If access is allowed somewhere else, a failed check for the permission doesn't prevent access, because it creates a neutral result.

As you found out you probably need to build a forbidden access result.
> 1 votes

---
Tags: 8, hooks
---


# Question
Title: Why is my Twig Override not displaying any content, when the original Twig was barely different and worked just fine?
I'm overriding a Twig template for the responsive\_menu module, and encountering an issue with content not displaying.

The original Twig is named `responsive-menu-horizontal.html.twig` and my replacement is named `block--responsive-menu-horizontal-menu.html.twig`. Please note that the name of the replacement was derived from my Inspect Element debugger's suggestions.

The two Twig pages are almost exactly the same, save for the names and the added classes for the ul and li pieces

!\[1\]: https://i.stack.imgur.com/T25DZ.png

When I use my override for the default Twig page, the nav completely disappears, and my debugger leaves me with this:

```
<!-- BEGIN OUTPUT from 'themes/indyres/templates/block/block--responsive-menu-horizontal-menu.html.twig' -->
<!-- END OUTPUT from 'themes/indyres/templates/block/block--responsive-menu-horizontal-menu.html.twig' -->

```

I'm confounded as to how it'll read my overriding template and render *nothing*. Any help/explanation is greatly appreciated, this is the first Drupal project I've ever worked on, and though I managed to keep my head above water in creating the styles for the rest of the site, this piece has me really lost.

# Answer
> 0 votes
After a lot of frustration, and realizing that I could (in fact) manage to get Superfish to do what I had originally wanted, I just `composer remove`'d the module and that's where it'll stay. Thanks for the help everybody!

---
Tags: theming
---


# Question
Title: How to add a pager at both the top and bottom of a View
How can I do this for Drupal 8?

I have searched for a solution but I didn't find anything yet, I hope some one here can help me.

I have this "pager.html.twig" (from the clasy theme) template in the path of my own theme, the path is "mytheme/templates/navigation/pager.html.twig" and this is rendered automatly by drupal in the views where the pager is requiered, but I have a requierement in my job that I have to place the pagination at the top and the bottom from my view.

## Example:

**\<\[1|2|3|4|5|6|7|8|9|10\]\> (this is the pager that I want to place on top)**

content of my view content of my view content of my view content of my view content of my view content of my view content of my view content of my view

**\<\[1|2|3|4|5|6|7|8|9|10\]\> (this is the drupal rendered pager automatly)**

Thanks in advace for the help.

# Answer
Ok, I solved it.

In my theme, I had copied all the content of classy theme because is like a copy of this.

In the theme exist an "**templeate**" folder, this have another folder called "**views**" inside this folder exist the file called "**views-view.html.twig**" in this file exist a few printing variables whit if conditions. All I had to do was copy the:

```
{% if pager %}
 {{ pager }}
{% endif %}
```

Condition almost at the end of the "**template**" and paste it where is above the content and *voilà*, I have my pager at the top and the bottom of my template.

I hope this be useful for anybody.

Thanks for your comments.
> 4 votes

# Answer
The first thing that popped into my mind, without testing, is that you can use a preprocess page function in your theme and add to variables a clone of the pager then you have to print (pager\_2) in a modified page template.
> -1 votes

---
Tags: 8, nodes, paging
---


# Question
Title: When to use a new field on the user account or a custom table and when use user.data service?
Is there any rule when to use a new field in the user account for storing information and when to use the user.data service?

My initial approach was: When the information should be editable either by an administrator or by the user itself, then use a new field. When the information should not be editable, only by code, use user.data service or a custom table.

E.g. in my case I am storing some information about where the user came from (marketing campaign) and some other information gathered during registration. This information is not meant to be shown to the user or edit by the user. Thus I decided to use the user.data service.

Now I am experiencing a very fast growth of the user\_data table and I'm wondering whether my approach was correct. Maybe I should have created a new table for this or use a new field in the account.

Is there any rule when to use the user.data service and any limitations?

# Answer
The purpose of the UserData API is to allow the storage of certain pieces of information related to a particular user. Its concept is similar to the State API in that the type of information stored is not a configuration that should be exported. In other words, it is specific to the current environment (but belonging to a given user rather than a system or subsystem).

Users are content entities, who can have fields of various data types. These fields are typically used for structured information pertaining to the user, for example, a first and a last name. However, if you need to store something more irregular, such as user preferences or flag that a given user has done something, the UserData is a good place to do that. This is because the information is either not something structured or is not meant for the users themselves to manage.

In the other hand if you want to be able to export and import your user information in different environments then you should use fields.
> 3 votes

# Answer
### user.data service

This is schema of table users\_data. User data service will stored data in this table.  And here are some data examples

Data of user will save in field value. This field has type **longblob**. Imagine, Customer want to filter all user enable allow contact. So what you will do?

So I think, just use **user.data service** when you need store data for user, don't need filter, compare... data with other user.
> 2 votes

# Answer
The only limitation of the *user.data* service is how you can retrieve the data, since you can do it by:

* `$module`, `$name`, and `$uid`
* `$module` and `$uid`
* `$module` and `$name`
* `$module` only

For example, you can find all the values a module set for a specific user passing `$module` and `$uid`, or find all the values set by a module passing only `$module`.
The data stored is serialized, though. If you need to index values using something else than module name, user ID, or a name assigned to the data, you need to create your own database table.

The pro of using the *user.data* module is that modules don't need to create the database table to store the data, and that the stored data is automatically deleted when a module is uninstalled (and in this case, all the data stored for that module is deleted) or when a user account is deleted (and in this case, all the data stored from the *user.data* service for that account, from any module, is deleted). This means less code for modules.

Entity fields aren't used to store preference, or information a module gather about users, but rather *properties* of the entity.

I would use the *user.data* service, except when it makes more complicated retrieving/altering the stored data. If I were to write a module that saves the IPs from which users access a Drupal site (including the first and the last time an IP was used from a user) to then check which users connected contemporary from the same IP, I would not use the *user.data* service, but a custom database table where each row contains user ID and IP, which allows to aggregate data and still be able to handle the information separately.

As for the database table growing quite fast, I would not worry about that, if using the *user.data* service is not causing data duplication. Using the previous example of storing the IP from which the users connect to a Drupal site, if the module is using `$user_data->set('mymodule', $uid, 'ips', $list_of_ips)` to store the list of IPs used from a user and `$user_data->set('mymodule', $uid, "ips:$current_ip", TRUE)` to quickly find the list of users using a specific IP with `$user_data->get('mymodule', NULL, "ips:$ip")`, then that is something to worry (and a sign that a different approach is better).
> 1 votes

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


# Question
Title: How to query all content type and add as checkbox for custom form?
Need help on how to create a custom form that is only available for admins that will query all content types and display the options as a checkbox.

The goal is to only add certain libraries to particular content types selectively through an admin form. How would i query all content types and display them as checkboxes?

What we tried:

**mymodule.module**

```
function mymodue_preprocess_node(&$variables) {
  $node = $variables['node'];
  $config = \Drupal::config('mymodule.settings');
  $enabled_content_types = !empty($config->get('enabled_content_types')) ? $config->get('enabled_content_types') : FALSE;

  // This is where we need help.
  if(in_array($enabled_content_type, $node->bundle()) {
    // perform some logic.
  }
}

```

**mymoduleForm.php**

```
<?php

namespace Drupal\mymodule\Form;

class mymoduleForm extends ConfigFormBase {
  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'mymodule.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'mymodule_settings';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $types = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->loadMultiple();

    foreach($types as $type) {
      $content_types[$type->id()] = $type->label();
    }

    // Need help setting this up so that the options are content types.
    $form['enabled_content_types'] = [
      '#type' => 'checkbox',
      '#title' => 'Enabled Content Types',
      '#description' => 'Run preprocess for all enabled content types only',
      '#options' => $content_types,
    ],
  }
}

```

# Answer
> 1 votes
This was inspired from @leymannx comments.

I changed the `'#type'` to `checkboxes`.

```
/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
 $types = \Drupal::entityTypeManager()
   ->getStorage('node_type')
   ->loadMultiple();

 foreach($types as $type) {
   $content_types[$type->id()] = $type->label();
 }

 // Need help setting this up so that the options are content types.
 $form['enabled_content_types'] = [
   '#type' => 'checkboxes',
   '#title' => 'Enabled Content Types',
   '#description' => 'Run preprocess for all enabled content types only',
   '#options' => $content_types,
 ],
}

```

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


title: Send mail to product owner with Rules

text:
# Question
Title: Send mail to product owner with Rules
I have a Drupal 7 site running including Commerce. I'm asked to make the webshop work in a way that the mail send after completing payment is send to the product owner(s).

So when creating a product via `/admin/commerce/products/add` the admin fills in the email address of the product owner/seller in a custom field called `field_seller_mail`.

When the visitor of the website pays its order, the site should send one or more mails to the owner(s) of the products zo that they can handle the delivery of the products.

In rules I choose the `when payed in full` trigger.
Then I choose to `loop` in the action part and loop trough the line items, but the field `field_seller_mail` is nowhere to be found.

What is the best way to solve this problem?

# Answer
> 1 votes
If the data about a product ***are not*** available when processing a "line item", you can ***make*** them available. To do so, use a technique similar to what is explained in my answer to "How to access commerce\_product field of line-items using Rules to flag the Commerce Product?", which includes a Rules Component that looks like so:

```
{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

```

Here is a blueprint of what you need to do:

1. Create a Rules Component, similar to the above Rules Component. Just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
2. Rework the Drupal Message shown via the last Rules Action in the Rules Component (Starting with "`Some details about this product`"), e.g. by also using any of the available tokens that fit your needs.
3. Execute that Rules Component inside your Rules Loop of the rule in which you want to loop over all line items.
4. Improve the Rules Component from Step 1 by creating whatever additional Rules Action(s) you need. Make sure to place these Rules Action(s) AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID".

---
Tags: 7, commerce, rules
---


title: Non-breaking space in menu link name

text:
# Question
Title: Non-breaking space in menu link name
How to put non-breaking space into a menu link name in Drupal 8? I tried ` ` but it got displayed literally.

# Answer
Use this in your theme so menu items can be processed as html

```
use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_HOOK()
 * processes 1 nested level of menu items
 */
function THEMENAME_preprocess_menu(&$vars){
  if($vars['menu_name'] == "main"){
    foreach($vars['items'] as &$link){
      $link['title'] = Markup::create($link['title']);
      foreach($link['below'] as &$nestedlink){
        $nestedlink['title'] = Markup::create($nestedlink['title']);
      }
    }
  }
}

```

**Alternatively** you can use css to make regular white space not wrap

```
.menu li a {
    white-space: nowrap;
}

```

Of course you have to adjust css for your particular menu class
> 0 votes

# Answer
Solution without code: On windows use the keyboard combination `alt 0 1 6 0` (hold alt key while typing the digits on the numerical pad) for a ` `. On Mac use `alt space`.

Free extra hint: use `alt 2 4 0` if you need to enter a `` soft hypen
> 0 votes

---
Tags: navigation
---


# Question
Title: Make custom field added to comments available in comment.tpl.php
I added a integer list field called "field\_rating" to the core comments. Now I want to use the new field directly in my comment.tpl.php with it's display settings, but I just don't know how to do that despite this should be a no-brainer. Help is much appreciated.

# Answer
> 1 votes
All you gotta do is add `<?php print render($content['field_rating']); ?>`

---
Tags: 7, theming
---


# Question
Title: Prefix of drupal: in front of certain dependencies and what does it mean?
I saw certain modules list their dependencies with a prefix of `drupal:`, while other don't.

What's the difference between:

```
name: Core
type: module
core: 8.x
dependencies:
  - block

```

And

```
name: Core
type: module
core: 8.x
dependencies:
  - drupal:block

```

Notice the extra prefix `drupal:` in front of `block`.

# Answer
> 2 votes
The 2nd is the correct way as per: https://www.drupal.org/docs/8/creating-custom-modules/let-drupal-8-know-about-your-module-with-an-infoyml-file but I think drupal is assumed for the project if its not specified (The first part before the : )

So for Drupal core modules they'd prefix with drupal: and for custom modules its usually the module name e.g. webform:webform as they are projects of themselves

---
Tags: 8
---


# Question
Title: Create a content for taxonomy vocabulary
I have one task to do but i'm not sure where to start. I have to create a content for storing current and historical data for each term in "extaxvoc", the current data will be shown on Search pages for "extaxvoc". I have no idea where to start with it as the task seems strange to me but at the same time i'm completely new to drupal cms overall.

# Answer
It seems like a little too many extra steps for me. You can use fields in taxonomy terms as well, if you want to store data. You can adjust the search to show terms afterwards, besides nodes(content entities). In any case, if this is mandatory, you can always add an entity reference field in the content type(the one you create for adding content which will store historical data and so on) and just add the needed fields there. Each node will be categorized by the category it references from "extaxvoc".
> 0 votes

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


# Question
Title: Unable to install the XYZ module since it requires the A module
When running (right after site install) the `drush cim -y` command, the following error appears:

> Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization. in Drupal\Core\Config\ConfigImporter-\>validate() (line 728 of /var/www/ifc\_test/web/core/lib/Drupal/Core/Config/ConfigImporter.php). The import failed due for the following reasons:
> Unable to install the XYZ module since it requires the YAML Editor module. Configuration XYZ.conf depends on the YAML Editor module that will not be installed after import. Configuration yaml\_editor.config depends on the YAML Editor module that will not be installed after import.

(*XYZ* is the name of the custom module.)

1. I have the *yaml\_editor* contrib module physically under modules
2. There is a dependency declared in the configuration files above
3. I also added *yaml\_editor* to the core.extension.yml file to make sure it should be installed

Why config importer not enabling the *yaml\_editor* module? I mean, that's what dependency declaration is for. Also, I've got a couple of other modules which are not enabled after site-install, they will be enabled during the `drush cim` process.

Of course `drush en yaml_editor -y` solves the problem, however, it's part of a building process, and I don't want to just insert an extra line into deployment script, just because this strange thing is happening.

Any ideas why config management doesn't enable (installs) this dependency, and why it says: "that will not be installed after import"?

# Answer
Adding the `yaml_editor` to `core.extension.yml` solved the issue. It perhaps were removed due to a complex `git merge`, and that's why my install process started to fail all that sudden.
> 10 votes

# Answer
I had the same issue. My situation as follow

Custom module with configuration. On export, the module's configuration data exported with name match the the code(php) configuration name as (xxx.settings.yml). If the "xxx" doesn't match the module name, the error occurs.

I changed the configuration name in the source code and it's working fine.
> 6 votes

# Answer
Suggestions:

* Try partial import by: `drush config-import --partial`.
* Make sure the required/missing module is present in `core.extension.yml`, e.g.

```
module:
  missing_module: 0

```

Note: If you're using *Configuration Split* module, make sure to populate the module to all files.
* Make sure you've run `drush updb` and cleared cache (`drush cr`).
* Try exporting first (especially `core.extension.yml`), then import again.
* Try to *Synchronize* from the UI (at `/admin/config/development/configuration`).

### Drupal Console

As for the alternative approach, try to do config import using Drupal Console, sometimes it can give you more clues about what's wrong. E.g.

```
drupal config:import

```

Or for a single item or a file (`--file`), try:

```
drupal config:import:single

```
> 4 votes

# Answer
The real cause:

Yaml Editor module was added to `drushcr.php` under `web/sites/default` the following way:

```
$command_specific['config-export']['skip-modules'] = ['yaml_editor'];
$command_specific['config-import']['skip-modules'] = ['yaml_editor'];

```

This way you can ignore modules from drush cim and/or cex to enable/disable modules. This is very useful when developing, since module likes devel, kint etc. will be enabled on your localhost, but when you make changes in the config, and you make a cex, these development modules won't be enabled on the production site.
> 0 votes

# Answer
Checkout your config with the latest code, run `drush cr`.

After that import your configuration to local.

```
drush cim -y

```
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: How to expose filter for entity reference as dropdown in the Search API view?
In my Search API view, I'd like an *Exposed filter \> Entity reference* to be a select box, not a text field.

### Details

I have a view which I created like:

* *Views \> Add new view \> Show: default node index*

So it uses the Search API index as a basis.

In the Search API I have ticked to index `field_entity` which is an `Entity reference > Content_type: entity` (confusing naming, I know).

I want the user to go to the views page & be able to filter the view results by `field_entity` (which is an exposed filter/entity reference).

The issue is the view shows the exposed filter as a text field. I have edited `field_entity` & checked the box `Render Views filters as select list` \- this works fine for a normal view but not for a Search API view.

### Question

Can I somehow convert this text field to a select box?

---

To clarify, I cannot use custom or contributed modules on this project, so it needs to be done without using hooks, or other modules, etc.

# Answer
Try to use TYPE =\> String. This work for me.
> 0 votes

---
Tags: 7, views, search
---


# Question
Title: d8 webform submission views how to exclude Action Apply to Selected Items
The view created using the webform views integration module.. all the fields are shown as desired. However the CBO box with choices to then apply changes is not wanted. Hoping it's a setting somewhere.

# Answer
Just after posting I found the answer. In fields section, the webform submissions bulk operation form entry can be deleted and that removes the pesky entry shown in the question.
> 0 votes

---
Tags: views, 8, webforms
---


title: view slideshow not working

text:
# Question
Title: view slideshow not working
I created a view block and a content type "slideshow image" with "title" and "image" specially for slideshow. In this block only images of "slidshow image" content will appear.

And i added up five elements and i see effects on the slide show.

And even i created a directory named "jquery.cycle" in libraries \sites\all\sites\all\modules\libraries. Added the jquery.cycle.all.js file into that directory and but i didnt got any sliding of images...

Only the latest image is displaying but no effects.

# Answer
> 1 votes
If you are using the libraries API module, the correct place for the JS code is actually sites/all/libraries, not \sites\all\sites\all\modules\libraries (why do you have sites/all in the path twice?)

What slideshow module are you using, views\_slideshow? I don't think you will actually need to add a jquery library if that is the module you are using, but that will depend on the actual module you are using. If you are trying to build a slideshow from scratch with jQuery cycle, here is info from the handbook on getting your js added to Drupal http://drupal.org/node/304255

# Answer
> 0 votes
> Only the latest image is displaying but no effects.

Make sure the view returns more than one image.

Also, for views\_slideshow module, make sure the display style is set to Slideshow and correctly configured.

# Answer
> 0 votes
download and install dev version of jquery\_update module and change version 1.7 of jquery on settings page

# Answer
> 0 votes
I solved this problem by unchecking the "Display all values in the same row" setting under the MULTIPLE FIELD SETTINGS for the image field I wanted to cycle through.

---
Tags: 7, media, javascript
---


# Question
Title: How can I fix site UUID does not match error during config import?
I'm getting this error below whenever I try executing the commands `drush config-import staging` on the CLI. I'm basically in the process of migrating a drupal 7 DB to Drupal 8 and currently following this guide since I'm still new with migration.

https://www.youtube.com/watch?v=\_z2FH0efd\_g

---

```
Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization. in         [error]
Drupal\Core\Config\ConfigImporter->validate() (line 728 of
/Applications/XAMPP/xamppfiles/htdocs/drupal-eight-iom/core/lib/Drupal/Core/Config/ConfigImporter.php).
The import failed due for the following reasons:                                                                [error]
Site UUID in source storage does not match the target storage.
Entities exist of type <em class="placeholder">Shortcut link</em> and <em class="placeholder">Shortcut set</em>
<em class="placeholder">Default</em>. These entities need to be deleted before importing.
The core.extension configuration does not exist.
Can not uninstall the Configuration module as part of a configuration synchronization through the user
interface.

```

---

```
$databases['default']['default'] = array (
  'database' => 'drupal-eight-iom',
  'username' => 'root',
  'password' => '',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['upgrade']['default'] = array (
    'database' => 'drupal-seven-iom',
    'username' => 'root',
    'password' => '',
    'prefix' => '',
    'host' => '127.0.0.1',
    'port' => '3306',
    'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
    'driver' => 'mysql',
  );

$settings['install_profile'] = 'standard';
$config_directories['staging'] = 'sites/default/config';
$config_directories['sync'] = 'sites/default/files/config_zB_DnNUK68i5Owp5a8FzTiClQfp3d3jrwcy0_HuS1hNCGv9Y_Iva2Ahm8LCH-P0j0M2jwmQAsA/sync';

```

# Answer
> 1 votes
> Site UUID in source storage does not match the target storage.

Make sure you've `system.site.yml` on your staging site, see: Site UUID in source storage does not match the target storage.

To check the current UUID, run:

```
drush config-get "system.site" uuid

```

to change it, run:

```
drush config-set "system.site" uuid "xyz"

```

See: How can I import the configuration on a different site?

> Entities exist of type *Shortcut link* and *Shortcut set* *Default*. These entities need to be deleted before importing.

Try removing these entities manually before the import as it says.

> The `core.extension` configuration does not exist.

Make sure you've `core.extension.yml` file in your config folder, otherwise generate one via `config-export`.

> Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.

Most likely it's related to the missing `core.extension.yml`.

---

Few hints:

---
Tags: 8, drush, migrations, configuration
---


# Question
Title: Difference between calling a service method in drupal 8
I want to know what difference does it make when i call a service this way :

```
$service = \Drupal::service('myservice.method');
$service->methodNameInService();

```

or this way (Dependency Injecton)

```
 public function __construct(MyService $myService) {
+    $this->myService = $myService;
   }

public function test() {
    // Call function from service
    $this->myService->methodNameInService();

}

```

Is this better for performance or is it just only the right way and has it zero effect on performance or something else?

# Answer
> 4 votes
Dependency Injection has several advantages when you try to create test for your code, and follow the Single Responsibility Principle.

Really, the second reason is a consequence than the first: "The code is testeable because follow the SRP"

Furthermore, IDEs can recognize better the class type (and create autocompletes, f.e.) if the class is defined using DI. In a normal IDE, $service defined in `$service = \Drupal::service('myservice.method');` has a unknown class.

In some places you cannot use DI (fe. in a .module) and you need to use the static load.

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


# Question
Title: Tags won't show on Advanced Forum Module
I am using Drupal 7. I'm struggling to get the tags to show on my forums within the Advanced Forum module.

I have configured them within the `manage fields` settings

but they will not show anywhere else on my forum pages. I have checked the Drupal listing here and tested both suggestions, still no change (even after clearing cache.)

What am I doing wrong or missing?

FYI: Please before suggesting any other tag modules, please help me with my current setup and Advanced Forum module. Thank you.

---

# Answer
> 0 votes
Dev error: They weren't showing on any of the posts, because it was a new field, hence once you make the new post and select tags for them, then post, then they show just fine.

---
Tags: views, nodes
---


# Question
Title: How to allow authenticated user to view others data?
My sales staff fills in a webform with uploaded pics The Service department needs to view the submitted pics for the installations. Wondering if a module is needed to allow an authenticated user to view the submitted data entered by someone else. Currently my view only shows up when the user is an administrator. Webform Views Integration works Great... if only my Service Dept users could see the data.

# Answer
> 0 votes
Found it in people/permissions Checked the authenticated user columns for webform submissions and pages. Now it works as it needs to.

---
Tags: views, 8, webforms
---


# Question
Title: How to assign programatically a field to a paragraph bundle
I'm developing a module to extend paragraphs module.

The idea is that the users can assign a description field to paragraphs bundles.

I have create a module, and also I have create the file `field.storage.paragraph.parrados_description.yml` If I go to `admin/reports/fields` or if I try to assign the field to a paragraph bundle with UI I can see it in the list of fields.

But what I want to make it's create a form with paragraphs bundles checkboxes, so the administrator / site builder can check the bundles to assign the field to it when the user submit the form.

But I don't find any method to assign a field to a bundle.

Thanks

Oskar

# Answer
> But I don't find any method to assign a field to a bundle.

This is not one single method, it's a bit more complicated than that. Example for the body field in a node bundle. First create the bundle specific field config referencing the existing field storage:

```
  $field_storage = FieldStorageConfig::loadByName('node', 'body');
  $field = FieldConfig::loadByName('node', $type->id(), 'body');
  if (empty($field)) {
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'bundle' => $type->id(),
      'label' => $label,
      'settings' => ['display_summary' => TRUE],
    ]);
    $field->save();

```

Then add the field to the display modes:

```
    // Assign widget settings for the 'default' form mode.
    entity_get_form_display('node', $type->id(), 'default')
      ->setComponent('body', [
        'type' => 'text_textarea_with_summary',
      ])
      ->save();

    // Assign display settings for the 'default' and 'teaser' view modes.
    entity_get_display('node', $type->id(), 'default')
      ->setComponent('body', [
        'label' => 'hidden',
        'type' => 'text_default',
      ])
      ->save();

    // The teaser view mode is created by the Standard profile and therefore
    // might not exist.
    $view_modes = \Drupal::entityManager()->getViewModes('node');
    if (isset($view_modes['teaser'])) {
      entity_get_display('node', $type->id(), 'teaser')
        ->setComponent('body', [
          'label' => 'hidden',
          'type' => 'text_summary_or_trimmed',
        ])
        ->save();
    }
  }

```

Code example from https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/node\_add\_body\_field/8.5.x
> 1 votes

---
Tags: 8, entities, paragraphs
---


# Question
Title: How to migrate users and keep their IDs unchanged?
I'm trying to use migrate\_d2d, via the UI, to migrate a site from D6 to D7. I need to preserve user UID's in the migration. I'm finding the documentation confusing..

Given this in the UI...

What do I need to do to import the users?

# Answer
Here is the solution (see image)

1. Uncheck DNM in 'Option:...' row
2. Enter 1 as default value
3. Save
4. Edit again
5. A new row will appear for 'Existing user ID'
6. Select Source field, i.e uid.
7. Save

This works...
> 1 votes

---
Tags: 7, users, migrations
---


# Question
Title: Can I enable the Honeypot module for comments on the Advanced Forum pages?
How do I configure the Honeypot module to work on comment pages for the Advanced Forum module?

I enabled the Honeypot module, checked *Blog entry node form* and *Forum topic node form* in *Node forms* and *Comment forms*.

# Answer
> 1 votes
The module configuration page is just the one on /admin/config/content/honeypot, which has the following settings.

>

If you expect to see a difference on protected forms, there isn't anything visible. The module creates a form element that is hidden to users, but tools that automatically fill the form will fill also that, making clear they aren't human users.
The module also doesn't accept a form submission before *time limits* seconds are passed from the moment the form is rendered.

If you are testing a form using a user account with the *administrator* role, that has the *Bypass Honeypot protection* permission, so you will not see any hidden form element even watching at the HTML markup of the page.

---
Tags: advertising
---


# Question
Title: Add an attribute to $variables from a Controller
I need to add an attribute to the body tag from a controller. Adding a body tag with `hook_preprocess_HOOK()` is not a problem.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MY_MODULE_preprocess_html(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'my.route') {
    $variables['attributes']['class'][] = 'my-class';
  }
}

```

However, I only want to add the attribute when the node object, which is already in the controller, meets a second condition which is:

```
if ((\Drupal::routeMatch()->getRouteName() == 'my.route') && ($this->moderationInformation->hasPendingRevision($node))) {}

```

I don't have `$variables` in the controller so how can this be done?

# Answer
> 2 votes
Rendered output from a controller or other page elements like blocks or menus don't have direct access to the variables of a page/html preprocess hook. You can however attach metadata to the render array which then bubbles up to the page level when rendered, for example html\_head or css libraries. In your case one possible way would be to attach a placeholder to the render array of the controller, which then replaces a placeholder class in the body tag. But I still would prefer to get the node via the route parameter, see the linked topic in the first comment.

A code example how to replace a body tag class from a controller. First add a placeholder class in the preprocess hook:

```
/**
 * Implements hook_preprocess_HOOK() for html.html.twig.
 */
function mymodule_preprocess_html(&$variables) {
  $variables['attributes']['class'][] = 'body-placeholder-class';
}

```

And then attach a placeholder to the build array to replace this class from the controller:

```
$build['#attached'] = [
  'placeholders' => [
    'body-placeholder-class' => [
      '#markup' => 'class-replaced-by-controller',
    ],
  ],
];
return $build;

```

---
Tags: 8, nodes
---


# Question
Title: How to add a field to be displayed alongside the title?
I'm trying to create a preprocess function to add one of my fields to be displayed alongside the title of my specific content type. So, instead of my title just saying **Book Name**, it'll say **Book Name - 2018**. Basically, the year would come from a field in the content type called `field_year`.

I have the following in my `.theme` file which doesn't seem to work but I really don't know where to go from here as I've not dabbled with preprocesses too much:

```
function THEME_preprocess_node__books(&$variables) {
  $node = $variables['node'];
  $variables['fields']['title'] = ($node->getTitle() + $variables['content']['field_year']['0']['#context']['value']);
}

```

Let me know what I'm doing wrong and what's the best way to go about this.

# Answer
> 0 votes
Your question may lead to different opinion-based answers. Some might say: Display Suite. Others might say: do it in templates. And you could also: hide this certain field to then preprocess it back as suffix of the title (`hook_preprocess_page_title`).

All of them are no ideal solutions, IMHO. Display Suite is too heavy. Templates get too fiddly too fast (and I don't like how they can make the Field UI needless). Same for the preprocess function. Although if I would be forced to choose one of the named options I'd rather take the preprocess approach.

What I'd recommend instead is to solve your problem the other way around: Make the title a field, a **pseudo field** to be precise, that can be placed like any other field in the "Manage display" settings of any content type. Then you simply can drag this title field next to your other field and style them with some basic CSS to be displayed inline.

If you are interested in making the title a pseudo field to solve your problem just implement the code snippets I documented in my other answer on that topic: https://drupal.stackexchange.com/a/263740/15055

Still, if doing it that way you need to edit `node.html.twig` to remove the default (hard-coded) title output from it, to prevent getting printed twice when viewing this node not as page. Your node title now will be printed like any other field. And of course you also may need to prevent the title block from being printed on your node pages. This can be done per content type in the block settings if I remember it right.

---
Tags: 8, theming
---


# Question
Title: How to use Docker for a drupal development site and then deploy to online provider?
I am operating a Drupal website with two installations:

* a development site on my local machine (*dev*)
* a live site at my ISP offering an Apache httpd, with PHP and MySQL (*live*)

For *dev*, so far I have just installed software on my local machine (httpd, php, mysql, drupal) and deployed updates to *live* by copying changed PHP files and uploading a database backup.

I am considering to use Docker for my *dev* installation (e.g., docker4drupal). However, due to ISP limitations for the *live* site I will still have to deploy updates by uploading PHP files from the webserver and database images from MySQL/MariaDB.

What is the best way to extract PHP files and DB snapshots from a docker4drupal installation (or similar Docker based set-ups)?

# Answer
> 0 votes
You're asking 2 questions in the post: a general one (title) & a platform specific one (body), which is off-topic here (we don't write tutorials for Drupal platform integration). I'll answer the general which is useful at-large.

Most of the docker-based Drupal dev tools have decent feature sets. Each tool has one-or-two features that make it uniquely standout for a particular use scenario. You have to judge a dev-tool on **who's** maintaining, **why** are doing it, **what** are its supported features/platforms, **how long** it's been in development.

Theoretically, everything being Dockerized means you build/test locally and can deploy anywhere that does Docker hosting. In practice, to get from point A to point B, you'll have to figure how what your host platform provides technically (e.g. IaaS vs PaaS, CI tools, etc.) to what you have for your dev setup is (e.g. Dockerized toolchains, source code host, etc.) and match it up to see if all the pieces fit.

You can decide **provider** or **docker-based dev-tools** first, but a choice of one is going to impact the other in some way. You basically have to go a through a matrix of:

* What the Docker dev-tool provides
* What features you want (for platform/dev-tools)
* What the platform provides (for integration)

Then the "best" is whatever matches lines up most in your matrix (or tensor since we're talking 3 attributes here). There's a lot of details along the way. You have to do a lot research to fill in the details that work best work for your project.

---
Tags: deployment
---


# Question
Title: How can I update a module to a specific version using Drush?
I am trying to update module entityform 7.x-1.4 to entityform 7.x-2.0-beta4.

The current version of the entityform module is 7.x-2.0-rc4. But I don't want to update at this version.

Can we update module at specific version using drush?

# Answer
> 9 votes
By default, `drush pm-update` will update Drupal core and all enabled projects to the latest recommended releases. The optional project argument allows you to provide a list of installed projects to update, thereby limiting the scope of the update.

You can also pass a specific version of Drupal core as a project argument and Drush will limit the upgrade to that version of core (and core only, unless you pass other projects along as arguments.)

```
drush pm-update entityform-7.x-2.0-rc4

```

---
Tags: drush
---


# Question
Title: Permission issues with Custom Content Entity exposed to REST API
I hope it's not a duplicate entry.

I've recently created my Custom Content Entity within a Custom module and I'm currently having trouble with permissions. (Please see permissions below)

The permissions work perfectly when using the add/edit/delete Drupal forms. It throws a 403 if the current user has not the permission, which is great because everything is normal here.

But when I expose the Custom Content Entity via RESTui module : GET, POST, UPDATE. (please see screenshot below). Anonymous users don't get 403 and are able to create, edit.

Are the permissions defined under mymodule.permissions.yml only for Drupal entity form ?

How do we define REST permissions for a Custom Content Entity ?

Thank you very much for your help

# Answer
Actually, this was a false positive error.. I did some testing with my REST Client in Chrome (please see screenshot at the end of the paragraph) and permissions are correctly working.

The issue was related to my XHR request which was (for some reasons) keeping a valid CSRF token and because of this I appeared to be identified as admin. And of course as admin ID 1, I was granted full access on CRUD..

Sorry and thanks for your time guys!
> 0 votes

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


title: add file browser button to ckeditor

text:
# Question
Title: add file browser button to ckeditor
I have installed ckeditor 3.5.2 with Wysiwyg profiles and every thing works great. but in admin user page i can see file browser link . how to add this link like button to ckeditor? i checked buttons like image and imce a but it doesn't add file browser to ckeditor. at now i have upload files in admin user page and link them with ckeditor. Anyone have this filebrwoser button (for uploading zip ,...) on ckeditor?

# Answer
I'm not 100% sure but I think you need the IMCE Wysiwyg Bridge module.
> 1 votes

# Answer
How to enable the file browser feature with Ckeditor in Drupal 8?

1. Install Embed Module.
2. Install Entity Embed module.
3. Install File Browser module. It requires following contributed modules - Entity Browser Entity Embed Embed dropzonejs DropzoneJS entity browser widget
4. To configure the "Entity Browser" Module, you will need ctools module.
5. At this page - https://example.com/admin/config/content/formats/manage/full\_html Drag the "File Browser" icon from Available Buttons to Ac
6. Enable the checkbox - "Display embedded entities"

Thats all.
> 0 votes

---
Tags: wysiwyg, files
---


title: Drupal 7 Bootstrap Subtheme update

text:
# Question
Title: Drupal 7 Bootstrap Subtheme update
I'm trying to understand the flow of the bootstrap subtheme. The subtheme on my site was originally installed by a developer. I have since edited the css file to my liking and made adjustments to the bootstrap\_subtheme.info, header.tpl.php, page.tpl.php, template.php and others.

The thing I don't understand is how to update the subtheme or even if I have to. I have been told by a developer that the bootstrap files are 5 years old. I apply each update as it comes into the list of updates and it is up to date in that respect. Do I have to update the subtheme manually from the basetheme? How do I find out the age/version of the subtheme?

# Answer
> 0 votes
The subtheme should inherit all of the basetheme files by default. So in theory you should be able to update the base bootstrap theme and your subtheme will gain all the benefits of those updates (Apart from things you're base theme has overwritten.)

E.g. if in bootstrap you have a page.tpl.php and you also have one in your subtheme then updating the bootstrap page.tpl.php won't have any effect as your subtheme has its own version of page.tpl.php

But anything that hasn't been overwritten/customised by your sub theme should be automatically be picked up by your subtheme. So you don't need to know what version your subtheme is, its effectly whatever the current bootstrap version is your subtheme is a ofshoot of that.

---
Tags: theming, bootstrap-theme
---


# Question
Title: How on node forms do I show weight of all menu items?
I'm wondering how it is possible (with a hook) to show the weight next to the menu title in the parent drop down found in the Menu Settings tab.

So this is what it is at this moment:

And this is what I want it to be, so the admin knows what weight to fill in to place the menu item at a certain place:

# Answer
> 0 votes
Doing a hook\_form\_alter on the node edit form should do the trick:

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

  function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** to appear on the node/add/page form, change this or add more for other content types **/
  if ($form_id == 'node_page_form') {
    $menuItems = $form['menu']['link']['menu_parent']['#options'];
    $menuItemsWithWeight = array();
    foreach ($menuItems as $menuKey => $menuValue) {
      $storage =  Drupal::entityManager()->getStorage('menu_link_content');
      $uuid = ltrim(strstr($menuKey, ':'), ':');
      $uuid = ltrim(strstr($uuid, ':'), ':');
      $link = $storage->loadByProperties(['uuid' => $uuid]);
      if(count($link) > 0) {
        $link = reset($link);
        $weight = $link->getWeight();
        $menuValue = $menuValue . ' ('.$weight.')';
      }
      $menuItemsWithWeight[$menuKey] = $menuValue;
    }
    $form['menu']['link']['menu_parent']['#options'] = $menuItemsWithWeight;
   }
  }

```

---
Tags: 8, navigation
---


# Question
Title: How can the author choose when to publish an article, whether the article gets a teaser or not?
Is there a possibility for the author/editor to decide - when publishing - whether the article (the content type) gets a teaser or not? This is important for the look of the article on the front page.

I thought so far that would have to be defined before in the content Type.

# Answer
If I understand your question, then this can be done by checking the `Promoted to Frontpage` box on the article.

You can then change your view to filter out nodes that have `Promoted to Frontpage` checked.
> 0 votes

# Answer
Have a look at Community Documentation about View modes, here is an intro about it (from that same page):

> How a node is displayed depends on the context in which it is viewed, such as the difference between full nodes and teasers. On the page for field display management there are extra settings under the label custom display settings. The settings consist of a check box list of all view modes available for nodes, marking which view modes should have customized display settings. In a standard Drupal installation only teaser is checked, resulting in two sub tabs on the manage display page – default and teaser. The sub tabs lead to separate settings for each view mode.

Some more details (from the same linked page):

* In Drupal 7, additional View modes can be added to entities using `hook_entity_info_alter()`.
* In Drupal 8, adding a custom view mode can be accomplished without code. To add one, expand Custom Display Settings on the Manage Display tab of a content type, then click Manage View Modes.

So if you'd only add 1 optional (text?) field to store such teaser, the author/editor could use that to optionally use such teaser, and by using "View nodes" you (as an admin) can decide how to dislay them.
> 0 votes

# Answer
There is not a built-in way to do this, you'll need to add a field or other setting to the content to indicate how the article is displayed. The Custom Publishing Options module would be one way to add the option to the edit form. Alternately you could just use a field.

As Pierre suggested, a custom view mode will help with the next step. You might create a new view mode called 'full\_or\_teaser':

```
/**
 * Implements hook_entity_info_alter().
*/
function mymodule_entity_info_alter(&$entity_info) {
   $entity_info['node']['view modes']['full_or_teaser'] = array(
  'label' => t('Full or teaser'),
  'custom settings' => FALSE,
 );
}

```

That view mode can then be selected in your front page view.

Now you need to select full or teaser output depending on the setting for the node. There's a number of ways you could do that but hook\_entity\_view\_mode\_alter looks like the best for this case:

```
function my module_entity_view_mode_alter(&$view_mode, $context) {
   if ($view_mode === 'full_or_teaser') {
       $node = $context['entity'];
       $view_mode = empty($node->myoption_full)? 'teaser': 'full';
   }
}

```
> 0 votes

---
Tags: nodes
---


# Question
Title: Execute actions (actions module not rules module) programatically
How can an action from the actions module be executed programatically? In D7 there was actions\_do() but in D8 actions are plugins or configuration entities according to https://www.drupal.org/node/2020549.

# Answer
You should inject the plugin manager as a service if possible, but for a plugin (code) based action:

```
$manager = \Drupal::service('plugin.manager.action');
$action = $manager->createInstance('action_plugin_id')
$action->execute();

```

Or if it's an advanced action, it's a config entity, so load and execute it that way:

```
$action = \Drupal\system\Entity\Action::load($action_id);
$action->execute();

```

Again if DI is an option, inject the entity type manager service and use that to load the action instead.
> 4 votes

---
Tags: 8, plugins, actions
---


# Question
Title: $.cookie is not a function from form.js with block cache
I am getting this error if I turn my block caches on. I have traced back the origin back to Drupal core form.js but can't seem to see what's going on here. Any ideas?

Here is the debug:

```
form.js?v=7.56:69 Uncaught TypeError: $.cookie is not a function
at String.<anonymous> (form.js?v=7.56:69)
at Function.each (jquery.min.js?v=1.7.2:2)
at HTMLFormElement.<anonymous> (form.js?v=7.56:67)
at Function.each (jquery.min.js?v=1.7.2:2)
at $.fn.init.each (jquery.min.js?v=1.7.2:2)
at $.fn.init.$.fn.once (jquery.once.js?v=1.2:55)
at Object.attach (form.js?v=7.56:65)
at Object.<anonymous> (drupal.js?p3kpc3:76)
at Function.each (jquery.min.js?v=1.7.2:2)
at Object.Drupal.attachBehaviors (drupal.js?p3kpc3:74)

```

Update: I think I am isolated this problem to a webform in a block on the page. If I get rid of that form, the error goes away. Also, this error doesn't happen every single time. Sometimes I have to change browser or open in incognito for it to crash, and then it happens repeatedly.

I can see that jquery.cookie is there when it works. But when there is a crash and I see the page source it's not there, so somehow it seems it's failing to load and when it happens I get the error. I am using JQuery Update (1.7).

# Answer
> -1 votes
This happens sometimes as $.cookie function is not supported. In those case you can try following approach.

Place this code in your JavaScript file

```
function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for (var i = 0; i var c = ca[i];
  while (c.charAt(0) == ' ') {
    c = c.substring(1);
  }
  if (c.indexOf(name) == 0) {
    return c.substring(name.length, c.length);
  }
}
return "";
}

```

Then you can use, `setCookie(cname, cvalue, exdays)` and `getCookie(cname)` to use set and get cookie functionalities instead of `$.cookie`.

Hope this works.

---
Tags: 7, javascript, blocks, caching
---


title: Drupal debug (know which file are used)

text:
# Question
Title: Drupal debug (know which file are used)
I need to modify something in a website (it's a form in the backoffice), the problem is that I don't know where is it located in the files, I try to search some words of the form with phpstorm but nothing.

Is there a way to activate something like a debug who can show which files are used to show the current page ?

# Answer
> 0 votes
Have a look at the id of the form. In my screenshot it says 'user-login-form'. If the form you are looking for is written in code (a custom module), you should find something when searching for 'user\_login\_form' (notice the difference: underscores instead of dashes)

# Answer
> 1 votes
**Theme debug mode**

As of Drupal 7.33, Drupal core has a theme debug mode that can be enabled and disabled via the theme\_debug variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments). To enable it, add this line to your settings.php:

```
$conf['theme_debug'] = TRUE;

```

You can enable it with drush using:

```
drush vset theme_debug 1

```

And disable using

```
drush vset theme_debug 0

```

---
Tags: 7
---


# Question
Title: How to fix "Unable to save a field collection item without a valid reference to a host entity" error?
I programmatically created a series of custom content entities which contain field collections. My site had an execution timeout error in the middle of entity creation and saving.

I can not delete some of these entities. Any attempt is met with:

> The website encountered an unexpected error. Please try again later.
>
> Drupal\Core\Entity\EntityStorageException: Unable to save a field collection item without a valid reference to a host entity in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>delete() (line 718 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

I need to be able to delete these host entities. They are still showing up in my entity list. I can edit and save them, I just cannot delete them.

How can I delete the host entities?

# Answer
Sorry for the late reply but your question is a bit confusing and I would like to clarify the mentioned issue (message). Did you use -\>setHostEntity($obj) at creation of the FieldCollection? I think that you created "ghost" fieldCollections. Have a look in DB if they was added there and you don't see the new FieldCollection at HostEntity in back end.

In my case, i was loading a FieldCollection Item which also did not have the HostEntity set and was struggling with the same Error Message (therefor the explanation). Later I figured out that the following procedure is correct - mention the saving of the HostEntity of the FieldCollection:

```
use Drupal\field_collection\Entity\FieldCollectionItem;

$fieldCollectionObj = FieldCollectionItem::load($fcId);
if($fieldCollectionObj->hasField('field_my_user_fc_field')) {
    $userObj = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $fieldCollectionObj->set('field_my_user_fc_field', 'my new value');
    $userObj->save();
}

```
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How do I find the role id from an og group role name?
I need to retrieve the rid to assign the 'student' role part of an **og group**.

I found this post in regards to ***user* roles** How do I find the role id from role name?

```
$rid = array_search('student', user_roles());
og_role_grant('node', $id, $user->uid, $rid);

```

Is there also a function for og group roles?

# Answer
Found a helpful solution using a db query https://www.hashbangcode.com/article/load-drupal-organic-group-role-name

```
$roleid = db_query("SELECT rid, name FROM og_role WHERE gid = :gid and name = :name ORDER BY rid",array(':gid' => 14, 'name' => 'student'))->fetchAssoc();

```

Let me know in case there is any other or better solution, thanks!
> 0 votes

---
Tags: organic-groups
---


# Question
Title: Why is Drupal Core not updating via composer?
We realized that our Drupal core version is outdated by two versions. We are currently running 8.5.3, but 8.5.5 has been released. Rather than updating directly two versions, we wanted to upgrade from 8.5.3 to 8.5.4 and then eventually from 8.5.4 to 8.5.5.

We tried the following but it didn't get updated.

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

```

Message after running composer command

> Nothing to install or update

I ran this command in the directory outside of docroot in `C:\users\name\Sites\mysite\` which has the following folders

1. .git
2. config
3. docroot
4. drush
5. hooks
6. vendor

I also ran `composer why-not drupal/core:8.5.4` and had the following message returned.

> There is no installed package depending on "drupal/core" in versions not matching 8.5.4

# Answer
> 5 votes
After running `composer why-not drupal/core:8.5.4` and doing some more research on the error message, I came across Upgrading from 8.5.0 to 8.5.1 using composer

This command did the trick for me.

```
composer require drupal/core:8.5.4  webflo/drupal-core-require-dev --update-with-dependencies

```

# Answer
> 1 votes
Look at your composer.json... do you see drupal/core listed under "require" or "replace"? Make sure you move it under "require"

---
Tags: 8, composer
---


# Question
Title: Save data to custom field columns using entity_metadata_wrapper
I have a simple custom module that creates a new field type. The field has multiple columns in the database; the idea is that a user (or code) will enter a single value, and then that value is converted into several different formats and saved to the database columns.

Currently, this is working by using a method from the book Drupal 7 Module Development, where the user's original value is converted using a widget validate function.

It works great when a human is filling out a form; but the problem is, when I try to create an entity in code, using entity\_metadata\_wrapper, there's no widget, and thus, no widget validate function runs.

It looks like I need to look at hook\_field\_info and specify a property\_type of 'struct' with a custom setter callback, but I can't find any documentation that describes how to use the property or getter/setter callbacks.

How can I use entity metadata wrappers with custom field database columns?

```
/**
 * Implements hook_field_info().
 */
function device_id_field_info() {
  return array(
    'device_id' => array(
      'label' => t('Device ID'),
      'description' => t('Converts the input device ID and saves it to the
        database in various formats.'),
      'default_widget' => 'device_id_simple',
      'default_formatter' => 'device_id_raw',
      'default_token_formatter' => 'device_id_combined',
      'property_type' => 'device_id',
      'property_callback' => array('_device_id_property_callback'),
      ),
  );
}

/**
 * Callback to alter the property info of device id fields.
 *
 * @see device_id_field_info().
 */
function _device_id_property_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $name = $field['field_name'];
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$name];

  $property['type'] = ($field['cardinality'] != 1) ? 'list<deviceid>' : 'deviceid';
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  $property['property info'] = device_id_property_info();

  unset($property['query callback']);
}

/**
 * Defines info for the properties of the device ID field data structure.
 */
function device_id_property_info($name = NULL) {
  // Build an array of basic property information for the device ID field.
  $properties = array(
    'raw_id' => array(
      'label' => t('Raw input ID'),
    ),
    'esn_hex' => array(
      'label' => t('Converted ESN in hexadecimal format'),
    ),
    'esn_dec' => array(
      'label' => t('Converted ESN in decimal format'),
    ),
    'meid_hex' => array(
      'label' => t('Converted MEID in hexadecimal format'),
    ),
    'meid_dec' => array(
      'label' => t('Converted MEID in decimal format'),
    ),
    'imei_hex' => array(
      'label' => t('Converted IMEI in hexadecimal format'),
    ),
    'imei_dec' => array(
      'label' => t('Converted IMEI in decimal format'),
    ),
    'iccid_hex' => array(
      'label' => t('Converted ICCID in hexadecimal format'),
    ),
    'iccid_dec' => array(
      'label' => t('Converted ICCID in decimal format'),
    ),
  );
}

/**
 * Implements hook_field_is_empty().
 *
 * Pseudo-hook.
 */
function device_id_field_is_empty($item, $field) {
  if ($field['type'] == 'device_id') {
    if (
      empty($item['raw_id']) &&
      empty($item['cap_dec']) &&
      empty($item['cap_hex']) &&
      empty($item['meid_dec']) &&
      empty($item['meid_hex']) &&
      empty($item['imei_dec']) &&
      empty($item['imei_hex']) &&
      empty($item['iccid_dec']) &&
      empty($item['iccid_hex'])) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Implements hook_field_widget_info().
 */
function device_id_field_widget_info() {
  return array(
    'device_id_simple' => array(
      'label' => t('Device ID text field'),
      'description' => t(
        'Allow the user to enter the device ID, and display it in
        whatever format it was entered'),
      'field types' => array('device_id'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
        ),
      ),
    );
}

/**
 * Implements hook_field_widget_form().
 *
 * Pseudo hook
 **/
function device_id_field_widget_form(
  &$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  switch ($instance['widget']['type'] == 'device_id_simple') {

    case 'device_id_simple':
      $element += array(
        '#element_validate' => array('_device_id_wrapper_validate'),
        'device_id_wrapper' => array(
          'input_id' => array(
            '#title' => t('Device ID'),
            '#type' => 'textfield',
            '#default_value' => isset($items[$delta]['raw_id']) ?
              $items[$delta]['raw_id'] : '',
          ),
        )
      );
    break;
  }
  return $element;
}

function _device_id_wrapper_validate($element, &$form_state) {
  //This function is also called when submitting the field
  //configuration form.  If so, skip validation since it
  //won't work anyway
  if ($form_state['complete form']['#form_id'] == 'field_ui_field_edit_form') {
    return;
  }

  $values = $form_state['values'];
  $language = $element['#language'];
  $field_name = $element['#field_name'];
  $item = $values[$field_name][$language][$element['#delta']]['device_id_wrapper'];

  foreach ($values[$field_name][$language] as $delta => $item) {
    if (is_array($item)) {
      if (array_key_exists('device_id_wrapper', $item)) {
        $conversion = new deviceIDConversion($item['device_id_wrapper']['input_id']);
        $conversion_values = $conversion->calculate();
        if ($conversion_values) {
          $new_values = array(
            'esn_hex' => isset($conversion_values['ESN_HEX']) ? $conversion_values['ESN_HEX'] : NULL,
            'esn_dec' => isset($conversion_values['ESN_DEC']) ? $conversion_values['ESN_DEC'] : NULL,
            'meid_hex' => isset($conversion_values['MEID_HEX']) ? $conversion_values['MEID_HEX'] : NULL,
            'meid_dec' => isset($conversion_values['MEID_DEC']) ? $conversion_values['MEID_DEC'] : NULL,
            'imei_hex' => isset($conversion_values['IMEI_HEX']) ? $conversion_values['IMEI_HEX'] : NULL,
            'imei_dec' => isset($conversion_values['IMEI_DEC']) ? $conversion_values['IMEI_DEC'] : NULL,
            'iccid_hex' => isset($conversion_values['ICCID_HEX']) ? $conversion_values['ICCID_HEX'] : NULL,
            'iccid_dec' => isset($conversion_values['ICCID_DEC']) ? $conversion_values['ICCID_DEC'] : NULL,
            'raw_id' => $item['device_id_wrapper']['input_id'],
            );
          form_set_value($element, $new_values, $form_state);
        } else {
          form_set_error($field_name, t('Your device ID doesn\'t match a valid format.  Check
            the device ID, verify it\'s correct, and type/scan it again.'));
        }
      }
    }
  }
}

/**
 * Implements hook_field_validate().
 *
 * Pseudo-hook.
 */
function device_id_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if (!empty($item['raw_id'])) {
      $conversion = new deviceIDConversion($item['raw_id']);
      $conversion_values = $conversion->calculate();
      if (!$conversion_values) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'device_id_invalid_format',
          'message' => t('Your device ID doesn\'t match a valid format.  Check
            the device ID, verify it\'s correct, and type/scan it again.'),
        );
      }
    }
  }
}

```

Here is some example code I'm using in a test page to work with this content; when I do entity\_load(), I can view the contents of the custom field, including the database columns I defined in hook\_info(). When I wrap this in entity\_metadata\_wrapper() and try setting the field value, nothing happens. Also, after wrapping, I can no longer see the field values, even with getPropertyInfo().

```
$ent = entity_load('node', array('2955'));
$new_ent = entity_metadata_wrapper('node', $ent['2955']);
$new_ent->field_device_id->meid_hex = 'a1000002747883';
$new_ent->save();
dsm($new_ent->getPropertyInfo());

```

# Answer
To access a field value from the wrapper try:

$new\_ent-\>field\_device\_id-\>meid\_hex-\>value();

or for the whole entity: $entity\_object = $new\_ent-\>value();
> 0 votes

# Answer
You can try the following:

```
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
//- Set Lang
$wrapper->language->set('en');
//- Set Title
$wrapper->title->set('test');
//- Set Body Value
$wrapper->body->set(array('value' => 'Some text', 'format' => 'full_html'));
//- Set Custom field
$wrapper->your_custom_field_name->set('field value');
$wrapper->save();

```
> 0 votes

---
Tags: entities
---


# Question
Title: Prevent page creation for a published custom content type
I have a Drupal 8 custom content type that is used in views only. I would like to prevent this type from creating a web page for content that is published.

# Answer
One easy method would be to add Rabbit Hole module and set it to "Page Not Found" when that content types view route is accessed.
> 1 votes

---
Tags: views, nodes, display-suite
---


title: How to let editors place custom forms?

text:
# Question
Title: How to let editors place custom forms?
I have a custom form:

```
\Drupal\module\Form\CustomForm

```

I want to be able to embed this form in a basic page by adding a shortcode/variable to the basic page such as:

```
[form][/form]

```

or

```
form

```

This is very easy to achieve in WordPress but really difficult in Drupal.

How can I achieve the above?

# Answer
As also WordPress is now moving towards modular content (codename Gutenberg) I'd advise you to do the same in Drupal with Paragraphs.

Then you can provide different paragraph types (image, text, CTA etc.), one of them could be a simple block reference (I don't remember if core already offers block reference fields or if you need Block field for that) with which you let editors choose blocks to be placed wherever they want. (Paragraphs also are resortable.)

So, you already have your form, cool. Next level is to let your custom module provide a block that outputs this form. Next, In your theme add a new region "Disabled" (that never gets printed anywhere) and place your block there. Now this block will be available to choose as block reference. (I guess it's desired behavior that only blocks that are assigned to a region can be referenced.)

Bonus would be a little bit of back-end JS to only display certain blocks in the block reference select list. But that's just bonus.
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Best theming practice for leanest possible code?
I am about to upgrade a website from Drupal 7 to Drupal 8 and with that, I am thinking to move away from Bootstrap to reduce page sizes. I am thinking to go three different routes with this one:

1. Use a smaller basetheme than bootstrap and build a subtheme. It will be easier for me to build. However, I am worried about having unnecessary code and increased page load times.
2. Build a theme from scratch. But my theming skills are not good and it will take so much time for me to come up with something good. But it has the advantage of being extremely small and page loads will be good I suppose.
3. Pick a drupal 8 theme that is closest to what I have in my mind and change it. However, I never realized how difficult it is to find a fluid full width simple clean small drupal 8 theme that is not dependent on a large basethemes.

What might be the best practice for theming, in someone who prefers to keep things as small as possible? How much of a difference will building from a basetheme cause to pageload times?

# Answer
I think the question is very broad but in general its always easier to finish a a project with a themebase that you are familiar with ... and the overhead of using bootstrap or any other themebase is not that great over a leaner theme.

Still if you know enough you can just load the boostrap javascript libraries that are needed and not all of them. Maybe bootstrap theme project already has an option but at least drupal core has ways to exclude .js or .css files that are not needed.

Also you have to consider the overhead of time it might take to create your own responsive solutions for common layout problems which bootstrap and other css frameworks have already implemented and have been tested by many people.

Perhaps you should test any other base themes from drupal.org and see which one feels more comfortable to extend based on your theming experience ... perhaps you can also try out bootstrap 4 base theme as a starting point which is probably a leaner themebase than bs3.
> 1 votes

# Answer
Take or build a theme that's based on Bourbon Neat. In contrast to Bootstrap it won't pollute your markup with a shipload of classes.

Basic (includes Neat 2.0) and Neato (includes Neat 1.0). But if I remember it right both have Drupal's "Classy" core theme as base theme. Which already provides quite an amount of predefined classes (as the name suggests). If you would like it even leaner you could start your own sub-theme of Drupal's "Stable" core theme.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Node ID is missing in contextual filters
The node ID is missing in the view contextual filters.

>

How can I use the node ID as contextual filter?

# Answer
In the screenshot you show, it's *Identifiant (ID)*, the third rown of the *Contenu* category (*Catégorie* in the screenshot).

Since the context filters have a category, the node ID is simply called *Identifier* or *ID*. There isn't any possibility to confuse it with other IDs, like the user ID, because other IDs have a different category. You cannot even confuse it with the revision ID (*Identifiant (ID) de révision*) or the UUID (*Identifiant universel unique (UUID)*).
> 0 votes

---
Tags: views, nodes
---


title: Migration sources files problem

text:
# Question
Title: Migration sources files problem
I am trying to migrate a drupal 6 to 8 through drupal migrate ui and i am getting a error with the sources files, drupal 8 is not able to read sites folders due is writting a double slash.

Does anyone why this happens?

> Source ID 3125: Cannot read from non-readable stream (http://dev.example.com/example//sites/default/files/)

The URL has an empty part in the path. I tried with full permissions in this folders, source in subdomain, domain, folder, etc.

# Answer
How are you providing the location of the files? IIRC, you can give it an absolute path ( /home/www/drupal ) or a URL ( http://www.example.com ).

In either case are you including a final '/'? If so, try removing it.
> 1 votes

---
Tags: 8, migrations
---


# Question
Title: Why don't all pages of content show up in the pagination beneath main content?
On a Drupal 7 site, I have several pages' worth of content, articles that are set to "published" and "promoted to front page". The page numbers underneath the main content part of the block show pages 1 through 5, and the "next \>" and "last \>\>" links. However they do not show pages 6 and beyond. Why not?

I can go to the content that's on pages 6 and beyond, by going directly to the node. I can even enter the URL manually for page 6 and it loads fine, so the articles are there, published, and promoted. However, the pagination does not show links for pages beyond 5. Clicking on the "last \>\>" link only goes to page 5. In the image below, you can see that I've manually opened the URL for page 6, which loads the content, yet the pagination only shows it on page 5 of 5.

Is there a setting somewhere to choose how many pages Drupal shows? Or is there some other issue?

Note: I'm using the default Drupal front page. I haven't configured a different view. Should this be necessary?

# Answer
This appears to be a bug in Drupal 7 or in some configuration. After migrating the site to Drupal 8, the full pages display correctly.
> 0 votes

---
Tags: 7, views, paging
---


# Question
Title: No welcome email sent when users register via profile2 registration path
I am using profile2 registration path for two different types of roles. The roles are auto-assigned when users register via one of the paths. I have used mail logger to check and the emails are not sent. Other types of emails are sent. I can block the new users then unblock them and registration emails are sent.

When a user is registered via the regular user registration (/user/register) an email is sent.

I am using Drupal core 7.59, profile2 7.x-1.4, profile2 registration path 7.x-1.13.

Any ideas about how to fix this?

# Answer
> 0 votes
This appears to be an issue with the profile2 module. I've created a patch for another issue and this, in turn, has fixed the no emails sent issue I was experiencing.

For a patch and proposed solution please see: https://www.drupal.org/project/profile2/issues/1993770#comment-12699962

---
Tags: users
---


# Question
Title: How to render only markup in region template?
I have created a `region--footer.html.twig` template which only contains the static markup for the footer. Now I would like to render this region at the bottom of each page so I have added the following to the end of `page.html.twig`:

```
{{ page.footer }}

```

This works fine as long as I have connected a block to the footer region under `admin/structure/block`. If no blocks are placed in the region it is regardes as empty and is not rendered. How can I change so the `region--footer.html.twig` is used even if there is no blocks placed in the region?

I was thinking of using a preprocess function for the region doing something like this:

```
function template_preprocess_region(&$variables) {
  if ($variables['region'] == 'footer') {
    $variables['content'] = 1;
  }
}

```

# Answer
```
/**
 * Implements hook_preprocess_page() for page.html.twig.
 */
 function hook_preprocess_page(array &$variables) {
   $variables['page']['footer'] = [     # Specify the region name
     '#theme_wrappers' => ['region'],
     '#region' => 'footer',             # Specify the region name
     'phantom_block' => [
       '#markup' => ' ',
       '#weight' => "-100",
     ],
   ];
 }

```

This way you are adding a block with a space to the region. Forcing Drupal to render that region. But as you will put a static HTML in that region, the content of the phantom block will not be rendered.
> 1 votes

---
Tags: 8, blocks, theming
---


title: How to get term by path or alias?

text:
# Question
Title: How to get term by path or alias?
I've seen this question posted many places, but no answers - or relevant answer. i.e. how to get term object or ID from path or alias e.g. /cat/subcat or /taxonomy/term/6??

# Answer
> 2 votes
I usually do something like this:

```
<?php

use Drupal\taxonomy\Entity\Term;

function hook_preprocess_page(&$vars) {
  $route = \Drupal::routeMatch();
  if ($route->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term_id = $route->getRawParameter('taxonomy_term');
    $term = Term::load($term_id);
  }
}

```

# Answer
> 1 votes
For each entity type you can use like here to get entity object:

`$term = \Drupal::request()->attributes->get('taxonomy_term');`

# Answer
> -1 votes
If you are using original path not URL alias then you can explode you path like that

```
$exp = explode('/','/taxonomy/term/6');
$tid = $exp[2];

```

Then you can load your term object using this tid as@Ronnie say.

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


title: Update manually installed modules

text:
# Question
Title: Update manually installed modules
I have installed Drupal Commerce 2 through composer as mentioned in

https://docs.drupalcommerce.org/commerce2/developer-guide/install-update/installation

after that, I have installed a few modules and a Barrio (Theme) directly through drupal admin interface.

Can I still update them through composer?

I have tried to update with `~/composer.phar update drupal/block_class --with-dependencies`, but I am getting the following output.

> DrupalProject\composer\ScriptHandler::checkComposerVersion Package "drupal/block\_class" listed for update is not installed. Ignoring.
> Loading composer repositor
> Updating dependencies (including require-dev)
> Nothing to install or update
> Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles

# Answer
> 0 votes
> Can I still update them through composer?

No, Composer can only manage packages that have been installed through Composer.

You could always add it to the `"require"` section of your existing composer.json (manually or by executing `composer require`), then Composer will know about it.

---
Tags: 8, commerce, composer
---


# Question
Title: How do I create a custom exposed filter?
I try to create a custom exposed filter in views 3 of Drupal 7

Where can I learn about how to create a custom exposed filter for Views 3 and D7?

Someone put some code example in the URL above, but it seems it is in views 2!? Does any one know how to make it in Views 3.

In the module:

```
/**
 * Implements hook_views_api().
 */
function modulename_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'modulename') . '/inc',
  );
}

/**
 * Implementation of hook_views_handlers() to register all of the basic handlers
 * views uses.
 */
function modulename_views_handlers() {
  return array(
    'info' => array(
      // path to handler files
      'path' => drupal_get_path('module', 'modulename') . '/inc',
    ),
    'handlers' => array(
      // register our custom filter, with the class/file name and parent class
      'modulename_handler_filter_filtername' => array(
        'parent' => 'views_handler_filter',
      ),
    ),
  );
}

function modulename_views_data() {
  $data = array();

  $data['node']['filtername'] = array(
    'group' => t('Custom'),
    'real field' => 'my_custom_filter_field',
    'title' => t('My custom filter'),
    'help' => t('Some more detailed description if you need it.'),
    'filter' => array(
      'handler' => 'modulename_handler_filter_filtername',
    ),
  );

  return $data;
}

```

In modulename\_handler\_filter\_filtername.inc

```
class modulename_handler_filter_filtername extends views_handler_filter {

  /**
   * Options form subform for setting exposed filter options.
   */
  function value_form(&$form, &$form_state) {
    parent::value_form($form, $form_state);

    // get list of years from database
    $query = db_select('node', 'n');
    $query->addExpression("FROM_UNIXTIME(n.created, '%Y')", 'year');
    if (isset($this->view->filter['type'])) {
      $query->condition('n.type', $this->view->filter['type']->value, 'IN');
    }
    $result = $query->orderBy('year', 'ASC')
      ->execute()
      ->fetchAllAssoc('year');

    $years = array(
      '0' => t('All'),
    );
    foreach ($result as $k => $v) {
      $years[$k] = $k;
    }

    // create form element with options retrieved from database
    $form['value']['year'] = array(
      '#type' => 'radios',
      '#options' => $years,
      '#default_value' => end($years),
    );
  }

  /**
   * Alters Views query when filter is used.
   */
  function query() {
    // make sure base table is included in the query
    $this->ensure_my_table();

    // retrieve real filter name from view options
    // this requires 'real field' filter option to be set (see code above)
    $real_field_name = $this->real_field;
    // get the value of the submitted filter
    $value = $this->view->exposed_data[$real_field_name];

    // finally, alter Views query
    if (is_numeric($value) && $value != 0) {
      /*
        Having several custom exposed filters, make sure subsitution patterns
        (e.g. :filtername_value below) don't match across different filters.
        I spent some time figuring out why all my filters had the same value.
        It looks like the query skeleton is built first and then all replacements
        are made in bulk. Prefixing value with filter name looks good imo.
      */
      $this->query->add_where_expression($this->options['group'],
        "FROM_UNIXTIME(node.created, '%Y') = :filtername_value",
        array(':filtername_value' => $value));
    }
  }
}

```

# Answer
> 12 votes
There's a module that provides some examples here: https://www.drupal.org/project/views\_plugin\_examples. It's limited but has an exposed filter example.

General discussion here: https://api.drupal.org/api/views/views.api.php/group/views\_plugins/7

In broad outline:

1. Create a custom module, with a subdirectory called "views"
2. In your .info file, add a line: `files[] = views/MODULE_handler_filter_FILTERNAME.inc` Your filter will never show up if you forget this!
3. In the .module file, add an implementation of hook\_views\_api():

```
function MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MODULE') . '/views',
  );
}

```
4. Within the views subdirectory, you will need to create two files, MODULE.views.inc and MODULE\_handler\_filter\_FILTERNAME.inc
5. In MODULE.views.inc, you will need to implement either:

hook\_views\_data\_alter() - for a new filter on an existing entity type that already has views integration, which is more common OR

hook\_views\_data() - to provide views integration for your custom entity, including filters.

API documentation is available for both functions.

A quick example:

```
    function MODULE_views_data_alter(&$data) {
       if ( isset($data['users']) && !isset($data['users']['FILTERNAME']) ) {
        $data['users']['FILTERNAME'] = array(
          'real field' => 'uid', // name of entity field to which filter applies
          'title' => t('HUMAN READABLE NAME OF FILTER'),
          'help' => t('HELP TEXT'),
          'filter' => array(
            'handler' => 'MODULE_handler_filter_FILTERNAME',
          ),
        );
      }
    }

```
6. All of the real work happens in MODULE\_handler\_filter\_FILTERNAME.inc. This file defines a new class that implements your filter, class MODULE\_handler\_filter\_FILTERNAME.

You will usually want to extend one of the existing views filter handler classes to get the benefit of existing code. Many of these can be found in subdirectories of the views module directory. The basic filters are in the "handlers" subdirectory, but many more complex filters may be found buried in subdirectories of the "modules" subdirectory. The views filter handlers you find there are the best documentation for how to implement a filter, as well as how to extend an existing filter, and you should read through them.

Normally your custom filter class will a) add fields to the extended filter's settings form, b) in the case of an exposed filter, modify the exposed widget, and then c) implement a query() method that does the real work, based on the saved settings and input from the exposed widget.

# Answer
> 0 votes
Ran into the same issue and figured it out, looks like the original op has the same problem.

Where you define your exposed filter form in value\_form(), the key you use in the array should be the same key used in view\_data (or views\_data\_alter).

e.g. in my case:

```
function value_form(&$form, &$form_state) {

  parent::value_form($form, $form_state);

  $form['users']['welcome_email_sent'] = array(
    '#type' => 'select',
    '#options' => array(
      0 => '- Any -',
      1 => 'Welcome Email',
      2 => 'Notification Email',

    ),
    '#title' => t('Email History'),
  );

  return $form;

}

```

And..

```
function ca_email_history_views_data_alter(&$data) {

  $data['users']['welcome_email_sent'] = array(
    'title' => t('Welcome email sent'),
    'help' => t('Filter based on e-mails the user has received'),
    'filter' => array(
      'handler' => 'ca_email_history_welcome_email_sent_handler',
    ),
  );

  return $data;

}

```

Notice how both have the key as 'welcome\_email\_sent', if I change them so they no longer match the issue where the query() function is never called occurs again.

---
Tags: 7, views
---


title: composer install error

text:
# Question
Title: composer install error
I can't install anything because of this error:

> \[RuntimeException\] Could not scan for classes inside "/app/vendor/symfony/serializer/src/" which does not appear to be a file nor a folder

and subsequently:

> Could not scan for classes inside "/app/vendor/symfony/yaml/src/" which does not appear to be a file nor a folder

I navigated to that directory and the src folder is indeed missing...

I'm using Lando and switch the PHP to 7.1. I tried deleting the vendor directory and rerunning `lando composer update` and `lando composer install` but get the same errors.

# Answer
Could be and over lap of composer requests. This example is for Pantheon resipe but it may help https://github.com/lando/lando/issues/340
> 0 votes

---
Tags: 8, composer
---


# Question
Title: How to change search_api_server options via CLI
I'm using drupalvm to create my local dev environment, and am writing scripts to automate importing an existing site's db and changing other settings so that it's more like our actual server-hosted sites.

Drupalvm creates a Solr server at /solr/collection1 and uses HTTP, whereas the existing site looks for a Solr server at /solr/live and uses HTTPS. When the db is imported, the local site is looking in the wrong place for the Solr server.

I'd like to check the feasibility of adding another .sh script that changes the db entry for search\_api\_server so that it uses http and /solr/collection1.

I tried using a sql command to update/set the new value for search\_api\_server 'options', and it does successfully change the scheme to HTTP but doesn't change the path. Also, when I load the site's search api server admin page, the options seem to be completely empty at first and you have to edit and save them again for it to stick.

P.s. I am also currently testing changing drupalvm's default Solr server so that it uses /solr/live and https, but having some issues with the https part.

# Answer
> 1 votes
This problem was probably specific to Drupal-VM, but here's how I solved it. Rather than write a post-provision script that tried to run the sql command itself, I made a new file containing the sql command and told the post-provision script to use that file.

So instead of the script running this itself

`sudo mysql -u root -proot drupal -e "UPDATE search_api_server SET options = 'a:14:{s:9:"clean_ids";b:1;s:9:"site_hash";b:1;s:6:"scheme";s:4:"http";s:4:"host";s:9:"localhost";s:4:"port";s:4:"8983";s:4:"path";s:17:"/solr/collection1";s:9:"http_user";s:0:"";s:9:"http_pass";s:0:"";s:7:"excerpt";i:0;s:13:"retrieve_data";i:0;s:14:"highlight_data";i:0;s:17:"skip_schema_check";i:0;s:12:"solr_version";s:0:"";s:11:"http_method";s:4:"AUTO";}' WHERE id='1'";`

It now does this

`sudo mysql -u root -proot drupal < $SEARCH_API_SERVER_SETUP_SQL_COMMAND_FILE`

(Replace -u root -proot drupal with your sql username, password, and the site db)

---
Tags: 7, database, drush, search
---


# Question
Title: How to search for complete SKU like "K-00019" (without splitting it at "-" and without removing leading zeros)
I am using Search API to search commerce products by SKU. But when I enter "K-00019" as search string, every item is retrieved that contains "19". I investigated why this happens and found, that a method called "prepareKeys" splits the string K-00019 into two parts: K and 00019, then ignores the first part (letter K) and transforms the second part to 19 because of leading zeroes. As you can mention, this behaviour leads to way too much results. I need a search that allows to search for the complete sku. Do you have an idea how I can accomplish this? I do not have to necessary use Search API, if you have another suggestion, it would be perfectly fine, even a workaround would be okay.

# Answer
> 1 votes
I made a workaround: I added a computed field to the product type , copying the SKU, removing the dash/hyphen and saving this value. Instead of including the real SKU in the index, I included this stripped version. At the form part, I added a validation function that removes dashes/hypens from the search input automatically. Just for sake of documentation:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['#validate'][] = 'sku_search_validate';
  }

function sku_search_validate($form, &$form_state) {
  if (isset($form_state['values']['my_sku']) && !empty($form_state['values']['my_sku'])) {
    $new_value = str_replace('-', '', $form_state['values']['my_sku']);
    $form['my_sku']['#parents'] = array('my_sku');
    form_set_value($form['my_sku'], $new_value, $form_state);
  }
}

```

---
Tags: 7, commerce, search
---


title: Rule to deselect checkbox item?

text:
# Question
Title: Rule to deselect checkbox item?
I have a mailchimp subscription content type that add a user to the email list in mailchimp. It works great and adds them to the list.

However, I want deselect that checkbox when they fill out a second content type with a rule.

So, on creation of content type unsubscribe, check mailchimp list and remove email from list.

I have been search for ideas everywhere and cannot find anything in a tutorial or in Drupal Stack Exchange. Looking for ideas to try and hopefully figure out. Thanks!

# Answer
if you wont find any other solution without coding to deselect that checkbox you can try to do it via your custom module (if you don't have any you will have to make one - that's different story).

```
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id){
  $form['field_order_details']['und']['0']['value']['#resizable'] = FALSE;
}

```

Something similar should work for your checkbox.

See `hook_form_alter()`.
> 0 votes

# Answer
For what its worth here is what I did...After the first content type gets submitted the emails subscribe to that Mailchimp list. When you create the second content type you use the same fields for the Mailchimp submission. In the settings for that field under 'Merge Fields', the field you match with needs to be exact. Be careful if you have many selections of the same name. That is what got me. When the second content type gets submitted it inherits the state of the first field and default. Selected. So, I created a Rule to unselect that field on the second content type and that removes is from the list. Wasted too many hours but that simple. Good Luck!
> 0 votes

---
Tags: rules, emails
---


title: Video Embed Field with Magnific Popup

text:
# Question
Title: Video Embed Field with Magnific Popup
I'm trying to display an embedded video in a popup window using the Magnific Popup Module. For the video field, I'm using Video Embed Field.The popup window works with images trouble-free. However when I try to set up the display with the video field (Magnific Popup formatter), the throbber keeps turning and I'm not able to save this configuration. Any ideas on that?

# Answer
I have the same issue. the problem was in the module:

> Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "colorbox.attachment";.

The module mantainer do not add colorbox to dependencies.

So you just to need to install and enable Colorbox module.
> 1 votes

---
Tags: 8, entities, media
---


# Question
Title: How do I programmatically create a route?
I'm trying to create a route programmatically using this code.

### example.routing.yml

```
route_callbacks:
    - '\Drupal\example\Routing\ExampleRoutes::routes'

```

### Drupal\example\Routing\ExampleRoutes.php

```
namespace Drupal\example\Routing;

use Symfony\Component\Routing\Route;

class ExampleRoutes {
    public function routes() {
        $routes = array();
        $routes['example.settings'] = new Route(
            '/example/',
            array(
              '_form' => '\Drupal\example\Form\ExampleForm',
            ),
            array(
              '_permission'  => 'access content',
            )
        );

        return $routes;
    }

}

```

When I install the module, I get the following error

> Class \Drupal\example\Routing\ExampleRoutes does not exist

Why doesn't the above code work?

# Answer
I think that in your case the problem is in this line:

```
    '/example/',

```

that should be:

```
    '/example',

```

so without the final `/`.

You can try with the other method extending from `RouteSubscriberBase` and your routes method needs to receive as a parameter a `RouteCollection`.

```
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class ExampleRoutes extends RouteSubscriberBase {

  public function routes(RouteCollection $collection) {

  }

}

```

And you need to define the Route Subscriber as a service

```
  example.route_subscriber:
    class: Drupal\example\Routing\ExampleRoutes
    tags:     - { name: event_subscriber }

```

Take a look at this example:

Dynamic Routes in Drupal 8 with a RouteSubscriber
> 3 votes

# Answer
Try the following example it works for me.

**example.routing.yml**

```
route_callbacks:
  - '\Drupal\example\Routing\ExampleRoutes::routes'

```

**src/Routing/ExampleRoutes.php**

```
namespace Drupal\example\Routing;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class ExampleRoutes{

  public function routes(){
    $route_collection = new RouteCollection();
    $route            = new Route(
    // Path to attach this route to:
      'example',
      // Route defaults:
      [
        '_form' => 'Drupal\example\Form\ExampleForm',
      ],
      // Route requirements:
      [
        '_permission' => 'access content',
      ]
    );
    $route_collection->add('example.settings', $route);
    return $route_collection;
  }

}

```

Note that path param 'example' shouldn't have any '/' .
> 1 votes

---
Tags: 8, routes
---