# Question
Title: How to assign multiple author names for one article?
Is there any way to mention two or more author names for a particular article in Drupal 7?

I need to add two author names for one article.

I tried to add two author names in the `Author` text box, separating them by commas, but it did not allow me to do this.

Is there any module or other way to do this?

# Answer
My workaround for this would be to enable a user reference field with multiple allowed values on the content type you want to put multiple authors on. Then just disable display of authoring info on that content type and instead display the user reference fields.

There are some things that you can't do with this but if you just want to display or categorize posts by multiple authors I think this will work fine.
> 3 votes

# Answer
Drupal provides the two contribute module for multiple author name to assign single article. `Entity Reference` module and `user Reference` module.
> 0 votes

# Answer
Organic Groups may be a good way to deal with this.
> 0 votes

---
Tags: 7, nodes
---


title: Can't uninstall User Badges

text:
# Question
Title: Can't uninstall User Badges
How can I uninstall the User Badges Module? I always get the same error when I try:

> Recoverable fatal error: Argument 1 passed to file\_delete() must be an instance of stdClass, string given, called in...

# Answer
Up to Drupal 7 all modules and themes list is stored in `system` table with there `enabled (i.e. 1) / disabled (i.e. 0)` status. To Disable your module, set the status to `0` for the module name that you want to disable. Check simple MySQL query below:

`UPDATE system SET status='0' WHERE name='module_name';`

After running the above query, try emptying the cache tables. You can identify cache tables by table name starting with `cache_`. To make sure Drupal doesn't try loading from cache.

You can find more details about same on Drupal.org in Disabling or enabling modules manually in the database Or check How to manually uninstall a module? question.
> 1 votes

---
Tags: 7, installation
---


# Question
Title: How to docreate a function to do if conditions dependign on content type name
```
{% if logged_in == false %}
 <div id="promoiton">
  <div id="promotion-image">
   <div id="promotion-bg">
   <div id="promotion-text">
   <h2>Heading</h2>
   <p>some text.</p>
  <ul>
     <li>something here</li>

   </ul>
    <button<a class="btn btn-primary btn-lg" href="#" role="button">Learn
    more</a></button>
   </div>
  </div>
 </div>
</div>
{% else %}

 <iframe{{ attributes }}{% if url is not empty %} src="{{ url }}{% if
 query is not empty %}?{{ query | url_encode }}{% endif %}"{% endif %}>
 </iframe>
 {% endif %}

```

Hi Folks, in the code example above I have tried do doing some twig foo. It works greate if th user is looged out.

But what if I like to seperate contnet types by machine name?

So for example you have two names lets say article and block

How to make shure that the field is visible on block but not on artivle for logged out users? in short what is the required functioon to get false or true bi a string containing the content type machine name to do something like

```
 {% if logged_in == false || somefunction= 'content_type_machine_name' %}

```

Is that possible?

# Answer
You can set a variable in hook\_preprocess\_Hook function which has the content type and then use that variable in twig file. `$node = \Drupal::routeMatch()->getParameter('node');
 $nids = $node->nid->value;
 if($nids){
 $variables['content_type'] = $node->bundle();
 }`
> 0 votes

---
Tags: theming
---


title: Customize the default search block

text:
# Question
Title: Customize the default search block
In the .theme file of my custom Drupal 8 theme, how do I customize the default search block so that I can add custom classes and also alter the input label to remove the word "search" but instead have a search icon from fontawesome?

Pretty much, I'd like the final output code to look like this:

```
<div class="infoBar-search">
  <form action="#!" class="searchForm">
    <input type="search" name="sitesearch" placeholder="Search...">
    <input type="submit" class="searchForm-submit fa" value="">
  </form>
</div>

```

Would the .theme approach be the best way to go about this? I tried altering a few template files but noticed this would affect the other forms on the site as well.

# Answer
I'm sure this can be done more elegantly , but I was able to do this with a #icon\_variable from the form\[\] to change the input suggestion. I just added side that I want the icon on the button and an extra option to ...-icon-class.html.twig etc.

1) Add a suggestion to the input

```
function MODULE_theme_suggestions_input_alter(array &$suggestions, array $variables, $hook) {

   if (isset($variables['element']['#icon']) || isset($variables['element']['#icon-left']) || isset($variables['element']['#icon-right'])) {
         $suggestions[] = 'input__submit_icon';
         if (isset($variables['element']['#icon'])) {
           $suggestions[] = 'input__submit_icon_' . $variables['element']['#icon'];
         }
      }
   }

```

Then I can add/alter this on the form:

```
   $form['actions']['submit']['#icon-left'] = 'icon-class';

```

With a template like `input__submit_icon.html.twig` :

```
<button {{ attributes }} >
    {% if element['#icon-left'] %}
        <i class="{{ element['#icon-left'] }}"></i>
    {% endif %}
    {{ attributes.value }}
    {% if element['#icon-right'] %}
        <i class="{{ element['#icon-right'] }}"></i>
    {% endif %}
</button>

```
> 2 votes

# Answer
First use the search block of drupal 8 and then override the search form with hook\_form\_alter function. and then finally render that block in the template file.

First override this twig file in your custom theme template. block--search-form-block.html.twig `div class="infoBar-search">
 {{ title_prefix }}
 {% if label %}
 {{ label }}
 {% endif %}
 {{ title_suffix }}
 {% block content %}
 {{ content }}
 {% endblock %}
 /div>`

Correct the div tag. Then use hook\_form\_alter in .theme file to alter what ever u want to alter.

`function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 if ($form_id == 'search_block_form') {
 $form['#attributes']['class'][] = 'searchForm';
 $form['keys']['#attributes']['placeholder'] = t('Search...');
 $form['actions']['submit']['#attributes']['class'][] = '"searchForm-submit fa';
 }`
> 1 votes

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


title: Problem with flexslider

text:
# Question
Title: Problem with flexslider
I have been searching everywhere for an answer to this. I created a views slide show, in Drupal 7, then found out it wasn't working with my responsive theme, so I followed a guide on how to install and use flexslide show modular. Everything worked great, in the preview it shows how it should look but once saved and viewed on website it is showing the nav arrows at the bottom together, not on side of slide show.

I have cleared cache, tried to edit using a css file, tried to move block to another region, tried to adjust size of images through styles, choose both styles and flex style in image format everything I have tried nothing works.

I can change the effects of the arrows, but I can not move them to where they should be. I have searched everywhere, but can not find anything on this problem or how to move them. I have included 2 screen shots of the preview in views and live site. Also, the address of the site i'm working on.

If someone could point me in right direction why this is happening would be great. Thanks!

prntscr.com/dhmdn4 **screen shot in views** prntscr.com/dhmde7 **screen show of live site**

I know that the views shows arrows cropped or missing the top and my pager buttons not center, I can fix that with .css file I created to override my theme I am working on. I just can't figure out why the nav arrows are showing like that.

# Answer
> 1 votes
remove the

```
/* position: absolute; */
/* bottom: 0; */
/* right: 0; */

```

from `.flex-direction-nav`

---
Tags: theming, javascript
---


# Question
Title: Disable the navbar in a Bootstrap sub-theme
I've noticed that the Bootstrap Navbar, while behaving like the 'Main menu' is not available to be enabled and disabled from the blocks admin page, furthermore at the admin menu admin/appearance/my-bootstrap-subtheme/settings there aren't any options to disable it...

Is there a line or option that I can add to the file at...

* my-bootstrap-subtheme/templates/page.tpl.php

...that would disable it?

Alternatively perhaps there is something that can be edited inside the (parent) bootstrap file...

* bootstrap/theme/settings.inc

around line 105 that would add a 'Disable Navbar' option at admin/appearance/my-bootstrap-subtheme/settings ...

Incidentally where would I put this edited settings.inc file inside my subtheme directory?

Thanks.

# Answer
So to add this as an optional setting we can look at how it's done for other navbar variables. For example the navbar positioning which is on line 112 of that settings.inc

```
  $form['components']['navbar']['bootstrap_navbar_position'] = array(

```

Let's see where the variables you can select in that are referenced, such as fixed-top. It's referenced in html.vars.php where they implement the hook\_preprocess\_html() function to take that selection using theme\_get\_setting('bootstrap\_navbar\_position') and create some related variables to pass into the classes\_array for the html.tpl.php.

So you can create a similar field with options like enabled and disabled and pass that on to the page.tpl.php using YOURTHEME\_preprocess\_page (which would probably go in template.php) to create a variable like navbar\_on when it's enabled

```
if (theme_get_setting('bootstrap_navbar_enabled') == 'true') {
  $vars['navbar_on'] = '';

 }

```

and then check in page.tpl.php to see whether or not that's true or not before printing the page.

```
     <?php if ($navbar_on): ?>
          NAVBAR CODE
     <?php endif; ?>

```

EDIT: actually maybe this is already in the theme, just not very clear https://www.drupal.org/node/2287185
> 1 votes

# Answer
I am not getting why I did not give answer to this question, even I have kept this question in favorite list. Probably I would have miss understood the question or currently I am miss understanding a question. Anyway, I am sharing following information which might be helpful. If not relevant please let me know.

There is a option in Drupal by which, you can ***enable/disable main-menu and secondary menu***. Even you can change the entire menu in-place of main-menu and secondary menu.

**Example:**

In following image main-menu and secondary menu, both are enabled.

>

If you go to `structure/Menus/Settings/` you will find the following configuration page. Which provides the option of altering the main-menu and secondary menu, even disabling them as you can see in following screen-shot.

>

Now, if I select `No main links` and `No secondary links` it will disable both menu as show in the following image.

>
> 1 votes

# Answer
I would remove/comment out the output found in page.tpl.php. This will require you to output this menu via an alternate method, if you need it at all. It sounds like you just want it gone, in which case removing the output should suffice.
> 0 votes

---
Tags: theming, navigation
---


title: How can I update a user flag in rules?

text:
# Question
Title: How can I update a user flag in rules?
I am using a user flag, **Visits**, to track each user's visits to other user's profiles.

When a user visits another user's profile, a rule is triggered that automatically flags the visited user on behalf of the visiting user.

Flagging the user on the first visit is no problem. But **on the second visit and thereafter, I want to update the flag that was flagged on the first visit.** To do this, I made the following rule:

