title: How to show a View with Rules

text:
# Question
Title: How to show a View with Rules
I want to add an action that shows a view whenever the user earns User Points. I checked it and there's no rules for Views so I'm wondering how could I do it.

I'm using Drupal 7.

# Answer
Assume that the path to the view you want to show is "`SomePath`". Then just create a rule with a Rules Action to "perform a redirect", to the path `SomePath`.

For a rule with such Rules Action, you just use whatever Rules Event that fits your needs (something related to user points I assume), and optionally add whatever Rules Conditions that fit. For a rule that you can probably use as a good starting point, have a look at my answer to "How to change user info with a rule when Points are granted to user (using userpoints module)?" (if you'd just add a Rules Action to redirect, you may be close already).
> 0 votes

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


# Question
Title: What is the template file for node add/edit page?
I need to add extra CSS styles for a set of fields in the node add page for the *jobs* content type, but I don't know what template file should I use. I enabled Twig debugging, and I tried the following options.

* page--node--add--jobs.html.twig, but it shows all regions
* `hook_theme()`, but the custom template is not getting applied

My code for `hook_theme()` is the following.

```
 function custom_module_theme() {
  //  dpm("node:".drupal_get_path('module', 'comp_jobs'));
  return [
    'node-jobs-form' => [
      'render element' => 'form',
      'template' => 'jobs',
      'path' => drupal_get_path('module', 'comp_jobs') . '/templates',
    ],
  ];
}

```

What template file should I use, and how do I tell Drupal to use that?

# Answer
The template for the node add form is **node-edit-form.html.twig**. But adding attributes to form fields is not an easy task in twig. You probably are able to do this more efficient in a form alter hook.
> 0 votes

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


title: Move aggregated JS file to the footer

text:
# Question
Title: Move aggregated JS file to the footer
Is there a method of moving the aggregated JS files to the footer? I've taken a look at hook\_js\_alter but that just gives me access to the individual files, not the aggregated ones.

I would prefer to not move the $scripts variable to the bottom of html.tpl.php

Any tips would be appreciated.

# Answer
> 0 votes
There is a module called Magic that will take care of all this for you instead of rolling your own approach.

# Answer
> 6 votes
Found this excellent code snippet for Drupal 7: https://gist.github.com/pascalduez/1418121

It offers a way to have $script and $head\_scripts so that you can specify which JS files need to go in the head. Example, Modernizr should go into the head scripts.

I'm copy pasting below the solution in the link to future proof the answer.

Cheers.

**html.tpl.php**

```
<!DOCTYPE html>
<html<?php print $html_attributes; ?>>
<head>
<?php print $head; ?>
<title><?php print $head_title; ?></title>
<?php print $styles; ?>
<?php print $head_scripts; ?>
</head>

<body<?php print $body_attributes;?>>
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $scripts; ?>
<?php print $page_bottom; ?>
</body>
</html>

```

**template.php**

```
// Used in conjunction with https://gist.github.com/1417914

/**
* Implements hook_preprocess_html().
*/
function THEMENAME_preprocess_html(&$vars) {
// Move JS files "$scripts" to page bottom for perfs/logic.
// Add JS files that *needs* to be loaded in the head in a new "$head_scripts" scope.
// For instance the Modernizr lib.
$path = drupal_get_path('theme', 'THEMENAME');
drupal_add_js($path . '/js/modernizr.min.js', array('scope' => 'head_scripts', 'weight' => -1, 'preprocess' => FALSE));
}

/**
* Implements hook_process_html().
*/
function THEMENAME_process_html(&$vars) {
$vars['head_scripts'] = drupal_get_js('head_scripts');
}

```

# Answer
> 5 votes
~~All of these examples are incorrect.~~ *Edit: The answer from TwoD posted after mine is also legit, although the easiest thing is still to use AdvAgg or Magic modules.*

Do not alter your templates or create new ones. Do not create new variables such as `$head_scripts`. This is incompatible with contrib modules because they don't know about your customizations. The Drupal API has had has had a solution for placing scripts in the footer scope since Drupal 6 was released in 2008.

The only correct way to do this is by using the `scope` setting within `drupal_add_js()`, which you can read about within the Drupal 7 API docs:

> **scope**: The location in which you want to place the script. Possible values are 'header' or 'footer'. If your theme implements different regions, you can also use these. Defaults to 'header'.

To re-iterate, this is the **only proper way** to move scripts into the footer. Any other way is a hack and will potentially break modules. Do not move the `$scripts` variable around inside your `html.tpl.php` template. That is wrong.

For Modernizr in particular, you can use the Modernizr Drupal module and it will properly place the JavaScript library at the beginning of your header JS stack... except if you've moved `$scripts` to the wrong location within the template.

If you'd like to see a code snippet that details how to *properly* scope all of your JS to the footer read this blog post:

http://pixel-whip.com/drupal-load-scripts-last.html

This pattern has been adopted by the community and several modules and themes respect these settings. Use a module such as Magic or AdvAgg to safely move the remaining scripts into the `footer` scope of Drupal's JS output. Major base themes such as Omega and Aurora are built to respect these settings as well.

# Answer
> 4 votes
Any method of moving scripts around must respect the way scripts are ordered, and thus loaded and executed, since they may perform tasks which cannot be postponed until the DOM is done loading.

Moving the `$scripts` variable to just above `$page_bottom` is one quick way of achieving this, and should be safe, but won't let you easily keep any scripts in the header.

The snippet at http://pixel-whip.com/drupal-load-scripts-last.html may be a popular way, but it shows this flaw very clearly. Any script expecting to run before the page is done loading, but after `Drupal.settings` has been set, will be unable to function properly because settings will always end up at the bottom of the script pile.

The documentation for drupal\_add\_js() shows how scripts are ordered. Note that the scope matters more than anything else, but drupal\_sort\_css\_js() does not take scope into consideration. This is because scripts from different scopes are normally requested separately, so there's no need to group by that first. Simply mashing all scripts into the 'footer' scope will make 'group' the most important sorting criteria, but scripts in different scopes can have the same group set while still needing to have one load before the other.

The settings object generated on the server and passed to the client as a JSON object creates a slight problem here, as drupal\_get\_js() normally "hard codes" it just after the header scripts, and thus ignores things like grouping or weighting for the inline script it creates.

One way to move scripts to the footer, while maintaining their relative order and keeping settings correctly positioned, from within a template.php file is like something like the hook implementation below. the code could probably be optimized a bit, especially if you only have 'header' and 'footer' scopes, but still runs quick enough.

```
/**
 * Implements hook_js_alter()
 *
 * Moves scripts from the header scope (and others) to the footer, maintaining
 * their relative positions by adjusting script groups while also making
 * sure settings are positioned just after the original header scripts.
 */
function MYTHEME_js_alter(&$javascript) {
  // List the scripts we want in to remain in their original scope.
  $untouched_scripts = array(
//   'sites/all/libraries/modernizr/modernizr.min.js',
  );

  $scopes = array(
    'header' => array(),
    'other' => array(),
    'footer' => array(),
  );
  // Scope group weights.
  $header_max = NULL;
  $other_min = NULL;
  $other_max = NULL;
  $footer_min = NULL;

  foreach ($javascript as $key => &$script) {
    // Categorize scripts by original scope.
    switch ($script['scope']) {
      case 'header':
        // Find the last header group weight.
        if (!isset($header_max) || $script['group'] > $header_max) {
          $header_max = $script['group'];
        }

      case 'footer':
        // Find the first footer group weight.
        if (!isset($footer_min) || $script['group'] < $footer_min) {
          $footer_min = $script['group'];
        }
        $scopes[$script['scope']][] = &$script;
        break;

      // It's impossible for to know in which order scopes defined by a
      // theme will be rendered, so just put them all together for now.
      // Ordering these scopes, if needed, is left as an exercise for the reader.
      default:
        // Find the first other group weight.
        if (!isset($other_min) || $script['group'] < $other_min) {
          $other_min = $script['group'];
        }
        // Find the last other group.
        if (!isset($other_max) || $script['group'] > $other_max) {
          $other_max = $script['group'];
        }
        $scopes['other'][] = &$script;
    }
    // Move scripts to footer.
    if ($script['scope'] !== 'footer' && !in_array($script['data'], $untouched_scripts)) {
      $script['scope'] = 'footer';
    }
  }
  if (!isset($header_max)) {
    // Just in case there were no header scripts.
    $header_max = -1;
  }

  $last_max = $header_max + 1;

  // Add settings as an inline script after the last header group.
  if (isset($javascript['settings'])) {
    $inline_settings = array(
      'type' => 'inline',
      'scope' => 'footer',
      'data' => 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($javascript['settings']['data'])) . ");",
      'group' => $last_max,
      'every_page' => TRUE,
      'weight' => 0,
    ) + drupal_js_defaults();
    // No need for drupal_get_js() to do this again.
    unset($javascript['settings']);

    $javascript['inline_settings'] = $inline_settings;
  }

  // If there are other scopes, push them all down below the header scripts.
  if (isset($other_min) && $other_min <= $last_max) {
    $diff = $last_max - $other_min + 1;
    foreach ($scopes['other'] as $key => &$script) {
      $script['group'] += $diff;
    }
    $last_max = $other_max + $diff;
  }
  if (!isset($footer_min)) {
    // Just in case there were no footer scripts.
    $footer_min = $last_max;
  }
  // Finally push footer scripts down below everything else.
  if ($footer_min <= $last_max) {
    $diff = $last_max - $footer_min + 1;
    foreach ($scopes['footer'] as $key => &$script) {
      $script['group'] += $diff;
    }
  }
}

```

This removes the need for any extra modules, and calling `drupal_get_js()` from anywhere will return the correctly ordered output.

This also works when Drupal's JavaScript aggregation/optimization setting is enabled.

# Answer
> 1 votes
Moving the `print $scripts` to the end of the page is the proper way to do it. In fact, I seriously doubt there is any other way.

I typically do this on all of my sites now. You need to keep an eye out for modules that add elements to the content and not with the Javascript API. Google Custom Search is one module that comes to mind that does this.

On one Drupal 6 site we did a few years ago, we had to port some legacy JS to Drupal and ended up using `drupal_get_js()` to get the JS for the page, split it out via regular expressions, build up `$scripts1`, `$scripts2`, `$scripts3`, etc, and then add them to `$variables` via a `template_preprocess_page()` for printing in the page template. This was a very custom theme, but it ended up as a messy solution. I don't recall how we handled aggregation.

Something similar to this would be your only real solution, and would require a lot of custom work.

---
Tags: javascript, css-js-aggregation
---


# Question
Title: Changing site:mode throws Twig memory error
I am trying to toggle the site mode for a new Drupal 8 development site. When I run the command `drupal site:mode dev` I get the following error:

```
PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 1038876672 bytes) in phar:///usr/local/bin/drupal/vendor/twig/twig/lib/Twig/Extension/Debug.php on line 56

```

Increasing the memory (even to something huge) doesn't resolve this. Is Twig trying to throw an error, or output loads of data? How can I fix this please?

# Answer
> 4 votes
You're debugging an entity or other object somewhere that has recursive references and debug gets into an endless recursion until all memory is used up.

Instead of debug(node) or similar, use debug(node.toArray()), that gives you the raw value instead of huge object structures.

---
Tags: 8
---


# Question
Title: How to remove duplicate nodes in a view with taxonomy relationship (1 node per term)?
I have a fairly straightforward view. Ie. Display nodes that are published & of content type X. Then sort by date.

It does however, have a relationship to a Vocabulary so that I can get access to the taxonomy image to display.

The result is a view that displays duplicate nodes if there is more than one taxonomy term of that vocab tagged on it.

How can I remove these duplicates?

I've tried the Query settings Distinct/Pure Distinct to no avail.

I'm also looking at this, but I'm hoping for a different solution. Views relationship outputting duplicate nodes?

**Update** I had seen the Views distinct module (suggested in an answer now) and should have added it to the possible solutions. I'm still hoping for a "*I just didn't know how to configure the view properly*" kind of solution, as it feels like there must be a way to do this in Views instead of adding another module.

# Answer
https://www.drupal.org/project/views\_distinct

use this module and configure the settings in the view Field.

This will remove those duplicates from your view. do this for the duplicated field items.
> 3 votes

---
Tags: 7, views
---


# Question
Title: get all parent terms of a term using php - Notice: Array to string conversion
I have term with tid=9 (sublevel 3). It is nested under 2 other terms. I use following code to get names of its parent terms:

```
    <?php
//term id of term that you are checking for top parent
$term_tid = '9';
//this will be your top parent term if any was found
$top_parent_terms = array();

$parent_terms = taxonomy_get_parents_all($term_tid);

//top parent term has no parents so find it out by checking if it has parents
foreach($parent_terms as $parent) {
  $parent_parents = taxonomy_get_parents_all($parent->tid);
  if ($parent_parents != false) {
    //this is top parent term
    $top_parent_term[] = $parent;
  }
return $top_parent_term;
}
?>

```

Problem: As a result I am getting "array" with error: "Notice: Array to string conversion in php\_eval() " instead of terms names. I tried bunch of other solutions but none of them work or I get same error (for example here https://api.drupal.org/comment/59421#comment-59421)

# Answer
> 0 votes
I think this is closer to what you want:

```
<?php
    //term id of term that you are checking for top parent
    $term_tid = '9';
    $parent_terms = taxonomy_get_parents_all($term_tid);

    //top parent term has no parents so find it out by checking if it has parents
    foreach ($parent_terms as $parent) {
      $parent_parents = taxonomy_get_parents_all($parent->tid);
      if (empty($parent_parents)) {
        //this is top parent term
        return $parent;
      }
    }
?>

```

Explanation:

* You don't need the `$top_parent_terms variable`. You can return the first `$parent` you encounter that doesn't have a `$parent_parent`.
* You were also probably having issues because you declare `$top_parent_terms`, but reference `$top_parent_term` (missing an 's').
* Also, this bit `$top_parent_term[] = $parent` would produce a result like this: `$top_parent_term = array(0 => $parent)` when you probably want `$top_parent_term = $parent`.
* Note that the returned `$parent` variable will be an object, not an array. taxonomy\_get\_parents\_all returns an array of term objects.

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


# Question
Title: Disable autocomplete entity reference field
In my page content type, I've created an entity reference field that references another page content. When entering data into the entity reference field, it does a search of all the content on the site and returns a list of it. I want to be able to just enter in the node ID, instead of making it search for it.

Currently, you cannot just put in the node ID, as it will throw an error about content not existing.

Is there a way to just input just the node ID? Is there a special format?

# Answer
There are a couple of options on how to do this.

1) switch the field settings reference method from "default" to "view", and create an entity reference view where the label is the nid

2) create a field widget plugin based on EntityReferenceAutocompleteWidget.php in your custom module, and replace the form element

