# Question
Title: Constructing array of term reference labels in php template?
I'm currently trying to set up a simple LMS and have already defined a content type `course` that contains a *term reference field* `accesstags`, which I would like to use for defining view permissions. I.e. the field `accesstags` will contain multiple terms that will be linked to roles that should have access to the node in question.

To make a long story short: I have created a custom module that contains the function `hook_entity_view_mode_alter` and I would like to check, whether the term reference field `accesstags` contains the term *"subscription"*:

```
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  ...
  if (in_array('subscription', ?????)) {
    ... allow access ...
  }
  ...
}

```

However, I'm not sure what to put at the spot that I marked with "?????". I know that I can construct the array of referenced terms by using `$entity->get('field_accesstags')->referencedEntities()`... but this array then contains the whole structure, whereas I only need the array of labels.

Is there an easy way for getting this array? Maybe even a built-in function?

Any help would be much appreciated.

# Answer
Following @4k4's suggestion to post the final code as an answer myself... here's the code that I'm now using and that seems to work well...

First of all, I defined a simple helper function:

```
function getTermName($term) {
  return($term->getName());
}

```

This allowed me to extend my code (see my original question above):

```
function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  ...
  $accesstags = array_map("getTermName", $entity->get('field_accesstags')->referencedEntities());
  if (in_array('subscription', $accesstags)) {
    ... allow access ...
  }
  ...
}

```

I'm still wondering, if there is a simpler way (without having to iterate over the array of terms), but for now the solution works well. Thanks again for your help, @4k4.
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: lost password "user-pass" form no more redering
We didn't touch our templates and the "lost password" form is no more rendering. here is my template code working fine with `$login_form`.

```
<div id="login-container">
    <div class="login-hint">
      <p><?php echo t('Pour vous connecter, veuillez indiquer votre adresse email (login) et votre mot de passe')?></p>
    </div>
    <?php
      $login_form['name']['#attributes']['placeholder'] = t('Login');
      $login_form['pass']['#attributes']['placeholder'] = t('Mot de passe');
      print drupal_render($login_form);
    ?>
</div>
<div id="password-container">
    <div class="pass-reset-hint"><?php echo t('Indiquez votre adresse e-mail de connexion, et vous recevrez un nouveau mot de passe')?></div>
    <?php
      $reset_pass_form['name']['#attributes']['placeholder'] = t('Addresse e-mail');
      //print drupal_render(drupal_get_form('user_pass'));
      print drupal_render($reset_pass_form);
    ?>
</div>

```

I also tried directly the following :

```
print drupal_render(drupal_get_form('user_pass'));

```

Here is the result of `print_r($reset_pass_form);` so, the it exists :

```
Array
(
    [#form_id] => user_pass
    [#type] => form
    [#build_id] => form-na8Ow30ky69azZcTP7vQ_BijkXKobSuPFtmsajrNveM
    [form_build_id] => Array
        (
            [#type] => hidden
            [#value] => form-na8Ow30ky69azZcTP7vQ_BijkXKobSuPFtmsajrNveM
            [#id] => form-na8Ow30ky69azZcTP7vQ_BijkXKobSuPFtmsajrNveM
            [#name] => form_build_id
            [#parents] => Array
                (
                    [0] => form_build_id
                )

            [#input] => 1
            [#process] => Array
                (
                    [0] => ajax_process_form
                )

            [#theme] => hidden
            [#defaults_loaded] => 1
            [#tree] =>
            [#array_parents] => Array
                (
                    [0] => form_build_id
                )

            [#weight] => 0
            [#processed] => 1
            [#required] =>
            [#attributes] => Array
                (
                )

            [#title_display] => before
            [#ajax_processed] =>
            [#sorted] => 1
        )

    [form_id] => Array
        (
            [#type] => hidden
            [#value] => user_pass
            [#id] => edit-user-pass
            [#parents] => Array
                (
                    [0] => form_id
                )

            [#input] => 1
            [#process] => Array
                (
                    [0] => ajax_process_form
                )

            [#theme] => hidden
            [#defaults_loaded] => 1
            [#tree] =>
            [#array_parents] => Array
                (
                    [0] => form_id
                )

            [#weight] => 0.001
            [#processed] => 1
            [#required] =>
            [#attributes] => Array
                (
                )

            [#title_display] => before
            [#name] => form_id
            [#ajax_processed] =>
            [#sorted] => 1
        )

    [#id] => user-pass
    [#method] => post
    [#action] => /login
    [#theme_wrappers] => Array
        (
            [0] => form
        )

    [#tree] =>
    [#parents] => Array
        (
        )

    [#validate] => Array
        (
        )

    [#submit] => Array
        (
        )

    [#theme] => Array
        (
            [0] => user_pass
        )

    [#processed] =>
    [#defaults_loaded] => 1
    [#required] =>
    [#attributes] => Array
        (
        )

    [#title_display] => before
    [#array_parents] => Array
        (
        )

    [#sorted] => 1
    [#attached] => Array
        (
            [js] => Array
                (
                    [0] => Array
                        (
                            [type] => setting
                            [data] => Array
                                (
                                    [urlIsAjaxTrusted] => Array
                                        (
                                            [/login] => 1
                                        )

                                )

                        )

                )

        )

)

```

Is it an update issue or anonymous user rights issue?

I'm on 7.58

Can you help me?

# Answer
> 0 votes
actually the user/password is accessible for everyone (unless some custom code changes this behaviour)

if the form elements are present in DOM but are not displayed, i would check if there is some custom css that hides it somehow.

---
Tags: views, theming, forms
---


# Question
Title: How to display node's first created date
There are options in views to display date regarding Node:

* Authored On : Displays When node was published, its modifiable, hence not a true created date.
* Changed : Displays last updated date.

Same fields are available for Content Revision, but i wonder if i can get created date of first Revision in views.

Any thoughts?

# Answer
> 0 votes
Created date of the First revision of a node is the node creation date.

---
Tags: views, 8
---


# Question
Title: Rendered entity reference field (list-group) disappears, when user can't access the referenced items. Why?
I have been trying to find the reason for this problem for a few days now... without any luck. Which is why I would like to ask for help here...

In a nutshell: I'm working on a simple LMS and have defined a content type `Course` that contains an entity reference field `field_lessons`, which refers to another content type `Lesson`. In the template file `node--course--full.html.twig` I'm using the following code to render a "table of contents" in the sidebar:

```
...
<aside>
  {{ content.field_lessons }}
</aside>
...

```

In addition I'm using a template file `field--node--field-lessons--course.html.twig` for rendering the field:

```
...
<nav class="list-group">
  {% for item in items %}
    {% if (item.viewaccess) %}
      <a class="list-group-item list-group-item-action" href="...">
    {% else %}
      <span class="list-group-item list-group-item-action disabled">
    {% endif %}
      <div class="list-group-item-heading">
        {{ item.title }}
      </div>
      ...
    {% if (item.viewaccess) %}
      </a>
    {% else %}
      </span>
    {% endif %}
  {% endfor %}
</nav>
...

```

(Note that I deliberately left out a few insignificant details in the code: These are marked with "...".)