* Event: User account page is viewed
* Condition 1: NOT `[account]` is `[site:current-user]`
* Condition 2: User is flagged (`[account]` on behalf of `[site:current-user]`)
* Actions-\> **How do I fetch and update the flag?**

This rule is triggered correctly; however, I don't know how to get the previous flag (the flag applied when the user visited the profile for the first time) in order to update it.

My question: how can I fetch the previously applied flag in rules so that I can update the timestamp and re-save it?

**What I tried**

Flag provides a rules action **Fetch user flagged by user**, but this does not help because this returns an array of users, not the flagging, which is what I want to update.

I can add the **Unflag a node** action and then the **Flag a node action**, but this will destroy my previous flag and replace it with a new one; since I want to track referer information over time, this is not a good solution.

Since I'm using Flag 3.x in which flags are entities, I tried using the **Fetch entity by property** action in Rules to fetch the *flagging*, but in this case the only property I can choose to select is the value of the **Referer** field, which is not helpful. There seems to be no way to fetch the flag by its endpoints.

**Why I'm doing this**

This flag has a computed field, **Referer**, which stores the value of `$_SERVER['HTTP_REFERER']` upon flagging.

When a user visits the profile of a user for the second time, I want to update this flag by updating the timestamp of the flagging and adding the new referer information to the flag.

# Answer
> 2 votes
> My question: how can I fetch the previously applied flag in rules so that I can update the timestamp and re-save it?

Some good news but mostly bad.

If you add an extra text field to the flag and add an extra rule to set its data value to `[flagged_uid]-[flagger_uid]` when a flag is created, it *seems* that you can then fetch the flagging using that field as the Property and `[account_uid]-[current-user_uid]`.

I say *seems* because while the rule runs without errors and I know my logic is right, I can't do anything to the fetched flagging to prove I've actually fetched it. I get an error when trying to delete it because "Rules doesn't have info about deleting a flagging" and saving it doesn't change the timestamp.

It just feels like it's not fully integrated. Even if you added a date field, I'm not sure Rules could access it on user view.

---

I guess I would either create a custom rules action to finish the rule or go with a fully fledged Field Collections solution.

# Answer
> 1 votes
You could add a count field to the flag entity (a numeric field). Every time a user visits a profile, grab the flag and +1 to the count field.

Unfortunately I would not be able to answer how you get this flag via the rules UI.

You could create a custom rule (in code), or a user view hook (hook\_user\_view). Within this hook, load the flag and update the count value.

The below code is an example of the idea, I havent tried it myself. If it doesn't work, try a different flag load and save method. (if no other better method is found you could even resort to a database query to load and update the flag).

```
HOOK_user_view($account, $view_mode, $langcode){
  if ($view_mode == 'profile') {

    // Get user id's
    global $user;
    $viewing_uid = $user->uid;
    $viewed_uid = $account->uid;

    // If we are not viewing our own profile
    if ($viewing_uid != $viewed_uid) {

      // Load the flag contents // Remember to check entity name, and field names
      $flag_entity = entity_load('user_flag', FALSE, array('uid' => $viewing_uid, 'content_id' => $viewed_uid));

      // Update the count
      $flag_entity->count = $flag_entity->count + 1;

      // re-save the entity
      $return = entity_save('user_flag', $flag_entity);
    }
  }
}

```

As a side note: If you have a problem displaying the flag contents on page/profile views, you could also use a load/view hook to override what is displayed. As its an entity however, the field should be available via the entity view mode or views.

I hope this helps.

---
Tags: rules, flags
---


title: Attaching libraries in modules

text:
# Question
Title: Attaching libraries in modules
I'm trying to attach a library in a custom shortcode but it doesn't show up neither using render array nor using attach\_library twig function.

```
  class MyTimeline extends ShortcodeBase {
  public function process($attributes, $text, $langcode = Language::LANGCODE_NOT_SPECIFIED) {
    $output = [
      '#theme' => 'my_timeline_theme',
      '#attached' => array(
        'library' => array('my_timeline/timeline')
      ),
    ];
    return $this->render($output);
  }

```

mymodule/my\_timeline\_theme.html.twig

```
{{ attach_library('my_timeline/timeline') }}

```

The only way I can attach it is using this last line in the active theme, ie node.html.twig

# Answer
The ShortcodeBase Class uses renderplain which strips 'the attached assets and cache tags'

In the comments to the source code they say: We use renderplain so that the shortcode's cache tags would not bubble up to the parent and affect cacheability. Shortcode should be part of contentand self-container.

In order to attach the library I then rendered the Array with this code:

```
$renderer = \Drupal::service('renderer');
return $renderer->render($output);

```

and it works. Need to understand if and how it affects cache, though.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to theme video_embed_field per node type
I have two seperate node types and d8 with media installed

in both node types there is a field called video using video\_embed\_field on a deeper layer in the theme because it uses media entity.

I try to find out how to alte the content of

video-embed-iframe.html per node type.

I am new to d8 and twig.

How can i td this inisde a theme without the need of a custom module

cold i theme the video field per contetn type and then display all template contetn in video field based on an if condition?

# Answer
Twig naming pattern for the field per content type is

```
field--field-name--content-type.html.twig

```

Read more on Twig naming convention here.

---

**update**

Media entity seems to be following custom template suggestions, that unfortunately are not documented anywhere. See `function media_entity_theme_suggestions_media()` here for template suggestions patterns. It does not include per content type template suggestion, but you can try overriding it in a custom module.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Adding dividers between list items in the menu.html.twig template
How do I add dividers between each `<li>` in the `menu.html.twig` template. Obviously with the code below, the divider also gets added after the last item, which isn't the desired result.

```
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    <ul class="loginbar pull-right">
    {% for item in items %}
      {%
        set classes = [
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
      <li class="topbar-devider"></li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

```

# Answer
See The Loop Variable in the Twig docs; you can use something like

```
{% if loop.last == false %}
  <li class="topbar-devider"></li>
{% endif %}

```
> 3 votes

---
Tags: theming, 8, navigation
---


# Question
Title: View ignores unchecked "require this relationship"
I am building a view in Drupal 8 that calls for two relationships:

* Nodes referenced by the current node (relationship required)
* A single node referenced by the above reference node (relationship not required)

Although that second relationship isn't required, my view is still filtering out all nodes where that second relationship is null. Is anyone else having this problem?

# Answer
> 0 votes
I was able to solve this by changing which field I wanted from the reference node. I was originally trying to get the path, but I switched it to "Link to Content." Still, it's odd that when trying to get just the path, views suddenly requires the relationship.

---
Tags: 8, views
---


title: Upload multiple files and directories

text:
# Question
Title: Upload multiple files and directories
Is there a way to upload files and directories, and make Drupal keep the structure in the destination folder?

# Answer
> 1 votes
If you are willing to upload zip files, then maybe Pack & Upload could work for you.

Although I haven't used this before, I would assume that folder structure would remain.

---
Tags: 8, files
---


# Question
Title: Using Rules to block system email or prevent from sending?
I have a unique use case. I am currently using mailcontrol module to disabled the sending of emails when news users are created. However I got to thinking about this, and I was wondering if there is a way to create a Rule to prevent the email from sending so I wouldn't have to use the mailcontrol module.

# Answer
> 0 votes
Maybe a custom module and lines in the setting.php?

Here is a simple tutorial showing how `$message['send'] = FALSE;` can stop it. Of course, you can also use if statments to add conditions.

Note: The developer does mention that you shouldn't use it on production...

---
Tags: rules
---


# Question
Title: Getting the node link in views-view-fields.html.twig
I've created a block display view to list recent posts on a page. Which variable can I use inside the `views-view-fields.html.twig` template file in order to retrieve the link to the post?

```
<div class="thumbnails thumbnail-style thumbnail-kenburn">
  <div class="thumbnail-img">
    <div class="overflow-hidden">
        {{ fields.field_image.content }}
    </div>
    <a class="btn-more hover-effect" href="{{ ??? }}">read more +</a>
  </div>
  <div class="caption">
    <h3>{{ fields.title.content }}</h3>
    {{ fields.body.content }}
  </div>
</div>

```

# Answer
> 2 votes
Add a "Path" field and include it in the view. It should be something like: {field.path.content} You can always format it :D

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


title: Button in block

text:
# Question
Title: Button in block
I want to add a *"View File"* button in Drupal 7 website. A PDF file associated with it, should open in new tab. The problem is that this button should be added inside a block.

I want to ask that how to add a button in a block?

# Answer
For multiple files:

1. Create a View
2. Add your file field and set "Formatter" as "URL to file".
3. Try rewriting the field as `<a href="[YOUR_FIELD]" target="_blank">Go to file</a>`
4. You could embed this view in a block as php. The simplest way would be to use the PHP Filter located in D7 core, but there are some reasons not to use it.

For just one file, use:

```
<a href="/sites/default/files/your-file.pdf" target="_blank">Go to file</a>

```
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: Invalidate node cache so hook_node_view() runs on each node view
My module uses hook\_node\_view() to add some contents to the node view.

```
function example_node_view() {
  if ($view_mode == 'full' && $node->bundle() == 'example')

  // Insert file listing content part
    $contents = Class::getContents();
    $build['example'] = $contents;
}

```

Drupal 8 caches the node view by default and only calls hook\_node\_view() once after each cache rebuild. For this module to function, hook\_node\_view() should run every time the node is requested. So, I am looking for ways to invalidate node:nid cache tag.

NB: \- I am not looking for ways to disable the caching for a development.

```
public function getContents(){
  return [
    "#type" = 'table',
    "#header' = 'header',
     .....
  ];

```

Solved by adding the CacheDependency to hook\_node\_view() as indicated by @4k4

```
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($build, $node->id());

```

# Answer
> 9 votes
For new content added to `$build` you have also add the cache metadata.

Example if you add data from a file entity do this:

```
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($build, $file);

```

This adds the cache tag for the file and whenever this file is changed, the cache item of the node which contains information from the file gets invalidated.

If the added `$content` is already a render array with cache metadata drupal will merge this. You can check, which cache tags are missing in `$content` and add them in the class that generates this data.

Reference: https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays

If what the comment in the code suggests you have a list of files, you can add the tag `'file_list'`. All entities invalidate the tag `[entity-type]_list` when creating, changing or deleting an entity.

