# Question
Title: Cannot create a views for show content revision
I got a problem when adding new view in
Home \> Administration \> Structure \> Views.
I insert options like this.

It shows (I applied Debug mode for look Stacktrace)

```
    The website encountered an unexpected error. Please try again later.</br>
</br><em class="placeholder">Drupal\Component\Plugin\Exception\PluginNotFoundException</em>: The "" plugin does not exist. in <em class="placeholder">Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition()</em> (line <em class="placeholder">52</em> of <em class="placeholder">core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php</em>). <pre class="backtrace">Drupal\Core\Plugin\DefaultPluginManager->getDefinition(NULL) (Line: 945)
Drupal\views\Plugin\views\wizard\WizardPluginBase->defaultDisplayFiltersUser(Array, Object) (Line: 904)
Drupal\views\Plugin\views\wizard\WizardPluginBase->defaultDisplayFilters(Array, Object) (Line: 725)
Drupal\views\Plugin\views\wizard\WizardPluginBase->buildDisplayOptions(Array, Object) (Line: 699)
Drupal\views\Plugin\views\wizard\WizardPluginBase->instantiateView(Array, Object) (Line: 1275)
Drupal\views\Plugin\views\wizard\WizardPluginBase->validateView(Array, Object) (Line: 167)
Drupal\views_ui\ViewAddForm->validateForm(Array, Object)
call_user_func_array(Array, Array) (Line: 83)
Drupal\Core\Form\FormValidator->executeValidateHandlers(Array, Object) (Line: 276)
Drupal\Core\Form\FormValidator->doValidateForm(Array, Object, 'view_add_form') (Line: 119)
Drupal\Core\Form\FormValidator->validateForm('view_add_form', Array, Object) (Line: 571)
Drupal\Core\Form\FormBuilder->processForm('view_add_form', Array, Object) (Line: 314)
Drupal\Core\Form\FormBuilder->buildForm('view_add_form', Object) (Line: 74)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 664)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)
</pre>

```

It tell The "" plugin does not exist. Any idea to find error cause for this problem. Thanks,

---

**More information**

occur on both Drupal version 8.5.1 and 8.5.3

I saw some solution in stack exchange. It solve by install GD library. but checked in Report status. it has already installed.

any advise solution.

# Answer
> 0 votes
The node\_revision table doesn't contain a column for type, so you can't add the content type filter here. So don't fill in a content type for now and create the View for all types. Then add a relationship to Content in the ADVANCED section. Now all node fields are available in the View and you can add a filter for the content type in FILTER CRITERIA.

---
Tags: views, 8
---


title: Live Inline Editing of Fields in Views

text:
# Question
Title: Live Inline Editing of Fields in Views
I know Drupal 8 has the quick edit module for inline editing, but how do you turn this feature on for a View that has fields where you can just click to edit it inline?

# Answer
Quick Edit of nodes in Views works. You can see this on the frontpage, which is a View.

However this works only for Views which show content.

If you have a View which shows content and want to choose the fields and customize the layout, you can create a custom viewmode, configure the fields there and put the layout in the twig files of the view mode.

Of course this does not provide all features of a View which shows fields and the module Editablefields. For this you would have to wait until this module is ported to D8.
> 4 votes

# Answer
views\_entity\_form\_field might become the replacement of editablefields module for views in Drupal 8.

> This module provides the ability to add form field widgets to a view to edit multiple entities at one time.
>
> Form field options will show up in a View's "Add field" list, prefixed with "Form field: " and then the name of the field being added.
> 1 votes

---
Tags: views, 8, entities
---


# Question
Title: Why won't custom field property values save if they are in a fieldset?
I'm creating a custom field for use with a bundle. I'm mentioning 'bundle' explicitly because the details of creating the field for use with an entity are slightly different.

* The module enables cleanly.
* The field table contains the property as defined in the field schema.
* The field name appears in the Add Field dialog.
* The field is added to a bundle cleanly, and its settings form contains the property in the default settings pane, properly.
* When content is created, the field and its property appear in the node edit form correctly.
* The node saves without throwing any errors.

When the node is saved and then re-edited, the field property is empty. In inspecting the field in the database, the instance meta such as bundle, and entity\_id are populated, but the property column is NULL.

***If the fieldset is removed, the value is saved as expected.***

Here is the field code: web/modules/custom/test\_video\_widget/src/Plugin/Field/FieldType/TestVideoWidgetField.php

```
<?php
namespace Drupal\test_video_widget\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
 * @FieldType(
 *   id = "test_video_widget",
 *   module = "test_video_widget",
 *   label = @Translation("Test Video Widget"),
 *   description = @Translation("This field stores video meta information."),
 *   default_widget = "TestVideoWidgetW",
 *   default_formatter = "TestVideoWidgetFormatter",
 * )
 */

class TestVideoWidgetField extends FieldItemBase {
    /**
     * {@inheritdoc}
     */
    public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {

        $properties = [];

        $properties['video_title'] = DataDefinition::create('string')
            ->setLabel(t('Video Title'))
            ->setDescription(t('Optional title to be displayed instead of the node title.'));

        return $properties;
    }

    /**
     * {@inheritdoc}
     */
    public static function schema(FieldStorageDefinitionInterface $field_definition) {
        $columns = array(
            'video_title' => array(
                'description' => 'Optional title to be displayed instead of the node title.',
                'type' => 'varchar',
                'length' => 255,
            ),
        );

        $schema = array(
            'columns' => $columns,
            'indexes' => [],
            //'foreign keys' => array(),
        );

        return $schema;
    }

```

Here is the field widget code that does NOT work: web/modules/custom/test\_video\_widget/src/Plugin/Field/FieldWidget/TestVideoWidgetW.php

```
<?php
namespace Drupal\test_video_widget\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 *
 * @FieldWidget(
 *   id = "TestVideoWidgetW",
 *   label = @Translation("Test Video Widget - Widget"),
 *   description = @Translation("Test Video Widget - Widget"),
 *   field_types = {
 *     "test_video_widget",
 *   },
 * )
 */

class TestVideoWidgetW extends WidgetBase {
  /**
   * {@inheritdoc}
   */
    public function formElement(
        FieldItemListInterface $items,
        $delta,
        array $element,
        array &$form,
        FormStateInterface $form_state
    ) {
        $element['video_meta'] = [
            '#type' => 'fieldset',
            '#title' => t('Video Meta'),
        ];

        $element['video_meta']['video_title'] = [
            '#type' => 'textfield',
            '#title' => t('Video Title'),
            '#default_value' => isset($items[$delta]->video_title) ? $items[$delta]->video_title : NULL,
            '#placeholder' => t(''),
            '#size' => 60,
        ];

        return $element;
    }
}

```

and here is the same method without the fieldset, which DOES work:

```
    public function formElement(
        FieldItemListInterface $items,
        $delta,
        array $element,
        array &$form,
        FormStateInterface $form_state
    ) {
        $element['video_title'] = [
            '#type' => 'textfield',
            '#title' => t('Video Title'),
            '#default_value' => isset($items[$delta]->video_title) ? $items[$delta]->video_title : NULL,
            '#placeholder' => t(''),
            '#size' => 60,
        ];

        return $element;
    }

```

also, the resulting field table for the field added to the bundle:

```
node__field_svideo;
+--------------------------------+------------------+------+-----+---------+-------+
| Field                          | Type             | Null | Key | Default | Extra |
+--------------------------------+------------------+------+-----+---------+-------+
| bundle                         | varchar(128)     | NO   | MUL |         |       |
| deleted                        | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id                      | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id                    | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode                       | varchar(32)      | NO   | PRI |         |       |
| delta                          | int(10) unsigned | NO   | PRI | NULL    |       |
| field_svideo_video_title       | varchar(255)     | YES  |     | NULL    |       |
+--------------------------------+------------------+------+-----+---------+-------+

```

# Answer
This is best resolved in the Widget Plugin as opposed to the FieldType so other widgets aren't adversely affect. Overwriting the `messageFormValues` method in your `TestVideoWidgetW` class will allow you to output the value the FieldType expects.

```
  /**
   * @inheritdoc
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    foreach ($values as &$value) {
      if ($value && array_key_exists('video_meta', $value)) {
        $value['video_title'] = $value['video_meta']['video_title'];
      }
    }
    return parent::massageFormValues($values, $form, $form_state);
  }

```
> 2 votes

# Answer
This added to the FieldType code resolves the issue:

```
public function preSave() {
    foreach ($this->values['video_meta'] as $key => $value) {
        $this->values[$key] = $value;
    }
}

```
> 0 votes

---
Tags: entities
---


# Question
Title: The test:run command is missing, but other commands work fine
I installed Drupal Console, put it on my path, ran `drupal init`, and successfully used Drupal Console to generate a module.

Now I want to run tests with `drupal test:run`, but I get this error.

> \[ERROR\] Command "test:run", is not a valid command name.

`drupal` lists many commands, but it is missing the ones for tests. This is a sample of the list.

```
 state
  state:delete (std)                      Delete State
  state:override (sto)                    Override a State key.
 taxonomy
  taxonomy:term:delete (ttd)              Delete taxonomy terms from a vocabulary
 theme
  theme:download (thd)                    Download theme in application
  theme:install (thi)                     Install theme or themes in the application
  theme:path (thp)                        Returns the relative path to the theme (or absolute path)
  theme:uninstall (thu)                   Uninstall theme or themes in the application
 update
  update:entities (upe)                   Applying Entity Updates
  update:execute (upex,updb)              Execute a specific Update N function in a module, or execute all
 user
  user:create (uc)                        Create users for the application
  user:delete (ud)                        Delete users from the application

```

Why are the commands for tests missing?

# Answer
> 0 votes
You need to enable Drupal Test module, then run drupal cache:rebuild, and command test:run will appear.

---
Tags: testing, console
---


# Question
Title: How to create an Ubercart add to cart button programmatically with defaults?
I am able to create an add to cart button:

```
$nid = 27;
$node = node_load($nid);
$add_to_cart = array(
    '#theme' => 'uc_product_add_to_cart',
    '#form' => drupal_get_form('uc_product_add_to_cart_form_' . $nid, $node)
);
return drupal_render($add_to_cart);

```

This gives me an add to cart button, but with no attributes selected. How can I alter this code to allow for the defaults to be set to specific values. For example, if I have an attribute with aid = 1, called "action", and two possible value... oid = 3 = register ... and oid = 4 = transfer..... of which I want the default to be "transfer" for example?

# Answer
I managed to use cart links instead:

```
/cart/add/p27_a6osfsdfsdfsdf_a7o706_a2o8_a1o515_q1-idomainName?destination=cart

```
> 0 votes

# Answer
This is the updated updated and more correct answer:

```
$node = node_load(123);
$drupalForm = drupal_get_form('uc_product_add_to_cart_form_' . $node->nid, $node);
$addToCartHTML = drupal_render($drupalForm);

```
> 0 votes

---
Tags: ubercart
---


# Question
Title: How to increase meta tag description field to 320 characters?
We are using metatag v8.x-1.5 on our D8 site (v8.5.3). When filling out the metatag description field, we enter any where from 180-320 characters into the field. However, when the page is displayed it is cutting off after 135 characters.

How can we increase the number of characters that are displayed?

Steps to reproduce:

1. Enter *"Compellingly re-engineer bleeding-edge interfaces whereas interoperable quality vectors. Uniquely incubate one-to-one action items before best-of-breed catalysts for change. Interactively."* into the Metatag Description field.

Current behavior:

`<meta name="description" content="Compellingly re-engineer bleeding-edge interfaces whereas interoperable quality vectors">`

Expected behavior:

`<meta name="description" content="Compellingly re-engineer bleeding-edge interfaces whereas interoperable quality vectors. Uniquely incubate one-to-one action items before best-of-breed catalysts for change. Interactively.">`

# Answer
I had to write a `hook_page_attachments_alter` for this

```
function mymodule_page_attachments_alter(array &$page) {
  foreach($page['#attached']['html_head] as &$html_head) {
    if($html_head[1] == 'description') {
      $html_head_content = $html_head[0]['#attributes']['content'];
      if(Unicode::strlen($html_head_content) > 320) {
        $html_head[0]['#attributes']['content'] = Unicode::truncate($html_head_content, 320);
      }
    }
  }
}

```
> 1 votes

---
Tags: 8, theming, meta-tags
---


# Question
Title: How to always require email verification before accessing a page?
I have a custom page defined by hook\_menu.

I want signed in users to be required to verify their email every time they want to access it. The page will have buttons on it that would allow someone to export all the data related to the account.

I've looked around for existing modules that could provide this. This looked the most promising: Email Required. However this only happens on their first visit to the page. So once the accounts email is verified the user would always have access to it.

How can I have people verify their email every time before allowing them to access the page? It would be good if the verification link in the email expired after a period of time if it isn't used for security.

Any pointers are much appreciated.

# Answer
Because the page I was creating was actually a form, I found this module got me out of trouble password\_require

Although strictly speaking my question didn't specify it was a form. Other than mentioning buttons.

Hope it helps someone
> 0 votes

---
Tags: 7, security
---


# Question
Title: How to show all revision(s) of current node?
I try to use filter criteria. It has filtering option with ID but I don't know how to use the current ID of Node.

Thanks

# Answer
> 2 votes
Just create a view with Show as "Content Revisions" like below

and select fields that are necessary to show. And under Relationship select Content under `Content revision` category.

And in contextual filters provide the default value for Content ID in URL.  After saving view goto blocks and enable it in node pages where you want to display.

---
Tags: views, 8
---


# Question
Title: Can't programmatically fill address field on taxonomy term creation
I'm creating some taxonomy terms inside of an update hook and they have a coordinates field and an address field containing only zipcode and locality.

The Vocabulary is called `cities`, the address field is called `field_cities_zip_city` and the coordinates are called `field_cities_coordinates`.

```
//the exact data that fails
$city = [
  'zip' => 1000,
  'name' => 'Lausanne',
  'lat' => '47.3879577',
  'lng' => '8.044136',
];

$term = Term::create([
  'name' => $city['zip'].' '.$city['name'],
  'vid' => 'cities',
  'field_cities_zip_city' => [
    'postal_code' => $city['zip'],
    'locality' => $city['name'],
  ],
  'field_cities_coordinates' => [
    'lat' => $city['lat'],
    'lng' => $city['lng'],
  ],
]);
$term->save();

```

What happens is, the term gets created, the coordinates get filled in properly, but the address remains empty despite even being required fields.

Trying like this did not change anything:

```
//the exact data that fails
$city = [
  'zip' => 1000,
  'name' => 'Lausanne',
  'lat' => '47.3879577',
  'lng' => '8.044136',
];

$term = Term::create([
  'name' => $city['zip'].' '.$city['name'],
  'vid' => 'cities',
  'field_cities_zip_city' => [
    'postal_code' => $city['zip'],
    'locality' => $city['name'],
  ],
  'field_cities_coordinates' => [
    'lat' => $city['lat'],
    'lng' => $city['lng'],
  ],
]);

//set the fields again manually, but this has no effect
$term->field_cities_zip_city->postal_code = $city['zip'];
$term->field_cities_zip_city->locality = $city['name'];

$term->save();

```

The address fields are still empty. What am I missing?? Thanks in advance for any help!

# Answer
> 3 votes
You need to provide the country\_code to your address field.

like

```
$city = [
  'zip' => 1000,
  'name' => 'Lausanne',
  'lat' => '47.3879577',
  'lng' => '8.044136',
];

$term = Term::create([
  'name' => $city['zip'].' '.$city['name'],
  'vid' => 'cities',
  'field_cities_zip_city' => [
    'country_code' => 'CH',  // country code is required
    'postal_code' => $city['zip'],
    'locality' => $city['name'],
  ],
]);
$term->save();

```

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


# Question
Title: textfield with #disabled = true, #input = false
A textfield with #disabled = TRUE will appear greyed out, and be unchangeable.

A textfield with #input = FALSE will not send its value to $form\_state\['values'\], and will be ignored by system\_settings\_form\_submit().

Unfortunately, a textfield with #disabled = TRUE and #input = FALSE no longer appears greyed out.

I want to make a textfield that is purely for display purposes, so a person can copy a value from there. What is the best way to do this?

EDIT I: What I tried so far

To clarify, my starting point is code like this:

```
$form['thetext'] = [
  '#type' => 'textfield',
  '#title' => t('The text'),
  '#disabled' => true,  // This should make it greyed out - but it doesn't due to #input = false below.
  '#input' => false,  // This should make this field ignored in $form_state['values'].
  '#value' => 'xyz',  // Either #value or #default_value.
];

```

EDIT II:

If this wasn't clear before: I really want the html output to be a textfield element. I also want to use the regular form + theme API, so that the element gets a label and wrapper div and theming like other form elements in the same form. E.g. if I would just hardcode the textfield html, it would no longer have the same classes, wrappers etc.

# Answer
> 2 votes
Use a markup element instead.

```
$form['element'] = array(
    '#type' => 'markup',
    '#markup' => 'This is the thing you want people to see. You can use <strong>html</strong>, too.',
);

```

You don't actually have to specify `#type => 'markup'` because drupal defaults to that type if you don't specify, but I do anyway as it seems to be good practice.

# Answer
> 0 votes
# input = FALSE is redundant if #disabled = TRUE. Whatever value is in the field will already be ignored if #disabled = TRUE.

---
Tags: 7, forms
---


# Question
Title: How Do I pass the Option description in Checkboxes to a webform result
I have a 3-option checkbox built as follows in Drupal 8.

How do I pass the value of the option title selected by the user into the webform submission result?

For example in the below, if a user chooses 21, the result should show 21 in the submission result.

```
[] 21
[] 22
[] 36

```

Each check box is a node field fld1, fld2, fld3. I have got these displaying correctly but the result shows up as \[fld1\] for option 21

**Additional details**

Here is the raw source generated by the webform module. This is Drupal 8 btw.

```
choose_a_value:
  '#type': checkboxes
  '#title': 'Choose a value'
  '#options':
    '[webform_submission:node:field_fld1:value]': '[webform_submission:node:field_fld1:value]'
    '[webform_submission:node:field_fld2:value]': '[webform_submission:node:field_fld2:value]'
    '[webform_submission:node:field_fld3:value]': '[webform_submission:node:field_fld3:value]'
   '#required': true
  '#required_error': 'Please choose a value'

```

# Answer
> 0 votes
It roughly depends on how you build that form element. Form API or Field API? Seems you are with Field API here. In general all you have to do is to provide an associative array for the options where key equals value.

### Form API

Here comes a simplified example for Form API. You might want to use `$options = array_combine($my_array, $my_array);` to build the options array dynamically.

```
$options = [
  '21' => '21',
  '22' => '22',
  '36' => '36',
];

$form['my_element'] = [
  '#type' => 'checkboxes',
  '#title' => 'Choose',
  '#options' => $options,
]

```

### Field API

With Field API and the list field you have to build the associated array in the `Allowed values list` like in the following example. Simply divide key and value with a pipe character.

```
21|21
22|22
36|36

```

---
Tags: 8, webforms
---


title: REST Basic Authentication not working

text:
# Question
Title: REST Basic Authentication not working
I configured my rest with services and installed the Basic authentication module.

I used Postman and selected basic authentication gave username and password, I got "Missing required argument username"

An important note is that If I change it to "no Auth" and send my username and password as JSON object it's authenticating, can someone help me? Thanks.

# Answer
Everything seems fine, as the response says, 'username' name/key is missing from the request. So construct a body request like follows or else follow the screenshot

```
{"username":'myusername', "password":"mypassword"}

```
> 0 votes

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


# Question
Title: Disabling reply link for comments not working
I would like to disable reply to comment for anonymous user.

I saw on sereval topics that you have to unset

> $variables\['content'\]\['links'\]\['comment'\]\['#links'\]\['comment-reply'\]

So I ended up adding a preprocess to the .theme file (bartik.theme since I'm using Bartik. Btw I'm using Drupal 8.5.3)

```
function bartik_preprocess_comment(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($variables['content']['links']['comment']['#links']['comment-reply']);
  }
}

```

Despite that preprocess, I still have the reply link when I'm anonymous. Does anyone has an idea about what's going on ?

# Answer
> 2 votes
You can use hook\_comment\_links\_alter() rather than THEME\_preprocess\_comment() .Where as hook\_comment\_links\_alter() will render all the comments links before build:

```
function YOURMODULE_comment_links_alter(array &$links, Drupal\comment\CommentInterface $entity, array &$context) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($links['comment']['#links']['comment-reply']);
  }
}

```

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


# Question
Title: Class declaration error when using ResourceBase
I tried following this guide: https://www.drupal.org/docs/8/api/restful-web-services-api/custom-rest-resources for the REST API.

However, when enabling the module, I get:

> Fatal error: Cannot declare class Drupal\my\_module\_rest\_api\Plugin\rest\resource\MyModuleResource, because the name is already in use in \[PATH\]\modules\my\_module\src\Plugin\rest\resource\MyModuleResource.php on line 0

It seems like it could be a simple class naming error, but I really tried following the guide to a tee. Here is `MyModuleResource.php` in full:

```
<?php

namespace Drupal\my_module_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a REST API Resource
 *
 * @RestResource(
 *   id = "my_module_resource",
 *   label = @Translation("My Module Resource"),
 *   uri_paths = {
 *     "canonical" = "/my_module_rest_api/my_module_resource"
 *   }
 * )
 */
class MyModuleResource extends ResourceBase {

    /**
     * Responds to entity GET requests.
     *
     * @return \Drupal\rest\ResourceResponse
     */
    public function get() {
        $response = ['message' => 'Hello, this is a rest service'];
        return new ResourceResponse($response);
    }
}

```

Here is the `rest.resource.my_module_resource.yml` file:

```
id: my_module_resource
plugin_id: my_module_resource
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - basic_auth

```

# Answer
> 0 votes
It looks like the problem was not with the REST API routes, but with the module name vs. namespace: in trying to pay attention to the details of the REST API extension, I missed that my module name was different from the namespace. In the above example, the module name is

> **my\_module**

while the namespace is

> Drupal\**my\_module\_rest\_api**\Plugin\rest\resource

---
Tags: 8
---


# Question
Title: Redirect to page after Simple News subscription
I wish to redirect the user to a specific page once they have inputted their email and pressed subscribe. Does anyone know how to achieve this please?

I have found the setting to achieve this but upon deeper digging it is not working. An issue has been opened here -\> https://www.drupal.org/project/simplenews/issues/2822420

# Answer
You do as follows:

> use Drupal\Core\Url;

```
function MODULENAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'FORM_ID') {
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_redirect_submit';
        }
    }
  }
}
/**
 * Add redirect to user after subscription.
 */
 function _redirect_submit(array &$form, FormStateInterface $form_state) {
    //If you know route name you can do like this
    $form_state->setRedirect(ROUTE_NAME); // example as "user.admin_create" redirects to user create page
    // If you have path do like below.
    $destination = "INTERNAL_URL";
    $url = Url::fromUri('internal:' . $destination);
    $form_state->setRedirectUrl($url);
 }

```
> 1 votes

# Answer
Please implement hook\_form\_alter() into your custom module..

```
/*
* Implement hook_form_alter()
*/
function custom_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_register_form':
        $form['#submit'][] = 'custom_form_submit';
      break;
  }
}

function custom_form_submit(&$form, &$form_state){
  return new RedirectResponse(\Drupal::url('user.page'));
}

```

Thank You.
> 0 votes

# Answer
This is what you need! https://www.drupal.org/project/redirect /. I made a redirect after subscribing with url mysite.com/node to anothersite.com .
> 0 votes

---
Tags: 8, emails
---


# Question
Title: Use Migrate to Import an RSS feed: get value of namespaced XML
I am trying to use the D8 core migrate module to import a feed. I followed this blog so I made a .yml file. It seems though that the xpaths I am using are incorrect. The import fails:

```
 [error]  Migration failed with source plugin exception: guid is defined as a source ID but has no value.

```

So the question is: How can I get, for example, the value of

```
<pro:id value="212149" />

```

I am aware of the namespaces, but I can't seem to figure out how to deal with them..;-(

This is (part of) the xml I am trying to parse:

```
<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005" xmlns:pro="http://schemas.stager.nl/2011">
    <id>tag:stager.nl,2011-05-01:https://example.stager.nl/web/feeds/events</id>
    <updated>2018-05-14T17:56:33+02:00</updated>
    <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/g/2005#event" />
    <title type="text">Stager event feed</title>
    <subtitle type="text">Events for example</subtitle>
    <generator version="1.0" uri="https://example.stager.nl/">stager</generator>
    <author>
        <name>example</name>
        <email>tickets@example.org</email>
    </author>
    <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="https://example.stager.nl/web/feeds/events" />
    <link rel="self" type="application/atom+xml" href="https://example.stager.nl/web/feeds/events" />
    <link rel="related" type="text/html" href="https://example.stager.nl/events/listmonth" />
    <link rel="related" type="text/calendar" href="https://example.stager.nl/web/calendar.ics" />
    <link rel="related" type="text/html" href="https://example.stager.nl/events/listweek" />
    <link rel="related" type="text/html" href="https://example.stager.nl/events/listday" />
    <entry>
        <pro:type value="event" />
        <pro:id value="212149" />
        <pro:eventGroupId value="213066" />
        <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact" />
        <title>House of bars</title>
        <pro:subtitle>Lorem Ipsum</pro:subtitle>
        <link rel="self" type="application/atom+xml" href="https://example.stager.nl/web/feeds/events/212149" />
        <link rel="alternate" type="text/html" href="https://example.stager.nl/events/212149" />
        <link rel="alternate" type="text/calendar" href="https://example.stager.nl/web/events/212149.ics" />
        <link rel="related" type="text/html" href="https://example.stager.nl/events/listday?month=5&year=2018&day=04" />
        <id>tag:stager.nl,2011-05-01:https://example.stager.nl/web/feeds/events/212149</id>
        <published>2018-03-20T17:17:16+01:00</published>
        <updated>2018-05-03T20:03:55+02:00</updated>
        <category scheme="http://schemas.stager.nl/2011#eventType" term="dancenight" label="Dancenight" />
        <pro:tags>rock, poop, </pro:tags>
        <gd:eventStatus value="http://schemas.google.com/g/2005#event.confirmed" />
        <pro:spaces>
            <pro:space>SUB</pro:space>
        </pro:spaces>
        <gd:where rel="http://schemas.google.com/g/2005#event" label="example">
            <gd:entryLink>
                <entry>
                    <title>example</title>
                    <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact" />
                    <gd:structuredPostalAddress primary="true">
                        <gd:street>ladida 39</gd:street>
                        <gd:city>Sometown</gd:city>
                        <gd:postcode>0000 AA</gd:postcode>
                        <gd:formattedAddress>example, ladida 39, 0000 AA Sometown </gd:formattedAddress>
                    </gd:structuredPostalAddress>
                    <summary>example, ladida 39, 0000 AA Sometown  </summary>
                </entry>
            </gd:entryLink>
        </gd:where>
        <gd:when startTime="2018-05-04T22:00:00+02:00" endTime="2018-05-05T02:00:00+02:00" />
        <gd:extendedProperty name="http://schemas.stager.nl/2011#doorsOpen">
            <gd:when startTime="2018-05-04T22:00:00+02:00" />
        </gd:extendedProperty>
        <pro:tickets isSoldOut="false">
            <pro:total>0</pro:total>
            <pro:remaining>0</pro:remaining>
        </pro:tickets>
        <link rel="hyperlink" href="https://www.example.net/" title="poop poop de doop" featured="false" />
        <link rel="audiolink" href="http://hcmaslov.d-real.sci-nnov.ru/public/mp3/Queen/Queen%20'A%20Kind%20Of%20Magic'.mp3" featured="false" />
        <link rel="videolink" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" featured="false" />
        <link rel="image" href="https://example.stager.nl/images/7/eventpublicationitem/320078/Screen Shot 2018-05-01 at 13.18.21.png" featured="false" />
        <content type="html"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer pulvinar nibh nec ante eleifend pulvinar. Nulla molestie vel justo ac faucibus. Duis consectetur eu ipsum at dictum. Suspendisse convallis hendrerit leo a molestie. Quisque sollicitudin felis velit, nec laoreet massa tincidunt et.</p><p>Aenean nec gravida mi, sodales hendrerit purus. Mauris gravida risus ipsum, sit amet porta tellus vehicula feugiat. Donec posuere fringilla sapien vel vestibulum. Nunc nec scelerisque ligula. Donec vitae tempus nulla, rhoncus egestas lacus. Nulla rutrum nec nulla ut ullamcorper. Ut consectetur blandit libero non eleifend. Duis ut rutrum sem. Sed dapibus lectus vel metus dictum euismod. Donec at purus vitae elit mattis consequat fringilla quis massa. Nam at velit sed lorem ultricies semper. Quisque viverra congue mi, at venenatis purus vehicula nec.</p></content>
    </entry>
</feed>

```

My .yml is this:

```
id: stager_events_importer
label: 'Import examples Stager Atom feed'
status: true

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  namespaces:
      atom: 'http://www.w3.org/2005/Atom'
      gd: 'http://schemas.google.com/g/2005'
      pro: 'http://schemas.stager.nl/2011'
  urls: 'https://example.stager.nl/web/feeds/events'

  item_selector: '/feed/entry'
  fields:
    -
      name: guid
      label: GUID
      selector: '/pro:id@value'
    -
      name: title
      label: Title
      selector: 'title'
    -
      name: pub_date
      label: 'Publication date'
      selector: 'published'
    -
      name: type
      label: Type
      selector: 'pro:type@value'
    -
      name: category
      label: Category
      selector: 'category[2]@term'
    -
      name: tags
      label: Tags
      selector: 'pro:tags'
    -
      name: body
      label: Body
      selector: 'content'

  ids:
    guid:
      type: string

destination:
  plugin: 'entity:node'

process:
  title: title
  field_type: type
  body: body
  created:
    plugin: format_date
    from_format: 'D, d M Y H:i:s O'
    to_format: 'U'
    source: pub_date
  status:
    plugin: default_value
    default_value: 1
  type:
    plugin: default_value
    default_value: event

```

I looked here, but I did not get it yet.

I have a contenttype 'event' with fields corresponding to the ones referenced in the process config of the yml.

# Answer
> 0 votes
Turns out it was mostly an indentation problem: the namespaces were two tabs in, instead of 1

```
namespaces:
      atom: 'http://www.w3.org/2005/Atom'
      gd: 'http://schemas.google.com/g/2005'
      pro: 'http://schemas.stager.nl/2011'

```

should be:

```
namespaces:
  atom: 'http://www.w3.org/2005/Atom'
  gd: 'http://schemas.google.com/g/2005'
  pro: 'http://schemas.stager.nl/2011'

```

Then the value of ID is:

```
-
      name: guid
      label: GUID
      selector: 'pro:id/@value'

```

and the title (this is catchy!, notice the 'atom:' prefix)

```
-
      name: title
      label: Title
      selector: 'atom:title'

```

Also this needs to be added (if, of course, there are no dependencies):

```
migration_dependencies:
  required: {}

```

---
Tags: migrations
---