So, depending on whether the current user can access a single lesson (I'm using the variable `item.viewaccess`, which depends on `hook_node_access()` and is set in `hook_preprocess_node()`), each lesson is rendered as *active* or *disabled* `list-group-item`. So far, this works perfectly.

Something weird happens, however, as soon as **all** lessons are locked for the current user: In this case, none of the lessons gets rendered and **the whole table of contents** (i.e. the whole `<nav>` block) **disappears**.

I'm totally stumped at this point. Can anyone offer an idea as to why this happens? Any help would be much appreciated.

# Answer
> 3 votes
FWIW :

The entity reference field formatters that are in core use the method getEntitiesToView() (From class EntityReferenceFormatterBase) to load the referenced entities.

This method honors entity access :

```
$access = $this->checkAccess($entity);
// ...
if ($access->isAllowed()) {
  // ...
     $entities[$delta] = $entity;
    }
//...
return $entities;

```

so yes, it seems normal that nothing is rendered.

---
Tags: 8, theming, nodes
---


# Question
Title: How to add one entity reference field that can reference either a node or a user?
I'm looking to create an entity reference field that can reference either nodes from a specific bundle, or users. Is their a way to do this either with a module , or programmatical,y?

# Answer
> 0 votes
I do not think you can do this with the Entity reference module. Look at its code:

```
/**
 * Implements hook_field_info().
 */
function entityreference_field_info() {
  $field_info['entityreference'] = array(
    'label' => t('Entity Reference'),
    'description' => t('This field reference another entity.'),
    'settings' => array(
      // Default to the core target entity type node.
      'target_type' => 'node',
      // The handler for this field.
      'handler' => 'base',
      // The handler settings.
      'handler_settings' => array(),
    ),
    'instance_settings' => array(),
    'default_widget' => 'entityreference_autocomplete',
    'default_formatter' => 'entityreference_label',
    'property_callbacks' => array('entityreference_field_property_callback'),
  );
  return $field_info;
}

```

I suggest you try a work-around. For example, you could create a content type that includes two entity-reference fields, one of type Node and one of type User. Maybe, for convenience, include a boolean or integer field indicating which of the two to use. Then use references to your new content type where you want to use node-or-user entity references.

Alternatively, you could use the Field collection module, which works the same way, creating node types to handle collections of fields: https://drupal.org/project/field\_collection.

# Answer
> 0 votes
For D8 this is now possible with the Dynamic Entity Reference field:

https://www.drupal.org/project/dynamic\_entity\_reference

---
Tags: 7, entities
---


# Question
Title: How to use drush locally with Acquia Dev Desktop2 and upgrade core
I just a new project in Drupal 8 and it's hosted on Acquias cloud using Dev Desktop 2 (DD later on). Now the project is working fine, but i can't use drush at all, as the settings.php is generated by DD as is the code for the DB conneciton.

```
if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) && file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/cld_my_site_default.inc')) {
  require $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/cld_my_site_default.inc';
}

```

I found a post here where the suggested method was to create a `local.settings.php` and in it paste the contents of the file `cld_my_site_default.inc` but that's a dead end as i can't access that file.

Anyone knows how do i setup drush so i can update the core, as per this tut.

# Answer
> 0 votes
in Acquia Dev Desktop application, when your project is selected there is a small icon on the right-hand side. If you press it will open CMD and the correct path will be autoselected. Drush up will work there.

Good Luck

---
Tags: drush, updating, acquia-dev-desktop, acquia-cloud
---


# Question
Title: Disable third-party modules before core update
I have a D8 (8.5.6) installation which I have been trying to upgrade to 8.6 since it came out. It is on a shared hosting account which does not allow drush, so FTP it is. During the database update, it fails and I end up with the proverbial white screen of death. Before delving into detail troubleshooting, I want to disable all the third-party modules, and see if this works. If successful, I want to enable the third-party modules, one by one.

Is that a "good practice" type of approach?

The point is to quickly identify whether it is a contrib module which causes problems are the core install. Normal troubleshooting procedures would follow in any case.

# Answer
The one and only way to solve your problem responsibly is the following.

1. Download all files to your local machine.
2. Where you have a web development setup. And Drush.
3. Download the database.
4. Setup the page on your local machine, import the database and re-do locally what you were currently trying to do on the live server.
5. Use your local Drush and whatever other tools you can get to check error messages, server logs, debug output etc.
6. Drop and re-import the local database and repeat every step until you have reproduced the problem often enough to know what went wrong in the first place.
7. Fix your live page.

And finally:

**Never ever again update stuff untested on the live server**. And have the database backed up let's say at least once a week. Good luck!
> 0 votes

---
Tags: updating
---


title: Modal Form Submission

text:
# Question
Title: Modal Form Submission
I have a modal form that I added to my module and patterned it after this article.

I have used it before with no issues, I was able to use the method to show the form and then save the data.

Now I am populating the form as an edit form. When I submit the form it calls the controller again, which calls the `buildForm()` method of the modal class and then wipes out the data that was entered into the form. The data was in the `$form_state` correct but after the `buildForm()` runs it finally get to the AJAX call back handler and the data is no longer in the `$form_state`. It is totally gone. I am not sure how to solve this. I can't update anything in Drupal based on the form submit.

```
TimeOffApprovalController.php (Entry point of the route)

namespace Drupal\timeoff\Controller;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormBuilder;

class TimeOffApprovalController extends ControllerBase {

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilder
   */
  protected $formBuilder;

  /**
   * The ModalFormExampleController constructor.
   *
   * @param \Drupal\Core\Form\FormBuilder $formBuilder
   *   The form builder.
   */
  public function __construct(FormBuilder $formBuilder) {
    $this->formBuilder = $formBuilder;
  }

  /**
   * {@inheritdoc}
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The Drupal service container.
   *
   * @return static
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('form_builder')
    );
  }

  /**
   * Callback for opening the modal form.
   */
  public function openModalForm($id) {
    $response = new AjaxResponse();

    // Get the modal form using the form builder.
    $modal_form = $this->formBuilder->getForm('Drupal\timeoff\Form\TimeOffApprovalForm', $id);

    // Add an AJAX command to open a modal dialog with the form as the content.
    $response->addCommand(new OpenModalDialogCommand('Approval Form', $modal_form, ['width' => '800']));

    return $response;
  }

}

```

TimeOffApprovalForm.php (Modal form)

```
namespace Drupal\timeoff\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\timeoff\Controller\TimeOffController;
use Drupal\Core\Ajax\RedirectCommand;

class TimeOffApprovalForm extends FormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
    $form['#prefix'] = '<div id="modal_example_form">';
    $form['#suffix'] = '</div>';

    // The status messages that will contain any form errors.
    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];

    $ids = \Drupal::entityQuery('time_off_day')
                  ->condition('timeoffid', $options)
                  ->execute();
    $entitys = \Drupal::entityTypeManager()->getStorage('time_off_day')->loadMultiple($ids);

    $deny_dropdown = array();
    $hours_value = array();

    foreach ($entitys as $the_entity) {
      $deny_dropdown[$the_entity->id()] = t($the_entity->label());
      $hours_value[$the_entity->id()] = $the_entity->getTimeOffHours();
      $form[$the_entity->getTimeOffDate()] = array(
        '#type' => 'textfield',
        '#title' => t($the_entity->getTimeOffDate()),
        '#value' => t($the_entity->getTimeOffHours()),
        '#required' => TRUE,
      );
    }

    $form['timeoffid'] = array(
      '#type' => 'hidden',
      '#value' => $options,
    );
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['send'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit Approval form'),
      '#attributes' => [
        'class' => [
          'use-ajax',
        ],
      ],
      '#ajax' => [
        'callback' => [$this, 'submitApprovalFormAjax'],
        'event' => 'click',
      ],
    ];

    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    return $form;
  }

  /**
   * AJAX callback handler that displays any errors or a success message.
   */
  public function submitApprovalFormAjax(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // If there are any form errors, re-display the form.
    if ($form_state->hasAnyErrors()) {
      $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
    }
    else {

      // Do the time off denial
      //$id = $form_state->getValue('timeoffid');
      //$denialid = $form_state->getValue('deny_reason');
      //$comment = $form_state->getValue('deny_comment');
      //$timeoffcontroller = new TimeOffController();
      //$timeoffcontroller->deny($id, $denialid, $comment);

      $referer_url = $_SERVER['HTTP_REFERER'];
      $response->addCommand(new RedirectCommand($referer_url));
    }

    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }

    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {}

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {}

  /**
   * Gets the configuration names that will be editable.
   *
   * @return array
   *   An array of configuration object names that are editable if called in
   *   conjunction with the trait's config() method.
   */
  protected function getEditableConfigNames() {
    return ['config.modal_form_example_modal_form'];
  }
}

```

Any help?

# Answer
Populating a form field should be done via `'#default_value' => ...` instead of `'#value' => ...`
> 1 votes

---
Tags: ajax, modal-dialogs
---


# Question
Title: How to force 403 or 404 on specific route
I have made a custom form to create nodes for a specific content type. Due to that, I want to throw a 403 or 404 on the admin page that creates new node. The route I mean is 'node/add/'.

I guess in my\_module.routing.yml I have to add something like this:

```
<MY_CUSTOM_ROUTE>.add-node:
    path: '/node/add/<CONTENT_TYPE>'
    defaults:
        _controller: 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException'

```

But I'm not able to find the right controller. Any idea?

# Answer
You can define a route where `_access` is set to FALSE, like this one from a test in core:

```
system_test.always_denied:
  path: '/system-test/always-denied'
  defaults:
    _title: 'Always denied'
    _controller: 'chop'
  requirements:
    _access: 'FALSE'

```

Although in this case an extra route shouldn't be necessary, because you can deny the permission to add a content type in UI.
> 0 votes

---
Tags: 8, routes, http-request
---


# Question
Title: When visiting /user/ID how to allow users to only visit their own user page
I created a Twig template for the user account `/user/ID` page on Drupal 8.

How to display this template only if it is the account page of the current user?

For example if I go to the page of my account, I can display the page. If I go to another user's account page, a 403 error should be displayed.

# Answer
Go to admin path : `/admin/people/permissions` and uncheck the permission named *'View user information'* for the concerned roles, then save.

This does not affect users when they are on their own account page.

I did the following test, created two new users (4 and 5 in my case) :

* user `4` can access `user/4` page but has *"Access denied"* for `user/5` page.
* user `5` can access `user/5` page but has *"Access denied"* for `user/4` page.
* both users `4` and `5` have *"Access denied"* for `user/1` page.
> 4 votes

---
Tags: 8, theming, users
---


# Question
Title: Can't get value from cache_page table only cache_default
I am fiddling a bit with drupal 8 cache. Looking at cache\_page table and there is clearly a value with CID i am trying to fetch. I try this.

```
if ($item = \Drupal::cache()->get($cid)) {
  dsm($item);
}

```

and keep getting nothing for that CID, when I try some CID from cache\_default. I get it without problem. So I am wondering how to get values from other tables?

# Answer
> 4 votes
Provide the cache bin `page`, otherwise it defaults to `default`:

```
\Drupal::cache('page')->get($cid)

```

---
Tags: 8
---


# Question
Title: How to get the selected items (with VBO) in the buildConfigurationForm of a custom Action
I have made a custom action which have a configuration form:

```
class MyAction extends ConfigurableActionBase

```

Thus, I have the opportunity to create a form that allows the user to set some options. This form is created inside

```
public function buildConfigurationForm(array $form, FormStateInterface $form_state)

```

I need to get the list of the selected items that will be processed at this stage in order for me to exclude some option in the configuration form. In my use case, I need to exclude some option depending of the bundle of the selected entities (by my VBO view)

# Answer
Provided you use the Views Bulk Operations contrib module, you can use code similar to the following, inside the `buildConfigurationForm()` method. Most importantly, you need to extend `ViewsBulkOperationsActionBase` instead of `ConfigurableActionBase`.

```
class YourAction extends ViewsBulkOperationsActionBase

...
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    ...
    $selectedItems = array_map(function ($listItem) {
      return reset($listItem);
    }, $this->context['list']);
    ...
  }
...

```

This will give you an array whose values are the entity ids of the selected items in your view. The keys of the array are the `bulkFormKey` for each selected entity.

See `ViewsBulkOperationsFormTrait::calculateEntityBulkFormKey()` and `ViewsBulkOperationsFormTrait::getListItem()` for more information about bulkFormKeys.

Hope this helps, good luck!

P.S.: And for anyone else landing here, the related VBO's documentation page is over at https://www.drupal.org/docs/8/modules/views-bulk-operations-vbo/configuring-an-action
> 3 votes

---
Tags: 8, views, actions
---


# Question
Title: Give priority to one filter over another one when limiting the number of results
I have a view with a filter which returns the nodes which contain the word "word" in the field "title". I limited the results to 3 nodes. If there aren't 3 nodes, the rest of the nodes will be the ones which have the word "word" in the field "body".

The results are not fetching automatically first the nodes which contain the word in the field "title" as I would like it to be.
I set up the filters with the operator "or" how could i change it to **and if not**?

For example

**node1**
title: ***word***
body: this is...

**node2**
title: this is the ***word***
body: lsjflsdjf

**node3**
title: there is
body: this is the ***word***

**node 4**
title: here is
body: these are the ***word***

So with my view I would like to get back node1, node2 and node3 or 4 and in this order first the ones which have "word" in their title and than the other ones.

# Answer
Views filters automatically work with the `AND` Operator, so you don't have to do anything special to the Operator configuration if you want to filter titles that contain some word but at the same time that word isn't present in the Body.

Simply add the Title Filter and set it to `Contains` and enter the "word".

Then add the Body Filter and set it to `Does not contain` and again enter the "word".

Filters will be executed in the order as you see them listed under `Filters`.

If you added the Title Filter after the Body Filter so they are in the wrong order, click on the drop-down arrow next to the `Add` button under `Filters` and rearrange them so Title comes first. Keep the `AND` as the Operator.
> 0 votes

# Answer
> returns the nodes which contain the word "word" in the field "title" and if not in the field "body".

Filter node title that contain ‘word’. Create an OR and filter by body contain ‘word’.

> The results are not fetching automatically first the nodes which contain the word in the field "title"

For this, you need sorts now.

Well, in the past I’ve tagged the view. Implement `hook_query_TAG_alter()` and add ORDER BY clause to it,

```
ORDER BY CASE WHEN title LIKE ‘%word%’ THEN 0 ELSE 1 ASC

```

A Drupal example on that hook. (D7, might need to be adapted).

```
// Get order by's from the view
$orderBys =& $query->getOrderBy();
// Copy the values
$OriginalOrderBys = $orderBys;

//Double check 'title' is the right column name.
$query->orderBy('CASE WHEN title LIKE '%word%' THEN 0 ELSE 1 END', 'ASC');

// Move original order by's to the bottom in the same order
// This brings priority to the ones above.
foreach ($OriginalOrderBys as $key => $orderBy){
  $val = $orderBy;
  unset($orderBys[$key]);
  $orderBys[$key] = $val;
}

```

MySQL example (if someone wants to test directly)

```
select * from node
left join node__body on node.nid = node__body.entity_id
left join node__field_title on node.nid = node__field_title.entity_id

where
  node__body.body_value like '%word%' or
  node__field_title.field_title_value like '%word%'

order by
  case when body_value like '%word%' then 0 else 1 end asc

```

Then add/change the limit to 3.
> 0 votes

# Answer
There is no such logical ***and if not*** operator.

Your logic requires at least one `else` statement after the first condition, and you also need a nested condition to yield additional results (from the 'body' field) if the search in 'title' field yielded less than 3 nodes. In a pseudo-code, that logic would be :

```
if (r = in_title(word)) {
  yield limit(3, r)
  if (r.count < 3)
    yield limit(3 - r.count, in_body(word)) # additional result
}
else if (in_body(word)) {
  yield limit(3, r)
}

```

The problem is you can't tell views to do that, views builds and optimizes its db queries, so this kind of logic will end up with an `OR` because the above is equivalent to this :

```
# with :
# - condition $a equivalent to in_title(word)
# - condition $b equivalent to in_body(word)

if ($a)
  something
else if ($b)
  something_else

```

that is equivalent to the following condition :

```
($a && something OR $b && somethingelse)

```

Now we have to realize that the *something* and the *somethingelse* has to be the same thing, that is for views to yield results based on the query built so far :

```
($a && something OR $b && something)

```

equivalent to :

```
(($a OR $b) && something)

```

so this ends up with the unwanted `OR`.

Another thing to realize is that if results are yielded regardless of condition $a and $b (*something* happens even if no result) is not incompatible with the initial logic, as long as we keep the nested condition, which simplifies a bit :

```
r = in_title(word)
if (r.count < 3)
  r += in_body(word))
yield limit(3, r)

```

Since there is no way to handle such conditional subquery from views admin interface, the nested condition described above cannot be executed in a procedural manner, that means the whole result set has to be gathered and limited prior to condition testing, our pseudo-code ought to be :

```
r = limit(3, in_title(word) + in_body(word))
yield r

```

That's it, we have a single db-query-like expression collecting the *union* (logical `OR`) of results from the fields title and body : `in_title(word) + in_body(word)`.

All this to say that **you must use the `OR` operator** in the views filter options to achieve what you want, nothing more. That means all you need then is to apply proper sort options :

* you want a set of documents that contains a given word in `title OR body` (filter options).
* first those containing the word in title, and then the others (sort options).
* limiting the entire set to 3 documents (limit options).

**What you need to fix is the sort order**.

For this you can use some hooks to alter the query once views has done most of the work. For example by implementing `hook_views_query_alter` or `hook_query_TAG_alter` you should be able to flag title-matched vs body-matched nodes and alter the sorting order according to these custom node flags.

My point is we are often confused by our own logic before even trying to apply filter/sort options to a data set. The thing is to think first about *what* -\> filtering, without missing any data, then when you have a complete data set, only then you can think about how would these data be sorted.

This is obvious but we sometimes forget that we won't sort anything good if the data set is not complete in the first place.
> 0 votes

# Answer
This may not be exactly what you're asking in terms of limiting the number of results, but it may give you more ideas about the **if not then** behavior in Views.

If the limit to have no more than 3 results for a word in Title weren't that important, and you wanted to show the Body word filter only if the Title word results were empty, you could embed `View area` into `No results behaviour`:

You create a Views Display with only the Title word filter, and another (Block) Display with only the Body word filter. Save the Views.

Then under the first Display under `No results behaviour` choose `View area` from the Global category and choose the second Display, the one that has the Body word filter.

This way your first Display would show results for the Title word filter, and if there were no results for that word, then the Block would be displayed instead showing the Body word filter results.

You can limit how many results are *displayed* in each case, but there is no easy way to make the views show the Block when the number of results is less than 3, this applies only when there is 0 results.
> 0 votes

---
Tags: views
---


title: Posting to a form via external URL

text:
# Question
Title: Posting to a form via external URL
I am writing an application (non-Drupal) that is POSTing to a 3rd party public form written in Drupal. The problem I am running into is that the 3rd party form never processes the request, it only returns the original form. Is there a trick to posting to Drupal forms? The URL that I am attempting to post to is:

https://www.modelaircraft.org/membership/verify?ama\_number=123&last\_name=smith&op=Submit&form\_id=membership\_verify\_form

The response should have the following fragment:

```
<div role="alert">
  <h2 class="visually-hidden">Error message</h2>
  No match found for AMA 123 and last name smith. Please verify.

```

But it does not.

# Answer
There is no special trick to posting to Drupal Forms. But, the way that form is set up, at least for validation errors, is ajax-based. Which means that you need to post to this URL instead:

```
https://www.modelaircraft.org/membership/verify?ajax_form=1&_wrapper_format=drupal_ajax

```

with the following parameters

```
_drupal_ajax    1
_triggering_element_name    op
_triggering_element_value   Submit
ajax_page_state[libraries]  classy/base,classy/messages,core/drupal.ajax,core/html5shiv,core/jquery.form,core/normalize,extlink/drupal.extlink,google_analytics/google_analytics,nt_ama/nt_ama,omega/omega,responsive_menu/responsive_menu.javascript,responsive_menu/responsive_menu.styling,system/base,tb_megamenu/theme.tb_megamenu
ajax_page_state[theme_token]
ajax_page_state[theme]  nt_ama
ama_number  123
form_build_id   form-pqXufm7ga3qhXz5_dpM6_AiGcgcExovHqBG6kkqcIIE
form_id membership_verify_form
last_name   smith

```

That should give you a json response, similar to this:

```
[{
    "command": "update_build_id",
    "old": "form-pqXufm7ga3qhXz5_dpM6_AiGcgcExovHqBG6kkqcIIE",
    "new": "form-_2pgVtOL0WW10yWGP8iS1o95GyJ5pMxo5M1Mk3Jy90c"
}, {
    "command": "insert",
    "method": "html",
    "selector": "#messages-wrapper",
    "data": "    \u003Cdiv role=\u0022contentinfo\u0022 aria-label=\u0022Error message\u0022 class=\u0022messages messages--error\u0022\u003E\n          \u003Cdiv role=\u0022alert\u0022\u003E\n                  \u003Ch2 class=\u0022visually-hidden\u0022\u003EError message\u003C\/h2\u003E\n                    No match found for AMA 123 and last name smith. Please verify.\n                \u003C\/div\u003E\n      \u003C\/div\u003E\n    ",
    "settings": null
}]

```

which contains the message you mention.

Good luck!
> 0 votes

---
Tags: forms
---


# Question
Title: Updating core from 8.5.4 to 8.6.3, can I skip the releases in between?
I have a website that is running on Drupal 8.5.4. I want to update it to Drupal 8.6.3 through the manual update option (link).

Can I directly update it to 8.6.3 skipping the releases in between? None of the releases in between (8.5.5, 8.5.6, 8.6.0, 8.5.7, 8.6.1, 8.5.8, 8.6.2) had updates to the `default.settings.php` file, and I don't have any custom modifications to the files `composer.json`, `.htaccess` and `robots.txt` either (which means I can overwrite these 3 files with the ones that come with the updated Drupal code).

I read somewhere on the internet (link) that, while updating Drupal, we can skip minor and patch updates in between. But the release notes for 8.6.2 (link) says sites running Drupal 8.5.X should first update to 8.5.8 and update to 8.6.X later.

Does this mean I should first update to 8.5.8 and then to 8.6.3? Or can I directly update to 8.6.3?

# Answer
You can skip releases and update directly to the latest release, unless you want to narrow down update issues by taking smaller steps.

You've mentioned the release note for 8.6.2:

> Sites on 8.5.x should update immediately to Drupal 8.5.8 instead, and plan to update to the latest 8.6.x release before May 2019.

This had a different background. This advice was for an urgent security update of versions \< 8.5.8, because this wouldn't have been the right time to evaluate the update to 8.6.x if you hadn't done it yet, while the minor update from 8.5.7 to 8.5.8 was easy to apply, because it didn't require a database update.
> 3 votes

---
Tags: updating
---


# Question
Title: Automating creation of a settings.php file in a version-agnostic way
To create a latest Drupal project with a local Drush I might do for example:

```
drt=/var/www/html
composer create-project drupal-composer/drupal-project "$drt"

```

To create a Drupal `settings.php` for such new Drupal project I assume I should do:

```
cp "$drt"/domain.tld/sites/default/default.settings.php \
"$drt"/domain.tld/sites/default/settings.php

```

Yet, I desire to make a **version agnostic** copy of the `settings.php` file that will be ready for other operations like `sed` or `awk`.

Is there some Drush/Drupal-console (or maybe even some Drupal-specified Composer option or argument - not sure about that) that will let me automize this operation in a version agnostic-way so that if "tomorrow" `default.settings.php` will have a different name or at least be located in another directory than `./sites/default/` I would still have a `settings.php`-like file without the need of a manual `cp` operation?

# Answer
I wouldn’t have thought so. Copying a file is such a trivial act that I doubt anyone would’ve thought to wrap it up in a specific piece of functionality.

The only time the file would move would be as part of a major breaking update (e.g. moving from 8.x to 9.x), at which point you’ll want to be checking what’s changes anyway, and adjusting any scripts to conform to any new requirements.

Maybe a command would be written into Drush/console in the future if there were any plans to move or rename settings.php - currently there aren’t any such plans so it probably doesn’t make sense for one to exist.
> 2 votes

---
Tags: 8, composer
---


# Question
Title: Add content type machine name as body class
Is there a way to insert a class to the body of the node page? It should be named like the current node type's machine name.

Maybe someone could extend this code below with a content type class:

```
function marienschule_preprocess_html(&$variables) {

  // Add node ID to the body class.
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
    $variables['attributes']['class'][] = 'node-' . $node->id();
  }
}

```

# Answer
The code sample from your question could be extended to look like that:

```
function marienschule_preprocess_html(&$variables) {

  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {

    // Add node ID body class.
    $variables['attributes']['class'][] = 'node-' . $node->id();

    // Add content type machine name body class.
    $variables['attributes']['class'][] = 'node-type-' . str_replace('_', '-', $node->bundle());
  }
}

```
> 4 votes

# Answer
You can do this without a preprocess hook, because the node type variable is already available in the html template:

```
{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
  ]
%}

...

<body{{ attributes.addClass(body_classes) }}>

```

Source: *html.html.twig* of Classy
> 5 votes

---
Tags: theming, nodes
---


title: Put Site-Wide Contact Form in a Block

text:
# Question
Title: Put Site-Wide Contact Form in a Block
I want to display the contact form inside a block, so that a user can access it directly from another page. Using Webform Module to create a new form would be overkill.

Is there a simple way to do this, either core, a small module or custom module?

# Answer
Use the Form Block module. Enables the presentation of user registration, **site wide contact**, or node creation forms in blocks.
> 4 votes

# Answer
You can do this with webform, take a look at this link, it tells you exactly what to do to enable it.
> 0 votes

# Answer
You can achieve this by using:

* hook\_form\_info() to define the block you want to add.
* hook\_block\_view($delta) to define the content you wish to add to your block. Basically just add this

```
$block = [];

switch ($delta) {
  case 'block_contact_form':
    module_load_include('inc', 'contact', 'contact.pages');
    $block['subject'] = t('Contact');
    $block['content']['form'] = drupal_get_form('contact_site_form');
  break;
}

return $block;

```
> -1 votes

---
Tags: 7, emails
---


# Question
Title: How do i select all from database and do while loop with them
I did this easy select and im getting Error: Call to a member function fetchAssoc() on boolean , im beginner, im just trying to pull out two variables and make operations with them.

```
$result = db_select('cities', 'c')
        ->fields('c')
        ->execute()
        ->fetchAssoc();

  while ($row = $result->fetchAssoc()) {

    $city_id = $row['city_id'];
  $city_name = $row['city_name'];

```

Only this is working for me

```
     $sql = "SELECT * FROM {cities}";
           $result = db_query($sql);

  while ($row = $result->fetchAssoc()) {

    $city_id = $row['city_id'];
  $city_name = $row['city_name'];

```

# Answer
Try with this:

```
   $results = db_select('cities', 'c')
    ->fields('c')
    ->execute()
    ->fetchAll(PDO::FETCH_ASSOC);

   foreach ($results as $result){
    $city_id = $result['city_id'];
    $city_name = $result['city_name'];
   }

```
> 0 votes

---
Tags: database
---


title: How to do a custom taxonomy breadcrumb

text:
# Question
Title: How to do a custom taxonomy breadcrumb
I'm using Drupal 8.3.0-beta1 and I need to write a custom module to customize breadcrumbs in some cases. On of this cases consists in customizing the breadcrumb in path **taxonomy/term/%** but with my current code there is a problem:

When I visit **taxonomy/term/%** the "applies" callback of my custom implementation of **BreadcrumbBuilderInterface** doesn't get executed. However, it gets called on **taxonomy/term/%/edit**. Maybe that's the reason why the core breadcrumb builder only returns "**Home /**" in this case. Do you think this is a core bug or I have done something wrong?

Notice I have another implementation of BreadcrumbBuilderInterface for nodes which works well. This is my code:

**custom\_breadcrumb.info.yml**

```
name: 'Custom breadcrumbs'
description: 'Custom breadcrumbs implementation'
package: 'Custom'
# core: 8.x
type: module

version: '8.x-1.0'
core: '8.x'
project: 'custom_breadcrumb'
datestamp: 1443649740

```

**custom\_breadcrumb.services.yml**

```
services:
  custom_breadcrumb.breadcrumb_blog:
    class: Drupal\custom_breadcrumb\Breadcrumb\BlogBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 101 }

```

**src/Breadcrumb/BlogBreadcrumbBuilder.php**

```
<?php

namespace Drupal\custom_breadcrumb\Breadcrumb;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\LinkGeneratorTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Link;
use Drupal\taxonomy\Entity\Term;

class BlogBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  use LinkGeneratorTrait;
  use StringTranslationTrait;

  /**
   * @inheritdoc
   */
  public function applies(RouteMatchInterface $route_match) {
    // This breadcrumb apply only for blog taxonomy terms of vocabulary 'categoria_blog'.
    $parameters = $route_match->getParameters()->all();

    /*
     * CORE BUG? applies callback gets called on "taxonomy/term/%/edit" but not in "taxonomy/term/%"
     * https://www.drupal.org/node/2622840
     */
    if (isset($parameters['taxonomy_term'])) {
      $term = $parameters['taxonomy_term'];

      if ($term->getVocabularyId() == 'categoria_blog') {
        return TRUE;
      }
    }

    return FALSE;
  }

  /**
   * @inheritdoc
   */
  public function build(RouteMatchInterface $route_match) {

    $parameters = $route_match->getParameters()->all();

    if (isset($parameters['taxonomy_term'])) {

      $term = $parameters['taxonomy_term'];

      // Breadcrumbs set up (cache settings are so important!).
      $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
      $breadcrumb->addCacheContexts(["url"]);
      $breadcrumb->addCacheTags(["taxonomy_term:{$term->id()}"]);

      $breadcrumb->addLink(Link::createFromRoute($term->getName(), '<none>'));
    }

    // Reverse order for this to work!!!.
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
    return $breadcrumb;
  }
}

```

# Answer
> 10 votes
The taxonomy module provides a default breadcrumb service and if you have a look at the declaration of this in the taxonomy.services.yml file you will see it has a priority of 1002.

Setting the priority of your breadcrumb service to a value higher than this should get Drupal to use your breadcrumb rather than the default one.

Something like this should do the trick:

**custom\_breadcrumb.services.yml**

```
services:
  custom_breadcrumb.breadcrumb_blog:
    class: Drupal\custom_breadcrumb\Breadcrumb\BlogBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 10001 }

```

# Answer
> 2 votes
according to https://www.drupal.org/docs/8/api/services-and-dependency-injection/service-tags

> A higher priority will be used over a lower priority.

and since the default implementation of `TermBreadcrumbBuilder` has a `priority` of `1002` the `priority` needs to be set to at least `1003`.

```
services:
custom_breadcrumb.breadcrumb_blog:
class: Drupal\custom_breadcrumb\Breadcrumb\BlogBreadcrumbBuilder
tags:
  - { name: breadcrumb_builder, priority: 10003 }

```

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


# Question
Title: Set views contextual filter as request_path()
There are fields in content type called **URL** and **Image**.

Suppose, A node has "service" value of "URL" field and I'm trying to show views block where current path (service) and "URL" field path (service) are same. The "URL" value can also be "content/services".

I tried with

* adding "Alias" field as contextual filter in views.
* adding URL field

**Updated:**

I also tried with URL field with PHP Code in contextual filter:

```
if(drupal_is_front_page()) {
    return '<front>';
}else{
    return request_path();
}

```

It works for only one path argument, like if current requested path is `services/one` and views contextual filter only takes first path component as you can see in attached image  However, I need to set contextual filter with whole path no matter how many components are requested.

**Theme**

I have a content type with image and URL fields, I need to show image on the path where URL field is matched with requested path using views.

How would I do that?

# Answer
I have done this by embedding the views block in tlp and passing the URL field filter by code. See code below:

```
$path = request_path();
$query = 'SELECT field_url_url FROM {field_data_field_url}
          WHERE bundle = :bundle AND entity_type = :entity_type AND field_url_url = :field_url_url';
$path = db_query($query, array(
            ':bundle'=>'page_banner',
            ':entity_type'=>'node',
            ':field_url_url'=> $path
        ))->fetchField();
if (!empty($path)):
  print views_embed_view('page_banner','block', $path);
endif;

```

I hope this will help someone who needs to add contextual filter as request URL.
> 0 votes

# Answer
If you want to filter nodes in a Views list that have the same expression in their "Alias" field as the path where the Views Block is shown then you can do it by adding the "Alias" field as a contextual filter and configured like this:

`When the filter value is NOT available`
**Provide default value**
**Raw value from URL**
**Path component** **1**

Adjust the path component to the place where your `service` appears in the path.

You can also adjust the validation and other options that are relevant to you, but that first bit is what is the most important to match the path to your field.

---

The field value `content/services` might match only on pages where the path starts with `content/services`. I haven't tested this, I expect the field expression will be treated as a one string, but the path will only take the first part before the `/` so in the end it won't match.

If you find that it doesn't work, then you might make it work with the help of Views Argument Substitutions and Views Contextual Filters OR.

You could also do it with the Context module and Context entity field but it's a fairly complex to configure.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How does the if statement work and why should I set a value prior to checking a condition?
```
{% set switch_check = true %}

{% if switch_check == 'Small' %}
      {{ content.field_value }}
 {% elseif switch_check == 'Large' %}
      {{ content.field_other_value }}
{% endif %}

```

I want to check if `content.switch_check == 'Small'` then print `content.field_value` else if `content.switch_check == 'Large'` then print `content.field_other_value`

Am I missing something?

# Answer
Yes, you are missing something.

You're setting a value to `true` and then checking whether it's `'Small'` or `'Large'`.

This will never return true, as seen below:

```
{% if true == 'Small' %}
      {{ content.field_value }}
 {% elseif true == 'Large' %}
      {{ content.field_other_value }}
{% endif %}

```

You may as well check whether `1 == 0` or `true == false`.

**EDIT:** Also, as Clive says in his comment above:

> If you want to check `content.switch_check`, why not `{% if content.switch_check %}`?

In other words, you're not even checking the thing you say you want to check.

In your own words:

> I want to check `if content.switch_check == 'Small'` then print `content.field_value` else `if content.switch_check == 'Large'` then print `content.field_other_value`

So try doing it like this:

```
{% if content.switch_check == 'Small' %}
      {{ content.field_value }}
  {% elseif content.switch_check == 'Large' %}
      {{ content.field_other_value }}
{% endif %}

```

Just for sanity's sake, try printing out the value of `content.switch_check` in a debugging statement so that you know what to expect when you make this comparison! You can remove the debugging statement once you know what the expected value is.
> 1 votes

---
Tags: theming
---


title: jQuery on Twig Template

text:
# Question
Title: jQuery on Twig Template
I am trying to create a basic jQuery function on my twig template but I can't seem to get it to work. Can someone please help me!?

My Twig File is as follows:

```
{% block javascripts %}
    {#if you include jquery here, the scripts that need jquery will fail because jquery exists since this point !#}

    <script type="text/javascript" src="{{ asset('js/jquery.min.js') }}">
    $(".nav li.expanded").hover(
        function(){
          $(this).addClass("open");
        },function(){
          $(this).removeClass("open");
        }
      alert("Inside Function");
      );
      alert("Outside Function");
      $(document).ready(function(){
        alert("Ready!");
      });
    </script>
{% endblock %}
{% set heading_id = attributes.id ~ '-menu'|clean_id %}
<nav role="navigation" aria-labelledby="{{ heading_id }}"{{ attributes.removeClass('clearfix')|without('role', 'aria-labelledby') }}>
  {# Label. If not displayed, we still provide it for screen readers. #}
  {% if not configuration.label_display %}
    {% set title_attributes = title_attributes.addClass('sr-only') %}
  {% endif %}
  <h2{{ title_attributes.setAttribute('id', heading_id) }}>{{ configuration.label }}</h2>

  {% block content %}
    {{ content }}
  {% endblock %}

```

# Error Output:

```
The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">Twig_Error_Syntax</em>: Unknown "asset" function. in <em class="placeholder">Twig_ExpressionParser->getFunctionNodeClass()</em> (line <em class="placeholder">38</em> of <em class="placeholder">themes/custom/navy/templates/block/block--system-menu-block--main.html.twig</em>). <pre class="backtrace">Twig_ExpressionParser->getFunctionNode('asset', 38) (Line: 162)
Twig_ExpressionParser->parsePrimaryExpression() (Line: 102)
Twig_ExpressionParser->getPrimary() (Line: 55)
Twig_ExpressionParser->parseExpression() (Line: 149)
Twig_Parser->subparse(Array, 1) (Line: 40)
Twig_TokenParser_Block->parse(Object) (Line: 192)
Twig_Parser->subparse(NULL, ) (Line: 105)
Twig_Parser->parse(Object) (Line: 716)
Twig_Environment->parse(Object) (Line: 774)
Twig_Environment->compileSource(Object) (Line: 452)
Twig_Environment->loadTemplate('themes/custom/navy/templates/block/block--system-menu-block--main.html.twig') (Line: 64)
twig_render_template('themes/custom/navy/templates/block/block--system-menu-block--main.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('block', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 450)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 182)
__TwigTemplate_7206b6943ab6709e209af4c71d787052441f5e0fc6966fa51bfb08236a79f5ef->block_main(Array, Array) (Line: 215)
Twig_Template->displayBlock('main', Array, Array) (Line: 65)
__TwigTemplate_7206b6943ab6709e209af4c71d787052441f5e0fc6966fa51bfb08236a79f5ef->doDisplay(Array, Array) (Line: 432)
Twig_Template->displayWithErrorHandling(Array, Array) (Line: 403)
Twig_Template->display(Array) (Line: 411)
Twig_Template->render(Array) (Line: 64)
twig_render_template('themes/custom/navy/templates/page/page.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('page', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 90)
__TwigTemplate_1851d7a76e53df9c9a6b9fa5328c4c7d784772b2109ead0be693668c41ae4e88->doDisplay(Array, Array) (Line: 432)
Twig_Template->displayWithErrorHandling(Array, Array) (Line: 403)
Twig_Template->display(Array) (Line: 411)
Twig_Template->render(Array) (Line: 64)
twig_render_template('themes/contrib/bootstrap/templates/system/html.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('html', Array) (Line: 437)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 147)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 148)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 156)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 67)
Drupal\simple_oauth\HttpMiddleware\BasicAuthSwap->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: 40)
Drupal\jsonapi\StackMiddleware\FormatSetter->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 666)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)
</pre>

```

# Answer
There are a few things going wrong:

1. jQuery is in no conflict mode, so there's no global `$`. A common pattern to provide it in the manner you're accustomed is:

```
(function($) {
  $(...);
})(jQuery);

```
2. Assuming you use a sensible theme, jQuery isn't actually available at that point in the document. The `<script>` tags are before the `</body>` tag.
3. You're not looking at your browser console, which would have told you much of this ;)

To include JS in a template, you should create a library, and attach it either in a preprocess function, or directly in the template itself with:

```
attach_library('mytheme/library')

```
> 3 votes

---
Tags: 8, javascript
---


# Question
Title: Is it possible to do a user search by taxonomy?
my question is because I have users with a taxonomy field and what I want to do is search for those taxonomies.

Example: a user in his profile chose a taxonomy, let's say soccer. I want to make a search engine in which users search for soccer and all users who have a soccer taxonomy appear.

I do not know any module for this and I do not know if it is possible to do it with a view.

•Drupal 7 •Views 7.x-3.20

Any help?

# Answer
1. Create a "User" View

2. Add a "Filter Criteria" with your taxonomy field

* Click "Expose this filter to visitors, to allow them to change it"
3. Done.
> 2 votes

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


title: Add menu links to custom generated menu

text:
# Question
Title: Add menu links to custom generated menu
I am working on a custom Drupal 8 module which generates a menu. Refer Create a new Menu in Drupal 8 programmatically for details.

I have the menu now, but when I try to add custom menu links to it, following add a menu link, somehow it's not getting added to that custom menu.

Another weird thing is that the links are getting added to the wrong menu, i.e. they show under `User Account Management` menu.

The only reason I can think of is, when I install the module, Drupal tries to create the menu link first, before it has created custom menu. As the custom menu is not there yet, it tries to add the menu links to another menu. Is that right?

Here is my code, if that helps:

```
// system.menu.aeauth.yml // This creates the new menu on module install

langcode: en
status: true
dependencies: {  }
id: aeauth
label: 'AE Authentication Links'
description: 'Links related to AE Authentication'
locked: true

```

---

```
// ae.links.menu.yml // This adds menu links to menus

ae.admin_settings:
  route_name: ae.adminForm
  title: 'AE Configuration'
  description: 'Configure AE for your website'
  parent: system.admin_config_system

ae.register:
  title: 'Register'
  description: 'Register using AE Connect'
  parent: aeauth
  route_name: ae.regroute

ae.login:
  title: 'Login'
  description: 'Login using AE Connect'
  parent: aeauth
  route_name: ae.loginroute

```

# Answer
> 0 votes
The problem is that you're not specifying what menu your links belong to. Instead you are setting the parent, but I think the parent doesn't exist in your cast. This works for me:

**custom\_module/system.menu.my-custom-menu.yml:**

```
langcode: en
status: true
dependencies: {  }
id: my-custom-menu
label: 'My Custom Menu'
description: ''
locked: true

```

**custom\_module/config/install/custom\_module.links.menu.yml:**

```
custom_module.custom_link:
  title: 'My Custom Link'
  weight: -10
  route_name: custom_module.custom_route
  menu_name: 'my-custom-menu'

```

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


# Question
Title: entity_load not fetching the updated column
I've a custom entity {my\_table} and added a new field in schema file as follows

```
/**
 * Add {new_column} field to {my_table} table.
 */
function MY_MODULE_update_7100() {
    $table = 'my_table';
  $spec = array(
    'type' => 'int',
    'description' => "blah blah",
    'size'=> 'tiny',
    'default' => NULL,
  );
  db_add_field($table, 'new_column', $spec);
}

```

When I ran update.php the database table column got updated.

But the problem is when I run '`entity_load`' it's not fetching the added column to the object.

```
$get_entity = entity_load('{my_table}', array(184));
dpm($get_entity) // showing all columns, except the new_column

```

I've cleared the cache but no luck. Any suggestions would be much appreciated.

# Answer
> 1 votes
If I have understood you correctly, as well as updating the table you must provide an updated schema definition for the entity. Drupal uses this definition to determine the names and properties of the columns in the entity.

Note you do not need to do an 'update' action for the schema definition: just change it to match the current code. You (only) need the update hook for databases that enabled the earlier version of the module. Also, importantly, the update hook must both add the column to the database, but set the new property value for any rows appropriately. Often this can be done by the database default value, but not always.

---
Tags: 7, entities
---


# Question
Title: How tu setup magazine-like content type?
I working on my first Drupal 8 site, and I heard 3 rules about Content Types:

* More than 5 content types is too much
* When content are similar (news, articles) is better to do one content type
* Do not store data in taxonomy

My content on site look similar to that:

* Editorial (title, description, author, contents, image, publish date, tags, category) :

+ News
    + Article
    + Blog
    + Review (summary, ratings)
    + Deal (link)
    + Contest (regulations, prizes, tasks)
    + Video (link instead of contents)
* Database:

+ Anime
        - Studio
        - Characters
        - Anime Reviews (generated by users)
* \[and more\]

Editorial have common fields, and some sub-types have additional fields. Anime have its own field, including Studio and Characters, which should have own fields (name, description etc).

And I'm lost, and researches don't give any results. There is my thoughts:

1. All as content types ;)
2. Editorial as content type, sub-types as drop down field, which change other fields. There is some solution for that ?
3. Anime as content-type, Characters and Studios as Vocabulary.
4. Anime Reviews are like comments with rating. Maybe add this like comment type ?

