# Question
Title: How to handle multiple forms' submission in a custom module by clicking on a link
I have 2 forms in my custom drupal7 module.
The 1st one (`mymodule_form1_form`) is a normal form with a lot of fields and a submit button at the bottom.
The 2nd one (`mymodule_delete_data_form`) has 1 hidden field and there is no submit button.
There is a link at the end of the 1st form which triggers a javascript logic. The javascript logic submits the 2nd form.

My problem is that I can't catch the submission of the 2nd form. The page reloads, but it doesn't entry into the `mymodule_delete_data_form_submit` function and I can't run the special business logic that removes the data from the database in this case.

The 1st form

```
function mymodule_form1_form($form, &$form_state, $node, $cid)
{
    $form['field1'] = array(
        '#type'       => 'textfield',
        '#title'      => 'Name',
        '#title_display'  => 'invisible',
        '#size'       => 60,
        '#maxlength'  => 128,
        '#required'   => TRUE,
        '#attributes' => array(
            'placeholder' => 'Name',
        )
    );

    $form['delete_record_link'] = array(
        '#markup'     =>
            "<div class='delete-record'>
                <a href='#' onclick='return false;'>I would like to delete my record...</a>
            </div>",
        '#attributes' => array(
            'class'   => array('additional')
        )
    );

    $form['submit'] = array(
        '#type'  => 'submit',
        '#title' => filter_xss("Submit"),
        '#value' => "Submit",
        '#title_display' => 'invisible'
    );

    return $form;
}

```

The 2nd form

```
function mymodule_delete_data_form($form, &$form_state, $node, $cid)
{
    $form['#submit'][] = 'mymodule_delete_data_form_submit';

    $form['delete_record'] = array(
        '#type' => 'textfield',
        '#title' => 'Remove the data from the database',
        '#title_display' => 'invisible',
        '#size' => 60,
        '#maxlength' => 128,
        '#attributes' => array(
            'placeholder' => 'Remove the data from the database',
        ),
        '#value' => "0"
    );

    return $form;
}

```

The submit function of the 1st form (it works like a charm):

```
function mymodule_form1_form_submit($form, &$form_state)
{
    echo "submit function 1<br/>";
    exit();
}

```