# Question
Title: Fatal error: Call to undefined function node_type_get_names() Drupal 7.59
I upgraded my Drupal site to Drupal 7.59 and now the site is down.

Fatal error: Call to undefined function node\_type\_get\_names() in D:\Development\xampp\htdocs\biobank\modules\comment\comment.module on line 119

List of installed modules:

1. admin\_menu
2. autocomplete\_deluxe
3. autologout
4. better\_exposed\_filters
5. bootstrap\_fieldgroup
6. chosen
7. conditional\_fields
8. ctools
9. date
10. devel
11. empty\_front\_page
12. entity
13. entityreference
14. entityreference\_autocreate
15. exclude\_node\_title
16. field\_collection
17. field\_collection\_table
18. field\_collection\_views
19. field\_group
20. field\_validation
21. jquery\_update
22. mass\_pwreset
23. module\_filter
24. msnf
25. restrict\_ip
26. securelogin
27. security\_review
28. termcase
29. title
30. token
31. unique\_field
32. vefl
33. views
34. views\_bootstrap
35. views\_data\_export
36. webform

# Answer
> 1 votes
Can't comment but I don't see the `Node` module. Its part of the core and should be present(thats where the missing function is defined). Verify that the module is present and permissions are set right

---
Tags: 7, comments
---


# Question
Title: Migrate Alt and Title text from a image file field
I'm trying to migrate a multi-value D6 image field to D8. I've already migrated the files with d6\_file and it worked. When I do the node migration with the image field works and I get all the values but the alt and title text are not migrated.

```
  field_image:
    plugin: sub_process
    source: field_image
    process:
      target_id:
        plugin: migration_lookup
        migration: upgrade_d6_file
        source: fid
      alt: alt
      title: title

```

# Answer
So this worked for me not sure why. But my file migration id was `upgrade_d6_file` and when I change this in line 54 of Drupal\file\Plugin\migrate\process\d6\FieldFile and ran the migration with the settings below I got the correctly referenced files and the alt/title text.

Diff

```
  // Configure the migration process plugin to look up migrated IDs from
  // a d6 file migration.
  $migration_plugin_configuration = $configuration + [
-   'migration' => 'd6_file',
+   'migration' => 'upgrade_d6_file',
    'source' => ['fid'],
  ];

```

Migrate yml

```
field_primary_image:
    plugin: d6_field_file
    source: field_image
    process:
      target_id:
        plugin: migration_lookup
        migration: upgrade_d6_file
        source: fid
      alt: alt
      title: title

```

Or even better is write your own process plugin like this: https://github.com/mikeryan776/d8-migrate-example-001/blob/master/migrate\_carlyle/src/Plugin/migrate/process/CarlyleCckFile.php
> 0 votes

---
Tags: 8, files, migrations
---


# Question
Title: How do I get the vocabulary of a term inside an "article" type content type?
I have a content type tagged with various vocabularies. Each vocabulary has terms which I want to style with particular colours based on the vocabulary. For example, say I have a "Fruits" vocab which has term 'apple' and 'banana' and a "veggies" vocab with 'onion' and 'carrot'. I want to colour the apple and banana tags RED and the onion and carrot tags BLUE \*in same node. Say I've a content type "article" which is tagged with apple from the fruits vocab and carrot from the veggies vocab. 'apple' should have a RED background and 'carrot' and BLUE background. Another content node has apple and banana for tags and they should both be RED.

I've found the following code, but it only works when the page I am viewing is the "apple" page - that is, I'm reading the page for the vocab term apple, NOT a content type tagged with apple. It DOESN'T work for tags in other content types and I'm failing miserably to find the right code.

```
function MYTHEME_preprocess_field__entity_reference(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
  // load the term entity and get the data from there
  $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
  $variables['vocab'] = $term->bundle();
  }
}

```

My theme has custom twig files for field--entity-reference.html.twig

and I'm trying to use the preprocess function above. Nothing I can find anywhere addresses this; what gives?

# Answer
Just in case someone comes along here, I've left the other answer (now below), but have since found a better solution.

Instead of using the `field--entity-reference.html.twig` I'm now using field.html.twig. I suspect that eventually this might lead to an 'include' or 'embed' solution, but I'm not there yet.

For now, since my "tags" will never show labels, I only use this code in the field.html.twig file @ `{% if label_hidden %}`. The code is copied twice (which I don't like and which makes me want to find a different, cleaner solution), once for `{% if multiple %}` and again for if not multiple, since a node may only have one tag, or several.

Here is the code:

```
{% if label_hidden %}
{% if multiple %}
<div{{ attributes.addClass(classes, 'field--items') }}>
  {% for item in items %}
  {% set mylabel %}
      {{ item.content }}
  {% endset %}
  {% set myclass %}
    {{ item.content['#options'].entity.vid.0.value['target_id'] }}
  {% endset %}
  {% set cls %}
  {{ ('field_' ~ myclass)|trim }}
  {% endset %}
  {% set cls = cls|replace({' ':''}) %}
  {% if (field_name|trim == cls|trim ) %}
  {% set myclass = myclass|replace({'_':'-'}) %}
  <div{{ item.attributes.addClass('taxonomy--item') }}>
    <a class="btn-small tag-{{ myclass|trim }}" href="{{ item.content['#url'] }}" role="button">{{ mylabel|striptags }}</a>
  </div>
  {% else %}
  <div{{ attributes.addClass(classes, 'field--item') }}>{{ item.content }}</div>
  {% endif %}
  {% endfor %}
</div>
{% else %}

```
> 0 votes

# Answer
Adding the answer now. My final code in the field--entity-reference.html.twig file:

```
{% for item in items %}
  {% set mylabel %}
    {{ item.content }}
  {% endset %}
  {% set myclass %}
    {{ item.content['#options'].entity.vid.0.value['target_id'] }}
  {% endset %}
  {% set myclass = myclass|replace({'_':'-'}) %}
    <div{{ item.attributes.addClass('taxonomy--item') }}>
      <a class="btn-small btn-primary tag-{{ myclass|trim }}" href="{{ item.content['#url'] }}" role="button">{{ mylabel|striptags }}</a>
    </div>
{% endfor %}

```

HERE is the code needed in a node to access the parent vocabulary of the taxonomy terms in the node. (That is, individual tags on a content type node).

```
item.content['#options'].entity.vid.0.value['target_id']

```

*NOTE: This is on Drupal 8.5.3 and none of my "tags" have more than one parent.*
> 0 votes

---
Tags: theming, taxonomy-terms
---


# Question
Title: Don't allow role to delete published content even its their own
thanks for reading my question.

I am currently working on Drupal 8 site, please consider the following roles:

```
Admin - Can do everything
Publisher - can do everything the Admin can do, except set up and edit new
administrators
Editor - Can do everything the publisher can do, except Publish content to live
Writer - Can do everything the Editor can do, except Delete published content

```

I have managed to satisfy the permission for the roles `Admin`, `Publisher`, and `Editor`, now it seems the `Writer` one is tricky.

The only option seems like to `Enable Delete own content` for `Writer`, but that won't solve the issue if his article was already published, he can delete it.

Is there a module that can be solved by this? Or a better approach on how to configure permissions?

Regards,

# Answer
> 1 votes
Simply search for and disable the permission "Delete any content" for any / all content types for the role of "writer".

This is also a very handy module to help you find permissions https://www.drupal.org/project/permissions\_filter

---
Tags: 8, users
---


# Question
Title: Which host do I need to fill in the database connection?
So I have made a local Drupal site and now I'm moving it to my webhost. In the database connection array:

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'localhost',
);

```

So I filled in all my credentials (driver, database, username,...) but what do I need to fill in after 'host'? Can I just leave it 'localhost' or do I need to fill in the host of my webhosting?

# Answer
It will depend on your hosting setup and where the DB is located. The `host` value can be:

* A reachable hostname where the PHP code is running (e.g. `localhost` for your local server)
* An IP address (e.g. `127.0.0.1`, the ip address normally used for `localhost`),
* A fully qualified domain name (e.g. `my-data-base-host.example.com`)

Consult your hosting provider on retrieving your DB host connection credentials.
> 3 votes

# Answer
You have to give like below for the remote server of drupal8.

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

```

You have to give host is webhost.like (wcs-xxxxx).
> 0 votes

# Answer
In the host, you need to add your host IP Address like:

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb',
  'username' => 'username',
  'password' => 'secret',
  'host' => '111.111.111.111',
);

```
> -2 votes

---
Tags: database
---


# Question
Title: Fatal error: Call to a member function extractFormValues()
I created a module with Drupal 8 beta11 which defines an content entity and a form (contentEntityForm) with custom submit callback.When I tried using the same module with Drupal 8 beta 14 it raise the following error.

> Fatal error: Call to a member function `extractFormValues()` on null in C:\xampp\htdocs\drupalbeta14\core\lib\Drupal\Core\Entity\ContentEntityForm.php on line 219

The form code is the following one.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['employee']['first_name'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#required' => TRUE,
  );

  $form['employee']['last_name'] = array(
    '#type' => 'textfield',
    '#title' => 'Last Name',
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#name' => 'employee-data',
    '#submit' => array('::submitEmployeeData')
  );

  return $form;
}

public function submitEmployeeData(array $form, FormStateInterface $form_state) {
}

```

After the form is submitted, the error mentioned above is shown.

I checked the *contentEntityForm.php* file on beta11 and beta14 and it seems to have a similar definition for `extractFormValues()`.

# Answer
> 0 votes
This question is old but I stumbled across this issue as well, so posting the solution for future googlers..

Basically, you need to init the form\_state within the buildForm method with:

```
if (!$form_state->has('entity_form_initialized')) {
  $this->init($form_state);
}

```

I found this solution here: https://withpulp.com/blog/drupal-forms-api/#initialize-the-form-state

When extending the ContentEntityForm class the parent buildForm normally handles this for you, but if for some reason you choose not to extend the buildForm you will need to init the form\_state yourself.

---
Tags: 8, forms
---


# Question
Title: How can I prevent text areas from being resizable?
Text areas in Drupal 7 are resizable by default. I would like to turn this off, but when I checked a text area with Firebug, I couldn't find the CSS that was making it resizable.

How can I prevent text areas from being resized?

# Answer
It's JS that makes the text areas resizable, not CSS. I think the simplest way to disable this behaviour for all textareas is to implement `THEMENAME_textarea()` in your theme and remove it there:

```
function THEMENAME_textarea($element) {
  $element['element']['#resizable'] = false ;
  return theme_textarea($element) ;
}

```
> 18 votes