How to setup that kind of structure with the best performance ?

# Answer
> 2 votes
Whoever gave you those rules was probably trying to stop you tying yourself in knots, so means well, but these rules are IMO just wrong.

The rules of good data structuring can be found in textbooks and I would encourage you to read them, but for this purpose:

* Use different content types to store different kinds of value. So in your example, although both News and Review both have body text, they are not interchangeable: you want news with news and not mixed with articles.
* Do not use different content types just because the appearance (rendering) of the content on a page differs. Use view modes, templates and/or CSS to do that.
* Keep the number of content types to the minimum you can that does not require "magical knowledge" such as "knowing" that a news article written by author bloggs is actually a Blog -- etc
* Be consistent. If you have four types of content as a group, and technically you could share two of them, don't: the consistency rule suggests that you need four types (and indeed you may find later that the two do indeed diverge).
* Where there are shared groups of data (a gallery of images, perhaps), consider whether it would be useful to make a content type (or paragraph entity) for that shared part, and then reference it as needed. Sometimes such referencing can help keep repetitive code at bay, but it can also complicate the data model. If unsure, don't.
* Look for opportunities to improve the model as the site grows and don't be afraid to adapt. Nothing is forever. Adopt the principle of least surprise.

Content types and entity definitions are composed of fields, and it is possible to share field definitions as well as types. Apply the same logic as above: just because you have an integer field doesn't mean you should use it wherever you need an integer: the field should IMO store a particular kind of data (e.g. speed in kph, dress size in EU units, number of items in cart). Don't mix them up.

