# Question
Title: getting 404 error while developing an example module
I have created custom module named hello my files are

**hello.info.yml** is

```
name: Hello
type: module
description: 'My first Drupal 8 module.'
package: Awesome modules
version: 1.0
core: '8.x'

```

**hello.module** file is

```
<?php

use Drupal\Core\Routing\RouteMatchInterface;
function hello_hello_world() {

    return t('Hello Drupal 8 World!');

}

```

\** hello.routing.yml\** file is

```
hello.content:
  path: '/hello'
    defaults:
       _controller: '\Drupal\hello\Controller\HelloController::sayhello'
  requirements:
    _permission: 'access content'

```

and last one is **HelloController.php** is under hello/src/Controller folder

```
<?php

namespace Drupal\hello\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 *
 */
class HelloController extends ControllerBase {
    /**
     * [sayhello description]
     * @return [type] [description]
     */
    public function sayhello() {
        return array('#markup' => hello_hello_world());
    }
}

```

when we browse this page mywebsite.com/hello it gives a `404 error` page.

**Note:** module is successfully enabled from admin

# Answer
The indentation of your hello.routing.yml file is wrong. It should be as the following one. (See user.routing.yml.)

```
user.pass:
  path: '/user/password'
  defaults:
    _form: '\Drupal\user\Form\UserPasswordForm'
    _title: 'Reset your password'
  requirements:
    _access: 'TRUE'
  options:
    _maintenance_access: TRUE

```

Indentation in YAML files is very important, since it changes the file content.

Notice that you can use `_access: 'TRUE'`, when the page doesn't require a specific permission. The `_maintenance_access: TRUE` line is not necessary. If you use it, users have access to your route even when the site is in maintenance mode; other requirements are still respected, so you could have something similar to the following.

```
user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

```

Before making any changes, uninstall the module, fix the file, and re-install the module.

As side note, you don't need the `use Drupal\Core\Routing\RouteMatchInterface;` line in your hello.module file, since you aren't using that PHP interface.
> 3 votes

# Answer
**Couple of things which is wrong in the above code**:

* help.routing.yml should be renamed to hello.routing.yml
* Controller folder should be under src folder. Structure should be hello/src/Controller/HelloController.php.

Hope that making these changes help you to render the page without 404 error.
> 1 votes

---
Tags: 8
---


title: How to create custom theme a view

text:
# Question
Title: How to create custom theme a view
I've defined a view with the CCK and Views modules. I have two ways for printing the result:

1. As node content
2. As fields content

If I choose node content, I need to choose the view mode, which by default allows to choose between teaser, and rss (among others). How do I create a new custom view mode?

If I choose fields content, I see the following data, under theme information.

* **Display output**: views-view.tpl.php, views-view--frontpage.tpl.php, views-view--default.tpl.php, views-view--default.tpl.php, views-view--page.tpl.php, views-view--frontpage--page.tpl.php
* **Style output**: views-view-unformatted.tpl.php, views-view-unformatted--frontpage.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--page.tpl.php, views-view-unformatted--frontpage--page.tpl.php
* **Row style output**: views-view-fields.tpl.php, views-view-fields--frontpage.tpl.php, views-view-fields--default.tpl.php, views-view-fields--default.tpl.php, views-view-fields--page.tpl.php, views-view-fields--frontpage--page.tpl.php

How do I create a custom theme for printing the result using the fields method?

**Edit1:** i create new view mode with Chapabu answer.(create a custom build mode you can use Entity view modes)

now i see this result in front page : Image Link

now, this print default content with default `html/css`.in act, i need `custom content` default for my theme. **Example** : i dont need to print date and author content! i need to print `image(Thumbs)`, `Summary` and `content type`. in `html/css` i need to list content in `<ul><li></li></ul>`Or Any Div or Span ... (custom `html/CSS`) How To Edit This `HTML/CSS`?

I Think Fields Method Better For My result. This Is TRUE? If YES, How To?

**EDIT2:** Example Of my Need Conetnt And CSS/HTML:

I need to design this block(in act example: article promoted front page Or last Article Or Last News ...) for show in vertical news ticker using jquery and css. this jquery plugin need to custom html/css:

```
 <h1>Latest News</h1>
<div class="newsTicker">
<ul>
<li><img class="Thumbs" src="" alt="">news item 1</li>
<li><img class="Thumbs" src="" alt="">news item 2</li>
<li><img class="Thumbs" src="" alt="">news item 3</li>
<li><img class="Thumbs" src="" alt="">news item 4</li>
<li><img class="Thumbs" src="" alt="">news item 5</li>
<li><img class="Thumbs" src="" alt="">news item 6</li>
<li><img class="Thumbs" src="" alt="">news item 7</li>
<li><img class="Thumbs" src="" alt="">news item 8</li>
</ul>
</div>

```

now, I need a custom content and html/css design views block for this.

# Answer
When you're not satisfied with the existing view modes you could create your own using either your own tiny plugin (see ready code) or use Display Suite. The new view mode will appear in Views UI for selecting.

I'd recommend however the true theming technique by using Views and fields. There you have more flexibility and control over the markup. You can do many things using Views UI (such as turning off the wrapper markup, linking a field to its content, overwriting some attributes, etc.) When you find out you cannot do something in Views UI this might be a reason for using a .tpl.php file at one of the output levels - in your case the style or row variants would be your friends)

It's recommendable that you watch some Views tutorials, such as NodeOne's Taming the Beast series or by Mustardseed Media (even if for Views 2 only) to get the idea how to tailor Views output to your needs.

Hope this helps.
> 0 votes

# Answer
There are a few ways to theme a view in drupal. AS you said before you can output the view as 'node content' or as 'fields'. If you select 'node content', drupal will get the parameters for this content type as you config them in the content type menu `(admin/structure/types/manage/{your-content-type}/display).` If you select 'fields' you have to add every field you want to be displayed in the view and config it's output in the fields section of the view. There you can select if you want labels, the widget or the markup for the field.

With this you can configure the HTML output, I don't know if you mean css when you ask about theming.

The template files are for advanced output and just clicking in the views UI you'll get options to configure almost everything.
> 0 votes

# Answer
You can use Entity view modes to create new view modes for your entities without writing any code.

> The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities. Custom entities are added to the entity registry via hook\_entity\_info\_alter() so they are available to any code that uses entity\_get\_info() to provide a list of view modes for an entity. This includes node and user reference fields, Views, etc.
> 0 votes

# Answer
Creating custom entity view modes or themeing the view is quiet an overkill for your intention.

To massage views' HTML output to your example, consider using the fences module to customize html tags for wrappers, labels and field content.

**In your case:**

1. Use the HTML list format, and show fields.
2. Add the image and text fields without labels.
3. For each field, under "STYLE SETTINGS", check "Customize field and label wrapper HTML", and select "- None -".

You'll get 90% of the structure you want, the rest is just tweaking.

**For more advanced customization:**

1. Exclude the 2 fields, and add a third field of type "Custom text".
2. In the custom text field, enter your more complex HTML structure, and use string replacement tokens to inject the field values.
> 0 votes

---
Tags: 7, views, blocks
---


# Question
Title: How to restrict user to chat with another user based on their payment and subscription?
I'm new to Drupal. I need to make a consulting website, where I need to restrict user from chatting. The user can chat only with the consultant they paid for. User can participate in forums as they are free of cost.

Any suggestions about how to implement this?

**Note**: for normal chat concept, I use DrupalChat.

# Answer
From the DrupalChat project page:

> ... provides optional integration with ... Flag Friend module.

And issue \# 936350 states:

> ... Would it be possible to show only friends from the Flag Friend module?

Since this issue has status closed(fixed), you should be able to use the Flag Friend module like so:

* After the payment was completed, grant the user some permission to be allowed to "flag" the consultant the user paid for.
* After such flagging is done, the user should be able to chat with such consultant.
> 0 votes

---
Tags: payment-gateways
---


# Question
Title: Composer download Drush 9 - But conflict errors
I just installed drush 7 and 8 in their own directory under /usr/bin as drush7, drush8 commands. Now I'm trying to do the same for drush9, but I'm getting a conflict error during the composer download of drush 9. How can I resolve this to only download the 9.x version?

The command I used was: **composer require drush/drush:9.\***

I got this idea of using all the drush versions from:

https://www.lullabot.com/articles/switching-drush-versions

# Answer
> 3 votes
When you request `composer require drush/drush:9.*`, you are telling Composer that you want the latest **stable** release of Drush on the 9.x branch. However, Composer considers dev, alpha, beta and even RC releases to be unstable. These releases can be downloaded in one of two two ways:

