# Question
Title: How to enable Database search & autocomplete live search?
Found a great article of how to enable live search on drupal 7 http://www.stevepolitodesign.com/blog/create-live-search-results-search-you-type-drupal

But seems all modules are not yet available for drupal 8. Can anyone show some light on this please of how a similar thing can be done on drupal 8?

# Answer
I don't know if I get this right, but you can just use this module https://www.drupal.org/project/search\_autocomplete where you get live autocompletion for your search terms.
> 2 votes

# Answer
You'll probably have to write a custom module for this.

Here's the basic idea:

* You should decide with which search mechanism you want this to work. For the sake of simplicity, I'll use the core Search module as an example.
* Declare a new autocomplete field with your custom callback path; it *might* work if you just alter the search field type, turn it into autocomplete and add your custom callback path. I'm not sure if this will work in D8 though.
* Whenever user changes the input, your module should query the database and see if there are any matching keywords stored in the search module. You can include any additional logic here, e.g. limit the search to nodes only, give some criteria higher visibility, exclude some keywords, etc.
* Return back the similar keywords so user can choose some of them.
* When search is submitted, display search results from core search module. If it's possible, the best would be to alter the search input field, so you don't have to much else to handle form submission, etc.

I didn't check much, but this should get you going. For more info on D8 form API, check this out. If you need to see how is this done in the core, check out the code for referencing the users (e.g. author field in node forms).

Hope this helps.
> 2 votes

---
Tags: 8, search, ajax
---


# Question
Title: Create a layout 3 column with 2-1-2 teasers
I would like to create a layout like in this image.

It's all the same content type, and I am displaying images.

The columns have all the same width, the first columns -left- contains 2 teasers ( one below the other), the second one -center- contains 1 teaser, the last column -right- contains 2 teasers ( one below the other).

The image teaser on the center column has the same width of the other but it has the double of height, so I will need another image style or another field.

I can't achieve this just with css otherwise the images will look stretched/cropped.

I don't know how to approach to this issue. How to say that each two nodes, I need to display one with a different image style or another field image, using views.

Any help, suggestion, idea would be appreciate!

# Answer
This solution is not perfect, but will most likely be the fastest to achieve:

* In `hook_node_preprocess()` render the image field twice, once with small and once with large image style.
* Edit your `node--YOUR-CTYPE.tpl.php` file and display both images.
* Use CSS to display the correct one. You can basically do this:

```
.views-row-1 .your-large-image-selector,
.views-row-2 .your-large-image-selector,
.views-row-4 .your-large-image-selector,
.views-row-5 .your-large-image-selector {
  /* Hide large image. */
}
.views-row-3 .your-small-image-selector {
  /* Hide small image. */
}

```

Other than that, you could try doing this in a custom module, unless you really need Views for something. I think doing this through a custom module makes more sense if you have to display a larger number of images on the page (e.g. 20-30), because with the approach above you will end up with twice as much images.

Here's what you would need to do in a custom module:

* Add `hook_theme()` implementation and declare your own custom template. Here you would display the first two items on the left, third in the middle and the last two in the right column. The arguments for the template would be just an array called `items` for example.
* Get all nodes you want to display, prepare the output and split them into groups of 5. Every third item would use the larger image style.
* Loop through the groups and theme the output based on your custom theme.
* Put everything together and display on the page.

This way you won't have 2 images for each node, but you will have to write custom code.

There are other ways to achieve this, but I believe developer sanity should not be overlooked. The ways I suggested above are more or less easy to do.

Hope this helps.
> 0 votes

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


title: hook_cron_queue_info stopped

text:
# Question
Title: hook_cron_queue_info stopped
I'm trying to use Drupal Queue and Cron to execute a task. In the following example I:

* select all the users
* create an item in the queue for each of them
* define the function that has to be run for the items of the queue