```
'#type' => 'entity_autocomplete',

```

with a text field.

```
 '#type' => 'textfield',

```

Below is a custom widget that does this.

Most of the changes are within the formElement method, but I added some validation to check if the entity is a valid entity of the correct type within the allowed bundles.

```
namespace Drupal\mymodule\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;

/**
 * Plugin implementation of the 'entity_reference_textfield' widget.
 *
 * @FieldWidget(
 *   id = "entity_reference_textfield",
 *   label = @Translation("Textfield"),
 *   description = @Translation("A text field for entity reference"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class EntityReferenceTextField extends WidgetBase  {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'size' => '60',
      'placeholder' => '',
    ) + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element['size'] = array(
      '#type' => 'number',
      '#title' => t('Size of textfield'),
      '#default_value' => $this->getSetting('size'),
      '#min' => 1,
      '#required' => TRUE,
    );
    $element['placeholder'] = array(
      '#type' => 'textfield',
      '#title' => t('Placeholder'),
      '#default_value' => $this->getSetting('placeholder'),
      '#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
    );
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();

    $operators = $this->getMatchOperatorOptions();
    $summary[] = t('Textfield size: @size', array('@size' => $this->getSetting('size')));
    $placeholder = $this->getSetting('placeholder');
    if (!empty($placeholder)) {
      $summary[] = t('Placeholder: @placeholder', array('@placeholder' => $placeholder));
    }
    else {
      $summary[] = t('No placeholder');
    }

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $values = $items->getValue();

    $element += array(
      '#type' => 'textfield',
      '#default_value' => isset($values[$delta]) ? $values[$delta]['target_id'] : NULL,
      '#size' => $this->getSetting('size'),
      '#placeholder' => $this->getSetting('placeholder'),
    );

    return array('target_id' => $element);
  }

  /**
   * {@inheritdoc}
   */
  public function errorElement(array $element, ConstraintViolationInterface $error, array $form, FormStateInterface $form_state) {

    if (empty($element['target_id'])) {
      return FALSE;
    }

    // Do some validation, to make sure this a real entity within
    // the list of allowed bundles.

    $settings = $this->getFieldSettings();

    $storage = \Drupal::entityTypeManager()->getStorage($settings['target_type']);

    $entity = $storage->load($element['target_id']['#value']);

    if (!empty($entity) && in_array($entity->bundle(), $settings['handler_settings']['target_bundles'])) {
      return $element['target_id'];
    }
    else {
      $form_state->setError($element['target_id'], t('This is not a valid entity reference id.'));
    }

    return FALSE;
  }

}

```
> 3 votes

# Answer
One quick solution without the need to code up anything is the following. This is only if you know the NID ahead of time either manually or programaticly. By default drupal autocomplete will try to search for it and the format will be like this once found:

**This is My Node Title (76)**

76 is the node id in this case. What you can do is just put any text before the (76) and it will work as the only thing you need is the (76). Like this:

**asdfjalkdsfjldsjflkjdslkfjldsf (76)**

Keep in mind you MUST have a SPACE between the text and the () or else it wont work!
> 2 votes

---
Tags: 8, entities
---


title: How to override default meta tags?

text:
# Question
Title: How to override default meta tags?
The meta tags module sets default meta tags that are rendering. However, I have a page with a panel and I am trying to override the default meta tags. I went into the panel and replaced the default meta tag tokens with custom text, but nothing changes. Any thoughts on why this might be happening? I'm using Drupal 7, and I'm hoping that we can do this through the admin UI.

# Answer
> 2 votes
In Drupal 8, there is a \[module-name\].module file inside your module. You can use "Hook attachments alter".

**Code to alter your meta tags** -

// For adding description in meta tag .

`function hook_page_attachments_alter(array &$attachments) {
 $attachments['#attached']['html_head'][] = array(
 array(
 '#tag' => 'meta',
 '#attributes' => array(
 'name' => 'description',
 'content' => 'Any thing in meta description',
 ),
 ),
 'description',
 );`

// For adding title in meta tag.

`$attachments['#attached']['html_head'][] = array(
 array(
 '#tag' => 'meta',
 '#attributes' => array(
 'name' => 'title',
 'content' => 'Any thing in meta title you want',
 ),
 ),
 'title',
 );`

// For adding noindex in meta tag-robots .

`$attachments['#attached']['html_head'][] = array(
 array(
 '#tag' => 'meta',
 '#attributes' => array(
 'rel' => 'robots',
 'href' => 'noindex',
 ),
 ),
 'noindex',
 );`

You can add more meta tags for different pages and can validate them too.

# Answer
> 1 votes
I have not worked much on drupal 7 but i found something called hook\_html\_head\_alter in 7.

Code for it as -

`function hook_html_head_alter(&$head_elements) {
 foreach ($head_elements as $key => $element) {
 if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'canonical') {
 // I want a custom canonical URL.
 $head_elements[$key]['#attributes']['href'] = mymodule_canonical_url();
 }
 }
}`

**Note** \-

$head\_elements: An array of renderable elements. Generally the values of the #attributes array will be the most likely target for changes.

---
Tags: meta-tags
---


title: Adding content to a specific view

text:
# Question
Title: Adding content to a specific view
I have views in a dropdown which hold my content lists, the issue is I cannot add specific content to a specific view.

I have 2 views; Current affairs and Education, I want to add content to a specific view; lets say to the Discussions view but when I add content it is added to both my views here are snips

I decide to add "PK Chishala Bana Mulenga" and "Child Labour, How can we alleviate it?" but I find them in both the Current Affairs view and Education view anyone who knows how I can solve this issue?

# Answer
A View is basically a query builder. You need to provide it with a filter that includes the content you want to show, and excludes the content you don't want to show.