1. Create a composer.json file, manually add the release designation you want (e.g. 9.\*), set the `minimum stability` to dev or alpha, or some other applicable value, and then run `composer install` (or `composer update`, if you already have a composer.lock file).
2. Explicitly request the version you want -- e.g. `composer require drush/drush:9.0.0-alpha1`, or \`\`composer require drush/drush:dev-master\`.

# Answer
> 1 votes
What I did was just download the master branch:

**composer require drush/drush:dev-master**

The master branch contained the latest drush version which is 9 as of today. But I'm still unsure how you can pick 9.x. Or how do you list out which branches you can select from.

---
Tags: drush
---


# Question
Title: Where are functions being called from when errors are vague?
I have the following errors which show up randomly when browsing the site. It's hard to reproduce, but also hard to debug. I was able to get it in the error state and have it stay during a reload in order for me to debug it.

I tried going to the code in question which resides in **includes/theme.inc** But when going to that line 1525. It doesn't really tell me much. The error states that its missing a tpl file, but doesn't say which one as I'm assuming its due to the $template\_file variable being blank.

How can I trace where is this function being called in order to find the module that is the culprit of this error?

I don't have xdebug installed as I know that can be used to do the tracing. I also don't have experience with it neither as I've mainly solved most of my php issues just by doing a print\_r() 99% of the time and I'm able to find where the issue lies, but this time its different.

What methods are there to debug it and find the source of the problem?

# Answer
> 4 votes
The Devel module can be extremely helpful in cases like this. Once installed, go to the `admin/config/development/devel` path, and you will see an option for additional error handlers:

If you select the Krumo backtrace option(s), Devel will register itself as the PHP error handler, and it can then show error messages with the full backtrace!

---
Tags: theming, debugging
---


# Question
Title: How to output $variables without loading everything?
I'm trying to debug a drupal 7 site and print\_r() the $variables variable, but its HUGE and crashes certain pages when there is alot of data in it. Is there a way to only output the first level of the array without outputting everything inside of it?

# Answer
Devel is a great tool for debugging. It comes with `krumo()` function which works similar to `print_r()` but doesn't output everything, only up to certain depth (I think 3 or 4 levels).
> 1 votes

# Answer
I faced a similar issue and found a raw solution, not very elegant nor easily usable in all cases, but it might help you:

1. First use `print_r(array_keys($variables))`.
2. Look at the result to locate which keys match your needs.
3. Then for each one, say `$var_x`, use `print_r($variables[$var_x])`
4. And if it's too heavy again, go to #1 replacing `$variables` by `$variables[$var_x])`... and so on!
> 1 votes

---
Tags: 7, debugging
---


# Question
Title: How to use external JSON API to create/update node's fields?
I have a content type: `siteinfo`.

This content type has multiple fields: text, entity reference etc.

**I want to use an external API to automatically fill some fields of the created node.**

The API I want to use says that:

> API returns consistent and well-structured data in XML & JSON format. Returned data contains parsed fields that can easily be used by your application. This is a RESTful based API.

And this is the API's output:

```
{
    "status": 1,
    "api_query": "siteinfo",
    "whois_record": {
        "domain_name": "example.com",
        "query_time": "2016-05-05 14:01:12",
        "create_date": "1995-08-14",
        "update_date": "2015-08-14",
        "expiry_date": "2016-08-13",
        "domain_registrar": {
            "iana_id": 376,
            "registrar_name": "RESERVED-INTERNET ASSIGNED NUMBERS AUTHORITY",
            "whois_server": "whois.iana.org",
            "referral_url": "http://res-dom.iana.org"
        },
        "name_servers": [
            "a.iana-servers.net",
            "b.iana-servers.net"
        ],
    },
}

```

## How can I use this external API?

# Answer
If there's no complicated authentication/request method for the service (e.g. a simple HTTP GET for http://service.example.com/api/siteinfo/1), then a combination of Feeds, Feeds extensible parsers, & Libraries with the JMESPath library installed works great here.

The Feeds module has an HTTP fetcher that can be used in conjunction with the **JSON JMESPath parser** that allows you to enter JMESPath queries for each field you want parse and insert/update into a node (e.g. in the parser settings you'd could put "@" (root) as the **Context** & "whois\_record. domain\_name" if you wanted to map that object's property to a node field).

In this solution, Feeds is handling the import/update bookkeeping while you're tasked with figuring out the correct queries to parse the data. If you go this path, it's very helpful to study JMESPath syntax while using the Feeds Import Preview module to test your imports before execution.

If you need your URL to vary for each import, you can wrap a programmatic invocation of a Feeds import into a function and call it for each imported URL in a `drush eval` or some other arbitrary location in your environment. For example:

```
//$url = Is your imported feed.
//$my_feed = Your imported feed machine name
//(i.e. the MY_FEED_MACHINE_NAME in http://example.com/import/MY_FEED_MACHINE_NAME)
function MYMODULE_import_feed($url, $my_feed) {
  $feeds_source = feeds_source($my_feed);
  $feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);
  $feeds_config['source'] = $url;
  $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
  $feeds_source->save();
  $feeds_source->startImport();
}

//Example execution
function MYMODULE_cron() {
  $import_titles = array('title_1', 'title_2');
  foreach ($import_titles as $title) {
    MYMODULE_import_feed("http://service.example.com/api/siteinfo/$title",'MY_FEED_MACHINE_NAME');
  }
}

```
> 2 votes

# Answer
### The no coding, clean hands, solution:

Feeds + Feeds JSONPath Parser

### Coding, dirty hands, solution:

Using REST with Webservices you can Get and then Post/Patch. You would also need to comeup with a way to schedule your code so it runs every x amount of time (create a cron job); in contrast, Feeds already has that feature.
> 1 votes

---
Tags: 7, feeds
---


# Question
Title: Bootstrap progress bar missing style option
Drupal 8 using Bootstrap theme. I am trying to create a progress bar on my form. I have done it in a block with no problem but in the form it loses the "style" option and displays a blank progress bar.

I put in this:

```
    $form['pr_bar'] = [
        '#markup' => '<div class="progress">
          <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40"
          aria-valuemin="0" aria-valuemax="100" style="width:40%">
            40% Complete (success)
          </div>
        </div>',
    ];

```

and get a blank bar. When i inspect element:

```
<div class="progress">
    <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete (success)</span></div>
</div>

```

Why is the style option missing and is this causing the blank bar?

# Answer
> 1 votes
`#markup` filters the style option because of the xss filter.

Use an inline template instead:

```
$form['pr_bar'] = [
  '#type' => 'inline_template',
  '#template' => '
    <div class="progress">
      <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="{{ complete }}"
      aria-valuemin="0" aria-valuemax="100" style="width:{{ complete }}%">
        {{ complete }}% Complete (success)
      </div>
    </div>',
  '#context' => [
    'complete' => '40',
  ],
];

```

You can pass the percentage value as twig variable.

---
Tags: 8, theming
---


# Question
Title: How to send an email using Rules when a node's boolean field is changed?
I managed to setup email notification via the Rules module when the content is updated.

But I want to limit this only when the value changes in a specific field that is boolean "Yes", "No".

Update:
This is the part where i am stuck. I am not sure what to pick at Data selector, while at bottom (Field: Value) i found the field i need. I tried to save with "node" to try 2nd condition but also did not find an option: "Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different."

# Answer
Here are some details about how to make this work (using Rules):

* **Rules Event**: Before saving content.
* **Rules Condition (1st)**: "Entity has field", whereas you should specify these values:
    + "node" (saved content) for the "data selector" of entity.
    + the machine name of your boolean field (for field).
* **Rules Condition (2nd)**: Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different.

So part of the "clue" to make this rule work is the condition `Entity has field`. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

**Update** (to further clarify the new questions in the "update" part of your question, with the quoted text copied from the update in the question):

> I am not sure what to pick at Data selector, while at bottom (Field: Value) i found the field I need.

You should select ***node (saved content)***, because you want to check if a "node" has the field you're looking for.

> ... but also did not find an option: "Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different."

For this you add an additional Rules Condition which is a ***Data comparison***. And the actual data to be compared are:

* original value of the field, which you should be able to find/select by first using as data selector the `node-unchanged:...(unchanged content)`, followed by selecting the field name of your field from the additional list that is shown after you selected that `node-unchanged:...(unchanged content)`.
* updated value of the field, which you should be able to find/select by first using as data selector the `node:...(saved content)`, followed by selecting the field name of your field from the additional list that is shown after you selected that `node:...(saved content)`.
> 2 votes

---
Tags: 7, rules, emails
---


# Question
Title: How the get all the child menu's Node IDs?
I've a very simple task to do in Drupal 8, but I've hard time to find the proper way to do that.

I have a simple menu like this (all basic pages).

* Company
    + Organization
    + Values
    + Terms
* Services
* Team

And when we go to Company page, I want to display all three sub-pages content in there.

How do I get the sub page node ID from the current menu? In Drupal 7, I'd go with something like menu tree data, and parse the URL to get the node ID; I'm sure we can do something similar with Drupal 8, but I can't find a way.

# Answer
I think you're approach is just from the wrong end, the menu is just a list of links and not meant to control content.
What you want to do is:

* Make "Company" as a views \> page or a views blocks within etc.
* Make a taxonomy reference for the sub pages or make them separate entity or content type, in order to specify your sub pages in views.
* Create view\_mode like teaser to format their subpage display.
> 0 votes

---
Tags: 8
---


# Question
Title: How to display all links of the Answers module on a single page?
I using the Answers module, which provide the various set of views as shown in the image below. But it does not provide anything where we can provide these views as a link. **I mean I want all these four views in one line as a menu tabs on page**,

So, it should be like this:

* Main menu tab: `Q&A`
* When this Q&A tab is clicked, it should show all these 4 tabs with first tab as default:

> All Questions | Unanswered Questions | Search Questions | Search & Add Page

I am surprised this option is not available by default.

# Answer
> 1 votes
Have a look at the (new) demo site of the Answers module (disclosure: I'm a co-maintainer of it). Consider this demo site link as the equivalent of what you named "main menu Q&A". Visiting that link will show various menu options within the block with title ***Answers Menu***, i.e.:

* **Questions** (= a view):
    + **All**: of all existing questions (= default tab).
    + **Answered**: all questions which have a "best" (= accepted) answer (= sub-tab).
    + **Unanswered**: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).