What happen is that at some point the system stops running the queue and the only way to start again the process is to kill it. (I'm using Ultimate cron to controll Cron processes).

I understood that after some time the system should stop the script and start it again at the following cron job. Am I wrong?

Here there is the code:

```
 function mymodule_cron() {
        $sql = db_query("select u.uid, u.mail FROM {users} u WHERE u.status=1");

    $queue = DrupalQueue::get("testlogging");

    $number_of_rows = $sql->rowCount();
    if ($number_of_rows > 0) {
        foreach ($sql as $record) {
            $queue->createItem($record);
        }
    }
}

function mymodule_cron_queue_info() {
    $queues = array();
    $queues['testlogging'] = array (
      'worker callback' => 'log_user',
      'time' => 300,
    );
    return $queues;
}

function log_user($record) {
    watchdog('MyModule', 'queue info: uid = ' . $record->uid . " " . $record->mail);
    sleep(2);
}

```

# Answer
> 0 votes
If you are sure that your execution do not produce programming errors, the problem may come from the fact that Drupal only executes queue items when running Cron. Taking into account that Drupal Cron is limited by time and PHP memory, your queue items may not be fully processed in a single Cron run.

You can refer to this issue I created some time ago about a very similar problem.

In short, I solved it by processing queue items every X minutes.

---
Tags: 7, cron, queue
---


title: Get site name in custom template

text:
# Question
Title: Get site name in custom template
I want to print the site name in a custom template (`page--front.html.twig`)

`{{ site_name }}` does not work.

If I use `{{ page['#title'] }}` I only get "Welcome to \[site\_name\]".

I'm looking for a way to only print the site\_name. Do anyone know how to achieve this?

Thanks!

# Answer
> 17 votes
Add this to the `YOUR_THEME.theme` file:

```
function YOUR_THEME_preprocess_page(&$variables) {
  $variables['site_name'] = \Drupal::config('system.site')->get('name');
}

```

And then this in your `page--front.html.twig` template:

```
{{ site_name }}

```

# Answer
> 6 votes
Things have changed some from Drupal 7 to Drupal 8. One of the things that have changed, is that it's a really good idea to use blocks instead of fetching and rendering this stuff yourself. The main reason is caching.

What you probably want to do, is to place the site branding block somewhere on the page (can display site name, logo and/or slogan). A lot of the stuff that was hardcoded in themes, are now blocks.

There was a big effort in doing this, as it makes the caching and huge performance gains possible, which was achieved in Drupal 8.

If you really want to do it the Drupal 7 way, @Aram's answer shows you how to do it with a preprocess hook.

# Answer
> 2 votes
Yes in `D8 twig template` files you can not write code to fetch data.

If you need any data then you need to set the variables in `preprocess` function & use that.

---
Tags: 8, theming
---


# Question
Title: Display text according to the access to a field
With field permissions, I restrict the access of a field to certain users.

I would like to display some text to inform the user that he has no access to the field.

I tried it in node.tpl.php :

```
<?php if (!field_access('view', field_info_field('field_name'),'node', $node)): ?>
    <p><?php print t('my text.'); ?></p>
<?php endif; ?>

```

It works, but I do not know how to restrict according to the type of content.

How can it be done? Also, is it the good method?

# Answer
> 0 votes
You can use drupal\_set\_message in hook\_node\_view to display the text as a message to the users.

```
function MODULE_NAME_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'your_node_type') {
    if (!field_access('view', field_info_field('field_name'),'node', $node)) {
      drupal_set_message(t('Your text.'), 'warning');
    }
  }
}

```

---
Tags: 7, entities, users, files
---


title: How to add custom metatags in drupal 7?

text:
# Question
Title: How to add custom metatags in drupal 7?
I need to add a custom metatag to D7 site, something like here: http://groups.drupal.org/node/83069. What are the possible options? I know there is a metatag module, but seems it doesn't support custom tags.

I could modify the theme, but I need some user configurable solution.

# Answer
Did you have a look at Meta tags quick?

There is a comparison page for meta tag generation modules.
> 2 votes

# Answer
Metatag does support custom tags by implementing **hook\_metatag\_metatags\_view\_alter()**. See the following hook implementation to add the Open Graph *video:duration* metatag from a custom entity:

```
/**
 * Alter metatags before being cached.
 *
 * This hook is invoked prior to the meta tags for a given page are cached.
 *
 * @param array $output
 *   All of the meta tags to be output for this page in their raw format. This
 *   is a heavily nested array.
 * @param string $instance
 *   An identifier for the current page's page type, typically a combination
 *   of the entity name and bundle name, e.g. "node:story".
 */
function mycustommodule_metatag_metatags_view_alter(&$output, $instance) {
  if ($instance == 'mycustom:entity') {
    $entity = mycustomentity_load(someid);
    $duration = $entity->duration;
    $output['video:duration']['#attached']['drupal_add_html_head'][0] = array(
      array(
        '#theme' => 'metatag_opengraph',
        '#tag' => 'meta',
        '#id' => 'video:duration',
        '#name' => 'video:duration',
        '#value' => $duration,
      ),
      'video:duration',
    );
  }
}

```
> 12 votes

# Answer
Replying late but this may be helpful for others:

I have written about my solution here http://mymixerone.blogspot.in/2012/11/adding-meta-tags-in-drupal-node.html

Just have a look if its helpful.

Here is the solution in brief, Try adding this in your templet.php file:

```
<?php
function <theme-name>_preprocess_html(&$variables) {
  switch(arg(1)) {
    //current-issues, node id 33
    case "33" :
      // title
      $variables['head_title']= "New Title";

      //key-words
      $page_keywords = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'name' => 'keywords',
          'content' => 'all keywords for this node',
        )
      );
      drupal_add_html_head($page_keywords, 'page_keywords');
      break;

    //node id 20
    case "20" :
      // title
      $variables['head_title']= "New Title";
      break;
  }
}
?>

```

other tags can be added similarly.
> 5 votes

# Answer
Thank you Atul. I've used your approach to make refreshing page in Drupal support module every 30 seconds.

```
function garland_preprocess_html(&$vars) {
//Adding Refresh to main tikets page BEGIN
//print 'Node id = ';print(arg(1));
switch(arg(1)){
//check node id : if nid=kontora then use custom "Refresh setup" (must be the name of client you want to refresh)
case "client1" :
/*Implementation of HTML equivalent <meta http-equiv="Refresh" content="30" />*/
$http_equiv = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
    'http-equiv' => 'Refresh',
    'content' => '30',
    )
  );
drupal_add_html_head($http_equiv, 'http_equiv');
// Meta tag code here
break;
/*
//node id 20
case "20" :
      // Meta tag code here
break;*/
     }
//Adding Refresh to main tikets page END
}

```
> 3 votes

# Answer
You can also implement hook\_metatag\_info in a custom module, define your metatag and then you can configure it with UI.

You can see this implementation from metatag module, by example http://www.drupalcontrib.org/api/drupal/contributions%21metatag%21metatag\_opengraph%21metatag\_opengraph.metatag.inc/function/metatag\_opengraph\_metatag\_info/7
> 0 votes

# Answer
Custom meta module will do it.
> -1 votes

---
Tags: 7, meta-tags
---


title: Add sufix to field in views

text:
# Question
Title: Add sufix to field in views
I have a view displaying webform fields (results).

In some questions, the user answered for example 15€, but I added the sufix "€" to the webform so the user won't have to write it. So the answer is just "15".

I want to add the same sufix "€" to the view field so it appears "15€". How can I do this?

# Answer
You can rewrite the output of any field in a view by using "Rewrite results" and clicking on "Rewrite the output of this field" (see screenshot below). You can use a replacement pattern for the actual content of your field and then add the "€" symbol.
> 0 votes

---
Tags: views
---


# Question
Title: Attributes in table in custom content type form
I am creating a custom content type named "Invoice". This content type is having attributes like Company Name (entity reference to company content type), Bill details, tax details and calculations. Can you please suggest how can I get elements/attributes like shown in an image in custom content type add new content form?

# Answer
> 1 votes
field\_collection module allows you to add a field (Bill details) that contains a collection of fields (Amount, Service Tax, VAT, etc.). Set it to accept multiple values and you get a list like the one shown in the photo.

# Answer
> 1 votes
You will need to override the node form template for your invoice content type with a custom template in your theme. More info -\> Theming Node Forms in Drupal 7 and here

In your template you'd build a layout for your fields and output form fields in place like this

```
<?php print drupal_render($form['fieldname']);?>

```

---
Tags: forms, entities
---


# Question
Title: Is it possible to force redirection from PayPal to the website after successful payment?
I'm using PayPal WPS with Ubertcart, and want to track the conversions using Adwords.

Is there any way to force *true* redirection back to the website within Ubercart?
The redirection in PayPal settings is already set to "On", however the users are still being asked to click to go back, or proceed to their PayPal settings page.

This results in losing the conversions.

Any ideas how to force the clients back directly to the website via Ubercart / custom module?

Thanks!

# Answer
The answer is unfortunately no.

PayPal will always display this as an option to the client, so you can't force the redirection back after the payment has been completed.
> 1 votes

---
Tags: 7, ubercart, payment-gateways
---


# Question
Title: Loading nodes from another Drupal database using Views
I'm trying to use Views to load nodes from another Drupal database defined in settings.php with a key of 'cms'. Both sites are Drupal 7. The other database is a different Drupal install which is acting as a content repository or centralized CMS. My goal is to create a new view type/group on the destination site, so when creating a view the site build can choose "CMS Content" instead of "Content". I'm hoping a site builder would then be able to build a view normally based on content types and content from the centralized CMS site, even if I have to tell views about all the fields in each content type.

In my hook\_views\_data() implementation I've set the 'database' key, but can't figure out how to read from the node table without overriding $data\['node'\].

```
function cms_connector_views_data() {
  $data['cms_connector']['table']['group'] = t('CMS Content');
  $data['cms_connector']['table']['base'] = array(
    'field' => 'nid',
    'title' => t('CMS Content'),
    'help' => t('Content from the centralized CMS.'),
    'database' => 'cms',
  );

  return $data;
}

```

Of course this doesn't look for a node table, it looks for a `cms_connector` table in my `cms` database, which doesn't exist.

`SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cms.cms_connector' doesn't exist`

http://views-help.doc.logrus.com/help/views/api-tables says that the key within $data…

> should be the actual database name of the table (not including prefix), but it can be an alias as long as the join information (explained later) contains the real name of the table.

I don't actually want to do a join, I want to create a base table from the other database's node table. But I tried this anyway (even though it doesn't really make sense) after seeing http://drupal.org/node/1713010#comment-6310438:

```
$data['cms_connector']['table']['join'] = array(
  'node' => array(
    'left_field' => 'nid',
    'left_table' => 'node',
    'field' => 'nid',
    'table' => 'node',
  ),
);

```

I've searched around here, d.o, and Stack Overflow, but most of what I'm finding is Some-other-database-to-Drupal, not Drupal-to-Drupal.

I found the https://drupal.stackexchange.com/questions/12736/using-nodes-from-another-site-database question here, but it's about node references, and is unanswered.

I thought about using Services to read XML/JSON from the centralized site, but there are too many hurdles to that approach. I don't really want to synchronize nodes either.

# Answer
Consider looking at the Forena module. It can be used to query (not update) the data in other databases. Various DBMS formats are supported, such as another Drupal database also.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports. For more details about Forena, 2 types of documentation are available:

* Community documentation.
* Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

+ **Forena documentation** \- use the link 'Reporting documentation' or visit relative link /reports/help.
    + **Forena samples** \- use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

Disclosure: I'm a **co**-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.
> 1 votes

# Answer
You can export content using the Views module to export data and import them using the Feeds module (you can import periodically using Rules module).
> 0 votes

# Answer
Check this modules:

EntityFieldQuery Views Backend or Web Service Data
> -1 votes

# Answer
One option using settings.php file. Configure 2nd database instance in settings.php file. After setting up instance use that db using `db_set_active('drupal2')` function and do anything with your second db.

e.g.

```
$databases = array(
    'default' =>
    array(
        'default' =>
        array(
            'database' => 'drupal1',
            'username' => 'root',
            'password' => '',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => '',
        ),
    ),
    'cms' => // additional database starts here
    array(
        'default' =>
        array(
            'database' => 'cms',
            'username' => 'root',
            'password' => '',
            'host' => 'localhost',
            'port' => '',
            'driver' => 'mysql',
            'prefix' => '',
        )
    ),
);

```

in your module you can use both database as below:

```
db_set_active('cms');
$node = node_load(10);
var_dump($node):

```
> -1 votes

---
Tags: 7, views
---


# Question
Title: Removing Drupal GET Form apparently unnecessary parameters
I have a FORM built with Drupal 7 Form API, with URL (action) pointing to:

```
www.example.com/search-products

```

and the default method POST. My SEO mate has asked me to change the method to GET, so for SEO indexing purposes the URL will be explicit, for example:

```
www.example.com/search-products?brand=BRAND%201&model=Model%20Fantastic

```

I have changed the behaviour of the form by adding the following line at the end of the `hook_form` function:

```
$form["#method"] = "get";

```

Now the problem is that the generated URL has some "extra" info that I wouldn't want to be displayed. And it is apparently unnecessary, because if the View (landing page of the FORM) is paged, if I only pass the above parameters + the page, it works perfectly, also if I remove this extra info by hand.

The "ugly" URL is:

```
www.example.com/search-products?brand=BRAND%201&model=Model%20Fantastic&op=Submit&form_build_id=form-Ab-i8LlsUjtftyuTlL8b7OvZj_tM1MfyuKCnAg5-VncY&form_id=hook_form

(extra info: ... &op=Submit&form_build_id=form-Ab-i8LlsUjtftyuTlL8b7OvZj_tM1MfyuKCnAg5-VncY&form_id=hook_form )

```

How can I make Drupal ignore that extra info?

# Answer
> 4 votes
Here's a workaround you can use:

```
    $form['#after_build'][] = 'mymodule_form_modify';

```

Then:

```
    function mymodule_form_modify($form){
      unset($form['form_token']);
      unset($form['form_build_id']);
      unset($form['form_id']);
      return $form;
    }

```

And finally to get rid of the `&op` parameter:

```
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
      '#name' => '',
    );

```

Source.

# Answer
> 1 votes
You can't, those "extra infos" are required by Drupal to process form submission.

EDIT : Well i have read too fast. If you use a custom action, and thus **does not have validate or submit function**, you can skip drupal specific parameters. Just add access false to fields you don't want to be submitted.

```
$form['form_build_id']['#access'] = FALSE;

```

# Answer
> 0 votes
No need to do that in Drupal:

You can hide parameters in Google.

Follow Google Webmaster --\> Crawl --\> URL Parameters, after that click Configure URL parameters » then click add parameters and add parameters which you want not to index in Google.

Solution

---
Tags: 7, forms
---


# Question
Title: How to enable an authenticated user to vote?
I am new to the field . I made a drupal 7 site using theme Danland, I am able to vote for the poll as an administrator but when I login as an authenticated user I can see the completed poll and I can not vote. What do I need to do.

# Answer
> 2 votes
Authenticated users probably do not have permissions to vote.

Go to administration \> People \> Permissions and then grant authenticated users the "vote" permissions.

---
Tags: 7, polls
---


# Question
Title: How to customize Schema.org at node level?
I am using the Schema.org module for schema tags, which allows me to customize schema tags at content type.

How can I customize schema tags at node level?

# Answer
> 1 votes
As I understand your question, you would like to be able to override the Schema.org types per each node separately.

This is not possible at least out of the box. You would have to write custom code to display a tab on each node form, store it somewhere and then load it when the node is about to be viewed.

This is because content types are generally used for storing the content of the same kind. For example: an article, a blog post, a static page, a webform and so on. This means that all nodes of certain type will need the same Schema.org declarations, and that's why it was implemented this way.

You are probably storing different kinds of nodes using one "generic" content type. This is not the most common use case. Unless you have strong reasons for doing this, I suggest migrating the content to separate content types. It will benefit you in case you want to use other similar modules as well, such as Metatag.

Hope I managed to explain it.

---
Tags: nodes, 7
---


title: Open preview in new window/page

text:
# Question
Title: Open preview in new window/page
I'm using drupal 7.

Normally, during the creation of a contents, the preview is added above the form.

I would wish that the preview opens in a new window, and that it is separated from the form of creation of contents.

Do you know a solution?

# Answer
> 0 votes
This module looks like something that might fit your need: Simple preview

---
Tags: 7, theming, forms
---


# Question
Title: How to configure the fields in the report created by the Content Audit module?
I use the Content Audit module on my site.

Does anyone know how to configure the fields that are present in the resulting report beyond modifying the `content_audit_report.views_default.inc` file?

# Answer
Have a look at the article about "Content inventory and content audit with Views". Here is an intro of it:

> Do you know the exact state of the content in your large Drupal site? Thinking of revamping, redesigning or upgrading your site? If you answered 'no!' to the first question or 'yes!' to the second question, it's time for content audit.
>
> In this blog post, I cover the what, why, who, when, where and how's of content audits. I've conducted a few small content audits, and I'm leading a much bigger one, on Drupal.org.

It's a pretty old article already (from 2011), and still contains Views2 screenprints. But it includes a lot of interesting details that should help to answer your question.

What is also interesting in this article are the recommendations to actually "evaluate your content", via a combination of these options (quote from the same article):

> * Option A (Export): export this view to CSV and manage your content audit in spreadsheet software or Google Docs. The Views Bonus Pack module will let you export the view as a CVS file. Pro: Less data to store in your database Con: Your inventory is almost immediately outdated; will be extra time-consuming to update on a regular basis
> * Option B (Flags): 'Flag' content that needs to be updated using the Flag module. You can adjust the flag settings so that only certain roles can use this flag, and then set which content types can be flagged (or set it as global). You can then add the Flag to the content audit view, and/or create a separate view of nodes that have been flagged. However, marking something as "needs work" doesn't provide enough detail, so you'll want to record notes somehow (see Option C). You can create additional flags for each type of action to be taken, e.g. "needs style review" or "redundant", without the casual visitor even knowing, while keeping your content team in the loop.
> * Option C: Keep 'audit notes' field on each content type in Drupal site database with the Annotate module or by creating a field on the nodes.
> * Option D: Use the Content Audit feature module, which constructs the View, and will soon have configured Annotation (this hasn't been built yet).
> * Option E: Create another node type called Audit notes, and once filled in, then nodereference the node it covers. Then, it's easy to build a view of the Audit notes (I'm also wondering whether this could be a custom bit of code to automagically do this, then include in the Content Audit module).

Some more module suggestions to **further enhance your content auditing experience** (which you may want to use as complements to configuration facilities available in the Content Audit module):

1. Consider using the Flag module (as in that "Option B" above). And then possibly combine anything that might get flagged with the Rules module to trigger things like:

* Unpublish and/or delete this content.
    * Add it to some type of review (workflow) process, like content accuracy, spell checking, etc.
    * Notify authors via eMails, like: "Please review this content, and use any of the available flags to indicate what your recommended action for it should be".
2. Auditors often like charts to visualize what's being audited (*a picture is worth more then 1000 words ...*). By simply installing (and enabling) the Charts module, and without any additional configuration, you get some Out-of-the-box examples that come with this module (in the format of some charts and/or a Views table display). They contain data about **the total number of nodes for each of the available content types**. And these data are **limited to the nodes for which the user has permission to view them**. Visit the Charts demo site for an online preview of of these out-of-the-box examples.
> 0 votes

---
Tags: 7
---


# Question
Title: How to Display a field only once in a view
How to display field only once, please find the image.

How can we show image only once in a row.

PS:

1. We can add as attachment with image and another one with out image, but still there will be two queries ran, that I dont want.
2. We can make display:block for the first one and display:none for the rest. But this will load all images.

# Answer
In your view create two displays.

**The first display (the display you'll be using in your site)**
Add the title field only
Show 5 rows starting from 1

**The second display (a block for the first item)**
Add the title, image and excerpt from the body
Show only 1 row starting from 0

**Save the view**

**Edit the second view**
add a *Global: View area*, select the second display and (this is important!) add the field *for this page only*.
> 1 votes

# Answer
There is a module for thatTM. Views nodes split module does exactly what you're looking for.

> This module allows site administrators or builders to have a different view mode for the first nodes of a view result.

### Update

This module works with view modes, not fields. That means, you should have at least 2 more view modes to be able to use this module for your approach. One view mode with image and one view mode without image.
> 0 votes

---
Tags: views
---


# Question
Title: Which Rules Event should I use to trigger a Rules Action when accessing a particular Views page?
I have a Views page, located at, say, `www.example.com/entrepreneur`.

When a user accesses that particular url, I want some rule to be executed.

I've looked at the Rules admininistration page to find out what exactly I should use as (the mandatory) "**React on event**", which looks like so:

But I am not able to find "**page is viewed**", but I need to execute the rule when user accesses the particular single page.

Any suggestions?

# Answer
> 0 votes
You need to download Rules module ,Rule\_link module Token module

1. Enable Rule and Rule link and Token module
2. Go to /admin/config/workflow/rules\_links
3. Add a new rule\_link, Give the rule label and all other required field
4. Click on Configure rules tab and in access conditions you can add your conditions

# Answer
> 0 votes
Let's assume that the Rules action that you want to trigger is to just set a Drupal message like "**Hi there ...**". But this action should only be triggered when "Viewing the content" located at a path like "`/entrepreneur`".

To get this to work, use the rule below (in Rules export format, just import it in your site and check the results of it):

```
{ "rules_visit_view_with_path_entrepreneur" : {
    "LABEL" : "Visit view with path entrepreneur",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "/entrepreneur" } }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Hi there" } } ]
  }
}

```

The rule above should be close to what you're looking for, except maybe from these further refinements:

* Replace the ***Rules Action*** by your own "Rules Action" (which you didn't specify).
* This Rules Action will be performed **before** your content located at `/entrepreneur` is actually shown. That implies you could also issue some redirect (to another path) for whatever reason (so that the content located at some other URL would be shown **instead**.

---
Tags: views, rules
---


# Question
Title: how to access custom function in twig template file
I've write small custom function in my .theme file. Is it possible to call that function in twig template files?

I would like to fetch description value for a field in views template file, so can we add a function like function getFieldDescription($field) and access in views template file ?

Ex: https://www.drupal.org/node/2486991 has url() function, which we can use in any twig template file.

# Answer
> 1 votes
Depending on the nature of your function, maybe but probably not.

As Clive pointed out, you can use certain functions in Twig. These functions however are mostly variable filters (formatters) for last minute alterations on variables. These can be used to translate, link, or in any way alter a provided variable. These functions are a combination of those provided by twig and some additions by Drupal. You can register your own Twig function, by extending on the TwigExtension class (example).

However most functions will probably be for adding additional data to the template and not to alter existing data. Instead you should place your custom function in a preprocessor and define a variable there. Then display this variable in the template.

Custom preprocessor (replace my\_theme with your theme or custom module name):

```
function my_theme_preprocess_node(&$variables) {
  $variables['my_variable'] = 'value';
}

```

Twig:

```
{{ my_variable }}

```

Here is some reading on twig best practices: Twig best practices.

Some example code on preprocessors is here: template\_preprocess\_node(). Which is in fact systems invocation of hook\_preprocess\_HOOK().

---
Tags: theming, hooks
---


# Question
Title: Set body format for a node when it is updated via REST API
I noticed that when I PATCH a node and update the body `value`, the body `format` and `summary` are set to `null`.

If I try to add the summary and format to the json sent to the API, I receive an error saying:

```
Unprocessable Entity: validation failed.
Body: this field cannot hold more than 1 values

```

Any ideas why I get this error and how can I preserve the body format?

This is my js object:

```
{
  title: { value: this.state.title },
  body: { value: this.state.body, format: "basic_html" },
  type: { target_id: 'article' },
  _links: {
    type: {
      href: 'http://localsite.dev/rest/type/node/article'
    }
  },
}

```

If I remove the `format: "basic_html"` part, I get no errors but the format and summary are set to null.

Thanks.

# Answer
Kind of surprised this even works. The value of a field is a list of field items. Try something like this:

```
body: [ { value: this.state.body, format: "basic_html" } ],

```
> 3 votes

---
Tags: 8
---


# Question
Title: How to get the string value from the function CountryManager::getStandardList()?
Input :

```
 $li = array();
    $list = \Drupal\Core\Locale\CountryManager::getStandardList();
    foreach($list as $key => $value){
        $li[$key] = $value;
    }
    // print_r($li);

```

Output :

```
[AF] => Drupal\Core\StringTranslation\TranslatableMarkup Object
        (
            [string:protected] => Afghanistan
            [translatedMarkup:protected] => Afghanistan
            [options:protected] => Array
                (
                )

```

How can I fetch String value from the above structure?

# Answer
To fetch the string value from the translatable markup object use type casting:

```
$li[$key] = (string) $value;

```
> 3 votes

# Answer
While you can explicitly cast it to a string as suggested in 4k4's answer, in 99% of the cases, you don't have to.

print\_r(), var\_dump() and similar will show the object, but when you actually print it out, it will be implicitly cast to a string.

There are only very few cases where you must cast yourself, for example when you want to use the string as an array *key*.

You can pass such an object along in a render array, #options for a select or almost anything else and it will just work.
> 1 votes

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


# Question
Title: Having some conceptual trouble creating a View to list users that have nodes containing entity references
Users on my site can create content by adding a new node of content type 'project'.

Projects are assigned to exhibitions through a drop down 'exhibition' field which is an entity reference to another content type named 'exhibition'.

Exhibitions are created by admins and each exhibition has a location field (one of three distinct values).

I would like to create a view that displays all users that have created projects for two or more locations. So that could be (for example) 5 projects for 2 exhibitions in location X and 2 projects for 1 exhibition in location Y.

Having some conceptual trouble putting the view together, any help much appreciated.

Danny.

# Answer
> 0 votes
Got around my mental block.

1. Created a 'Users' view.
2. Added an 'Entity Reference: Referenced Entity' relationship.
3. Turned on aggregation for my view
4. Added the field I wanted to count and selected COUNT (distinct)

Working well now.

Danny.

---
Tags: entities, views
---


title: Flexslider JS not Loading

text:
# Question
Title: Flexslider JS not Loading
Using the Nexus theme, I'm getting the following error when using the theme rotater.

"The History Plugin requires Galleria version 1.2.5 or later."

Updated and its still busted.

http://www.athleteyouniversity.com/

# Answer
> 1 votes
I see in your page source it says:

```
http://www.athleteyouniversity.com/sites/all/themes/nexus/sites/all/libraries/galleria/plugins/history/galleria.history.min.js?o30qzc

```

You have a `sites/all/` folder inside your theme `/nexus` folder, which is not how it's suppose to be. **The libraries folder needs to be outside of your theme folder.**

**It's suppose to be** `/sites/all/libraries/galleria/plugins/history/galleria.history.min.js`

---
Tags: javascript
---


# Question
Title: Set permision to create nodes of certain content type programatically
I have created a content type. Now I need to set the permision to create a node of this content type programatically (the path node/add/this-content-type must not be accessible). How can I get that?

# Answer
> 0 votes
You can use hook\_node\_access(), where you can set permissions to concrete node type by your module. Here is the example:

```
function MODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  //if it is your content type and operation
  if ($type == 'CONTENT_TYPE' && $op == 'create') {
    //specify your logic - allow or deny access to certail roles, users, etc...

    //if you would like to allow access, you have to return NODE_ACCESS_ALLOW
    //if you would like to deny access, you have to return NODE_ACCESS_DENY
  }
  //in all other cases, return NODE_ACCESS_IGNORE, which means, your module does not modify access in this case
}

```

# Answer
> 1 votes
You cant implement hook node\_access in a custom module and deny access to node add page to the node/add specific path. Here you have a sample:

```
  /**
    * Implements hook_node_access().
    */
  function mymodule_node_access($node, $op, $account) {
    switch ($op) {
      case 'create':
        $path = current_path();
        if ($path == 'node/add/your-content-type') {
          return NODE_ACCESS_DENY
        }
        break;
    }
  }

```

# Answer
> 0 votes
Isn't the permission in the admin list of permissions? Simply don't give any role the ability to add/edit/delete that type of content. They won't see any link(s) to add it.

---
Tags: nodes, users
---


# Question
Title: Creating a page to display several content types
I have a website to build that requires several quite long pages, each containing several sections with quite different content in each.

A content type for each page isn't going to work as some sections would need to contain several entries, to be displayed as a slider.

So, I think, I need to create each section as a different content type and my problem becomes displaying several of these on the same page?

How can I display several content types on the same page?

Or maybe I could create a category for each page and add the types to those?

# Answer
> 0 votes
The Views module might help you for this purpose. It is highly configurable, and it allows you to display several items on a single page. Other modules can add functionality, like the Views Slideshow module.

Learning how to use Views takes some time, but there are many Views tutorials available in the web. A possible starting point might be this one:

# Answer
> 0 votes
You can use Panels and Views to make it. With Panels you can create a new page with the regions you need, and with Views you can create blocks which can list nodes.

So you create Views of each content type you need and put it with Panels.

# Answer
> -1 votes
Views module is what you need.

Edit:

With this module, you can customize the presentation of the content (and different content types) of your Drupal site in many different ways on a single page and in many other ways. The fact that the module is so flexible, it can be assumed as "advanced web based query builder" and hence also makes it that confusing and complex at the same time.

It can take some time to grasp the whole concept of views as the other answer illustrates, however you can start using it to fit your simple needs in no time. You can follow some tutorials and make use of it in no time. The link that the other answer has provided looks like a good place to start. Here's one more.

---
Tags: 7, theming
---


# Question
Title: How do I use the login for an external application?
Long ago I built a php based application for room reservations which basically ran on its own – outside the website's CMS. It was part of what I would now call a custom made intranet – or "custom-app".

Now the main website finally runs on drupal – but now we have the drupal login ***and*** the custom-app login. How could I now 'teach' the custom-app to accept visitors that are already logged in to the dp based CMS?

I know, the 'easiest' or actually 'most correct' way of doing this would probably be to develop the custom-app into a module. But are there other ways e.g. to pass the login information over to the custom-app? Any pointers would help. Thank you!

update1: both are running on the same server under the same domain.

update2: I finally came across this question "How to call drupal\_bootstrap from custom file in subfolder?" – I guess going bootstrap would be the right direction for now…

# Answer
> 0 votes
You can install in your drupal site a contrib module which allow you to create an API which can access another modules.

You can use Services module which implements route to allow users login across external sites, and another route to get the current user logged in.

So you can install this module and enable this routes, and with your php site make http calls to this sites to log in the user and check if he is logged in.

---
Tags: authentication-authorization, external-scripts
---


# Question
Title: How to disable a troublesome module that causes admin/modules to not list all modules?
I ran into an unexpected situation after installing the 7.x-2.1 of the Multilang - Embed multiple translations inside a unique node or block module. I was actually experimenting with that module to better understand the question about Why is the recommended release of my module not proposed in Drupal updates?

After I finished experimenting with that (version of that) module, I wanted to disable it again, via the typical `admin/modules` link. The link still worked (so no WSOD situation like you may get if you run into memory problems), but not even 1 module (enabled or disabled) was shown in my module list. So no way to "disable" that Multilang module from there.

**How can I disable this module without using the `admin/modules` link** (since there it doesn't show up)?

# Answer
> 3 votes
1. I was lucky enough to have Drush available. So by simply using `drush dis multilang`, the module got disabled. And Eureca ... the link at `admin/modules` started to work again.
2. Even though I have not had to use another approach, this would have been my plan-b: disable the Multilang module manually in the database, via an SQL command like so:

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

or as a variation, using PhpMyAdmin (if that's available).
3. If for whatever reason plan-b would not have worked either, you could consider deleting the entire module folder (for module Multilang) in the modules directory where that module got installed. That would, pretty sure, have "killed" the trouble module also. Though it would have left the module's row in the `system` table in some bad shape (to be repaired afterwards, probably with something like the "Registry Rebuild" module.

However, as pointed out by Molot also (merci! aka thanks!), deleting files is problematic. Because it prevents you from ever running uninstall on a module. And Registry Rebuild will probably not fix that. So think twice before using this plan-c ...

# Answer
> 1 votes
When I run into a similar problem (Devel Themer is such a case) I just delete the bothersome module folder and run **update.php**. Then I re-upload the module folder where it was before and it shows as deactivated in the module list. You can then uninstall it from the data base if you're not going to use it.

---
Tags: 7, installation
---


# Question
Title: Why does my background image only sometimes show?
I have a background image set for #region-header-first on this page http://www.smith-howard.com/resources?type=article&sort\_bef\_combine=created%2BDESC

However, it only shows sometimes in Chrome (mostly not). If I clear all Drupal caches (and browser cache) it will show once, but on the first refresh and so on it doesn't show any more.

If i check web inspector in safari (where it always works), it definitely shows the background image in the CSS.

```
#region-header-first background:url(http://www.smith-howard.com/sites/default/files/resources-articles2_0.jpg);

```

But inspecting it in Chrome doesn't show that the background image is set in the CSS at all. This is just mind boggling. Any help is greatly appreciated.

# Answer
> 0 votes
To fix it, if you want, you can check all your blocks and views and template files to see if you can find the HTML (as you can see it when you view source)

```
    <style type="text/css" media="all">
    .not-front #region-header-first .field-name-field-headline,.not-front #region-header-first .field-name-field-subhead{color:#ffffff !important;}
    </style>

```

code and remove it, OR don't worry about it and just add

```
.not-front #region-header-first .field-name-field-headline,.not-front #region-header-first .field-name-field-subhead{color:#ffffff !important;}

```

to your theme's .css file

---
Tags: caching, theming
---


# Question
Title: I have a query tagged QueryAlterableInterface that I need to add an item to the IN clause
I want to alter the term\_access query and it's tagged in QueryAlterableInterface. There are items I want to add to an IN clause that's been altered before my module.

I've tried something

```
$query->condition('ga.gid', $new_items, 'IN');

```

But that just adds a new db\_placeholder\_n to the arguments array without altering the query itself.

Query is:

```
SELECT DISTINCT base.tid AS tid, base.vid AS vid, base.name AS name, base.description AS description, base.format AS format, base.weight AS weight, base.uuid AS uuid, v.machine_name AS vocabulary_machine_name
FROM {taxonomy_term_data} base
INNER JOIN {taxonomy_vocabulary} v ON base.vid = v.vid
LEFT OUTER JOIN {og_membership} ga ON ga.etid = base.tid
AND ga.entity_type = :entity_type
AND ga.field_name = :field_name
WHERE  (base.tid IN  (:db_condition_placeholder_1)) AND( (ga.gid IS NULL ) OR( (ga.group_type = :db_condition_placeholder_2) AND (ga.gid IN  (:db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5)) ))

```

# Answer
Ok here's what happened. Basically, I had to unset the conditions and then just rewrite all of them. Any better solutions I will accept as the answer but this is how I solved it.

```
$where =& $query->conditions();

if(empty($where[1])) {
  return;
}

unset($where['1']);
$list = my_custom_function_to_get_groups();

$groups = array();

foreach($list as $group) {
  if(!empty($group->nid)) {
    $groups[] = $group->nid;
  }
}

$query->condition('ga.gid', $groups, 'IN');

```
> 0 votes

---
Tags: taxonomy-terms, database
---


# Question
Title: Create new content when an image is uploaded, using rules
I've been working all day to try and figure this out.

I have a view set up that takes every content type of "Gallery" and creates a nice view of all gallery types. I also have a webform where a user can upload an image. I then set up rules so that when an image is uploaded using that form an entity is created of type "Gallery"....and that's where I've been stuck.

I've been searching online for answers but can't find anything. Is there a way to take the image that was uploaded using the webform, and place it into the new gallery content in the field-images field?

https://i.stack.imgur.com/72Sjg.jpg

That's my rules page currently. The php code that I was using was just dsm to check what was actually inside of each entity, along with me trying random code to try and figure out how to do this. None of it worked.

I'm not sure if this is the best way to do this or not, so feel free to let me know if you know a better way to do this (I'm a drupal beginner still).

Any help would be appreciated!

# Answer
> 1 votes
In your conditions, add entity has field: web form \> image field.

That should allow you to set a data value on your created node with that image.

---
Tags: rules
---


# Question
Title: Send Email when node has been updated with specific term/selection
I am looking for a way to configure a Drupal site to automatically send an email when a certain selection is made. Specifically, I have a content type with a field that presents the option 'In Progress' or 'Complete', and I would like to trigger an email when someone marks an instance of the content type as 'Complete.'

Not sure how to do this. Any help is appreciated!

# Answer
In rules **Add Condition** \>\> Data Comparison \>\> node:field-\[name of your field goes here\]

Add Action \>\> Send Mail
> 1 votes

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


# Question
Title: How to disable the title field in a content type?
i'm using drupal 7
How to disable the title field in a content type?

# Answer
> 12 votes
I think the Automatic Nodetitles module is what you're after:

> "auto\_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

# Answer
> 1 votes
As Clive suggests, auto\_nodetitle is a good module for removing the title from the form. If you wanted to serialize the content serial is a good simple module that would do the job that jimajamma explains but with an automated serial number. Then finally, the simplest way without any custom code to hide the title field from display totally (or put any fields where you want) is display suite.

# Answer
> 0 votes
If you need to hide the title for an entity you can try the following. (Note, I don't think this is the best method and I am open to suggestions that make this better). Put this in your theme's template.php

```
function THEME_preprocess_page(&$vars, $hook) {

  if(isset($vars['page']['content']['system_main']['ENTITY_TYPE'])) {
   drupal_set_title('');
  }
}

```

What this does is if the entity is being displayed in the \['content'\] region of the page, in much the same way a node would be displayed in the content region, then change the title to nothing. You need to replace THEME with the name of your of your theme and ENTITY\_TYPE with the entity whose title you want to suppress. If it does not work, go to page.tpl.php and add `<pre> <?php print_r($vars['page']) ?> </pre>`, reload the page of interest, and work your way down the tree to find the path into the array that identifies the the thing that you want to suppress.

# Answer
> 0 votes
Another option in D7 and D8 (where it is in core) is the Title module which lets you treat Title like a field eg set Title to hidden in the content type Display pane, set it to show in a Block with the Field as Block module to pop it in to a sidebar etc

The module contributors say:

> While working on the new content translation system for Drupal 7, we (the Drupal core i18n team) faced the need to convert node titles to the Field API in order to make nodes fully translatable. We were not able to make this happen in Drupal 7 core, so we decided to find a solution for this in contrib: the idea is replacing node titles with fields à la Automatic Nodetitles.

---
Tags: nodes
---


# Question
Title: cron for rebuild xmlsitemap mannually without drush in cpanel
I'm using this: **XMLsitemap** module: https://www.drupal.org/project/xmlsitemap

I have a cpanel shared hosting in hostgator and drupal 7. I can not install Drush, ssh access is not enabled. i go to tasks cron in cpanel and setup the cronjob, but in field 'COMMAND' i tried :

```
curl drush xmlsitemap-rebuild http://link.com.br/cron.php?cron_key=xxxxx

```

Nothing , because i dont have a drush installed. So, i tried:

```
curl xmlsitemap-rebuild http://link.com.br/cron.php?cron_key=xxxxx

```

Nothing too,lastly I used:

```
xmlsitemap-rebuild http://link.com.br/cron.php?cron_key=xxxxx

```

But that is not recognized as Linux command in Terminal .... cron does not happen, what should I do?

EDIT 1: the task only works if i press the button on image,

# Answer
> 0 votes
You can probably request the the Drupal 7 cronjob by using `wget` or `curl`. On my server I can use: `/usr/bin/wget -O -q /dev/null http://www.example.com/cron.php?cron_key=XXXXX`.

The cron key is different per website and can be found on your status report page.

This basically opens a webpage just as if you would be running cron manually, but you can set an interval for it. If you set xmlsitemap to generate a new sitemap during cron (I believe that is default behavior), you should be good. You can set the rebuild time on the settings tab: .

There is no direct need for Drush (though you can do this with Drush as well), and it is not possible to run Drush with curl.

If you or someone else wants to use Drush; After installing Drush on the system you can use it like any other program: `drush xmlsitemap-rebuild` or `drush @site_alias xmlsitemap-rebuild` if you configured a site alias.

---
Tags: cron
---


# Question
Title: Is it still possible to use a custom attribute for a form (e.g. $form['#foo'])?
In the documentation for #value, the Drupal 7 documentation contains the following note:

> Note that as of Drupal 6, you can also simply store arbitrary variables in `$form['#foo']` instead, as long as `'#foo'` does not conflict with any other internal property of the Form API.

Is that still possible, in Drupal 8?

I looked at the documentation for the `Value` class, but the note given for Drupal 7 is not present.

I know Drupal adds `$form['#token']` to forms, but I take it is a special case Drupal handles in a particular way.

# Answer
See FormCache::setCache(). The whole $form is put in the cache, anything that's in there is stored and fetched again.

That said, I would definitely advise against using it. The recommended and standard way to store something is $form\_state-\>get()/set().

Also be aware that while this still works *when* the form is cached, Drupal 8 only caches form/form\_state once an actual form submission happens. Usually that means only for ajax requests and in case of form validation errors (although I don't 100% know how it behaves then).

That means you can *not* put something in $form\['#whatever'\] or $form\_state-\>set('whatever, ...) on the first form build and expect it to stay there.
> 2 votes

---
Tags: forms, 8
---


# Question
Title: Is it possible to write test against the current database?
I'm building some modules onto an existing and somewhat active site. From my understanding, SimpleTest creates a new, temporary database and effectively reinstalls a copy of Drupal.

However, I'd like to take over some current items for the existing site such as taxonomy and content types and test against this data.

Do I have to manually do this all in `setup()`? Or is there a way to clone or import existing tables into the testing database that SimpleTest sets up?

# Answer
The testing environment is by default completely separated from your website, so module testing is in no way affected by the environment. However you might be able to switch the database. There is this article about testing on the live database: http://www.codesidekick.com/blog/break-out-simpletest-sandbox. Basically you override some variables during setup and teardown in a class extending DrupalWebTestCase:

```
/**
 * @file
 * Common testing class for this Drupal site.
 */
abstract class SiteTesting extends DrupalWebTestCase {

  /**
   * Overrides default set up handler to prevent database sand-boxing.
   */
  protected function setUp() {
    // Use the test mail class instead of the default mail handler class.
    variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
    $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
    $this->public_files_directory = $this->originalFileDirectory;
    $this->private_files_directory = variable_get('file_private_path');
    $this->temp_files_directory = file_directory_temp();

    drupal_set_time_limit($this->timeLimit);
    $this->setup = TRUE;
  }

  /**
   * Overrides default tear down handler to prevent database sandbox deletion.
   */
  protected function tearDown() {
    // In case a fatal error occurred that was not in the test process read the
    // log to pick up any fatal errors.
    simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);

    $emailCount = count(variable_get('drupal_test_email_collector', array()));
    if ($emailCount) {
      $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
      $this->pass($message, t('E-mail'));
    }

    // Close the CURL handler.
    $this->curlClose();
  }
}

```

Then in the test, make sure to extend your newly created class:

```
class SiteTestingHomePageTest extends SiteTesting {
  ...
}

```

I have never tried this, and please be aware that depending on the test, they might alter the live database (if you add a node in the test, it will show up on the site), but it might be what you are looking for. Make database backups and remove all created entities in the end of the test.

If you do not want to affect live data, you will have to add the content types and taxonomy terms manually.
> 5 votes

---
Tags: 7, testing
---


# Question
Title: Email all Organic Group members when a subgroup is created
I have an Organic Groups / subgroups structure where an Organisation is a group, a Property is a child group of an Organisation, and a claim is a child group of a property. So: Organisation \> Property \> Claim Each subgroup is set to inherit its parents users

When a new Property is created, I can use rules to 'Get group members from group audience' to email all of the members of the group:

However when a new Claim is created the same rule only emails the user who created the Claim. I think that this might be because inherited users are handled differently from normal users. You can see this by going into the 'group' tab on the claim and then clicking on people:

We can see in the screenshot above that there are three inherited users, but only the user who created the node will be emailed, the other two will not.

How should I email the inherited users when subgroups like Claim are created?

-- Addition --

og\_subgroups.views.inc is used to create the view shown above. The contents of this file are:

```
function og_subgroups_views_pre_render(&$view) {
  if ($view->name == 'og_members_admin') {
    // Add an overview of the users that are inherited from parent groups.
    $inherited_users = _og_subgroups_get_inherited_users($view->args[0], $view->args[1]);
    $header = array('Name', 'Inherited from');
    $rows = array();
    $membership_states = og_group_content_states();
    if (!empty($inherited_users)) {
      foreach ($inherited_users as $inherited_uid => $data) {
        $row = array();
        $row[] = l($data[0]['user']->name, 'user/' . $inherited_uid);
        $inherited_from = array();
        foreach ($data as $inheritance) {
          $inherited_from[] = t('!parent (@roles)', array(
            '!parent' => l(entity_label($inheritance['inherited_from']['type'], $inheritance['inherited_from']['entity']), 'group/' . $inheritance['inherited_from']['type'] . '/' . $inheritance['inherited_from']['id'] . '/admin/people'),
        '@roles' => implode(', ', $inheritance['roles']),
      ));
    }
    $row[] = implode(', ', $inherited_from);
    $rows[] = $row;
  }
}
$view->attachment_after = theme('table', array(
  'caption' => t('Inherited users'),
  'header' => $header,
  'rows' => $rows,
  'empty' => t('No inherited users.'),
));
  }
}

```

It would be great if someone could suggest how I might be able to use the above code in rules. It would be great if I could use'Execute custom PHP code' and use something like

```
$inherited_users = _og_subgroups_get_inherited_users($view->args[0], $view->args[1]);

```

but that doesn't work in a custom PHP block in Rules. I can see the function `_og_subgroups_get_inherited_users` in og\_subgroups.common.inc and am not sure if I can use this code to help.

Using Organic Groups 7.x-2.7 and Organic groups subgroups 7.x-2.0-beta1

# Answer
> 0 votes
I managed to use make a custom rules file for OG Subgroups that achieves what I need it to. It adds the rule 'Get subgroup group members from group audience' to a 'Custom' rule group:

This makes the users of the subgroup available to rules. You can then loop through the users and send an email to each of them:

In order to do this I created custom 'og\_subgroups.rules.inc' file in the root of the OG subgroups module. This is the code I used inside it:

```
<?php

/****************
Adds the ability to get the members of the parent group from a subgroup using rules
/****************

/**
 * Implements hook_rules_action_info().
 */
function og_subgroups_rules_action_info() {
  $items = array();

  $items['og_subgroups_get_members'] = array(
    'label' => t('Get subgroup group members from group audience'),
    'group' => t('Custom'),
    'parameter' => array(
      'group_content' => array(
        'type' => 'entity',
        'label' => t('Group content'),
        'description' => t('The group content determining the group audience.'),
      ),
    ),
    'provides' => array(
      'group_members' => array('type' => 'list<user>', 'label' => t('List of subgroup members')),
    ),
    'base' => 'og_subgroups_rules_get_members',
    'access callback' => 'og_subgroups_rules_integration_access',
  );

  return $items;
}

/* NEW FUNCTION ************************************************/

// This callback creates the hashed string by using the parameters provided through rules' UI
function og_subgroups_rules_get_members($group_content) {

// get the nid from the passed value of the content being added
$nid = $group_content->nid->value();

// trying to manually call the get inherited users function from og_subgroups.common.inc
$inherited_users = _og_subgroups_get_inherited_users("node", $nid);

$members = array();

foreach ($inherited_users as $inherited_uid => $data) {
  // Get the group members the group content belongs to.

  $user=user_load($inherited_uid);

  // push the returned user to the array of members
  array_push($members, $user);

}

// return the users
  return array('group_members' => $members);

}

/**
 * OG Rules integration access callback.
 */
function og_subgroups_rules_integration_access($type, $name) {
  // Grant everyone access to conditions.
  return $type == 'condition' || user_access('administer group');
}

```

For those of you who prefer patches here is the patch I created: Patch on drupal.org

---
Tags: rules, organic-groups
---


# Question
Title: OG Subgroups - call function _og_subgroups_get_inherited_users
I am trying to create a custom rule for OG Subgroups to email the members of a subgroup when content is added to it.

In og\_subgroups.common.inc I can see the function I wish to use to return the inherited users of a subgroup

```
function _og_subgroups_get_inherited_users($group_type, $group_id, $states = array(OG_STATE_ACTIVE))

```

In my custom rule action I'm not sure what I should be passing to the function as $group\_type and $group\_id parameters. I have tried things like "node" and the NID of the group:

```
$array = _og_subgroups_get_inherited_users("node", 27);

```

Once I get it working with a hardcoded node e.g. node 27 I will then try to pass the details of the parent groupd that content has been added to.

I'm using OG Subgroups 7.x-2.0-beta1. For the full background into why I'm creating this custom rule action you can see my original drupal answers question

# Answer
I was able to solve this by creating a custom og\_subgroups.rules.inc file. For details of this see my answer in: Email all Organic Group members when a subgroup is created

The line in question above needed to be:

```
$inherited_users = _og_subgroups_get_inherited_users("node", $nid);

```
> 0 votes

---
Tags: rules, organic-groups
---


# Question
Title: Display entity images with thumbnails and 1 large image
I want to attach multiple images to custom entity (commerce product), and display them as follow: 1 large image, and list of thumbnails, user can click on thumbnail thus changing large image.

I found and plan to use the library http://www.elevateweb.co.uk/image-zoom/examples#gallery-lightbox

So my steps:

1. create subtheme of bootstrap theme
2. add field "images" to the commerce product entity
3. write twig file to display images

Is it correct path? or maybe there is better solution? better library?

With image zoom, I need to get output like this

```
<img id="img_01" src="small/image1.jpg" data-zoom-image="large/image1.jpg"/>

<div id="gal1">

  <a href="#" data-image="small/image1.jpg" data-zoom-image="large/image1.jpg">
    <img id="img_01" src="thumb/image1.jpg" />
  </a>

  <a href="#" data-image="small/image2.jpg" data-zoom-image="large/image2.jpg">
    <img id="img_01" src="thumb/image2.jpg" />
  </a>

</div>

```

# Answer
> 3 votes
```
<?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Field\FieldFormatter\SlickMyentityGalleryFormatter.
 */

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Html;

/**
 * @FieldFormatter(
 *   id = "slick_myentity_gallery",
 *   label = @Translation("Slick Myentity Gallery"),
 *   field_types = {
 *     "image"
 *   }
 * )
 */
class SlickMyentityGalleryFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'visible_slides' => 3,
      'image_style' => 'thumbnail',
      'arrows' => TRUE,
      'dots' => TRUE,
      'fade' => FALSE,
      'standalone_image' => TRUE,
      'standalone_location' => 'above',
      'standalone_style' => 'xlarge',
      'vertical' => FALSE,
      'lazy_load' => 'ondemand',
      'hide_single_navigator' => TRUE
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = parent::settingsForm($form, $form_state);
    $field_name = $this->fieldDefinition->getName();

    $image_style_entities = \Drupal::entityManager()
      ->getStorage('image_style')
      ->loadMultiple();

    $image_styles = array_map(function($image_style) {
      return $image_style->label();
    }, $image_style_entities);

    $image_styles = ['_original' => '- ' . $this->t('Original') . ' -'] + $image_styles;

    $element['visible_slides'] = [
      '#type' => 'number',
      '#title' => $this->t('Number of visible slides'),
      '#default_value' => $this->getSetting('visible_slides'),
      '#min' => 1,
      '#max' => 10,
      '#description' => $this->t('Number of images visible at once.')
    ];

    $element['image_style'] = [
      '#type' => 'select',
      '#title' => $this->t('Image style'),
      '#default_value' => $this->getSetting('image_style'),
      '#options' => $image_styles,
      '#description' => $this->t('Image style to display the images with.')
    ];

    $element['arrows'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Show arrows'),
      '#default_value' => $this->getSetting('arrows'),
      '#description' => $this->t('Display the navigation arrows.')
    ];

    $element['dots'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Paging'),
      '#default_value' => $this->getSetting('dots'),
      '#description' => $this->t('Display the paging dots.')
    ];

    $element['fade'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Fade'),
      '#default_value' => $this->getSetting('fade'),
      '#description' => $this->t('Fade between transitions.')
    ];

    $element['vertical'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Vertical slider'),
      '#default_value' => $this->getSetting('vertical'),
      '#description' => $this->t('Display slider vertically instead of horizontally.')
    ];

    $element['lazy_load'] = [
      '#type' => 'select',
      '#title' => $this->t('Lazy load'),
      '#options' => [
        'none' => '- ' . $this->t('None') . ' -',
        'ondemand' => $this->t('On demand'),
        'progressive' => $this->t('Progressive')
      ],
      '#default_value' => $this->getSetting('lazy_load'),
      '#description' => $this->t('Lazy load the images to increase page performance.')
    ];

    $element['standalone_image'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Standalone active image'),
      '#default_value' => $this->getSetting('standalone_image'),
      '#description' => $this->t('Display the active image separately.')
    ];

    $element['standalone_style'] = [
      '#type' => 'select',
      '#title' => $this->t('Standalone image style'),
      '#default_value' => $this->getSetting('standalone_style'),
      '#options' => $image_styles,
      '#description' => $this->t('Image style to display the standalone image with.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    $element['standalone_location'] = [
      '#type' => 'select',
      '#title' => $this->t('Standalone image location'),
      '#default_value' => $this->getSetting('standalone_location'),
      '#options' => [
        'above' => $this->t('Above'),
        'below' => $this->t('Below'),
        'left' => $this->t('Left'),
        'right' => $this->t('Right')
      ],
      '#description' => $this->t('Display slider vertically instead of horizontally.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    $element['hide_single_navigator'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Hide single item carousel'),
      '#default_value' => $this->getSetting('hide_single_navigator'),
      '#description' => $this->t('If standalone image is displayed and there is only one image, the carousel will be hidden.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    return $element;
  }

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

    if ($this->getSetting('standalone_image')) {
      $standalone_style = $this->getSetting('standalone_style');
      if ($standalone_style == '_original') {
        $summary[] = $this->t('Display standalone image without image style.');
      } else {
        $style = \Drupal::entityManager()->getStorage('image_style')->load($standalone_style);
        $summary[] = $this->t('Display standalone image with %style image style.', [
          '%style' => $style ? $style->label() : 'original'
        ]);
      }

      $location = $this->getSetting('standalone_location');
      $location_labels = [
        'above' => $this->t('above'),
        'below' => $this->t('below'),
        'left' => $this->t('left'),
        'right' => $this->t('right')
      ];
      $summary[] = $this->t('Standalone image position: %position.', [
        '%position' => $location_labels[$location]
      ]);

      if ($this->getSetting('hide_single_navigator')) {
        $summary[] = $this->t('Hide carousel with single image.');
      }
    }

    $image_style = $this->getSetting('image_style');
    if ($image_style == '_original') {
      $summary[] = $this->t('Display images without image style.');
    } else {
      $style = \Drupal::entityManager()->getStorage('image_style')->load($image_style);
      $summary[] = $this->t('Display images with %style image style.', [
        '%style' => $style ? $style->label() : 'original'
      ]);
    }

    if ($this->getSetting('vertical')) {
      $summary[] = $this->t('Display slider vertically.');
    }

    switch ($this->getSetting('lazy_load')) {
      case 'ondemand':  $summary[] = $this->t('Use <em>on demand</em> lazy loading.'); break;
      case 'progressive':  $summary[] = $this->t('Use <em>progressive</em> lazy loading.'); break;
    }

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    // Skip if there are no items to display.
    if ($items->isEmpty()) {
      return [];
    }

    $standalone_html_id = Html::getUniqueId($items->getName() . '-standalone');
    $carousel_id = Html::getUniqueId($items->getName() . '-nav');
    $lazy_load = $this->getSetting('lazy_load');
    $use_lazy_load = $lazy_load != 'none';

    // Retrieve file IDs.
    $fids = [];
    foreach ($items->getIterator() AS $item) {
      $fids[] = $item->get('target_id')->getValue();
    }

    // Load files so we can get their URIs.
    $files = \Drupal::entityManager()->getStorage('file')->loadMultiple($fids);

    // Make a list of all URIs.
    $uris = array_map(function($file) {
      return $file->getFileUri();
    }, $files);

    // Set up the render element.
    $element = [
      '#attached' => [
        'library' => [
          'mymodule/slick_myentity_gallery'
        ]
      ]
    ];

    // Create carousel for the standalone image if needed.
    if ($this->getSetting('standalone_image')) {
      $element['#attributes']['class'][] = 'with-standalone';

      $element['standalone'] = [
        '#theme' => 'item_list',
        '#items' => [],
        '#weight' => 0,
        '#attributes' => [
          'id' => $standalone_html_id,
          'class' => [
            'slick-myentity-gallery',
            'slider-standalone',
            'location-' . $this->getSetting('standalone_location')
          ],
          'data-slick-settings' => json_encode([
            'slidesToShow' => 1,
            'slidesToScroll' => 1,
            'arrows' => FALSE,
            'fade' =>  TRUE,
            'asNavFor' => '#' . $carousel_id,
            'lazyLoad' => $lazy_load,
            'mobileFirst' => TRUE
          ])
        ]
      ];

      foreach ($uris AS $uri) {
        $element['standalone']['#items'][] = $this->getImageItem($uri, $this->getSetting('standalone_style'), $use_lazy_load);
      }
    }

    // Create the main image carousel.
    $element['carousel'] = [
      '#theme' => 'item_list',
      '#items' => [],
      '#weight' => 1,
      '#attributes' => [
        'id' => $carousel_id,
        'class' => [
          'slick-myentity-gallery',
          'slider-navigation',
          $this->getSetting('vertical') ? 'vertical' : 'horizontal'
        ],
        'data-slick-settings' => json_encode([
          'slidesToShow' => (int) $this->getSetting('visible_slides'),
          'slidesToScroll' => 1,
          'asNavFor' => '#' . $standalone_html_id,
          'dots' => (bool) $this->getSetting('dots'),
          'arrows' => (bool) $this->getSetting('arrows'),
          'fade' => (bool) $this->getSetting('fade'),
          'vertical' => (bool) $this->getSetting('vertical'),
          'verticalSwiping' => (bool) $this->getSetting('vertical'),
          'focusOnSelect' => TRUE,
          'lazyLoad' => $lazy_load,
          'mobileFirst' => TRUE,
          'rtl' => \Drupal::languageManager()->getCurrentLanguage()->getDirection() == 'rtl',
          'infinite' => FALSE
        ])
      ]
    ];

    foreach ($uris AS $uri) {
      $element['carousel']['#items'][] = $this->getImageItem($uri, $this->getSetting('image_style'), $use_lazy_load);
    }

    // Display the carouse first if the standalone image is visible and
    // is positioned below the carousel or to the right next to it.
    if ($this->getSetting('standalone_image') && in_array($this->getSetting('standalone_location'), ['below', 'right'])) {
      $element['carousel']['#weight'] = -1;
    }

    // Hide navigator if standalone image is displayed and there is only
    // one image.
    if ($this->getSetting('standalone_image') && $this->getSetting('hide_single_navigator') && $items->count() == 1) {
      unset($element['carousel']);
    }

    return [$element];
  }

  /**
   * Helper method to generate image for provided style
   * that takes the lazy load setting into account.
   *
   * @param string $uri
   *   The original image uri.
   * @param string $image_style
   *   The image style name.
   * @param bool $lazy_load
   *   If TRUE the lazy slick load image will be returned.
   *
   * @return array
   *   Renderable array for a single image.
   */
  function getImageItem($uri, $image_style, $lazy_load = FALSE) {
    if ($lazy_load) {
      $style = \Drupal::entityManager()
        ->getStorage('image_style')
        ->load($image_style);

      return [
        '#type' => 'inline_template',
        '#template' => '<img data-lazy="{{ path }}" />',
        '#context' => [
          'path' => $style ? $style->buildUrl($uri) : file_create_url($uri)
        ]
      ];
    } else {
      return [
        '#theme' => 'image_style',
        '#uri' => $uri,
        '#style_name' => $image_style
      ];
    }
  }

}

(function($) {

  Drupal.behaviors.slickMyentityGallery = {
    attach: function(context) {
      // Initialize the Slick Carousel on all appropriate elements.
      $('.slick-myentity-gallery[data-slick-settings]', context).once('slick-myentity-gallery-init').each(function() {
        var $this = $(this);
        var settings = $this.data('slick-settings');

        // Adjust behavior if this is a Field API field.
        var $fapi_items = $this.find('.field__item');
        if ($fapi_items.length != 0) {
          $fapi_items.parent().slick( settings );
        } else {
          $this.slick( settings );
        }
      });
    }
  }

})(jQuery);

```

---
Tags: theming, commerce, 8
---


title: Contextual filter : Override Title

text:
# Question
Title: Contextual filter : Override Title
The content architecture of the site which I am working on is something like:-

1. Song - Content type
2. Genre - Vocabulory

Song has an entity reference field which points to the terms in "Genre" vocabulary.

**Genre** field is added in the view which lists **Songs** content.
The field result has been rewritten as link which points to the URL pattern : `songs/<genre-name>` (`[field-genre]` was used).

The path `songs/%` is a separate view page, which is supposed to take the "genre name" as contextual filter, and show songs of that particular genre.

Here the url gets the taxonomy term name but the title gives %2 instead of the name

Override title is %2

The view is working fine but I am not able to replace the title.

# Answer
I tried %1 in the override title and it worked.
> 0 votes

---
Tags: views
---


# Question
Title: Form states with "and" and "or" conditions
Using form API in D7, I need to use from states to setup a visible input with this condition :

```
field1 = value A AND (field2 = value B OR value C OR value D)

```

Something like this, but this example doesn't run :

```
'#states' => array(
      'visible' => array(
        array(':input[name="question_inhabitant_type"]' => array('value' => 'owner')),
        'AND',
        array(':input[name="question_building_type"]' => array('value' => 'house100')),
        'OR',
        array(':input[name="question_building_type"]' => array('value' => 'house150')),
        'OR',
        array(':input[name="question_building_type"]' => array('value' => 'house200')),
      ),
    ),

```

Any idea?

# Answer
You can use `or/xor` in form states. For `and`, continuation of the conditions is enough. For example your code the condition can be written as:

```
'#states' => array(
  'visible' => array(
    array(':input[name="question_inhabitant_type"]' => array('value' => 'owner')),
    array(
      array(':input[name="question_building_type"]' => array('value' => 'house100')),
      'or',
      array(':input[name="question_building_type"]' => array('value' => 'house150')),
      'or',
      array(':input[name="question_building_type"]' => array('value' => 'house200')),
    ),
  ),
),

```

**Note:** jQuery 1.7 doesn't support OR/XOR's for `#states`. So, make sure you have latest jQuery version on you site (\>1.7).

Unfortunately the above code didn't worked as expected. Please help through your comments to correct it. Also meanwhile you can try this code:

```
'#states' => array(
  'visible' => array(
    ':input[name="question_inhabitant_type"]' => array('value' => 'owner'),
    ':input[name="question_building_type"]' => array(
      array('value' => 'house100'),
      array('value' => 'house150'),
      array('value' => 'house200'),
    ),
  ),
),

```
> 6 votes

---
Tags: 7, javascript
---


# Question
Title: Change Content region width when Sidebar has content?
hello i have what i feel is (hopefully) an easy problem to solve. Basically i have my regions defined which is fine but i have my sidebar that i want to display on the right of the content region. if the sidebar has blocks the 'Content' region should gain a class that adjusts the width to allow the sidebar to display, if no content in sidebar then the content region should display in full width. In the page template i have this so far

```
<?php if ($page['sidebar_first']): ?>
         <aside id="sidebar-first" role="complementary" class="sidebar clearfix">
           <?php print render($page['sidebar_first']); ?>
         </aside> <!-- /#sidebar-first -->
         <?php endif; ?>
         <?php if (!empty($page['sidebar_first']): ?>
         <div class="content-region-sidebar-sibling">
         <?php print render($page['content']); ?>
         </div>
         <?php else: ?>
           <?php print render($page['content']); ?>
         <?php endif; ?>

```

yet the line for
\<`?php (!empty($page['sidebar_first']); ?>` continues to return TRUE whether the region has content or not.. i need to know how to fix this syntax so that if my sidebar region is with blocks, the content region will receive the class assigned(which is how i'm editing the width) and will not get the class if there is no sidebar blocks active on that page. Can anyone help?

# Answer
`$page['sidebar_first']` is an empty array when you have no content in that region. So it is defined and the condition

```
if ($page['sidebar_first']):

```

is true even if you have no block in the sidebar. So

```
print render($page['sidebar_first'])

```

gets executed and, after the rendering, `$page['sidebar_first']` will look something like

```
array(
  '#printed' => true,
  '#children' => '',
)

```

meaning that it's no longer empty and the condition `if (!empty($page['sidebar_first']):` will be met in any case. You may want to rewrite your code to something like

```
      <?php if (!empty($page['sidebar_first']): ?>
       <aside id="sidebar-first" role="complementary" class="sidebar clearfix">
         <?php print render($page['sidebar_first']); ?>
       </aside> <!-- /#sidebar-first -->
       <div class="content-region-sidebar-sibling">
         <?php print render($page['content']); ?>
       </div>
     <?php else: ?>
       <?php print render($page['content']); ?>
     <?php endif; ?>

```
> 1 votes

# Answer
This is a bit old but i had the same problem. This is how i made it work.

```
  <?php if (count(block_get_blocks_by_region('sidebar_first')) > 1): ?>
   <aside id="sidebar-first" role="complementary" class="sidebar clearfix">
     <?php print render($page['sidebar_first']); ?>
   </aside> <!-- /#sidebar-first -->
   <div class="content-region-sidebar-sibling">
     <?php print render($page['content']); ?>
   </div>
 <?php else: ?>
   <?php print render($page['content']); ?>
 <?php endif; ?>

```

Count is \> 1 because if a block exists then this array also contains an index "#sorted" with it. So this could be 0 if no block is assigned to this region or 2 or more if one or more blocks are assigned.

Also this works fine with block region demonstration which were failing when i used

```
!empty($page['sidebar_first']):

```

or

```
if ($page['sidebar_first']):

```
> 0 votes

---
Tags: blocks, theming
---


# Question
Title: What is the basic use of the breakpoints.yml file?
What's the purpose of breakpoints defined in \`breakpoints.yml?

Why are the media queries defined in breakpoints.yml, and not in CSS files?

# Answer
> 8 votes
There is no way to use the breakpoints defined in a breakpoints.yml file in CSS without pre or post-processing. Since we don't use processors for styling in core, the breakpoints are still hard coded in the CSS files. In a custom theme you are however free to use tools like Gulp or Grunt and it would theoretically be possible to use the breakpoints.yml input for your CSS generation.

Currently the breakpoints.yml is mainly interesting for JavaScript (JS). Have for example a look at the Toolbar module in core. The breakpoint info is added to the 'drupalSettings' JS object in 'src/Element/Toolbar.php' like so:

```
$breakpoints = static::breakpointManager()->getBreakpointsByGroup('toolbar');
if (!empty($breakpoints)) {
  $media_queries =  array();
  foreach ($breakpoints as $id => $breakpoint) {
    $media_queries[$id] = $breakpoint->getMediaQuery();
  }

  $element['#attached']['drupalSettings']['toolbar']['breakpoints'] = $media_queries;
}

```

Then in JS the run-time settings as defined above are read in.

```
var options = $.extend(
  {
    breakpoints: {
      'toolbar.narrow': '',
      'toolbar.standard': '',
      'toolbar.wide': ''
    }
  },
  drupalSettings.toolbar
);

```

Later an event listener is added per breakpoint so that 'something' can be done when the screen size changes.

```
for (var label in options.breakpoints) {
  if (options.breakpoints.hasOwnProperty(label)) {
    var mq = options.breakpoints[label];
    var mql = Drupal.toolbar.mql[label] = window.matchMedia(mq);
    mql.addListener(Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label));
  }
}

```

In the event of a change different actions can be undertaken per breakpoint.

```
Drupal.toolbar = {
  mediaQueryChangeHandler: function (model, label, mql) {
    switch (label) {
      case 'toolbar.narrow':
        model.set({
          isOriented: mql.matches,
          isTrayToggleVisible: false
        });
        break;

      case 'toolbar.standard':
        // Logic
        break;

      case 'toolbar.wide':
        // Logic
        break;

      default:
        break;
    }
  }
};

```

**Note**: the code examples are taken from the Drupal Toolbar module and stripped. Use as inspiration, not as functional code.

A good explanation about using JS mediaQueries in general can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/Media\_Queries/Testing\_media\_queries

---
Tags: 8, theming
---


# Question
Title: How to make Taxonomy replacement tokens available to the HTML email action in Rules?
I have created a rule for a client that triggers an HTML email to them every time an authenticated site visitor downloads one of their PDF brochures.

I have no problem including things such as the username, email address, filename and other info, but the client wants to have the "vertical" of the PDF displaying as additional information on the outgoing email.

The PDF's are uploaded as a unique content type and are categorised by using taxonomy terms through a select field.

Unfortunately, when editing the HTML email action element on the rule, there are a whole bunch of replacement tokens, except any related to taxonomy. I tried to "wing it" and create a taxonomy token, but of course this did not work and it seems logical that there would naturally be a disconnect here as how would the rule know to relate the correct term to the file being downloaded.

Any advice with regards to possible workarounds?

# Answer
Make sure to add a Rules condition `Entity has field` (related to your field you indicated via the "**through a select field...**" in your question).

That's also what is mentioned in the Rules UI, e.g. 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')*".

Your question seems to be related to using such field in a Rules Action (instead of a Rules Condition). However, have a look at the sample rule in included in my answer to "How to specify a Rules condition related to select list values?". That rule doesn't have a "Rules Action" that uses that field (as you seem to try to do). Though using the Rules UI to (eg) edit the message I'd want to display in my sample rule, within the list of tokes available for ***Replacement patterns for created content***, one of them is actually `[node:field-optionlist]`. And the 'created content' in my case is because of the Rules Event `node_insert` that's used in my sample rule.

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.

**PS**: To have such field available to use it in any other Rules Condition also, I always add such `Entity has field` condition BEFORE any other Rules Conditions, if any.
> 0 votes

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


# Question
Title: Best way to add fields to the output of a View
I have a View which lists contents. I have a few fields which are composite and have a somehow convoluted logics. What I do is to add some "dummy" fields (for example, the nid of content, or the rf (reference) of product) to the View, and then in `hook_views_prerender` I modify the value by the logic. For example:

```
$brand = $view->result[$key]->taxonomy_term_data_field_data_field_brand_name;
if($brand == WHATEVER){
   $view->result[$key]->field_field_field_rf_product_3[0]["rendered"]["#markup"] = function_to_substitute_complicated_value($parameters);
 ...
 }

```

Now, is it good idea to have this dummy field, **field\_rf\_product\_3**, or would it be better to create a new field programmaticaly, and if so, how could it be done to be added at the proper place (after a given rendered field) in the View output?

# Answer
Basically you have two options to do this elegantly.

1. Use the computed field module (it also includes the storing of the results in the database to save on heavy SQL queries as mentioned in the comments). It comes with a lot of documentation and examples at the bottom of that page.

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

2. Write a custom views field handler (example is for Drupal 7 only!). In drupal 8 some functions like hook\_views\_api() have been removed and the info file has changed.

This is less flexible and will result in a specific field to choose when building a view. However sometimes less flexible can be desirable.

In order to do this you need to write a custom module. Consisting the following folder and files:

* module\_name
    + module\_name.info
    + module\_name.module
    + views
        - module\_name.views.inc
        - module\_name\_handler\_field\_custom\_field.inc

The .info file describes the module:

```
name = Custom Views field
description = Provides an additional field to Views
core = 7.x
package = Views
dependencies[] = views
files[] = views/module_name_handler_field_custom_field.inc

```

The .module file contains the module, which in this case is only a function to let Views know where to look for its files.

```
/**
 * Implements hook_views_api().
 */
function module_name_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'module_name') . '/views',
  );
}

```

The file `module_name.views.inc` performs the logic for Views. If you define a new entity, use `hook_views_data()`. If you alter an existing entity such as a user or a node, use `hook_views_data_alter()` but also look at the example code of `hook_views_data()`.

In order to create a new field based on another field, you can do something like this:

```
/**
 * Implements hook_views_data_alter().
 *
 * Defines a new field with content built by the module_name_handler_field_custom_field class.
 * @see hook_views_data()
 */
function hook_views_data_alter(&$data) {
 // This example adds an example field to the users table.
  $data['node']['example_field'] = array(
    'title' => t('Example field'),
    'help' => t('Some example content'),
    'real field' => 'field_existing_base_field', // Enter the base fields system name here.
    'field' => array(
      'handler' => 'module_name_handler_field_custom_field',
    ),
  );
}

```

Finally the handler, which composes the field. Here we can alter the output of the field using the real field we defined above as input.

```
class module_name_handler_field_custom_field extends views_handler_field {
  /**
   * Render a computed field value (multiplied by 5).
   */
  function render($values) {
    // Load real field value.
    $real_value = $this->get_value($values);
    // Generate new value.
    $value = function_to_substitute_complicated_value($real_value);
    return $this->sanitize_value($value);
  }
}

```
> 7 votes

---
Tags: entities, views
---


# Question
Title: How to join my custom table data to a node using nid
My module implements a custom content type, let's say **Magazines**.
This content type will have just title and tags field in order to use taxonomy from Drupal.
I have a custom table `custom_magazines` where I store several attribute fields to the magazines.
The custom\_magazines table will have a `nid` field where I reference the Drupal node.
How do I handle a form to mix the node fields (title and tags) and `custom_magazines` field?
How do I insert or update the data in both node and `custom_magazines` tables?
I'm using Drupal 7. I know about cck and eck modules, but I don't want to create an additional table for my custom attributes.
Is there an example where I can see this working?

# Answer
The "Drupal Way" would be using fields for your additional data instead of a custom table. This would imply the following benefits:

* you could easily query the contents using entityfieldqueries or Views
* the fields would show up/being saved within your content type's edit form without any additional coding
* the additional information would load together with the content type when using node\_load or node\_load\_multiple respectively.

However, if you'd like to stick to your architecture, you can query the database using db\_select for fetching information:

```
$query = db_select('node', 'n');

$query->join('custom_magazines', 'm', 'n.nid = m.nid'); //JOIN node with magazines
$query->condition('type', 'magazines')

  ->fields('n')
  ->fields('m');

$result = $query->execute();

```

Please note that this way makes it harder to handle node information (as your taxonomy field contents) together with your additional information. You might need to load your nodes anyway or join the query with the field contents as well.

You'd also have to add the required form fields to your content type's edit form manually, and implement a custom submit callback for saving the form values to your custom table.

Additionally you should consider implementing hook\_node\_insert, hook\_node\_update and hook\_node\_delete to keep your additional data in sync with your custom content type. (All steps that can be omitted using fields.)
> 0 votes

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