# Question
Title: Cannot create custom config entity fails because ID is blank
I have created the following custom config entity. When I try to create a new one, I get the following error:

```
Drupal\Core\Entity\EntityMalformedException: The entity does not have an ID. in Drupal\Core\Config\Entity\ConfigEntityStorage->save() (line 248 of core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php).
Drupal\Core\Entity\Entity->save() (Line: 637)
Drupal\Core\Config\Entity\ConfigEntityBase->save() (Line: 151)

```

My understanding is that the entity system will create an ID for this entity, but it doesn't seem to be working in my case. I'm struggling to figure out what I need to change to get this work:

```
<?php

namespace Drupal\example\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\example\Entity\ExampleConfigInterface;

/**
 * Defines the ExampleConfig entity.
 *
 * ExampleConfig config entities define a configuration for a specific
 * entity/bundle. Per entity settings are then saved as ExampleContent
 * entities.
 *
 * @ConfigEntityType(
 *   id = "example_config",
 *   label = @Translation("Example configuration"),
 *   fieldable = FALSE,
 *   handlers = {
 *     "list_builder" = "Drupal\example\ExampleConfigListBuilder",
 *     "form" = {
 *       "add" = "Drupal\example\Form\ExampleConfigForm",
 *       "edit" = "Drupal\example\Form\ExampleConfigForm",
 *       "delete" = "Drupal\example\Form\ExampleDeleteForm",
 *     }
 *   },
 *   config_prefix = "example",
 *   admin_permission = "administer site configuration",
 *   entity_keys = {
 *     "id" = "id",
 *     "example_entity_type" = "example_entity_type",
 *     "example_bundle" = "example_bundle",
 *   },
 *   links = {
 *     "edit-form" = "/admin/config/content/example/{example_config}",
 *     "delete-form" = "/admin/config/content/example/{example_config}/delete",
 *   }
 * )
 */
class ExampleConfig extends ConfigEntityBase implements ExampleConfigInterface {

  /**
   * The ID of the block.
   *
   * @var string
   */
  protected $id;

  protected $exampleEntityType;
  protected $exampleBundle;
  protected $exampleExpiry;
  protected $exampleDefaultStatus;

  /**
   * Get the bundle
   */
  public function getExampleBundle() {
    return $this->exampleBundle;
  }

  /**
   * Get the entity type.
   */
  public function getExampleEntityType() {
    return $this->exampleEntityType;
  }

  /**
   * Get the expiry time for this configuration.
   */
  public function getExampleExpiry() {
    if (!$this->exampleExpiry) {
      return example_expiry_default();
    }
    return $this->exampleExpiry;
  }

  /**
   * Get status for this configuration.
   */
  public function getExampleStatus() {
    return $this->exampleDefaultStatus;
  }

}

```

I have ended up prefixing all the custom properties to try to make sure I wasn't overriding something on accident. Even when the custom entity is blank, it still won't add.

# Answer
> My understanding is that the entity system will create an ID for this entity, but it doesn't seem to be working in my case. I'm struggling to figure out what I need to change to get this work:

That understanding is wrong. Config entities have machine names as ID's, you have to provide that. Most UI's generate one from the label, but that's form/UI code, the API has no such thing.
> 3 votes

# Answer
Yes, Berdir is right.

While creating new entity programatically, need to provide **ID\[machine name of entity\]**.

You can pass any random unique string to id or time.

E.g:

```
$entity = example_config::create(
               [
                 'label' => 'Example Entity',
                 'id' => time(),
                 'status' => true,
                 'created' => time()
               ]
         );
 $entity->save();

```
> 1 votes

---
Tags: 8, entities
---


title: Display Suite Fields not showing

text:
# Question
Title: Display Suite Fields not showing
I created a bootstrap sub theme and and have enabled display suite. I have enabled ds extra fields and chose a layout for my content type for full view display. When going to the full view page of my content none of the ds fields are showing.

I have enabled title, author, post date, submitted by but none of these are showing. Is there something special you must do to get ds to work on a subtheme?

# Answer
> 0 votes
Which version of Drupal are you using? If 8.3 you may wanna update to DS 8.x-3.0-beta3 which no longer requires the layout plugin module, instead uses "Layout Discovery" in core.

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

---
Tags: 8, display-suite
---


title: Opposite result views with comparison

text:
# Question
Title: Opposite result views with comparison
I'm trying to achieve this...

A Views that shows as result the names of people who do not appear in list of published nodes of a content type. (List of people who will not attend an event...)

Configuration:

Content Type Event: Person field, supports adding more than one (multivalue), using autocomplete. This field is of the entity reference type and displays the list of possible names obtained from the result of a view.

Assuming that the list of persons is total A B C and D.

I create 1 node of event type And I included people A and B.

The result of the views should be... People C and D.

Is this achievable?

# Answer
> 0 votes
Previous setup: Create a new computed field for the content type where you want to work: Extract the names from the multivalue field (entity referenced field)

```
foreach ($entity->field_campos as $field) {
}
foreach ($entity->field_campos as $field) {
}
foreach ($field as $index => $valores) {
$terminos[] = $valores['value'];
}
$item2 = field_collection_item_load_multiple($terminos, $reset = FALSE);

$referenced_titles = array();
foreach ($item2 as $indice => $values) {
  $referenced_node = node_load($values->field_nombre_2['und'][0]['target_id']);
$entity_field[]['value'] = $referenced_node->title;
}

```

Now that every node from this content type has a special field for extracting the values in a more "flat" way we can compare two views. The first with the name list (usually partial) and the second, a views containing the full name list.

```
<?php
$result = views_get_view_result('calendari_intern', 'nombres');
$result2 = views_get_view_result('nom_expedients', 'entityreference_1');

```

First load both arrays. The first one, is the view result with partial name list. The second, is the view of the full name list.

Extract and create a new array saving only the names from the arrays:

```
foreach ($result2 as $index => $val) {
$expedient[] = $val->node_title;
}

```

Do the same in the other one:

```
foreach ($result as $index => $values) {
$entidades[] = $values->_field_data[nid][entity];
}
foreach ($entidades as $indice => $valores) {
if ($valores->field_nombres[und] !=NULL)
$casi[] = $valores->field_nombres[und];
}
foreach ($casi as $indice2 => $valores2) {
 foreach ($valores2 as $indice3 => $valores3) {
if ($valores3["value"] != NULL) {
$misnombres[] = $valores3["value"];
}
}
}

```

Then compare the arrays with array\_diff function.

```
$diferencia = array_diff($expedient, $misnombres);
echo '<pre>';
print_r ($diferencia);
echo  '</pre>';
?>

```

---
Tags: views
---


# Question
Title: Drupal 8.3.1 CSS and JS aggregated by default
I just installed Drupal 8.3.1 and created my own theme. I have both 'Aggregate CSS files' and 'Aggregate JavaScript files' unchecked. Also, in my settings.local.php I have:

```
/**
* Disable CSS and JS aggregation.
*/
$config['system.performance']['css']['preprocess'] = TRUE;
$config['system.performance']['js']['preprocess'] = TRUE;

```

Yet, Instead of having all the css style sheets in head and all the JS files at the bottom of the page, I have 4 aggregated style sheets in head and one aggregated js file at the bottom of the page.

Any idea what is causing that?

# Answer
If you want to disable aggregation, you need to set these variables to 'FALSE' instead of 'TRUE'.

If you are interested in disabling cache for development purposes, you can find more information in the following response: https://drupal.stackexchange.com/a/183397/27068
> 3 votes

---
Tags: 8
---


title: Get view result depending on pager url

text:
# Question
Title: Get view result depending on pager url
In drupal 7 ,this returns the results of the view first page, if using a pager: Is there a way to get the results depending on the page? (depending on url argument maybe?)

```
$result = views_get_view_result('viewname', 'displayname');

```

# Answer
> 2 votes
I didn't test the code. But you can use this code.

```
$page = 1;
$view = views_get_view('payment_schedule_students');
$view->set_display('payment_schedule_students_select');
$view->set_current_page($page);
$view->execute();$view->result;

```

Where you can set the `$page` variable from the url.

---
Tags: 7, views
---


title: How to alter the Views UI config form

text:
# Question
Title: How to alter the Views UI config form
Part 1: How do I add a form element (ie checkbox) to the field of a specific type (ie all image fields) inside the admin Views UI. What code do I need include in a custom module.

Part 2: How do I save it to the database.

This is not a default view.
I am not creating a need field. I am trying to alter an existing field.

# Answer
> 1 votes
Was able to solve this problem with 2 functions:

* `hook_field_formatter_info_alter()`
* `hook_form_FORM_ID_alter()` where FORM\_ID = views\_ui\_config\_item\_form

`hook_field_formatter_info_alter()` lets you set the default value.

The value itself gets save to the view/database. There is no extra code you need to write for this to happen.

Below is an example that went into MYMODULE.module file (MYMODULE = image\_field\_caption).

```
/**
 * Implements hook_field_formatter_info_alter().
 */
function image_field_caption_field_formatter_info_alter(&$info) {
  // Add a caption visible setting to image field.
  $info['image']['settings'] += array(
    'caption_visible' => TRUE,
  );
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Altering formatter settings for field handlers in Views.
 * TODO: Drupal 8 change to hook_field_formatter_settings_form_alter().
 */
function image_field_caption_form_views_ui_config_item_form_alter(&$form, &$form_state) {
  // Get the views handler.
  $handler = $form_state['handler'];

  // Check to see if the field is an image type.
  if (isset($handler->field_info['type']) && $handler->field_info['type'] == 'image') {
    $form['options']['settings']['caption_visible'] = array(
      '#title' => t('Include Caption'),
      '#type' => 'checkbox',
      '#default_value' => $handler->instance['display']['_custom']['settings']['caption_visible'],
      '#description' => t('By default, the caption is attached to the image in the view.'),
    );
  }
}

```

Another alternative for Drupal 7 is to use the Field Formatter Settings API module. This module add the `hook_field_formatter_settings_form_alter()` hook which you can use.

For Drupal 8 `hook_field_formatter_settings_form_alter()` is now part of core see field\_ui.api.php API documentation.

# Answer
> 1 votes
You need to use Views handlers https://api.drupal.org/api/views/views.api.php/group/views\_handlers/7.

Basically, you need to extend the handler class that is used by that field which in your case is field\_image.

In order to start and make your custom handler work you need two basic functions to tell Views you mean some business with them. These are hook\_views\_api() and hook\_views\_data\_alter() function.

MODULE.module