The submit function of the 2nd form (it doesn't trigger):

```
function mymodule_delete_data_form_submit($form, &$form_state)
{
    echo "submit function 2<br/>";
    exit();
}

```

The javascript logic that submits the 2nd form, when you click on the link in the 1st form:

```
jQuery(function() {
    var delete_record_field = jQuery("#edit-delete-record");
    var delete_record_link  = jQuery("#mymodule-form1-form .delete-record a");

    delete_record_link.on("click", function() {
        // set the value of the hidden field to 1
        delete_record_field.val("1");

        // submit the form
        jQuery("#mymodule-delete-data-form").submit();
    });
});

```

What is wrong in my code? How can I catch the submission of the 2nd form?

# Answer
Drupal requires a submit button to submit - it uses the value of the submit button to determine which form was submitted.

Add a submit button to your form, and instead of executing $.submit() on your form, execute $.mousedown() on the hidden submit button.
> 0 votes

---
Tags: forms
---


# Question
Title: drupal_get_form not working when called inside a block
I have a custom module installed which displays a form at user/UID/apps/add. So, what this form does is lets user add node/nodes of "x" content type he/she wants in their app. Form is created using this function-

*function devconnect\_developer\_apps\_edit\_form(array $form, array &$form\_state, stdClass $account, $app\_id = NULL)*

I'm trying to implement this form on every node so that the user can add that particular node to an existing or a new app on a button click.

Figured out I should be passing this nodeID as a default value to the form using drupal\_get\_form. So created a block which renders the said form and to test if the form is being rendered I added it to a page to only see a 500 error.

Here is the block-

```
 <?php
    /**
     * Implements hook_block_info().
     */
    function sei_useapi_block_info() {
      $blocks = array();

      $blocks['MYBLOCK'] = array(
        'info' => t('My block'),
        'cache' => DRUPAL_NO_CACHE,
      );
      return $blocks;
    }

    /**
     * Implements hook_block_view().
     */
    function sei_useapi_block_view($delta = '') {
      $block = array();

      switch ($delta) {
        case 'MYBLOCK':
          $block['subject'] = t('My block title');
          $block['content'] = drupal_render(drupal_get_form('devconnect_developer_apps_edit_form'));
      }
      return $block;
    }

```

Don't have a clue what went wrong. Any ideas? Thanks for reading !

# Answer
> 1 votes
The third argument to your form is $account, and it doesn't have a default argument. You aren't passing that block in your argument, which is why it is crashing.

# Answer
> 0 votes
Rightly pointed, Thanks

For any other noobs like me out there-

```
'page arguments' => array('devconnect_developer_apps_edit_form', $user, NULL),

```

---
Tags: forms, hooks
---


# Question
Title: How do I translate "Please fill out this field." on the user registration form?
Obviously users need to add an email address to register an account.

I'm using the Bartik theme. In Firefox and Chrome, if I don't enter a value for the email address and press submit, the form is not sent; instead, I get a JS popup, "Please fill out this field."

When I search the translation UI, I can't find this string ("Please fill out this field.")

I also can't find the string when I grep for it over the entire D8 git repository.

How do I translate this string?

# Answer
> 10 votes
This message is coming from the browser and not from Drupal, so, there's not much we can do about this, except for not using HTML5 required attributes.

I have my system in French and the message comes in French, and I don't have the French language installed in my site.

Read more about this in the Drupal core issue about "HTML5 validation is not fully accessible".

**EDIT:** It seems that we have a working patch that solve the problem.

# Answer
> 2 votes
You can set it in Javascript with

```
$('input[type="text"]').setCustomValidity("This is a custom message");

```

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


title: bootstrap-carousel.tpl.php not used

text:
# Question
Title: bootstrap-carousel.tpl.php not used
I have the bootstrap D7 Theme as a base themen. I added a new content-type for my header images and then create a bootstrap carousel using the bootstrap carousel view type.

Now I do get a carousel which seems to work fine but it looks crap, so I'd like to style it etc.

So accomplish this I though I could just "overload" bootstrap-carousel.tpl.php. But it doesn't work - it works for other template files though. Even worse: The original bootstrap-carousel.tpl seems to never be used. (Which porbably is the reason why my carousell looks totally unstyled).

What could be the reason for this?

Permission should be fine since it all the same and as I said, overloading other template files works.

Edit: For the carousel feature I use the bootstraps views module. I kind of expected that the tempalte files from the base theme kind of overwrite the ones from the module but it seems that isn't the case. why?

# Answer
Since the bootstrap carousel is based on a content type, you should be overriding node.tpl.php instead. Try dropping a node--bootstrap\_carousel.tpl.php into your theme and making your markup changes there.
> 0 votes

---
Tags: theming
---


# Question
Title: Form API ajax add group of users and numbers
Im quite a newbe to Drupal, but have made some php.

My problem is that by the help of ajax example pages i've made ajax function to show two fields when checkbox is 1.

When i press the add button i get two more fields, but they are not sortet the way i want to.

The fields are Number and User.

The initial layout when checkbox is checked is:

**Number**

**User**

When i press the Add button i get:

**Number** **Number**

**User** **User**

instead of:

**Number** **User**

**Number** **User**

This is my full custom module code:

```
/*
 * Implements hook_menu().
 */
function test_menu() {
  $items['test'] = array(
    'title' => 'Test functions',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'description' => 'Test functions.',
    'access callback' => TRUE,
  );
  return $items;
}

function test_form($form, &$form_state) {

  $form['#tree'] = TRUE;

  $form['terms3'] = array(
    '#type' => 'checkbox',
    '#title' => t('add users.'),
    '#ajax' => array(
      'callback' => 'test_form_callback',
      'wrapper' => 'options',
      'effect' => 'fade',
    ),
  );

  $form['options'] = array(
    '#title' => t("Generated text fields users and usernumber"),
    '#prefix' => '<div id="options">',
    '#suffix' => '</div>',
    '#type' => 'container',
    '#description' => t('This is where we put automatically generated textfields'),
  );

  // Since checkboxes return TRUE or FALSE, we have to check that
  // $form_state has been filled as well as what it contains.
  if (!empty($form_state['values']['terms3']) && $form_state['values']['terms3']) {
      if (empty($form_state['num_names'])) {
        $form_state['num_names'] = 1;
        }
        for ($i = 0; $i < $form_state['num_names']; $i++) {
            $form['options']['number'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('number:'),
            );
            $form['options']['Name'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('Name of user:'),
            );
  }
          $form['options']['add_user'] = array(
            '#type' => 'submit',
            '#value' => t('Add'),
            '#submit' => array('test_form_add_more_add_one'),
            // See the examples in ajax_example.module for more details on the
            // properties of #ajax.
            '#ajax' => array(
              'callback' => 'test_form_callback',
              'wrapper' => 'options',
            ),
          );
          if ($form_state['num_names'] > 1) {
            $form['options']['remove_user'] = array(
              '#type' => 'submit',
              '#value' => t('Remove'),
              '#submit' => array('test_form_add_more_remove_one'),
              '#ajax' => array(
                'callback' => 'test_form_callback',
                'wrapper' => 'options',
              ),
            );
  }
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Click Me'),
  );

  return $form;
}

/**
 * Callback for autotextfields.
 *
 * Selects the piece of the form we want to use as replacement text and returns
 * it as a form (renderable array).
 *
 * @return array
 *   Renderable array (the textfields element)
 */
function test_form_callback($form, $form_state) {
  return $form['options'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function test_form_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function test_form_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

```

Hope someone can help.

# Answer
> 0 votes
You just have to move the $i value.

Instead of

```
for ($i = 0; $i < $form_state['num_names']; $i++) {
            $form['options']['number'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('number:'),
            );
            $form['options']['Name'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('Name of user:'),
            );
  }

```

Use

```
for ($i = 0; $i < $form_state['num_names']; $i++) {
            $form['options'][$i]['number'] = array(
                '#type' => 'textfield',
                '#title' => t('number:'),
            );
            $form['options'][$i]['Name'] = array(
                '#type' => 'textfield',
                '#title' => t('Name of user:'),
            );
  }

```

---
Tags: forms, ajax
---


# Question
Title: Webform twig template causes "the form has become outdated" error
We want to customize the theme of our webforms. We will want the ability to add markup around individual webform elements (like my\_element\_01 and my\_element\_02 in the example below)

Below is a very basic twig template that seems like the right path (based a little on How to access webform elements in webform.html.twig ). However, when I submit this form I get "The form has become outdated. Copy any unsaved work in the form below and then reload this page.".

I have read that the form\_id and form\_build\_id has to be rendered in the template but I am doing that. I am not sure what is wrong or if there is a better approach.

```
{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_01 }}

  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.actions }}

{{ title_suffix }}

</form>

```

# Answer
> 3 votes
The issue was I was not rendering out the {{ element.form\_token }} element. I added that element and it works:

```
{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_02 }}

  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.form_token }}
  {{ element.actions }}

{{ title_suffix }}

</form>

```

This works which is why I submitted it as an answer. I do think it could be better written. This would require effectively using the twig 'without' filter which I can't get to work. I am creating a separate post about that as I feel they are different topics. The basic idea is I shouldn't have to fish or remember to render all the items that make up a drupal form such as form\_build\_id, form\_id, form\_token, or actions. I should render the entire element array and hide the fields I want to wrap in markup. Then I can explicitly render those fields. Something like:

```
{{ element.elements.form_description }}

<form{{ attributes }}>

{{ title_prefix }}

  {{ element|without('elements) }}

  {{ element.elements.my_element_01 }}
  {{ element.elements.my_element_02 }}

{{ title_suffix }}

</form>

```

But that currently renders my\_element\_01 and my\_element\_02 twice.

---
Tags: theming, webforms
---


# Question
Title: How do I stop content overlap with Display Suite on mobile/narrow screens?
Building a site where sugar glider breeders and vendors can list their businesses and wares and find informational articles, links to exotic vets, and more.

The site is built on **Drupal Core 8.2.7** with **Adaptivetheme 8.x-2.0** and uses **Display Suite 8.x-2.6** with the *Fluid two column stacked layout* applied to the *Full Content* view to display business information in a columnar format with contact info and links on the left and tags from several Taxonomies on the right. **Field Group 8.x-1.0-rc6** was used to construct several **Fieldset** groups, and custom CSS was applied to those fieldsets to give them a unique look and border.

This works pretty well on desktop displays, tablets, and some landscape smartphones:

But looks awful if you narrow down a desktop browser or view the site on a portrait smartphone. The boxes adjust well down to a certain size, then "responsive" goes out the window and they start overlapping. The About Us section is in the Footer of the Display Suite layout, so it is unaffected.

The site exhibits the same behavior, where the *Right* and *Left* Display Suite regions overlap on small displays instead of stacking (as would seem logical), regardless of whether the fields are in a Field Group or whether any custom CSS has been applied. This leads me to believe it is something to do with Display Suite, but I have not been able to find any way to control how its regions are rendered. I can control the flow of regions for the theme (e.g. Sidebar 1, Main Content, Sidebar 2) from the theme's Layout settings, but I cannot find any similar functionality for Display Suite regions.

I assume this is possible because my other site (built on the same Drupal Core, Adaptivetheme, Display Suite, and most of the same modules) stacks its content vertically when the screen gets too small. The only significant differences I can think of are that the other site is mostly text next to images or videos rather than text next to text like this one, and the other site's Display Suite layouts are applied to **Paragraphs** instead of being applied to the Content type directly.

Any thoughts for what may be causing this and how to resolve or work around it are welcome.

# Answer
> 0 votes
Found the solution when I discovered a difference between this site and the other that did not register fully when I posted the question.

The Content Types on this site and the Paragraphs on the other both use Display Suite, but this site was using one of the default Display Suite layouts. I built the other one later and used the more flexible Adaptivetheme bootstrap-style layouts.

Turns out the layout is the reason that items were stacking vertically on one site and stubbornly staying side-by-side on the other. When I switched this site to an Adaptivetheme layout like the other, things were much improved:

In case anyone else has a similar issue and is stuck with a default Display Suite layout, I also found that the email field was the only field causing problems. You apparently cannot truncate an Email field, but I found that switching the content regions so the taxonomy tags were on the left and the location, contact, and links were on the right was better than the original layout because the email address could stretch its box without running into the box on the other side.

---
Tags: display-suite, theming
---


# Question
Title: Views row style plugin override not saving in Views UI
In my ongoing journey to create a customized RSS feed in my D8 site, I've finally gotten closest to what I need by using a Feed display in Views. The basic feed is working, but I need to add a couple custom elements for each item. So based on the fact that the rss fields are rendered in the RSSFields class (\Drupal\views\Plugin\views\row)

```
namespace Drupal\video_export\Plugin\views\row;

use Drupal\views\Plugin\views\row;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Renders an RSS item based on fields.
 *
 * @ViewsRow(
 *   id = "mycustom_rss_fields",
 *   title = @Translation("My Custom Fields"),
 *   help = @Translation("Display fields as RSS items."),
 *   theme = "views_view_row_rss",
 *   display_types = {"feed"}
 * )
 */
class MyCustomRssFields extends RssFields {

  public function render($row) {
    parent::render();

  }
}

```

So when I place this in `/modules/custom/video_export/src/Plugin/views/row`, if I go to select the style, I see my new plugin, but when I click Apply, nothing happens. Is there anything else I need to add to my override to get it to save?

# Answer
The issue was an incomplete namespace in the `use` statement for the `RssFields` class. I had

```
use Drupal\views\Plugin\views\row;

```

so it was looking for that class in my module. Changing it to

```
use Drupal\views\Plugin\views\row\RssFields;

```

made everything work.
> 1 votes

---
Tags: views, 8, feeds, plugins
---


title: If Content Type Equals, then

text:
# Question
Title: If Content Type Equals, then
I'm trying to get run some code if the content type of the current page is equal to `events`. I am using Drupal 8.

However, I'm unable to write the if statement.

I've tried:

```
if ($node->type == 'events'){...}
if (Node::getType == 'events'){...}

```

I also saw this question, but I have no idea how to apply it.

Full code:

```
// Add og:event:start_date meta tag

function MY_THEME_preprocess_html(&$variables) {
  if ($node->getType() == 'events'){
    $time = [
      '#tag' => 'meta',
      '#attributes' => [
        'http-equiv' => 'og:event:start_date',
        'content' =>  $node->field_next_time->value,
      ],
    ];

    $variables['page']['#attached']['html_head'][] = [$time, 'og:event:start_date'];
  }

}

```

# Answer
You need to pull the node object out of the variables array.

`$node = $variables['node'];`

In certain preprocess functions this may not be available, so you can try the request service:

`$node = \Drupal::request()->get('node');`

The object must be of type `Node`. Therefore:

`$node->getType() == 'events'`

As Berdir mentioned, you should check and ensure that `$node` is a valid `Node` object to see if it is an instance of `NodeInterface` before operating on it. This will prevent fatal errors in the event that `$variables['node']` is actually a node and not some ad-hoc variable created in code from which you can't call methods on:

### Example 1 (using `$variables` array):

```
if (isset($variables['node']) && $variables['node'] instanceof NodeInterface) {
  $node = $variables['node'];
  $title = $node->getTitle();
  $type = $node->getType();
  // more code...
}

```

### Example 2 (using the request):

```
$node = \Drupal::request()->get('node');

if (isset($node) && $node instanceof NodeInterface) {
  $title = $node->getTitle();
  $type = $node->getType();
  // more code...
}

```
> 7 votes

---
Tags: 8, nodes
---


# Question
Title: How do I make theme suggestions for pagers?
I am trying to create `theme suggestions` function for pagers in my \*.theme. Is this possible in Drupal 8? If it is possible, what is wrong with the following code? Is `suggestions_pager_alter` the right way to access the hook call so I can add a theme suggestion to a page, so I can override the template. I am not worried about the functions logic.

```
function mytheme_suggestions_pager_alter(array &$suggestions, array $variables) {
  // Add template suggestions based on the current view mode.
   print_r(); exit;

}

```

# Answer
`mytheme_suggestions_pager_alter` is the correct way to use the hook. The issue was my pager in the view footer was not working and this stop the function from being called
> 0 votes

---
Tags: theming
---


title: How to extend a function

text:
# Question
Title: How to extend a function
I am new to Drupal. Learning Drupal 8. I am little aware of "hooks", but I am little confused.

For example, I have installed Rate module.

Now, I am trying to do more things based on user's action on RATE, whether vote up/down?

On each vote up/down, add some more details on Node and reward/penalise the node author.

I have tried doing: in my `my_module.module` file

```
function my_module_vote_rate_vote_alter($vote, $context) {
    drupal_set_message(t('called '), 'error');
}

```

But this does not display message.

I know this is third party extension.

But **I am more interested in how to know, which `alter/hook` method I can use within the module/drupal**.

# Answer
I'm not seeing any hook named hook\_vote\_rate\_vote\_alter(), and the Drupal 8 version of the module is in development still. Your problem may be there.
> 1 votes

---
Tags: 8, hooks
---


title: How to alter views page attachments

text:
# Question
Title: How to alter views page attachments
I want to remove the

```
<link rel="canonical" href="/taxonomie_term_url">

```

From my `<head>` section

and add

```
<link rel="next" href="base_url?page=1" />

```

on the first page

```
<link rel="prev" href="base_url" />
<link rel="next" href="base_url?page=2" />

```

on the second

and on the last page only

```
<link rel="prev" href="base_url?page={x}" />

```

I tried to do it in a page\_attachment\_alter() hook but there were no view attachments. Than I tried to do it in a view pre\_render / post\_render / pre\_build / post\_build hook. I'm pretty sure this is the false tendency, though.

```
if($view->current_display == 'block_pager') {
  $links = $view->getBaseEntityType()->get('links');
  if (array_key_exists('canonical', $links)) {
    $links =  array_filter($links, function ($link) {
      return $link !== 'canonical';
    }, ARRAY_FILTER_USE_KEY);
    $view->getBaseEntityType()->set('links', $links);
  }
}

```

But that gives me

```
Drupal\Core\Entity\Exception\UndefinedLinkTemplateException: No link template 'canonical' found for the 'node' entity type in Drupal\Core\Entity\Entity->toUrl() (line 214 of core/lib/Drupal/Core/Entity/Entity.php).
Drupal\node\Controller\NodeViewController->view(Object, 'full', NULL)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
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}()
call_user_func_array(Object, Array) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
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: 652)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

And adding those rel"next/prev" stuff I tried to include them in my html.html.twig but I have no pager context there.

I have found a solution about those next/prev stuff

```
global $pager_total, $pager_page_array;
  $current_path = Url::fromRoute('<current>');
  $path = $current_path->toString();
  if ($path == '/startseite') {
    $path = '/';
  }
  if ($pager_page_array[0] == 1) {
    $prev = '';
  }
  else {
    $prev = '?page=' . $page = $pager_page_array[0] - 1;
  }
  if ($pager_page_array[0] == 0) {
    $attachments['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'next',
        'href' => $path . '?page=' . $next = $pager_page_array[0]+1,
      ],
    ], 'rel_next_first'];
  }
  if ($pager_page_array[0] != 0 && $pager_page_array[0]+1 != $pager_total[0]) {
    $attachments['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'next',
        'href' => $path . '?page=' . $next = $pager_page_array[0]+1,
      ],
    ], 'rel_next'];
    $attachments['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'prev',
        'href' => $path . $prev,
      ],
    ], 'rel_prev'];
  }
  if ($pager_page_array[0]+1 == $pager_total[0]) {
    $attachments['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'prev',
        'href' => $path . $prev,
      ],
    ], 'rel_prev_last'];
  }
  if ($pager_page_array[0] > 0) {
    $attachments['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'canonical',
        'href' => $path . '?page=' . $pager_page_array[0],
      ],
    ], 'canonical_url'];
  }