# Answer
If you only need CSS3 compatibility, you can use the following CSS:

```
textarea { resize: none; }

```

Or if you need to disable resize on a specific textarea, add the ID of that text area:

```
.edit-body-und-0-value { resize:none }

```
> 4 votes

# Answer
Overriding this in the theme is a last minute change, which modules won't have a chance to react on.

It's just as easy to do this via a module and a `#process` callback:

```
/**
 * Implements hook_element_info_alter()
 */
function custom_element_info_alter(&$types) {
  $types['textarea']['#process'][] = 'custom_process_textarea';
}

/**
 * A custom callback to disable "grippies" on textareas.
 */
function custom_process_textarea($element) {
  $element['#resizable'] = FALSE;
  return $element;
}

```

This gives modules like Wysiwyg a chance to notice that a textarea should not have a grippie, so it can avoid to attach that behavior when disabling an editor.
> 1 votes

# Answer
Implement this in your THEME. It will force the `#resizable` to `FALSE` and prevent the JS and markup from rendering.

```
/**
 * Implements template_preprocess_textarea().
 */
function THEME_preprocess_textarea(&$variables) {
  // Hide grippie.
  $variables['element']['#resizable'] = FALSE;
}

```

The accepted answer is close but theme\_\* functions shouldn't be called directly as they may bypass process/preprocess functions unintentionally
> 1 votes

# Answer
You can add custom inline CSS to your form, to hide the grippies:

```
$form['#attached']['css'][] = array(
  'data' => '.resizable-textarea .grippie { display: none; }',
  'type' => 'inline',
);

```
> 1 votes

# Answer
A new module called Disable Resizable Textarea was release now.

> This is a simple module that add ability to override the default #resizable property of textarea fields. By default, all textareas are resizable. This module allows you to disable this feature on each field.

It is very easy to set up. Just edit the desired field and you will see an "Disable #resizable property of this textarea" option. You can also disable resizable from its summary, if the field is of type "Long text with summary".
> 0 votes

# Answer
You can do form alter of node or comment.

Check out the sample code and comments below:

```
$form['body'][LANGUAGE_NONE][0]['value']['#resizable'] = FALSE;

```

For mozilla and chrome, we can still see the issue. place css hack.

```
textarea {
 resize: none;
 }

```
> 0 votes

# Answer
I was recently solving this problem too and found out these 2 solutions:

First one I prefer the most: Use this code in your theme's `template.php` and all grippies and textarea.js will disappear:

```
/**
 * Override of theme('textarea').
 * Deprecate misc/textarea.js in favor of using the 'resize' CSS3 property.
 */

function THEMENAME_textarea($variables) {
  $element = $variables ['element'];
  element_set_attributes($element, array('id', 'name', 'cols', 'rows'));
  _form_set_class($element, array('form-textarea'));

  $wrapper_attributes = array(
    'class' => array('form-textarea-wrapper'),
  );

  $output = '<div' . drupal_attributes($wrapper_attributes) . '>';
  $output .= '<textarea' . drupal_attributes($element ['#attributes']) . '>' . check_plain($element ['#value']) . '</textarea>';
  $output .= '</div>';
  return $output;
}

```

Don't forget to change THEMENAME to your theme name and flush all caches.

Second way is to install module Disable resizable textarea but I try to keep number of modules in my installations as low as possible.
> -1 votes

---
Tags: 7, theming
---


title: Showing flagged content to users

text:
# Question
Title: Showing flagged content to users
I have flagged contents in a block.But only admin can see the these flagged contents(contents are product variations).I want to show these contents to all authenticated users and anonymous users.Is it possible?Can you help me to solve this issue.

# Answer
> 0 votes
Sounds like a permission issue, each flag you create has it's own permission settings. Have a look under `admin/people/permissions`

---
Tags: commerce, flags
---


# Question
Title: Access violation error on any page or drush
Recently started working with an inherited Drupal 8 website which I am trying to get up and running on my Mac OS X (Sierra) but I am getting this error with a stack trace every time I try run `drush` or simply visit the website. Any pointers on what is causing this and possibly how to fix would be appreciated.

```
    jc@~/Development/Sites/example-website/web $ drush
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1231 Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER' in     [error]
/Library/WebServer/Documents/example-website/web/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php:170
Stack trace:
#0 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(170): PDO->exec('SET sql_mode =
...')
#1 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Core/Database/Database.php(376):
Drupal\Core\Database\Driver\mysql\Connection::open(Array)
#2 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Core/Database/Database.php(166):
Drupal\Core\Database\Database::openConnection('default', 'default')
#3 [internal function]: Drupal\Core\Database\Database::getConnection('default')
#4 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php(79):
call_user_func_array('Drupal\\Core\\Dat...', Array)
#5 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Component/DependencyInjection/Container.php(177):
Drupal\Component\DependencyInjection\PhpArrayContainer->createService(Array, 'database')
#6 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php(264):
Drupal\Component\DependencyInjection\Container->get('database', 1)
#7 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php(62):
Drupal\Component\DependencyInjection\PhpArrayContainer->resolveServicesAndParameters(Array)
#8 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Component/DependencyInjection/Container.php(177):
Drupal\Component\DependencyInjection\PhpArrayContainer->createService(Array, 'cache.container')
#9 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Core/DrupalKernel.php(508):
Drupal\Component\DependencyInjection\Container->get('cache.container')
#10 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/lib/Drush/Drupal/DrupalKernel.php(53):
Drupal\Core\DrupalKernel->getCachedContainerDefinition()
#11 /Library/WebServer/Documents/example-website/web/core/lib/Drupal/Core/DrupalKernel.php(461):
Drush\Drupal\DrupalKernel->initializeContainer()
#12 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/lib/Drush/Boot/DrupalBoot8.php(146): Drupal\Core\DrupalKernel->boot()
#13 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/includes/bootstrap.inc(354):
Drush\Boot\DrupalBoot8->bootstrap_drupal_full()
#14 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/includes/bootstrap.inc(509): drush_bootstrap(5, 7)
#15 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/commands/core/help.drush.inc(103): drush_bootstrap_max()
#16 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/includes/command.inc(422): drush_core_help()
#17 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#18 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/includes/command.inc(199): drush_command()
#19 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#20 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/includes/preflight.inc(66):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#21 /Library/WebServer/Documents/example-website/web/vendor/drush/drush/drush.php(12): drush_main()
#22 {main}

```

settings.local.php db details (Minus password obviously)

```
$databases['default']['default'] = array (
    'database' => 'example_website_drupal_db',
    'username' => 'exsiteuser',
    'password' => 'xxxxxxxxxx',
    'prefix' => '',
    'host' => '127.0.0.1',
    'port' => '3306',
    'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
    'driver' => 'mysql',
);

```

Apache is running PHP 7.0

Drupal Version: 8.2.7

MySql version: 8.0.11

Drush version 8.1.16 (I get an error trying to install 9 via composer)

Composer install has been run to get modules.

# Answer
> 1 votes
Drupal 8 doesn't support MySQL 8 yet. See this issue for the details.

For now you'll either need to downgrade to an earlier DBMS version, or apply the patch in the above issue.

---
Tags: database, configuration
---


title: How to get query result in devel?

text:
# Question
Title: How to get query result in devel?
In Admin we have

http://domain.com/devel/php

I added query

```
$result = db_query("SELECT name FROM `users_field_data`");

print ($result);

```

It's not showing result. How to show that?

# Answer
Enable the Kint module (comes with devel) then do

`kint($result->__toString());` or `kint($result->arguments());`
> 0 votes

# Answer
Using the module Devel Kint, you can use it to dump the variable to the screen.

```
kint($result);

```

If you do not have Devel Kint enabled, or simply want a different option, this page shows all the different ways you can debug using the Devel module.

http://ratatosk.net/drupal/tutorials/debugging-drupal.html
> 0 votes

# Answer
In the devel module, we can't use the print. like below, we have to use.

```
 $query = db_select('users_field_data', 'n');
    $query  ->fields('n', array('name ', 'name'));
    $result = $query->execute()->fetchAll();
   dpq($query); // Display the query.

   dvr($result);// Dispaly the result

```
> 0 votes

---
Tags: 8
---


# Question
Title: Read only version of node form for anonymous users?
Use case: a site that accepts applications for courses. Users need to register first before they can create an application (for security, spam etc.) - however the registration process might put them off; can anyone suggest a way to preview the form?

Requests to '/node/add/application' obviously get Access Denied when not logged in, because Anonymous Users don't have the "Application: Create new content" permission.

# Answer
> 0 votes
> can anyone suggest a way to preview the form?

The no code way would be to use screen shots (images).

Alternatively, you could check if the user is logged, it they are not then unset the submit button via a hook\_form\_alter.

> prevent someone from circumventing it by submitting the form manually

Better yet, if user is anonymous, you alter the callback function of the submit button by unsetting the existing one and adding a new custom callback.

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


title: Role based User profile template

text:
# Question
Title: Role based User profile template
I would like to have a different user template for each role, but I can't figure it out how do do it.

I've added a preprocess function in my themename.theme like this:

```
function ras_preprocess_page(&$variables) {

    $variables['role'] = \Drupal::currentUser()->getRoles();
}

```

and then used role in my user.html.twig like this:

```
{% if role == 'administrator' %}
   <p>Hello, admin</p>
{% elseif role == 'anonymous' %}
   <p>Hi, stranger</p>
{% endif %}

```

But it doesn't work as I would expect.

# Answer
> 2 votes
You can use hook\_theme\_suggestions\_HOOK\_alter() like below:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEME_NAME_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  $roles = \Drupal::currentUser()->getRoles();
  if (in_array('YOUR ROLE',$roles)) {
    $suggestions[] = 'user__'.ROLENAME;
  }
}

```

and you have to create

> user--YOURROLE.html.twig

in order to get a specific template for the user based on their role.

---
Tags: 8, theming
---


# Question
Title: Mapping or migrating path alias using using Migrate Source CSV
I am importing content from SharePoint into Drupal 8 using Migrate Source CSV and a large CSV file. I successfully mapped id,title,body,date. But I cannot map the path alias? In Drupal 7 the Feeds module mapped this easily. Does anyone know how to do this in Drupal 8?

This is a snippet from my yml file:

```
process:
  id: id
  nid: nid
  title: title
  alias: path
destination:
  plugin: entity:node

```

my csv file

```
"id","nid","title","body","path","date"
"1","1","title1","bodytext","content/12/mypath","2014-08-12"