As a result, fields should have names that reflect both their use and their "units": field\_dress\_size\_eu, field\_thrust\_newtons, field\_speed\_kph, etc. Of course the units can be omitted from the name - but only because the site never uses an alternate for that kind of datum (e.g. all speeds are kph, not metres\_second or miles\_per\_hour).

---
Tags: 8, nodes
---


# Question
Title: selecting all field_data_body for all content types
We are trying to search all text\_long or text\_with\_summary fields for all content type nodes. I can do it for the field\_data\_body. I need to expand this for all content types using text\_long and text\_with\_summary. I would like to iterate all nodes for all content types and select all fields in the node with the text\_long and text\_with\_summary field type.

Here is what I use for selecting just the body. I use a cursor to search each db which is why I have a v\_db variable. Don't worry about v\_db and @j is the search string I pass to the select statement. I wish there was a nice GUI for visualizing joins.

select "',v\_db,'", ',v\_db,'.node.nid, LEFT(',v\_db,'.node.title,30), LEFT(',v\_db,'.body.body\_value,300) from ',v\_db,'.node INNER JOIN ',v\_db,'.field\_data\_body AS body ON node.nid = body.entity\_id WHERE body.body\_value like ',@j);

thanks

# Answer
> 0 votes
I needed to do something a bit similar a while ago, and used the drupal field definition tables to identify the field type (text/long et al) and work from there to the nodes. I suggest you do likewise.