There are many different different ways to solve it, here are a few of the common ones:

* Use different content types for the different types of content, and filter by "Content type" in the Views
* Add a Vocabulary, "Post Type" or something, with "Current Affairs" & "Education" as terms; attach a term reference field for that vocab to the content type, filter on that instead in the Views
* Add a boolean/text/numeric/whatever field to the content type, set that to a value on a node-by-node basis, use that to filter the Views.
> 2 votes

# Answer
There are a number of options open to you, here are 2:

1. Put taxonomy terms on your content and filter the view for specific taxonomy terms. This is the more automatic version
2. Use an entityqueue for each view, which requires much more manual input, but gives you the ability to explicitly choose the order in which articles appear.
> 1 votes

# Answer
Create a vocabulary under admin/structure/taxonomy & add terms like current affairs and education.Now create a field in your content type with term reference and choose your vocabulary now when add content choose any of the term from the field like education or current affairs.

Now create views and in filter criteria choose has taxonomy term & choose your vocabulary & select either of the term education or current affairs.

Now create another page view for the same view with different path and select the remaining term. That's how the content will not get repeated in both views
> 1 votes

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


# Question
Title: How to Display Custom Token in Rules UI Data Selector?
We use Rules and its submodule, Rules UI to manage our Rules. We have recently created some custom tokens, which are under the 'node' type. I have tested to make sure that these tokens 1) get the proper value and 2) are present among the Drupal tokens (by viewing them at /admin/help/tokens).

We would now like to use these tokens, both present under 'node'. However, they **refuse** to show up in the Rules UI. I have tried to add a condition to the Rule that 'Entity has field' of the custom token(s), but they do not appear there.

How can I make a custom token appear in Rules (UI), when it already exists in Drupal's token system?

**Update:**

The Token is an email address. It appears the token *will* appear in the field where I can select an email to be sent. However I would really like it to be available in the 'Entity has field' and/or the 'Data is empty' selectors, so I can choose whether or not to send the email based on whether the token has an email address associated with it.

Any ideas for getting it to appear in either of these locations ('Entity has field' or 'Data is empty')?

# Answer
Here are 2 options you may want to try:

1. Rework your Rule so that part of the logic of it you move to another (new) Rules Component (which uses "node" as a parameter) and then in your rules component check in its conditions if those tokens become available.
2. Use the Conditional Rules module so that within your Rules Action you can add a "condition" where these tokens may show up.

As per your "*It appears the token will appear in the field where I can select an email to be sent*", either of both options should work, if you use those options AFTER the Rules Action where you can already use the token for sending an eMail.
> 1 votes

---
Tags: 7, rules, tokens
---


title: Bootstrap Views Accordion Problem

text:
# Question
Title: Bootstrap Views Accordion Problem
I am trying to create a website. For this website, Ι am using the bootstrap business theme (Bootstrap Business Demo) of the good people of More than just Themes. I have also downloaded and enabled the Views module and the Views Bootstrap module.

I have created multiple views, all of which have as content types articles: one of them is the view *studies*, another one is named *announcement* and another one is called *events*. Along with these views, I have created their assorted blocks.

The blocks are customized as follows:

> **Format** : Bootstrap accordion using fields
>
> **Fields**: Content: Body , Content: Title

**The problem:**

I have set the blocks (three blocks each representing a different view) to appear in the themes' second sidebar. When I press the elements of any block different from the top one, the top blocks' collapse effect of the corresponding item is activated instead. That is, if I press the second accordion item of the third block, the second accordion item of the first block will be expanded(if it doesn't exist, then the second item of the second block will be expanded etc.).

**The proposed solution:**

I think I know *why* this is happening. I am currently working on the *how*. I used the inspect element feature of my chromium browser and came up with this:

Studies block, first element:

```
<a class="accordion-toggle" data-toggle="collapse"
   data-parent="#views-bootstrap-accordion-1" href="#collapse0">
     Study 1
</a>

```

Announcements block, first element:

```
<a class="accordion-toggle" data-toggle="collapse"
   data-parent="#views-bootstrap-accordion-2" href="#collapse0">
     Announcement 1
</a>

```

Events block, first element:

```
<a class="accordion-toggle" data-toggle="collapse"
   data-parent="#views-bootstrap-accordion-3" href="#collapse0">
     Event 1
</a>

```

Although their data parent is different (views-bootstrap-accordion-\[1-3\]), all of these items reference the same collapse0 id(?) element. I am currently trying to figure out the css(?) file these point to and see if I can fix this, either by tweaking the module (views bootstrap) or the theme(bootstrap business).

Any help would be mush appreciated.

# Answer
> 1 votes
Came across your post considering I had the exact same problem. I had several different attached views to my page that were grouped by different taxonomy terms.

The way I fixed it is a little janky, but it works... basically edit the Views Bootstrap module in **sites/all/modules/views\_bootstrap/templates/accordion/views-bootstrap-accordion-plugin-style.tpl.php** and store a random integer in PHP as a variable with rand(); then append that variable to the $key on your accordion-toggle tag as well as the "collapse" div.

It should work after that.

# Answer
> 1 votes
Just wanted to add to **Milo25's** Answer a slightly cleaner approach would be to add the id of the **views-bootstrap-accordion** instead of a random number Element:

```
<a class="accordion-toggle"
         data-toggle="collapse"
         data-parent="#views-bootstrap-accordion-<?php print $id ?>"
         href="#collapse<?php print $key . $id ?>">

<div id="collapse<?php print $key . $id ?>" class="panel-collapse collapse">

```

---
Tags: views, navigation, theming
---


# Question
Title: How to print taxonomy term field in node.html.twig?
In Drupal 7 we use following snippet to print taxonomy term field in node.tpl.php

```
$term = taxonomy_term_load($node->field_example['und'][0]['tid']);

$result = field_view_field('taxonomy_term',$term,'field_desired_field');

echo render($result);

```

In Drupal 8 how we can print taxonomy term field in node.html.twig?

# Answer
To get the field value from a field in a taxonomy term that is referenced in the node:

```
{{ node.field_example.entity.field_desired_field.value }}

```

If you want to render a formatted output, use either the ui to configure a custom view mode or use the module Twig Tweak:

```
{% set tid = node.field_example.target_id %}
{% if tid %}
  {{ drupal_field('field_desired_field', 'taxonomy_term', tid) }}
{% endif %}

```
> 13 votes

# Answer
The nearest equivalent is described here Rendering arbitrary field values without a parent entity in Drupal 8 and a core issue to make it more reasonable is #2274169 EntityViewBuilder::viewField() / viewFieldItem() don't work for arbitrary added field values
> 0 votes

# Answer
In drupal 8, you can do it as -

`{% if node.hasField('field_TAXONOMY-TERM') == true %}
 {{ node.field_TAXONOMY-TERM.value }}
 {% endif %}`
> -2 votes

---
Tags: theming, 8
---


# Question
Title: Custom form values in hook_form_alter() not available in custom validate function
I'm modyfing a node form to add a few extra fields. On submit, I need to program some extra logic to these values then save them to the node object.

```
function module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'my_node_form') {
    $form['custom_form'] = array(
     '#type' => 'textfield',
     '#title' => t('Custom field'),
     '#default_value' => 'enter custom text here',
    );

    $form['#validate'][] = 'custom_form_process_values';
  }
 }

 function custom_form_process_values(&$form, &$form_state, $form_id) {
    echo '<pre>' . print_r($form_id,1) . '</pre>';
    echo '<pre>' . print_r($form_state,1) . '</pre>';
    exit();
  }

```

When I go to node/22/edit and change "enter custom text here" to something else, and I submit the form, I only ever see "enter custom text here" and not the new text I entered. It seems that it does not carry the text through to the validate function. Also tried it in a submit function but the same problem occurs.

Why does this happen?

# Answer
> 0 votes
This pair of functions should do the trick:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (stripos($form_id, 'node_form') !== FALSE) {
    $form['custom_form'] = array(
     '#type' => 'textfield',
     '#title' => t('Custom field'),
     '#default_value' => 'enter custom text here',
    );
    $form['#validate'][] = 'mymodule_custom_form_process_values';
  }
 }

function mymodule_custom_form_process_values($form, &$form_state) {
  // Check to see if the default text has been altered by the user.
  if ($form_state['values']['custom_form'] != $form['custom_form']['#default_value']) {
    // Do something here...
  }
}

```

Tested on Drupal 7.53.

---
Tags: 7, forms
---


title: Make a custom date formatter for view

text:
# Question
Title: Make a custom date formatter for view
Looking for a way to add my own date formatter in view. Actualy have the "default" and "Time ago" one, but I want to had another one to display date has FB do in the notification feed :

For today notification : Today, 09:33

For Yesterday notification : Yesterday, 10:36

For this week notification (except today and yesterday) : Mon. 06:34

All other notification : 09/12/17, 15:59

Is this possible ? Or maybe in an other way than add something in view module ?

Working on Drupal 8.2.0 version.

# Answer
In Drupal 8, views field output uses the field formatters that entities use (Drupal 7 uses its own plugins for this).

The "Today", "Yesterday", "Monday", other functionality cannot be handled by the standard field formatters.

Drupal 8 makes it easy, though, to make new formatters. Make a custom module, and extend `DateTimeDefaultFormatter`. Inside this class, you would override the `formatDate()` method (and possible the `defaultSettings()` one, depending on how fancy you want to be. The method would look something like this

```
protected function formatDate() {
  $timezone = $this->getSetting('timezone_override') ?: $date->getTimezone()->getName();

  if ($date is today) {
    $output = $this->t('Today, @formatted', [
      '@formatted' => $this->dateFormatter->format($date->getTimestamp(), 'custom', 'H:i', $timezone != '' ? $timezone : NULL);
    ]),
  }
  else if ($date is yesterday) {
    $output = $this->t('Yesterday, @formatted', [
      '@formatted' => $this->dateFormatter->format($date->getTimestamp(), 'custom', 'H:i', $timezone != '' ? $timezone : NULL);
    ]),
  }
  else if ($date is this week) {
    $output = $this->dateFormatter->format($date->getTimestamp(), 'custom', 'D. H:i', $timezone != '' ? $timezone : NULL);
  }
  else {
    $output = $this->dateFormatter->format($date->getTimestamp(), 'custom', 'm/d/y H:i', $timezone != '' ? $timezone : NULL);
  }

  return $output;
}