Edit:

If you use the standard tools, that is building single entity displays with the view() method and list of entities with Views, then you don't need to take care of cache dependencies, because the render arrays these tools produce contain all necessary cache metadata.

---
Tags: 8, caching
---


# Question
Title: What is a good flexible way to send auto system emails to users?
I would like to know a good user friendly, easy to setup and flexible way to send automated emails to users. This will be in response to an event triggered by a user. I guess it does not matter what it is for. Just need a good way to send system emails, which is widely used.

# Answer
# Only using Rules may not be sufficient

The Rules module, as suggested in the previous answer, is indeed capable to perform these Rules Actions:

* **Send Mail**.
* **Send mail to all users of a role**.

However, if you have not installed any other modules (that integrate with Rules), that's really it (eg Send HTML e-mail is only available if you also install some other module which integrates with Rules).

# Message stack

As per the "most flexible way to send eMails"-part of the question, Rules is only a part of the answer. I recommend you to also have a look at the Message Stack. These are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.

If you'd rather look at an existing module as an example, then checkout the 7.x-4.x version of the Answers module (disclosure: I'm a co-maintainer) and its **Answers Notification** sub-module. This sub-module allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.

# Create a Message archive (audit trail)

By using the Message module, you automagically also create an archive of all Messages. Which is very handy in cases such as when a user claims to never have received some eMail. In such cases, with only Rules, think about how you'd proof that some eMail was mailed somewhere in the past ... as compared to using Message and just bring up that message again ...

# Combining Rules and Message