```

This is the the point where this ghost `<link rel="canonical">` is created. At Line 69 NodeViewController::view()

```
 if ($this->currentUser->isAuthenticated() || $url->access($this->currentUser)) {
   // Set the node path as the canonical URL to prevent duplicate content.
   $build['#attached']['html_head_link'][] = [[
     'rel' => $rel,
     'href' => $url->toString(),
   ], TRUE,];
 }

```

Now if I wrap this snippet with

```
if (rel !== 'canonical') {}

```

It works and that ghost attachment is gone. But hacking core is real evil, so how do I achieve this in a clean or almost clean way?

# Answer
To add next and prev link tags to your add use a page\_attachment\_alter hook.

```
/**
 * Implements hook_page_attachments_alter().
 */
function my_module_base_page_attachments_alter(array &$attachments) {
  global $pager_total, $pager_page_array;
  $current_path = Url::fromRoute('<current>');
  $path = $current_path->toString();
  if ($path == '/startseite') {
    $path = '/';
  }
  if ($pager_page_array[0] == 1) {
    $prev = '';
  }
  else {
    $prev = '?page=' . $page = $pager_page_array[0] - 1;
  }
  if ($pager_page_array[0] == 0) {
    $attachments['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'next',
        'href' => $path . '?page=' . $next = $pager_page_array[0]+1,
      ],
    ], 'rel_next_first'];
  }
  if ($pager_page_array[0] != 0 && $pager_page_array[0]+1 != $pager_total[0]) {
    $attachments['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'next',
        'href' => $path . '?page=' . $next = $pager_page_array[0]+1,
      ],
    ], 'rel_next'];
    $attachments['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'prev',
        'href' => $path . $prev,
      ],
    ], 'rel_prev'];
  }
  if ($pager_page_array[0]+1 == $pager_total[0]) {
    $attachments['#attached']['html_head'][] = [[
      '#type' => 'html_tag',
      '#tag' => 'link',
      '#attributes' => [
        'rel' => 'prev',
        'href' => $path . $prev,
      ],
    ], 'rel_prev_last'];
  }
}

```

For that duplicate canonical I had to alter the entity.node.canonical route controller...

```
<?php

namespace Drupal\my_module\Routing;

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