```

You need to work out the logic to choose the proper format. Set the annotation on the formatter properly, and you can use this formatter in the view (or anywhere else).

This should give you a start.
> 5 votes

# Answer
You can make such functionality using a custom template. Please look my example:

**field--node-post-date--article.html.twig**

```
    {% for item in items %}
      <div class="date">
        <span class="day">{{ item.content[0]['#markup']|date('j') }}</span>
        <span class="year">{{ item.content[0]['#markup']|date('M.Y') }}</span>
      </div>
    {% endfor %}

```

As you can see, you can use some additional login in Twig.
> 1 votes

---
Tags: views, 8, datetime
---


# Question
Title: Why are there several branches at the official documentation (e.g. 8.0.x, 8.1.x)?
Why are there several branches (e.g. 8.0.x, 8.1.x) at the official documentation?

Is it planned that sub versions of Drupal 8 will be developed independently?

If yes, then what's the point?
If no, then why are these branches mentioned in the documentation?

# Answer
Drupal 8 made the switch to semantic versioning, and a shorter release cycle between minor versions.

Per release policy, there can be differences between minor versions. In general, new minor versions are backwards compatible (or provide a BC layer), but can also introduce new features. In addition, as minor versions get released, some functionality remains but becomes deprecated.

This is why there is different documentation for different minor versions; the document actually is slightly different.

To keep on top of changes in Drupal 8, monitor the list of Change Records or the Twitter account that announces each new one.
> 7 votes

# Answer
This is a change in policy from previous Drupal releases. New code and API can be and have been released in minor releases. The API pages are necessary so that it is possible to lookup specific API in minor releases since a minor release may still be valid.

https://www.drupal.org/core/d8-allowed-changes#minor

> Drupal 8 introduces a six-month minor release cycle. Minor releases provide new improvements and functionality without breaking backward compatibility (BC) for public APIs. The following types of changes are allowed for minor releases in addition to those allowed for patch releases. For example, following the release of 8.1.0, these changes will not be committed to 8.1.x, but instead can be committed to 8.2.x for inclusion in 8.2.0.

https://www.drupal.org/core/d8-bc-policy

> Minor releases (8.x.0) may include non-API-breaking refactoring, new features, or enhancements of existing features. In such cases the core team will work to ensure that these enhancements do not alter the existing public-facing API of core systems.
>
> Necessary security hardening takes priority over API stability.
>
> We will make every effort to address security issues without affecting the public API. However, in some cases it will not be possible to address a security vulnerability without an API change. In such cases we will work to minimize the scope of the API change and document it thoroughly.
> 5 votes

# Answer
It's because the API can introduce changes in each of those versions and introduce new core modules or core experimental modules (which are publicly tested and can later become part of core or move to contrib). Those are just a few reasons.
> 2 votes

---
Tags: 8
---


title: Creating Routes to deal with a form

text:
# Question
Title: Creating Routes to deal with a form
So I have created a block in which I've added a form, build with the form API. It contains a textfield and a submit button. My next step is to create a route that calls a method in a controller in my Module.

I am wondering how to do this. The form itself part of the main menu, so visible on any page. I'm not sure how to define this route. I've read there are `form routes`, but I don't think that's what I am looking for.

The Drupal Form API documentation says something like this:

```
module_search.form:
  path: '/'
  defaults:
    _title: 'Search form'
    _form: 'Drupal\module_search\Form\SearchForm'
  requirements:
    _permission: 'access content'

```

But I have no clue how to handle the request itself to do something with the data this form provides.

# Answer
> 1 votes
If you want a form in the main menu of every page, you don't need a route for it. You can just create a block, either for just the search form or for the main menu, and load the form in as a variable into that block.

```
namespace Drupal\module_search\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Header Search Block Form' block.
 *
 * @Block(
 *  id = "header_search_block",
 *  admin_label = @Translation("Header Search Form Block"),
 * )
 */
class HeaderSearchFormBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $form = \Drupal::formBuilder()->getForm('Drupal\module_search\Form\SearchForm');
    return [
      $form,
      '#cache' => [
        'contexts' => ['url.path', 'url.query_args']
      ],
    ];
  }
}

```

What you're returning is a render array, so you might want caching settings on there, otherwise, you can just return the form itself. If you want to prefill the search term on every page, you'd want a cache context that includes page arguments, like above. If you want the fields empty, such as if your form only contains a textfield for searching, then you don't need a separate cached version on every page and you can just return the form in your build() function:

```
  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\module_search\Form\SearchForm');
  }

```

Another option, you can preprocess your main menu block to add the form as a variable as well.

```
function mymodule_preprocess_block__system_menu_block__header_menu(&$variables) {
  $variables['search_form'] = \Drupal::formBuilder()->getForm('Drupal\module_search\Form\SearchForm');
}

```

then in your block template (such as block--system-menu-block--header-menu.html.twig)

add

```
{{ search_form }}

```

As far as redirecting to search, my preferred method is with javascript, as you don't need to hit the backend. You can just redirect to your search page from the javascript.

Just attach the javascript library to your form

```
$form['#attached']['library'][] = 'mymodule/mymodule.header_search';

```

(etc. there are many tutorials on this)

and then in the javascript do something like:

```
 $('#' + formID).submit(function(e) {
   e.preventDefault();
   var filters = self.gatherFilters();
   var url = searchURL + '?' + $.param(filters);
   window.location.href = url;
 });

```

If for some reason, you need backend processing, your form can have a submitForm method that then sets the redirect on the $form\_state object:

```
$query = ['keyword' => $search_term];
$form_state->setRedirect($route_name, [], ['query' => $query]);

```

with $query being an array of query arguments.

For your search results page, I would recommend you create a different search form. As a small textfield in the header is different than filters on a form.

Without custom coding, you could use a Drupal view page, and set a contextual filter set to keyword, or you could create a controller in your custom module that returns a different search form with filters as well as the results from Elastisearch.

---
Tags: forms, routes
---


# Question
Title: How to get the content of a node with Devel Path?
I am quite new to Drupal an would like to get the Data of a Node. With the Devel module I read out the Path to the information I like get with PHP.

```
$var->location['postal_code']

```

How can I access this path? I would like to get this info an pass to Javascript. So I think I have to access this path with PHP and then use `drupal_add_js` to pass it to JS. But I don\`t even know where to put the PHP code.

Any suggestion?

# Answer
> 0 votes
If your main goal is to expose a piece of data to JavaScript, you can use `drupal_add_js()` to add a "setting". Here is the example from api.drupal.org:

```
drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

```

(https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_js/7.x)

That then becomes available in the frontend in the Javascript variable: `Drupal.settings.myModule.key`.

Now, the question is WHERE do you put that call to `drupal_add_js`? That depends on exactly what data you want to expose, and when you want to expose it, but in general you would create a custom module and implement a Drupal hook that runs `drupal_add_js` at a specific point in the Drupal pageload life cycle.

If, as it sounds from your question, you want to add node information to a node's "view" page (ie: on the /node/1 path), one option is to implement `hook_node_view()` in a module called `mymodule` like so:

```
/**
 * Implements hook_node_view().
 */
function mymodule_node_view($node, $view_mode, $langcode) {

  // If the node contains the field we want, add it to a JS setting.
  if (!empty($node->location['postal_code'])) {
    drupal_add_js(array('mymodule' => array('postal_code' => $node->location['postal_code'])), 'setting');
  }
}

```

Here is the documentation for that hook: https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_view/7.x

That's just one way to do it. There are lots of other hooks where this could be done, again: depending on when and where you want it to.

---
Tags: 7, nodes
---


title: Form Ajax submission: erratic behavior

text:
# Question
Title: Form Ajax submission: erratic behavior
I'm experiencing a weird behavior with an ajax form submit that I cannot find an answer to.

This is my first attempt at making an ajax form so bear with me if I'm making a rookie mistake somewhere.

```
namespace Drupal\MYMODULE\Forms;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

class InputForm extends FormBase {