You could consider using the mysql fulltext search facilities - it is much faster and much more capable than 'like'.

Of course, the drupal way would be to configure the search module properly...

---
Tags: nodes
---


# Question
Title: How to remove exposed filter if value is supplied in url?
We have a `view page` (path = `/some-path/`) that has an `exposed filter` called `category`. The detailed view setup is below. How would we hide the `exposed filter` if it is supplied from the `url`?

**View setup:**

Filter criteria:

Settings:

1. `Operator` = `is one of` (list of all tags term values)
2. `Filter type to expose` = `single filter`

Advanced

1. Require relationships for `field_tags`
2. `when the filter value is not in the url` --\> `display all results for the specified field`
3. `when the filter value is in the url or default is provided`

a. `specify validation criteria -> validator -> taxonomy term name` where `vocabulary = tag`

b. `action to take if filter value does not validate = display contents of no results found`

c. `case = lower case`

d. `more -> transform spaces to dashes in url -> enabled`

Expected behavior:

1. when `/some-path/` is navigated to, then the exposed filter should show
2. when `/some-path/term-value/` is navigated to, it will filter the results and hide the exposed filter

Current behavior:

1. navigating to `/some-path`, shows all results with the exposed filter displaying allowing a visitor to change it.
2. navigating to `/some-path/value2/` filters the results and displays the exposed filter.