```
/**
 * Implements hook_views_api().
 */
function uc_addons_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'uc_addons') . '/views',
  );
}

```

MODULE.views.inc

```
/**
 * Implements hook_views_data_alter().
 */
function uc_addons_views_data_alter(&$data) {
  dsm($data);
}

```

The hook\_views\_data\_alter() function needs to be inside your MODULE.views.inc file.

Lastly of course is your handler w/c adds your field by extending the base handler as you can get more idea from the link. Also from my experience, the saving of values from fields are taken care by Views already.

# Answer
> 1 votes
**Drupal 8** example: how to add a new custom setting in the Views UI config form.

This example adds new option to the Ajax settings by checking the `use_ajax` option, but you can change it to anything you like.

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

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_views_ui_edit_display_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (!empty($form['options']['use_ajax'])) {
    /** @var \Drupal\views\Entity\View $view */
    $view = $form_state->getStorage()['view'];
    $display = $view->getExecutable()->getDisplay();
    $form['options']['mymodule_option'] = [
      '#type' => 'checkbox',
      '#title' => t('Use mymodule_option'),
      '#default_value' => !empty($display->display['display_options']['mymodule_option']),
    ];

    array_unshift($form['actions']['submit']['#submit'], '_MYMODULE_form_views_ui_edit_display_submit');
  }
}

/**
 * Form submit callback for views_ui_edit_display.
 */
function _MYMODULE_form_views_ui_edit_display_submit(&$form, FormStateInterface $form_state) {
  /** @var \Drupal\views\Entity\View $view */
  $view = $form_state->getStorage()['view'];
  $display = $view->getExecutable()->getDisplay();
  $display->display['display_options']['mymodule_option'] = $form_state->getValue('mymodule_option');
}

```

---
Tags: views
---


title: Redirect node form to view after submit

text:
# Question
Title: Redirect node form to view after submit
I have a view for a Drupal 8 site that uses 'work' as its path. I want to redirect user to this path right after the node has been submitted.

Form alter seems to be the right solution as it was in Drupal 7, but it's more complicated then it was before. In Drupal 7 we just used a direct path and redirect took place; now we need to provide a route name which isn't that obvious anymore. How do we find proper route name value? It's different for nodes, views, custom paths etc.

What I should use as argument for `$form_state->setRedirect('')`? How do I find what route name I should use in different cases?

```
function work_form_alter(&$form, \Drupal\Core\Form\FormStateInterface\FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'node_work_form':
      $form['actions']['submit']['#submit'][] = 'work_redirect';
      break;
  }
}

function work_redirect($form, FormStateInterface $form_state) {
  // Set redirect to some path.
  $form_state->setRedirect(''); // What should I provide here as an argument/arguments
}

```

# Answer
> 4 votes
For Views, the route pattern is `view.(view_id).(display_id)`.

For instance, if I have a view called Articles, and a display that I named "All", it would be:

```
$form_state->setRedirect('view.articles.all');

```

If you don't rename your display ids (I usually do), it is probably `page_1` or something of that nature.

Beyond that it's similar to how it was before. Here is a redirect with query string args attached:

```
$form_state->setRedirect('view.articles.all', ['keywords' => $form_state->getValue('keywords')]);

```

# Answer
> 2 votes
Instead of setRedirect($route\_name) we can use setRedirectUrl(Url $url) method which requires only the url.

To use this method you need use this namespace at the top of the page:

```
use Drupal\Core\Url;

```

Redirect function would look like this:

```
function work_redirect($form, FormStateInterface $form_state) {
  // Path needs to start with / or # or ?
  $redirect_path = "/work";
  $url = url::fromUserInput($redirect_path);
  $form_state->setRedirectUrl($url);
}