/**
 * Class RouteSubscriber.
 *
 * @package Drupal\mylife_base\Routing
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    $hmm = $collection;
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setDefault('_controller', '\Drupal\my_module\Controller\NodeViewController::view');
    }
  }
}

```
> 1 votes

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


title: Don't link menu in the active page

text:
# Question
Title: Don't link menu in the active page
My Q is equal as Remove link from active page in menu

> I need the active page in my menu not to be a link.
>
> So let's say I'm on the services page, I need my menu structure to look like this:
>
> ```
> <ul class="menu">
>     <li class="first leaf"><a href="/mysite/">home</a></li>
>     <li class="leaf">services</li>
>     <li class="leaf"><a href="/mysite/portfolio">portfolio</a></li>
>     <li class="leaf"><a href="/mysite/contact">contact</a></li>
> </ul>
>
> ```

How can I do that in drupal 8?

**Update** what about this thing in my theme menu--main.html.twig?

```
{% if item.attributes.hasClass('active') %}
<span>{{ item.title }}</span>
{%- else -%}
{{ link(item.title, item.url) }}
{%- endif -%}

```

# Answer
In D8 the handling of active links is split between php and js, so that the menus can be cached independently from the page they appear on. A solution in php or twig is only possible when you switch off caching of menus, but this is not good for performance. So a better approach is probably in javascript.

Remove the link tag by selecting the links with the class `is-active`:

*mytheme/js/remove-active-links.js*

```
(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.removeActiveLinks = {
    attach: function (context) {

      $(context).find('a.is-active').contents().unwrap();

    }
  };

})(jQuery, Drupal);

```

You need to define a dependency on the core active-link.js, which sets the class `is-active`, so that your js file runs later:

*mytheme/mytheme.libraries.yml*

```
remove-active-links:
  version: 1.x
  js:
    js/remove-active-links.js: { }
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.active-link

```

---

**Background information**

The js code above is the most basic solution, but it loads jQuery also for anonymous traffic, which is not a problem if you already use it.

If you want to avoid jQuery see `ActiveLinkResponseFilter`, which is a response subscriber adding the class `is-active` for anonymous requests.

You can then alter the result in a custom response subscriber with a lower priority, similar to the js code above.
> 4 votes

# Answer
The HTML is generated by a twig template, you should see `{% for item in items %}` in one of your theme's menu templates, and then do a condition e.g. `{% if item.in_active_trail %}`. You could probably just check for `item.in_active_trail` in the item variable, but if that's not good enough, just use Kint (from the devel module) to figure out a variable that works for your situation.
> 0 votes

---
Tags: 8, navigation
---


# Question
Title: What tables are affected by "drush cc all"?
What database tables are affected from `drush cc all`? Obviously, I could gather all the tables starting with cache\_.

Is there any other table that is affected by this command?

# Answer
> 4 votes
The list is dynamic, there's a convention to use `cache_` as a prefix but it's not enforced. Modules can implement `hook_flush_caches` to register names of tables to clear:

> This hook allows your module to add cache table names to the list of cache tables that will be cleared by the Clear button on the Performance page or whenever drupal\_flush\_all\_caches is invoked.

So basically the answer lies in the code for the modules you have installed, and you'll need to invoke that hook to get an accurate list of tables used as cache bins.

---
Tags: drush, caching
---


# Question
Title: Node data retrieval for different language
I have two languages (English \[en\] and Arabic \[ar\]) setup in Drupal 8.3 CMS. I am trying to retrieve data with Node using API, based on the user input language parameter. When I print the node data by default I get result in English language. What will be the simplest way to get result in Arabic?

I am using the following function to get the details from DB.

```
    $node_type = $response['course_type'];

    $nids  = \Drupal::entityQuery('node')->condition('type', $node_type)->execute();
    $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

    foreach ($nodes as $key => $item) {

        $dish_title                                            = $item->title->value;
        $response['get_courses']['dishes'][]                   = trim($dish_title);
        $response['get_courses'][$dish_title]['dish_image'][]  = trim("upcoming");
        $response['get_courses'][$dish_title]['course_name'][] = trim($item->getType());
        $response['get_courses'][$dish_title]['description'][] = trim($item->body->value);
        $response['get_courses'][$dish_title]['dish_name'][]   = trim($dish_title);

}

```

Please refer the following link for the result array. http://www.heypasteit.com/clip/0D7TT6

Thanks.

# Answer
> 0 votes
Use `->getTranslation()` on the node:

```
foreach ($nodes as $node) {
  $node = $node->getTranslation($langcode);
  // get the field values from the translated node
  $field_example_value_translated = $node->field_example->value;
}

```

---
Tags: nodes, taxonomy-terms
---


# Question
Title: Why do I get "Command 'drupal-update' is not defined" when I run "composer drupal-update"?
I'm using Drupal 8.2.7 on XAMPP, on Windows 10. I am installing AMP via Composer, but I received an error when I run `composer drupal-update`.

I ran the command from the Drupal root folder.

> \[Symfony\Component\Console\Exception\CommandNotFoundException\]
> Command "drupal-update" is not defined.

What happened?

# Answer
Neither Drupal core nor Composer define that command. It's the Composer Manager module that defines it.

Be sure to read carefully the instructions to properly install the module, and the following note the project page gives.

> ### Drupal 8
>
> The Drupal 8 version of this module is deprecated and no longer needed, due to improvements in Drupal 8.1. Use Composer directly to get the needed modules, which will also download their required libraries.

The installation instructions are the following.

> ### Installation
>
> * Install the Composer Manager module.
> * Run the module's init.php script on the command line (`php scripts/init.php` from inside the composer\_manager module directory). This registers the module's Composer command for Drupal core.
> * Run `composer drupal-update` from the root of your Drupal directory.

If you are wondering why you don't see the Drupal 8 version in the project page, that is because, as the project page says, the Drupal 8 version is deprecated. The last Drupal 8 version is 8.x-1.0-rc2, visible in the releases page.
> 1 votes

---
Tags: composer
---


# Question
Title: webform: redirect to modified result page
* After somebody submits a webform, he should be redirected to the "webform result" (which is standard generated, but only accessible by clicking the "webform results" tab as an admin).
* My module needs to hook into the "webform results", and add some simple custom PHP calculations on top of that "webform result" (for example: if two radio-elements have a certain value, a warning is displayed on top of that result page)

Any ideas ?

cheers

# Answer
> 0 votes
You have do some customization for this, use hook\_form\_alter().

1. Create a custom module.
2. Create a result page in that module.
3. Alter the webform.
4. Do the calculation.
5. Sent the data to result page and show.

Example:

```
function  MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'webform_client_form_') === 0) {
    // webform_client_form_ (change this id with your form id)

   $form['#submit'][] = 'changeform_form_submit';

  }
}

function changeform_form_submit($form, &$form_state) {
  ... your submission logic ...
}

```

---
Tags: hooks, webforms
---


# Question
Title: Right to left theme: Bootstrap or Zurb Foundation?
I am developing multilingual site (English and Arabic) in Drupal 8. I want to use bootstrap or zurb foundation, which out of these is good for developing Right to left theme. Site will mainly work in Arabic.

# Answer
"Foundation was built to support right-to-left text direction out of the box, but you'll need to make a couple of adjustments to your markup and Sass to get everything up and running." This is just some minor changes, nothing special. For bootstrap there's a special version that is focused on RTL support: https://github.com/Kaakati/RTL\_Bootstrap
> 0 votes

---
Tags: 8
---


# Question
Title: How to test installed configuration entities?
I want to test a custom module, which uses configuration entities, as described in Creating a configuration entity type in Drupal 8. The configuration is during installation of the module populated by multiple entities, as described in this answer.

The module works fine, but when I want to test it, then I receive three (error) messages during installation of the module:

```
public static $modules = array('example');

```

If I delete all the yaml files in the directory config/install/, then the test runs through.

---

The messages:

1. Warning:

> Invalid argument supplied for foreach() in \_batch\_finished() (line 405 of /www/sites/mysite.dev/htdocs/core/includes/batch.inc) #0 /www/sites/mysite.dev/htdocs/core/includes/bootstrap.inc(552): \_drupal\_error\_handler\_real(2, 'Invalid argumen...', '/www/sites/hand...', 405, Array) #1 /www/sites/mysite.dev/htdocs/core/includes/batch.inc(405): \_drupal\_error\_handler(2, 'Invalid argumen...', '/www/sites/hand...', 405, Array) #2 /www/sites/mysite.dev/htdocs/core/includes/batch.inc(333): \_batch\_finished() #3 /www/sites/mysite.dev/htdocs/core/includes/batch.inc(95): \_batch\_process() #4 /www/sites/mysite.dev/htdocs/core/includes/batch.inc(77): \_batch\_do() #5 /www/sites/mysite.dev/htdocs/core/modules/system/src/Controller/BatchController.php(55): \_batch\_page(Object(Symfony\Component\HttpFoundation\Request)) #6 \[internal function\]: Drupal\system\Controller\BatchController-\>batchPage(Object(Symfony\Component\HttpFoundation\Request)) #7 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call\_user\_func\_array(Array, Array) #8 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/Render/Renderer.php(574): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() #9 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer-\>executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure)) #10 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) #11 \[internal function\]: Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() #12 /www/sites/mysite.dev/vendor/symfony/http-kernel/HttpKernel.php(144): call\_user\_func\_array(Object(Closure), Array) #13 /www/sites/mysite.dev/vendor/symfony/http-kernel/HttpKernel.php(64): Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #14 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #15 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #16 /www/sites/mysite.dev/htdocs/core/modules/page\_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #17 /www/sites/mysite.dev/htdocs/core/modules/page\_cache/src/StackMiddleware/PageCache.php(78): Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object(Symfony\Component\HttpFoundation\Request), 1, true) #18 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #19 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #20 /www/sites/mysite.dev/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #21 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/DrupalKernel.php(656): Stack\StackedHttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #22 /www/sites/mysite.dev/htdocs/index.php(19): Drupal\Core\DrupalKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request)) #23 {main}.

2. Notice:

> Undefined offset: 0 in \_simpletest\_batch\_finished() (line 474 of /www/sites/mysite.dev/htdocs/core/modules/simpletest/simpletest.module) #0 /www/sites/mysite.dev/htdocs/core/includes/bootstrap.inc(552): \_drupal\_error\_handler\_real(8, 'Undefined offse...', '/www/sites/hand...', 474, Array) #1 /www/sites/mysite.dev/htdocs/core/modules/simpletest/simpletest.module(474): \_drupal\_error\_handler(8, 'Undefined offse...', '/www/sites/hand...', 474, Array) #2 /www/sites/mysite.dev/htdocs/core/includes/batch.inc(414): \_simpletest\_batch\_finished(false, Array, Array, '1 Sekunde') #3 /www/sites/mysite.dev/htdocs/core/includes/batch.inc(81): \_batch\_finished() #4 /www/sites/mysite.dev/htdocs/core/modules/system/src/Controller/BatchController.php(55): \_batch\_page(Object(Symfony\Component\HttpFoundation\Request)) #5 \[internal function\]: Drupal\system\Controller\BatchController-\>batchPage(Object(Symfony\Component\HttpFoundation\Request)) #6 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call\_user\_func\_array(Array, Array) #7 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/Render/Renderer.php(574): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() #8 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer-\>executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure)) #9 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) #10 \[internal function\]: Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() #11 /www/sites/mysite.dev/vendor/symfony/http-kernel/HttpKernel.php(144): call\_user\_func\_array(Object(Closure), Array) #12 /www/sites/mysite.dev/vendor/symfony/http-kernel/HttpKernel.php(64): Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1) #13 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #14 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #15 /www/sites/mysite.dev/htdocs/core/modules/page\_cache/src/StackMiddleware/PageCache.php(99): Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #16 /www/sites/mysite.dev/htdocs/core/modules/page\_cache/src/StackMiddleware/PageCache.php(78): Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object(Symfony\Component\HttpFoundation\Request), 1, true) #17 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #18 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(50): Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #19 /www/sites/mysite.dev/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #20 /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/DrupalKernel.php(656): Stack\StackedHttpKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request), 1, true) #21 /www/sites/mysite.dev/htdocs/index.php(19): Drupal\Core\DrupalKernel-\>handle(Object(Symfony\Component\HttpFoundation\Request)) #22 {main}.

3. Error:

> InvalidArgumentException: Invalid database prefix: in Drupal\Core\Test\TestDatabase-\>\__construct() (Zeile 81 in /www/sites/mysite.dev/htdocs/core/lib/Drupal/Core/Test/TestDatabase.php).

---

I have published a test module for testing this issue and also a bug report on Drupal.org.

# Answer
It looks like, that simpletests are very sensitive to incorrect types in yaml files. If e.g. in the config/schema/test\_module.schema.yml is a a field with type string:

```
field:
  type: string
  label: 'String'

```

and in the config/install/test\_module.test\_module.id1.yml is a number:

```
field: 1

```

then the error messages are generated. The error messages are not easy to read, so it is quite complicated to find, why the tests fail.

The solution is to change the type of the field:

```
field:
  type: integer
  label: 'String'

```

or to add quotation marks around the number:

```
field: '1'

```
> 1 votes

---
Tags: 8, entities, testing
---


# Question
Title: Create a form for editing a single field of an entity
I need to find a way for users just to edit a specific node field. We have a quite large content type and in a review process we would like some fields of a node to be editable for the revisioning user and some not. To avoid that the revisioning user needs to scroll through a large node form it would be very handy if he/ she would find a link on node detail page close to the text of the field where he/ she is pointed to a form just showing the field.

I found "Editable Fields" and "Quickedit" module which work not so well in our project due to some JavaScript conflicts. Additionally they do not really meet our needs as our main aim is not to make nodes editable on detail page. We just want to show a reduced form to the user for one specific field.

Does anyone has a solution how to create such a form? I think of something like calling the path "custom-form/\[NID\]/\[REVISION\_ID\]/\[FIELD\_NAME\]" which is connected to a page callback which renders a form for field \[FIELD\_NAME\] in node \[NID\] of the corresponding revision version and validating and saving the input respecting the field's widget settings.

# Answer
> -2 votes
You can install the Field Permissions module.

---
Tags: 7, nodes, forms
---


# Question
Title: How do I pull in a group of term descriptions instead of their names?
I am using a taxonomy to categorize content of type "lesson plan" by subject. Each lesson plan can belong to multiple subjects.

In a view where I display these lesson plans, I would like to have a field that lists all of the term's descriptions, rather than their names.

I followed these steps to pull in `Taxonomy term: Term description` instead of `Content: Subject` (where Subject is the name of the vocabulary) in the view.

However, in the Rewrite Results area, `[description]` only pulls in the first term's description, instead of all of them.

How do I get all of them?

# Answer
One quick way to solve it with code would be to add a custom field formatter:

```
function MYMODULE_field_formatter_info() {
  return [
    'taxonomy_term_csv_descriptions' => [
      'label' => t('Taxonomy term CSV descriptions'),
      'field types' => ['taxonomy_term_reference'],
    ],
  ];
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = [];

  if ($display['type'] == 'taxonomy_term_csv_descriptions') {
    $descriptions = [];

    foreach ($items as $item) {
      $descriptions[] = check_markup($item['taxonomy_term']->description, $item['taxonomy_term']->format);
    }

    $element[0] = ['#markup' => implode(', ', $descriptions)];
  }

  return $element;
}

```

That will give you a new formatter to use for taxonomy term reference fields in Views or the Manage Display pages for content types.

If you go with this solution you can remove the relationship to the Taxonomy Term from your View.
> 0 votes

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


title: Taxonomy Terms List and Features

text:
# Question
Title: Taxonomy Terms List and Features
I noticed that, while I am able to build taxonomy into my feature, it doesn't seem to include the list of terms within the taxonomy. When I go to create a feature, the `uuid_term` section does list a few, but not many, actual terms for me to select. What am I missing? It's worth mentioning that I am starting with a Demo build and customizing from there. The only terms that are actually listed are not showing up in Structure \> Taxonomy.

I tried upgrading UUID to no avail.

Drupal 7.54 UUID 7.x-1.0 Features 7.x-2.10

# Answer
You must have Features, UUID and UUID Features modules enabled. In the uuid\_features configuration, `admin/structure/features/uuid_features`, select " Auto detect uuid terms. When exporting a vocabulary, include its terms."
> 2 votes

---
Tags: 7, taxonomy-terms, features
---


# Question
Title: How to add Bootstrap Class like col-md-4 to your fields
This is my form and i want to make all the select tabs in one line How and where i will write bootstrap class to make this all select box come in one row.

# Answer
There is a module named field group. Download that module and then extend that. In Content type field edit form there a button will come with name of add group. Select HTML element and fill the required details and just arrange that in manage form display. U can add any css class. Then save that. Hope that will help
> 1 votes

---
Tags: theming
---


# Question
Title: Message not being sent in the body of the mail
I am using the code below and the mail gets sent but without the body of the message, but the subject is correct am I sending the body in thee wrong parameter?

```
 function mailMessage($msg){
 $mailManager = \Drupal::service('plugin.manager.mail');
 $module = "mymodule";
 $key = 'uploaded files';
 //$to = \Drupal::currentUser()->getEmail();
 $to="diana@me.com";
 $params['message'] = "THIS IS my body of the message";
 $params['node_title'] = "File Upload Report";
 $params['subject'] = "File Upload Report";
 $langcode ="en";
 $send = true;
 $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
 if ($result['result'] !== true) {
   drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
 }
 else {
   drupal_set_message(t('Your message has been sent.'));
 }
}

```

# Answer
> 1 votes
The body of the message is set by the implementation of `hook_mail()` done from the module sending the message. The code invoking that hook is the following one. (See `MailManager::doMail()`, the method called from `MailManager::mail()`.)

```
  // Bundle up the variables into a structured array for altering.
  $message = array(
    'id' => $module . '_' . $key,
    'module' => $module,
    'key' => $key,
    'to' => $to,
    'from' => $site_mail,
    'reply-to' => $reply,
    'langcode' => $langcode,
    'params' => $params,
    'send' => TRUE,
    'subject' => '',
    'body' => array(),
  );

  // Build the default headers.
  $headers = array(
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal',
  );
  // To prevent email from looking like spam, the addresses in the Sender and
  // Return-Path headers should have a domain authorized to use the
  // originating SMTP server.
  $headers['Sender'] = $headers['Return-Path'] = $site_mail;
  $headers['From'] = $site_config->get('name') . ' <' . $site_mail . '>';
  if ($reply) {
    $headers['Reply-to'] = $reply;
  }
  $message['headers'] = $headers;

  // Build the email (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use
  // moduleHandler()->invoke() as we need to have $message by reference in
  // hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

```

As you see, `$message['body']` is set to an empty array before passing it to `hook_mail()`. If your module doesn't implement `hook_mail()`, `$message['body']` will stay an empty array, if there aren't other module that implement `hook_mail_alter()`.
The comment before the code invoking `hook_mail()` is also explicit about what expecting from that hook: *get subject and body, allow additional headers*.

As usual, that is the default implementation of the mail manager. It could be a different mail manager sets the message body to a more significant value, but a module should not depend on the mail manager doing it.

As side note, Drupal doesn't use `$message['message']` as your code does.

# Answer
> 1 votes
You need to add a `hook_mail` code

As this line `$mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);` behind the scenes will invoke this hook\_mail function.

something like this:

```
/**
* Implements hook_mail().
*/
function <module_name>_mail($key, &$message, $params) {

 $options = array(
   'langcode' => $message['langcode'],
 );

 switch ($key) {
   case 'uploaded files':
     $message['from'] = \Drupal::config('system.site')->get('mail');
     $message['subject'] = t('@title', array('@title' => $params['node_title']), $options);
     $message['body'][] = $params['message'];
     break;
 }
}