  public function getFormID() {
    return 'authForm';
  }
  /**
   * Implements \Drupal\Core\Form\FormInterface::buildForm().
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#prefix'] = '<div id="testdiv"></div>';

    $form['key'] = array(
        '#type' => 'textfield',
        '#title' => t('Key'),
        '#size' => 10,
        '#name' => 'key',
        '#required' => TRUE,
        '#attributes' => ['id'=>'key','name'=>'key','class'=>array('input-sm')]
    );

    $form['code'] = array(
        '#type' => 'textfield',
        '#title' => t('code'),
        '#name' => 'code',
        '#required' => TRUE,
        '#attributes' => ['id'=>'code','name'=>'code','class'=>array('input-sm')]
    );

    $form['form_submit'] = array(
        '#type' => 'submit',
        '#value' => t('submit'),
        '#name' => 'submit',
        '#ajax' => [
            'callback' => '::test',
            'prevent' => 'submit',
            'progress' => []
        ]
    );
    return $form;
  }
  public function validateForm(array &$form, FormStateInterface $form_state) {

      if (strlen($form_state->getValue('key')) < 10) {
        $form_state->setErrorByName('key', $this->t('Key is too short'));
      }

  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Handle submitted form data.
  }

  public function test(array &$form, FormStateInterface $form_state) {
    if($form_state->hasAnyErrors()) {
        $form_state->setRebuild(TRUE);

        return($form);
    }

    $response = new AjaxResponse();
    $response->addCommand(
        new HtmlCommand(
            '#testdiv',
            '<p>HELLO</p>'
        )
    );
    return $response;

  }

}

```

So the erratic behavior is in the validation of the form. What is happening is when I click the submit button (with no values in the input fields) the ajax fires and through var dumping I know the `$form_state->hasAnyErrors()` returns true but the form rebuild that is returned is not modifying the form highlighting the fields with errors as expected.

So after spending a couple hours trying to sort out this issue I got frustrated and mashed the submit button over and over again in a rage and low and behold it did what it's supposed to do after about eight clicks.

So then I tried to narrow down how many times it would take hitting the button before it would work correctly and it would always happen at random clicks. Sometimes after 2, sometimes after 3... sometimes after 10.

I'm stumped as to why it doesn't happen each and every single time the button is clicked rebuilding the form properly with errors.

Of Note:

* Have tried removing the prevent key
* Have tried with Bartik theme with same results
* Have tried setting an ID on the submit button but then ajax doesn't fire
* Have confirmed that the form does have errors
* Have input values into the fields (key value shorter than 10) and the same behavior happens in the validateForm() function

If anyone could point me to what I could be doing wrong I'd very much appreciate it. Thanks in advance!

Edit for visual example: Gif showing behavior

# Answer
HTML 5 Validation

**THIS** is the validation that is showing up in the gif. For whatever reason, when doing the ajax call it (HTML5 Validation) would sometimes fire and sometimes not.

My personal solution: Disable HTML5 clientside validation and handle that myself.

```
$form['#attributes']['novalidate'] = 'novalidate';

```

Hopefully this helps some future reader.
> 0 votes

# Answer
What you can see in the Gif looks more like the validation of the form in javascript not in ajax.

Normally you decide in the submit button by including the option `'wrapper' => 'ajax-wrapper-id'`, if you want to use the wrapper method and return in the ajax callback the new version of the form or parts of it, or use the response method and build an ajax response in the callback. Doubt that you can mix it like this.

If you use the wrapper method you don't need to rebuild the form, because it is already rebuilt, when it reaches the ajax callback.
> 0 votes

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


# Question
Title: Create custom front page without adding content
I am trying to create a custom welcome front page, it should contain two parts (left block and right block).

Each block has a background image (editor can upload), a logo (1 logo for each block), a description text...

Creating a new content type, is not a good idea in my opinion, because I don't like editors to add as much as they want nodes of that content type, so it should be only **one** content the editor can edit it each time he want to edit the background or logo...

I am thinking of creating a new setting form for this specific front page content containing those fields in a custom module. In this case, can I use picture module to make the background load a responsive image and not the default one uploaded by the editor ?

Thanks in advance.

# Answer
> 0 votes
In your case, yes you can create settings form, where admin will load background images, logo and enter description. But why you want use picture module? You can define new variables in hook preprocess\_page for front page. Where in variable you put url to background image, url to logo, descriptions. After in front page template file, set url background to our block, logo and place descriptions. Finally add styles to block class or id in css file for align background at the block. For this you can use something like this:

```
.your-class {
    background: transparent url("path/to/background.jpg") no-repeat scroll 50% 50% / cover;
    width: 100%;
}

```

background url you add in template. I write path to url in code for quick example, you can place this code in some div, add correct url and see result.

# Answer
> 0 votes
I understand that:

* Your key reason for not considering a content type is that you wish only one of this content type to be added to the site.
* It is the intention that all of the content for the homepage is to be editable.

I would suggest that using a content type may still be a suitable approach: by virtue of not granting any role the "create new \[content type x\] permission", you ensure that the only type of user who could add new homepages would be the "administrator role" which you have set - a role which you won't have given to content editors.

For the blocks with background images, you might wish to consider use of the field\_collection module to create sets of grouped fields; you can template field collections, allowing you to create an element with a background image and other field outputs contained within that element, for example. Ref http://www.drupalcontrib.org/api/drupal/contributions!field\_collection!field-collection-item.tpl.php/7 for templating a field collection item. (If you prefer to use the paragraphs module, an equivalent approach would apply.)

The key thing here is that when you create your templates, you can output the file names of the editor-uploaded background images (e.g. a small inline CSS block), and ensure that you make use of the background-size property (you want "cover"). Set the position of the background images depending on how you'd like the visual effect of the responsive behaviour to work.

* For example, 50% 50% will keep the centre of the image in the centre of the available area, while 0 0 would pin the top left corner to the top left of the area.

(The Picture module is aimed at embedding responsive content images, rather than for background images, so would not help you to achieve what I understand you're trying to do.)

---
Tags: 7, theming, media
---


# Question
Title: Print custom HTML between Exposed Filter Area and Results in Views
I set up a view in drupal 7 that displays all my content. I exposed filter criteria's Title and Taxonomy, so now there's a title and taxonomy search field that appears above the result set. How do I print custom text like "Search Results:" between the filters and the results?

# Answer
> 4 votes
This can easily be achieved using themeing.

* In the edit view for your view click on advanced
* At the bottom of the section is "theme information"
* Look for the line "Display output" and from left to right the themeing becomes more specific
* Decide how specific you want the themeing to be (hint if unsure go to the right)
* Copy the theme file name (which should be something like `views-view--example--page.tpl.php`) and create a new file in your theme folder with that name
* Click on the display options link and copy the contents of the file from the `<?php` through to the bottom of the fixed width text and paste that into the new file
* Add your text after the code block that looks like this:

> `<?php if ($exposed): ?>`
>
> `<div class="view-filters">`
>
> `<?php print $exposed; ?>`
>
> `</div>`
>
> `<?php endif; ?>`

* Save the file
* Click the "Back to theming information" link
* Click the rescan template files link
* Save your view
* Visit the page your view is on

# Answer
> 0 votes
Quick edit to the previously provided response:

Copy the views-view.tpl.php provided by the Views module into your templates folder of your theme, and rename it views-view--example--page.tpl.php

After:

```
   <?php if ($exposed): ?>
 <div class="view-filters">
 <?php print $exposed; ?>
 </div>
<?php endif; ?>

```

add:

```
  <?php if (!$empty): ?>
    <?php print t('Your search results are below.'); ?>
  <?php endif; ?>

```

Save the file. Make sure to rescan you template files within the view.

This ensures that your custom text is only displayed when results are found. Without the check to see if the view is empty, your custom text will display even if no results are found, which is not good UX.

---
Tags: 7, views
---


# Question
Title: How do I get a URL variable in a template?
I am trying to include a certain .html file if the URL has ?work=1.

So far I have this, which I got from Check URL for string in a Twig file.

```
 {% if 'work' in url %}
    {{ include('work/index.html') }}
 {% endif %}

```

They say I need a function in my .theme file to actually get the URL variable.
Is that right? Is there any way to get it with just Twig?

# Answer
> 0 votes
Ok nevermind. On the other stack I mentioned the function was

```
function riptide7_preprocess_page_title(&$variables) {
  $variables['url'] = $_SERVER['REQUEST_URI'];
  $variables['#cache']['contexts'][] = 'url.path';
    echo "What?!";
}

```

and I just had to change preprocess\_page\_title to preprocess\_page

---
Tags: theming, 8
---


# Question
Title: What's the syntax to apply hook_schema() in .install file?
I want to build a installable module. Let's assume the module name will be `bluedog_calculator`. I have already created other required files like `bluedog_calculator.info` and `bluedog_calculator.module`. Now I am trying to use `hook_schema()` and whenever i am trying to use `drush dre bluedog_calculator -y`, Konsole gives me an error as follows:

> `SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; [error]
>  check the manual that corresponds to your MariaDB server version for the right syntax to use near 'unsigned NOT NULL COMMENT`.

I am not sure what is the right syntax for applying this hook.

My code is

```
function bluedog_calculator_schema(){
    $schema['bluedog_calculator_machine'] = array(
    'description' => 'TODO: please describe this table!',
    'fields' => array(
      'id' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'serial',
        'not null' => TRUE,
        ),
      'name' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'varchar',
        'length' => '100',
        'not null' => TRUE,
        ),
      'speed' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'float',
        'not null' => TRUE,
        ),
      'cost' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'float',
        'not null' => TRUE,
        ),
      'image' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE,
        ),
      'web_link' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'text',
        'unsigned' => TRUE,
        'not null' => TRUE,
        ),
      'is_default' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 0,
        ),
      ),
    'primary key' => array('id'),
);

return $schema;
}

```

# Answer
The only place you use 'unsigned' is in this block:

```
'web_link' => array(
  'description' => 'TODO: please describe this field!',
  'type' => 'text',
  'unsigned' => TRUE,
  'not null' => TRUE,
),

```

'unsigned' does not apply to text columns. Try removing that line from the web\_link column definition. https://api.drupal.org/api/drupal/includes!database!schema.inc/group/schemaapi/7.x has useful reference on this.

(The docs state that unsigned is ignored for other types, but it seems the error is in that chunk, so I'd certainly try removing it in case your database engine is not ignoring it.)
> 2 votes

# Answer
I didn't try. But I believe that `not null` and `default` should not appear at the same time in a field.
> 1 votes

---
Tags: 7, database, hooks
---


# Question
Title: Kernel Test: Programmatically create a vocabulary and add a field to it
I want to add a taxonomy term and add field to it. My current code looks this way:

```
<?php

namespace Drupal\Tests\permissions_by_term\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\taxonomy\Entity\Vocabulary;

/**
 * Tests the ERR composite relationship upgrade path.
 *
 * @group permissions_by_term
 */
class SelectTermTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = array('taxonomy', 'text');

  /**
   * List of taxonomy term names by language.
   *
   * @var array
   */
  public $termNames = [];

  /**
   * The vocabulary used for creating terms.
   *
   * @var \Drupal\taxonomy\VocabularyInterface
   */
  protected $vocabulary;

  function setUp() {
    parent::setUp();

    $this->installEntitySchema('taxonomy_term');

    // Create a vocabulary.
    $this->vocabulary = Vocabulary::create([
      'name' => 'Views testing tags',
      'vid' => 'views_testing_tags',
    ]);
    $this->vocabulary->save();

    // Add a translatable field to the vocabulary.
    $field = FieldStorageConfig::create(array(
      'field_name' => 'field_foo',
      'entity_type' => 'taxonomy_term',
      'type' => 'text',
    ));
    $field->save();
    FieldConfig::create([
      'field_name' => 'field_foo',
      'entity_type' => 'taxonomy_term',
      'label' => 'Foo',
      'bundle' => 'views_testing_tags',
    ])->save();
  }

  public function testSomething() {
  }

}