```

---
Tags: 8, forms, redirection
---


# Question
Title: Form API multiple select drop downs in a paragraph
I am trying to recreate the following paragraph in a custom Drupal form.

>

How do you create multiple selects in a single paragraph?

# Answer
> 1 votes
You can try a combination of wrapping the whole form in a div, so:

```
form['#prefix]='<div class="form-wrapper">';
  $form['markup1'] = array(
    '#type' => 'markup',
    '#markup' => 'Hello this is a pulldown '
  );
  $form['pulldown1'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => array('option1', 'option2', 'option3'),
  );
  $form['markup2'] = array(
    '#type' => 'markup',
    '#markup' => ' and this is another pulldown '
  );
  $form['pulldown2'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => array('option4', 'option5', 'option6')
  );
form['#suffix]='</div>';

```

then use theme\_form\_element to remove the field wrapper divs that Drupal injects automatically around each field, see this post. Once these individual divs around each pulldown are removed then the pulldowns will render inline with the markup.

---
Tags: 7, forms
---


# Question
Title: AddThis Icons Being Blocked on SSL/HTTPS Site
I've installed and configured the AddThis module to show sharing buttons to my users. It works great on my local machine. When I put the site on my SSL/HTTPS enabled site however the buttons do not show up (although I see the they are in in the page inspector) and Chrome gives me JavaScript errors that the script being used to get those icons is calling from http://s7.addthis.com/js/300/addthis\_widget.js...a not-secure link and is being blocked).

Does anyone know how to change the link the addthis module is calling to make it SSL/HTTPS compatible?

# Answer
> 1 votes
I ended up contacting AddThis and they told me the Drupal module is outdated, and to instead use this code:

```
    <script type="text/javascript"
src="https://s7.addthis.com/js/300/addthis_widget.js"></script>
    <div class="addthis_toolbox addthis_default_style addthis_32x32_style
">
    <a class="addthis_button_facebook"></a>
    <a class="addthis_button_twitter"></a>
    <a class="addthis_button_email"></a>
    <a class="addthis_button_pinterest_share"></a>
    <a class="addthis_button_compact"></a>
    <a class="addthis_counter addthis_bubble_style"></a>
    </div>

```

So I put the first line (the tag) in my html.tpl.php file and put the rest of the code in a block in my footer. I had to make sure to put all the tags on the same line otherwise Drupal was forcing
tags between them making it impossible to style the toolbox correctly. Making sure the block content was set to 'Full HTML' and I was good to go.

The negative of this approach is that it requires another call to an external script. The positive is it negates the need for another module - you can safely remove 'addthis'.

# Answer
> 1 votes
/admin/config/user-interface/addthis/advanced Service URL's and you can put https instead of http and problem is fixed!

# Answer
> 0 votes
Use secure pages module and make this **Switch back to http pages when there are no matches** option checked on below config page.

sitename/admin/config/system/securepages

---
Tags: ssl
---


# Question
Title: How do I alter the order used to load JavaScript files?
I created a libraries.yml file with the following content.

```
highcharts:
  css:
    theme:
      highcharts/css/highcharts.css: {}
  js:
    highcharts/highcharts.js: {weight: -400}
    highcharts/modules/exporting.js: {weight: -29}
    highcharts/modules/data.js: {weight: -28}
    highcharts/modules/drilldown.js: {weight: -27}
    js/hc.js: {weight: -1}
  dependencies:
    - core/drupal
    - core/jquery

```

*hc.js* is my custom JavaScript file content. I set its weight to -1 to make it the last used file, but after clearing the cache and refreshing the page, I still JavaScript error because the order used to load the JavaScript files. (hc.js is loaded before highcharts.js).

Do I need to change the content of the libraries.yml file?

# Answer
> 1 votes
I'd set it up like this:

```
highcharts:
  css:
    theme:
      highcharts/css/highcharts.css: {}
  js:
    highcharts/highcharts.js: {weight: -400}
    highcharts/modules/exporting.js: {weight: -29}
    highcharts/modules/data.js: {weight: -28}
    highcharts/modules/drilldown.js: {weight: -27}
  dependencies:
    - core/drupal
    - core/jquery

charts:
  js:
    js/hc.js: {}
  dependencies:
  - mymodule/highcharts

```

Then add the library mymodule/charts.

---
Tags: javascript
---


title: a href links not showing url aliases

text:
# Question
Title: a href links not showing url aliases
I am using redirect module with Drupal 8 latest version. It is working fine when we open any node in url, it converts node to the path alias. But issue is with a href links. **When we hover on any "a" link it is showing the node number not the path alias** set for that node. After click on it is displaying again path alias in the url bar.

How we can display the alias on hovering any "a" href link ?

# Answer
You can try Linkit. This will allow you to select internal links inside CKEditor and will convert them to aliases.

> Linkit provides an easy interface for internal and external linking with wysiwyg editors by using an autocomplete field. Linkit has by default support for nodes, users, taxonomy terms, files, comments and basic support for all types of entities that defines a canonical link template.
> 1 votes

---
Tags: path-aliases, redirection
---


# Question
Title: Unable to manually install the http_proxy module
We are behind a corporate firewall, so the first thing I do with new Drupal 7 is to manually download, unzip, & use Drush to enable the http\_proxy module ($ drush en http\_proxy.) Once that is configured, I can then run cron, do drush dl xxxx modules etc. without firewall issues.

For my first Drupal 8 venture, I updated to Drush 8.1.10; downloaded the Drupal 8 gzip file from the http\_proxy project, then copied & unzipped the file to /modules/contrib/http\_proxy/ \> on my server.

When I try to enable the http\_proxy contrib module, I get the following loop -- never get the module enabled.

Is there some special trick with Drupal 8 for manual module installation?

```
$ pwd
/apps/drupal-sites/TEMS/modules/contrib

$ cls
[drupal@drupaldev1 contrib]$ drush --version
Drush Version   :  8.1.10

$ pwd
/apps/drupal-sites/TEMS/modules/contrib
$ ll -R
.:
total 4
drwxrwxr-x 2 drupal 4096 Nov 17  2012 http_proxy/

./http_proxy:
total 36
-rw-rw-r-- 1 drupal  2446 Nov 17  2012 http_proxy.admin.inc
-rw-rw-r-- 1 drupal   308 Nov 17  2012 http_proxy.info
-rw-rw-r-- 1 drupal  2015 Nov 17  2012 http_proxy.module
-rw-rw-r-- 1 drupal 18092 Sep 17  2011 LICENSE.txt
-rw-rw-r-- 1 drupal   735 Nov 17  2012 README.txt

$
$ drush en http_proxy
http_proxy was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                  [ok]
http_proxy
Would you like to download them? (y/n): y
Install location /apps/drupal-sites/TEMS//modules/contrib/http_proxy     already exists. Do you want to overwrite it? (y/n): n
Skip installation of http_proxy to /apps/drupal-    sites/TEMS//modules/contrib/http_proxy.                         [warning]
http_proxy was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                  [ok]
http_proxy
Would you like to download them? (y/n): y
Install location /apps/drupal-sites/TEMS//modules/contrib/http_proxy     already exists. Do you want to overwrite it? (y/n): y
Project http_proxy (8.x-1.0) downloaded to /apps/drupal-    sites/TEMS//modules/contrib/http_proxy.                 [success]
Project http_proxy contains 0 modules: .
http_proxy was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                  [ok]
http_proxy
Would you like to download them? (y/n): y
Install location /apps/drupal-sites/TEMS//modules/contrib/http_proxy     already exists. Do you want to overwrite it? (y/n): y
Project http_proxy (8.x-1.0) downloaded to /apps/drupal-    sites/TEMS//modules/contrib/http_proxy.                 [success]
Project http_proxy contains 0 modules: .
http_proxy was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                  [ok]
http_proxy
Would you like to download them? (y/n): n

```

# Answer
> 0 votes
Looking at the files for the 8.x-1-x branch, I noticed that those files are essentially the files for Drupal 7, not Drupal 8. Even the https://ftp.drupal.org/files/projects/http\_proxy-8.x-1.0.tar.gz archive contains file for Drupal 7.

One of the differences between the versions for Drupal 7 and Drupal 8 is that for Drupal 8 the http\_proxy.info file should be replaced from a http\_proxy.info.yml file.
Since Drush uses the content of that file to understand if the directory contains a module, and to retrieve the information about that module, without any .info.yml file with the information about the http\_proxy module Drush is not able to find it in the already downloaded modules. That is why it keeps saying it doesn't find it.

So, to answer your question: No, you don't need any particular trick to download and install modules on Drupal 8. It just happens the module has not been really ported to Drupal 8, and Drush gets confused.

---
Tags: drush
---


# Question
Title: How to hide custom fields on the menu item form?
I've added two new fields to the menu item form (admin/structure/menu/item/{ID}/edit):

```
function modulename_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  $fields = [];

  if($entity_type->id() == 'menu_link_content') {
    $fields['show_mobile'] = \Drupal\Core\Field\BaseFieldDefinition::create('boolean')
      ->setLabel(t('Show in mobile menu bar.'))
      ->setDescription(t('Toggles the display of the menu item in the menu bar at the bottom of pages in mobile view.'))
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'weight' => '0',
        'settings' => [
          'display_label' => TRUE,
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['svg_icon'] = \Drupal\Core\Field\BaseFieldDefinition::create('string')
      ->setLabel(t('Mobile Menu Bar SVG Icon'))
      ->setDescription(t('Select the icon you want the menu item to use in the mobile menu bar.'))
      ->setDisplayOptions('form', [
        'type' => 'string',
        'weight' => '0',
        'settings' => [
          'display_label' => TRUE,
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);
  }

  return $fields;
}

```

But now I run into the issue, that I only need these fields for the main navigation menu, and thus want to remove or hide these on all other menu item forms.

Preferably I would like to keep it all to the module that adds the fields, and not have to create a custom admin theme just to visually hide them.

What should I look at to figure this one out? I've tried googling a lot of different combinations of the question, but have yet to find anything that remotely looks like a solution.

Many thanks in advance to anyone who can point me in the right direction.

# Answer
> 1 votes
`hook_entity_base_field_info` will add fields to the entire *entity*. If you want to hide the fields in specific *forms*, you will have to use a form alter to hide the fields. The following code might be what you are looking for.

```
/**
 * Implement hook_form_FORM_ID_alter();
 */
function modulename_form_menu_link_content_menu_link_content_form_alter(&$form, FormStateInterface $form_state) {
  $name = $form_state->getFormObject()->getEntity()->getMenuName();
  if ($name !== 'my-menu') {
    $form['show_mobile']['#access'] = FALSE;
    $form['svg_icon']['#access'] = FALSE;
  }
}

```

Change `my-menu` with the menu machine name of the only menu that you want the fields to appear on.

---
Tags: 8, entities, navigation
---


# Question
Title: How to switch back and logout of masquerade user back to admin?
I've setup masquerade module and switched to a regular user, but my switch back to admin block doesn't show up in the main theme and the user has no access to the admin theme. Is there a link I can use to switch myself back to admin?

# Answer
Looking at the module code, I notice the module defines a block with links for the masquerading operations. If that block is visible for the user account to which you switched, you should see a link to go back to your original account.

This is the code used from the module to show the block.

```
/**
 * Implements hook_block_view().
 */
function masquerade_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'masquerade':
      if (isset($_SESSION['masquerading']) || (user_access('masquerade as user') || user_access('masquerade as admin'))) {
        $block['subject'] = t('Masquerade');
        $block['content'] = drupal_get_form('masquerade_block_1');
      }
      break;
  }
  return $block;
}

/**
 * Masquerade block form.
 */
function masquerade_block_1() {
  global $user;
  $quick_switch_links = array();
  $markup_value = '';
  if (isset($_SESSION['masquerading'])) {
    $quick_switch_links[] = l(t('Switch back'), 'masquerade/unswitch', array('query' => array('token' => drupal_get_token('masquerade/unswitch'))));
    if ($user->uid > 0) {
      $markup_value = t('You are masquerading as <a href="@user-url">%masq_as</a>.', array('@user-url' => url('user/' . $user->uid), '%masq_as' => $user->name));
    }
    else {
      $markup_value = t('You are masquerading as %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous'))));
    }
  }
  else {
    $quick_switches = variable_get('masquerade_quick_switches', array());

    // Add in user-specific switches, and prevent duplicates.
    $user_switches = db_query("SELECT uid_to FROM {masquerade_users} WHERE uid_from = :uid_from", array(':uid_from' => $user->uid))->fetchCol();
    $masquerade_switches = array_unique(array_merge($quick_switches, $user_switches));

    foreach ($masquerade_switches as $switch_user) {
      if (!isset($_SESSION['user']->uid) || $switch_user != $_SESSION['user']->uid) {
        $account = user_load($switch_user);
        if (isset($account->uid)) {
          $switch_link = 'masquerade/switch/' . $account->uid;
          if ($account->uid) {
            $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
          }
          if ($switch_user == 0) {
            $account->name = variable_get('anonymous', t('Anonymous'));
            $quick_switch_links[] = l($account->name, $switch_link, array('query' => array('token' => drupal_get_token($switch_link))));
          }
        }
      }
    }

    if (masquerade_menu_access('autocomplete')) {
      $markup_value .= t('Enter the username to masquerade as.');
      $form['masquerade_user_field'] = array(
        '#prefix' => '<div class="container-inline">',
        '#type' => 'textfield',
        '#size' => '18',
        '#default_value' => '',
        '#autocomplete_path' => 'masquerade/autocomplete',
        '#required' => TRUE,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Go'),
        '#suffix' => '</div>',
      );
    }

  }
  if ($quick_switch_links) {
    $markup_value .= '<div id="quick_switch_links">' . t('Quick switches:') . theme('item_list', array('items' => $quick_switch_links)) . '</div>';
  }
  $form['masquerade_desc'] = array(
    '#prefix' => '<div class="form-item"><div class="description">',
    '#markup' => $markup_value,
    '#suffix' => '</div></div>',
  );
  return $form;
}

```

Reading it, I see the same block shows you a *Switch back* link in the case you are masquerading as another user.
Assuming the block is enabled for all the roles in the site, and it is assigned to a region the currently-set theme uses, one of the reasons for the *Switch back* link not appearing could be an issue with the user session; in that case `isset($_SESSION['masquerading'])` could return `FALSE`.

There is also a bug report about switching back: masquerade/unswitch throws a no acccess error. In that issue is clearly stated you need to use the block to switch back; it also seems there are some issues when the clear URLs aren't enabled.
> 2 votes

---
Tags: 7
---


# Question
Title: Display additional fields from included content with Entity Reference field
I'm building a site in Drupal 8 using a content type for products, and I want to show for each product, some "Related Products" that are set in an entity reference field called field\_related\_products.

Each related product wants to show the title and link (as the field works by standard), but also include the product image and price (defined in fields against each piece of content).

Is there a way to alter the output of the field to do this?

I've seen also that views might be a route to take, but can't seem to get contextual filters to work - the closest I've come is displaying all content that is included as a "related product" throughout the site, which feels a large portion of the way there, but whatever combination I try with contextual filters/default values, it just seems to remove all my results.

Thanks for any advice.

# Answer
You can achieve this by setting a view mode (recommended: Teaser) in the node display for the entity reference field at `/admin/structure/types/manage/[CONTENT_TYPE]/display`, and then adding the price and picture fields to the Teaser display of the referenced entity.

If the referenced entity is also a node then it would have a similar path of `/admin/structure/types/manage/[OTHER_CONTENT_TYPE]/display/teaser`. The path would be different if it is not a node, but should be easily found for most custom entities through the UI under the commonly named entity page 'Manage Displays'. Once there view modes can be selected at the top of the page for editing them.
> 0 votes

---
Tags: theming, entities, views
---


# Question
Title: Can I create my module's tables before I use the Entity API?
If I want to create a module, can I create the tables first in something like phpMyAdmin and then do the module, or should I always define them first and have the tables created by Drupal?

What if I need a new table later after everything has been built? And, that new table has keys that need to fit into the other tables already built?

Edit: https://www.drupal.org/docs/8/api/update-api/updating-database-schema-andor-data-in-drupal-8

This answers some of it, but am I really unable to use a tool like MySQL Workbench or phpMyAdmin to do this same thing?

# Answer
No. Please don't use php my admin. Use the SchemaAPI and Entity API proper. Creating a table in MySQL and not going through these APIs will cause a lot of trouble.

Future updates to schema can be done with update hooks and updating the initial schema definition.
> 1 votes

---
Tags: entities
---


# Question
Title: put the contents of one field into another field upon form submit
how can I add a field to a form submission upon submit that will have the same value as the field name "mail" but with the name "email"

# Answer
> 0 votes
In Drupal 8 I did it this way, there may be a shorter way though

```
$value=$form_state->getValue('field_name');
$number=($value[0]['value']);
$form_state->setValue('other_field',$number);

```

# Answer
> 0 votes
I think it'll work if you implement hook\_form\_submit() hook for this form, and in that function set the value of one field to another.

E.g.,

```
FORM_ID_form_submit($form, &$form_state) {
  $form_state['values']['email'] = $form_state['values']['mail'];
}