Moreover, by using the technique of ***Replacement tokens***, it's possible to create your own Message-"tokens" using ... Rules! If these *Replacement Tokens* don't mean anything to you (ie you don't understand what they are really about), then head over to the answer to What's the purpose of "Replacement tokens" of a Message type? for (way) more details on that.
> 1 votes

# Answer
I think the most easy and user friendly way for you is to use Rules module.

EXAMPLE: Create new rule  Add action

Follow next steps to set your mail.
> 2 votes

---
Tags: 7, users, emails, notifications
---


# Question
Title: How do I add javascript to a node or block
I've made a cost calculator script and want to use it on my Drupal 7 site.

I heard to use `drupal_add_js`, but I don't know in what context.

# Answer
Use a function in the template.php file: `yoursite.com/sites/all/themes/YOUR_THEME/template.php`

Add JS file in a block:

```
function YOUR_THEME_preprocess_block(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/scripts/path');
}

```

Add JS file to ***one*** page or node:

```
function YOUR_THEME_preprocess_page(&$variables) {
  if ($variables['nid'] == 'INSERT_NODE_ID') {
     drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/scripts/path');
  }
}

```

Add JS file to a content type:

```
function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {
       drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/scripts/path');
  }
}

```

Add JS file to a view:

```
function YOUR_THEME_preprocess_views_view(&$variables){
  if ($variables['name'] == 'INSERT_VIEW_MACHINE_NAME') {
    // include javascript
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/scripts/path');
  }
}

```

As mentioned by @Pierpaolo Cira, you could always replace `MY_THEME` with `MY_MOUDLE`. To get the path to your module you would have to use `drupal_get_path('module', 'my_module')`.

**Note**: `MY_THEME` and `MY_MODULE` needs to be lowered case if your module or theme name is lowercased. (E.g. `MY_THEME` would be replaced with `zen` if zen)

Source
> 8 votes

# Answer
You can add the js **inside a module** :

Create the module and put inside the mymodule.module

```
drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');

```

or **in the theme**:

in the .info file

```
name = My theme
description = Theme developed by me.
core = 7.x
engine = phptemplate

scripts[] = mytheme.js

```

or in a preprocess\_page function

```
function mytheme_preprocess_page(&$vars, $hook) {
  if (true) {
    drupal_add_js(drupal_get_path('theme', 'mytheme') . '/mytheme.js');
    $vars['scripts'] = drupal_get_js(); // necessary in D7?
  }
}

```
> 3 votes

# Answer
A better approach would be to get the path from Drupal, and you have to put the code in the form function;

```
function mymodule_form($form, &$form_state) {

... some of your forms goes here

    $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/myscript.js';

  return $form;

```

Also add your javascript between the code below

```
(function($)  {
  function mymodule_function(context)  {

  // from here

  // paste your code in here

  // till here

  }

  Drupal.behaviors.custommodule = {
    attach: function(context)  {
      mymodule_function(context);
    }
  }
})(jQuery);

```
> 2 votes

# Answer
Use function in template.php

Add JS file in block:

```
function MYTHEME_preprocess_block(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');
}

```

Add JS file in page or node:

```
function MYTHEME_preprocess_page(&$variables) {
     drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/mytheme.js', 'file');

}

```
> 2 votes

# Answer
if your script is saved as .js you can add it like that in html.tpl.php:

```
<?php drupal_add_js('location/of/my/script/my_script.js'); ?>

```

more info here

OR

```
<script src="location/of/my/script/my_script.js"></script>

```

in your block or node body (make sure that you select format that does not filter JavaScript i.e. "PHP code")
> -1 votes

---
Tags: 7, nodes, javascript, blocks
---


# Question
Title: yml settings file is just read on module install
I have a config/install/module\_name.settings.yml with some configuration values needed for my module. Now while developing the code I need to change or add values to the file. But for the script to be able to access the information I need to deinstall and install the module each time.

Is this normal?

I guess the yml file is just read on install; afterwards, the values are stored in database.

How should I store configuration data without needing to reinstall the module each time?

# Answer
> 7 votes
This is normal, because if the user modifies the settings, he doesn't expect that the changes are overwritten by a module update.

If you want to change the settings in an update hook, you can use the config API.

```
\Drupal::configFactory()->getEditable('mymodule.settings')->set('mysetting', $value)->save();

```

In development you can export the complete config of your site once to the sync folder. There you will find the yml file: /sites/default/files/config\_hash/sync/module\_name.settings.yml.

Edit the yml file in the sync folder and import the config as often as you want until you find the final version. After you've finished the development you can copy the final version of the settings yml in the module folder.

For export and import you can either use the admin configuration interface or use `drush config-export` and `drush config-import`.

Another option is to directly edit the config on the command line:

```
drush config-edit module_name.settings

```

After closing the editor the settings are imported in the active config. After you've finished the development open the settings one more time and copy and paste the end result in the yml file of your module.

---
Tags: 8
---


# Question
Title: Custom module hook entity presave not 'firing'
I've seen other posts and did all the good things, I think... still not firing.

I use Commerce Kickstart 2 in Drupal 7

I want my module to be called for the hook\_entity\_presave event.

I followed the docs to create my custom module: call it 'Update Description' I put my new mod in sites/all/modules/update\_description

```
update_description.info
update_description.module

```

I named the files and added the appropriate info

```
name = Update Description
description = This module populates a description field based on the selected product attributes.
core = 7.x

```

I see, and **enabled the module** in the modules list, and I **cleared cache**

The module looks for a type of entity, and updates it:

```
function update_description_hook_entity_presave($entity, $type){
    $entity->changed = REQUEST_TIME;
    $vari_result = "";

    watchdog('update_description', 'type: ' . $entity->type, array(), WATCHDOG_DEBUG, NULL);

    if($entity->type == 'my_new_content_type' && $entity->product_id && $entity->revision_id) {
        // do stuff
        /// watchdog the results
    }
}

```

But I never see any log messages show up when I create or update an item of 'my\_new\_content\_type', other than the default creation 'info' log message that happens anyway.

What do I need to do to get this my module to 'hook' into this call?

# Answer
> 2 votes
The `hook_` part is for example only; it should be replaced completely by your module's name:

```
function update_description_entity_presave($entity, $type) {

```

---
Tags: 7, hooks
---


# Question
Title: Custom module pages not rendering when added to admin menu
I have a custom module that outputs some sql reports in a table with a csv button. These are SQL tables that are not accessible via views which is why I had to make this module.

Now when these links are accessible through the frontend (ie do not have 'admin' in the path ) the page and table's contents render just fine.

```
$items['custom_report/glp_report'] = array(
'title' => 'GLP Report',
'description' => 'Report for Guided Learning Pathways.',
'page callback' => 'op_reports_page',
'access callback' => 'op_reports_permission',
 //'theme callback' => 'op_theme',
'type' => MENU_NORMAL_ITEM,
);

```

When I switch this to an admin path only the table headers render but no content.

```
$items['admin/custom_report/glp_report'] = array(
'title' => 'GLP Report',
'description' => 'Report for Guided Learning Pathways.',
'page callback' => 'op_reports_page',
'access callback' => 'op_reports_permission',
 //'theme callback' => 'op_theme',
'type' => MENU_NORMAL_ITEM,
);

```

Theme\_debug is on and I can see that on the frontend the bootstrap block.tpl serves the table correctly

```
<!-- BEGIN OUTPUT from 'sites/all/themes/bootstrap/templates/block/block.tpl.php' -->

```

however on the admin page it loads block/block.tpl

```
<!-- BEGIN OUTPUT from 'modules/block/block.tpl.php' -->

```

## Hypothesis

Drupal Admin theme is different than the frontend theme. For whatever reason, this new theme uses a different template and that different template can't render my output.

### Approach 1 Create custom template for the page

So I wanted to force a custom template hoping that would fix the module override:

Here is the page callback:

```
function op_reports_page() {
$page = drupal_render(drupal_get_form('op_reports_form', 'glp'));
$page .= op_reports_table('glp');

$page = array
(
'op_reports_page' => array
(
// Note - we will register theme_my_page in the next step
'#theme' => 'glp_reports',
'#contents' => $page,
),
);

return $page;
}

```

Here is the theme\_hook:

```
function op_reports_theme()
{
  return array
  (
    'glp_reports' => array
    (
      'variables' => array('contents' => array()),
      'template' => 'op_theme', // don't add .tpl.php
    ),
  );
}

```

Template file:

```
<h2><?php print t('My Page'); ?></h2>
<div id="my_page_wrapper">
  <?php print render($contents); ?>
</div>

```
Outcome

While this renders for frontend, on the admin I get a blank content section.

### Approach 2 force the theme through the hook\_menu

Using the theme callback you can tell Drupal how the page should be rendered

Hook Menu:

```
  $items['admin/custom_report/glp_report'] = array(
    'title' => 'GLP Report',
    'description' => 'Report for Guided Learning Pathways.',
    'page callback' => 'op_reports_page',
    'access callback' => 'op_reports_permission',
    'theme callback' => 'op_theme', //name of bootstrap extended theme
    'type' => MENU_NORMAL_ITEM,
  );

```
Outcome

Blank page on admin page

### Approach 3 hook\_custom\_theme

Hook\_custom\_theme should override any theme with the machine name theme

```
  function op_reports_custom_theme(){
    return 'op_theme';
  }

```
Outcome

Blank page on admin page

## Ask

So while I appreciate getting stripes on my Drupal white belt, I would really just like to know the best way to make my custom module render output on an admin path.

# Answer
> 0 votes
All I can suggest is to look at page callbacks that already render on administrative pages (like the ones in core). There should be nothing special between a core or third-party module in this respect.

More thoughts:

* You should not call `drupal_render()` in a page callback. Return the render array and let core do the rendering
* No need for 'theme callback' in a menu definition here

# Answer
> 0 votes
Do not name your access callback `op_reports_permission()`. The conventional name is `op_reports_access()`. You accidentally implemented `hook_permission()`, and I bet you get some warnings when you `drush cc all`.

I think you have misdiagnosed the problem. If the table headers are rendering, but not the table body, then I think something is going wrong in generating the table. You have not shown us the contents of `op_reports_form()` nor `op_reports_table()`, and I suspect that is where the problem is.

I have created a test module for this issue at https://github.com/benjifisher/test-drupal-module. Note that I have tagged two releases: v1.0.0 is the minimal example, and v1.0.1 uses a custom theme function as in your first approach. Feel free to send a pull request!

Standard rules of debugging apply. Make the simplest example you can that reproduces the problem.

> These are SQL tables that are not accessible via views which is why I had to make this module.

It may be easier to tell View how to handle these tables by implementing `hook_views_data()`. A little Google search turns up this blog post. (I cannot vouch for its accuracy, but it looks like what you need.)

---
Tags: 7, theming
---


# Question
Title: How do you allow logged in users to comment via Disqus without extra login?
I have a Drupal site that utilizes Disqus commenting, but want users to be able to use commenting function, without having to login to Disqus.

Is there a way to make Disqus automatically inherit the user information of a person already logged onto my Drupal site?

# Answer
This question is old, but for the sake of the completeness: you have to use Single Sign-On from DISQUS API. In the comment section, logged in users will see themselves connected to the DISQUS system with the cretentials from their Drupal account and will be able to comment directly with no additionnal login. The anonymous users will have to previously connect to DISQUS, Facebook, Twitter or Google before sending their comment. Note that this question has already bee answered here.
> 1 votes

---
Tags: comments
---


# Question
Title: How to update drupal by drush automatically
In common use,after typing "drush up drupal" it need type "yes" for confirm.If I need to use Linux's cron to run drush automatically,how to bypassing the confirm part?

# Answer
> 2 votes
Updating Drupal Core to the latest version e.g. currently Drupal 8

```
drush up drupal -y

```

Updating a specific Drupal Core Version.

```
drush up drupal-7 -y

```

---
Tags: drush, updating
---


# Question
Title: How do I programmatically render a menu's label?
I'm trying to render out a menu with its label in Drupal 8. I am able to get the menu and its links inside of a preprocess function using a helper function, but I can't locate the menu's title.

Here is how I'm getting the menu. I'm able to add the return value as a twig variable $variable\['menu'\]\['menu-name'\] and render out an `<ul>` anywhere I need to.

```
function get_menu($menu_name) {
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
  $tree = $menu_tree->load($menu_name, $parameters);
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);
  $menu = $menu_tree->build($tree);

  return array('#markup' => drupal_render($menu));
}

```

# Answer
> 1 votes
Here is the snippet to change the menu name:

```
 function example_preprocess_menu(&$variables) {
      $element = &$variables['items'];
      foreach ($element as &$item) {
        if ($item['original_link']->getMenuName() == 'menu-machine-name') {
        //For the menu label
       $menu = entity_load('menu', 'menu-machine-name');
          $menu_label = $menu->label();
          if ($item['title'] == 'Example menu') {
            $item['title'] = 'New menu name';
          }
        }
      }
    }

```

---
Tags: theming, 8, navigation
---


# Question
Title: How to get all field name of field type?
I want get all the field names for the fields whose field type is *image*, by code. How can do that?

# Answer
> 8 votes
You are looking for EntityFieldManager::getFieldMapByFieldType():

```
\Drupal::service('entity_field.manager')->getFieldMapByFieldType('image');

```

---
Tags: 8, entities
---


# Question
Title: How to decide to create a multilingual site or to create different site for each language?
This is the first time I want to create a multilingual website. The site is Turkish now and I want to add English as second language (for both interface and content).

The main site (the Turkish one) has about **15 content types** and each content type has **10-20 fields** (text, entity reference, date, image etc). Also each content type has its own `node.tpl.php` and I made lots of **customization** to display node types. In short, the site is a bit **complex**.

I made some research about creating multilingual site (in Drupal of course) but I couldn't decide yet to use Drupal's multilingual features or to clone the Turkish site and create another site for English with some (language) modifications.

Creating two separate site is easier for me but using Drupal's multilingual features seems the **"correct"** way but more painful.

**How to decide to create a multilingual site or to create different site for each language?**

*(More details: **-** Almost all of the contents in the Turkish site will have its corresponding content in the English site. **-** There is a team of non technical editors.)*

# Answer
In my personal view, I will consider if the new language site will be mostly identical to the existing one or not.

It means that if most of the pages / contents in the Turkish site will have its corresponding page / content in the English site, then I will build multilingual site, otherwise, I would like to set up a separate one.
> 3 votes

# Answer
> Using Drupal's multilingual features seems the "correct" way but more painful.

Indeed, more painful, but I think it is what you should go for. Because in the long run you'll achieve the best possible solution for also addressing your requirement "***Almost all of the contents in the Turkish site will have its corresponding content in the English site***".

If you do go for such a multi language implementation, you'll run into some typical issues (questions) for which many contributed modules will actually help you out (the most painful part is to know which module is available to solve which issue). To get you started (in getting used to the pains?), here are some challenges (in a random order), which may help to establish evaluation criteria to decide:

Think about how you would address those challenges if you'd be using multiple sites ... I'm not sure it's possible ... So i18n (and other modules related to it) is the way to go.

PS: Multi language in D8 has become easier ... a bit.
> 3 votes

# Answer
I'd take into consideration who will maintain the content of the page. I've done some multilanguage sites already and i have to admit, that not every content editor will follow the sometimes hilarious ways of managing multilingual content in drupal. I'd say the work of maintaining two complex single sites can easily equal the effort that has to go into making a site truely multilingual.
> 2 votes

# Answer
I have bit of experience working with Drupal multilingual sites.

Another thing to consider if you are using 'entity reference' and referencing nodes to other nodes. This will be bit complex to non technical users.

As the referencing child nodes has to have the same language as the parent node.

as an example: if you have a main/parent product in "Turkish" and you have referenced products(nodes) as "related products", Those has be translated to Turkish as well. you cannot link a node in "English" to another node in "Turkish".

since it's only for one language that's fine. assuming that you can give a training session to them.

Other than that you'll be good to go with "internationalization"

it will give a translate tab in the node/edit when you activate it. you will just need to create translations for those.

for blocks you need to activate the block languages module then you'll be able to translate the blocks too.

Menu translation will be done by activating the "Menu translation(i18n\_menu)" www.drupal.org/node/1113982 module.

views translation can be done by activating the "Views translation (i18nviews)" www.drupal.org/node/2326037 can be filtered using "current users language" in filters in the view.

There won't be any need to change the template files. It will use the same template that is in currently use.

Hope this helped too.

Cheers!
> 2 votes

# Answer
The main thing to consider when asking to solve multi lingual issue by creating multiple instances of the same site (same code base but different database) or using Drupal's multi lingual system is:

1. Is it important that content is linked, so you can find same article in different languages?
2. Is the editorial team split into regional teams, where one or more can't be trusted?

## Why select Multi Lingual (ML) solution

The main thing you gain by setting up Drupal to be ML, is that all content is available in a single site. You can provide information about which languages the content is translated into and links to see the translated content. You only need a single login. Solving the ML issue is only something you need to solve once. Create a new language site will always take a certain amount of time depending on complex your Drupal site is.

## Why select separate installation solution

On the other hand creating separate sites allow you manage the content better. I have a few times, tried being asked to limit the access of certain users, so they only could make changes on the *local* site. For big companies where branding and control can be important, solving this issue can be quite troublesome. Implementing custom access control on nodes based on language is doable, but once the site start using modules like panels, it's not really possible to manage user control. Having the content on separate sites instantly solve these issues.

## Conclusion

Overall most people will benefit from using ML solution. With entity translation handling ML in Drupal 7 isn't that bad. There are many blog posts and experiences all over the internet that can help you in most situations. I've seen separate site route work well in some situations. Usually site that doesn't have a lot of content, like e-commerce sites are viable for this. Note that no matter which solution you end up choosing, there will be pains you have to overcome. What you need to do, is pick the solution where these pains are manageable and acceptable for stakeholders.
> 2 votes

---
Tags: 7, i18n-l10n
---


title: Site is not sending any email

text:
# Question
Title: Site is not sending any email
I have setup web in Drupal 7 and I am using `webform` module to create/configure the forms. The web is not sending any email including registration emails.

I tried to use the following php script to debug the root issue but couldn't-

```
<?php
$to  = 'aidan@example.com' . ', '; // note the comma
$to .= 'wez@example.com';
$subject = 'Birthday Reminders for August';
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: Mary <mary@example.com>, Kelly <kelly@example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday@example.com>' . "\r\n";
$headers .= 'Cc: birthdaycheck@example.com' . "\r\n";
if (mail($to, $subject, $message, $headers)) {
   echo("<p>Email successfully sent!</p>");
}
else {
   echo("<p>Email delivery failed…</p>");
}
?>

```

The script show me successful message. I tried to check the logs at admin/reports/dblog but can't see any error log.

Since I am behind this proxy. Hence I have set the proxy in sites/default/settings.php file as following-

```
$conf['proxy_server'] = '192.168.68.10';
$conf['proxy_port'] = 3128;
$conf['proxy_username'] = 'myuser';
$conf['proxy_password'] = 'mypass';
$conf['proxy_exceptions'] = array('127.0.0.1', 'localhost');

```

The above configurations working fine as I can check for the updates after setting the proxy.

Why drupal is not sending any emails? How to debug it?

# Answer
> 1 votes
While sending email, you can decide whether to host your own SMTP server or you can use the gmail SMTP server. For both include the SMTP module in your site.. configuration of gmail SMTP server is available here: https://stackoverflow.com/questions/8939238/gmail-smtp-configuration-for-drupal-7 Create a gmail account of yours and use it for your site :)

# Answer
> 1 votes
I had the same problem following a recent upgrade to the latest version of modules in Drupal 7.

It turned out that following the upgrade I had to use the same email address as the web address, i.e. if the web address is indigoextra.com, you would have to use something@indigoextra.com as the email address that emails are sent from using Mime Mail.

I'm sure this won't always fix the problem, but it's an easy check to make and you can configure this here - /admin/config/system/mimemail

---
Tags: 7, emails
---


# Question
Title: Accessing hreflang in a preprocessor or twig layer
How do I access this link in either the twig layer or a preprocessor in Drupal 8. I need to modify to edit the hreflang. Thanks

```
<link href="http://www.drupal.com/au" rel="alternate" hreflang="au" />

```

# Answer
```
function MODULE_page_attachments_alter(array &$attachments) {
 foreach ($attachments['#attached']['html_head'] as $can_key => $can_value) {
       foreach ($can_value as $low_value) {
          if (isset($low_value['#attributes']['rel']) && $low_value['#attributes']['rel'] == 'alternate') {
             // Unset canonical tags if present there.
             $attachments['#attached']['html_head'][$can_key]['#attributes']['hreflang'] = 'your value';
           }
        }
     }
}

```
> 1 votes

---
Tags: i18n-l10n
---


# Question
Title: How to print user role id with dynamic variable of language?
How to make this code dynamic initially its printing only user role id for english language only ,if my current site having more then 10 to 20 languages how to change this code to dynamic

```
         global $user;
 global $language;
      //$lg =$language->language;
     dpm(user_load($user->uid));
    $user_fields = user_load($user->uid);
      //echo $user_fields->field_role['en'][0]['value'];

       $lg = $user_fields->language;
         //echo $lg;

     echo $user_fields->field_role['$lg'][0]['value'];

```

if i replace the \['en'\] with \['$lg'\] nothing is printing

# Answer
> 0 votes
You're using `$lg` inside single quotes (**'**), because of which PHP is considering it as static text. If you want to use variable inside quotes, use double quotes (**"**). Check this ans for more details.

Try below code, to print role based on language:

```
<?php
global $user, $language;
$user_fields = user_load($user->uid);
// $lg = $user_fields->language;
$role = (!empty($user_fields->field_role[$language->language]) ? $user_fields->field_role[$language->language][0]['value'] : $user_fields->field_role['en'][0]['value'])
echo $role;
?>

```

---
Tags: 7
---


title: Cannot use libraries in sub-theme

text:
# Question
Title: Cannot use libraries in sub-theme
I'm experiencing a weird problem. I'm making a sub-theme of the Bootstrap theme that's available for Drupal 8. However, after trying all the possible ways of how to attach a library to a page in my theme, no one seems to work. Am I doin'g something wrong?

Here's my libraries.yml file

```
countdown-timer:
version: VERSION
js:
  js/jquery.countdown.min.js: {}
  js/auction-timer.js: {}

```

Here's how I am trying to attach it to all pages in .info.yml

```
libraries:
  - numisvet/countdown-timer

```

I have already tried the approach of adding `'#attached'` to the render array or using `{{ attach_library('numisvet/countdown-timer') }}` in a twig file.

No one of these seems to work, only libraries defined by the Bootstrap theme are getting loaded.

Am I doing something wrong? Thanks a lot for all replies.

# Answer
Simply add your library here in your's my libraries.yml file

```
 bootstrap-scripts:
 js:
bootstrap/js/affix.js: {}
bootstrap/js/alert.js: {}
bootstrap/js/button.js: {}
bootstrap/js/carousel.js: {}
bootstrap/js/collapse.js: {}
bootstrap/js/dropdown.js: {}
bootstrap/js/modal.js: {}
bootstrap/js/tooltip.js: {}
bootstrap/js/popover.js: {}
bootstrap/js/scrollspy.js: {}
bootstrap/js/tab.js: {}
bootstrap/js/transition.js: {}
bootstrap/js/transition.js: {}

Your-sub-theme/js/jquery.countdown.min.js: {}

Your-sub-theme/js/auction-timer.js: {}

```

\**No need to define it separately also place your js file at correct folder path should be eg:Your-sub-theme/js/jquery.countdown.min.js then clear cache \**.
> 0 votes

---
Tags: 8, theming
---


title: How to handle field with multiple items

text:
# Question
Title: How to handle field with multiple items
I have created a field with unlimited number of values allowed. Now, using view I want to display all even number items (like 2nd, 4th, 6th and so on). How can I do that?

My thought: May be I need to edit **views-view-field.html.twig** file. But I'm not finding any way to display items in field instead of complete field. Please help me.

View source of views-view-field.html.twig:

{{ output -}}

# Answer
The standard field handler in Views returns flat rendered output. To change this or put in the feature for even/odd numbered values you would need to implement a field handler plugin. For this task that would be a bit too much work. You can improvise in theming to get the same result.

In Views you can define a separator for multiple field values. Choose a separator that is not in the content of the field. Default is `','`.

In Twig you can use the filter `split` to get the array `items`. Use the separator from the multiple field settings.

**views-view-field--field-fieldname.html.twig**

```
{% set items = output|split(',') %}

```

Put `items` in a loop and display only even number items:

```
{% for item in items %}
  {% if loop.index is even %}
    {{ item }}
  {% endif %}
{% endfor %}

```
> 4 votes

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


# Question
Title: Completely hide/remove views exposed form?
I created a view with exposed filters. The only purpose of the filters is to have url query parameters, which are controlled through custom UI elements.

There is no purpose in displaying the exposed form.

I can think of a number of ways to get rid of the form. But they all involve custom code that directly targets the view id. So it will be throwaway code, not reusable.

Another option could be to put the exposed form into a block, and then simply not display this block. But this will produce noise in features.

I wonder if there is a more elegant way to do this. E.g. a contrib module or a piece of custom code which gives me a checkbox in Views UI where I can say "don't show an exposed form". Maybe an exposed form plugin which does not display the form at all..

# Answer
> 2 votes
If you're using hidden exposed filters instead of contextual filters, then you're already on a bit of a hacky path so you might as well just hide the filters with css.

If you think the contextual filters won't work which is sometimes the case, then the elegant solution is using the Global:Null contextual filter + Views Argument Substitutions to use parts of the url in the normal filters.

But really, just hide it with css.

# Answer
> 0 votes
Here is my solution with a custom views exposed\_form plugin. I don't know if this the best way to do it, but it seems to work.

Create a module `views_unexpose`, with dependencies `views` and `xautoload`. The latter is optional, depends how you want to organize your class files.

In `src/ViewsPlugin/ViewsPlugin_ExposedForm_Unexpose.php`:

```
<?php

namespace Drupal\views_unexpose\ViewsPlugin;

class ViewsPlugin_ExposedForm_Unexpose extends \views_plugin_exposed_form_basic {

  /**
   * @param bool $block
   *
   * @return string
   */
  public function render_exposed_form($block = FALSE) {
    // If the parent method is not called, the entire view will be empty.
    parent::render_exposed_form($block);
    // Ignore the return value from the parent method, return '' instead.
    return '';
  }

}

```

In `views_unexpose.views.inc`:

```
<?php

use Drupal\views_unexpose\ViewsPlugin\ViewsPlugin_ExposedForm_Unexpose;

/**
 * Implements hook_views_plugins().
 */
function views_unexpose_views_plugins() {
  $plugins = [];

  $plugins['exposed_form']['unexpose'] = [
    'title' => t('Unexpose'),
    'help' => t('Completely hides/removes the exposed form.'),
    'handler' => ViewsPlugin_ExposedForm_Unexpose::class,
  ];

  return $plugins;
}

```

In `views_unexpose.module`:

```
<?php

/**
 * Implements hook_views_api().
 *
 * @see views_unexpose_views_plugins()
 */
function views_unexpose_views_api() {
  return array(
    'api' => 3,
  );
}

```

---
Tags: 7, views
---


title: Add background image to block from view

text:
# Question
Title: Add background image to block from view
I created a view that list items from a content type. I have a block display for this view. I want to be able to put a different background image on each instances of this block.

Ideally, it could show up as an option in Block Settings \> Allowed settings so this way every instance would have its own background image.

A second option would be that there is an other option in Block Settings below Block Name, something like Block Bakgorund. This time the same background image would be use as every instance of the block.

An other option would be to create a custom block that has 2 fields, a background image and a entity reference field on the content type my view was listing. Two problems with this, first this come to the same as re-write the functionality of Views, and second I am not sure if I would be able to create a field that is an entity reference on a block created programmatically (module plugin)

Any solution to this or thoughts?

# Answer
I finally had time to make a custom module for that: ctool\_views\_extender

In your MODULE.module:

```
<?php

use Drupal\views\Plugin\views\display\Block as CoreBlock;
use Drupal\MODULE\Plugin\Display\Block;

/**
 * Implements hook_views_plugins_display_alter().
 */
function MODULE_views_plugins_display_alter(&$displays) {
  if (!empty($displays['block']['class'])) {
    $displays['block']['class'] = Block::class;
  }
}

```

In src/Plugin/Display/Block.php:

```
<?php
/**
 * @file
 * Contains \Drupal\MODULE\Plugin\Display\Block.
 */

namespace Drupal\MODULE\Plugin\Display;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\Block\ViewsBlock;
use Drupal\ctools_views\Plugin\Display\Block as CtoolsBlock;

/**
 * Provides a Block display plugin that allows for greater control over Views
 * block settings.
 */
class Block extends CtoolsBlock {

  /**
   * {@inheritdoc}
   */
  public function optionsSummary(&$categories, &$options) {
    parent::optionsSummary($categories, $options);
    $filtered_allow = array_filter($this->getOption('allow'));
    $filter_options = [
      'background' => $this->t('Background')
    ];
    $filter_intersect = array_intersect_key($filter_options, $filtered_allow);

    $options['allow'] = array(
      'category' => 'block',
      'title' => $this->t('Allow settings'),
      'value' => empty($filtered_allow) ? $this->t('None') : implode(', ', $filter_intersect),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $options = $form['allow']['#options'];
    $options['background'] = $this->t('Background');
    $form['allow']['#options'] = $options;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm(ViewsBlock $block, array &$form, FormStateInterface $form_state) {
    $form = parent::blockForm($block, $form, $form_state);

    $allow_settings = array_filter($this->getOption('allow'));
    $block_configuration = $block->getConfiguration();

    if(!empty($allow_settings['background'])){
      $form['override']['background'] = array(
        '#type' => 'managed_file',
        '#title' => $this->t('Background'),
        '#description' => $this->t('Enter background image'),
        '#default_value' => isset($block_configuration['background'])?$block_configuration['background']:'',
        '#upload_location' => 'public://backgrounds'
      );
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit(ViewsBlock $block, $form, FormStateInterface $form_state) {
    // Set default value for items_per_page if left blank.
    if (empty($form_state->getValue(array('override', 'items_per_page')))) {
      $form_state->setValue(array('override', 'items_per_page'), "none");
    }

    parent::blockSubmit($block, $form, $form_state);
    $configuration = $block->getConfiguration();
    $allow_settings = array_filter($this->getOption('allow'));

    if (!empty($allow_settings['background'])) {
        $background = $form_state->getValue(['override', 'background']);
        $configuration['background'] = $background;
        // fix bug in Drupal which does not put the image as permanent
        $fid = $form_state->getValue(['override', 'background'])[0];
        /** @var \Drupal\file\Entity\File $file */
        $file = \Drupal\file\Entity\File::load($fid);
        /** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */
        $file_usage = \Drupal::service('file.usage');
        $file_usage->add($file, 'ctools_views', 'image', 1);
    }

    $block->setConfiguration($configuration);
  }
}

```

Then all you need to do is output it in a twig template. I use another module that I made to simplify things (get\_url\_from\_fid on github or How to get path of image from file id on SE)

```
{% set background = '' %}
{% if configuration.background.0 %}
  {% set background = 'background-image: url(' ~     get_url_from_fid(configuration.background.0) ~ ')' %}
{% endif %}

<div{{ attributes.addClass(classes) }} style="{{ background }}">

```

Cheers!
> 1 votes

# Answer
Finally I decided to patch ctools view block. I have plan to replaced this patch with an object that will extend ctools' view's Block (core/modules/ctools\_views/src/Plugin/Display/Block.php) I paste here for anyone to use.

```
[apache{} patches]$ more ctool-add-bg-to-block.patch
diff --git a/modules/ctools_views/src/Plugin/Display/Block.php b/modules/ctools_views/src/Plugin/Display/Block.php
index 9b72f34..19b64aa 100644
--- a/modules/ctools_views/src/Plugin/Display/Block.php
+++ b/modules/ctools_views/src/Plugin/Display/Block.php
@@ -31,7 +31,8 @@ class Block extends CoreBlock {
       'hide_fields' => $this->t('Hide fields'),
       'sort_fields' => $this->t('Reorder fields'),
       'disable_filters' => $this->t('Disable filters'),
-      'configure_sorts' => $this->t('Configure sorts')
+      'configure_sorts' => $this->t('Configure sorts'),
+      'background' => $this->t('Background')
     ];
     $filter_intersect = array_intersect_key($filter_options, $filtered_allow);

@@ -54,6 +55,7 @@ class Block extends CoreBlock {
     $options['sort_fields'] = $this->t('Reorder fields');
     $options['disable_filters'] = $this->t('Disable filters');
     $options['configure_sorts'] = $this->t('Configure sorts');
+    $options['background'] = $this->t('Background');
     $form['allow']['#options'] = $options;
     // Update the items_per_page if set.
     $defaults = array_filter($form['allow']['#default_value']);
@@ -79,6 +81,16 @@ class Block extends CoreBlock {
       unset($form['override']['items_per_page']['#options']);
     }

+    if(!empty($allow_settings['background'])){
+      $form['override']['background'] = array(
+        '#type' => 'managed_file',
+        '#title' => $this->t('Background'),
+        '#description' => $this->t('Enter background image'),
+        '#default_value' => isset($block_configuration['background'])?$block_configuration['background']:'',
+        '#upload_location' => 'public://backgrounds'
+      );
+    }
+
     // Provide "Pager offset" block settings form.
     if (!empty($allow_settings['offset'])) {
       $form['override']['pager_offset'] = [
@@ -270,6 +282,19 @@ class Block extends CoreBlock {
       }
     }

+    if (!empty($allow_settings['background'])) {
+        $background = $form_state->getValue(['override', 'background']);
+        $configuration['background'] = $background;
+        // fix bug in Drupal which does not put the image as permanent
+//      kint($form_state->getValue(['override', 'background'])[0]);
+        $fid = $form_state->getValue(['override', 'background'])[0];
+        /** @var \Drupal\file\Entity\File $file */
+        $file = \Drupal\file\Entity\File::load($fid);
+        /** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */
+        $file_usage = \Drupal::service('file.usage');
+        $file_usage->add($file, 'ctools_views', 'image', 1);
+    }
+
     // Save "Pager offset" settings to block configuration.
     if (!empty($allow_settings['offset'])) {
       $configuration['pager_offset'] = $form_state->getValue(['override', 'pager_offset']);

```
> -1 votes

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


title: Breadcrumbs are cached

text:
# Question
Title: Breadcrumbs are cached
In Drupal 8, if I create a node, add a menu link, save it, then go back and edit the menu link title in the node, the breadcrumb title does not update until I clear the cache.

How can this be set so it reflects this change without requiring flushing the cache?

# Answer
Breadcrumbs for nodes have no cache tags. The reason is that the node entity has no specific breadcrumb builder. The generic path based breadcrumb builder gets the title from the title resolver and is not aware where the title is from and what tag it should set.

You can add tags for nodes in `hook_system_breadcrumb alter()`:

```
function mymodule_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  if ($route_match && $node = $route_match->getParameter('node')) {
    $breadcrumb->addCacheableDependency($node);
  }
}

```

To test this you need to have extended the breadcrumb behavior to display the title. In my test site this was the Bootstrap theme. Another option would be the module Current Page Crumb.
> 15 votes

# Answer
I am very sorry that I don't (yet) have the "50 reputation" to comment on 4x4's excellent answer above, but we have a pathogical case already identified in that same issue queue...

---

It would be great to pop that code segment into Menu Breadcrumb but we still have no way of converting all menu link plugin IDs in the active trail into entities. Please see Menu Breadcrumb issue 2831084 for a counter-example. The general difficulty is phrased here and if we find an answer there would finally be a release candidate for Menu Breadcrumb.

For relevance to the original posting, once that happens (i.e. we know how to produce a cacheable entity for all items on the menu active trail) I will come back & modify this answer if it's not already posted.
> 4 votes

---
Tags: 8, caching, breadcrumbs
---


title: Preserve nids script add in migrate d2d

text:
# Question
Title: Preserve nids script add in migrate d2d
What is the file name I have to add the following script in it?

> This is actually easy to do. In the prepare() function of the node migration class, just set the nid and is\_new to true:
>
> ```
> public function prepare($node, $row) {
>   // Preserve old nid so that old links to nodes using /node/nid still work
>   $node->is_new = TRUE;
>   $node->nid = $row->nid;
> }
>
> ```
>
> Source link: How can I preserve nids during a migration?

# Answer
> 2 votes
Unfortunately, sometimes answers on stackexchange are misleading. It doesn't look like ANY classes within migrate\_d2d extend MigrateDestinationEntity, that invokes a "prepare" hook. So I think the question itself is misguided.

Looking in the migrate code, it looks like any class that extends abstract class MigrateDestinationEntity can call this process function see /migrate/plugins/destinations/entity.inc,

on line 140:

```
// Then call any entity-specific handlers
migrate_handler_invoke_all($this->entityType, 'prepare', $entity, $source_row);

```

Rather than trying to find a place to call this from DrupalNodeMigration, which will never call this function, what you need to do is add a mapping for nid, and a mapping for "is\_new".

In your class that extends the DrupalNodeMigration class, in the \__contruct() function, just make sure to add a mapping for nid and is\_new.

```
$this->addFieldMapping('nid', 'nid');
$this->addFieldMapping('is_new')->defaultValue(TRUE);

```

Otherwise, nid will be automatically assigned.

# Answer
> 1 votes
I understand why you're asking, that answer is not really clear, or very generic at best. Let's see if we can figure out what they meant.

The `prepare()` methods of Migration classes are invoked from the prepare() method found on the `MigrateDestinationEntity` class (migrate/plugins/destinations/entity.inc). In the case of a d2d node migration, the Migration class is `DrupalNodeMigration` (migrate\_d2d/node.inc). Other d2d Migration classes, like `DrupalRoleMigration`, also implement a `prepare()` method. So, my conclusion would be that this code should be added in `DrupalNodeMigration`.

Disclaimer: I didn't test this, it is just my conclusion based on reading the answer and code.

I must add that editing the code of a contributed module is never recommended. A cleaner, but more time consuming way would be to create a new Migration class in a custom module, make it extend `DrupalNodeMigration`, and add the prepare method there. How to do that exactly is beyond the scope of this question.

---
Tags: 7, migrations
---


# Question
Title: Include custom node id when POST'ing data through the REST API
Is it possible to include a custom node id when POST'ing a node using the REST API? Knowing the node id in advance makes it easier to update the nodes in a future stage.

# Answer
I think the default REST services don't allow that. You could implement yor own. It would need logic that prevents that existing nodes are overwritten exactly.
> 0 votes

---
Tags: nodes, 8
---


# Question
Title: The directory sites/default/files is not writable on Mac OS X
I had my website developed by someone else and it is currently working with no issues on our web server. I'm trying to set the same site up on my Mac OS X 10.6 using the preinstalled Apache server, MySQL, and PHP5. Also, it's Drupal 6.22 we're using. I copied all of the website files (including Drupal and the .htaccess file) and put them in /Library/WebServer/Documents/website. I then did a mysql backup on the server and imported that file on the local machine with phpMyAdmin. I configured the settings.php file and everything else to work nicely so it can connect to the DB, etc.

Most of the site works as expected, however, there is a couple of nodes that won't work at all. Instead I get this message when I go to them:

*"The site is currently not available due to technical problems. Please try again later. Thank you for your understanding."*

The weird part is if I enter in the URL to go to the edit page for that node it works, but I still cannot view the page.

When trying to search for problems that only issue I found anywhere is in the "Status Report" page it says the file system is not writable. I get this message:

*"The directory sites/default/files is not writable."*

I checked the permissions and that folder has drwxr-xr-x set for it.

Any ideas as to what might not be set properly would be greatly appreciated.

# Answer
The *files* directory in your site must be writable by the webserver. In the finder, do a Get Info on the *files* directory and assign *read & write* permissions to *staff*. (Make sure that this applies to any directories inside *files* as well.) Alternatively, in the terminal you could "chmod -R 775 my-site-path/sites/default/files" to take care of *files* and any contained subdirectories.
> 2 votes

# Answer
I had checked which user is running the "httpd" process. In my case it was "daemon".

> sudo chown -R daemon sites/default/files/ had solved the problem (permissions: 775)
> -1 votes

---
Tags: nodes, database, installation, files
---


# Question
Title: How to show message view containing own and following activity?
I have created a message view using the Message module. I want this view to show the current user activity and activity of the user he is following using the "follow" flag (user). i.e own + following.

The Message module comes with a "message subscribe" flag, but I do not want to use that. What should be the setting of my view particularly the relationship and contextual filters?

# Answer
> 2 votes
# About the Message module and user activity

Even though you're question doesn't really say so, I'm assuming that:

* "***activity***" in this question is about message instances created by the Message module, targeted to the current user.
* "***activity of the user he is following***" is about message instances target to the current user (also), though they are about events related to any of the followed users (indicated by your follow-flag).

If these assumptions are correct, then your question is about creating a view of various flavors of messages (typically created using various ***Message Types***), which are all targeted to the current user.

# Creating a view about Messages by user

### Add a new view

* View name "Messages by user".
* Show *Message*.
* Type *All*.
* Create a page (not a block)

### Create a table display of this view

For this question here, you only need a single table display, of ***All*** messages.

To differentiate this "All", think of additional displays you might want to add later on, such as:

* Read messages
* Unread messages

### Add Contextual Filters

* Message: User uid, and for "When the filter value is NOT in the URL" use "Provide default value" with Type "User ID from logged in user".

### Add Relationships

"***Message: User uid***" will result in the messages targeted to the current user, so that one you need for sure.

I suggest you create a first display only using the above relationship (to check the results you get so far). Then clone this display into another one, in which you add another relationship like "***Flags: follow (by current user)***" (assuming that `follow` corresponds to your follow-flag). By swapping between the 2 displays, you can decide which one you really want, or just keep both.

### Add Fields

* Message: Message ID (Msg ID)
* Message: Timestamp (Created on)
* Message: Render message (Get text) (Text)
* (User) User: Name (User), and use "Exclude from display" for this field, which is only needed to add a "Global: Text area" to the views headers which contains something like `Messages for user [name]`.

### Add Sort criteria

* Message: Timestamp (desc)

### Further Refinements

* Filter criteria: none
* Page settings:

+ Path: `/user/%/messages`
    + Menu tab: Messages

# Make the Messages manage-able

If you complete the above steps, you'll have a view that shows all relevant messages ... and that's really it. It won't be obvious for a user to remember which messages have been read already, and which ones are new (= unread). Try it for yourself (to experience the pain ..).

To implement a facility to mark messages as read/unread, just perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

1. Create a flag (using the the Flag module).
2. Create a view 'Messages by user' (= improved version of the view specifications described above).
3. Use Rules to flag/unflag messages.
4. Trigger the Rules Component to mark messages (using the VBO module).
5. Create notifications about Unread Messages (using the "Menu Badges" module). So that whenever a new message gets created, the user gets a notification in the format of an iOS-like (red) badge with the number of unread messages.

# Fruit of your labor

If you follow the above steps, the result of it is something similar to an eMail client inbox, whereas the eMail "messages" are not real eMails, but instances of messages created by the Message module.

---
Tags: 7, views, flags, message-subscribe
---


# Question
Title: How to resolve drush error: the file name, directory name, or volume label syntax is incorrect
I've adding and removing modules with drush when something went wrong. I'm using the latest version of Acquia devdesktop and now when I run any drush command I get the error "the file name, directory name, or volume label syntax is incorrect." This error seems to be specific to the site I am working on, as drush works outside of the site folder. How can I fix this?

UPDATE: so, I deleted what I thought were the offending folders but the problem persists.

Update2: ran the drush debug command and I didn't see anything meaningful or diagnostic in the results.

```
Starting Drush preflight. [0.21 sec, 1.68 MB]                        [preflight]
Loading drushrc "C:\Program Files\Dev                                [bootstrap]
Desktop\drush\vendor\drush\drush\drushrc.php" into "drush" scope.
[0.22 sec, 1.69 MB]
Cache MISS cid:                                                          [debug]
8.0.0-rc1-commandfiles-0-d122bbeed82161c117b94e5f9e65d6f6 [0.33 sec,
1.72 MB]
Cache SET cid:                                                           [debug]
8.0.0-rc1-commandfiles-0-d122bbeed82161c117b94e5f9e65d6f6 [0.41 sec,
1.74 MB]
Scanning into C:\ProgramData/Drush/etc/drush for                     [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [0.51 sec, 3.41 MB]
Scanning into C:\ProgramData/Drush/etc/drush for                     [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [0.51 sec, 3.41 MB]
Scanning into C:\Program Files\Dev                                   [sitealias]
Desktop\drush\vendor\drush\drush\includes/.. for
/.*aliases\.drush(8|)rc\.php$/ [0.52 sec, 3.41 MB]
Scanning into C:\Program Files\Dev                                   [sitealias]
Desktop\drush\vendor\drush\drush\includes/.. for
/self\.alias\.drush(8|)rc\.php$/ [0.62 sec, 3.42 MB]
Scanning into C:\Users\Nick/.drush for /.*aliases\.drush(8|)rc\.php$/[sitealias
[0.71 sec, 3.42 MB]
Scanning into C:\Users\Nick/.drush for                               [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [0.71 sec, 3.42 MB]
Scanning into C:\Users\Nick/.acquia/DevDesktop/Drush/Aliases for     [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [0.72 sec, 3.42 MB]
Scanning into C:\Users\Nick/.acquia/DevDesktop/Drush/Aliases for     [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [0.72 sec, 3.42 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/../drush for        [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [0.72 sec, 3.42 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/../drush for        [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [0.72 sec, 3.42 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/drush for           [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [0.73 sec, 3.42 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/drush for           [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [0.73 sec, 3.42 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/sites/all/drush for [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [0.73 sec, 3.42 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/sites/all/drush for [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [0.73 sec, 3.42 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/sites/default for   [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [0.73 sec, 3.42 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/sites/default for   [sitealias]

/self\.alias\.drush(8|)rc\.php$/ [0.73 sec, 3.43 MB]
Begin redispatch via drush_invoke_process(). [1.32 sec, 5.17 MB]        [notice]
Scanning into C:\ProgramData/Drush/etc/drush for                     [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [1.32 sec, 5.17 MB]
Scanning into C:\ProgramData/Drush/etc/drush for                     [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [1.33 sec, 5.17 MB]
Scanning into C:\Program Files\Dev                                   [sitealias]
Desktop\drush\vendor\drush\drush\includes/.. for
/.*aliases\.drush(8|)rc\.php$/ [1.33 sec, 5.17 MB]
Scanning into C:\Program Files\Dev                                   [sitealias]
Desktop\drush\vendor\drush\drush\includes/.. for
/self\.alias\.drush(8|)rc\.php$/ [1.41 sec, 5.17 MB]
Scanning into C:\Users\Nick/.drush for /.*aliases\.drush(8|)rc\.php$/[sitealias]
[1.5 sec, 5.17 MB]
Scanning into C:\Users\Nick/.drush for                               [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [1.5 sec, 5.17 MB]
Scanning into C:\Users\Nick/.acquia/DevDesktop/Drush/Aliases for     [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [1.5 sec, 5.18 MB]
Scanning into C:\Users\Nick/.acquia/DevDesktop/Drush/Aliases for     [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [1.51 sec, 5.18 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/../drush for        [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [1.51 sec, 5.18 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/../drush for        [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [1.51 sec, 5.18 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/drush for           [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [1.51 sec, 5.18 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/drush for           [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [1.51 sec, 5.18 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/sites/all/drush for [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [1.52 sec, 5.18 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/sites/all/drush for [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [1.52 sec, 5.18 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/sites/default for   [sitealias]
/.*aliases\.drush(8|)rc\.php$/ [1.52 sec, 5.18 MB]
Scanning into C:\Users\Nick\Sites\devdesktop\psr/sites/default for   [sitealias]
/self\.alias\.drush(8|)rc\.php$/ [1.52 sec, 5.18 MB]
Backend invoke: "C:\\Users\\Nick\\Sites\\devdesktop\\psr\\drush"       [command]
--root="C:\\Users\\Nick\\Sites\\devdesktop\\psr" --local --debug
--verbose  core-status 2>&1 [1.53 sec, 5.19 MB]
Calling proc_open("C:\\Users\\Nick\\Sites\\devdesktop\\psr\\drush"  --root="C:\\
Users\\Nick\\Sites\\devdesktop\\psr" --local --debug --verbose  core-status 2>&1
);
The filename, directory name, or volume label syntax is incorrect.
End redispatch via drush_invoke_process(). [1.55 sec, 5.18 MB]          [notice]

```

# Answer
This error just happen to me.

Not sure about how to fix this error. But for workaround, I install drush via composer and use that Drush. Not the one installed from Acquia Dev Desktop.

Because I use Drupal Comoposer project template, this is the command I run:

```
D:\Sites\myweb\web>..\vendor\bin\drush.bat cr --root="D:\\Sites\\myweb\\web"
Cache rebuild complete.

```
> 1 votes

# Answer
I had the same error in a new Drupal project which installed drush (8.1.8) for that project via composer (inside the project/vendor folder).

The command 'drush status' showed that I was using an older, global installed version of drush (inside C:\Users\Gebruiker\AppData\Roaming\Composer\vendor\drush\drush).

I edited my environment variables, edited the PATH variable, and changed the global drush path to my projects drush path. Then closed all command windows and my IDE and reopened my IDE and project.

The command drush status now showed the correct drush version (8.1.8) and all drush commands are now working fine.
> 1 votes

# Answer
Hopefully, you should be able to discover which file/directory name is causing the problem, by making Drush print some debugging info:

```
drush -d -d status

```
> 0 votes

---
Tags: drush
---


# Question
Title: How to use rendered file entity in view header as background image for view
I would like to set a background image on a div in my views-view.tpl.php using the image from a rendered entity field in the View Header.

Something like:

```
   <div class="group-header" style="background-image:;">
    <div class="group-heading container">
      <?php print render($title_prefix); ?>
      <?php if ($title): ?>
        <div class="page-title">
          <h1 class="l-view-title"><?php print t($title)?></h1>
        </div>
      <?php endif; ?>
      <?php print render($title_suffix); ?>

      <?php if ($header): ?>
        <?php print $header; ?>
      <?php endif; ?>
    </div>
  </div>

```

How do I print just the url of the entity from the header? It would be great if I could pull the image URL and add an inline style on the `group-header` div. Any ideas on how to accomplish this?

Similar to this question: Use image from view as background image of div in page.tpl.php

# Answer
> 0 votes
Is there something the Background Images Formatter module can do for you?

The module allows you to set a background to any CSS selector(s) you can think of. Combine it with a selector built with NID-token (NID field in Views, excluded from display, and its token used in the selector you assign the background-image to), and it will probably save you some templating headaches.

# Answer
> 0 votes
The simplehtmldom parser will be helpful to render this for you.

https://www.drupal.org/project/simplehtmldom

we can supply the html to this parser and capture the output by the APIs provided. http://simplehtmldom.sourceforge.net/manual.htm

http://simplehtmldom.sourceforge.net/manual\_api.htm

```
      $html_obj = new simple_html_dom();

      $wrapped_header = "<div class='header_url'>{$header}</header>";
      $html_obj->load( $wrapped_header );
     $url_forimage="";
      // use the wrapped class
      foreach ($html_obj->find('header_url') as $plain_text_obj ) {
//get class of the rendered element and use that to capture the src tag.
//check API for more info. you should list them in the DOM hierarchy.
//I have used this DOM hiearchy "div.views-field-field-banner-image > div > a > img" for the below code.

           $url_forimage= $plain_text_obj->find('div[class=views-field-field-banner-image] div a img',0)->src;
          }

      <div class="group-header" style="background-image:<?php print $url_forimage;?>">
        <div class="group-heading container">
          <?php print render($title_prefix); ?>
          <?php if ($title): ?>
            <div class="page-title">
              <h1 class="l-view-title"><?php print t($title)?></h1>
            </div>
          <?php endif; ?>
          <?php print render($title_suffix); ?>

          <?php if ($header): ?>
            <?php print $header; ?>
          <?php endif; ?>
        </div>
      </div>

```

You will need work on this to get it work.

---
Tags: 7, views, theming
---


title: Ordering taxonomy view by date added

text:
# Question
Title: Ordering taxonomy view by date added
I have an taxonomy and an view that displays it.

This view has default sorting by `Taxonomy term: Weight (increasingly)`. I would like to add, as second criteria (when the weights are equal) the date when taxonomy term has been added.

Unfortunately on the list under criteria -\> add I cannot see anything date-related:

Where should I find the date of term has been created?

# Answer
Try using the Taxonomy Creation Date module. It adds creation and updated date rows to the database, so you should be able to use it in view.
> 0 votes

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


title: custom number field input on yaml forms

text:
# Question
Title: custom number field input on yaml forms
I need to ask the user for an 8-digit number within a yaml form.

the number I need is 12345678 and goes is this layout: 1.234.567-8

is it possible to ask the user for this 8-digit number field and display it as 1.234.567-8 ?

ideally the field would be rendered to the user as: _ . _ _ _ . _ _ _ - _ while it's being filled.

thanks in advance

# Answer
> 0 votes
The YAML Form module supports inputmasks which can be configured to handle any desired input format. The submitted value will match your input mask. If you need to submitted value to be converted to a number, you will have to write an update hook to do the conversion.

---
Tags: 8, forms
---


# Question
Title: Editable Fields, Custom Submit function is not being called?
I'm using editable fields, so I can edit the fields on node display page (e.g. at node/123). I want to add a submit function, so that I can add other process every time the user edit the field. My problem is my custom submit function is not being called.

Below is the code I'm using:

```
function apws_extras_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'editablefields_form_node_field_apws_batch_completed_field':
      if ($form['type']['#value'] == 'apws_batch') {
        $form['#validate'][] = 'apws_extras_batch_completed_form_validate';
        $form['#submit'][] = 'apws_extras_batch_completed_form_submit';
      }
      break;
  }
}

function apws_extras_batch_completed_form_validate(&$form, &$form_state){
  // Check if this field is set.
  // Code for validation here.
}

function apws_extras_batch_completed_form_submit(&$form, &$form_state) {
  drupal_set_message('Submit is working');
}

```

# Answer
> 1 votes
You can try this:

```
function apws_extras_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
case 'editablefields_form_node_field_apws_batch_completed_field':
      if ($form['type']['#value'] == 'apws_batch') {
        $form['#validate'][] = 'apws_extras_batch_completed_form_validate';
        //$form['#submit'][] = 'apws_extras_batch_completed_form_submit';
        $form['actions']['submit']['#submit'][] = 'apws_extras_batch_completed_form_submit';
      }
      break;
  }
}

function apws_extras_batch_completed_form_validate(&$form, &$form_state){
  // Check if this field is set.
  // Code for validation here.
}

function apws_extras_batch_completed_form_submit(&$form, &$form_state) {
  drupal_set_message('Submit is working');
}

```

---
Tags: 7, forms
---


# Question
Title: access the node id of a field collection
How do I access the node id of a d8 field collection that is attached to the node in hook\_preprocess\_field(&$variables)?

# Answer
> 1 votes
It works for me. You can do it as follows-

`/**
 * Function hook_preprocess_field.
 */
function [theme_name]_preprocess_field(&$variables) {
 if ($variables['field_name'] == [FIELD_COLLECTION_NAME]) {
 if ($variables['element']['#entity_type'] == "node") {
 $node_id = $variables['element']['#object']->id();
 //Rest of the code.
 }
 }
 }`

Hope it works for you too.

---
Tags: 8, entities
---


# Question
Title: Drupal 8 Display True/False instead 0/1 on checkbox value in ConfigFormBase
By default the boolean fields' value displayed as 0/1 when user filled the checkbox field under custom configuration form. Need to render True/False instead of 0/1.

```
$form['newfield'][$id]['required'] = array(
  '#type' => 'checkbox',
  '#default_value' => ($config[$id]['required'] ? $config[$id]['required'] : $field['required_disabled']),
  '#disabled' => $field['required_disabled'],
);

public function submitForm(array & $form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $config = $this - > config($this - > configId);
    $fields = static::getFields();
    $values = $form_state - > getValues();
    $values = $values['newfield'];
    foreach($values as $key => $field) {
        $config_values[$key] = array('visible' => $field['visible'], 'required' => $field['required'], );
    }
}

```

# Answer
In drupal8, you can easily handle this from "Manage Display" of your content type.

> Go to /admin/structure/types/manage/article/display Select your "view\_mode". Ex- Default.

> Go to the boolean field and click on its settings icon which is placed at atmost right side of the field. Change the output format to "True/False".

Hope, this works for you.
> 1 votes

---
Tags: forms, 8, configuration
---


# Question
Title: Show Taxonomy with all terms in article url
i want to show http://example.com/category/subcategory-1/subcategory-2/title of article format for any article.

I have used Pathauto module but unable to configure as desired.

# Answer
> Go to url- /admin/config/search/path/patterns/add.
>
> Select "Pattern type" from drop down.(Ex- Content.)
>
> Select "Content type" for those you want to configure the path.
>
> Provide a nice label to it.(recommended)

Rest select the available tokens for the content type that you can use from "Browse available tokens" link.

Refer to the attached screen shot.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: Change CSS of grid view (Not just for a field) in Drupal 7
I designed a grid of 3 columns in Drupal 7 using view. Below is the default outcome-

It doesn't look beautiful. Hence I want to change the css for each row and column, something like following-

I already have awards and award-list class defined inside style file. But I don't know how to configure the view, so that it uses these class instead of default classes.

Notice carefully the first image, in which I am able to add the css class *awards* (in the first line *div*). Also I am able to add css to each *td* element. This is perfectly fine. The problem is that *td* has some more parameters defined such as *background, color, text-align, border* etc, which I don't need for this view. Also there are few more unwanted attributes defined for table class *view-view-grid cols-3*. These elements are *background* and *border*, which I don't want for this view.

I found out a workaround, in which I redefine all these attributes inside `style.css` and I changed the border from 1px to 0px etc. See below the css, which I appended in style.css-

```
.awards table{
  background: #BAF5D9;
  border: 0px;
}

.awards td{
  background: #BAF5D9;
  color: #333;
  text-align: center;
  padding: 0px;
  border: 0px;
}

```

Here `#BAF5D9` is background color of the theme. You can notice that it not a proper way to redefine. as the css is getting bigger.

I want to configure this view, in such a way, so that these attributes don't be generated.

Please have a look. I really appreciate your help.

# Answer
> 1 votes
You can add classes to view https://www.ostraining.com/blog/drupal/css-views/

Also see: How to add CSS classes to a Views-generated block? (NOT to its generated content, the block itself!)

---
Tags: views
---