```

---
Tags: emails
---


# Question
Title: How do I make a list of Users and their total number of posts in a given date?
I have D7 and I can already display a list of users with their total number of nodes with Views but how can I make it so that I can choose the date range? Its like analytics to see if a User has any posts in a given month.

# Answer
You may want to check if using the Views Date Format SQL module could be a solution for you. Here are some quotes about it (from its project page):

> ... allows to format date fields using SQL.
>
> The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE\_FORMAT rather than PHP's format\_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views\_handler\_field\_date.
>
> The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts (disclosure: I'm a co-maintainer) module.
> 0 votes

---
Tags: 7, views
---


# Question
Title: form_get_errors() is NULL when calling it in an AJAX form callback
I have a form with a bunch of required fields that all have the same callback. Here's a single field example:

```
$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => 'callback_show_buttons',
      'wrapper' => 'formwrapper',
    ),
  );

```

`formwrapper` is a wrapper around the entire form:

```
$form['#prefix'] = '<div id="formwrapper">';
$form['#suffix'] = '</div>';

```

Here's the callback, inspired by this guy's code:

```
function callback_show_buttons($form, &$form_state) {
    $allajaxchanges = array( '#type' => 'ajax', '#commands' => array() );

    if ( form_get_errors() ) {
        $form_state['rebuild'] = TRUE;
        $allajaxchanges['#commands'][] = ajax_command_replace( "#formwrapper", render($form) );
    }

 return $allajaxchanges;

```

If I inspect form\_get\_errors(), it is always NULL, no matter if I validate the form in code or not. `drupal_get_messages()` is also completely empty, and `theme('status_messages')` also has nothing in it (these solutions were suggested here). These methods do return something if I submit the form in a non-AJAX way.

Anyone have any idea how to check if a form has errors in it if these don't work?

# Answer
I found a way to make this work.

I haven't fully investigated this for issues yet but it works with and without javascript enabled.

My use case was only running my validation if other validation passed:

```
/**
 * Custom validation function for some form.
 */
function MODULE_NAME_custom_form_validate(&$form, &$form_state) {
  if (isset($form_state['storage']['errors']) && !empty($form_state['storage']['errors'])) {
    return;
  }
  // Do our extra validation here since other validation passed.
}

```
> 0 votes

# Answer
You need to add `drupal_validate_form('give_your_form_id', $form, $form_state)`; on ajax callback function and return `return $form["wrapper"];`
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: Custom javascript file not working in mobile browsers
I have added a custom jQuery file to my theme with the theme.libraries.yml. In my laptop and fullscreen browsers the added javascript is working without any issues. But it seems the javascript does not have any effect in mobile browsers(I'm testing with ipad and iphone browsers in both safari and chrome). My custom\_theme\_libraries.yml is as following

```
global-scripts:
  js:
  js/jqueryfile1.js: {}
dependencies:
- core/jquery

```

And my jqueryfile1.js is as following

```
(function ($){
Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
        $(document).ready(function(){

            //code goes here

            });
        });
    }
};
})(jQuery);

```

Is there any additional configurations to be considered to get the code works in mobile browser also?

# Answer
It seems like your code is the problem. You have extra `});`

Should be

```
(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      $(document).ready(function() {
        // code goes here
      });
    }
  };
})(jQuery);