```

If your fields are fields of a content then replace the above line with this:

`$form_state['values']['email']['und'][0]['value'] = $form_state['values']['mail']['und'][0]['value'];`

---
Tags: 8
---


# Question
Title: Statistics module has less functionality
The official documentation for the statistics module lists some exciting features. Here is a quote of what I found there.

> **Viewing site usage**
>
> The Statistics module can help you break down details about your users and how they are using the site. The module offers four reports:
>
> * Recent hits displays information about the latest activity on your site, including the URL and title of the page that was accessed, the user name (if available) and the IP address of the viewer.
> * Top referrers displays where visitors came from (referrer URL).
> * Top pages displays a list of pages ordered by how often they were viewed.
> * Top visitors shows you the most active visitors for your site and allows you to ban abusive visitors.

Unfortunately I don't see any of those functionalities in my drupal 8 site. All I see is the number of views on a node, and no way to see the IP addresses, or referal URL or any of the above functionalities. Looking at the source code, I also don't see where the above functionalities are implemented.

What do I need to do to get the functionalities listed above?

# Answer
> 2 votes
Based on Drupal 8.3.1, it appears that documentation is incorrect. Well, they seem to primarily relate to Drupal 7.

The statistics module doesn't appear to store IP addresses or user names.

The module does provide a popular content block, which is based on view statistics.

The module also provides views integration, so you can create reports that have statistics data using views, but it doesn't add any default views similar to the reports mentioned in those docs.

---
Tags: 8, nodes
---


# Question
Title: best way to restrict endpoints such as /node or /filter/tips
I am looking for the best way to restrict access to drupal pages such as `/node`, `/filter/tips` and `/filter/tips/plain_text` etc.

Do I add rewrite rules to the .htaccess file?

# Answer
One way to restrict access to specific paths is to use the Custom Permissions module.

It allows you to create path based permissions at */admin/people/custom\_permissions*.

Then you can configure which roles have those custom permissions as you would any other permission at */admin/people/permissions*.

I probably wouldn't use this solution if I had a very large number of paths to restrict but it's a very usable solution for a few pages, especially if you still want admins to be able to access them.

.htaccess restrictions are also possible if you want to go that way. That would mean there would be no database load involved in restricting access, which might be a consideration for very high traffic sites but would generally be negligible for an average site.
> 1 votes

---
Tags: security, .htaccess
---


# Question
Title: What is the purpose of the user_data table?
I'm using Drupal 8 and I wonder what the purpose is of the user\_data table? How can I can store custom data in that table? In my site, the content of that table is the following.

>

# Answer
This table is the backend for the User Data service. The User Data service is used to store data specific to users in the system.

You can set data like this:

```
\Drupal::service('user.data')->set($module, $uid, $key, $value);

```

Where:

`$module` = the machine key of your module

`$uid` = the UID of the user for whom data should be retrieved

`$key` = a key to identify which data you are storing

`$value` = the value to be stored

This data can be retrieved with the get() method:

```
$value = \Drupal::service('user.data')->get($module, $uid, $key);

```

`$value` will be equal to the `$value` you used when setting the data.
> 6 votes

---
Tags: users
---


title: How to use database BETWEEN query?

text:
# Question
Title: How to use database BETWEEN query?
I need to fetch the database records for particular date using database query , i tried some queries to fetch but it showing all records in table .

**controller.php**

```
public static function load($entry = array()){
$maxDate = \Drupal::request()->query->get('set_start_date');
$minDate = \Drupal::request()->query->get('set_end_date');
 $select = db_select('pastpayments', 'x');
 $select->fields('x');
 foreach ($entry as $field => $value) {
 $select->condition('paiddate', $maxDate, "<=");
 $select->condition('paiddate', $minDate, ">=");
}
 return $select->execute()->fetchAll();
}