# Answer
> 2 votes
Here's a clever way to do it without coding: use two different Views displays and embed one of them as `View area` into another's `No results behavior` and configure the contextual accordingly.

1. Create the Page *with* the Exposed Filter but *without* the Contextual filter
2. Duplicate that Page to create another Page display with the same Path, but make these changes:
    1. override the Filters and remove the Exposed filter
    2. override the Contextual filters and Add your Term name there with these settings:
    `When the filter value is NOT available`
    **Display contents of "No results found"**
    `When the filter value IS available or a default is provided`
    **Specify validation criteria**
    \[your settings\]
    `Action to take if filter value does not validate`
    **Display contents of "No results found"**
    3. Override the `No results behavior`, add **View area** and choose the first Page display under `View to insert` (the one with the Exposed filter). Save the View if you don't see that display as option at first.

This way you get the first page to kick in for `/some-path` and you see the exposed filter, but if you add a term name to the path and it validates `/some-path/value2/` the second Page display kicks in and you don't see the Exposed filter, you see the contextual results.

If the argument doesn't validate, you see the first Page and allow users to choose the term from the Exposed filter. You can change that to something else if it makes more sense. The part that makes this views switching work is the first part of the contextual filter `When the filter value is NOT available` **Display contents of "No results found"** and the embedded View area.