```

But it is nonsense to use `$(document).ready` as it is already handled by `Drupal.behaviors`.

So the proper way is.

```
(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      // code goes here
    }
  };
})(jQuery);

```

The `attach()` method is called when the DOM has loaded both initially and after any AJAX calls.

See this doc for more info. https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
> 3 votes

---
Tags: theming, 8
---


# Question
Title: Find the password for user admin from a replicated old version of site
I have access to a copy of an old version of a production site on a dev server, but the owner of the website on prod has lost his credentials to admin and doesn't know his ssh login credentials. The only option for me to do his content updates is via the drupal web interface.

I'm able to get into the dev site via **drush uli admin**, but I need the password extracted from the dev server in order to get into the prod website.

How can this be done?

# Answer
> 0 votes
Short answer: it can't be done.

The password is a salted hash, and unless you have access to specialist cracking equipment, you're not likely to reverse engineer that hash in yours, or even your great, great, great, great grandkids' lifetimes. Even with access to the original salt.

As Pierre mentioned in the comments, submitting a password reset link on the live site is probably the simplest course of action.

Or contact your hosting provider; most will find you a way back into a server you're locked out for a nominal fee, once they've verified your ownership.

Bottom line, you're not likely to recover the password from the hash in the database, so you'll need come up with a creative workaround.

# Answer
> 0 votes
Similar to what Clive wrote in the previous answer: it's a waste of time to try to extract that password (at least as of D7, in D6 you could still do that).

Similar to what I suggested in my comment from before:

> If eMail is working in your site, ask for a password reset link. Try to find a way to get access to that eMail (which should arrive at the owner's eMail ID I'd guess ...) and use that link to then reset the password.

If you can't find such way to access that eMail, try these alternatives (if your available infrastructure allows you to do so):

* find a way to perform an edit (using something like PhpMyAdmin) of the database table that contains the eMail Id related to the user with `uid=1`, and adapt that eMail Id to your own eMail Id. Then continue as I suggested in my comment already.
* find a way to perform an edit (using something like PhpMyAdmin) of the database table that contains the roles granted to any of the users that are able to login to the site, and adapt these data to grant such user an admin role. Then login with that userid, and do what's needed (reset password or edit the eMail Id) for the original userid you're trying to get to work again.

# Answer
> 0 votes
Do you have access to the database like PHPMyAdmin or similar? If yes, then you can reset the password by updating the `pass` field.

In your local you can run `./scripts/password-hash.sh abcdef` where `abcdef` is your password then it will generate a hashed password.

But as other mentioned password reset would be the simplest solution.

---
Tags: 7, users, drush, security
---


title: How to get term from alias

text:
# Question
Title: How to get term from alias
I've to get the `taxonomy_term` tid from the alias ('`/alias/of/my/term`')

Is there a way to do this without making a query on url\_alias table?

# Answer
> 1 votes
The only way to avoid a query is if the alias is already in the cache. Rather than worry about that yourself, it's best to use the API (even more so in Drupal 8 as path alias storage is pluggable and may not be in the database):

* Drupal 7, using `drupal_get_normal_path()` :

```
$system_path = drupal_get_normal_path($path_alias, $langcode);

```
* Drupal 8, using the path alias manager service:

```
$system_path = \Drupal::service('path.alias_manager')->getPathByAlias($path_alias, $langcode);