* **Answers** (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
* **Rankings** (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
* **Ask Question**: to post a new question (the equivalent of `node/add/question`), which is only shown for authenticated users though.

These views also use the dataTables format, but you could easily replace that with any views display format you'd want. And because of the search box that comes with dataTables, there is no need for extra menu links to search within questions, answers or rankers.

These new/enhanced views were created starting from the 7.x-4.x-rc2 release of Answers, and will be included in the next release of it also (together with various other enhancements not yet visibile in the demo site). Which should address your "***I am surprised this option is not available by default***" also, no?

# Answer
> 1 votes
The Panels module allows you to create "pages" of blended content at an URL or URL with a context argument (like a node ID). For example an arbitrary node, 4 views, a custom text panel and a block. It's extremely flexible and fairly easy to learn. Once you've learned the basics you'll never build a site without it.

Panels module

# Answer
> 0 votes
After doing some try and error, I myself found the answer, but do not know this is the right way to do or not, but it is working.

1. `Search Question` and `Search & Add Page` does not have any menu link in the Menu option under the `Page setting` for their views, So, just provided `Menu tab` and provided the title, hence now it is showing the all four tabs in one line.
2. Main Menu tab: I just added the tab in the main menu as Q&A and provided the path `/questions` which is the path of first tab, hence when person clicks `Q&A`, it just lead to first page of `All Questions`.

Please correct if there is a better way to do this.

---
Tags: views, navigation, 7
---


# Question
Title: Why does 'Search Question' of the Answers module not show any results?
The "Search Questions" view page which is provided by the Answers module does not show any results. I am pasting the typed question as it is yet it just shows "No questions match".

What could be the issue?

**Edit**: I did get the solution just now, I was trying other related modules Best Answer and Answers Userpoints and after enabling them the Search feature started working. Probably some other module which is mutual between them gets enabled and start working, But I could not figured it out, as the Answers module list was showing all dependency modules enabled prior to all this. Any way it start working.

# Answer
Have a look at Comment #1 in issue 1619676, which states:

> One hypothesis: have you run cron?
>
> The way content gets indexed is during cron runs ... not immediately when new content is created.

It could well be that "in the meantime" cron was run, which would explain why "*... the Search feature started working...*" (as in your comment).

Disclosure; I'm a co-maintainer of the Answers module.
> 1 votes

---
Tags: views, 7
---


# Question
Title: Where can I download the Windows installer for Drush?
I cannot find the link where to download Drush windows installer. Can anyone tell me if there is or how to do?

I am using Drupal 8.1 and Windows 7.

# Answer
You need to install it using composer as specified here:

https://github.com/drush-ops/drush/blob/master/docs/install.md

After installation, make sure to run and use the drush command inside Git's shell only (the shell environment bundled with Git for Windows)
> 2 votes

# Answer
Use Acquia Dev Desktop. Drush is Pre Installed
> 0 votes

---
Tags: 8, drush
---


# Question
Title: Update to Search API 1.18 causes HTML to be displayed as plaintext
A security update to Search API (7.x-1.18) adds new sanitation as a security measure. Great! ..Except it now causes my custom field to be displayed as plaintext instead of HTML.

Here is the relevant code that was added to Search API:

```
/**
 * Sanitizes field values returned from the server.
 *
 * @param array $values
 *   The field values, as returned from the server. See
 *   SearchApiQueryInterface::execute() for documentation on the structure.
 *
 * @return array
 *   An associative array of field IDs mapped to their sanitized values (scalar
 *   or array-valued).
 */
function search_api_get_sanitized_field_values(array $values) {
  // Sanitize the field values returned from the server. Usually we use
  // check_plain(), but this can be overridden by setting the field value to
  // an array with "#value" and "#sanitize_callback" keys.
  foreach ($values as $field_id => $field_value) {
    if (is_array($field_value)
      && isset($field_value['#sanitize_callback'])
      && ($field_value['#sanitize_callback'] === FALSE || is_callable($field_value['#sanitize_callback']))
      && array_key_exists('#value', $field_value)
    ) {
      $sanitize_callback = $field_value['#sanitize_callback'];
      $field_value = $field_value['#value'];
    }
    else {
      $sanitize_callback = 'check_plain';
    }
    if ($sanitize_callback !== FALSE) {
      $field_value = search_api_sanitize_field_value($field_value, $sanitize_callback);
    }
    $values[$field_id] = $field_value;
  }
  return $values;
}

```

**Question**

Because it says

```
  // Sanitize the field values returned from the server. Usually we use
  // check_plain(), but this can be overridden by setting the field value to
  // an array with "#value" and "#sanitize_callback" keys.

```

I know I need to set the field value to an array with `#value` (my custom HTML) and `#sanitize_callback` keys, but *where* do I set this, and what do I use for `#sanitize_callback`?

**My Custom Code**

I'm using a callback to generate my field with custom HTML:

```
<?php

/**
 * @file
 * Contains SearchApiAlterAddViewedEntity.
 */

/**
 * Search API data alteration callback that adds an URL field for all items.
 */
class MySearchAlterAddUsercacheEn extends SearchApiAbstractAlterCallback {

  /**
   * Only support indexes containing entities.
   *
   * @see SearchApiAlterCallbackInterface::supportsIndex()
   */
  public function supportsIndex(SearchApiIndex $index) {
    return (bool) $index->getEntityType();
  }

  public function alterItems(array &$items) {
    // Prevent session information from being saved while indexing.
    drupal_save_session(FALSE);

    // Force the current user to anonymous to prevent access bypass in search
    // indexes.
    $original_user = $GLOBALS['user'];
    $GLOBALS['user'] = drupal_anonymous_user();

    foreach ($items as &$item) {
      // Since we can't really know what happens in entity_view() and render(),
      // we use try/catch. This will at least prevent some errors, even though
      // it's no protection against fatal errors and the like.
      try {
        $render = user_view($item, 'ensearch', 'en-US');
        $text = render($render);
        if (!$text) {
          $item->search_api_viewed_en = NULL;
          continue;
        }
        $item->search_api_viewed_en = $text;
      }
      catch (Exception $e) {
        $item->search_api_viewed_en = NULL;
      }
    }

    // Restore the user.
    $GLOBALS['user'] = $original_user;
    drupal_save_session(TRUE);
  }

  public function propertyInfo() {
    return array(
      'search_api_viewed_en' => array(
        'label' => t('Entity (en-US) HTML output'),
        'description' => t('The whole HTML content of the entity when viewed.'),
        'type' => 'text',
      ),
    );
  }

}

```

# Answer
> 1 votes
The fix is described in this d.o issue.

```
function MODULE_search_api_results_alter(array &$results, SearchApiQueryInterface $query) {
  if (!empty($results['results'])) {
    foreach ($results['results'] as $id => $result) {
      if (!empty($result['fields']['search_api_viewed'])) {
        $results['results'][$id]['fields']['search_api_viewed'] = array(
          '#value' => $result['fields']['search_api_viewed'],
          '#sanitize_callback' => FALSE,
        );
      }
    }
  }
}

```

# Answer
> 1 votes
`check_plain()` encodes special characters that has special meaning in HTML (such as \< and &) into plain text entities (i.e. \< and & respectively) that will make these be rendered literally (not interpreted as HTML) when that string that is then displayed as part of a page with HTML-markup. `filter_xss()` filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities.

In other words, filter\_xss() takes care of security, while not plain-texting HTML.

I propose you to patch the Search API function with 'filter\_xss' as a callback instead of 'check\_plain', create an issue on drupal.org and explan that case.

---
Tags: search, security
---


# Question
Title: Override a single JavaScript file from a module
In my theme's libraries.yml file, after the global-styling section, i'm trying to replace one JavaScript file from the core Toolbar module (it's addition of padding-top to body interferes with our theme, so just changing that to margin-top).

```
libraries-override:
  toolbar/toolbar:
    js:
      js/views/BodyVisualView.js: js/views/BodyVisualView.js

```

I repeatedly get the error:

> Drupal\Core\Asset\Exception\IncompleteLibraryDefinitionException: Incomplete library definition for definition 'libraries-override' in extension 'mythemename' in Drupal\Core\Asset\LibraryDiscoveryParser-\>buildByExtension() (line 93 of /vagrant/web/core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php).

# Answer
The answer is simply that the `libraries-override` definition must go in the .info.yml not .libraries.yml:

So in mythemename.info.yml:

```
libraries:
  - mythemename/global-styling
libraries-override:
  toolbar/toolbar:
    js:
      js/views/BodyVisualView.js: js/views/BodyVisualView.js

```

If placed logically there, alongside the libraries definition, it works perfectly.

Note that the second 'toolbar' is the library name from toolbar.libraries.yml, other library names in there include toolbar.menu, so if overriding a file from there it would be "toolbar/toolbar.menu:" instead of "toolbar/toolbar:".
> 23 votes

---
Tags: 8
---


# Question
Title: Restricting view to content associated with user profile
On my site some users have the permission to see others' profile.

I'm looking to show a view in a block containing a *food* content type. It will be displayed on the profile page of the users (user/\*). The block will contain content associated with that user (somehow I need to tell that when I am creating the content).

For example: Content "rice" belongs to user1; content "potatoes" belong to user2.

When I enter the user1's profile I see "rice"; when I enter user2 profile I see "potatos". It's the same block with the information changing according to the user profile I am seeing.

# Answer
> 2 votes
What you're wanting is a contextual filter for your view. Create a node view with a block display and in the **Advanced** section under **Contextual Filter** click the **Add** button.

From there you can add *Content: Author uid* which will tell the view to filter by author UID. On the popup modal, under the **WHEN THE FILTER IS NOT....** fieldset, select *Provide default value* with **Type** of *Raw value from URL* and **Path** component of *2*. This essentially tells the view to pull the UID from Drupal's internal path (i.e. the *XXX* in **/user/XXX** when viewing a user page).

After saving the view, you should be able to place it your region to display against user profile pages.

---
Tags: users, views
---


# Question
Title: How reliable is hook_post_action module?
I am using this module under Drupal 7 to execute some code after nodes of a particular content type get updated. My question, is this module reliable? Would the post save event be called every time my target nodes get updated?

This is the module's page: https://www.drupal.org/project/hook\_post\_action

# Answer
The module register a shutdown function in `hook_entiyt_delete()`, `hook_entity_insert()`, and `hook_entity_update()`.

```
/**
 * @param $entity
 * @param $type
 */
function hook_post_action_entity_insert($entity, $type) {
  drupal_register_shutdown_function('_hook_post_action_post_save', $entity, $type, 'insert');
}

```

As such, the hooks invoked from that shutdown function are always invoked, except in the case the shutdown function is not called, which as the documentation for `register_shutdown()` says, it can happen if the process is killed with a SIGTERM or SIGKILL signal. Since PHP doesn't have a function to removed a shutdown function, I would say the module is reliable.

As side note, `hook_node_postsave()` and `hook_entity_postsave()` are always invoked, whenever the entity is created, updated, or deleted.

```
/**
 * @param $entity
 * @param $type
 * @param $op
 */
function _hook_post_action_post_save($entity, $type, $op) {
  $entity_is_saved = FALSE;
  $new_entity = NULL;

  if ($op == 'insert' || $op == 'update') {
    $entity_is_saved = TRUE;
  }
  if ($op == 'delete') {
    list($id) = entity_extract_ids($type, $entity);
    $new_entity = entity_load($type, array($id));
    if (!$new_entity) {
      $entity_is_saved = TRUE;
    }
  }
  if ($entity_is_saved) {
    module_invoke_all('entity_post' . $op, $entity, $type);
    module_invoke_all('entity_postsave', $entity, $type, $op);

    if ($type == 'node') {
      module_invoke_all('node_post' . $op, $entity);
      module_invoke_all('node_postsave', $entity, $op);
    }
  }
}

```
> 5 votes

---
Tags: 7, hooks
---


# Question
Title: Views Exposed form in block : how to add a ajax results counter?
I implemented a view as following :

* a page display with an extensive exposed filters form (Better exposed filters), ajax enabled, let's call it the landing page
* a clone of it, in a second page display with exactly the same fields, but few exposed filters instead (quick search form)
* that clone has exactly the same path, **Exposed form in block is set to yes**

I display the clone created block (quick search form) on homepage : submitting its form redirects to landing page with correct results and the complete exposed filters. This is fine.

## Question :

I need to display **a results count** next to the exposed form block, **which refreshes each time** you change a exposed filter value in the form.

The **Global: Result summary** in header or footer doesn't work because footer and header aren't displayed together with the exposed block, they only come with the full view display.

How could solve that, either with UI or programmatically ? Below some ideas to begin, there might be a good and straight way :

* force the results count header to be displayed next to exposed block ?
* add a markup to the form with ajax results ?
* create another block ?

## EDIT

I tried several approaches based on Shreya answer below, but the blocking point is always the same, I need to execute the view to get result count, but as soon as I do, it returns an *Allowed memory size exhausted*.

in template.php :

```
function shoot_preprocess_views_exposed_form(&$vars){

  if($vars['form']['#id'] == 'views-exposed-form-customer-products-list-search-block') {
    $view = views_get_view('MY_VIEW');
    $view->set_display('MY_DISPLAY');
    $view->execute();
    $count = count( $view->result );
    $vars['count'] = $count;
  }
}

```

in views-exposed-form--MY\_VIEW.tpl.php

```
print 'There are:'. $count. 'results';

```

And other tries with `views_get_current_view()` or `views_get_view_result()` in the tpl, also tried within form alter :

```
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-my-view-my-display') {
    $view = views_get_view('MY_VIEW');
    $view->set_display('MY_DISPLAY');
    $view->get_total_rows = true;
    $view->pre_execute();
    $view->preview('MY_DISPLAY');
    $view->execute();
    $content = $view->total_rows;
  }
  $form['submit']['#value'] = 'Voir les'. $content.' résultats';
}

```

Any clue to explain why I can't execute the view, or how to return count in that context ?

# Answer
1. Create a folder structure as sites/all/themes/example\_theme/templates/views

2.Create a file named views-exposed-form.vars where you use MYTHEME\_preprocess\_views\_exposed\_form. Code snippet below:

```
function example_theme_preprocess_views_exposed_form(&$vars){
  if($vars['form']['#id'] == 'views-exposed-form-exaample-page') {
    $views_rows = views_get_view_result('my_custom_view', 'page');
$count_rows = count($views_rows);
   $vars['count'] = $count_rows;
  }

}

```
3. Then you can override the exposed filter tpl. To override the exposed form template for a particular view, you need to create a template in the following name pattern,

**views-exposed-form--view\_name.tpl.php**

and print the $count variable wherever you want to place the count. Once you add the template clear the cache.
> 1 votes

# Answer
You could try a front-end approach. In the views header you can show the total results (Global: Result Summary) in a hidden div and, using js, take the value from there and print it wherever you want.

> Edit: I misuderstood your implemmentation. You could try using a block with exactly the same filters (hidden with css) you need, showing nothing but a header. You can adjust it to work with ajax, so the results will be refreshed and use js to change the filters with those changed in the exposed form in the block.
> 0 votes

---
Tags: ajax, views, blocks
---


# Question
Title: How to hide set up database step in a installation profile?
In a installation profile, how do I fill values for *Set up database* step programmatically and hide it so user doesn't need to fill the form?

How to do the above action for the *Select language* step?

# Answer
> 4 votes
You wanted an example -- which is basically showing you how to do it. From the docs I supplied and the help others that gave you cookie crumbs provided should have lead you towards a solution, Other than saying "show me" all the code.

A working profile example is in this GIST, you make a `shortprofile` directory in your /profiles directory and select "Short Profile" from the Installation screen. This is the "long way" to do this, there is a shorter way in-theory ... see my code comments.

**Be sure to change the $databases\['default'\]\['default'\] in line 47 of .profile to the existing database credentials that will work in your environment. Look for my comments in the code to change the db credentials and db password (line 125 of .profile).**

# Answer
> 2 votes
Fair warning I haven' done this before (but I have made install profiles and used them via Drush Make). So I was interested in how you might try to do this ...

I found this documentation page, How To Write a Drupal 7 Installation Profile

I assume you are using the 'Miminal' or 'Standard' defaults in your profile to save you some headache, or else you'd know the answer to your own question in building a complete profile from scratch ... I think you need to do 2 things:

(1) If you're using the minimal or standard defaults you can use hook\_install\_tasks\_alter() to change the visibility of the database Step to hidden. If your defining your own install tasks via hook\_install\_tasks() in yourprofile.profile

(2) You need to provide the database parameters. You can do that probably most straight-forwardly via hook\_form\_alter() as described in the documentation page linked above. You may also be able to muck with the values in $install\_state for hook\_install\_tasks as described in install\_state\_defaults()

I suggest you read up on all these hook functions and the documentation page above. good luck.

# Answer
> 2 votes
For me the accepted answer didn't work. It would just fill the form with default values but the user would still need to click to "save configuration" button to go forward. This is not what I would call a "skip step" if the user still has to press a button.

But basing on the solution I could find something that worked for me. First alter the step in question in your\_profile\_install\_tasks\_alter

```
your_profile_install_tasks_alter(&$tasks, $install_state) {
  $tasks['install_settings_form']['display'] = FALSE;
  $tasks['install_settings_form']['function'] = 'your_profile_install_settings_defaults';
  $tasks['install_settings_form']['type'] = 'normal';
}

```

Setting the type to form gave me problems as I was trying to call drupal\_form\_submit (would complain function is undefined) and overcomplicating my life

Now just copy paste the code from the submit function from core:

```
function your_profile_install_settings_defaults(&$install_state) {

  $database = array(
    'database' => 'yourparams',
    'username' => 'yourparams',
    'password' => 'yourparams',
    'prefix' => '',
    'host' => 'localhost',
    'port' => '',
    'driver' => 'mysql'
  );

  // Update global settings array and save.
  $settings['databases'] = array(
    'value' => array('default' => array('default' => $database)),
    'required' => TRUE,
  );
  $settings['drupal_hash_salt'] = array(
    'value' => drupal_hash_base64(drupal_random_bytes(55)),
    'required' => TRUE,
  );
  drupal_rewrite_settings($settings);
  // Indicate that the settings file has been verified, and check the database
  // for the last completed task, now that we have a valid connection. This
  // last step is important since we want to trigger an error if the new
  // database already has Drupal installed.
  $install_state['settings_verified'] = TRUE;
  $install_state['completed_task'] = install_verify_completed_task();
  return NULL;
}

```

That worked for me.

# Answer
> 1 votes
Database credentials are set in settings.php. So you'd provide a settings.php with your distribution, or you'd write out the db array to the settings.php at some point during installation.

You could do this in an installation profile, with `hook_install_tasks_alter()`, by changing `install_settings_form`.

Same caveats as tenken... I haven't done this.

---
Tags: 7, distributions
---


# Question
Title: QR Barcode automatic creation from Nodes new or previously created
I wish to create automatically created barcodes from newly create Node content and also Node content already created in the Drupal V7.3x system. Further to my previous posting Barcode Creation I can allow a user to create a QR barcode from a text field entered on a Node Form which successfully shows the QR on the Node display page; but this is no longer what I want, I require the QR code to create on the fly to create the QR code which will ultimately be the URL of that Node which is being shown so that the user then can scan it and save for later ie on a mobile device.
I have tried with Rules, but to date cannot get the Rule to write, save or show any QR code.

If it is a PHP script code, then what would it be to create onto the Node page the user would see.

I want to do it via Rules is possible but the barcode field wasn't showing in Rules. Any advice on a correct procedure or a Rules structure is most welcome.

PS:

I have found this type of PHP on https://www.drupal.org/node/1364118, and I wonder if this is the direction I need to go? to solve it:

```
    <?php
if (!isset($commerce_product->field_barcode['und'][0]['value'])) {
$commerce_product->field_barcode['und'] = array(0 => array ('value' => $commerce_product->sku));
}
else {
if ($commerce_product->field_barcode['und'][0]['value'] == '') {
$commerce_product->field_barcode['und'][0]['value'] = $commerce_product->sku;
}
}
commerce_product_save($commerce_product);
?>

```

# Answer
Since my original posting, a new module appeared. So I ultimately chose this module: drupal.org/project/page\_url\_qr\_code\_block does the job spot on and creates Node QR Codes on the fly via a Block. There maybe other ways, but for now, this is it. Thanks all.
> 1 votes

# Answer
The Ugly way: print qr-related to node on node template in your theme.

Less restrictive way: Create extra field in a module. hook\_field\_extra\_fields Google offers good examples with decent snippets with that hook search.
> 0 votes

# Answer
Below is a possible explanation/solution to this part of your question:

> I want to do it via Rules is possible but the barcode field wasn't showing in Rules.

This is a typical "issue" (not problem or bug) with the Rules module.

Make sure to add a Rules condition `Entity has field` (related to your barcode field) in your Rules condition). And make sure to add that `Entity has field` condition BEFORE other condition(s) you may already have.

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

Refer to my answer to "How to specify a Rules condition related to select list values?" for an actual Rules example (in Rules export format) that includes such 'entity has field' condition.

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.
> 0 votes

---
Tags: 7, nodes, rules
---


# Question
Title: How to download a file from private file system
I need a function in my module for users to download a file from a private filesystem.

```
$file : "private://sample.csv"

```

Which function should be used, `file_download()`, or `file_transfer()`?

```
function file_download_page() {
  $file = "private://sample.csv";
  //code for downloading $file
}

```

Please provide sample code.

# Answer
You just need to call file\_create\_url().

It will return an URL that will go through Drupal which will then check the appropriate permiss (if you need custom checks, you need to implement hook\_file\_download)
> 6 votes

# Answer
I use hook\_file\_download\_access:

```
/**
 * Implement hook_file_download_access().
 */
function YOURMODULENAME_file_download_access($file_item, $entity_type, $entity) {
  global $user;
  return (in_array('hr', $user->roles) || in_array('administrator', $user->roles)) ? TRUE : FALSE;
}

```
> 1 votes

# Answer
Using DownloadFile you can download the file. I am using this module
> 0 votes

---
Tags: 7
---


# Question
Title: Show and hide form element based on values of other form elements
`$form['bookpage']` should be hidden at first. Then should be shown based on user selected value in `$form['student']`.

But somehow, before user selects anything, upon loading the option list, it already triggers the `$form['student']`'s ajax function and shows the `$form['bookpage']`.

Why is this so?

P.S. `_lms_user_get_students` will return following array:

> array('0'=\>'----', 'all'=\>'All', '2456'=\>'Student A', '2462'=\>'Student B')

```
 $form['student'] = array(
        '#type' => 'select',
        '#title' => t('Student'),
        '#options' => (!isset($form_state['values']['book']) || $form_state['values']['book']==NULL)?array('0'=>'----'):_lms_user_get_students($form_state['values']['class']),
        '#prefix' => "<div id='student_div'>",
        '#suffix' => "</div>",
        '#id' => 'select-student',
        '#ajax' => array(
            'callback' => 'ajax_student_select_callback',
            'event' => 'change',
            'wrapper' => 'statistic_table_div',
            'method' => 'replace',
            'effect' => 'fade'
       ),
   );

  $form['bookpage_toggle'] = array(
        '#type' => 'hidden',
        '#value' => 'off'
  );
$form['bookpage'] = array(
            '#type' => 'select',
            '#title' => t('Page'),
            '#options' => (!isset($form_state['values']['book']) || $form_state['values']['book']==NULL)?array('0'=>'----'):_lms_user_get_bookpages($form_state['values']['book']),
            '#prefix' => "<div id='bookpage_div'>",
            '#suffix' => "</div>",
            //'#disabled' => TRUE,

            '#states' => array(
                'visible' => array(
                    ':input[name="bookpage_toggle"]' => array('value' => 'on'),
                ),
                'invisible' => array(
                    ':input[name="bookpage_toggle"]' => array('value' => 'off'),
                ),
            )
       );

    function ajax_student_select_callback($form, &$form_state) {

        //show page drop
        if($form['student']['#value'] == 'all') $form['bookpage_toggle']['#value'] = "on";
}

```

# Answer
> 1 votes
Why the in-between form element? You can use Drupal's Form API #states property to check for a value in a select as well. Just check the `student` form element and it's value `all`.

```
$form['bookpage'] = array(
  ...

  '#states' => array(
    'visible' => array(
      ':input[name="student"]' => array('value' => 'all'),
      // Use multiple lines here for an AND condition. eg:
      // ':input[name="other-field"]' => array('value' => 'all'),
    ),
  )
);

```

This way you can remove the AJAX callback, and the `bookpage_toggle` element.

If you want to support multiple conditions, you can wrap the jQuery selectors in another array to function as an OR:

```
$form['bookpage'] = array(
  ...

  '#states' => array(
    'visible' => array(
      array(':input[name="student"]' => array('value' => 'all')),
      array(':input[name="student"]' => array('value' => 'other value')),
    ),
  )
);

```

Finally if you want exclusive OR (XOR) you can do it like this to toggle on one of the elements, but never both of them:

```
$form['bookpage'] = array(
  ...

  '#states' => array(
    'visible' => array(
      'xor',
      array(':input[name="student"]' => array('value' => 'all')),
      array(':input[name="student"]' => array('value' => 'other value')),
    ),
  )
);

```

See this comment for AND, OR and XOR and a combination of those.

---
Tags: javascript
---


title: Showing form data in a block

text:
# Question
Title: Showing form data in a block
I have a multi step custom made form in Drupal 8.2.x.

Some of the user input from the form needs to be shown on a separate block.

The following code worked fine for users that are logged in:

```
$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

```

But it doesn't work for anonymous users on my site.

Is there a tempstore for anonymous users that works site wide that I just haven't discovered yet?

# Answer
you should use session manager for storing current sessions for anonymous users

private\_tempstore gives us a temporary store that is private to the current user

refer to this link asked some days ago session storage for anonymous users
> 2 votes

---
Tags: forms, 8, blocks
---


# Question
Title: How to execute some js code after click on exposed filter AJAX enabled submit?
I have tried to update the input value of an exposed filter field before submit of the exposed filter through Js.

What I have tried

```
$('#edit-submit-phrases').on('click', function() {
  alert('check');
});

```

No alert message.

I also tried:

```
jQuery('#edit-submit-phrases').mousedown()

```

# Answer
> 1 votes
You can use the ajaxStart() function, to execute something before Ajax request begins:

```
 Drupal.behaviors.<themename/modulename> = {
  attach: function (context, settings) {
    $('#edit-submit-phrases').on('click', function() {
      $( document ).ajaxStart(function() {
        alert('check');
      });
    });
  }
};

```

---
Tags: javascript, ajax, views
---


# Question
Title: how to use hook_views_query_alter() to modify where condition?
I'm trying to modify the where condition of a views query. till now I was successful with altering **"order by"**, but I have no idea how to alter the **where condition**. I want to check the search\_term and if it was in uppercase, transform it to lowercase so the query can find it. also there are some special characters in my language (persian) that I need to replace them before the query runs. anyone can help me where to start or what hooks or views\_handlers to use?

```
<?php
/**
 * Implementation of hook_views_query_alter
 * @param type $view
 * @param type $query
 */
function nashreneydev_views_query_alter(&$view, &$query) {
  //krumo($query);
  //krumo($view);
  if ($view->name == 'custom_search') {
    $search_term = $view->exposed_raw_input['combine'];

    **//$query->where[0]['conditions'][0]['field']= "?????";**
    $view->query->orderby[1]['field'] = "CASE node_type WHEN 'product_display' THEN 1 ELSE 2 END";
    $view->query->orderby[1]['direction'] = "ASC";
    $view->query->orderby[0]['field'] = "CASE node_title WHEN '".$search_term."' THEN 1 ELSE 2 END";
    $view->query->orderby[0]['direction'] = "ASC";
    //krumo($view->query->orderby);
  }
}
?>

```

the devel result for where condition is as follow right now. :views\_combine is equal to %s%.

> CONCAT\_WS(' ', node.title, ' ', field\_data\_body.body\_value, ' ', field\_data\_field\_author.field\_author\_target\_id, ' ', field\_data\_field\_translator.field\_translator\_target\_id, ' ', field\_data\_field\_book\_tags.field\_book\_tags\_tid) LIKE :views\_combine

# Answer
> 9 votes
You can access the content of a where condition modifying its value:

```
$query->where[0]['conditions'][0]['value'] = 'something...';

```

Pretty similar what you did with orderby. Also you can add custom where conditions (https://api.drupal.org/api/views/plugins%21views\_plugin\_query\_default.inc/function/views\_plugin\_query\_default%3A%3Aadd\_where/7 and https://api.drupal.org/api/views/plugins%21views\_plugin\_query\_default.inc/function/views\_plugin\_query\_default%3A%3Aadd\_where\_expression/7)

# Answer
> 14 votes
To add a new where clause you can use, add\_where

For example :

```
$query->add_where(1,'taxonomy_term_data_node.tid', $value, 'NOT IN');

```

# Answer
> 2 votes
```
function mymodule_views_query_alter(&$view, &$query) {
  // Term id's to unset from result set.
  $tids = array(346,355,359);
  if ($view->name == 'yourviewname') {

    $query->add_where(1,'taxonomy_term_data_node.tid', $tids, 'NOT IN');
    $query->orderby[0]['field'] = "CASE WHEN taxonomy_term_data_taxonomy_term_hierarchy.weight IS NULL THEN taxonomy_term_data_node.weight ELSE taxonomy_term_data_taxonomy_term_hierarchy.weight END";
    $query->orderby[0]['direction'] = "ASC";
    $query->orderby[1]['field'] = "taxonomy_term_data_node.weight";
    $query->orderby[1]['direction'] = "ASC";
  }
}

```

# Answer
> 0 votes
Try this,

```
 $location_value = strtolower($string);
 $query->where[1]['conditions'][0] = array('field'=>"node.title","value"=>'%'.$location_value.'%',"operator"=>"LIKE");

```

# Answer
> 0 votes
You can use just like

```
$query->add_where(1,'node.nid',$value,'=');

```

---
Tags: 7, views
---


# Question
Title: How to get last insert ID of drupal_write_record
I need to get the last inserted id in drupal 7. I am using

```
drupal_write_record('user_log', $log)

```

How we can get the last\_instered\_id?

# Answer
Assuming your `{user_log}` table has a PRIMARY KEY with it, or something else serial, then it should be set in in the array you passed to it. In your case, it would be something like

```
$last_log_id = $log['log_id'];

```
> 4 votes

# Answer
If you are not dependent on drupal\_write\_record you can use *db\_insert* and/or *db\_update* instead. The execute() method of the query objects returns the current id.
> 0 votes

---
Tags: database
---


title: Can I use a style.php?

text:
# Question
Title: Can I use a style.php?
I was wondering if I can change the style sheet of a theme from style.css to style.php and Drupal will use it? I tried it and it didn't work. I did, of course, change the file name in template.php as well. Is there anything else I need to consider?

# Answer
> 2 votes
Yes you can but you shouldn't.

When adding a stylesheet, Drupal does not tamper the file names. So regardless of the way you add it, your PHP file or whatever file name you use will be added to the `import` clauses or to the `link` tag.

However, note that Drupal can combine those CSS files, and it uses `file_get_contents()` function to get the file contents. In that case, Drupal will get the source code of your PHP file, making this approach fail.

If you want to add dynamic CSS, you can go for some workarounds though.

* Add all possible styles to one stylesheet under different classes, and only change the class name of the HTML that you want to change styles of.
* Have a predefined set of stylesheets, and only add the ad-hoc in a preprocess function or something.
* Add the styles as inline CSS.

Other than that, the core Color module has some similar approaches that you might find useful.

# Answer
> 0 votes
If you want to use variables for the colors you can, for example:

* Put the colors in a style attribute (not in the stylesheet) so you can change it when you want
* Define different colors for different classes and change the
classes of the dom elements for which you want to change the color.
* Programattically edit the css file content with something like:

$file = fopen($destination, "w+"); fputs($file, $data); fclose($file);

(I wouldn't suggest this if It's something that must be done periodically).

Sure there are other ways to accomplish what you want to do without calling a php file as an stylesheet (which, for what I know, is not feasible).

# Answer
> 0 votes
I did create a dynamic stylesheet once, as a test, by defining a menu callback at `/some/path/stylesheet.css` and returning CSS code. However it's really not a good idea because the stylesheet must be generated (or if you make a bit smarter: retrieved from cache) every time by a fully bootstrapped Drupal, which is much slower than letting the web server return the contents of a plain text file.

If you really need a dynamically generated CSS file, I would generate it when the settings change (probably triggered by a form submit), write the CSS file to the public files directory, and include the CSS file using the `#attached` property on a render array or drupal\_add\_css. If I'm not mistaken, this approach is more or less what color.module does too.

---
Tags: theming
---


# Question
Title: How to set the default "Show as expanded" to true in a custom menu item
I am creating a series of menus in a custom module. This site also has a custom theme. Is there a way in the theme, or in the module, to set a menus "Show as expanded" to true. This way, if I move my site, uninstall, or whatever, it comes back the way it should right out of the box.

# Answer
I couldn't find it anywhere on the Drupal documentation, but adding

```
expanded: TRUE

```

in the module.links.menu.yml file works.
> 2 votes

# Answer
According to Drupal API for hook\_menu:

> "**expanded**": Optional. If set to TRUE, and if a menu link is provided for this menu item (as a result of other properties), then the menu link is always expanded, equivalent to its 'always expanded' checkbox being set in the UI.

So while writing your custom hook simply add `expanded` option.

```
$items['examples/page_example'] = array(
    'title' => 'Page Example',
    'page callback' => 'page_example_description',
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

```
> -1 votes

---
Tags: theming, 8
---


title: Products with Vehicle Fit Guide

text:
# Question
Title: Products with Vehicle Fit Guide
I'm in the process of developing a website for vehicle cargo boxes and adventurous vehicle accessories, and the client has requested a fit guide.

What I need is a jumping off point: Do I build a taxonomy list of vehicle makes/models/year first and then ask vendors such as Yakima and Thule for their products? Do I ask the vendors first for their products and incorporate the vehicle list later?

I'm ultimately looking to host all vendors products within the site itself, and not have any iFrame solutions or link to vendor cart solutions.

I've searched for days now and have found multiple pre-built databases for vehicle's but am still wondering where to start...

# Answer
> 1 votes
Start wherever it makes sense to you. Your project sounds iffy if your not hired directly by any of these entities to promote their products.

I'd recommend a content type or entity as Accessory and then taxonomy terms for Make Model and Years of cars which will facilitate searching.

Start with that site structure, if it doesnt work for you then change it later.

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


title: How to make blob file downloadable?

text:
# Question
Title: How to make blob file downloadable?
I have created a Module to make blob file available for Download in Drupal 7 .

Below my code for .module file

```
<?php

function blobfile_block_info() {
  $blocks = array();
  $blocks['blobfile_block'] = array(
    'info' => t('Blob Files Download'),
  );

  return $blocks;
}

function blobfile_block_view($delta) {

      $query = db_select('health_policy_document_upload_dtl', h)->fields('h');
      $result = $query->execute();

      $content ='';
      while($record = $result->fetchAssoc()) {

          $filename = $record['Document_Name'];
          $file     = $record['Document'];
          $type     = $record['Document_Type'];
          $size     = filesize($file);

          header("Content-length: $size");
          header("Content-type: $type");
          header("Content-Disposition: attachment; filename=$filename");

          $content .= "<a href='#'>".$filename."</a>";
          $content .= "<br>";
      }

    return array(
      'subject' => t('Bids'),
      'content' => $content
    );

}

```

Please guide me where I went wrong.

# Answer
I'm assuming you have already come up with a solution to upload the files and put them in the database, and that you have a good reason not to use Drupal's built-in file handling (I question that second assumption particularly given the reference to health policy but I'll grant it).

The block you created needs to just provide the list of links, but you should not set the headers there, just generate the links. The link should probably be in the form of something like: /custom\_files/\[filename\] (or something clearer based on your complete context.

First you need a `hook_menu()` to define the menu router to get your files. Something like:

```
function mymodule_menu() {
  $items['custom_files/%mymodule_filename'] = array(
    'page callback' => 'mymodule_filedownload',
    'page arguments' => array(1),
    'delivery callback' => 'mymodule_file_delivery',
  );
}

```

*You should also add some permissions handling here, the documentation on hook\_menu() explains how that works. Also read the section on deliver callbacks because those also have security implications I'm glossing over.*

Next you need the page callback function to actually send the file:

```
function mymodule_filedownload($mymodule_filename) {
   // Validate permissions
...
   // Validate filename
...
   // Load file object from database
   $query = db_select('health_policy_document_upload_dtl', h)->fields('h')->condition('filename', $mymodule_filename,'=');
  $result = $query->execute();

   // Prep an array to hand data off to the delivery callback. It might just be the results, but often you want to tweak details...
...
  return $file_data_array;

}

function mymodule_file_deliver($file_data) {
   // Check $file_data to see if this is a valid file or an error of some kind.
...
  // Process and errors found and send proper error response.
...

  // Send file
  drupal_add_http_header("Content-length: ".$file_data['size']);
  drupal_add_http_header("Content-type: " .$file_data['type']);
  drupal_add_http_header("Content-Disposition: attachment; filename=".$file_data['filename']);

   print($file_data['data']);

   drupal_page_footer();
}

```

Obviously lots of details are glossed over here. In addition to hook\_menu()'s documentation you likely will also want to read `drupal_deliver_html_page()`. Note the use of `drupal_add_http_header()` instead of PHP's `header()`, for most basic tasks Drupal has internal functions that provide some clean up and standardization to avoid basic mistakes and conflicts with other module; you should use them whenever possible.
> 0 votes

---
Tags: 7, files
---


# Question
Title: What are efficient solutions to prevent a huge amount of panes in a Panel?
Using Panels for some years I still have one question that I struggle with.

I have set up a Panel with a special layout, with a filter on a specific bundle type.

I have more than 10 views content panes that I want to show in that panel, but each one on its own entity.

So the obvious solution is to add Pane Visibility Rules to each of the panes, which filter by URL of the entity.

I think this is neither efficient nor userfriendly. It's hard to manage for more than 10 panes and have a clear insight about all the visibility rules of each pane.

I thought about using ViewField module for the entities showing a specific view, and still allow them to use the Panel. As far as I can see, that does not allow for the use of the Panel pane context tokens.

Suggestions are very welcome.

# Answer
> 0 votes
Panels have "varients" with selection rules. You can set up which variant is triggered by which value in the url variable that you named in the path setup. This way, you can have your pane layouts not get so cluttered with options that are only visible a fraction of the time, but still have the same capability. Either way, the check for display is a growth order of O(1) so not that much of an efficiency concern. The views would be a better place to increase efficiency, set a limit and a link to the full list in a footer.

---
Tags: views, panels, tokens
---


title: How to add link (via php) to xmlsitemap

text:
# Question
Title: How to add link (via php) to xmlsitemap
I have a site where some pages are "virtual".

The path is :

internal\_node/XYZ

where * internal\_node/% is defined in a hook\_menu() * XYZ is a number

my "internal\_node" callback call an external service using XYZ like argument, get soma data and display this data to the user. All works without problem. And all is legal.

Now I want to add all "interal\_node" links to my google's sitemap.

I have installed xmlsitemap, but this module create a google sitemap for only all internal drupal node and my "internal\_node" are not a drupal node.

So, how can I add link to xmlsitemap ?

Thanks.

# Answer
you could put those links in a menu and have that menu included to your xmlsitemap.
> 0 votes

# Answer
There are a few ways you can add links to the xmlsitemap.
> 0 votes

---
Tags: 7, xml-sitemap
---


title: How do I use "GROUP BY"?

text:
# Question
Title: How do I use "GROUP BY"?
How do I use `GROUP BY` to display the result by group (email)? this is my file .php

```
<?php
/**
 * Created by PhpStorm.
 */
namespace Drupal\gestion_contact\Controller;
use Drupal\Core\Controller\ControllerBase;
class GestionContactController extends ControllerBase
{
    public function admin() {

        $result = db_query("SELECT * FROM {contact}");

            $node = $result->fetchAll();

        return array(
            '#theme' => 'gestion_contact',
            '#nodes'=> $node,

        );
    }
    public function delete($id)
    {

        db_delete('contact')
            ->condition('id_contact', $id)
            ->execute();
        drupal_set_message(t('Your form has been deleted'));

        $result = db_query("SELECT * FROM {contact}");

        $node = $result->fetchAll();
        return array(
            '#theme' => 'gestion_contact',
            '#nodes' => $node,

        );
    }
    public function afficher()
    {

        $result = db_query("SELECT * FROM {contact} WHERE vu = :vu",
            array(':vu' => 'false'));
        $node = $result->fetchAll();
        return array(
            '#theme' => 'nouveaux_contact',
            '#nodes' => $node,
        );
    }
}

```

# Answer
Follow an example:

```
$result = db_query('SELECT tid, count(tid) AS count FROM {taxonomy_term_field_data} WHERE vid <> :vid GROUP BY tid', array(':vid' => 'tags'));

```

But, from docs...

> **Deprecated**
>
> as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get a database connection injected into your service from the container and call query() on it. For example, $injected\_database-\>query($query, $args, $options);

More info in db\_query.

**Edit 1:**

Drupal set by default sql\_mode with 'only\_full\_group\_by', in your case when you use `SELECT *`, an database exception is throw, look in your log, you will see something like this:

> Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'database.table.field' which is not functionally dependent on columns in GROUP BY clause.

So to correct this you must aggregate all fields in your SELECT list. If you only need e-mail list something like this can solve:

```
db_query('SELECT email FROM {contact} GROUP BY email');

```
> 3 votes

---
Tags: database, 8
---


# Question
Title: How to show a user's friends with only the Views and Flag module?
Is it possible to show user's friends on a user's page (located `user/%/friends`) with Views by using only Flag module? So without the Flag Friend module or any other modules.

# Answer
# Step 1:

Use the Flag module to create a flag labeled "Friend" (or something like that). Here is such Flag definition (in export format) you could use for it (just import it in your own site):

```
$flags = array();
// Exported flag: "Friend".
$flags['friend'] = array (
  'entity_type' => 'user',
  'title' => 'Friend',
  'global' => '0',
  'types' =>
  array (
  ),
  'flag_short' => 'Friend',
  'flag_long' => 'Mark as friend',
  'flag_message' => 'User marked as friend',
  'unflag_short' => 'Unfriend',
  'unflag_long' => 'Remove as friend',
  'unflag_message' => 'User removed as friend',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'show_on_profile' => 1,
  'access_uid' => 'others',
  'api_version' => 3,
);
return $flags;

```

# Step 2:

Use the Views module to create a view of users that flagged other users with that "Friend" flag. Here is such view (in export format) you could use for it (just import it in your own site):

```
$view = new view();
$view->name = 'my_friends';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'My friends';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Friends';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Flags: friend */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'users';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'friend';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: User: Last login */
$handler->display->display_options['fields']['login']['id'] = 'login';
$handler->display->display_options['fields']['login']['table'] = 'users';
$handler->display->display_options['fields']['login']['field'] = 'login';
$handler->display->display_options['fields']['login']['date_format'] = 'long';
$handler->display->display_options['fields']['login']['second_date_format'] = 'long';
/* Field: User: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
/* Field: Flags: Flagged time */
$handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['table'] = 'flagging';
$handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['relationship'] = 'flag_content_rel';
$handler->display->display_options['fields']['timestamp']['date_format'] = 'long';
$handler->display->display_options['fields']['timestamp']['second_date_format'] = 'long';
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user/%/friends';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'Friends';
$handler->display->display_options['menu']['description'] = 'Users marked as friends';
$handler->display->display_options['menu']['weight'] = '9';
$handler->display->display_options['menu']['name'] = 'user-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;

```

# Result

After you enable the view, the result of it is that it'll show a tabular list of users, via path `user/%/friends`, and it will add a "***Friends***" tab on the user profile page (also).

Here is a sample of such table:

```
Name           ! Last login                  ! Uid
---------------+-----------------------------+----
Dries.Buytaert ! Monday, May 2, 2016 - 18:19 ! 19
Demo.User      ! Friday, May 6, 2016 - 12:16 ! 8

```
> 1 votes

# Answer
You can add a contextual filter to the User uid on the flag.
> 0 votes

---
Tags: views, flags
---


# Question
Title: how to modify the path with hook_menu_local_actions_alter
when I add the hook\_local\_actions\_alter to my module, I can see that the node.add.page link shows up on certain pages as below. how can I modify this so that this also show up on a different path in addition to the "admin/content" link it already shows up on ? I want it to also show up on "admin/owncontent" .

\[node.add\_page\] =\> Array ( \[id\] =\> node.add\_page \[title\] =\> Drupal\Core\StringTranslation\TranslatableMarkup Object ( \[string:protected\] =\> Add content \[translatedMarkup:protected\] =\> \[options:protected\] =\> Array ( )

```
                    [stringTranslation:protected] =>
                    [arguments:protected] => Array
                        (
                        )

                )

            [weight] =>
            [route_name] => node.add_page
            [route_parameters] => Array
                (
                )

            [options] => Array
                (
                )

            [appears_on] => Array
                (
                    [0] => system.admin_content
                )

            [class] => Drupal\Core\Menu\LocalActionDefault
            [provider] => node
        )

```

# Answer
> 1 votes
Local actions and tasks (and menu links) don't apply to paths, they apply to routes.

For local actions to appear somewhere, you put them in the appears\_on list, as you can see in your dump for the system.admin\_content route. Just add your own route name there.

If you don't know your route name (e.g., because it is a view or otherwise dynamically defined page), you can look it up for example with the WebProfiler module that's part of Devel. Or you look in the `router` table.

Note that having hardcoded definitions on something like a view is a bit problematic, if the view is deleted or renamed, the route name will change and your code will break. That's probably OK for custom modules as you can assume that nobody will do that. One way to work around that is to specify a dummy route with the same path in a routing.yml file, views will see that and use the same route name.

---
Tags: 8, hooks
---


# Question
Title: Get webform submissions filtered by data value
I have 2 webforms set up, one form collects the user email address and emails the user some info, the second form collects their email address again and needs to select the previous form's submitted data from the database and forward this onto a selected user.

Is there an efficient method for selecting webform data filtered by a field, rather than nid or sid, (in my case it would be an email address)?

# Answer
> 1 votes
The `$filters` parameter on `webform_get_submissions()` can be used for field filtering. The function's code loops over the filters and adds them as conditions.

```
foreach ($filters as $column => $value) {
  $pager_query->condition($column, $value);
}

```

So something like:

```
$old_form_submission = webform_get_submissions(array('email_field_name'=> $provided_email));

```

# Answer
> 0 votes
I know that in Webform 4.x, you can select a certain array of fields to print to download by navigating to your webform, and then going to the download area. I use this to grab email address's for everyone who has opted in for newsletters, so that I can compile a list of first names, last names, and email address's to import into Mail Chimp.

---
Tags: webforms
---


# Question
Title: Looking for an entityreference widget that allows to preselect an entity bundle
I'm using one entityreference field in many entity types (bundles) because of the convenience that gives in Panels (just one relation to add in context).

However, the drawback is that the standard entityreference widgets show one bunch of target entities, which is not userfriendly.

What I want is a widget that includes a select field for the entity type (bundle) in order to filter the select field next to it.

I saw the Entityreference View Widget but but I'm looking for something more simple, just two select fields of which the first filters the second.

# Answer
This module does it: Entity Reference Dynamic Select https://www.drupal.org/project/entityreference\_dynamicselect\_widget
> 0 votes

---
Tags: entities
---


# Question
Title: drush/drush dev-master requires codegyre/robo ~1.0.0-beta1
I'm transitioning a Drupal 6 site to Drupal 8.1 so following the official instructions, I set up a new install in its own directory. Since this is only one site, I followed the instructions to put my database credentials in sites/default/default.settings.php after the declaration of the $databases array.

Running `drush --status` returns the following.

```
Drush version          :  8.1-dev
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :
Drupal root            :  /media/psf/Home/apps/newp
Drupal Settings File   :  MISSING

```

Since this Drupal is 8.1-dev that must mean I need to upgrade it. Since this is a global install using Composer, I run `composer global update`.

> Your requirements could not be resolved to an installable set of packages drush/drush dev-master requires codegyre/robo ~1.0.0-beta1

Checking the drush-ops page on github doesn't show any anomalies like this nor my Google search.

What am I overlooking?

# Answer
The dev/master branch of Drush is a development release, so it depends on non-stable components such as Robo 1.0.0-beta1. Composer will reject this component unless you have `"minimum-stability": "beta"` in your composer.json file. Note that Drush itself has this setting, but if you include Drush from some other project (e.g. your Drupal site), then you will also need to set your minimum-stability in your project's top-level composer.json file.

Perhaps a more reasonable solution would be to run `composer require drush/drush:~8`, and use the stable release of Drush.

**UPDATE**

Drush `master` is now using the stable release of Robo ~1, so it should be easier to install Drush via `composer require`, at least for the time being. It is always possible that at some point in the future, though, the dev version of Drush may become dependent on features only available in some non-stable release of one of its dependencies, so you should always be prepared to set your minimum stability when requiring a dev version of Drush -- or any other Composer project.
> 22 votes

---
Tags: 8, drush
---


# Question
Title: Programmatically select image style for use with custom file entity view mode
I have created an empty custom view mode for file entities with `hook_entity_info_alter()`.

I would like to programmatically select settings for it, so that they can be deployed without a user having to go to the file entity display settings GUI and select "image" for type of file display and "original size" for the image style.

I cannot do this with `hook_entity_view_mode_alter()` because that appears to only fire for nodes, not for file entities.

How can I programmatically set the display settings for my custom view mode for file entities?

# Answer
> 1 votes
Sounds like something like this should work for you, to set the file display for the image file type, view mode name VIEW\_MODE (replace with your custom view mode), to display original image. It either adds a new file display or updates an existing one:

```
$displays = file_displays_load('image', 'VIEW_MODE', TRUE);
$formatter = 'file_field_image';
if (array_key_exists($formatter, $displays)) {
  $display = $displays[$formatter];
}
else {
  $display = (object) array(
    'api_version' => 1,
    'name' => 'image__VIEW_MODE__' . $formatter,
  );
}
$display->status = 1;
$display->settings['image_style'] = '';
file_display_save($display);

```

---
Tags: media, entities, files
---


# Question
Title: How to add 'not equal' condition in form #states
In my form, there are 3 selection list A, B and C.

I wanna show or hide C based on values of A and B selected. C should be shown if A's value = 'all and B's value != 'all'

How to set the #state condition in this case?

```
 $form['C'] = array(
        '#type' => 'select',
        '#title' => t('C'),
        '#states' => array(
            'visible' => array(
                ':input[name="A"]' => array('value' => 'all'),
                ':input[name="B"]' => array('value' => 'all') //???how to set !='all' here?
            )
        )
)

```

# Answer
This code should work:

```
':input[name="B"]' => array('!value' => 'all')

```
> 6 votes

# Answer
Although I don't think you can make negative condition with states in D7, **you can make C invisible** when B value equal *all*.

```
$form['C'] = array(
    ...
    '#states' => array(
       'visible' => array(
          ':input[name="A"]' => array('value' => 'all'),
       ),
       'invisible' => array(  // you choose 'invisible' parameter
          ':input[name="B"]' => array('value' => 'all')
       )
    )
)

```
> 2 votes

---
Tags: javascript
---


# Question
Title: How do I return a number in render arrays?
I am building a module in Drupal 8. I am doing a query in database and I return the number of users and the number of nodes. I write of screen this numbers without errors, but I cannot write them in a block.

This is the code I am using.

### Module file

```
/**
 * Implementa hook_theme ()
*/
function my_module_theme() {
  return array(
    'my_module_test' => array(
      'template' => 'test',
      'users' => NULL,
      'questions' => NULL,
    ),
  );
}

```

### The class implementing the block

```
  namespace Drupal\my_module\Plugin\Block;
  use Drupal\minka_qa_core\FormatUtils;

  use Drupal\Core\Block\BlockBase;

  /**
   * Provides a 'Bloco' block.
   *
   * @Block(
   *  id = "bloco",
   *  admin_label = @Translation("Bloco"),
   * )
   */
   class Bloco extends BlockBase {

     /**
      * {@inheritdoc}
      */
     public function build() {
       //$count = $this->countTest();
       $example = $this->test();
       $example2 = $this->test2();

       print_r($example);
       printf('\n');
       print_r($example2);
       //$questions = $this->countTest2();
       /*$build = [];
       $build['bloco']['#theme'] = 'my_module_test';
       $build['bloco']['#plaint_text'] = 'Questões';
       $build['bloco']['#users'] = $count;*/
       return [
         '#theme' => 'my_module_test',
         '#plain_text' => 'Questões',
         '#users' => $example,
         '#questions' => $example2,
       ];
   }

   public function test() {
     $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('type', 'questoes');
     $nids = $query->count()->execute();

     return FormatUtils::formatNumber($nids);
   }

   public function test2(){
     $query = \Drupal::entityQuery('user')
      ->condition('status', 1);
     $nids = $query->count()->execute();

     return FormatUtils::formatNumber($nids);
   }

```

}

### The template file

```
<div class="test">
  <p>Test twig template!</p>

  <p>user: {{ users }}</p>
</div>

```

Why isn't my code working?

# Answer
> 2 votes
There is a mismatch in `hook_theme()`, template is "test", elsewhere "my\_module\_test". And the return array has three levels, with the keys `variables` and `template` in the second level and the twig parameters in the third:

```
  return [
    'loremipsum' => [
      'variables' => [
        'source_text' => NULL,
      ],
      'template' => 'loremipsum',
    ],
  ];

```

---
Tags: 8, blocks
---


# Question
Title: Why I cannot export vocabulary terms via Features?
Ok, I've installed features, uuid, uuid\_features.

According to docs vocab terms shouls be exported too when creating taxonomy feature.

So I run a command:

> drush fe my\_feature taxonomy:tags

but every time inside feature there is no such thing like terms. Only vocabulary is exported. What I am doing wrong?

From code review I see that only hook\_taxonomy\_default\_vocabularies is implemented.

# Answer
You need to use the module uuid\_features.

It is both possible to export individual terms by listing the ones you want or you can export all terms with the vocabulary:

1. Enable uuid\_features
2. Go to admin/config/content/uuid\_features
3. Check the boxes of the Vocabularies under "Exportable Taxonomy term bundles"
    * If you want to export all terms then check the "Auto detect uuid terms" option, so future additions / changes will be added.
4. * If you didn't select the "Auto detect uuid terms" option: Do a drush fc and you will see a new item "uuid\_term", get the list of components and do a drush fe FEATURENAME uuid\_term:THETERMSUUID1 uuid\_term:THETERMSUUID2 (gets really long, hence the "Auto detect uuid terms" option)
    * If you selected the "Auto detect uuid terms" option: you just need to export the taxonomy so do a drush fe FEATURENAME taxonomy:VOCABNAME

Sorry about the odd bulletted list, trying to represent two options in one list.
> 5 votes

# Answer
The best way to export taxonomy terms without any extra modules is with update\_hook\_N() in your .install file.

Here's the code I use:

```
/**
 * Insert terms for MYVOCAB vocabulary.
 */
function MYMODULE_update_7101() {
  $terms = array(
    'Term #1',
    'Term #2',
    'Term #3',
    '...',
  );
  // Check if term exists in vocabulary and add it if not.
  MYMODULE_safe_add_terms($terms, 'MYVOCAB');
}

/**
 * Helper function for adding terms to existing vocabularies.
 *
 * @param array $term_names
 * @param string $vocabulary_machine_name
 * @param int $weight
 */
function MYMODULE_safe_add_terms($term_names = array(), $vocabulary_machine_name = '', $weight = 100) {
  //  Make sure the vocabulary exists.  This won't apply all desired options
  //  (description, etc.) but that's okay.  Features will do that later.
  //  For now, we just need somewhere to stuff the terms.
  $vocab = taxonomy_vocabulary_machine_name_load($vocabulary_machine_name);

  // Load the vocabulary.
  // Check if field already exists and add it if not existing.
  if (is_object($vocab) && property_exists($vocab, 'vid') && $vocab->vid > 0) {
    //  Load each term.
    $i = 0;
    foreach ($term_names as $term_name) {
      $term = taxonomy_get_term_by_name($term_name, $vocabulary_machine_name);
      // Check if term exists and if it doesn't exist create a new one.
      if (count($term) == 0) {
        $term = (object)array(
          'name' => $term_name,
          'vid' => $vocab->vid,
          'weight' => $weight + $i,
        );
        // Save new term.
        taxonomy_term_save($term);
        $i++;
      }
    }
    drush_log($i . ' terms added to ' . $vocabulary_machine_name . ' vocabulary', 'notice');
  }
  else {
    drush_log('Vocabulary "' . $vocabulary_machine_name . '"" not found', 'error');
  }
}

```
> 0 votes

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


# Question
Title: How do I set a visibility rule for the individual menu block items?
Is there a way of setting visibility of menu items itself based on the URL?

With the Panels module, we can set visibility of the panel section based on the URL or other rule. How can I set that kind of rule for individual items of a menu block?

For example, the menu block has the following items: Item-1, Item-2, Item-3, Item-4. If the URL is node/, display all items; if the URL is node/string-1, display Item-1, Item-2, Item-3; if the URL is node/string-2, display Item-4, item-5, Item-6.

# Answer
> 1 votes
# Step 1

Create 3 blocks:

* Block 1 containing links pointing to all items like Item-1, Item-2, Item-3, Item-4, ... etc.
* Block 2 containing links pointing to all items Item-1, Item-2 and Item-3.
* Block 3 containing links pointing to all items Item-4, Item-5 and Item-6.

# Step 2

Enable the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".

# Step 3

As per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown for the listed pages).

So create 3 Rules Components, each with a Rules Condition that performs a *Text comparison* with `Parameter: Text: [site:current-page:path]` and an appropriate *Matching Text* for the URLs like:

* (NOT `node/string-1` AND `node/string-2`), to show Block 1.
* `node/string-1`, to show Block 2.
* `node/string-2`, to show Block 3.

---
Tags: 7, blocks
---