# Answer
> 0 votes
I am not sure it will help but you could check out the module "better\_exposed\_filters". It sets out to do this sort of thing.

---
Tags: views, 8, hooks, input-formats
---


title: How can I mock a service?

text:
# Question
Title: How can I mock a service?
i have this code:

```
/**
 * Defines a wrapper target around a paragraph bundle's target field.
 *
 * @FeedsTarget(
 *   id = "feeds_para_mapper_temp_target",
 *   field_types = {
 *     "entity_reference_revisions",
 *   },
 *   arguments = {
 *     "@entity.manager",
 *     "@entity_field.manager"
 *   }
 * )
 */
class TempTarget extends FieldTargetBase implements, ConfigurableTargetInterface,
{
  protected $entity_type_manager;
  protected $field_manager;
  public function __construct(array $conf, $id, array $def, EntityTypeManagerInterface $en_man, EntityFieldManagerInterface $f_man)
  {
    parent::__construct($conf, $id, $def);
    $this->entity_type_manager = $en_man;
    $this->field_manager = $f_man;
  }
  // Here is where i need the instance, and it's weird because it gets called
  // without instantiating this class:
  public function defaultConfiguration(){
    // This function create a form configuration and return it:
    $definition = $this->targetDefinition;
    $field = $definition->getFieldDefinition();
    $instance = $this->createTargetInstance($field,$this->feedType)
  }
  // Calls this plugin manager to get instance of another plugin
  public function createTargetInstance(FieldConfigInterface $field, FeedTypeInterface $feed_type){
    // This is where the test is failing:
    $manager = \Drupal::service('plugin.manager.feeds.target');
  }
}

```

what it does it calls a plugin manager in order to create instance definition, whenever it gets tested i see this error:

```
\Drupal::$container is not initialized yet.

```

which i know is caused by calling to the service i have tried this in the test file:

```
$container = new ContainerBuilder();
$manager = $this->prophesize('Drupal\feeds\Plugin\Type\FeedsPluginManager');
$container->set('plugin.manager.feeds.target', $manager);
\Drupal::setContainer($container);

```

Not working. i tried as the answer suggested in the comment bellow to add implement `ContainerInjectionInterface` not working, and with `ContainerFactoryPluginInterface` as this article suggested, not working too, in both implementations the `create()` method is never get called i tried to add this to he annotation:

```
 *   arguments = {
 *     "@entity.manager",
 *     "@entity_field.manager",
 *     "@plugin.manager.feeds.target"
 *   }

```

with this constructor:

```
public function __construct(array $$conf, $id, array $def, EntityTypeManagerInterface $en_m, EntityFieldManagerInterface $f_m, FeedsPluginManager $p_m)
  {
    $stop = null;
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entity_type_manager = $en_m;
    $this->field_manager = $f_m;
    $this->plugin_manager = $p_m;
  }

```

and it's working only if this class is instantiated, and as i said it's not when the `defaultCongiguration()` get called, i can go without the plugin manager at this stage but i really prefer if i can have it in this function.

# Update:

The reason why implementing either `ContainerInjectionInterface` or `ContainerFactoryPluginInterface` didn't work is because i added my dependencies in the `arguments`, annotation and in the `create()` method too.

# Answer
This is probably a unit test (not mentioned in the OP). If so, the intention should be to test the methods of the `TempTarget` class, which means, that the first thing needed would be to instantiate an instance of that class, e.g.

```
/**
 * Instantiates and returns a TempTarget object.
 */
protected function getTempTargetInstance()
{
  $id = $this->generateId();
  $def = $this->generateDef();
  // This is where you mock the constructor dependencies/services.
  // You probably will need to create a mock like this:
  //   $this->getMockBuilder('Drupal\Core\Entity\EntityTypeManager')
  //     ->disableOriginalConstructor()
  //     ->getMock();
  $this->entityTypeManager = $this->getEntityTypeManagerMock();
  $this->entityFieldManager = $this->getEntityFieldManagerMock();

  // You can now call the constructor.
  $tempTarget = new TempTarget($id, $def, $this->entityTypeManager, $this->entityFieldManager);
  return $tempTarget;
}

```

At this point, your object should be instantiated and you can call methods on it to assert the assumptions you want to be testing. For example:

```
public function testDefaultConfigurationMethod()
{
  $tempTarget = $this->getTempTargetInstance();
  $formConfiguration = $tempTarget->defaultConfiguration();
  // Test different assertions given the $formConfiguration object.
}

```

However, at the time you call `defaultConfiguration()` you know that you need a container available that holds an entry for `plugin.manager.feeds.target`, so, you have to have that prepared in advance. The right place for that would be your `setUp()` method in your class, for example:

```
/**
 * {@inheritdoc}
 */
public function setUp() {
  parent::setUp();

  // Provide a mock service container, for the services our module uses.
  $container = new ContainerBuilder();
  $container->set('plugin.manager.feeds.target', $this->getFeedsTargetPluginManagerMock());
  \Drupal::setContainer($container);
  ...
  // Further setting-up of your testing class.
}

```

with `getFeedsTargetPluginManagerMock()` looking something like this:

```
/**
 * Creates and returns a mock for the feeds
 */
protected function getFeedsTargetPluginManagerMock() {
  $feedsTargetPluginManager = $this
    ->getMockBuilder('Drupal\feeds\Plugin\Type\FeedsPluginManager')
    ->disableOriginalConstructor()
    ->getMock();
  ...
  // Further mocking of the objects methods if needed.
  ...
  return $feedsTargetPluginManager;
}

```

Good luck!
> 2 votes

---
Tags: 8, testing
---