```

If I run the test by the following command:

> vendor/bin/phpunit -c modules/permissions\_by\_term modules/permissions\_by\_term/tests/src/Kernel/SelectTermTest.php

I'm getting the following output:

> PHPUnit 4.8.11 by Sebastian Bergmann and contributors.
>
> E
>
> Time: 882 ms, Memory: 6.00Mb
>
> There was 1 error:
>
> 1) Drupal\Tests\permissions\_by\_term\Kernel\SelectTermTest::testSomething Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException: The Drupal\field\Entity\FieldStorageConfig class does not correspond to an entity type.
>
> /home/peter/Websites/pbt-d8/core/lib/Drupal/Core/Entity/EntityTypeRepository.php:98 /home/peter/Websites/pbt-d8/core/lib/Drupal/Core/Entity/EntityManager.php:375 /home/peter/Websites/pbt-d8/core/lib/Drupal/Core/Entity/Entity.php:509 /home/peter/Websites/pbt-d8/modules/permissions\_by\_term/tests/src/Kernel/SelectTermTest.php:49
>
> FAILURES! Tests: 1, Assertions: 1, Errors: 1.

I do not understand this part:

> Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException: The Drupal\field\Entity\FieldStorageConfig class does not correspond to an entity type.

As an example I have used the Drupal core taxonomy test from

> core/modules/taxonomy/src/Tests/Views/TaxonomyFieldFilterTest.php

This test does what I want to do, but is not a Kernel test. It is a Simpletest, since it inherits from WebTestBase. If I use WebTestBase, it works. But the test is much slower then. Do you know what's missing in my code for running it as a Kernel Test?

# Answer
> 7 votes
You need to enable the field module so its entity types are present. Kernel test base *does not* enable required modules so the FieldConfig and FieldStorageConfig entity types don't exist until you enable the field module. Put it in the $modules property with 'taxonomy' and 'text'.

# Answer
> 5 votes
You should try FieldKernelTestBase instead of just KernelTestBase. There is a helper method called createFieldWithStorage who will do the job.

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


# Question
Title: Change print icon programmically through template.php
I'm using the Print module, version 7.2, and trying to change the icon through the template.php.

After researching, I have found the main functionality in the FAQ of the module, which provides this:

> The example below is for the 6.x-1.x and 7.x-1.x branches. In 7.x-2.x the theme function is theme\_print\_ui\_format\_link.
>
> You will have to define a theme\_print\_format\_link function which will replace the module's function with the same name and where you can indicate your custom-defined icon, and set the html element to true so that your image tag is interpreted as HTML. See the following for an example:

```
function theme_print_format_link() {
  $print_html_link_class = variable_get('print_html_link_class', 'print-page');
  $print_html_new_window = variable_get('print_html_new_window', 0);
  $print_html_show_link = variable_get('print_html_show_link', 1);
  $print_html_link_text = filter_xss(variable_get('print_html_link_text', t('Printer-friendly version')));

  $img = local_path_to_your_img_file;
  $title = t('Display a printer-friendly version of this page.');
  $class = strip_tags($print_html_link_class);
  $new_window = $print_html_new_window;
  $format = _print_format_link_aux($print_html_show_link, $print_html_link_text, $img);

  return array('text' => $format['text'],
               'html' => $format['html'],
               'attributes' => print_fill_attributes($title, $class, $new_window),
              );
}