public function entryList() {
$content = array();

$content['message'] = array(
  '#markup' => $this->t('Generate a list of all entries in the database. There is no filter in the query.'),
);

$rows = array();
$headers = array(t('Member Id'), t('Name'), t('Paid Date'), t('Paid Date'));

foreach ($entries = $this->load() as $entry) {
  // Sanitize each entry.
  $rows[] = array_map('Drupal\Component\Utility\SafeMarkup::checkPlain', (array) $entry);
}
$content['table'] = array(
  '#type' => 'table',
  '#header' => $headers,
  '#rows' => $rows,
  '#empty' => t('No entries available.'),
);
// Don't cache this page.
$content['#cache']['max-age'] = 0;

return $content;

```

}

> how i can fetch the table records for particular date ranges

**database query**

```
mysql> select * from pastpayments where paiddate >='2017/03/01' and paiddate <='2017/03/30';

```

# Answer
My answer

```
public static function load($entry = array()) {
  $maxDate = \Drupal::request()->query->get('set_start_date');
  $minDate = \Drupal::request()->query->get('set_end_date');

 $select = db_select('pastpayments', 'x');
 $select->fields('x');
 $select->condition('paiddate', array($maxDate, $minDate), 'BETWEEN');
     $ans=$select->execute()->fetchAll();
     return $ans;

```

}
> 1 votes

# Answer
You can use BETWEEN like this:

```
$query->condition('myfield', array(5, 10), 'BETWEEN');

```

In your case:

```
$query->condition('paiddate', array('2017/03/01', '2017/03/30'), 'BETWEEN');

```

For more information see the Conditional Clauses documentation.

It depends on how your dates are stored as to what min and max values you should pass in.

For example it could be a unix timestamp or it could be an actual date. I would recommend doing a more generic select on the data to find out the format of the dates and then replicate that format in the values that you are passing in.
> 8 votes

---
Tags: database
---


# Question
Title: How do I change a view pager submit from GET to POST?
Currently when I have a view pager at my site and I want to click on another site the pager gives me a link similar to "base\_url/?page=0" How can I change that so that the link just shows me the "base\_url"? In my understanding thats because the pager submit handles requests via GET.

# Answer
You can't POST a link, it's a link; by definition clicking it will send a GET for the target href. The best you could do is hijack the click to POST via JS, set something in the session, then reload the page. Or wrap the View in a form and convert the pager to use submit buttons (possibly styled like links)

But that's very awkward, and would be more than a trivial amount of effort to achieve. Plus you'll need to write a custom Views pager for either method, and you lose the ability to link directly to a certain page, destroying navigation and SEO.

I would just leave it as it is (ie the same as every pager you're likely to find), or install Views Load More or something, if it's the UI you're concerned about.
> 2 votes

---
Tags: views
---


# Question
Title: How do I create hierarchical taxonomy terms on import nodes?
I use drupal 7 and the feeds module.

I have an excel file that contain 10 fields,So I want to import these 10 fields to specified content type as node and for 3 fields of those create hierarchical taxonomy terms on importing file. For example My excel file have 10 columns.

> * column 1 (cars name)
>
> + BMW
>     + Chery
>     + MVM
> * column 2 (cars model)
>
> + BMW 110
>     + Chery tigo 5
>     + MVM 110s
> * column 3 (color)
>
> + red
>     + black
>     + silver
> * column 4
>
> + ...
>     + ... . . . .

I want to import this file and after importing have 3 hierarchically taxonomy like following that assigned to nodes of content type. Taxonomy terms is not added by me to content type yet and I want to create taxonomys and terms automatically and assign automatically to nodes.

I have created 3 taxonomy vocabulary in my drupal site (but not added any terms to those): 1- Car name (taxonomy vocabulary 1) 2- Car model (taxonomy vocabulary 2) 3- Car color (taxonomy vocabulary 3)

I want to have taxonomy terms such as: -car name : -BMV \- BMV 110 \- red \- Chery \- tgo5 \- black

Please Help me for importing some fields of my file as taxonomy terms and sub terms .

I Can't type english verywell.sorry thank you

# Answer
> 0 votes
First make 3 taxonomy feeds importers for each of the tree taxonomy vocabularies separately

Import the terms from the same source file you got - you need only to specify Term Name and matching the right columm under Mapping for "Taxonomy term processor"

In case you want to import taxonomy with the hierarchy, use Taxonomy CSV import/export to put the taxonomy terms. Sample import file with terms&hierarchy should look like this:

BMW;BMW 5;

BMW;BMW 7;

Audi;R8;

Audi;A1;

After you run these imports, make the final node importer. Change the settings to node processor. Remember under Mapping for Node processor when you map taxonomy terms to have "Search taxonomy terms by: Term name" checked on these three columns

---
Tags: entities, taxonomy-terms, feeds
---


# Question
Title: File browser of ckeditor increase overhead by loading unnecessary folders
When I try to use the image file browser of the CKeditor, the browser takes a lot of time to load. When I checked the request, I found that the browser loads a lot of folders that are not even displayed.

The logs shows that the file browser try to load all the folders under `/pub/sites/default/files/` will it be possible to limit that to only request the folders under `/pub/sites/default/files/u285430` where u285430 is the user folder ?

# Answer
> 0 votes
This might help people having the same issue.

The way IMCE works will scan the whole directory over Http requests then filter using permissions. This can cause a big overhead.

My solution was to dynamically generate new folder every month, this way I make sure that there are not that many pictures to load every time.

---
Tags: files, wysiwyg
---


title: Select options from JSON file

text:
# Question
Title: Select options from JSON file
I have JSON file with some id and value, and this need to be populated in form as select list:

```
$form['select_item'] = [
      '#type' => 'select',
      '#options' => $list,
      '#title' => $this->t('Choose'),
      '#required' => TRUE,
    ];

```

What is the best way to approach this. Can I somehow convert this JSON in array or something and use it in options?

I would like to have this values form JSON in separate file and to use it from there.

Any idea?

# Answer
Drupal doesn't have a lot to help with this, it's really a general PHP task.

If you're determined to use the API for it, just load the file data in any way you like (`fopen`, `file_get_contents`, etc), and use `Json::decode()` to turn it into an array.
> 2 votes

---
Tags: forms, 8
---


# Question
Title: Can I safely use the same UUID on independent sites?
I'm trying to create a site building workflow which uses some sort of blueprint site, providing a shared, tested set of the Drupal core, modules, content types, paragraph types, a base theme, etc. for all our client work.

Projects/websites shall initially start with the same configuration as the blueprint site, but later on those projects are otherwise completely independent (different clients, different themes, modules will be added/removed, content types will change, ...)

From what I've read this should be possible with config export/import and by manipulating the UUID of the sites.

The question is: Is it a problem when ALL our projects share the same UUID? In the long run I'm going to end up with about 30-50 projects, each project will a dev and a prod environment, so in total there will be ~ 60-100 installations with the same UUID.

Updating the core and shared modules shall also be done and tested on the central blueprint site, and then pulled and merged by all projects.

# Answer
Following Kevin's hint using the Features module I've done some testing, and this is what I've got so far:

Blueprint site:

1. Create a Drupal composer project
2. composer require all shared modules
3. drush site-install minimal
4. Set up my desireded configuration
5. In features module, create a blueprint feature containing every single component and export it
6. Commit to git
7. (Later on: update core and shared modules, after successful test push to git again; repeat)

Client project spawning:

1. Init a new repository, add blueprint as additional remote and pull from blueprint
2. composer install
3. drush site-install minimal
4. drush en blueprint\_theme
5. drush en blueprint\_module
6. git push to project's own origin remote
7. (Later on: pull core and shared module updates from blueprint repository, but do not import config)

Some things I've learned so far:

* Features exports your config as a custom module, you don't even need features to import the blueprint config into the client project, you simply enable the module.
* The theme used on your blueprint site must exist and must be activated before enabling the blueprint module on the client project. (I guess this is coming from blocks being included in config)
* All modules have to exist in your client project directory before activating the blueprint module. They don't need to be enabled, but Features can't download missing modules.
* Features seems to merge & override the existing client project configuration, but it does not remove additional configuration existing only on client. (e.g. it does not delete additional content types from the client project. This behavior differs from Drupal core configuration management.)
* Uninstalling the blueprint module has no effect at all, it will not revert your configuration.

It is neither perfect nor extensively tested so far, but it seems to be a much cleaner solution than messing around with UUIDs.
> 1 votes

# Answer
This is a perfect use case for Features. You can export shared sets of functionality and configuration without worrying about UUID stripping or collision.

> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
>
> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it contains additional information in its info file so that configuration can be checked, updated, or reverted programmatically.
>
> Examples of features might be:
>
> * A blog
> * A pressroom
> * An image gallery
> 1 votes

---
Tags: 8, configuration
---


# Question
Title: How can I add a special classes to all block of custom kind?
Is there any `hook_preprocess_block` or any other way to I can add my custom classes to all blocks of a custom kind?Or in the other words:
How can I target all blocks of custom kind?

For example I want to add `search` class to all search blocks (or target all search blocks in my theme by using default auto-generated classes by Drupal core if it be available), or add `user-login` class to all user login blocks and so forth in my theme without any need to create a template for every block.

# Answer
It's no problem to add classes in a block preprocess hook:

```
use Drupal\Component\Utility\Html;

  function mytheme_preprocess_block(&$variables) {
    $variables['attributes']['class'][] = Html::getClass('block-id-' . $variables['elements']['#id']);
    $variables['attributes']['class'][] = Html::getClass('block-plugin-' . $variables['elements']['#base_plugin_id']);
    $variables['attributes']['class'][] = Html::getClass('block-provider-' . $variables['elements']['#configuration']['provider']);
  }

```

This example simply adds the available information to all blocks. You can start with this and narrow it down to what you want.
> 1 votes

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


# Question
Title: Is it possible to get user uid in login form submit in DrupalGap?
I have altered the login form like

```
if (form_id == 'user_login_form') {
    form.submit.push('my_module_user_login_submit');
  }

```

In submit I need the uid.

```
function my_module_user_login_submit(form, form_state) {
   //I need the uid of login user here;
  if(form_state.values.name){
   form.action = 'user-dashboard/'+ uid;
   }
}

```

Tried

**var uid = Drupal.user.uid;** but not working.

More info

```
function my_module_menu() {
var items = {};
items['user-dashboard/%'] = {
    title: 'User dashboard',
    page_callback: 'my_module_user_dashboard_page',
    page_arguments: [1],
    pageshow: 'my_module_user_dashboard_pageshow'
  };
return items;
}

**
 * The user dashboard page callback.
 * @param uid
 * @returns {{}}
 */
function my_module_user_dashboard_page(uid) {
  var content = {};

  // Build an empty container where the user dashboard will go.
  var attributes = {
    id: my_module_user_dashboard_container_id(uid),
    class: 'user-dashboard'
  };
  content['my_widget_container'] = {
    markup: '<div ' + drupalgap_attributes(attributes) + '>' +
      'Loading dashboard...' +
    '</div>'
  };

  return content;
}

/**
 * The user dashboard pageshow event handler.
 * @param uid
 */
function my_module_user_dashboard_pageshow(uid) {
alert(Drupal.user.uid);
  // Load the user account...
  user_load(uid, {
    success: function(account) {
    var content = {};
    content['txt'] = {
        markup: '<div>' + account.name + '</div><div>' + account.uid + '</div>'
    };

      // Inject it into the container.
      var container_id = my_module_user_dashboard_container_id(uid);
      $('#' + container_id).html(drupalgap_render(content)).trigger('create');

    }
  });
}

function my_module_user_dashboard_container_id(uid) {
  return 'user-dashboard-' + uid;
}

```

# Answer
> 1 votes
Try using this hook in your app: http://api.drupalgap.org/7/global.html#hook\_services\_postprocess

```
/**
 * Implements hook_services_postprocess().
 */
function my_module_services_postprocess(options, result) {
  if (options.service == 'user' && options.resource == 'login') {
    drupalgap_goto('user-dashboard/'+ Drupal.user.uid);
  }
}

```

You may also need to set the `action` on the form object to `null` so that DrupalGap core doesn't try to redirect the page to the path indicated by the form's `action` variable:

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(form, form_state, form_id) {
  if (form_id == 'user_login_form') {
    form.action = null;
  }
}

```

---
Tags: 7, javascript
---


# Question
Title: View a log of administration configuration changes for Drupal 7?
I'm working on a Drupal 7 site and we have multiple developers and administrators accessing the site. Many times when the site breaks I can't see what was changed previously and by whom. Is there a log tracker where I can see what things were changed on the site? I know I can goto admin/content to see what content has been updated, but this isn't the case for configuration changes.

# Answer
There's nothing in core, no.

One option from contrib is to use the Journal module

> Journal module adds additional fields to all forms in a Drupal site to allow developers and site administrators to record and track all changes that have been performed to setup a site or alter its configuration.

It's not automatic (that would be too complicated, forms can obviously do just about anything and it's not obvious enough from context what every action is to be able to label it automagically), so you need to trust that your editors will fill it out correctly.

But you can make it required/able to be bypassed based on user roles, so it's a good solution to the problem.
> 2 votes

---
Tags: 7, configuration
---


# Question
Title: Adding existing contact form in another page
There is a contact form in the contact page, which is perfectly working fine. I want to add the same form in a different page (say product page). How can I do that in Drupal 8?

# Answer
> 0 votes
You could use Contact Block module which will allow you to place a contact form block on whatever page and region you desire.

Once installed place a block as usual and filter for contact block, then in the block configuration settings you can choose which contact form to use. You can also add pages to display the block, remember to add pages with a slash "/my-pages-path"

---
Tags: emails
---


# Question
Title: Edit the token values submitted by webforms
I am using webform for user registration and confirmation page as profile page. I have included the token as follows " \[submission:values:name\] \[submission:values:email\] \[submission:values:country\] \[submission:values:date\] " Now the submitted values are displayed in profile page but my requirement is the user should be able to edit and save only few fields but view all fields. How i would include edit option for displayed data using tokens. Please help me on this issue. Thanks

# Answer
> 0 votes
Have a look at the Field Permissions module. From its project page:

> ... allows site administrators to set field-level permissions to edit, view and create fields on any entity.

Since users are entities also, it should work for any of your fields.

---
Tags: webforms, tokens
---


# Question
Title: Missing bundle entity, entity type block_content_type, entity id basic
I have updated one of my D8 sites to the latest stable version - 8.3.1 using `drush up`. When applying the database update, the update fails with the following error message:

> Failed: LogicException: Missing bundle entity, entity type block\_content\_type, entity id basic. in Drupal\Core\Entity\EntityType-\>getBundleConfigDependency() (line 882 of /var/www/sitename/core/lib/Drupal/Core/Entity/EntityType.php).

This has only happened on 1 site, so it's possibly a config issue specific to the site.

How do I manually create the missing bundle entity?

# Answer
> 2 votes
To get passed this error I deleted some rows in the config table:

```

delete from config where name in ('block_content.type.basic', core.entity_view_display.block_content.basic.default', field.field.block_content.basic.body');

```

---
Tags: 8
---


# Question
Title: Drupal 8 How to fix "URL is Incomplete" error at Facebook Instant Articles
When I try to submit my HTML code for Facebook's new Instant Articles, I get the error below. This is the only error I get and it is displayed at the bottom of the pasted code.

URL is Incomplete: The URL used for this media element is missing information. We have automatically filled in information for you. Please check that the URL is now correct and complete. Any idea how to fix that?

img src="/sit/to/img/" - wont work

img src="http://mydomain.de/path/to/img/"

help me please

# Answer
> 1 votes
As I understand it, the Pathologic module should fix this issue for you.

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds. See more example use cases on the documentation page.

---
Tags: social-network
---


# Question
Title: Can't set field names with Given users behat call
When I run the following behat test:

```
Scenario: Logs in to the site
  Given users:
  | name     | pass        | mail                  | roles         | status | field_fir | field_la |
  | someuser | sompassword | someone@xenomedia.com | administrator | 1      | Some      | User     |
  Given I am on "/user"
  When I fill in "Username" with "someuser"
    And I fill in "Password" with "sompassword"
    And I press "Log in"
  Then I should see "Some User"
  Then I visit "user/logout"
  Then I should be on the homepage

```

I get the following error:

```
Given users:                                # Drupal\DrupalExtension\Context\DrupalContext::createUsers()
  | name     | pass        | mail                  | roles         | status | field_fir | field_la |
  | someuser | sompassword | someone@xenomedia.com | administrator | 1      | Some      | User     |
  Warning: explode() expects parameter 2 to be string, array given in /var/www/xmd8/vendor/drupal/drupal-extension/src/Drupal/DrupalExtension/Context/RawDrupalContext.php line 316

```

The weird thing is if I remove `field_fir` and change `Then I should see "Some User"` to `Then I should see "User`, it works. For some strange reason it doesn't like field\_fir. I verified that field\_fir and field\_la have exactly the same settings.

# Answer
I didn't think this was the issue but I recently upgraded to PHP 7. I downgraded to PHP 5.6 and the issue went away. I created an issue on Drupal.org.

Turns out that I was using an older version of drupal-extension. Upgraded to and the issue went away:

```
"drupal/drupal-extension": "^3.2",

```
> 0 votes

---
Tags: testing
---


# Question
Title: Get the submitted values from $form_state
Is there a function (in Drupal 8) to build an array containing the submitted values in `$form state`? If I use `$form_state->getValues()`, I get more values than the ones I need.

# Answer
If you are getting values like form\_id, form\_token, or form\_build\_id, which you don't want, then you need to use the following code.

```
$values = $form_state->cleanValues()->getValues();

```

The documentation for `FormState::cleanValues()` says:

> This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.
>
> * form\_id
> * form\_token
> * form\_build\_id
> * op

`FormState::cleanValues()` returns `$this`, so it can be used in chained calls, as in the code I showed.
> 13 votes

---
Tags: 8, forms
---


# Question
Title: hook_entity_field_access - trying to check if there's a value
I am trying to check if a given FieldItemListInterface is empty or not (and if not, grab the entity)

Using the example in https://www.drupal.org/project/examples \- the team I'm on was able to get an access function written that should theoretically work only if there are items with an entity in them.

However whenever we have the correct field definition name, and check for items, they're all empty:

```
if ($items) {
// Code does not execute here - $items value is always NULL.
}

```

I'm not quite sure why but for some reason the value is always NULL, even if I would think it should be full.

Why exactly would this value be NULL if the field definition exists on a given entity, and has a value?

What am I missing?

Further code example:

```
function MY_MODULE_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {

if ($field_definition->getName() != 'field_attendee_only_content') {
    return AccessResult::neutral();
  }

// Code gets to here.

  if ($items) {
// Code here is never executed. $items is ALWAYS NULL.
    $entity = $items->getEntity();
  }
}

```

For additional information, the field in question is a file field.

# Answer
In the documentation for `EntityAccessControlHandler::fieldAccess()`, the method that invokes the hook you are implementing, `$items` is defined as follows.

> \Drupal\Core\Field\FieldItemListInterface $items: (optional) The field values for which to check access, or **NULL if access is checked for the field definition, without any specific value available**. Defaults to NULL.

This could also happen if the entity containing the field is being created, and not modified. That is the reason why Drupal core implementations of that hook always check the value of `$items` before using it.

```
  // language_entity_field_access()
  // Only allow edit access on a langcode field if the entity it is attached to
  // is configured to have an alterable language. Also without items we can not
  // decide whether or not to allow access.
  if ($items && $operation == 'edit') {
    // Omissis.
  }

```

```
  // views_entity_test_entity_field_access()
  if ($field_definition->getName() == 'test_text_access') {
    if ($items) {
      if ($items->value == 'no access value') {
        return AccessResult::forbidden()->addCacheableDependency($items->getEntity());
      }
    }
  }

```
> 2 votes

---
Tags: 8, users
---


# Question
Title: Best practice for node comparison for more than 2000 nodes
I have around 250 content types for a total of 2000 nodes. What I have to do is finding a clone of each node and display those related clones below the node page in a block (just their titles).

So I'm finding clones on basis of same term reference field value.

For example, for the node with an ID of 6783, there is a field of type term reference (tags). This tag field contains 15 target IDs.

Now I will search all other 199999 nodes; if any node has exactly the same target IDs found in that particular tag field\**, I will make all those titles populated below /node/6783.

I need to check on three stages: On first stage, check for all the nodes with the same target IDs; on second stage, check for 90% cloning, meaning looking for the nodes that have 90% of the target IDs; on third stage, check for 80% cloning.

If I will search 2000 nodes, it will exceed the query execution time limit.

What would be the best approach so that it will not affect the performance of website too.

# Answer
I do not know of a query execution time limit, so I will assume you meant php's max execution time.

If the clone search does not need to be instantly updated, a good approach would be to run the query on cron and cache the results, which means running a single query to fetch the data, process it, and save the results for a quicker fetching at a later time. Cron disables the execution time limit and will run indefinitely in the background.

If the site's cron runs once a day, the clone search results will be up to a day old.

Some resources to give some direction:
> 0 votes

---
Tags: 8, nodes, database
---


# Question
Title: Hide user profile field based on its own value
Situation:

* I added a boolean field named `Fee waived` to the user account.
* On the edit form, this field is represented as a single checkbox.
* Users cannot edit the value; only admins can see and edit it (I'm using `field_permissions`).
* When the checkbox is selected, `Fee waived: Yes` appears in the user profile. I want this.
* When the checkbox is NOT selected, `Fee waived: No` appears in the user profile. I don't want this. I don't want anything to show (because I don't want users wondering how to get their fee waived).

By default, when a user account field is empty, nothing is displayed for it in the user profile. However, a non-checked checkbox is not empty; it has a value of 0 (or whatever has been defined for it). This is why I get `Fee waived: No` in the user profile.

Question:

Is there a simple way to keep the field from being displayed in the user profile when it is not selected?

Attempted solutions:

* If the `conditional_fields` module would allow a field to be dependent upon itself, that would work beautifully to solve the problem. But it does not. I tried disabling the 'same field' check in the module's code. This works, in that the field is hidden exactly as I want it to be, but when the `dependent` and `dependee` fields are the same: (1) the dependency configuration form ceases to hide irrelevant fields due to a Javascript error and (2) a PHP error is thrown when the dependency is saved. These can be ignored and the dependency still works, but it makes the solution ugly.
* I tried other modules that allow value-based field control (`field conditional state` and `field formatter settings`), but none seem to allow a field to depend upon itself.
* I placed a span tag with the class `conceal` in the `Off value` for the boolean field and then injected the following Javascript into the user profile page:

`jQuery("span.conceal").closest("div.field").css("display", "none");`

This works, but when the profile is displayed, the user sees a "hiccup" as the to-be-hidden field is briefly shown and then hidden.

# Answer
> 0 votes
In the end, the most straightforward solution I could find was to:

* create a duplicate user profile field named `Fee waived dup`.
* use `field_permissions` to always hide this field from all users.
* create a rule to set `Fee waived dup` equal to `Fee waived` when the user account is saved.
* use the `conditional_fields` module to display `Fee waived` only when `Fee waived dup` is true.

If there were multiple fields to be hidden based on their own values, this might not be such a good solution. I have only one such field, so it is OK.

# Answer
> 1 votes
One way to do it is in a twig template that renders the profile. Something like:

```
{% if user.field_fee_waived is not empty and user.field_fee_waived.value == 1 %}
  {{ content.field_fee_waived }}
{% endif %}

```

Basically, twig looks at the user object to see if the field is present, and that its value is 1/true. If not, it won't render the field. This same approach can work on `node` or `paragraphs` or any entity that gets passed along to a template. `content.field_fee_waived` is the render array that renders that specific field to your configuration you set under `Manage Display`.

---
Tags: users
---


# Question
Title: Migrate D2D UI - Source field missing from dropdown menu when editing field mappings
I got an `PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value` error on one of the fields for a content type that I'm importing from a D6 site to a D7 site, and the import of all those nodes is failing. I looked at the field on the Field Mappings page, and found that the field is not in the Source dropdown menu, and therefore cannot be mapped. I think this is why the import is failing. The field exists in both the source D6 database and the destination D7 database.

How do I get Migrate D2D to recognize this field so that it appears in the field mappings menu?

# Answer
> 0 votes
I found the cause of the problem, and a solution:

I had cloned my old D6 site, then performed the core and CCK upgrade to D7 as described in Drupal's documentation, during which I mistakenly converted the above-mentioned field to a `Boolean` type when it should have been (based on the old site's field) converted to the `List (text)` type. I manually deleted the field and recreated it as the proper type, ran the migration, and the nodes were imported as expected.

---
Tags: 7, migrations
---


# Question
Title: Drupal 7: Is hook_update_N() called when a module is updated between minor versions?
Say I'm trying to update a module from version 7.03 to 7.04, and version 7.04 has a function called mymodule\_update\_7704() which updates the module's schema.

If I go to the modules page and update mymodule, will the mymodule\_update\_7704() function run, and update the module's schema?

Also, if the above is correct and mymodule\_update\_7704() does run, will the user have to click to run the update, or is it silent?

Sorry if this question seems elementary, I just can't test this without releasing my module, and I'd rather know first before I do release.

# Answer
> 0 votes
`hook_update_N` is only invoked when:

* The update process is running (via /update.php, drush, etc).
* The current schema version for the module is less than the update hook's schema version (The `N` in `hook_update_N`).

No updates are run when you visit the modules admin page, the process will always be invoked by an administrator (or perhaps an automated task, but never silently/automatically by Drupal itself).

As an aside (in case it comes to bite you at some point), no update hooks are invoked when installing a module, only for already-installed modules during the update process. The update hooks are only for getting older installations up to speed with what the current release offers upon installation anyway.

As another aside, your schema numbering looks a bit suspect if you want to stay within common practice; have a read through the `hook_update_N` docs for more info, but your numbering should probably be in the 7100s at this point.

---
Tags: 7, database, updating
---


# Question
Title: Autocomplete selection in Rules Component
How do I create a rules component which lets you select or autocomplete a node from an existing list of nodes?

I have tried all the Data Type while creating a Rule Component. Each one of them requires a direct input rather than a Drop Down Select List or Autocomplete function.

Please advice

# Answer
> 2 votes
I'm assuming that your question is related to ***executing*** a Rules Component, and not ***creating*** it.

A possible approach might be to *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* load the VBO list of entities (such as nodes) that you want to be processed.
* add a loop to perform a Rules Action, for each entity (such as a node) contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

---
Tags: 7, rules, views
---


# Question
Title: Migrate dashboard goes to content dashboard
I am clicking on "configure" under Modules \> Migrate UI and it is just taking me to `admin/content`. According to the migrate\_d2d module page, the migrate module should have a dashboard.

> Enabling the migrate\_d2d\_ui module will add an "Import from Drupal" subtab to the Migrate dashboard

I made sure to give the admin user permissions to use the module and I cleared the caches.

I am using Drupal 7.50 on the site I am migrating data from and 7.54 on the new site.

# Answer
I am not sure why it happened but I was able to resolve this issue by uninstalling and then reinstalling migrate module.
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server
I recently tried to setup a dev environment for my production site and replicated the same architecture.

I've a server hosting Drupal, a second server for mysql and a memcached server. All the setup was good.

* Exported the Prod DB
* Installed Drush
* Made sure the latest code is pulled
* run Drush status

Drupal version : 7.37
Site URI : http://default
Database driver : mysql
Database hostname : ip address
Database port : 3306
Database username : username
Database name : dbname
PHP configuration : /etc/php.ini
PHP OS : Linux
Drush script : /usr/local/bin/drush
Drush version : 8.1.9
Drush temp directory : /tmp
Drush configuration :
Drush alias files :
Drupal root : /path/to/root/folder
Drupal Settings File : sites/default/settings.php Site path : sites/default

The issue is when trying to load the website I get :

PDOException: SQLSTATE\[HY000\] \[2003\] Can't connect to MySQL server on 'ip-address' (13) in lock\_may\_be\_available() (line 167 of /var/www/cw/html/includes/lock.inc).

Any idea why this is happening ? If I run `drush sqlc` I'm able to connect to the remote database.

Any help will be much appreciated.

# Answer
For anyone having the SAME error code, please check if you have SELinux enable by typing `sestatus`. If that's the case then your firewall is most likely blocking the connection to the db.

To allow it you can use the following command line :

```
setsebool httpd_can_network_connect_db=1

```
> 2 votes

# Answer
Have you created user with APP Server IP in your database. If not please create the user first.

CREATE USER ‘username’@’APP\_SERVER\_IP’ IDENTIFIED BY ‘password’; GRANT ALL PRIVILEGES ON *.* TO ‘username’@’APP\_SERVER\_IP’; FLUSH PRIVILEGES;

and then use this user in your drupal site to connect with database.

If it is not working then please check the MySQL Database port on DB Server. If it is not open then open it first.
> 0 votes

---
Tags: 7, database
---


# Question
Title: How to programmatically enable/disable Quantity text widget on cart/checkout page?
There are the following things which I've investigated so far:

* Version of Commerce Cart: 7.x-1.9
* Shopping cart form is controlled by `commerce_cart_form` view.
* Checkout page is controlled by `commerce_cart_summary` view.
* Quantity widget can be enabled or disabled in Manage display for Product display content type. But there are no any rule actions controlling display Quantity widget.

So the question is, how do I (programmatically) enable or disable text Quantity widget on checkout page (e.g. for certain conditions/product types)? So people can edit the Quantity for only certain product types.

There is Commerce Rules Extra module, but it doesn't provide much functionality, but I've already posted feature request for that.

# Answer
It seems the Quantity widget is a matter of configuring the views.

If you'll edit one of the commerce views e.g. `commerce_cart_form` or `commerce_cart_summary`, Quantity can be found in the field list.

By default Commerce Cart module has Quantity set to text field (File: commerce\_cart.views\_default.inc), so to change the widget from text field to numeric and vice versa you need to edit your view and replace the Quantity field with other one.

There are two fields available for these views:

* Commerce Line Item: Quantity

The quantity of the line item.

Machine name: quantity

Handler: views\_handler\_field\_numeric
* Commerce Line Item: Quantity text field

Adds a text field to edit the line item quantity in the View.)

Machine name: edit\_quantity

Handler: commerce\_line\_item\_handler\_field\_edit\_quantity

If you need to switch between numeric and text widget on certain conditions, you'll have to alter the view by using `hook_views_pre_view()` and change the handler on the fly.

Here is a simple example:

```
/**
 * Implements hook_views_pre_view().
 */
function MODULENAME_views_pre_view(&$view) {
  switch ($view->name) {
    case 'commerce_cart_form':
    case 'commerce_cart_summary':
      $view->display['default']->handler->options['fields']['quantity']['field'] = 'edit_quantity'; // 'quantity' for numeric, 'edit_quantity' for text field
      break;
  }
}

```

Other method is to create TPL view template file i.e. `views-view-field--commerce-cart-summary--default--quantity.tpl.php` and change the widget from there. Check 'Theme:Information' in view edit page for more info.

---

Here is example for restricting Quantity field based on the product type:

1. You need at least one TPL file created in your template directory (sites/all/themes/foo)

* for cart page:

    views-view-field--commerce-cart-form--default--quantity.tpl.php
    * for summary page:

    views-view-field--commerce-cart-summary--default--quantity.tpl.php

with the following PHP code:

```
print foo_quantity_available_for_row($row) ? $output : 1; // Hardcoded '1'.

```

Note: If Quantity is numeric, it'll always display 1, so extend it based on your needs.
2. And the following two functions:

```
/**
 * Implements hook_views_pre_view().
 */
function foo_views_pre_view(&$view) {
  switch ($view->name) {
    case 'commerce_cart_form': // On cart page
    // case 'commerce_cart_summary': // On summary page
      $view->display['default']->handler->options['fields']['quantity']['field'] = 'edit_quantity'; // Enforce Quantity field from numeric to text field for further changes.
      // $view->display['default']->handler->options['fields']['text_quantity'] = $view->display['default']->handler->options['fields']['quantity']; // Create clone.
      break;
  }
}

/**
 * Restrict edit of Quantity field based on the product type.
 *
 * Callback from views-view-field--commerce-cart-summary--default--quantity.tpl.php.
 *
 */
function foo_quantity_available_for_row($row) {
  ($line_item = $row->commerce_line_item_field_data_commerce_line_items_line_item_) &&
    ($line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item)) &&
      ($product = $line_item_wrapper->commerce_product->value());

  if ($product) {
    switch ($product->type) {
      case 'product_type_1':
      case 'product_type_2':
        return TRUE; // Allow users to edit Quantity field.
        break;
    }
  }
  return FALSE; // Disallow users to edit Quantity field.
}

```

It could not work in all cases, so modify based on your needs.

---

Other method, as suggested by MarcElbichon would be to use hook\_form\_alter:

```
<?php
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if (strpos($form_id, 'views_form_commerce_cart_form_') === 0 ) {
        $form["edit_quantity"][0]["#attributes"]["readonly"] = "readonly";
        $form["edit_quantity"][0]["#attributes"]["disabled"] = TRUE;
    }
}
?>

```
> 2 votes

# Answer
I found this article on heavy kettle and this method works for me.

The Commerce Shopping Cart is produced with Views. This makes it easy to modify, but difficult to conditionally manipulate the line items with Rules.

That's where hook\_form\_alter comes to the rescue with the help of entity\_metadata\_wrapper. Looping through the line items makes it possible to disable the Quantity and Remove fields for line items of a particular product type. Accomplishing this however is not immediately obvious as it requires comparing the shopping cart line item ID with the form line item ID attribute.

With that in mind, the following code illustrates how to disable the Quantity and Remove fields for line items of a particular product type.

```
/**
 * Implements hook_form_alter().
 */
function custom_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_form_commerce_cart_form_default') {
    global $user;
    $product_types = array('pickup', 'delivery');
    $cart = commerce_cart_order_load($user->uid);
    foreach (entity_metadata_wrapper('commerce_order', $cart)->commerce_line_items as $delta => $line_item_wrapper) {
      // check current line item product type against list of types to be disabled
      if (in_array($line_item_wrapper->commerce_product->value()->type, $product_types)) {
        foreach ($form['edit_quantity'] as $index => $line_item) {
          if (is_numeric($index)) {
            // compare the current shopping cart line item ID to the form line item ID
            if ($line_item_wrapper->raw() == $form["edit_quantity"][$index]['#line_item_id']) {
              $form['edit_quantity'][$index]['#attributes']['readonly'] = 'readonly';
              $form['edit_quantity'][$index]['#attributes']['disabled'] = TRUE;
              $form['edit_quantity'][$index]['#attributes']['title'] = t('This quantity cannot be changed.');
              unset($form['edit_delete'][$index]);
            }
          }
        }
      }
    }
  }
}
```
> 2 votes

# Answer
Besides the described options, it is also possible to solve this by making use of the **views\_conditional** module.

Altering the quantity field in the cart form i.e. works like this

1. Open the view at /admin/structure/views/view/commerce\_cart\_form/edit
2. Add relationship Commerce line item: Referenced products
3. Add field Commerce Product: type; place above existing quantity text field, hide field
4. Add field Commerce Line Item: quantity; place above existing quantity text field, hide field
5. Hide existing Commerce Line Item: quantity text field
6. Add field Views: Views conditional; place below the above
    * Title: Quantity
    * If this field…: \[type\_1\] == Commerce Product: type
    * Is…: NOT equal to
    * This value: YOUR-PRODUCT-TYPE
    * Then output this…: \[quantity\]
    * Otherwise, output this…: \[edit\_quantity\]

This way I managed to enable editing the quantity for just one product type.
> 1 votes

---
Tags: views, commerce, forms
---


# Question
Title: What is the name of the template to theme a reset password mail?
I want to theme the mail which is used to sent a link to user when the user forgot the password. I want to know what I need to name the template file so that Drupal will take my email template file.

I am using the Mime Mail module. How do I find the key of that particular module?

# Answer
> 1 votes
This

> mimemail-message--user-pasword-reset.tpl.php

template file name is not worked.Belowone worked for me

> mimemail-message--password\_reset.tpl.php

# Answer
> 0 votes
```
mimemail-message--user-pasword-reset.tpl.php

```

this is how you should name the template file that will cover User Password Reset email.

More information here: Theming HTML Mail sent through Mime Mail

I'd recommend installing Mail Logger. It shows the mail key of every email that is sent. Note: this module currently has only D7 release.

# Answer
> 0 votes
use

> mimemail-message--user--password\_reset.tpl.php

correct format mimemail-message--\[module\]--\[key\].tpl.php . The module in this case is "user" (check yoursite/modules/user). The keys can be found in the module's hook\_mail() implementation, in this case "password\_reset"

---
Tags: theming, emails
---


# Question
Title: LoginToBoggan and user registration password to allow users register with password and email verification at the same time
I am using the LoginToBoggan module to enrich the account functionalities. In its settings there is a *Set password* field; when it's not checked anonymous users can't choose their passwords in registration form but they can receive verification emails.

I need both functionalities: email verification and set the password field in registration form. I found the User registration password module which allow users to choose password in the registration form.

The problem is when I create a new account. The user can login with the chosen password, but I need they first verify their email.

So the process must be like this:

* Anonymous users register and choose their password in the registration form
* They receive a verification email
* They click on the link given in the email to activate the account

The problems I have now are the following.

* Users can log in after registration, even if they didn't click on the link sent via email
* The link in the email is a kind of reset password link and not a link to verify the email link

Is there a possibility to fix this and allow users to choose their password in registration even if they still to verify the email they use for the site?

# Answer
> 0 votes
You could use https://www.drupal.org/project/registration\_role to auto assign a different role (as in other than authenticated) to users who register. https://www.drupal.org/project/autoassignrole this one offers a little bit more functionality.

# Answer
> 0 votes
enable logintoboggan\_rules module and import following rule

```
{ "rules_notify_user_when_account_activated" : {
    "LABEL" : "Notify user when account activated",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "logintoboggan_rules" ],
    "ON" : { "logintoboggan_validated" : [] },
    "DO" : [
      { "user_send_account_email" : { "account" : [ "account" ], "email_type" : "status_activated" } }
    ]
  }
}

```

---
Tags: 7, authentication-authorization
---


# Question
Title: Allow editing of user content by account creator
I have to create a set of user roles and permissions for sets of teams.

Users with a "coordinator" role would be able to create and manage a set of subordinate accounts.

The 'coordinator' role should also be able to edit content created by one of their own subordinates - but no one others.

If the coordinator were to change, it should be possible to assign their existing permissions and privileges in regards to their subordinates to a new user.

Is this easy to do with Drupal 8?

# Answer
> 2 votes
Your question looks like a perfect fit for the Group module, which can be used to create collections of content (nodes) that can be accessed by sets of users and with variations of access levels, such as none, read only, edit, etc.

Have a look at the answer to "What are the alternatives for the Organic groups module?" for a brief introduction to the Group module.

For this specific question, here is a blueprint of how it could be used/configured:

* Group Type: Teams
* Group Roles (refer to "What are the various roles supported by the Group module?" for more details):
    + Coordinator.
    + Team Member (or whatever fits), used for those who have access to a Team's content.
* Groups: 1 such group for each team (simple as that ...).
* Optional (not sure if you want this): If a user creates a new group, then automatically assign the "Group Owner"-role to the user who created the group.
* Group permissions: grant permission to the user with role "Group Owner" to perform actions like "Add members" or "Invite members to join".

Special case: "*If the coordinator were to change*" (as in your question), then simply tune the permissions to grant the "Coordinator" role to another appropriate user (how easy can it be ...).

To use the Group module from within a custom module, start from its Development guide and/or have a look at its API for D7 or API for D8.

# Resources

PS: Even though this question is related to D8, this answer applies for either D7 ...

---
Tags: 8, users
---


# Question
Title: How to identify all modules hosted on drupal.org that depend on a given module?
Assume any contributed module X (e.g Quiz) on drupal.org (=D.O), or any of its sub-modules Y (e.g Quiz Stats). Any such (sub-)module may depend on one or more other contributed (sub-)modules Z (e.g Charts, disclosure: I'm a co-maintainer), as indicated in the (sub-)module's info file (e.g in the last line of the info file of the Quiz Stats module).

**My question**: How can I identify all modules X and submodules Y, which depend on module Z?

The question about "Is there a drupal.org API for retrieving the list of available modules?" is somehow related (not a duplicate IMO), but none of the answers there seem to help to find the answer to my question, or am I missing something in those answers?

**Note**: this question is really about modules "on drupal.org", so I may not even have Drupal installed anywhere ... Think of this question in the context of, for example, a d8rules campaign, where somebody wants to try to find other modules depending on Rules to reach out to the module (co-)maintainers of those other modules (for whatever reason related to such campaign).

# Answer
> 3 votes
As was mentioned above the solution could be parsing info files of all projects hosted on drupal.org. You can use this small tool to facilitate the process of obtaining the codebase of Drupal contributed projects.

Below is an example of searching dependencies for Quiz module.

```
drupal-project-loader -c 5 -b 7.x -d d7_modules -y &&
cd d7_modules && ag 'dependencies\[\] = quiz$' -G \.info$ |
sed 's/\/.*//;s/^/https:\/\/www.drupal.org\/project\//' | uniq | sort

```

The result:

```
https://www.drupal.org/project/certificate
https://www.drupal.org/project/certify
https://www.drupal.org/project/civicrm_cert_quiz
https://www.drupal.org/project/cloze
https://www.drupal.org/project/course
https://www.drupal.org/project/elms_features
https://www.drupal.org/project/grouping_question
https://www.drupal.org/project/image_target_question
https://www.drupal.org/project/kalvi_core
https://www.drupal.org/project/mark_word
https://www.drupal.org/project/og_quiz
https://www.drupal.org/project/opigno
https://www.drupal.org/project/opigno_pretest_app
https://www.drupal.org/project/opigno_quiz_app
https://www.drupal.org/project/opigno_quiz_import_app
https://www.drupal.org/project/qq_import
https://www.drupal.org/project/quiz
https://www.drupal.org/project/quiz_ddlines
https://www.drupal.org/project/quiz_drag_drop
https://www.drupal.org/project/quiz_evaluation
https://www.drupal.org/project/quizfileupload
https://www.drupal.org/project/quiz_h5p
https://www.drupal.org/project/quiz_progress
https://www.drupal.org/project/quizrubric
https://www.drupal.org/project/quiz_sentence_drop
https://www.drupal.org/project/quiz_share
https://www.drupal.org/project/quiz_userpoints
https://www.drupal.org/project/quiz_voice_answer
https://www.drupal.org/project/quizwebform
https://www.drupal.org/project/simple_mcq
https://www.drupal.org/project/tincanapi

```

---
Tags: community-official-site
---


# Question
Title: render form item of type text_format in twig file
I have created a form element, basically I want text formats to change texts as accordingly.

```
$form['thankyou'] = [
        '#type' => 'text_format',
        '#title' => $this->t('Thank you'),
        '#format'=> 'full_html',
        '#default_value' => $config->get('thankyou'),
      ];

```

Now, I have created a function, where I'm getting this form element value.

```
$config = \Drupal::configFactory()->getEditable('myconfig');
 $thankyou_paid = $config->get('thankyou');

```

If I directly debug `$thankyou_paid`, I get all my data formatted. (in bold)

But If I render it through hook\_theme,

```
return array(
      '#theme' => 'mytwig',
      '#type' => 'markup',
      '#thankyou' => $thankyou_paid,
      '#cache' => ['max-age' => 0,],
    );

```

It gives me `<b>ugwdegfgiurgiuterug</b>`. Means, data gets rendered without formatting.

How to get this text (ugwdegfgiurgiuterug) as **ugwdegfgiurgiuterug**.

# Answer
It's unsafe to use the raw filter, better use the render element

> **raw**
>
> This filter should be avoided whenever possible, particularly if you're outputting data that could be user-entered. See this page for more information on auto-escape in Drupal 8.

`processed_text`:

```
return [
  '#theme' => 'mytwig',
  '#thankyou' => [
    '#type' => 'processed_text',
    '#text' => $thankyou_paid,
    '#format' => 'full_html',
  ],
];

```

To configure the text format visit */admin/config/content/formats* and read the warnings

> **Improper text format configuration is a security risk.**

In this case it might be better to use *Restricted HTML* or *Basic HTML*.
> 8 votes

# Answer
solution in twig file:

**{{ element\['#thankyou'\]|raw }}**

raw provides formatted text.
> -3 votes

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


# Question
Title: Create a controller and a empty theme page
On Drupal 8, I'm looking for a way for creating an empty page (a page without any theme) that contains JavaScript code.
I created a controller via Drupal Console, and I searched for an example on the web, but I found only very simple examples.

Is it possible to create an empty page accessible via a controller and add JavaScript code to this page?

# Answer
> 2 votes
Controllers must return a response (you will get an error if you don't). Your options are to return a render array, an HtmlResponse, a JsonResponse, or an AjaxResponse.

Edit: Or as Kevin posted below, a Response.

By the sounds of it, you are wanting to return JSON, so JsonResponse is likely what you are looking for.

---
Tags: page-controller
---


# Question
Title: Display custom output if field doesn't have value in hook_field_formatter_view
Display custom output of field in hook\_field\_formatter\_view() if field is empty.

```
function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  //My Snippet to display custom output
  // Here $items variable is empty.
  $element = array();
  switch ($instance ['widget'] ['type']) {
  case 'my_widget' :
    if (!isset($items[0])) {
      $output = generate_custom_output();
      $element [0] = array ('#markup' => $output );
    }
    break;
  }
  return $element;
}

```

my custom field is empty, no $item is available. Now I want to return custom output. But above code doesn't work.

Please suggest any solution.

# Answer
I am able to do this as below in hook\_field\_formatter\_view().

```
switch ($instance ['widget'] ['type']) {
  case 'my_widget' :
    if (empty ( $items )) {
      $output = generate_custom_output();
      $element[]['#markup'] = $output;
      $element ['#items'][] = array('value' => $output);
      $items[] = array('value' => $output);
    }
  break;
}

```

If anyone have better solution please provide.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: fetchAllAssoc() is returning only first row
I have a query like this:

```
  $product_classes = db_select('node_type', 't')->fields('t', array('name', 'type'))->condition('module','uc_product')
  ->execute()->fetchAllAssoc('orig_type', PDO::FETCH_ASSOC);

```

It will return an array with only first valid table row, however there are more valid rows.

If I use this query, without specified fields:

```
  $product_classes = db_select('node_type', 't')->fields('t')-:condition('module','uc_product')
  ->execute()->fetchAllAssoc('orig_type', PDO::FETCH_ASSOC);

```

It will return array with all the valid rows. It is a drupal bug?

# Answer
> 1 votes
The column name **orig\_type** used in `->fetchAllAssoc('orig_type')` must be included in

`->fields('p', array('name', 'type', 'orig_type))`

too, otherwise only one record will be returned.

# Answer
> 0 votes
Maybe the reason? "If the given key appears multiple times, later records will overwrite earlier ones." https://api.drupal.org/api/drupal/includes!database!database.inc/function/DatabaseStatementInterface%3A%3AfetchAllAssoc/7

---
Tags: database
---


# Question
Title: Add target="_blank" to menu item of type MENU_LOCAL_ACTION
How can I add a target="\_blank" property to a menu item of type MENU\_LOCAL\_ACTION ? I cannot do 'options' on MENU\_LOCAL\_TASK, MENU\_DEFAULT\_LOCAL\_TASK, and MENU\_LOCAL\_ACTION items. I tried with jQuery

```
(function($) {
    $(document).ready(function() {
        $('.page-admin-commerce-reports-incomplete-payments .action_links li a[href]').attr({
            target: "_blank",
            title: "Opens in a new window"
        })
    });
}(jQuery));

```

But it didn't work. Thanks!

# Answer
> 0 votes
There seems to be a module for this: Menu target.

In case you need to do it programmatically, you can have a look at the source code for inspiration. As far as I see, the module adds a special class to the menu items you select, and then some JS captures the click and opens a new window:

```
  $('a.target-blank', context).once('target-blank', function () {
    $(this).click(function() {
      window.open(this.href);
      return false;
    });
  });

```

# Answer
> 0 votes
So I misspelled the class name! `.action-links` **not** `.action_links` My fault, the jQuery code worked fine.

# Answer
> 0 votes
You could try Menu Attributes module. It works with Drupal 8 as far as I know

---
Tags: navigation
---