# Question
Title: How to redirect user to login page when anonymous user click on the flag link?
Redirect user to login page when anonymous user click on the flag link.

How to achive this?

I have created flag links by

```
   function MYMODULE_preprocess_node(&$variables) {
 $node = $variables['elements']['#node'];
  $flag_link_service = \Drupal::service('flag.link_builder');
$flag_link = $flag_link_service->build($node->getEntityTypeId(), $node->id(), 'YOUR_FLAG_MACHINE_NAME');
$variables['flag_link'] = $flag_link;
}

```

Placed variable in twig template.

I want to do something like

```
 If ($user->uid) == 0)
 {
redirect to login
 {
 else
 {
   {{ flag_link }}
   }

```

# Answer
> 4 votes
I have handled this by only showing the flag element when the user is logged in. When the user is not logged in, I have rendered out the flag graphic (eg, the heart) as a link to 'user/login?destination=whatever'. This eliminates the need to alter the flag link, especially since it also typically has AJAX associated with it.

# Answer
> 0 votes
I have achived this by using twig

```
{% if logged_in %}
{{ flag_link }}
{% else %}
custom image link
{% endif %}

```

---
Tags: 8, flags
---


# Question
Title: Get all submissions from specific webform
I am trying to load webform submissions by a particular webform `sign_up`.

Using Query webform submissions, this does get me all the IDs associated and I can load the data using

```
$query = \Drupal::entityQuery('webform_submission')
  ->condition('webform_id', 'sign_up');
$result = $query->execute(); // Gives me IDs associated with the "sign_up" webform.

$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);
$submission_data = array();
foreach ($submissions as $submission) {
  $submission_data[] = $submission->getData();
}
// $submission_data now contains all the submissions from "sign_up" webform.

```

Is this the correct way of getting the submissions? I would think Webform comes with some sort of API to query the submission results.

I also tried: https://www.drupal.org/project/webform/issues/2902682 but ended up with an empty array.

# Answer
The Webform module stores submission data using a custom Entity-Attribute-Value model. Your example code is the easiest and fastest way to get all the submission data. The only limitation would be the number of submissions vs PHP's memory limit. You will run out of memory if you are loading 1000's submissions
> 5 votes

# Answer
My example shows one less line to loading the WebformSubmission entity, also uses $webform-\>hasSubmissions() to check if there are submissions before forging ahead:

```
// Set the webform.
$webform = Webform::load('sign_up');
if ($webform->hasSubmissions()) {
  $query = \Drupal::entityQuery('webform_submission')
    ->condition('webform_id', 'sign_up');
  $result = $query->execute();
  $submission_data = [];
  foreach ($result as $item) {
    $submission = \Drupal\webform\Entity\WebformSubmission::load($item);
    // Do something with the WebformSubmission item
    $submission_data[] = $submission->getData();
  }
}

```

so the submission loading line:

```
$submission = \Drupal\webform\Entity\WebformSubmission::load($item);

```

replaces:

```
$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);

```

But which is actually better/more efficient, not sure.
> 2 votes

---
Tags: 8, webforms
---


# Question
Title: How can I override the container.html.twig template for one submit button only?
How can I override container.html.twig for one submit button only?

It showing no template suggestions.

# Answer
Based somewhat on kiemi's answer, you could go for something to this degree:

```
<?php

/**
 * Implements hook_theme_suggestions_container_alter().
 */
function yourtheme_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  $pieces = [
    $variables['element']['#type'],
    $variables['element']['#name'],
    $variables['element']['#display_id'],
  ];
  $suggestions[] = 'container__' . implode('_', $pieces);
}

```

This will produce a suggestion, for example, of `container--view-articles-featured.html.twig`

Of course, if you want it to follow true Drupal template suggestion standards, you'll want to add several suggestions with varying levels of specificity.
> 5 votes

# Answer
The Template Suggest module now includes container template suggestions. An example of what it will provide for a view:

```
 FILE NAME SUGGESTIONS:
   * container--view--case-study--page-listing.html.twig
   * container--view--case-study.html.twig
   x container--view.html.twig
   * container--no-parent.html.twig
   * container.html.twig

```

For the original post use case of a submit button, here is what a typical container around a submit button will provide:

```
 FILE NAME SUGGESTIONS:
   * container--actions.html.twig
   * container--has-parent.html.twig
   x container.html.twig

```

So it makes it easy to target all actions-containing containers, which include submit buttons, with a `container--actions.html.twig` template. (Or all form containers with `container--has-parent.html.twig`.)

If the goal though is truly to target a container for *one particular submit button* and not other submit buttons, that's getting a good deal harder. The problem is even the ID of the form isn't any more precise than the template suggestions the module gives us (for example, this core form has `edit-actions` as its ID, and a webform which gets the suggestion `container--webform-actions.html.twig` simply gets the ID `edit-actions`!)

One approach would be to override `container--actions.html.twig` to remove the div etc. and try to reproduce them as needed in the `input--submit.html.twig` template (a suggestion which core provides). But that's risky because a container can have more than one input button.

Because the information in these buttons themselves are not naturally unique (for example, ID of `edit-submit` on core admin forms and `edit-actions-submit` on webforms), i'll hold off on further digging up possible template suggestions or approaches until the original poster (or other interested parties!) can clarify precisely their intention.

Here's the code the module uses, originally based on Kevin's answer on the related post:

```
function twigsuggest_theme_suggestions_container_alter(array &$suggestions, array $variables)
{
  $element = $variables['element'];

  // We cannot count on template_preprocess_container having run, so we copy
  // its logic here to provide templates for forms (has parents) or not forms.
  // Special handling for form elements.
  if (isset($element['#array_parents'])) {
    $suggestions[] = 'container__has_parent';
  }
  else {
    $suggestions[] = 'container__no_parent';
  }

  if (isset($element['#type']) && $element['#type'] != 'container') {
    $suggestions[] = 'container__' . $element['#type'];
  }

  if (isset($element['#type']) && $element['#type'] == 'container' && isset($element['children']['#type'])) {
    $suggestions[] = 'container__' . $element['children']['#type'];
  }
}

```
> 3 votes

# Answer
```
function MYTHEME_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'container__';
}

```

You can put something like this in your theme. I'm trying to do the same thing, but I only dont know how to get the variables...
> 1 votes

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


title: Redirect to home after NODE_ACCESS_DENY

text:
# Question
Title: Redirect to home after NODE_ACCESS_DENY
My D7 customer uses the Workbench suite of modules to use taxonomy to allow fine-grained access to nodes successfully. But with a large amount of data to manage, sometimes they want to unpublish a node for the time being while keeping the data available in case they want to publish again. In Workbench, I've set up an "Archived" option which successfully renders that content unavailable to anonymous users. So when anonymous users visit that node, workbench, using hook\_node\_access() renders that node to NODE\_ACCESS\_DENY and it appears Drupal takes over and redirects the user to /user. That's good, but the customer wants to redirect back to root if they are anonymous. I thought about modifying Workbench using their API but it seems to be after stepping through how Drupal handles the menu\_execute\_handler() that the redirection to /user occurs. I need workbench to return the DENY so I can use that as one condition to dynamically alter how Drupal renders the view in a DENY situation. But I haven't found which part of core handles this redirection. Hunting through searches I found this suggestion which suggests to handle all 403s.

```
function my_module_menu() {
  $items['403redirect'] = array(
    'page callback' => 'mymodule_unpublished_redirect',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    );
return $items;
}

function mymodule_unpublished_redirect() {
    if (<TRUE>) {
        header('location:'. url('/', array('absolute' => TRUE)), TRUE, 302);
    }
}

```

But when visiting the node that is "Archived" redirects to /user which suggests that this function is ignored at this point. So how should I alter this redirect?

# Answer
> 2 votes
The idea of creating a menu entry to redirect in the case of a 403 is fine, except that you need to configure the core handler to point to it, which is the element missing from your question (it's mentioned in the comment you linked to).

Once you have defined your menu entry go to Administer \> Site Configuration \> Error Reporting and set the value of the 403 page to the corresponding path.

Now the page callback for your menu entry will be invoked whenever there is access denied, so you can supply the appropriate logic for your needs.

---
Tags: hooks, workbench
---


# Question
Title: Cannot translate a content type "The configuration objects have different language codes so they cannot be translated"
I cannot translate a content type

The configuration objects have different language codes so they cannot be translated: node.type.article : fr core.base\_field\_override.node.article.title : en

I think it was because by mistake the article was created in French then after I go back to en... But I don't know how to change it ?

I tried to fix this via drush :

```
drush cset node.type.article langcode en

```

but it doesn't seems to work so I would like to know how to fix it via the admin ?

# Answer
Export the configuration:

```
drush cex

```

then change the langcode in `sites/default/files/config_HASH/sync` and import the configuration again:

```
drush cim

```

Look for all non english langcodes that are in the base `sync` folder (or non default langcode, if you have another default language).
> 2 votes

# Answer
What worked for me, was to make the content type translatable again together with the specific field with the wrong translation. Then add the correct translation.
> 0 votes

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