```

As always it's preferable to inject the service into the consuming class if context allows.

Both methods will get you the system path, e.g. taxonomy/term/1, from which you can extract the term ID.

---
Tags: path-aliases
---


title: Drupal 8 - User Login

text:
# Question
Title: Drupal 8 - User Login
I am using Drupal 8 and want to know how I make my wesbite only usable when a user login. At the moment my websites features also used when a user has not logged in.

# Answer
Go to Admin -\> People -\> Permissions, and uncheck any permissions for anonymous users.

Go to Admin -\> Configure -\> People -\> Account settings, and under 'Who can register accounts?', choose 'Administrators only'.
> 1 votes

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


# Question
Title: How does Drupal Commerce use the commerce_line_items field?
I have been trying for some time to figure out how Drupal Commerce uses the `commerce_line_items` field. It looks to me like this is the field that provides the link between a commerce line item and the order to which it is attached, so that if all you had was the order\_id, you wouldn't have to query the entire `commerce_line_items` table, but could just look at this field. However, I cannot figure out how or where this field is defined, and where its values are set. If anybody can get me pointed in the right direction, I will happily write some documentation so that others may understand what is going on.

# Answer
This answer refers to the Drupal 7 version, but I assume it's similar for D8.

The `commerce_line_items` field is a field of type `commerce_line_item_reference` (basically a reference field) that is defined and instantiated inside the function `commerce_order_configure_order_type`, in the file `commerce_order.module`.

This field of unlimited cardinality stores references to each of the line items in an order. Think of the line items as basically each of the "lines" in an order or invoice that reference a specific product, its quantity, price, and total price etc.

The values of the `commerce_line_items` field are initially set in the `commerce_cart.module` file, inside the `commerce_cart_product_add` function (basically when you add a product to the cart), in line 1377.

All of this information can be glanced by studying these files.

\[EDIT\]

I'm not sure I'm understanding where you are going with this question, but given your recent edition, yes, you can access the values of the line items by using, for example, an `entity_metadata_wrapper`, which will allow you to navigate the relationship to each line item and all its fields and properties. See this tutorial for entity\_metadata\_wrapper
> 1 votes

---
Tags: commerce
---


# Question
Title: How can I make a custom content entity ID editable on the content entity form?
I've created a custom content entity with a string ID field named 'lot\_number':

```
*   entity_keys = {
*     "id" = "lot_number",

```

This is its field definition:

```
$fields['lot_number'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Lot Number'))
  ->setDescription(t('Unique alphanumeric lot number for a batch of inventory.'))
  ->setRequired(TRUE)
  ->setSetting('max_length', 20)
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'string',
    'weight' => 10,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'string_textfield',
    'weight' => 10,
    'settings' => array(
      'size' => '10',
      ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->addConstraint('UniqueField', []);

```

My problem is that this lot\_number field does not show up on the content entity form. I tried adding it to the form programmatically in the buildForm() method of my form controller (that extends ContentEntityForm.) The following code gets it to show up on the form:

```
$form['lot_number'] = [
  '#type' => 'machine_name',
  '#title' => $this->t('Lot Number'),
  '#weight' => 10,
  '#size' => 20,
  '#maxlength' => 20,
  '#required' => TRUE,
  '#default_value' => $lot_master->getLotNumber(),
  '#machine_name' => [
    'exists' => '\Drupal\galt_inv\Entity\LotMaster::load',
  ],
  '#disabled' => !$lot_master->isNew(),
];

```

However, when I attempt to submit the form, I get an error message:

```
Error: Cannot unset string offsets in Drupal\Core\Field\WidgetBase->extractFormValues() (line 354 of core/lib/Drupal/Core/Field/WidgetBase.php).

```

I tried changing $form\['lot\_number'\] to $form\['lot\_number'\]\['widget'\]\[0\] in an attempt to make it match the rest of the form elements, but that didn't work at all.

Is there some simple way to get a content entity ID onto the content entity edit form? Any advice would be greatly appreciated.

# Answer
You have both a widget configured and a custom form element, that results in Drupal being confused about the structure.

If you have a form element defined by yourself, don't define form display options and you should be OK.

The reason the widget show up like with other fields is likely actually a regression with the security fix in 8.3.1 that denies edit access to the entity. When we did that, we didn't anticipate a use case like this. You could override the default fieldAccess() method on the EntityAccessControlHandler to grant edit access to the id field, at least when it is new.

Or you do not make the lot number the actual entity ID but have a technical auto-increment ID, then you don't have to worry about this stuff.
> 3 votes

---
Tags: 8, forms
---


# Question
Title: Multilingual multisite problem after changing standard language
We have a multisite and one site is multilingual with (i18n). It contains a lot of translated views (title and standard words like "more" being translated with Views translation (i18nviews)). This works very well as long as the standard language (atm german) is not changed. If we change to another language as standard the view translations are not working anymore, which means the new language gets mixed up with the old standard language on that specific view items.

Has someone else run into this? Where is the configuration setting to get this solved?

Thanks in advance.

Background for this is, that the client wanted another language as front page (so if there's a hint how to solve this in a multisite environment other than changing the standard language, be welcome. We have tried a bunch of htaccess redirects to no avail).

# Answer
Here is a *hint* (as in your question), that might help: make sure the URL of the homepage is defined as a "multilingual" variable. The relative URL to display as the front page is specified within `admin/config/system/site-information`.

If you want to be able to specify a value for it that is different for each of the site's languages, make sure you have made it a "multilingual" variable (it should say "**`This is a multilingual variable.`**" in the description of that variable on that page).

For more details about how to get this done, refer to my answer to "How to make content translation available for front page?".
> 1 votes

# Answer
Try this module https://www.drupal.org/project/lingotek, everything you need is solved with this module, it translate variables, nodes, labels, views, everything. They have a youtube channel https://www.youtube.com/channel/UC-ePFjCRHGIPtDzJDb459Yg
> 0 votes

---
Tags: 7, views, i18n-l10n, multi-sites
---


title: Installing new module

text:
# Question
Title: Installing new module
I have downloaded and installed Drupal 8. The first thing I need to ensure when I create articles URL is automatically generated. In Wordpress this comes by default. But it appears not the case for Drupal.

I searched and found Pathauto (https://www.drupal.org/project/pathauto) will do what I want but facing difficult installing it. The page https://www.fastcomet.com/tutorials/drupal8/module-installation shows a tab **List** with button **+Install New Module** but on my system when I visit http://localhost/admin/modules I don't see the tab **List** or **+Install New Module**.

What could I be missing?

# Answer
If you don't have this button, try to enable the module ***Update manager***. Maybe this makes the button show .. What backend theme are you using ?

Here's the path to the module installation page: `http://localhost/admin/modules/install`
> 2 votes

# Answer
Pathauto will do what you want. Download the module to /modules, and upload it to your server (FTP or via git).

Note that fastcomet.com is not the official docs.

Here are the official docs. https://www.drupal.org/docs/8/extending-drupal/installing-contributed-modules

The docs say you must have Update Manager installed to see the link. I personally do not do that - but to each his own.
> 1 votes

# Answer
Go to admin/reports/updates install bootstap theme. Install and set to default. This should enable both the install theme button and the install module button. You can then revert to the Bartik theme or any other theme.
> 0 votes

---
Tags: 8
---


# Question
Title: How we can define constant in template.php for our theme
I want to define some constant for my theme like theme path etc. How i can achieve that.

For module we can define like this

```
define(THEME_PATH, drupal_get_path('theme', 'xyz'));

```

But it is undefined in theme. Any suggestion would be appreciated.

# Answer
In the preprocess function (hook\_preprocess\_THEME), you can use this:

```
$variables['theme_path'] = drupal_get_path('theme', 'xyz');

```

Which you can then use as $theme\_path in your template.
> 1 votes

---
Tags: theming, hooks
---


# Question
Title: How to create a view with a list of items and item clicked?
I want to create a view which shows a list on the left side and the content of the item in the center. When a user clicks on an item in the list on the left side, the item must be shown in the center region or column. It should be done without page refresh.

Think of a view showing articles. The left side list will show a small image, title and trimmed description, whereas, the middle column will show the actual item clicked.

How to do that?

**Note:** I can use panels as well.

# Answer
> 1 votes
Views does have an Ajax option in the advanced setting, although it may or may not be appropriate or have enough features for what is being described above.

See the previous answers https://stackoverflow.com/questions/3016747/drupal-use-ajax-to-update-views-content and How to load and display a view with Ajax in Drupal 7? and Using AJAX to access the content of a view .

Any solution may or may not require customization.

# Answer
> 1 votes
Here are some pointers. You might have to write some code though:

**Long answer**

* Setup the view (the list of content) as a block and place it in the sidebar.
* You can display the above block for only the relevant node types in the `node/*` path. That way, you have nodes displaying in the main content area.
* Create a `MENU_CALLBACK` using a custom module (or a view maybe?) which will accept an `nid` as input and return the rendered node (markup) as output.
* Now, use `Drupal.behaviors` to add a click-listener to override clicks on the links in the sidebar block.
    + When the user clicks these links, read the node-id of the link clicked. Tip: You can re-write the views field output to include an attribute with the node ID, like `<h2 data-nid="XXX">Node Title</h2>` so that you can easily read the node ID using jQuery.
    + Make sure your `click` callback returns `false` so that the default click event dies in your callback.
    + Use this node-id and send it to the AJAX callback we prepared above. So, in the AJAX response, you will get the markup for the concerned node.
    + Now, simply place the rendered node markup in the `#block-system-main .content` (the main page content block)!

**Short answer**

* list node previews / teasers in a views block placed in the sidebar.
* the user clicks a link in the view.
* node-id is sent to the server to fetch markup for the node and the default click event is killed.
* markup for the node is displayed in the main content region (:

Hope this helps.

# Answer
> 1 votes
Thank you for all the answers. It is amazing that someone once said that In drupal, there is a module for everything.

I found Views Vertical Tabs modules which does exactly what I wanted.

# Answer
> 0 votes
No page refresh means you will have to either load all the data and hide it with JS or bring in data using AJAX. I'm personally not aware of anything like that in Views.

If you are ok with using Panels then 'Panels Ajax Tabs' might be what you are looking for though again I cant tell if it can do what you need right out of the box.

---
Tags: 7, views, nodes, blocks, panels
---


# Question
Title: I use jQuery to alter the exposed form select options. Got error: "An illegal choice has been detected." How to bypass validation?
I have a view that has three expose filters (Manufacturer, Type, Model), three options list (term reference to Printer vocabulary) .

Vocabulary: Printer (3 levels)

```
-- HP
---- xxx
------ xxxx
-- Apple
---- xxxx
------ xxxxxx
-- Dell
---- xxxx
------- xxxxx
-- ...
-- ...
(thousands of terms)

```

Since Form API AJAX doesn't work on views expose form, I am unable to make the them dependent select for exposed form fields. So I used jQuery to make the exposed form fields "dependent select / cascading select".

Basically, I empty all the options in views\_exposed\_form\_alter() firstly:

```
$form['manufacturer_id']['#options'] = $form['type_id']['#options'] = $form['model_id']['#options'] = array();

```

then populate the option lists with my jQuery code accordingly.

However I get "An illegal choice has been detected." on page load, and form submit. Form submission is prevented due to Drupal form validation mechanism .

It's the form validation detect the options generated by jQuery are not come with the original form data, as I removed the options in form alter. Value of a select box is not present in its defined options .

So I tried to remove form validation in form alter as:

```
unset($form['#validate']);

```

still doesn't work, the illegal choice error remains.

============ UPDATED =================

Inspired by @kiamlaluno 's answer below, the only solution I came up is hack/patch the core. Here is what I done:

Edited `/includes/form.inc` : (line 2014)

I removed the code:

```
$element['#needs_validation'] = TRUE;

```

and added:

```
// if not these fields, mark for validation as usual.
// so if are these fields, validation will be passed.

if ($element['#name'] != 'manufacturer_id'  &&
    $element['#name'] != 'type_id'          &&
    $element['#name'] != 'model_id' ) {

  $element['#needs_validation'] = TRUE;
}

```

It works, the exposed form select option bypassed the validation.

But **my solution is very ugly** which modified the core.

I wonder if there is any other solution without touching the core? How can I bypass the validation of these exposed form fields?

Thanks!

# Answer
> 9 votes
The function that shows those errors is \_form\_validate(), which contains the following code.

```
  // Validate the current input.
  if (!isset($elements['#validated']) || !$elements['#validated']) {
    // The following errors are always shown.
    if (isset($elements['#needs_validation'])) {

      // ...

      if (isset($elements['#options']) && isset($elements['#value'])) {
        if ($elements['#type'] == 'select') {
          $options = form_options_flatten($elements['#options']);
        }
        else {
          $options = $elements['#options'];
        }
        if (is_array($elements['#value'])) {
          $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
          foreach ($value as $v) {
            if (!isset($options[$v])) {
              form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
              watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
            }
          }
        }

        // ...
      }

```

The function is always executed, whenever the form has a validation handler, or not.

You could set `$form['#needs_validation']` to `FALSE`, but \_form\_builder\_handle\_input\_element() sets it to `TRUE`. The function is called from form\_builder(), which is then called from drupal\_process\_form(), or drupal\_rebuild\_form().

```
  // Mark all posted values for validation.
  if (isset($element['#value']) || (!empty($element['#required']))) {
    $element['#needs_validation'] = TRUE;
  }

```

After `_form_builder_handle_input_element()` is called, `form_builder()` calls any #process function set for the form element.

```
  // Handle input elements.
  if (!empty($element['#input'])) {
    _form_builder_handle_input_element($form_id, $element, $form_state);
  }
  // Allow for elements to expand to multiple elements, e.g., radios,
  // checkboxes and files.
  if (isset($element['#process']) && !$element['#processed']) {
    foreach ($element['#process'] as $process) {
      $element = $process($element, $form_state, $form_state['complete form']);
    }
    $element['#processed'] = TRUE;
  }

```

It also calls any #after\_build functions set for the form element.

```
  // The #after_build flag allows any piece of a form to be altered
  // after normal input parsing has been completed.
  if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
    foreach ($element['#after_build'] as $function) {
      $element = $function($element, $form_state);
    }
    $element['#after_build_done'] = TRUE;
  }

```

You could set a `#after_build` function that executes code similar to the following one.

```
function mymodule_remove_validation($form_element) {
  unset($form_element['#needs_validation']);

  return $form_element;
}

```

I am using `unset($form_element['#needs_validation'])` because the if-statement in `_form_validate()` checks `isset($elements['#needs_validation'])`, instead of `!empty($elements['#needs_validation'])`.

In this way, the form element would not have `#needs_validation` set to `TRUE`, and Drupal would not check the returned value for the form element is one of the possible values it can get, nor is the length of a textfield string longer than required.
It doesn't avoid the form validation handlers are run, thought.

# Answer
> 4 votes
You need empty '#options' not in form\_alter but in theming function. In this case validation will not display 'illegal choice error'.

First in views\_exposed\_form\_alter() add custom theme function to your selects.

```
$form['manufacturer_id']['#theme'][] = 'select_empty';
$form['type_id']['#theme'][] = 'select_empty';
$form['model_id']['#theme'][] = 'select_empty';

```

Then in module or template.php file create new theme function.

```
function THEME_NAME_theme($existing, $type, $theme, $path) {
  return array(
    'select_empty' => array(
      'render element' => 'element',
     ),
  );
}

function THEME_NAME_select_empty($vars) {
  // Empty select values and add one fake option for correct theming.
  $vars['element']['#options'] = array(
    'All' => t('All'),
  );

  // return default select.
  return theme('select', $vars)
}

```

# Answer
> 1 votes
IIRC, it's not possible to disable validation on Form API starting from Drupal 6. Instead of emptying out options in Drupal, you can empty them with jQuery. This way, the options still exist on the Drupal side, and the validation error is not triggered.

# Answer
> 0 votes
The hard part is updated, available colors, change the shape of the filter through AJAX. We can only tell an exposed filter to update its values on the basis of a AJAX UI through it will be great. Unfortunately, it is not yet possible. Actually, it is not possible to expose the filter to provide dynamic values is logical to consider any kind. When it can not change it because you will need to refresh themselves through AJAX? HPE0-Y53 PDF Dumps

---
Tags: 7, forms, views
---


# Question
Title: Drupal Commerce Relationship Description
A small question:

Shouldn't the Help text in the commerce\_line\_item module at line 1582 that defines the relationship between commerce\_line\_items and commerce\_orders say something like "Relate this entity to the order to which it is attached". As it now stands, the text says "Relate this entity to the line items reference by its commerce\_line\_items field". Which doesn't seem to make much sense.

# Answer
OK, I think I understand this now, and the Help text is actually correct as it stands.

Each order, it turns out, has a commerce\_line\_items \[note the plural\] field attached to it, and it is this field, of unlimited cardinality, that stores all of the commerce\_order/commerce\_line\_item pairs that are associated with this order. What this relationship does, then, is make the commerce\_line\_item reference field that is stored in the commerce\_line\_items field available to the view designer. Once this commerce\_line\_item reference field is available, all of the fields in the commerce\_line\_item itself become available.

The thing that was confusing is that the commerce\_line\_items field does not show up in a Site Builder's "Manage Fields" configuration screens, and I had not been able to find it in the code. Many thanks to argiepiano, who showed me where to find the definition of the commerce\_line\_items field \[in the commerce\_order module\], and the place where data is saved into that field \[in the commerce\_cart module\].

So that is the way that this all works ...

... I think.
> 0 votes

---
Tags: commerce
---


title: Load form and use custom submit handler

text:
# Question
Title: Load form and use custom submit handler
In my Controller I'm loading a form with the following code.

```
$form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\CustomForm');

```

Depending on different cases I would like to use different processing of the form.

I see 3 possibilities to handle this:

1. Use different forms and load the correct depending on the case
2. Include some hidden fields and evaluate these fields in the submit handler of the form
3. Use different submit handlers

I think the third possibility is the best one. But when I try to use a custom submit hanlders.

```
$form['#submit'] = 'custom_module_form_submit';
// or
$form['actions']['submit']['#submit'][] = 'custom_module_form_submit';

```

They both don't work. How can this be achieved? Is there a better way of doing this?

# Answer
@kiamlaluno is right, you have to use the form builder directly. But for this question in the comments there is a solution:

> ... its a custom class extending FormBase. But I still don't get how to change the submit handler. In my controller ...

you can put additional parameters in `formBuilder()->getForm('Drupal\custom_module\Form\CustomForm', $param)`, which you then can use in the form class to build the form differently, for example add different submit handlers:

```
  public function buildForm(array $form, FormStateInterface $form_state, $param = NULL) {

    if ($param == 1) {
      $form['actions']['submit']['#submit'][] = 'custom_module_form_submit';
    }

  }

```
> 1 votes

---
Tags: 8, forms
---


title: Content Type User Permissions

text:
# Question
Title: Content Type User Permissions
Is there a way to change the user permissions of a content type? As I would not like the anonymous user to access a specific content type.

# Answer
You could use the Group module. All you'd have to do is:

* Create 1 group (pick your name) in 1 group type (pick your name).
* Give access to all users to that group.
* Use the group permissions to indicate you do NOT want to give anonymous users access to the content type you have in mind.

Done.
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: Is it possible to change the view type form "content" to "content revision"?
I created a view with several displays. The view type is CONTENT.

But now I need to change the type from CONTENT to CONTENT REVISION, without to be constrained to rewrite all the displays.

Is it possible?

# Answer
Technically speaking, the type of a view corresponds to the base table against which a database query is executed. This means that it sets the stage, so to speak, for the data that is going to be collected. All fields, filters, sort options etc. are configured in relation to that starting point.

Since changing the view type would mean changing the base table, you would be replacing the foundation your view is built on. This a tricky thing to do, because the data you are collecting may not relate to the new base table as it did to the old base table. (In a more radical example, imagine turning a Content view, which retrieves the node ID, into a User view. That would break because users do not have a node ID.)

So is it completely impossible? Maybe not, especially because node and node revisions are somewhat similar. When you look at the exported configuration (YAML markup) of a "Content" view, you will see a line `base_table: node_field_data`. In a "Content revisions" view you will find the line `base_table: node_field_revision`. If I had to try this (disclaimer: I never did!), I would do the following:

1. Duplicate the view I want to change (so I don't lose the original) and save it without changing anything
2. Go to /admin/config/development/configuration/single/export to get the config YAML of the duplicated view
3. Copy the config and paste it into a text editor
4. Change `base_table: node_field_data` to `base_table: node_field_revision`
5. Delete the duplicated view
6. Copy the edited YAML from your text editor and import it via /admin/config/development/configuration/single/import
7. Hope that the import doesn't generate errors
8. Go to the configuration screen of your newly imported view, see if it reports problems, and try to make it work

Good luck. When you do try the above, I would love to read if it worked for you.
> 2 votes

---
Tags: views
---


# Question
Title: Secure pages and installing new modules (AJAX error)
I've just configured my website to work with secure pages and everything seems to be working fine except for the ability to install a new module. Whenever I try, I get this error:

> An AJAX HTTP request terminated abnormally. Debugging information follows. Path: https://www.mysite.com/authorize.php?batch=1&id=329&op=do\[1\] StatusText: ResponseText: ReadyState: 4

It also offers an error page that says this:

> Notice: Undefined index: log in update\_authorize\_install\_batch\_finished() (line 250 of /home1/me/public\_html/mysite.com/modules/update/update.authorize.inc). Warning: Invalid argument supplied for foreach() in update\_authorize\_install\_batch\_finished() (line 250 of /home1/me/public\_html/mysite.com/modules/update/update.authorize.inc). Notice: Undefined index: log in update\_authorize\_install\_batch\_finished() (line 291 of /home1/me/public\_html/mysite.com/modules/update/update.authorize.inc). Notice: Undefined index: tasks in update\_authorize\_install\_batch\_finished() (line 292 of /home1/me/public\_html/mysite.com/modules/update/update.authorize.inc). Installation failed! See the log below for more information.

All I can find on secure pages and AJAX is to add `*/ajax/*` to the "ignore pages" field. I've done that but I'm still having the same issue. Has anyone else figured this out? I feel like it should be pretty standard stuff!

# Answer
I got this same error, but the cause was unrelated to secure pages, so it may not apply to your case. Mine resulted from upgrading to Drupal 7.3 and having uncommented the two lines in the .htaccess file "To redirect all users to access the site WITHOUT the 'www.' prefix." When I commented those two lines, my module installer started working again. So if you have those two lines in .htaccess uncommented, try commenting them out and see if that makes a difference.
> 0 votes

# Answer
I had the same problem installing modules, would receive the same error mentioned in OP.

After reading the first answer posted above, I tried that but it did not work for me. However, that made me think my other edits to .htaccess (redirect to HTTPS for all links) may be the cause. I restored the original .htaccess that is installed with drupal and I was able to get past the error I was having.

I then restored the .htaccess file for the HTTPS redirects and things seem to be working fine.
> 0 votes

---
Tags: 7, ajax, installation, security
---


# Question
Title: Migrating Users with Migrate D2D when/if they already exist
How does Migrate D2D module handle the migration of users if the matching users already exist in the database? I did a user import with MySQL different way earlier, but I want to do it through this module in order to scoop up a few missing pieces, such as the user avatars.

Thanks!

# Answer
> 0 votes
If Migrate and Migrate D2d modules are installed with the UIs, go to Content \> Migrate tab. Once you get the migration set up, there is an option under "options". Check "update" and it will just update the existing users with any information that is new or not matched, keeping the UIDs, etc. It will also update with any new users. It's a long process if you have a lot of users, but so far so good.

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


# Question
Title: Why with new bootstrap 3x-3.13 it doesn't work?
After update bootstrap module my theme doesn't work correctly. I use this code in my template.php (sub theme based on bootstrap).

```
function mytheme_preprocess_block(&$variables) {
  $block = $variables['block'];

  // Create css id attribute based on the block's administrative name
  if ($block->module == 'block') {
    $custom = block_custom_block_get($block->delta);
    $id = strtolower($custom['info']);
    $variables['block_html_id'] = $id;
  }
}

```

It was before I updated module

It's after

# Answer
First of all, bootstrap is a theme not module. You were using following code to above the main container(outside the image area as soon in your attachment):

```
function mytheme_preprocess_block(&$variables) {
  $block = $variables['block'];

  // Create css id attribute based on the block's administrative name
  if ($block->module == 'block') {
    $custom = block_custom_block_get($block->delta);
    $id = strtolower($custom['info']);
    $variables['block_html_id'] = $id;
  }
}

```

If you were using this code in bootstrap theme's template.php, instead of a child theme, than after updating the theme the custom code will be no more there as the old files are replaced by new updated files.

So you need to add your code in new template file updated.
> 0 votes

---
Tags: 7, theming
---