```
1. If I don't change the code at all, it never gets called.
2. If I change the first line to `subtheme_print_ui_format_link() {`, it gets called, but then I get the error

`Fatal error: Call to undefined function _print_format_link_aux() in ...../public_html/sites/all/themes/subtheme/template.php on line ...`

I have tried:

* `subtheme_print_format_link_aux()`
* `_subtheme_print_format_link()`
* `_print_ui_format_link_aux()`
* `_print_ui_format_link()`

and a bunch of others instead of `_print_format_link_aux()`, but error just replaces the first function with the one I tried.

**Note:** I have have changed `local_path_to_your_img_file` to `'images/print_icon.png'`

# Answer
I found a site that helped me a lot. I just changed the `$icon` value.

This is the code I am using in the template file.

```
/**
 * Format the Printer-friendly link
 *
 * @return array
 *   An associative array containing:
 *   - text: The content of the link
 *   - html: TRUE if the text contains HTML tags, FALSE if it's plain text
 *   - attributes: several attributes of the link tag (title, class, target,
 *     onclick, rel)
 *
 * @see _print_ui_fill_attributes()
 * @ingroup themeable
 * @ingroup print_themeable
 */
function subtheme_print_ui_format_link($vars) {
  $format = $vars['format'];
  $path = '/images/print_icon.png'; //path to file, relative to theme YOUR_THEME

  foreach (module_implements('print_link') as $module) {
    $function = $module . '_print_link';
    if (function_exists($function)) {
      $link = call_user_func_array($function, array());
      if ($link['format'] == $format) {
        $link_class = variable_get('print_' . $link['format'] . '_link_class', $link['class']);
        $new_window = FALSE;
        $func = $module . '_print_new_window_alter';
        if (function_exists($func)) {
          $func($new_window, $link['format']);
        }
        $show_link = variable_get('print_' . $link['format'] . '_show_link', PRINT_UI_SHOW_LINK_DEFAULT);
        $link_text = filter_xss(variable_get('print_' . $link['format'] . '_link_text', $link['text']));
        if ($show_link >= 2) {
          // Work out which icon we want to show based on the link's format.
          switch ($link['format']) {
            case 'html':
              $icon_name = 'print';
              break;

            case 'mail':
              $icon_name = 'envelope-o';
              break;

            case 'pdf':
              $icon_name = 'file-pdf-o';
              break;
          }

          // Build the icon.
          $path = '/' . drupal_get_path('theme', 'YOUR_THEME') . $path; //the path is relative to the theme 'YOUR_THEME'
          $icon = "<img src='" . $path . "' class='print-icon " . $link_class . "' alt='Print this page' />";

          // Show the icon with or without text, depending on config settings.
          switch ($show_link) {
            case 2:
              $text = $icon;
              break;
            case 3:
              $text = $icon . ' ' . $link_text;
              break;
          }
          $html = TRUE;
        }
        else {
          $text = $link_text;
          $html = FALSE;
        }

        return array(
          'text' => $text,
          'html' => $html,
          'attributes' => _print_ui_fill_attributes($link['description'], strip_tags($link_class), $new_window),
        );
      }
    }
  }
}

```
> 2 votes

---
Tags: 7
---


title: How can I change the file private URL

text:
# Question
Title: How can I change the file private URL
So I've uploaded a private file. It can be accessed like following:

`http://drupal8.dev/system/files/2016-12/README.txt`

How can I change how that file is accessed?

`http://drupal8.dev/files/README.txt`, etc.

# Answer
> 0 votes
This is a route in system.routing.yml:

```
system.private_file_download:
  path: '/system/files/{filepath}'
  defaults:
    _controller: 'Drupal\system\FileDownloadController::download'
  requirements:
    # Permissive regex to allow slashes in filepath see
    # http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html
    filepath: .+
    _access: 'TRUE'

```

You can change the path in a route subscriber.

Reference: https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones

# Answer
> 0 votes
Assuming I understand the question: To the best of my knowledge, you cannot. For a file in the private file system, the file URL must be rendered on a page in order to be accessed. Redirects and rewrites won't work.

---
Tags: 8
---


title: How to logout all active users?

text:
# Question
Title: How to logout all active users?
Instead of putting my site in "maintenance mode" I would like to put it in a complete "readonly mode". There is a module for that, however, it only prevents "node add and edit". I would like to prevent all user activity including login and registration to basically have the site get served from the (varnish) cache. As as side benefit I would use this type of "read only mode" if the site gets flooded with requests.

My question: how can I logout all active users? The login and registrations I can then redirect with a hook.

# Answer
As far as I know you can empty the sessions table and all users will be logged out. There may be an issue though, depending on the modules that you have installed. For example, modules that implement `hook_user_logout()` will never get their actions fired, which could be an issue. Check to make sure none of your installed modules is implementing this hook.
> 16 votes

# Answer
You can empty the sessions table using drush

```
drush sqlq "TRUNCATE sessions"

```

or if you have set prefixes for table names:

```
drush sqlq --db-prefix "TRUNCATE {sessions}"

```
> 16 votes

# Answer
Use Force Logout Module ..

# Features

* Settings form where you can enable and disable (Force logout).
* Permission so you can exclude some user roles if you want to exclude administrator for example.
> 2 votes

# Answer
You can force to logout all the users via an update hook:

```
/**
 * Force to logout all the users.
 */
function mymodule_update_7001() {
  db_truncate('sessions')->execute();
}

```
> 1 votes

---
Tags: 7, sessions
---


title: How to use or operator in a view?

text:
# Question
Title: How to use or operator in a view?
I have a view page and I want to show two content type same time. What I want is simple: I have two content types and these content types have own type fields. Like this:

Content Type 1 - Cars (this have a type field names "BMW")

Content Type 2 - Motorcycle (this have a type field names "Ducati")

I want to show all BMW Cars and Ducati Motorcycles at the same page. How can I do that with view filters? I try that but it is not working:

In my example;

Cars = Post

Motorcycle = Feed

BMW = Type (= iframe)

Ducati = Type (or foto, video, ...)

# Answer
> 0 votes
Only two filters can do that for you -

* Content : Published(= yes)

**OR,**

* Content : type(= Feed) **And,**
* Content : field\_car(= BMW)

**OR,**

* Content : type(= Post) **And,**
* Content : field\_motorcycle(= DUCATI)

Apply pager for the view with 10 or 15 content on one page, etc.

---
Tags: 7, views
---


title: get language on form alter

text:
# Question
Title: get language on form alter
I try to get selected language for specified node (I mean in edit form) on form alter with following snippet in `MODULENAME.module`

```
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function MODULENAME_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'node_trends_edit_form') {
        kint($form);
        kint($form_state->getValue('langcode'));
        kint($form_state->getValues());
    }
}

```

BUT results for `kint($form_state->getValue('langcode')); kint($form_state->getValues());` are `NULL`.

how can I get language selected for node on `form_alter`

# Answer
According to this question , first try to get `$node = $form_state->getFormObject()->getEntity();` then get langcode with `$langcode = $node->langcode->value;`

```
<?php

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function MODULENAME_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'node_trends_edit_form') {
        $node = $form_state->getFormObject()->getEntity();
        $langcode = $node->langcode->value;
        kint($langcode);

    }
}

```

**it RETURN EDITING NODE LANGCODE** =\> en,ar,tr,fr, etc
> 4 votes

# Answer
The code to get the entity language is present in `language_form_alter()`, which you can take as an example to write your code.

```
  $form_object = $form_state->getFormObject();
  if ($form_object instanceof ContentEntityFormInterface && $form_object->getEntity()->getEntityType()->hasKey('langcode')) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_object->getEntity();
    $entity_type = $entity->getEntityType();
    $langcode_key = $entity_type->getKey('langcode');

    // Your code goes here.

  }

```

If you are sure the edit form is for a content entity (such as a node), you could remove the part verifying that `$form_object` is a content entity object. I would leave it, but that is my personal preference.
> 4 votes

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


# Question
Title: Is there a way to enable Basic Auth for only one specific type of node?
Can't really find much useful in the way of googling.

I have a special content case on my site where I have created a page template which displays a series of blocks in my `theme` code. To apply this template to this particular page, I made a custom node type for it. However, this content is (and should be) restricted only to users with a certain permission, which I accomplished via the Content Access plugin.

I want to use wkhtmltopdf to output a PDF of that page for internal use. The only way I think I can get the node instance to allow wkhtmltopdf to view it is to run wkhtmltopdf with the --custom-header flag with an Authorization header. I need this to happen once per day, and was thinking of setting up a cron task to run wkhtmltopdf nightly on a Linux system (so far I have just been testing it manually on a Windows system where the node had no permission requirements and everything seems fine).

I know that enabling basic auth for certain paths is a thing I can do using a plugin, but this content is not defined by a plugin and is just a node I created using the Drupal interface.

Is this possible, or do I have to tear it down and start over and build a new custom plugin?

# Answer
Probably there is no one here, that has tried the method you've described. I would start with a custom entity, use the basic auth or create a new authentication provider and apply this for the entity route. You can do this with drupal console within a minute.

And you don't need contrib code to configure access for the custom entity, because here you can do what you want in core. I wouldn't use an Access plugin from contrib, until there is a stable release.
> 3 votes

# Answer
## Solution 1 - override the node access controller

The node entity type, defines the node access controller. This is done through annotation (system that allow you to define things through comments.)

If you use `hook_entity_type_alter` you can change the node access controller to a subclass you make and implement any kind of logic.

## Solution 2 - use basic auth on all pages

Is there any reason why you shouldn't be able to authenticate with basic auth on all pages. Drupal has this feature OOB from the `basic_auth` module, so you simply could turn it on. I don't see that being a security info as you would need to pass credentials on all requests (instead of logging in once and using a cookie).

You need to enable for global use, look the cookie authenticator:

```
user.authentication.cookie:
  class: Drupal\user\Authentication\Provider\Cookie
  arguments: ['@session_configuration', '@database']
  tags:
    - { name: authentication_provider, provider_id: 'cookie', priority: 0, global: TRUE }

```

## Solution 3 - generate a cookie used for requests

Another solution would be to login with Drupal (simply post the login form and get the cookie in return) and you could just add the cookie in all requests. That would provide you access. The services modules in Drupal core might help making some of these things a bit easier.
> 2 votes

---
Tags: nodes, 8
---


# Question
Title: Nexus theme slider is not showing up when logged out
I gradually found that if I comments the following code in custom. css, it shows up.

Any clue what is wrong here.. Any help is appreciated

I faced the same issue, and realised the issues in custom.js I commented the following code in custom.css and slider showed up

```
 /* jQuery('#main-menu > nav > ul').mobileMenu({
    prependTo:'.mobilenavi',
    groupPageText: Drupal.t('Main'),
    topOptionText: Drupal.t('Select a page')
  });*/

```

# Answer
Yes, it is because your custom.js is causing conflict with the slider.

You need to use the proper synthax for jQuery.

As mentioned in Working with JavaScript and jQuery

```
(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

    //code starts
    $('#main-menu > nav > ul').mobileMenu({
    prependTo:'.mobilenavi',
    groupPageText: Drupal.t('Main'),
    topOptionText: Drupal.t('Select a page')
    //code ends

  }
};
})(jQuery);

```
> 0 votes

---
Tags: 8, javascript
---


title: Get Instagram realtime count likes

text:
# Question
Title: Get Instagram realtime count likes
Here is how the application is structured:

It was built this way to add moderation of images, so that when an image is unpublished, it wont show up in the gallery. The publish and unpublish aspect works through a tool page where there is an additional flag to remove from the queue as well.

Question is: Since the gallery view is based on the values stored on an instagram node in contenttype.
Is there a way to update the value for the likes count field without having to make a call to the API everytime any user goes to the gallery page?
Otherwise the 'like' counts stored on the article become outdated.

Let me know if I can provide more info.

# Answer
I don't know anything about the Instagram API, but if you want to keep the like counters up to date you will need to make API calls at some point.

If you expect many viewers then as you say, you probably don't want to make that call every time a user goes to the gallery, I would suggest adding another function to cron that iterates through your currently active Instagram content and refreshes the like counter.
> 1 votes

# Answer
There exist a module that integrates instagram with drupal check and see if it could help with your approach drupagram
> 1 votes

# Answer
If you want realtime, you're going to have to use JavaScript like node or something to get true real time.
> 0 votes

# Answer
Have a look at the Menu Badges module to add such notifications to any **menu item** and/or **menu tab** of your choice.

Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it". And as per your "***... it creates a new article on the instagram content type ...***" in your question, it should be straight forward to have such view only count the articles of instagram content type that are "new".

### Video tutorials:
> 0 votes

---
Tags: 7, services, cron
---


# Question
Title: What's the correct way to include JavaScript dependencies into modules?
With Composer we can require PHP dependencies for our modules. What's the right way to include third party dependencies such as a jQuery plugin into a module?

# Answer
> 2 votes
There are a couple of ways you can do it. One way is to define a remote JS resource in your libraries.yml.

See the "CDN/Externally hosted" section here: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

I do this for AddThis (which can be done at the theme or module level) and Fontkit. This is an approach you can take with jQuery plugins that are available via CDN. As long as that resource is available, all you have to do is attach it when needed.

For Javascript that has no external hosting, like CKEditor plugins, I write in the README to download the plugin to libraries/(plugin name) of the `docroot`. There is no way, that I know of yet, to automate that process. This also requires writing into `hook_requirements` in the install file of the module to check that the file exists on the server before installing.

Another way, you could have composer do a `bower install` or `npm install`:

https://stackoverflow.com/questions/25122187/using-composer-to-install-npm-and-bower-packages-on-production-i-e-no-devdepen

Though, it would require the user to have all of those tools installed, and to be a composer user. One gap for that right now is if someone grabs the tarball off drupal.org or uses drush to get your module, none of that would work and they'd still be missing packages. Pathing could also be a headache when trying to write these commands to work for everyone, as well. Composer usage hasn't gained as much traction yet as it needs to beyond developers, but it will become more important moving forward. For example, modules requiring PHP packages (like Search API) simply cannot be drush installed or downloaded from drupal.org and manually placed - a method many, many site builders still use.

Others would say to just stick it in your module, but unless you wrote the plugin, that is against the Drupal licensing/contrib guidelines regarding third party code.

---
Tags: 8, javascript
---


# Question
Title: How to expose paging data in REST export views
How to allow views to export paging data along with entities?

I can set pager, and it works of course, for example my\_view?page=1 displays something like

```
[
  {...},
  {...}
]

```

but I only get list of filtered or paginated entities, and I would like to include paging information, something like

```
[
  paging_info: [
    total: 4,
    per_page: 2,
    current_page: 1,
    ...
  ],
  data: [
    {...},
    {...}
  ]
]

```

# Answer
> 2 votes
Enable pager Exposed option "Allow user to control the number of items displayed in this view" in rest display, then build custom module with views style plugin - to return results and pager data, and set in rest display

short code from custom style plugin:

```
$ret = $this->serializer->serialize(
 [
   'results' => $rows,
   'pager' => [
     'count' => $count,
     'pages' => $pages,
     'items_per_page' => $items_per_page,
     'current_page' => $current_page,
   ]
 ],
 $content_type
);

```

full code in gist: https://gist.github.com/svetlio/79f3c32667b21d89ed03cdb660308668

thanks to Dan's post here: https://www.mediacurrent.com/blog/8-insights-and-useful-snippets-d8-rest-module

# Answer
> 0 votes
So as a temp solution I ended up creating custom route which executes the view I want and returns JSON response. So in a controller method I have something like this

```
$view = \Drupal\views\Views::getView('MY_VIEW_NAME');
//...
$view->executeDisplay('MY_VIEW_DISPLAY_NAME');

$rendered = $view->render();
$json = $rendered['#markup']->jsonSerialize();
$data = json_decode($json);

$pager = [
  'total_rows' => $view->total_rows,
  //...
];

return new JsonResponse([$pager, $data]);

```

I wont mark this as an answer because I'm sure there is better way of getting desired output.

---
Tags: views, paging, 8
---


# Question
Title: How can I attach multiple pdfs to drupal_mail() function?
Was doing something like this

```
        global $base_url;
        $uri = $base_url . '/sites/default/files/test.pdf';
        if(!empty($mail_content)) {
            /*send mail */
            $to =$mail_content['to'];       //gets the current user's mail address
            $from = variable_get('site_mail', '');    //admin's mail address
            $body = $mail_content['body'];

            $filemime = $mail_content['mime'];
            $filename = $mail_content['filename'];
            //$filepath =
            //$filealtname  = drupal_basename($filearray['uri'], $suffix = NULL);

                $attachment = array(
                'filecontent' => 'http://localhost/cando/sites/default/files/test.pdf',
                'filename' => $filename,
                'filemime' => $filemime,
            );

            $mail_content['params']['attachments'][] = $attachment;
            $params = array(
                'subject' => $mail_content['subject'],
                'body' => $body,
                'attachment'=>$attachment,
            );

             // print_r($attachment);print_r($params);exit;
        //  print_r(file_get_contents(DRUPAL_ROOT));die;
            $message = drupal_mail('cando_custom', $mail_content['mkey'], $to, language_default(),$params,$from);

            return 'Mail Sent ... ';

        }
    }

```

# Answer
You forgot to add headers to the params array.

I did something like :

```
$attachment = array(
      'filecontent' => $filepathname,
      'filename' => $namefile,
      'filemime' => 'application/pdf'
      );
//where $filepathname should contain the path to the file and $filename should contain the name of the file.

$params = array(
  'headers' => array('Content-Type' => 'text/html'),
  'key' => 'test',
  'to' => 'test@example.com',
  'from' => 'test@example.com',
  'subject' => 'Test email',
  'body' => 'test',
  'attachment' => $attachment
);

drupal_mail($module, $key, $to, $language, $params, $from, $send);

```

which worked for me.

In your case:

1. Check the value of $filemime variable.
2. Add headers to the code.
> 0 votes

# Answer
Here is an example of how you can attach multiple attachments to an e-mail:

```
/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  switch($key) {
    case 'test1':
      $message['subject'] = 'Hello World';
      $message['body'][] = $params['body'];
      $message['params']['attachments'][] = $params['attachment'];
      $message['params']['attachments'][] = $params['attachment2'];

      break;

    case 'test2':
      $message['subject'] = 'Hello Kitty';
      $message['body'][] = $params['body'];
      $message['params']['attachments'][] = $params['attachment'];
      $message['params']['attachments'][] = $params['attachment2'];

      break;
  }
}

/**
 * Implements hook_node_presave().
 */
function mymodule_node_presave($node) {

        $attachment = array(
            'filecontent' => file_get_contents($node->field_name[LANGUAGE_NONE][0]['uri']),
            'filename' => $node->field_name[LANGUAGE_NONE][0]['filename'],
            'filemime' => $node->field_name[LANGUAGE_NONE][0]['filemime'],
        );

        $attachment2 = array(
            'filecontent' => file_get_contents($node->field_name[LANGUAGE_NONE][1]['uri']),
            'filename' => $node->field_name[LANGUAGE_NONE][1]['filename'],
            'filemime' => $node->field_name[LANGUAGE_NONE][1]['filemime'],
        );

        $params = array(
            'body' => 'cool',
            'attachment'=> $attachment,
            'attachment2'=> $attachment2,
        );

       $to = $node->field_enter_email[LANGUAGE_NONE][0]['value'];

       if($something){

           drupal_mail('mymodule', $key = 'test1', $to, language_default(), $params, $from = 'admin@yourdomain.com', $send = TRUE);

       }
       else {

           drupal_mail('mymodule', $key = 'test2', $to, language_default(), $params, $from = 'admin@yourdomain.com', $send = TRUE);

       }

}

```
> 0 votes

---
Tags: 7, files, emails
---


title: Passing control to another controller

text:
# Question
Title: Passing control to another controller
In a module I use forms. On special occasions I have to start another form in another module. In this case I would like to do the following: 1 pass the control from the form to the Controller(1) of the module 2 this Controller(1) should then pass the control to the Controller(2) of the other module 3 this Controller(2) should start the desired form

Step 1 and 3 I can perform

Step 2 is still a problem because I read that a controller always must render output. I do not want to create a new instance of Controller 2 in Controller 1.

Found out that you can return a redirect to another controller. The parameter handling is not yet clear to me, I cannot find a good tutorial about the usage ofRedirect and passing parameters with it.

# Answer
> 0 votes
My aim is the implementation of a Mediator Pattern. Best practice to do this is using the Event Dispatcher Mechanism. This is explained here.

A good example of implementing the mechanism, even create your own event type (above the existing types of Drupal) is described here

---
Tags: redirection
---


title: Can't update the second front end

text:
# Question
Title: Can't update the second front end
I tried to run drush up on two front-ends (sharing a common database server). The first server went right and updated Drupal and modules just fine. But when I tried to run the same command on the second front end I just got:

```
Command pm-update needs a higher bootstrap level to run - you will   [error]
need to invoke drush from a more functional Drupal environment to run
this command.

```

Yes, I am on the same directory on both servers. And yes, the SITE works on the second front end (checked with change to hosts) so it surely gets connection to the database server.

If I run drush status the outputs are same EXCEPT FOR missing "Drupal bootstrap: Successful" and lines for Drupal user and two Theme lines missing. So any ideas how to start resolving this problem?

hank

# Answer
Drush uses the database to determine what versions of modules are installed; therefore, Drush believes the second frontend to be up-to-date, even though the code is still at an older version.

To update your site:

* Do not update live. Make a local dev environment by copying one of the frontends and the database. Update the local dev environment
* After updating and testing the local system, push the new code to the live systems.
* Run `drush updatedb` on both frontends
> 3 votes

---
Tags: drush, updating
---


# Question
Title: Rebuild Form Element with new property after Ajax
I want to rebuild a Form Item with new property after Ajax triggered on page, I try following codes

```
<?php

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {
        $form['langcode']['widget'][0]['value']['#ajax'] = array(
            'callback' => 'MYMODULE_language_change',
             'wrapper' =>'edit-field-trends-wrapper',
            'event' => 'change',

        );

        $form['field_trends']['widget'][0]['value']['#autocomplete_route_parameters'] = array('lang'=>'test');
        $form['field_trends']['#prefix'] = '<div id="edit-field-trends-wrapper">';
        $form['field_trends']['#suffix'] = '</div>';
    }

}

/**
 * Ajax callback.
 */

function MYMODULE_language_change(array $form, FormStateInterface $form_state) {
        $form_state->setRebuild(TRUE);
            $form['field_trends']['widget'][0]['value']['#title'] = "New Title After Ajax";

        $form['field_trends']['widget'][0]['value']['#autocomplete_route_parameters'] = array('lang'=>'onajax');
        return $form['field_trends'];
}

```

**Update :** in order to find the problem I change the code to simplest manner,

**The Problem is** when ajax triggered autocomplete replaced but changing on `#autocomplete_route_parameters` to applied !!!

**Update 2** Strange things is I try to change field title on ajax callback handler **it applied** and after ajax new title is **New Title After Ajax** but autocomplete parameters not changed. I confused

# Answer
Finally I achieve it with following, *Change autocomplete parameters prperty in form alter on rebuild event INSTEAD of changing property worked for me*,

```
    use Drupal\Core\Form\FormStateInterface;
    use Symfony\Component\HttpFoundation\Request;

    function zeytondev_form_alter(&$form, FormStateInterface $form_state, $form_id) {

        if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {
            $form['langcode']['widget'][0]['value']['#ajax'] = array(
                'callback' => 'zeytondev_language_change',
                'wrapper' =>'mtrend-wrapper',
                'event' => 'change',

            );

            //kint( $form['field_trends']);
            $form['field_trends']['#prefix'] = '<div id="mtrend-wrapper">';
            $form['field_trends']['#suffix'] = '</div>';
            $langcode = $form_state->getValue('langcode');
            if($langcode) {
                $langcode = $form_state->getValue('langcode');
                $langcode = $langcode[0]['value'];
            }
            else {
                $langcode = 'en';
            }
            //var_dump($langcode);
            $form['field_trends']['widget'][0]['value']['#autocomplete_route_parameters'] = array('lang'=>$langcode);
        }

    }

    function zeytondev_language_change(array &$form, FormStateInterface $form_state) {
        $form_state->setRebuild(TRUE);
        return ($form['field_trends']);
    }

```
> 0 votes

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


# Question
Title: How to run cron automatically after node published?
cron has to run after some time of node publishing.I tried like this

```
 function custom_module_cron{
//($updated = node published time)
if(date("Y/m/d H:i:s") == date("Y/m/d H:i:s",$updated+60)){
//code here
}
}

```

but its not running automatically. Can anybody help ?

# Answer
have you managed your cron configuration, if no then go to **/admin/config/system/cron** and set your cron settings to run on that interval of time.

Hope it solves your issue.
> 0 votes

---
Tags: cron
---


# Question
Title: how to discover where mini-panels are surfaced in Drupal 7
We have an old, infrequently updated site which has a custom module which we wrote that either needs to be updated or removed.

This module provides two blocks, and if those blocks aren't being used, we can remove the module. Otherwise, we have to update it to use new functionality, which we would like to avoid if it's not necessary.

I looked under the `admin/structure/block` menu and discovered they are not placed in any regions.

Since I'm a back-end developer, and not really familiar with the theming and templating, I asked one of our front-end devs if the blocks might be used in any other places on the site. She looked through the pages and panelizer stuff, and discovered that the block is being used in a Mini Panel.

So now, the question is, is the mini-panel surfaced to end-users? Nobody presently at the organization is familiar with mini-panels and how they are used. Is there a way, either through the UI or perhaps looking through the tables, to find out of a particular mini-panel is being used?

# Answer
Assuming your site is using Drupal 7 version.

Mini-panels gives us a way to group together multiple blocks (and other content) into a single block. Which can then be placed on page using **Panels** or **Drupal Blocks (Admin =\> Structure =\> Blocks)**. Check this Question Looking for a good Mini - Panels tutorial for more details.

There are 3 places you can check if **Mini Panels** are actually used in your site:

1. **Drupal Blocks** (Admin =\> Structure =\> Blocks) - *Block name is usually shown as '**Mini panel: "Mini Panel Name"**'*
2. **Panel Pages** (Admin =\> Structure =\> Pages). Check all panel pages by editing them and navigating to **Content** section of Panel page.
3. Rendered in Code directly (Since this works similar to block, and can be rendered using the way blocks are rendered programatically). i.e. programatically rendered in theme or module. This might not be in your case, but just to make sure you can check this as well.

This Tutorial shows use of Mini Panels as Drupal Block.

Check out this tutorial on How to use Mini-Panels to create one block that includes all our global blocks \- *The video is paid, but description gives an overview of what it is.*
> 2 votes

---
Tags: 7, panels
---


# Question
Title: Add custom validation on views exposed filter block form
I have one content type called Address. It has title, body, etc.. fields. Initially Created view for Address.

Later client wants to add search field for this view. So created exposed filter block for body field.

Now search block with results working fine.

But challenge is, we need `MINLENGTH` validation to that search field.

Added `$form['#validate'][] = _custom_validate;` in `form_alter`.

```
if ($my_field_length < 4) {
  form_set_error('my_field', t('Please enter minimum 3 characters.'));
}

```
* First Question: This validation is happening on each page load but it is not triggering when we submit form (**This is ajax form**).
* Second question: Is that any possible to stop validation or auto submit on intial page load?

# Answer
There are many issues reported for this behavior on Drupal.org and Drupal Answers.

As a work around, you can try HTML5 `pattern` attribute to add minimum length validation, check example here.

Or add a small JS snippet to validate input field on blur event.
> -1 votes

---
Tags: views
---