```

# Answer
> 7 votes
@Jigar's answer is close but not quite. Here is what I eventually figured out. It should be path/alias and not just path. Also, if you have pathauto module installed it will create the path based on the patterns. So, in order for our path to be imported from csv, the path auto needs to be disabled first. You set path/pathauto's default value to 0 to do that.

```
source:
...
 constants:
  slash: '/'
....
process:
...
 path/pathauto:
   plugin: default_value
   default_value: 0 # Disable pathauto
 path/alias:
   plugin: concat
   source:
     - constants/slash
     - url

```

# Answer
> 6 votes
Just tried it out while trying to find an answer to a similar question. Here's how it should look:

```
source:
  ...
  constants:
    slash: '/'
process:
  ...
  // This parameter should be "path" and not "alias".
  path:
    plugin: concat
    source:
      - constants/slash
      - path

```

**Note:** Path aliases get imported the first time you import the data. However, if you run `drush migrate-import MIGRATION-ID --update`, the path aliases do not get updated.

# Answer
> 1 votes
I haven't tried mapping paths in a node migration myself (the core upgrade path migrates aliases separately), but I will observe one thing - the path needs to start with '/', so you should use the concat process plugin to prepend that.

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


# Question
Title: D8 - How to modify url params on form submit?
Im using form\_alter on a views exposed filter form. There are 2 date fields (start-date and end-date) which are exposed filters that Ive hidden from the user. I want to populate the url argument of these 2 fields when the form is submitted.

Ive tried both methods using a submit and validation callback but neither seems to work.

My form\_alter is:

```
function mymodule_form_views_exposed_form_alter(&$form,
  FormStateInterface $form_state, $form_id) {
    if ($form['#id'] == 'views-exposed-form-my-form-id') {
  ...
  ...

  $form['#submit'][] = '_my_custom_submit';
  $form['#validate'][] = '_my_custom_validate';
}

```

My callback looks like:

```
function _my_custom_validate($form, FormStateInterface $form_state) {

  // Pass date range selection to date fields.
  $date_range = $form_state->getValue('date-range');
  $date_range_split = explode(":", $date_range, 2);
  $start_date = $date_range_split[0];
  $end_date = $date_range_split[1];

  $form_state->setValue('start-date', $start_date);
  $form_state->setValue('end-date', $end_date);

  $input = &$form_state->getUserInput();
  $input['start-date'] = $start_date;
  $input['end-date'] = $start_date;
  $form_state->setUserInput($input);
}

```

When I dpm() any of my vars above I see the data but I can not get it passed into the url's arg on submit so I keep getting http://domain.com&start-date=&end-date=

How can I populate/modify the url args after the user clicks submit but before the page reloads?

If theres any other info that I can provide that may be helpful, please let me know.

Thanks!

# Answer
> 0 votes
You might have a logic-error in

```
$input['end-date'] = $start_date;

```

should be this:?

```
$input['end-date'] = $end_date;

```

How ever you can add a parameter with "query-\>add":

```
\Drupal::request()->query->add(['start-date' => $start_date, 'end-date' => $end_date]);

```

Note that you "mix" POST and GET - variable. So in your "submitForm" - method you need to process the GET - variables by yourself.

# Answer
> 0 votes
I was hoping there was a more drupal way to do this without js but ended up just using js to populate the fields before form is submit.

---
Tags: forms
---


# Question
Title: How to allow any file extension (or use a blacklist instead of a whitelist) for file fields in Drupal 8?
For a file field, it’s required to enter file extensions in "Allowed file extensions".

Is there a way to allow *any* file extension? Or a way to switch from a whitelist to a blacklist?

### What I found

# Answer
Implement a hook alter on the node form or the field level and in it change the validator to your custom function:

```
/**
 * alter form field element:.
 *
 * Implements hook_FORM_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
    $upload_validators = array(
        'my_module_file_validate_extensions_blacklist' => ['jpg jpeg gif png mp4']
    );
    $form['your_file_field_element']['#upload_validators'] = $upload_validators;

}

```

Alternatively you can change the behavior of the field on any node, or entity by altering the widget form:

```
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
   if ( "condition to check if it's your field" == TRUE) {
     $upload_validators = array(
            'my_module_file_validate_extensions_blacklist' => ['jpg jpeg gif png mp4']
        );
        $element['#upload_validators'] = $upload_validators;
  }
}

```

Then write you own function to do what you want:

```
function my_module_file_validate_extensions_blacklist(stdClass $file, $extensions) {
  $errors = array();
  $regex = '/\\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  if (preg_match($regex, $file->filename)) {
    $errors[] = t('files with the following extensions are not allowed: %files-allowed.', array(
      '%files-allowed' => $extensions,
    ));
  }
  return $errors
}

```
> 2 votes

---
Tags: 8, entities, files
---


# Question
Title: Why am I getting a "You are not authorized to access this page." on the Drupal Migrate UI page?
I just installed this module on my Drupal 8 site hosted locally on Acquia Dev Desktop. I haven't had this issue with any other modules and this is occurring immediately after I install the module.

# Answer
> 0 votes
Are you logged in? Is your login the superuser? You can always get into your local site w/ drush:

```
$ cd /path/to/docroot
$ ../vendor/bin/drush uli --no-browser
http://default/user/reset/1/1527085618/[RANDOM_STRING]/login

```

Assuming your setup uses the drupal-project composer approach. Otherwise, you could use drush w/ a site alias or params.

If you're logged in as the superuser and still have issues, that's indicative of something wrong w/ the routing specification. That shouldn't happen with a contrib module, unless you've made any modifications? If you haven't and the superuser can't access the UI, then I would file an issue w/ the migrate module.

---
Tags: 8, migrations, upgrading
---


# Question
Title: How to configure htaccess to redirect ALL traffic through https?
I'm looking for a way to redirect users to https://domain.com whether they type the www or not

I'm using a shared host for a drupal website so i don't have access to virtual host config files. A let's encrypt certificate if included with the hosting package
Right now the website can be accessed both with http and https depending on what you type in the browser.
In looking for a solution to force redirection to https i found this section in the in the .htaccess file that redirects users who type the www. to https://domain.com

```
# To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
   RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
   RewriteRule ^ https%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

```

Now i'm looking for a way to redirect when typing http://domain.com without the www.

Do i need to put another rule somewhere in addition to the line i uncommented or is there some other way to do this ?

# Answer
> 1 votes
You could use something like this:

```
 RewriteCond %{HTTPS} !=on
 RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L,NE]

```

# Answer
> 0 votes
I'm using this piece of code for both situations (with and without www.):

RewriteCond %{HTTPS} off \[OR\] RewriteCond %{HTTP\_HOST} ^www.DOMAINNAME.com\* RewriteRule ^(.\*)$ https://DOMAINNAME.com/$1 \[L,R=301\]

And it works fine

---
Tags: 7, ssl
---


title: Get Last Register User's ID

text:
# Question
Title: Get Last Register User's ID
I am trying to retrieve the details of the last user who registered to the site. There is a similar question here: How to get the uid of a newly created user? but it assumes that the registration is also done programmatically, while I don't have any such assumption.

The only way I saw how to do it was to go to the DB directly (not recommended by basically every resource I read). Is there a way to do this through some other interface?

# Answer
You don't need to query the DB directly, you can use an entity query:

```
$uids = \Drupal::entityQuery('user')
  ->sort('created', 'DESC')
  ->range(0, 1)
  ->execute();
$uid = reset($uids);

```
> 0 votes

---
Tags: 8, users
---


# Question
Title: Upgrading Drupal 7.43 to 8 error: Source database is Drupal version 8 but version 7 was selected
I am new to Drupal, but I am trying to upgrade a site with the version 7.43 to 8, flowing these steps: https://www.drupal.org/docs/8/upgrade/upgrade-using-web-browser

After installing the Migrate modules and defining the source site, I have the following error message:

> Source database is Drupal version 8 but version 7 was selected.

In my old site's database, the drupal\_version table is empty.

Any help?

# Answer
I managed to solve it. It was caused be an update on PHP, that caused blank pages or “white screen of death” (WSOD) in the admin, too. After updateing to 7.59, everithing was OK. This article helped me: https://www.drupal.org/node/158043
> 0 votes

---
Tags: migrations, upgrading
---


# Question
Title: How can i prove that the activation link sent to subscriber (anonymous user) has actually been activated?
Where can i find a log entry or related information documenting that the activation link in the confirmation mail sent to simplenews-subscribers has been activated?

# Answer
> 0 votes
You can check the Status of your subscribers by going to People \> Newsletter subscriptions (`/admin/people/simplenews`).

---

There are 4 places within Drupal admin navigation that Simplenews entries are interspersed into:

* Configuration » Web services » Newsletters (`/admin/config/services/simplenews`) for **creating different Newsletters** (you want at least one)
* Structure » Content types » Simplenews newsletter (`/admin/structure/types/manage/simplenews`) to choose and edit a **Content type to use for the newsletter content**
* People » Newsletter subscriptions (`/admin/people/simplenews`) to list and filter all **your Subscribers**
* Content » Newsletters (`/admin/content/simplenews`) to see all the created **Newsletter issues** and their status

---
Tags: emails, notifications
---


title: AJAX callback: error with firefox

text:
# Question
Title: AJAX callback: error with firefox
I've a custom callback with a form which works well in last chrome and last FF.

```
$form['foo']['bar'] = array(
  '#type' => 'submit',
  '#value' => t(''),
  '#attributes' => ['class' => array('search-api glyphicon glyphicon-refresh btn-primary')],
  '#ajax' => [
    'callback' => '::fetchApiData',
    'event' => 'click',
    'effect' => 'none',
    'progress' => [
      'type' => 'throbber',
      'message' => NULL,
    ],
  ],
);

```

However, my customer has a old version of firefox, the **esr 45.9.0** version, and when we click on the button that trigger the callback, we have an alert error.

> An error occurred while attempting to process /declaration?ajax\_form=1&\_wrapper\_format=drupal\_ajax: invalid regular expression flag a

Does anybody know how to debug this?

# Answer
This issue is related to drupal/boostrap theme. It doesn't occur with default drupal theme.
Replace methods in Attributes.cleanClass pass the identifier as a 3rd parameter isn't needed because string replacements in JS are chained. https://www.drupal.org/project/bootstrap/issues/2969106
> 1 votes

---
Tags: 8, forms, ajax
---


title: Thickbox with Ajax loaded images

text:
# Question
Title: Thickbox with Ajax loaded images
I using ThickBox to display large image when thumbnails are clicked. This works great with static content that;s loaded with the page.

However, I'm now trying to use Ajax calls to display some of the content, as it involves API calls that can slow down the page generation. I've placed a small JQuery document.ready script like this:

```
Drupal.behaviors.brickFilterBehavior = function (context)  {
  var element = this;
  $('.brick-filter-test').each(function () {
    var element = this;
    $.get('/brick_filter/test/', function(data) {
      element.innerHTML = data;
    });
  });
});

```

This fetches HTML from the URL and inserts it into a `<div>` with the class "brick-filter-test". The handler for the URL looks like this:

```
function lego_filter_test()
{
  // Print out HTML directly.
  print ('<a href="https://images.brickset.com/sets/images/928-1.jpg" rel="lightbox" title="Space Cruiser And Moonbase"><img src="https://images.brickset.com/sets/small/928-1.jpg" alt="Space Cruiser And Moonbase" class="lego-filter-set-image"></a>');
  // Return success.
  exit(0);
}

```

The real handler uses API calls to generate the content, so I've simplified for this example. This just returns a static HTML snippit.

On my test page, I have the following HTML:

```
<div>
  <a title="Space Cruiser And Moonbase" href="https://images.brickset.com/sets/images/928-1.jpg" rel="lightbox">
    <img src="https://images.brickset.com/sets/small/928-1.jpg" alt="Space Cruiser And Moonbase" class="lego-filter-set-image">
  </a>
</div>
<div class="brick-filter-test">Loading test content...</div>

```

You can see this in action here: http://www.neoclassicspace.com/test

In the example, I have two thumbnail images, one statically included in the page, the other dynamically loaded. The static one behaves correctly, and the ThickBox pop-up gets applied. The dynamic one isn't getting the Thickbox treatment, even though it uses the same HTML.

I have tried adding alerts into the JS for both my code and Thickbox, and this has shown that my code runs before Thickbox initialises, so my dynamic DOM objects should be present when it runs.

I've also tried adding `Drupal.behaviors.initThickbox(context);` to the end of my function, which should cause Thickbox to reinitialise. I've confirmed this runs twice with an `alert` statement when I do this.

I'm really appreciate any suggestions on this.

Thanks,

James

# Answer
You need to add the behaviors like this:

```
Drupal.attachBehaviors($('.ajax-container'));

```

So looks like in your case it would be:

```
Drupal.attachBehaviors($('.brick-filter-test'));

```

This should do the trick

```
$.get('/brick_filter/test/', function(result){
  element.innerHTML = data;
  Drupal.attachBehaviors($('.brick-filter-test'));
});

```
> 1 votes

---
Tags: 6, javascript
---


title: Add datepicker to view exposed filter

text:
# Question
Title: Add datepicker to view exposed filter
I have a view and an exposed filter with a date field, I want to make this filter as a date picker, not a text field, I've used Better Exposed Filters but didn't find anything in view, I had used it much time in D7 but In D8 cannot find it in the view exposed form style. So what should I do to use this module

# Answer
You can add the jquery date picker in for that page as dependency.

### your\_theme.libraries.yml

```
date-picker:
  js:
    script/site-datepicker.js : {}
  dependencies:
    - core/jquery
    - core/jquery.ui.datepicker

```

### site-datepicker.js

```
Drupal.behaviors.customDatepicker = {
  attach: function (context, settings) {
    jQuery(function () {
      jQuery("#datepicker").datepicker({
        dateFormat: "dd-mm-yy",
        altField: "input[data-drupal-selector=edit-created]",
        altFormat: "yy/mm/dd 23:59:59"
      });
    });
  }
};

```

### views-exposed-form--views-block-name.html.twig

```
{% if q is not empty %}
  {#
    This ensures that, if clean URLs are off, the 'q' is added first,
    as a hidden form element, so that it shows up first in the POST URL.
  #}
  {{ q }}
{% endif %}

<input id="datepicker" type="text">
<input data-drupal-selector="edit-created" data-msg-maxlength="This field field has a maximum length of 128." name="created" size="30" maxlength="128" aria-invalid="false" type="hidden">
{{ form|without('created') }}

```

There is also the Date Popup module, for Drupal 8. You can use that module and implement this functionality.
> 5 votes

---
Tags: 8, views
---


# Question
Title: Including static pages in the search index?
I've got a page set up like this:

```
$items['mypage'] = array(
  'title' => 'My Page',
  'page callback' => 'mymodule_mypage',
  'access callback' => TRUE,
);

```

and then

```
function mymodule_mypage() {
    return 'This is a test! Also, pollywog.';
}

```

Now, if I go to /search/node/pollywog, I would like to see the above page as one of the search results. I currently don't, because I assume search just covers database content. Is there a way to make it also include specific pages? Something like the below would be amazing:

```
$items['mypage'] = array(
  'title' => 'My Page',
  'page callback' => 'mymodule_mypage',
  'access callback' => TRUE,
  'includeInSearchIndex' => TRUE, // <<----- this!!
);

```

Would it be possible to build in something like "includeInSearchIndex" and then make that index the static page?

# Answer
> 0 votes
Your module needs to implement hook\_search\_info, hook\_update\_search and as part of that hook call search\_index and then fully define how the content is indexed.

Out of interest why don't you just create static pages as regular nodes?

---
Tags: 7, search
---


title: Additional twig suggestions for menus

text:
# Question
Title: Additional twig suggestions for menus
Unlike other elements, the base twig suggestions for menus are only "menu.html.twig" and "menu-\[menu\_name\].html.twig".

I am aware that I can generate additional suggestions through the hook `THEME_theme_suggestions_menu_alter`, but the `$variables` array does not contain any useful data. Case in point, I want to retrieve the current region, is it possible?

# Answer
> 4 votes
All steps described here work for me with some minor modifications.

GOAL: show main menu in both header and footer region, but use a different template file for both (based on their region). PREMISE: your theme has regions (like header and footer) and you have used the drupal block system to place the main menu in both your header as in your footer.

I did this in mytheme.theme file: Dont forget to add the Block use statement in the beginning of your .theme file:

```
use Drupal\block\Entity\Block;

```

Now here's the magic for region based menu templates. Also inside your .theme file:

```
/**
 * Implements hook_preprocess_HOOK().
 *
 * Pass block region value to content so this can be used in
 * MYTHEME_theme_suggestions_menu_alter.
 */
function MYTHEME_preprocess_block(&$variables) {
  if (isset($variables['elements']['#id'])) {
    $region = Block::load($variables['elements']['#id'])->getRegion();
    $variables['content']['#attributes']['region'] = $region;
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 *
 * Provide region based menu suggestions.
 */
function MYTHEME_theme_suggestions_menu_alter(&$suggestions, array $variables) {
  if (isset($variables['attributes']['region'])) {
    $suggestions[] = 'menu__' . $variables['menu_name'] . '__' . $variables['attributes']['region'];
  }
}

```

RESULT when inspecting the main menu inside the header:

```
<!-- FILE NAME SUGGESTIONS:
* menu--main.html.twig
* menu--main--header.html.twig
* menu.html.twig
-->

```

RESULT when inspecting the main menu inside the footer:

```
<!-- FILE NAME SUGGESTIONS:
* menu--main.html.twig
* menu--main--footer.html.twig
* menu.html.twig
-->

```

# Answer
> 3 votes
There are a couple of functions that seem like they can help here:

function hook\_theme\_suggestions\_HOOK\_alter

function hook\_theme\_suggestions\_alter

This blog post has a useful (if a little bit hacky) way of adding to the template suggestions based on block ID.

http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion

He suggests using `hook_preprocess_block()` to add the block ID to the variables array and then using `hook_theme_suggestions_HOOK_alter()` to add that ID to the theme suggestions for the menus.

```
/**
 * Implements hook_preprocess_block().
 */
function THEMENAME_preprocess_block(&$variables) {
  $variables['content']['#attributes']['block'] = $variables['attributes']['id'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  // Remove the block and replace dashes with underscores in the block ID to
  // use for the hook name.
  if (isset($variables['attributes']['block'])) {
    $hook = str_replace(array('block-', '-'), array('', '_'), $variables['attributes']['block']);
    $suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
  }
}

```

So you'll end up with an additional `menu--MENU-NAME--BLOCK-NAME.html.twig` template possibility. It's a neat trick and works well!

# Answer
> 2 votes
Confirming $variables\['attributes'\] is always empty in 8.2.x, so there's insufficient contextual info to form a new suggestion

I solved by installing the menu block module, which adds an field for Theme Hook Suggestion for the menu.html.twig into the edit screen for each menu block.

# Answer
> 1 votes
You can't get any extra info in suggestions alter, like context. But it's possible to inject suggestions when you render any thing in Drupal 8.

Normally you would do something like this:

```
$variables['menu'] = [
  '#theme' => 'menu',
  ...
];

```

Code like this, will probably be inside a menu block, but it could be anywhere.

What you can do to achieve your goal is to change the theme call:

```
$variables['menu'] = [
  '#theme' => 'menu__header',
  ...
];

```

Doing the above will add the *header* suggestion to *menu* template. I'm not sure how to best accomplish the above.

1. You should subclass the menu block and change the code a bit
2. I'm not sure that you can get the region the block is placed in on redner. Otherwise you can add the suggestion as a setting which is configured on the block along with the other menu settings.

# Answer
> 0 votes
Basically the workaround suggested by featherbelly does work on a Drupal 8.2.7, but it's really hacky and the attributes possibly will also get rendered unless you explicitly unset them again. If they do get rendered this will cause invalid markup.

Using menu\_block as suggested by user73304 is way the better option here and it gives you full control of which template is used for any menu via the UI, which is great and better than hacky code that might not work anymore in future versions.

---
Tags: theming
---


title: Anonymous Users to view PRODUCTS

text:
# Question
Title: Anonymous Users to view PRODUCTS
I have enabled "View all products product" -- I have disabled sql rewriting.

Although I still cannot get anonymous users to VIEW ANYTHING in the store. Because of the ADMIN overlay?

# Answer
> 0 votes
It sounds like you aren't very clear on what that permission does vs. how products are displayed. I'm guessing here that you're using Drupal 7. If so, it seems your problem is you're trying to expose the admin paths to products to customers, but those paths aren't intended to be viewed by them. Instead, you're supposed to create either a View that renders product entities directly or a node type with a product reference field on it that functions as what we called a product display. When you attach a product reference field to a node type, it supports embedding product fields into that node while rendering the field itself as an Add to Cart form.

There are a variety of tutorials / guides to understanding and implementing this on the project website: https://drupalcommerce.org

When you need to grant that permission and / or disable SQL rewriting is when you have a View that creates a relationship between your node type (or order line items) to product entities. In that case, though, the View should have additional filters on it to apply appropriate access control so customers only have access to view in that context the products or line items they should.

---
Tags: commerce
---


# Question
Title: How to rename or choose twigs file name suggestions?
When I create a custom block called `Lorem ipsum Dolor`, I have not the possibility to choose the machine name. So when I have to make a twig template, the file suggestion is :

> block—loremipsumdolor.html.twig

I mean it is without undescore. I found it hard to handle all these twig file when I work on a custom template. It is not human friendly readable.

Is there a way to choose the name of the file name or the block machine name ?

Other example :

> Block name : Custom Search form

```
<!-- FILE NAME SUGGESTIONS:
   * block--customsearchform.html.twig
-->

```

I have not this problem with node :

> node--13--teaser.html.twig

# Answer
Given a block name of 'Custom Search form', you can add to the file name suggestions using a preprocess hook in your theme.

An example of code to add to the `.theme` file:

```
/**
 * Add an alternative to file name suggestions the Custom Search form block.
 *
 * Implements hook__suggestions_HOOK_alter().
 * @return array Suggestions.
*/
function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
    if($variables['elements']['#id'] == 'customsearchform'){
        $suggestions[] = 'block__custom_search_form';
    }
}

```

This will result in an additional file name suggestion:

```
<!-- FILE NAME SUGGESTIONS:
   * block--custom-search-form.html.twig * block--customsearchform.html.twig
-->

```
> 4 votes

---
Tags: theming, blocks
---


# Question
Title: Validate a file extension using getMimeType
I want to create a hook that will validate a file upload and only allow jpg extension or a multiple array jpg, gif. I am not sure how to do this. If this below can validate the length of the file title.

```
if (strlen($file
 ->getFilename()) > 100) {
    $errors[] = t("The file's name exceeds the 100 characters limit.");
 }

```

Then can something simular to this work?

```
use Drupal\Core\Form\FormStateInterface;
 function blank_moda_file_validate(Drupal\file\FileInterface $file) {
   $errors = array();

if ($file
 ->getMimeType()) !== jpg, gif) {
   $errors[] = t("The file is not a jpg or gif.");
}

```

# Answer
You can use file\_validate\_extensions() for this
> 1 votes

---
Tags: 8, forms
---


# Question
Title: custom field - How to get saved term selected for entity_autocomplete
I've looked all over, and for my level of understanding, I can't figure out how to get the stored value of an entity autocomplete field targeting taxonomy term type. I thought I could do something similar to what I have for select field, but it breaks the page. This is for a custom field...

```
    $element['description_term'] = array(
      '#type' => 'entity_autocomplete',
      '#target_type' => 'taxonomy_term',
      '#selection_settings' => [
        'target_bundles' => [
          'descriptors'
        ],
      ],
      '#title' => t('descriptor'),
      'default_value' => previously-entered-value,
      // this didn't work... '#default_value' => isset($items[$delta]->descriptor) ? $items[$delta]->descriptor : NULL,
      '#required' => FALSE,
  );

```

# Answer
> 0 votes
with some help above from Ajay Reddy, I was able to finally get to something that worked... Here's what did it:

> '#default\_value' =\> \Drupal\taxonomy\Entity\Term::load($items\[$delta\]-\>description\_term),

---
Tags: 8, entities
---


# Question
Title: Most efficient way to do simple Entity API queries by node id and content type?
A very basic 8.x API question.

What is the approved/simplest methods of confirming a node matching a certain content type and ID exists, and then loading it as an object?

(Use case: a module which accepts a node ID in the URL, that needs to be checked.)

Currently I have:

```
$node = \Drupal::entityTypeManager()->getStorage('node')->load(123);

if ($node->getType() == 'application') {
  return $node;
} else {
  return false;
}

```

My first attempt was in reserve (longer/less efficient):

```
$nids = \Drupal::entityQuery('node')
  ->condition('type', 'application')
  ->condition('nid', 123)
  ->execute();

// followed by entityTypeManager()->getStorage('node') etc.

```

But I was wondering if there was a way to make entityQueue() return a **flat** array of IDs rather than an associative `[1=>1,2=>2,3=>3]` which you then have to mess around with.

# Answer
> 6 votes
I don't know how your module URL/API is structured, but if your module route has something like `myapi/foo/bar/(id)` to return a node object, you could upcast it instead. Here is an example from the node module:

```
entity.node.version_history:
  path: '/node/{node}/revisions'
  defaults:
    _title: 'Revisions'
    _controller: '\Drupal\node\Controller\NodeController::revisionOverview'
  requirements:
    node: \d+

```

`{node}` will be upcast to a node object and available in the incoming request to the receiving class.

See: https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes

So when you pass that to the receiving method:

```
use Drupal\node\NodeInterface;

class ExampleController {
  public function foo(NodeInterface $node) {
    if ($node->getType() != 'application') {
      // do something, throw Exception, etc?
    }

    // Otherwise this node is an application type.
    return $node;
  }
}

```

There may be a way to expand on this in the route definition, so you can upcast the node *and* ensure it is a specific type before doing anything else, eliminating the checking in the method - but I am not sure.

Perhaps:

# Answer
> 2 votes
> What is the approved/simplest methods of confirming a node matching a certain content type and ID exists, and then loading it as an object?

I could easily be wrong, but I'm not sure there is one, really. It depends how you define "simplest".

Personally I'd test the object type first:

```
$node = \Drupal::entityTypeManager()->getStorage('node')->load(123);
if ($node instanceof \Drupal\node\Entity\Node && $node->getType() == 'application') {

}

```

If you're just talking about performance between the two different approaches, then yes, the first approach is better as it requires at most one query, whereas the second requires two.

> rather than an associative \[1=\>1,2=\>2,3=\>3\] which you then have to mess around with.

I'm not sure what you mean by that; an associative array is exactly the same as a "flat" array in that example - just ignore the keys or values as required.

# Answer
> 2 votes
I'd do this:

```
$nid = 123;
$type = 'application';
$node_exists = (bool) db_query('SELECT 1 FROM {node} WHERE nid = :nid AND type = :type', [':nid' => $nid, ':type' => $type)->fetchField();

if ($node_exists) {
  return node_load($nid);
}

return FALSE;

```

# Answer
> 2 votes
I'm using EntityStorageBase::loadByProperties, because it's flexible and lightweight in my eyes. It returns an array, so you can use reset() to get the node if exists:

```
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'nid' => $nid,
  'type' => 'application'
]);
if ($node = reset($nodes)) {
  // do something
}

```

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


title: how to get the date value in drupal 8

text:
# Question
Title: how to get the date value in drupal 8
On submitting a form getting error as

Error: Call to a member function format() on null.

Here is the function:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  $exp_date = $form_state->getValue('expire_date')->format('H:i:s');
}

```

# Answer
As mentioned by @awm in the comment you have to use the DateFormatter service. But the format() method needs a timestamp so you can use strtotime() to parse the value:

```
$exp_date = \Drupal::service('date.formatter')
  ->format(strtotime($form_state->getValue('expire_date')), 'H:i:s');

```
> 0 votes

---
Tags: 8
---


# Question
Title: CAS module - disabling auto login / want nonpersistent cookies - deleted when browser closes
Our security team says we need to modify the cas module so that it either deletes the session cookies when the browser closes or use a session variable rather than a cookie. I can't figure out how to satisfy their requirements. I don't see such a setting in the cas module.

Currently, the cas module auto logs in users even though the Gateway autologin setting is disabled. The security team says this is OK on the first load but after the browser is closed, the site is not reauthenticating but instead relying on the cookie which is not acceptable. I don't know how they know this is what is happening.

I'm using Drupal 8.5.3.

It seems to me that the CAS settings under Configuration -\> CAS

Gateway Feature (Auto Login)
when the radio button "disable gateway feature" is checked, that users should be required to login but though this option is checked, they are not required to login.

The cas module READ.md file writes this about the Gateway feature,
"This feature is not currently compatible with any form of page caching."

Page caching is disabled in settings

```
$settings['cache']['bins']['render'] = 'cache.backend.null';

```

Dynamic Page cache is also disabled

```
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

In addition, the CAS settings "Forced Login" is enabled.

php.ini has cookie lifetime set to 0

; Lifetime in seconds of cookie or, if 0, until browser is restarted.

```
session.cookie_lifetime = 0

```

Thanks for any help.

---

Resolved:

I resolved this issue by making the following changes to the following files:

core.services.yml
default.services.yml
services.yml

```
# Set session cookie lifetime (in seconds), i.e. the time from the session
# is created to the cookie expires, i.e. when the browser is expected to
# discard the cookie. The value 0 means "until the browser is closed".
# @default 2000000
cookie_lifetime: 0

```

# Answer
> 0 votes
Not sure if this would meet your requirements but look at the require\_login module. I'v done CAS and Shib authenticated sites using this module.

My solution was to have an excluded custom login page that was set up as the user login path in this module. This page generally had the welcome / security blurb and a button that linked to the Authentication agent (CAS / Shib). I seem to remember having to custom craft this to include the page to return to after login.

The part that might not work for you is that if a user had authenticated via CAS on another site and then came to this site, they did not see this page but where autologged into Drupal.. after all CAS, Shib, and the like are Single Sign On solution.. ;)

This might work for you with the Gateway option off.

Otherwise you might have to look at creating a custom event subscriber that handles the CAS authentication. E.g., if a user logs in and they are a CAS user, send them to the login page. Set some flag on the login page and then allow them to "login".

---
Tags: users, cookies
---


# Question
Title: Drupal 7 Views filter criteria Entity Reference
At the moment i'm making a drupal environment.

I'm trying to reach the following:

"Use a views to show my content types, but only the content types that have lets say "ads" as a field\_type (Entity Refrence)."

Setup:

* Content Type: Packets
    + Title
    + Image
    + Entity Reference field\_type to Content type: packets\_types..

It gives me blank result.. the sort criteria is just working fine on thee Pakket\_type

I've tried the Relationships, but this didn't changed anything for me.

If there is someone out there to help me, i would love that =)

Already thanks!

# Answer
> 0 votes
Correct me if Im wrong but I think the problem is that Type Reference filed is actually node id.

What worked for me is the following:

1. Add a relationship from the Type Reference field.
2. Add the field you are trying to use as filter and use relationship from (1). Set your operator and value.
3. Profit!

P.S. It seems that using Taxonomy terms would be a better solution though i have no idea what you are trying to achive.

---
Tags: 7, views, nodes, entities
---