# Question
Title: How to count the number of consecutive days on which verified users accessed the website?
My main problem is very similar to How to grant userpoints to users who perform a login 5 days consecutively?: I would like to keep track of the number of consecutive days on which verified users accessed the website. Therefore, I added an integer user field *Consecutive days* and created the following Rule that hooks into "visiting the website" (see How to hook into "visiting the website"?):

```
{ "rules_extra_consecutive_day_online" : {
    "LABEL" : "Extra consecutive day online",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-user:field-consecutive-days" ],
              "value" : "0"
            }
          },
          { "AND" : [
              { "data_is" : {
                  "data" : [ "site:current-user:last-access" ],
                  "op" : "\u003C",
                  "value" : "today midnight -1 second"
                }
              },
              { "data_is" : {
                  "data" : [ "site:current-user:last-access" ],
                  "op" : "\u003E",
                  "value" : "yesterday midnight"
                }
              }
            ]
          }
        ]
      }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "site:current-user:field-consecutive-days" ],
            "op" : "+",
            "input_2" : "1"
          },
          "PROVIDE" : { "result" : { "new_streak" : "New streak" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-consecutive-days" ],
          "value" : [ "new-streak" ]
        }
      },
      { "schedule" : {
          "component" : "rules_reset_consecutive_days",
          "date" : "+2 days midnight",
          "param_user" : [ "site:current-user" ]
        }
      },
    ]
  }
}

```

The scheduled Rules component at the end of the Rule resets *Consecutive days* to `0` if necessary:

```
{ "rules_reset_consecutive_days" : {
    "LABEL" : "Reset consecutive days",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [
      { "data_is" : {
          "data" : [ "user:last-access" ],
          "op" : "\u003C",
          "value" : "yesterday midnight -1 second"
        }
      }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "user:field-consecutive-days" ],
          "value" : "0"
        }
      }
    ]
  }
}

```

This seems to work relatively well, but there is a catch: the *Last access* field is not updated at every page request. As a result, users can increase their *Consecutive days* during a few minutes right after midnight by refreshing the page again and again.

How can I fix this issue? Should I override the *Last access* field at every page request or is there an alternative way to correctly update *Consecutive days*?

# Answer
Overriding the built-in *Last access* field is not possible with Rules, so I added a new user Date field *Last day online* that stores a day, month and year. Recall that I had already created another user integer field *Consecutive days*. Here is the magical Rule:

```
{ "rules_extra_consecutive_day_online" : {
    "LABEL" : "Extra consecutive day online",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1", "3" : "3" } }
        }
      },
      { "OR" : [
          { "data_is" : { "data" : [ "site:current-user:field-consecutive-days" ], "value" : "0" } },
          { "data_is" : {
              "data" : [ "site:current-user:field-last-day-online" ],
              "value" : "yesterday midnight"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "site:current-user:field-consecutive-days" ],
            "op" : "+",
            "input_2" : "1"
          },
          "PROVIDE" : { "result" : { "new_consecutive_days" : "New consecutive days" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-consecutive-days" ],
          "value" : [ "new-consecutive-days" ]
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-last-day-online" ],
          "value" : "today midnight"
        }
      },
      { "schedule" : {
          "component" : "rules_reset_consecutive_days",
          "date" : "+2 days midnight",
          "param_user" : [ "site:current-user" ]
        }
      }
    ]
  }
}

```

This is what the Rule does in words:

* First, check that the current user is verified, and make sure the user's *Consecutive days* field is zero or the user's *Last day online* is yesterday.
* If the above requirements are satisfied, then increase the *Consecutive days*, change the *Last day online* to today and schedule the component *Reset consecutive days*.

Underneath is an export of the mentioned Rules component. It resets the *Consecutive days* field if the *Last day online* field is less than yesterday (which means that the user was not online on at least one day).

```
{ "rules_reset_consecutive_days" : {
    "LABEL" : "Reset consecutive days",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [
      { "data_is" : {
          "data" : [ "user:field-last-day-online" ],
          "op" : "\u003C",
          "value" : "yesterday midnight"
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "user:field-consecutive-days" ], "value" : "0" } }
    ]
  }
}

```
> 1 votes

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


# Question
Title: How can I get the form validated with AJAX?
I'm building pretty simple forms loaded with AJAX and displayed with Foundation Reveal. I can get the form submission to work with AJAX, and update the markup inside the reveal, but with the AJAX-powered submission button, the validation method is not executed.

Why? How can I get the form validated with AJAX?

I just want the normal form validation process, where I can add my own validation to `::validateForm` and then pass control to my AJAX form submission handler.

```
$form['submit'] = [
  '#type' => 'submit',
  '#value' => 'Tallenna',
  '#ajax' => [
    'callback' => '::ajaxFormSubmitHandler'
  ]
];

```

I tried with `$form['#validate'] = array('::validateForm');`, but it doesn't work. I also tried calling `Form::validateForm($form, $form_state)` in the submission handler with the following code.

```
Form::validateForm($form, $form_state);
if ($form_state->hasAnyErrors()) {
  $form_state->setRebuild();
  $errors = $form_state->getErrors();
  return($form);
}
else {
  $form_state->setRebuild(FALSE);
}

```

I can set up the callback for a single element.

```
$form['field_asiakkaan_nimi'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Asiakkaan nimi'),
  '#required' => TRUE,
  '#ajax' => [
    'callback' => array($this, 'validateNimiAjax'),
    'event' => 'change',
  ],
  '#suffix' => '<span class="nimi-valid-message"></span>'
];

```

I can use that callback for the field processing.

```
  public function validateNimiAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $message = 'Nimi validoitu!';
    $response->addCommand(new HtmlCommand('.nimi-valid-message', $message));
    return $response;
  }

```

This doesn't seem to be the proper way to go about this.

I am also getting this error:

> The form has become outdated. Copy any unsaved work in the form below and then reload this page.

How can I get AJAX delivered forms validated and processed?

# Answer
Here is a very basic example that will validate your data. It should give you an idea of how to handle it:

```
class myForm extends FormBase {
  public function getFormId() {
    return 'my_form';
  }

  public function buildForm(array &$form, FormStateInterface $form_state) {
    $form['#prefix'] = '<div id="my_form_wrapper">';
    $form['#suffix'] = '</div>';
    $form['some_text'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Enter a value'),
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
        'wrapper' => 'my_form_wrapper',
        'callback' => '::ajaxCallback',
      ],
    ];

    return parent::buildForm($form, $form_state);
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    if($form_state->getValue('some_text') != 'Awesome')  {
      $form_state->setError($form['some_text'], $this->t('Please enter "Awesome"'));
    }
    parent::validateForm($form, $form_state);
  }

  public function ajaxCallback(array &$form, FormStateInterface $form_state) {
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('The form was submitted'));

    parent::submitForm($form, $form_state);
  }
}

```

With the above code, the form is built, and the ajax is set. Note that no validation needs to be set, as the validateForm() method will be called automatically if it exists. When the ajax is executed, it will always call the validate form method first. If validation is passed, then the submitForm() method will be called, but if validation is failed, it will not. Finally the ajax callback is called and the form is returned.
> 5 votes

# Answer
This look like correct, just try to use an ID instead of a class

```
  '#ajax' => [
    'callback' => '::ajaxFormSubmitHandler'
  ]

```

and

```
//$response->addCommand(new HtmlCommand('.nimi-valid-message', $message));
$response->addCommand(new HtmlCommand('#nimi-valid-message', $message));

```

Example: http://www.drupal8.ovh/en/tutoriels/26/ajax-form
> 0 votes

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


# Question
Title: Module to Automatically Create URLs from Article Titles for Drupal 8
I am wondering if there exists a module that would automatically create "nice" URLs using titles of posts in Drupal 8. I am aware of aliasing; however, if there is a lot of posting activity on the site, it can become a substantial time sink.

**Example:** (something along these lines would suffice)

**Title of a post:**

> How to create neat URLs in Drupal 8

**corresponding URL:**

> www.example.com/how-to-create-neat-urls-drupal-8

# Answer
> 3 votes
Yes, just use the Pathauto module with Token. Pretty straightforward.

---
Tags: uri
---


# Question
Title: How to add cursor to text field on page load?
I'm working on an attendance site in Drupal 7 and I use a reference entity field to accept scanned ID badges. Once the ID number is saved in the field the page reloads.

I'd like to have a cursor appear in the field after the page is reloaded. I know this can be done with java script but I haven't been able to get it to work. I added `scripts[] = scripts.js` in the `.info` of the theme and created a `.js` file with the same name in my theme directory.

```
(function setFocus() {
document.getElementById("field_student").focus();

```

}

```
function select() {
    document.getElementById("field_student").select();

```

}

I'm not very adept at javascript and I'd appreciate it if someone could point me in the right direction.

# Answer
You can actually do it with html autofocus now - no need for JS.

You should be able to do it with this:

```
<?php
  // inside a hook_form_alter()

  $form['field'] = [
    '#type' => 'textfield',
    '#attributes' => array('autofocus' => TRUE)),
  ];

```
> 3 votes

---
Tags: javascript
---


# Question
Title: Avoid duplicate product while using variations
I am new to drupal and fetching Drupal commerce variations from Views and the products are getting duplicated what would be the best way to avoid duplicate when using product variations. Here are the screenshots from views http://puu.sh/vn1Po/75e158f5c5.png Any help is really appreciated.

# Answer
> 3 votes
It sounds like you reference multiple products per display node, so adding that relationship results in multiple rows. A real easy solution is to filter by the delta value from your product reference field so that only the first referenced product results in a row being shown. Ideally we'd add another filter that let you filter by the *default* delta value, as that can differ from 0 if altered via code.

The filter you're looking for should read something like: **Content: Product (field\_product:delta)** and you should set the filter value to 0. No need to expose it.

# Answer
> 0 votes
You may get it to work using the Views Distinct module. From its project page:

> Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.

---
Tags: commerce
---


# Question
Title: Node Referenced entity fields not showing in views?
I have created a content types "**author detail and blog content**".

**In which author detail is having fields**

1)author name

2)author picture

3)author designation

4)about author

Then i created a field "author details(node reference field)" in **blog content**

After creating a view block none of fields of **author details**(reference entity) is showing and also this block should be contexual filter based.

I have tried to achieve it by reading articles available on internet,Only one field is holding all the fields value ,i want to show field value in such sequence so that i can give specific class to each and every field.

1)author name

2)author picture

3)author designation

4)about author

How to achieve?

# Answer
> 1 votes
For displaying the authors details within a Twig template see How can you render fields from an entity reference in node templates? \[Drupal 8\] \- for creating a views block this page might help you: https://www.drupal.org/node/1841004

---
Tags: 8, entities
---


title: Can't get hook_uninstall to trigger

text:
# Question
Title: Can't get hook_uninstall to trigger
In mymodule.install i try to implement a hook\_uninstall call, but it never triggers. What am I doing wrong?

```
function hook_uninstall() {
echo "uninstalling";
...more stuff...
}

```

# Answer
> 1 votes
First off, the implementation of a hook never has a name starting with *hook\_*; you always replace *hook\_* with the machine name of the module, followed from an underscore. Similarly, the name of the file containing an implementation of `hook_uninstall()` must be the machine name of the module followed by .install.
So, if you are literally calling the function `hook_uninstall()`, and *mymodule* is not the machine name of your module, Drupal will never consider that function a hook implementation.

Second, if you are using `echo` to check if the hook is being invoked, you will not get any output. Use `watchdog()` (Drupal 7) or `\Drupal::logger($module)->error($message)` (Drupal 8) inside a hook, if you want to verify a hook is invoked.

Third, `hook_uninstall()` is invoked from Drupal only when a module is uninstalled. There is no other way to be sure Drupal is invoking that hook, if not installing and uninstalling the module implementing it. In Drupal 7, don't get confused from disabling a module, and uninstalling it: Disabling a module doesn't cause Drupal to invoke `hook_uninstall()`.

---
Tags: hooks, installation
---


title: Edit meta tag for taxonomy terms

text:
# Question
Title: Edit meta tag for taxonomy terms
I have around 15 categories in my site. I need different meta tags for each category page. How is that possible? I have tried using meta tag context.But it didn't worked. I have these modules enabled: Metatag and Page titles.

# Answer
> 3 votes
Got it! I have found the option to edit the meta tags for taxonomy terms in Admin-\>Structure-\>Taxonomy-\>Category name-\>Edit-\>List Then select the category which you want to edit.

---
Tags: taxonomy-terms, meta-tags
---


# Question
Title: How do I change the transport for remote drush alias calls
We're moving to an environment where our drupal instances will live inside docker containers managed by kubernetes.

Currently I've got scripts for things like checking module security status across large numbers of drupal sites. Basically I maintain a file full of aliases, and I iterate over those. It works well enough.

With the move to kubernetes, what I'd like to happen is that my aliases would somehow specify that the way to call the remote instance is via a kubectl command that effectively invokes drush in the remote container. It looks a lot like an alternative to ssh as the transport.

1. Is something like this possible?
2. OK, so I've got the source code, and anything is presumably possible, but what might a sensible approach look like? What should I look at to get my head around this?

# Answer
It seems that you currently can't change the transport / replace SSH. However, most of the work can be fixed be writing wrapper scripts. Read https://github.com/drush-ops/drush/issues/2367
> 0 votes

---
Tags: drush
---


title: Where can i find buildRow parameter?

text:
# Question
Title: Where can i find buildRow parameter?
in EntityListBuilder::buildRow we can define row like below:

```
$row['title']['data'] = array(
    '#type' => 'link',
    '#title' => $entity->label(),
    '#suffix' => ' ' . drupal_render($mark),
    '#url' => $uri,
  );

```

question is: where can i find list of the options/parameters documentation of this? (#type, #title, what is the other possible option?)

# Answer
> 1 votes
This is the render element Link, which is used to make the title clickable. The non linked version would look like this:

```
$row['title'] = $entity->label();

```

You can use any render element or a nested render array.

# Answer
> 0 votes
I guess you would want to know about Render arrays in Drupal 8.

Generic properties that can be given for a render element can be found here

As mentioned in that page, every element of a type can have some specific properties which have to be figured out individually.

For Ex: Element of type can have title, url while element of type markup can have #markup.

---
Tags: 8, entities
---


# Question
Title: How to apply multiple sort criteria on views?
I have created a view where I used

> Display a specified number of items | 5 items

And I have 2 sort criterias.

> SORT CRITERIA
>
> Add sort criteria
>
> List additional actions Content:
>
> Authored on (desc)
>
> Content: Page Views (desc)

What I want is sort criteria 1 should be applicable on first 3 rendered items, and sort criteria 2 should be applied on next 2 items. So here right now, total 5 items are displaying. From them, I want first 3 items to pass from sort criteria 1 and other 2 items from sort criteria 2.

How this can be achieved?

# Answer
One of the solutions can be using 2 views and use one view as footer attachment to the other view

View 1 with sort criteria 1 (no of items 3) View 2 with sort criteria 2 (no of items 3)

For View 1 footer, use View 2
> 1 votes

---
Tags: 8, views
---


title: Translatable rich text configuration

text:
# Question
Title: Translatable rich text configuration
I have a problem with translating my configuration form in Drupal 8, particularly with rich text fields.

This is my configuration file.

```
langcode: en
more_info_text: 'More info'
first_link_list:
second_link_list:
third_link_list:

```

Here is my schema file:

```
customization.config:
  type: config_object
  label: 'Website config'
  mapping:
    more_info_text:
      type: text
      label: 'More info text'
      translatable: true
    first_link_list:
      type: text_format
      label: 'First link text'
      translatable: true
      class: '\Drupal\Core\TypedData\Plugin\DataType\StringData'
    second_link_list:
      type: text_format
      label: 'Second link text'
      translatable: true
      class: '\Drupal\Core\TypedData\Plugin\DataType\StringData'
    third_link_list:
      type: text_format
      label: 'Third link text'
      translatable: true
      class: '\Drupal\Core\TypedData\Plugin\DataType\StringData'

```

The form itself works fine, but I cannot get the text format working for translations of the fields; it's always missing. Any ideas?

# Answer
I was playing with configs and finally found a solution. The configs should be:

```
langcode: en
more_info_text: 'More info'
first_link_list:
  format: 'full_html'
  value: ''
second_link_list:
  format: 'full_html'
  value: ''
third_link_list:
  format: 'full_html'
  value: ''

```

And the scheme file should not contain the following line

```
class: '\Drupal\Core\TypedData\Plugin\DataType\StringData'

```

Another thing I noticed is that you should translate the whole custom form, otherwise it will give an error at config inspector, so in my case I had to split my form into general and language specific.

Hope this helps somebody
> 0 votes

---
Tags: i18n-l10n
---


title: Module template file to extend theme

text:
# Question
Title: Module template file to extend theme
I want my module (events) to have its own template files but extend the base theme currently enabled.

**`hook_theme()`**:

```
function events_theme($existing, $type, $theme, $path) {
    return array(
        'test_events' => array(
            'variables' => array('testingvar' => 123),
            'template' => 'test_events',
            'path' => drupal_get_path('module', 'events') . '/templates',
            'base hook' => 'mytheme'
        )
    );
}

```

In my menu callback I have: `print theme('test_events');`

This outputs the contents of the template file, but it doesn't recognize the current theme that is enabled. Is there anyway I can extend the themes layout?

---

Edit: current situation:

Abstract of my directory structure:

```
Modules\
-custom\
--events\
---templates\
----test_events.tpl.php

Themes\
-mytheme\
--templates\
---test_events.tpl.php

```

events.module:

```
function events_theme($existing, $type, $theme, $path) {
    return array(
        'different_event_hook' => array(
            'path' => $path . '/templates',
            'template' => 'test_events'
        )
    );
}

```

menu callback:

```
print theme('different_event_hook');

```

**Result** renders from module template file, if I change `different_event_hook` to `test_events` it renders from the theme template file.

# Answer
The Drupal process is Core -\> Module -\> Theme. Trying to work backwards on that route is bad design, and should be avoided at all costs. Modules should not be based on themes, nor should they have any dependencies on themes, as themes are entirely dependent on modules, and downstream of modules.

If you need to make changes based on theme, it should happen in the theme.

Example. In your module, define hook\_theme()

```
function hook_theme($existing, $type, $theme, $path)
{
  return array
  (
    'my_theme_hook' => array
    (
      // the template will be in [MODULE_ROOT]/templates
      'path' => $path . '/templates',
      'template' => 'my-theme-hook', // leave off the .tpl.php
    ),
  );
}

```

The above defines a new theme hook called `my_theme_hook`, and the output of that theme hook is built in the template `[MODULE_ROOT]/templates/my-theme-hook.tpl.php`

Now you can use `[MODULE_ROOT]/my-theme-hook.tpl.php`, or even `[MODULE_ROOT]/templates/my-theme-hook.tpl.php` (this location works automatically for any templates). Clear your cache, and now the template in your theme will be used instead of the template in the module. Again, don't forget to clear your cache - the template will not be picked up until then.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: "CSRF validation failed" when try to send POST request in custom module
This is my full codes. I want to create a node with service post method. But I cant post. "CSRF validation failed".

I followed this tutorial: https://www.youtube.com/watch?v=Wz2uaRF9RGc

Anyone suggest something.

```
<?php
/**
* Block Info
*/
function mymodule_block_info(){
$blocks['mymodule_testing'] = array('info' => t('Mips Testing Block'));
return $blocks;
}

function mymodule_block_view($delta = ''){
$blocks['content'] = '<h1>MIPS Testing Block</h1>';

/* POST Request */
$post_data_results = mymodule_create_requested_data();

return $blocks;
}

/* Create data with POST Method */
function mymodule_create_requested_data(){
$path = $_SERVER['HTTP_REFERER'] . 'serve/node';

$node_type = 'apply';
$node_title = 'This is title ' . date('c');
$node_body = 'Node Body';
$node_format = 'filtered_html';

$node_data = '{
    "type": "'. $node_type .'",
    "title": "'. $node_title .'",
    "body": {
        "und": {
            "0": {
                "value": "'. $node_body .'",
                "format": "'. $node_format .'"
            }
        }
    }
}';

$node_options = array(
    'headers' => array(
        'Content-Type' => 'application/json',
        'Cookie' => mymodule_application_authentication('test', '123'),
        ),
    'method' => 'POST',
    'data' => $node_data
);

return drupal_http_request($path, $node_options);
}

function mymodule_application_authentication($username, $password){

if(isset($_COOKIE['mymodule_authentication_name']) && isset($_COOKIE['mymodule_authentication_id'])){
    return '' . $_COOKIE['mymodule_authentication_name'] . '=' . $_COOKIE['mymodule_authentication_id'];
} else {
    $login_url = $_SERVER['HTTP_REFERER'] . 'serve/user/login';

    $user_data = '{
        "username" : "'. $username .'",
        "password" : "'. $password .'"
    }';

    $user_options = array(
        'headers' => array('Content-Type' => 'application/json'),
        'method' => 'POST',
        'data' => $user_data
    );

    $result = drupal_http_request($login_url, $user_options);
    if($result->code == '200'){
        $user_data = json_decode($result->data);

        setcookie('mymodule_authentication_name', $user_data->session_name);
        setcookie('mymodule_authentication_id', $user_data->sessid);

        return '' . $user_data->session_name . "=" . $user_data->sessid .'';
    } else return FALSE;
}

}

```

# Answer
> 1 votes
You need to get a CSRF token before making your POST call.

```
function getCsrfToken(callback) {
  jQuery
    .get(Drupal.url('rest/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

```

and use this in your ajax call as a new header:

```
  jQuery.ajax({
    url: 'http://example.com/entity/node?_format=hal_json',
    method: 'POST',
    headers: {
      'Content-Type': 'application/hal+json',
      'X-CSRF-Token': csrfToken
    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });

```

https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities

---
Tags: 7, services
---


title: Cache breaks functionality?

text:
# Question
Title: Cache breaks functionality?
I have added some jQuery functionality to create a popup when hovering over a link to the script.js file included with the particular theme I am using. It is enclosed in `jQuery(document).ready(function($) {}`.

It works perfectly at first, but it seems that once Drupal 7 caches/aggregates the script.js file, it no longer works at all. I'm not 100% sure it is a caching related issue, as it works fine for hours, but eventually stops working. Clearing the CSS/JS cache after it stops working makes it work again.

```
function contactLinkInit() {
        var div = '<div class="contact-popup">' +
                '10320 Globe Road<br/>Morrisville, NC 27560<br/>' +
                'Phone: <a href="tel:919-361-4333">919-361-4333</a><br/>' +
                'Fax: 919-361-4388<br/>' +
                '<a href="mailto:info@dosoffice.com">info@dosoffice.com</a>';

        var firstRun = true;
        var firstEntered = true;
        var enteredPopup = false;

        $("a.contact-link").mouseover(function(event) {
            if (firstRun) {
                $("body").append(div);

                $("div.contact-popup").mouseover(function() {
                    if (!firstEntered) {
                        enteredPopup = true;
                    }
                    else {
                        firstEntered = false;
                    }

                    $("div.contact-popup").css('visibility','visible');
                });

                $("div.contact-popup").mouseout(function() {
                    enteredPopup = false;
                    $("div.contact-popup").css('visibility','hidden');
                });

                $("a.contact-link").mouseout(function() {
                    if (!enteredPopup) {
                        $("div.contact-popup").css('visibility','hidden');
                    }
                });
                firstRun = false;
            }
            $('div.contact-popup').css('left',event.pageX + "px");      // <<< use pageX and pageY
            $('div.contact-popup').css('top',event.pageY + "px");
            $("div.contact-popup").css('visibility','visible');
        });
    }

    contactLinkInit();

```

I'm sure what I've done here is not best practice, neither Javascript nor Drupal are my forte. Not only am I looking for a solution to the problem itself, I certainly wouldn't mind suggestions as how to improve the code itself.

# Answer
> 0 votes
I have redone my code as suggested in the comments so that it uses Drupal behaviors and the Drupal's javascript-api. I also moved my code out of the existing theme's `script.js` to its own file, and added that file to the scripts array in the theme's `.info` file.

Below is my updated code, in case it should help anyone that encounters this same sort of problem and is unfamiliar with Drupal behaviors. This has solved my problem with my code no longer working once the JS is aggregated and/or cached.

```
   (function($) {
     Drupal.behaviors.contactLinkHoverPopout = {
         attach: function(context, settings) {
             var div = '<div class="contact-popup">' +
                 '10320 Globe Road<br/>Morrisville, NC 27560<br/>' +
                 'Phone: <a href="tel:919-361-4333">919-361-4333</a><br/>' +
                 'Fax: 919-361-4388<br/>' +
                 '<a href="mailto:info@dosoffice.com">info@dosoffice.com</a>';

             var popupVisible = false;

             // we only want mouseovers applied once!
             $('a.contact-link', context).once(function() {
                 // add the invisible popup div
                 $('body', context).append(div);

                 // add mouseover to contact-link
                 $('a.contact-link', context).mouseover(function() {
                     $('div.contact-popup', context).css('left', event.pageX + "px");
                     $('div.contact-popup', context).css('top', event.pageY + "px");
                     $('div.contact-popup', context).css('visibility', 'visible');
                     popupVisible = true;
                 });

                 $('div.contact-popup', context).mouseover(function() {
                     $('div.contact-popup', context).css('visibility', 'visible');
                     popupVisible = true;
                 });

                 $('a.contact-link', context).mouseout(function() {
                     if (popupVisible) {
                         $('div.contact-popup', context).css('visibility', 'hidden');
                         popupVisible = false;
                     }
                 });

                 $('div.contact-popup', context).mouseout(function() {
                     if (popupVisible) {
                         $('div.contact-popup', context).css('visibility', 'hidden');
                         popupVisible = false;
                     }
                 });
             });
         }
     };
 }(jQuery));

```

---
Tags: javascript, caching
---


title: Tablesort with EntityQuery

text:
# Question
Title: Tablesort with EntityQuery
Inside a block plugin I'm creating a table (in Drupal8). Like so

```
            $header = [
                t('Name'),
                t('Number'),
                t('Rank'),
            ];
            $nids = \Drupal::entityQuery('node')
                ->extend('Drupal\Core\Database\Query\TableSortExtender')
                ->orderByHeader($header)
                ->condition('type', 'my_content_type')
                ->condition('status', 1)
                ->pager(5)
                ->execute();
            foreach ($nids as $nid) {
                $node            = \Drupal\node\Entity\NODE::load($nid);
                $row = [
                    'data' => [
                        $node->title->value,
                        $node->field_number->value,
                        $node->field_rank->value,
                    ],
                ];
                $rows[] = $row;
              }
            $render = [
                'table'           => [
                    '#prefix'        => '<h1>Entries</h1>',
                    '#theme'         => 'table',
                    '#attributes'    => [
                        'data-striping' => 0
                    ],
                    '#header' => $header,
                    '#rows'   => $rows,
                ],
            ];
            return $render;

```

Without the code below

```
 ->extend('Drupal\Core\Database\Query\TableSortExtender')
 ->orderByHeader($header)

```

the table renders just fine, but if I do include it I get the error

> Call to undefined method Drupal\Core\Entity\Query\Sql\Query::extend()

I'm guessing that it -\>extend does not work on EntityQueries, but if that's the case how can I add table sorting to my table?

UPDATE: I've changed my $header array to include 'field' like so

```
            $header = [
                [
                    'data'  => t('Title'),
                    'field' => 'title'
                ],
                [
                    'data'  => t('Race'),
                    'field' => 'field_number'
                ],
                [
                    'data'  => t('Time'),
                    'field' => 'field_rank',
                ],
            ];

```

and tried adding

```
 ->tableSort($header)

```

to the query and removing extend and orderByHeader from the query but then I receive the following error

> Drupal\Core\Entity\Query\QueryException: '' not found in Drupal\Core\Entity\Query\Sql\Tables-\>ensureEntityTable()

UPDATE 2: I tried changing the $header array to use a specifier and type property like so.

```
                    'data'      => t('Name'),
                    'type'      => 'field',
                    'specifier' => [
                        'field'    => 'title',
                        'column'   => 'value',
                    ],

```

But I end up with the same error and get an additional error

> Undefined index: specifier in Drupal\Core\Entity\Query\QueryBase-\>tableSort()

# Answer
> 7 votes
Following some of the information found in Berdirs answer and comments I was able to arrive at a solution.

I formatted my header like so:

```
            $header = [
                'title'      => [
                    'data'      => t('title'),
                    'field'     => 'title',
                    'specifier' => 'title',
                ],
                'number'       => [
                    'data'      => t('Number'),
                    'field'     => 'field_number',
                    'specifier' => 'field_number',
                ],
                'time'       => [
                    'data'      => t('Time'),
                    'field'     => 'field_rank',
                    'specifier' => 'field_rank',
                ],
            ],

```

I then performed the EntityQuery like so

```
            $nids = \Drupal::entityQuery('node')
                ->tableSort($header)
                ->condition('type', 'my_content_type')
                ->condition('status', 1)
                ->pager($items_per_page)
                ->execute();

```

I formatted my rows like so

```
                $row = [
                    'data' => [
                        $node->title->value,
                        $node->field_number->value,
                        $node->field_rank->value,
                ];

```

After that generating the table was easy

```
            $render = [
                'table'           => [
                    '#prefix'        => '<h1>Entries</h1>',
                    '#theme'         => 'table',
                    '#attributes'    => [
                        'data-striping' => 0
                    ],
                    '#header' => $header,
                    '#rows'   => $rows,
                ],
            ];

```

The important parts I was missing is the proper format for $header. And using -\>tableSort($header) instead of -\>extend('Drupal\Core\Database\Query\TableSortExtender') -\>orderByHeader($header) in my entityQuery

# Answer
> 5 votes
~~Entity query doesn't support extend() as you guessed and it also doesn't have any built in support for anything like Tablesort.~~

You should still be able to define the $header (your example is not correct, it needs to have a key for the field at least and optionally default sort order) and then use tablesort\_get\_order() and tablesort\_get\_sort() to get the field to sort on as well as the sort direction.

Edit: Turns out entity query does support that with tableSort(), but as I said, your header definition is not correct, see comments.

---
Tags: database
---


# Question
Title: Routing custom module with alphabetic pagination
My custom module: \- Plugin/Ziektes.php array returns to hook\_theme

```
public function build() {

$letter_path = 'B';
$path = base_path();
$current_url = Url::fromRoute('<current>');
$current_path = $current_url->toString();

// Query for newest articles and return max 3 results.
$query = \Drupal::entityQuery('node');
$news = $query->condition('type', 'ziekte')
  ->condition('status', 1)
  ->condition('title', $letter_path, 'STARTS_WITH' )
  ->sort('created', 'ASC')
  ->execute();

// LoadMultiple News in $nodes variable
$nodes = Node::loadMultiple($news);

// Return $nodes variable with name items to the module.
return array(
  '#theme' => 'mytheme_ziektes',
  '#items' => $nodes,
  '#path'  => $path,
  '#url'   => $current_path,
);

```

I have an alphabetical pagination printedn in twig like this:

Below this pagination there are the results of nodes for example in the letter 'B' there are nodes from content-type 'ziektes' that starts with the letter B.

As you can see in my module Ziektes.php file its not dynamic it uses

`$letter_path = 'B';
->condition('title', $letter_path, 'STARTS_WITH' )`.

When there is clicked on a letter it goes to ziektes/'theletter' for example ziektes/b so that I can get the letter from the url and make the query dynamic.

But at page ziekte/\*anyletter I get an 404 page not found so I've made a Controller and a routing:

**Routing**:

```
myroutingname.settings:
  path: '/ziektes/{letter}'
  defaults:
    _controller: '\Drupal\myblocksroute\Controller\ZiektesController::ziekte'
    _title: 'Routing Ziektes'
  requirements:
    _permission: 'access my routing ziektes'

```

**Controller**:

```
namespace Drupal\myblocksroute\Controller;

class ZiektesController
{
  public function ziekte($letter) {
    return [
      '#title' => $letter
    ];
  }
}

```

This returns the letter that is clicked, that's good! But Its only a new page with the as title the letter 'b' for example, I can't keep the twig template and the EntityQuery are not reachable from here. It suppose to stay at /ziektes form template but the url is /ziektes/b, so that the query will check the letter after the ziektes/ where I can make my $letter\_path dynamic.

How can I do this?

# Answer
> 1 votes
As I alluded to in my comment, you are close, I believe. Here are some changes to get you in the right direction which begins by extending ControllerBase:

```
class ZiektesController extends ControllerBase
{

  // set any scope/variables here

  public function __construct($args...) {
    // set your injected dependencies to local variables
  }

  public static function create($args...) {
    // here you inject dependencies you need
  }

  public function ziekte($letter) {
    return array(
     '#theme' => 'mytheme_ziektes',
     '#items' => $this->queryNodes($letter),
     '#path'  => $path,
     '#url'   => $current_path,
    );
  }

  protected function queryNodes($letter) {
    // the following code can be refactored
    $letter_path = 'B';
    $path = base_path();
    $current_url = Url::fromRoute('<current>');
    $current_path = $current_url->toString();

    // Query for newest articles and return max 3 results.
    $query = \Drupal::entityQuery('node');
    $nodes = $query->condition('type', 'ziekte')
      ->condition('status', 1)
      ->condition('title', $letter_path, 'STARTS_WITH' )
      ->sort('created', 'ASC')
      ->execute();

    return count($nodes) ? $this->entityTypeManager->getStorage('node')->loadMultiple($nids) : array();
  }
}

```

`ControllerBase` should inject everything you need already, like `entityTypeManager`. That can be used to load nodes, as shown above. You don't need to call `Node`, and you likely don't have to do the same for `Url` either.

You can bring in your query as a helper method and you can inject entityQuery into your controller, see this comment on how to do that. That way, you're not using the global static container (`\Drupal::`). Then your code becomes:

```
    // Query for newest articles and return max 3 results.
    $query = $this->entityQuery->get('node');
    $nodes = $query->condition('type', 'ziekte')
      ->condition('status', 1)
      ->condition('title', $letter_path, 'STARTS_WITH' )
      ->sort('created', 'ASC')
      ->execute();

```

I am not sure why you need path and url though - every filter link will be routed to `'/ziektes/{letter}'`.

---
Tags: 8, paging
---


# Question
Title: How can I render a token within a token via rules mail action?
I want to send a node via rules. I can send it using the \[node:body\] token. However, I want to be able to use tokens in the actual node body as well. (Note: These are not global tokens)

Think of it like a newsletter and in the body field I am using

Dear \[field\_ef\_first\_name\], ...

I can get the token to render if I put it directly in the rules action mail message body, but if it is in the node body field itself, it doesn't render.

The name field is coming form a views rule loop.

Rule exported:

```
{ "rules_send_newsletter_when_published" : {
"LABEL" : "Send newsletter when published",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_insert--blog" : { "bundle" : "blog" } },
"DO" : [
  { "VIEW LOOP" : {
      "VIEW" : "entityforms",
      "DISPLAY" : "views_rules_1",
      "ROW VARIABLES" : {
        "field_ef_email" : { "email" : "Email" },
        "field_ef_first_name" : { "first_name" : "First Name" }
      },
      "DO" : [
        { "mail" : {
            "to" : "[email:value]",
            "subject" : "[node:title]",
            "message" : "[node:body]",
            "language" : [ "" ]
          }
        }
      ]
    }
  }
]

```

} }

# Answer
\[EDIT\]

While the other answers are workable, this is the simplest and closest to your current implementation using Views Rules.

First of all, be sure to **enable the module PHP Filter**

Also: the body of your blog needs to use the following custom token format: `!first_name!`. This string gets replaced inside your rule with the value of the Entityform `field_ef_first_name` field.

Here's the exported version of the Rule, modified from your original. **SCROLL DOWN** for an explanation.

```
{ "rules_send_newsletter_when_published" : {
    "LABEL" : "Send newsletter when published",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "ON" : { "node_insert--blog" : { "bundle" : "blog" } },
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "entityforms",
          "DISPLAY" : "views_rules_1",
          "ROW VARIABLES" : {
            "field_ef_first_name" : { "first_name" : "First name" },
            "field_ef_email" : { "email" : "Email" }
          },
          "DO" : [
            { "variable_add" : {
                "USING" : {
                  "type" : "text",
                  "value" : "\u003C?php\r\n$text = str_replace(\u0027!first_name!\u0027, $first_name, $node-\u003Ebody[LANGUAGE_NONE][0][\u0027value\u0027]);\r\necho $text;\r\n?\u003E"
                },
                "PROVIDE" : { "variable_added" : { "processed_body" : "Processed body" } }
              }
            },
            { "mail" : {
                "to" : "[email:value]",
                "subject" : "Subject",
                "message" : "[processed-body:value]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

Here's an explanation:

This implementation of your Rule uses the action "Add a Variable" before sending the email. I named this variable "processed\_body." I use **PHP Evaluation** to set the value of this variable:

```
<?php
$text = str_replace('!first_name!', $first_name, $node->body[LANGUAGE_NONE][0]['value']);
echo $text;
?>

```

Basically, this snippet replaces the "token" `!first_name!` with the value of the Views Rule loop-provided variable $first\_name. Then, I use the variable `processed_body` to send in the email body.

NOTICE that you will need to manually process any other custom tokens that you would like to add to your Blog body. For example, if you want the body to contain the last name of the recipient (e.g. `!last_name!`), you'll need to manually add a `str_replace` function that replaces `!last_name!` with the correct value.

\[EDIT 2\]

Here's the code with an added `!last_name!` "token" replacement. I assume your entityform field is `field_ef_last_name` and it has been added to the Rules View as such.

```
{ "rules_send_newsletter_when_published" : {
    "LABEL" : "Send newsletter when published",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "ON" : { "node_insert--blog" : { "bundle" : "blog" } },
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "entityforms",
          "DISPLAY" : "views_rules_1",
          "ROW VARIABLES" : {
            "field_ef_first_name" : { "first_name" : "First name" },
            "field_ef_email" : { "email" : "Email" },
            "field_ef_last_name" : { "last_name" : "Last name" }
          },
          "DO" : [
            { "variable_add" : {
                "USING" : {
                  "type" : "text",
                  "value" : "\u003C?php\r\n$text = str_replace(\u0027!last_name!\u0027, $last_name, $node-\u003Ebody[LANGUAGE_NONE][0][\u0027value\u0027]);\r\n$text =  str_replace(\u0027!first_name!\u0027, $first_name, $text);\r\necho $text;\r\n?\u003E"
                },
                "PROVIDE" : { "variable_added" : { "processed_body" : "Processed body" } }
              }
            },
            { "mail" : {
                "to" : "[email:value]",
                "subject" : "[node:title]",
                "message" : "[processed-body:value]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

The PHP code in the added Rules Variable value is

```
<?php
$text = str_replace('!last_name!', $last_name, $node->body[LANGUAGE_NONE][0]['value']);
$text =  str_replace('!first_name!', $first_name, $text);
echo $text;
?>

```
> 1 votes

# Answer
Using tokens within the body of a node, combined with using `[node:body]` in a Rules Action, will only result in the token being included as is (without rendering). However, based on what you're trying to do, you may want to have a look at an entirely different approach to achieve your goal ...

Enable the Forena module (disclosure: I'm a co-maintainer), and have a look at Active Users Email (using FRX syntax), which is one of the samples included in the module (which can be used to eMail a ***template message body*** to all registered users).

These are the parts in this FRX file that are relevant to the question here:

* The datablock `drupal/active_users`, which is (just) an SQL statement that looks like so:

`--ACCESS=access administration pages`

`SELECT uid, name, mail, login, status`

`FROM {users}`

`WHERE status=1 order by name`
* The `frx:foreach="*"`, which will cause an iteration for each row included in the results of the data block, for everything inside that `div` (related to the datablock).
* The `div` with `class="email-body"`, which starts with `Dear {name}`, and which includes a ***replacement token*** indicated with `{name}`.
* The line with `<frx:doc type="email" />`, to enable document format "Send eMail".

After you enabled the module, and visit the relative path at `/reports/drupaladmin.sample_active_users_letter`, this is what will happen:

1. Run the SQL query (as contained in the datablock).
2. Iterate over each of the results returned by the datablock (SQL statement).
3. For each iteration resolve all the tokens (i.e. as within that `Dear {name}`).
4. Display how the eMail will actually look like (for each iteration).
5. Add link (upper right) titled "eMail". If you actually click that "eMail" link, a confirmation screen will be shown with these details:
    * number of eMails that will be eMailed (= number of rows in the datablock).
    * radio button to either send an eMail, or actually send all eMails.

With the above in mind, this is what you'd need to get it to work for your case:

* Clone the delivered sample, and tune it as detailed below.
* Adapt the datablock to retrieve the desired data (columns), similar to what your view is doing. Or create a new one that fits your needs and use that one instead. Make sure to include the data related to your `field_ef_email` and `field_ef_first_name`.
* Adapt the *From*, *To* and *Subject* to fit your needs.
* Use whatever tokens you need, anywhere in the *Body* of your eMail. E.g. to replace that `Dear {name}`. If you need more, or other, data, just add an appropriate name to your datablock (as an extra column). As a sample, here is part of an FRX file I created to transform webform submissions into some kind of followup-eMail to each of those who submitted the form:

`<p>Hello,</p>`

`
thank you for using our form (with node id = {node}) to submit your feedback (with submission id = {submission}). You're now confirmed via the eMail Id you entered (= {fieldvalue}) to receive eMails from us.
`

`<p>We'll get back to you shortly for an additional followup eMail.</p>`
> 2 votes

# Answer
The following creates a mail message based on a profile & commerce product, custom entity, commerce credit.

Trying to pull all these things in together without coding up your own rule or rule handler is a bit much too expect. The comment regarding random complexity and disparate objects means you don't have a sane alternative. This answer goes a long way out of the domain of rules.

There is mimemail in this setup to detect and send html mail.

I did start off with a handler, but the custom rule makes things explicit.

## Rule

```
function yhivepasses_rules_action_info() {
  $items = array();

  $items['yhivepasses_email_passes'] = array(
    'label' => t('Send pass email'),
    'group' => t('YogaHive Passes'),
    'parameter' => array(
    'commerce_order' => array(
      'type' => 'commerce_order',
      'label' => t('Order'),
      'description' => t('The order containing the credits bought.'),
    ),
  ),
  'callbacks' => array(
    'execute' => 'yhivepasses_rules_action_send_pass_on_checkout',
  ),
);

return $items;
}

```

## Callback function

I have just

```
function yhivepasses_rules_action_update_on_checkout($order) {
  $yogaHivePasses = new YogaHivePasses();
  $yogaHivePasses->checkoutRule($order);
}

```

## Data building classes

The callback function calls a set of classes that bring the data together from the rule and secondary sources.

I shove this all into a data object.

## Call drupal mail

```
protected function sendToStudio(YogaHivePassDao $passDao) {
 $message_studio_contact = [];
 $message_studio_contact['module'] = YogaHivePasses::MODULE_NAME;

 $this->studioContactEmail($message_studio_contact, $passDao);
 $langStudio = $this->mailSetLanguage($message_studio_contact, $passDao->getStudioUser());
 $result = drupal_mail(YogaHivePasses::MODULE_NAME, YogaHivePasses::EMAIL_KEY, $passDao->getStudioUser()->mail, $langStudio, $message_studio_contact);
}

```

This calls a method that builds the html mail body from a template.

## Mail template processing

This relies on hook\_theme which defines the templates.

```
public function studioContactEmail(&$message, YogaHivePassDao $passDao) {

// Needs User object. Not bothering with printing out actual order details.
$content_templated = theme('yhivepasses_studiocontact_purchase_studio_email', array(
  'passDao' => $passDao,
 ));

 $content_templated .= theme('yhivepasses_email_footer', array());
 $message['body'][] = $content_templated;
 $message['subject'] = 'Studio pass purchased on YogaHive';
 $current_credit = current($credit);
 $message['subject'] .= ' ' . $current_credit->credit_type;

 $headers = array(
  'MIME-Version' => '1.0',
  'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
  'Content-Transfer-Encoding' => '8Bit',
  'X-Mailer' => 'Drupal'
 );
 foreach ($headers as $key => $value) {
  $message['headers'][$key] = $value;
 }
}

```

## Hook mail

Hook mail is needed to add the body, subject and headers in the correct places.

```
function yhivepasses_mail($key, &$message, $params) {
 switch ($key) {
  case YogaHivePasses::EMAIL_KEY :
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];

  // May not be any parameters. Parameters are mainly used to send attachments.
  if (array_key_exists('params', $params)) {
    $message['params'] = $params['params'];
  }

  foreach ($params['headers'] as $key => $value) {
    $message['headers'][$key] = $value;
  }
  break;
default:
  return;

```

} }
> 1 votes

---
Tags: rules, tokens
---


# Question
Title: Can Views theme/rendering be disabled programmatically?
I'm creating an RSS feed using the default Views RSS display and by default it contains a bunch of characters that cause the output to be invalid XML (I believe this has to do with bugs within views related to double encoding or other related functions).

So, to fix this, during hook\_views\_pre\_render() I am able to manipulate the fields with php to output valid stuff. Within views when I "preview" the output, it's exactly as it should be.

However, when I view the actual feed output at the views url, the output has changed because views has done something to render it (I'm assuming putting it thru the theme system, etc), thereby breaking my 'fixes' again.

Manipulation of the fields in the UI (ie. using plain text as the output, etc) don't do what i need, so those aren't an option.

Is there a way, programmatically, to disable any rendering and tell views to output exactly what I'm seeing in the Views preview?

# Answer
> 0 votes
Yes under `Advanced` there is a `Theme Information` link that will show you template file(s) that you can override to meet your needs depending on the display format selected (fields, rendered entity, etc).

If you need to change how the page itself renders for example, you can also affect the sitewide theme function used to create the url by changing `theme function` in hook\_menu.

---
Tags: views, theming
---


# Question
Title: Content types on "Add Content" randomly re-sort themselves
Does anyone know why sometimes the content types on "node/add" in the admin will list differently every so often?

Example, say I have Article, Job, Page, Product, Resource, Webform. Sometimes they are listed alphabetically (**preferred**), but I just noticed after creating some content, some of the items are out of order - Drupal 8.2.7.

# Answer
> 2 votes
You can check in which order the content types are loaded from the configuration storage with drush:

```
drush ev "print_r(array_keys(\Drupal::entityTypeManager()->getStorage('node_type')->loadMultiple()))"

```

---
Tags: 8
---


title: colorbox gallery with media field

text:
# Question
Title: colorbox gallery with media field
I am looking for a way (in D8) to create a colorbox gallery for a node field with multiple images but I am facing the following problems:

* colorbox only works as an image field formatter (no media field formatter).
* I would prefer media field since its nice to have entity browser to reuse some of the images.
* Trying to create an image field that collects image using entity browser did not work for me. I was getting the error "The entity must be of type file" and none of the solutions seemed to work either. I even created a new entity browser but it did not succeed.
* Media gallery and other related modules are not yet ported to Drupal 8

Is there any alternative?

# Answer
> 2 votes
I have finally managed to find a workaround which involves creating a view that displays the media field images based on contextual information from the node. The field formatter can be changed to a view using views\_field\_formatter module

Here is in a little more detail

lets assume the content type that we want to have media gallery is named "gallery" and it contains a media field "field\_media" and assume colorbox and views\_field\_formatter modules are installed and enabled

1. prepare a view that displays nodes of content type "gallery" (a block view is enough)
2. add relationship that exposes the field\_media and call it "media"
3. add contextual filter "Content ID" based on "media" relationship
4. add appropriate image field to display (based on the "media" relationship) and use colorbox formatter (since this field is an image colorbox will be available)
5. go to the gallery content type display settings and configure the media field to use the view prepared above passing as first parameter the node id

---
Tags: javascript, media
---


# Question
Title: How to force cron to use config saved during a SimpleTest?
I write a test using Drupal\simpletest\WebTestBase for a custom module, which implements hook\_cron(). The test saves a configuration object, which should be used by the cron, and then runs the cron:

```
function testCron()
{
    $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
    $config
      ->set('some_setting', 'some value')
      ->set('another_setting', 'another value');
    \Drupal::service('cron')->run();
}

```

The settings are saved and can be used during the test. But when I want to use them in the cron (in mymodule.module):

```
/**
 * Implements hook_cron().
 */
function mymodule_cron()
{
    $config = \Drupal::config('mymodule.settings');
    ...
}

```

then instead of the saved values, the default settings from config/import/mymodule.settings.yml are used.

How can I force the cron to use the settings saved in the test?

# Answer
> 3 votes
As commented, you were missing the save call in the test.

That means that the change is only in the runtime object returned by getEditable() and since get() and getEditable() do not share the static cache, you didn't see the change.

---
Tags: 8, cron, testing
---


# Question
Title: How to restrict a module to a specific core version?
Drupal 8.3 introduced some changes, which broke a custom module; fixing the changes causes the module to break in previous Drupal versions. One way to handle this would be to require Drupal core to above version 8.3+ for this module. However, the following changes to YAML file does not work.

```
core: '8.3'
core: '8.3.x'

```

Drupal shows the following incompatibility message.

> This version is not compatible with Drupal 8.x and should be replaced.

The official documentation does not provide useful information for core keyword.

So how should Drupal core version requirement specified in the .info file? If not, is there any other way to specify such requirement?

# Answer
Using *core* only supports the major version, but you can add a dependency on the system.module with a specific version.

```
dependencies:
 - system (>=8.3)

```

Due to a bug in version parsing, you can only do this with the minor version. You can't specify a patch release like 8.3.1.
> 10 votes

# Answer
You can check in hook\_requirements like so:

```
function mymodule_requirements($phase) {
  // code
  $version = \Drupal::VERSION;
  // code that checks version info here

  return $requirements;
}

```

If `$version` is not what you're expecting, throw a REQUIREMENT\_ERROR. In fact, there is sort of an example on the docs page.

```
function mymodule_requirements($phase) {
  $requirements = [];

  // code
  $version = explode('.', \Drupal::VERSION);
  // code that checks version info here

  if ($version[0] == 8 && $version[1] < 3) {
    $requirements['mymodule'] = [
      'title' => t('My Module'),
      'description' => t('This module requires Drupal 8.3.0 or higher before it can be installed.'),
      'severity' => REQUIREMENT_ERROR
    ];
  }

  return $requirements;
}

```
> 2 votes

---
Tags: 8, .info
---


# Question
Title: Does Drupal Disqus Commenting have a Server Side rending for SEO indexing?
Having to outsource the commenting service to disqus saves alot of time, but is there a way to have these Disqus comments rendered on the server side before displaying it to the end user? My main concern is for SEO indexing. What solutions are there to keep the SEO indexing in tact when using Disqus commenting?

# Answer
Disqus itself does support this (see this post for example) but I do not believe that the Disqus Drupal module supports this. It would probably be a worthwhile contribution to that module (or perhaps a companion module).
> 1 votes

---
Tags: 7, comments
---


title: First things first with Ajax

text:
# Question
Title: First things first with Ajax
Somehow I can't get through the first Ajax lesson.

This is the code of a simple module that I put together:

```
function myajax_menu() {
  $items = array();

  $items['myajax/param/%'] = array(
    'page callback' => 'dynamic_products_ajax_callback',
    'page arguments' => array(1),
    'access arguments' => TRUE, // array('access dynamic_products content'),
    'type' => MENU_CALLBACK
  );

  return $items;
}

function myajax_ajax_callback($type = 'ajax', $param){
   if ($type == 'ajax') {
    $commands[] = ajax_command_html('#myajax_wrapper', '[Content returned for argument ' . $param . ' will be here]');
    $page = array('#type' => 'ajax', '#commands' => $commands);
    ajax_deliver($page);
  }  else {
    $output = t("This is some content delivered via a page load.");
    return $output;
  }
}

```

This is my markup.

```
drupal_add_library('system', 'drupal.ajax');

// Output a link
print l(t('AJAX 12'), 'myajax/param/12', array('attributes' => array('class' => array('use-ajax'))));
print l(t('AJAX 20'), 'myajax/param/20', array('attributes' => array('class' => array('use-ajax'))));
// Output a wrapper
print '<div id="myajax_wrapper"></div>';
?>

```

All I'm getting is a JavaScript alert that informs me about AJAX error that occurred, and the result code is 200.

Is the example module missing anything?

**Question revision:**

After much googling I've come up with a very rudimentary working Ajax example that does what I want - it replaces HTML of a wrapper with a response obtained from a dynamic link. Hope it'll be of some help for newbies.

Module:

```
<?php
function myajax_menu() {
  $items = array();

  $items['myajax/param/nojs/%'] = array(
    'page callback' => 'myajax_ajax_callback',
    'page arguments' => array(2,3),
    'access arguments' => TRUE,
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  $items['myajax/param/ajax/%'] = array(
    'delivery callback' => 'ajax_deliver',
  ) + $items['myajax/param/nojs/%'];

  return $items;
}

function myajax_ajax_callback($ajax, $param){
    $is_ajax = $ajax === 'ajax';

    drupal_add_library('system', 'drupal.ajax');

    if ($is_ajax) {
      $commands = array();
      $commands[] = ajax_command_html('#myajax_wrapper', "This is some content delivered via a page load with param <b>" . $param . "</b>.");

      return array(
        '#type' => 'ajax',
        '#commands' => $commands,
      );
    } else {
      drupal_set_message(t('JavaScript should be enabled to avoid page reloads.'));
      drupal_goto();
    }
}

```

The markup:

```
<?php
print l(t('AJAX 12 '), 'myajax/param/nojs/12', array('attributes' => array('class' => array('use-ajax'))));
print l(t('AJAX 20 '), 'myajax/param/nojs/20', array('attributes' => array('class' => array('use-ajax'))));
?>

<div id="myajax_wrapper"></div>

```

The problem with disappearing admin\_menu persists. If anyone could tell me why...

# Answer
> 3 votes
The problems with your original (first) question are as follows:

* Your callback function expects 2 parameters, but you are providing just one.
* You are missing `nojs` in your url.
* You are giving `param` as a parameter to your callback function, but you wanna `%` instead/

So it should look like something like this:

```
  $items['myajax/param/nojs/%'] = array(
    'page callback' => 'myajax_ajax_callback',
    'page arguments' => array(2,3), // drupal starts counting from 0 so nojs is 2nd and % is 3th arg
    'access arguments' => TRUE,
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

```

I hope this will help someone.

P.S. sorry for my English

# Answer
> 1 votes
Yes, the examples seem to be all concerned with forms. It does seem difficult to find a place where you can find a solution that is just click a link and get a html response.

This is my version

# Menu

```
function hottopicsnotify_menu() {
 $items = array();
 $items[HOTTOPICSNOTIFY_MODULE_NAME . '/pause'] = array(
  'title' => 'Share Hot Topic with Public',
  'access callback' => 'hottopicsnotify_access_callback',
  'page callback' => 'hottopicsnotify_pause',
  'page arguments' => array(2),
  'file' => 'includes/HotTopicsAcceptanceVote.php',
  'type' => MENU_CALLBACK,
);

```

# Template

Complicated, call block from template file to get this result in the source code. Render block to get 'id' set.

```
<section class="hottopics-paused">
    <div id="paused-ajax-container">
  Hot topics Voting <span style="color:red">Paused</span>.   <a href="/hottopicsnotify/pause" id="ajax-link">Start</a>
</div>

```

Without digressing into how to render a block, the shortcut way is calling render on a block content array.

```
<?php
 $block['content'] = array(
 '#type' => 'link',
 '#title' => 'Pause',
 '#href' => '/hottopicsnotify/pause',
 '#ajax' => array(
   'effect' => 'fade',
 ),
);

print render($block['content']); ?>

```

# Call back function

```
/**
 * Toggle the pause variable.
 */
function hottopicsnotify_pause() {
 $paused = variable_get(HOTTOPICSNOTIFY_EDITORIAL_BOARD_PAUSED, FALSE);
 drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');

 $block['content'] = array(
  '#type' => 'link',
  '#title' => 'Pause',
  '#href' => '/hottopicsnotify/pause',
  '#ajax' => array(
    'effect' => 'fade',
  ),
 );

 $response_text =  "Hot topics report running. " . render($block['content']);
...

 $commands = array();
 $commands[] = ajax_command_html('#paused-ajax-container',
 $response_text);
 ajax_deliver(array('#type' => 'ajax', '#commands' => $commands));
 drupal_exit();
}

```

---
Tags: 7, ajax
---


# Question
Title: Render React Components in Twig Templates
I am using React JS in my theme (installed via NPM), and exporting views using REST. I want to render the JSON view data into React components and call them in the twig templates.

The way I have it working now is I have js/main.js importing components eg: js/components/slider.jsx etc. The component files decide where to render. Eg:

```

ReactDOM.render(
  document.getElementById('elementid')
);

```

I have a gulp task running which bundles, transforms ES6 - ES5, and uglifies all the JS imported in js/main.js into js/script.js which is the only JS loading from the theme. I'm not sure if this is the best option for performance.

Maybe another option is to compile each component (ES6 must be transformed to ES5) into it's own JS file and define them as libraries, which can be then called in the twig templates?

I have tried to use TwigReactDirective but I get errors following the instructions.

Are there better options / ways of doing this?

# Answer
After doing some research, I found 3 options to render React components on the server side.

* Use the PHP V8Js extension to run an embedded V8 engine
* Execute node.js processes on demand
* Run a node.js rendering daemon for rendering

Rendering on the server side is beneficial for performance of the initial page load. Using the V8Js extension and a twig extension like Tesonet seems like the best option for me.

V8Js installation instructions can be found here

Some other good options to try out are: React Renderer or symfony-react-sandbox or React Bundle. Symfony React Sandbox integrates React Bundle. React Bundle integrates React Renderer.

Read more here
> 2 votes

---
Tags: theming, 8
---


title: Setting value for a view filter

text:
# Question
Title: Setting value for a view filter
How do I set a view filter so that the date of item makes it disappear WHEN the event occurs?

Right now when I edit the filter I have it Operator set to 'is greater than or equal to' and the Value set to 'today', but I want it to disappear at the exact time the event is occurring.

What do I put in 'value' for that to happen?

# Answer
`now` worked. I also discovered `+1` works for one hour before the event.
> 0 votes

---
Tags: views, 8
---


# Question
Title: Get cron to process QueueWorker items at a specific time
I have a `Plugin\QueueWorker` that creates a queue of emails to send from nodes that are created/updated throughout the day. I've defined a `processItem()` method, as well as an arbitrary function (let's call it `mymodule_add_to_queue()`) that runs `$queue->createItem()` to add the node to the queue. When cron runs, all the items in the queue get run, which is fine and dandy.

The only problem is that cron is running every hour, and it seems the `QueueWorker` class will run the process every time, when I only want it to run once, say between 2am and 3am.

I have the code that checks the `REQUEST_TIME` and the state of the last time it ran and all that, however I don't know where to put it. Even if it goes into `hook_cron()`, it doesn't appear to make any difference to the default behaviour.

Pseudocode for what kind of thing I'd be expecting to happen is:

```
<?php

// @file src/Plugin/QueueWorker/MyModuleCronQueueWorkerEmailSend.php
class MyModuleCronQueueWorkerEmailSend extends QueueWorkerBase {
  public function __construct () {
    this.auto_cron = FALSE;
  }
  public function processItem() {
    doSomething();
  }
}

// @file mymodule.module
function mymodule_add_to_queue() {
  $queue = \Drupal::queue('mymodule_queue_worker_email_send');
  $queue->createItem(['foo' => 'bar']);
}

function mymodule_cron() {
  if (some_cron_conditionals()) {
    $queue = \Drupal::queue('mymodule_queue_worker_email_send');
    $queue->process();
  }
}

```

... this may be completely out of scope though, or there may be a really obvious other method I'm missing. Any thoughts? As always, thanks in advance :)

# Answer
Copied from `\Drupal\Core\Annotation\QueueWorker`, the annotation and placd where the @QueueWorker annotation is documented.

```
 * Worker plugins are used by some queues for processing the individual items
 * in the queue. In that case, the ID of the worker plugin needs to match the
 * machine name of a queue, so that you can retrieve the queue back end by
 * calling \Drupal\Core\Queue\QueueFactory::get($plugin_id).
 *
 * \Drupal\Core\Cron::processQueues() processes queues that use workers; they
 * can also be processed outside of the cron process.
 *
 * Some queues do not use worker plugins: you can create queues, add items to
 * them, claim them, etc. without using a QueueWorker plugin. However, you will
 * need to take care of processing the items in the queue in that case. You can
 * look at \Drupal\Core\Cron::processQueues() for an example of how to process
 * a queue that uses workers, and adapt it to your queue.

```

See the last paragraph, the solution is simply to just fill an arbitrary queue and then implement similar logic as Cron::processQueues() for your queue to process the items when you want. Nothing will happen automatically with items of a queue that doesn't have a worker plugin.

Instead of a plugin, you can implement your login in a service instead and call that from your own cron implementation.
> 2 votes

# Answer
Try using https://www.drupal.org/project/ultimate\_cron, which should give you a fine-grained control over when each cron task runs.
> 0 votes

---
Tags: 8, cron, queue
---


# Question
Title: Populate Taxonomy Term reference field in node
I'm using data from JSON to create new nodes on my Drupal 8 website. So, I have a `createNode` method that create these nodes.

Here is the code I'm using

```
  protected function createNode($json) {

    foreach ($json as $row) {
      $node = Node::create(array(
        'type' => 'product',
        'langcode' => 'en',
        'uid' => '1',
        'status' => 1,
        'title' => $row['title'],
        'field_code' => $row['code'],
        'field_manufacture' => $row['manufacture'],
        'field_product_type' => $row['type'],
        'field_barcode' => $row['barcode'],
        'field_packages' => $row['packages'],
        'field_pallet' => $row['pallet'],
      ));

      $node->save();
    }

  }

```

The problem is with `field_manufacture` and `field_product_type`, those are entity reference field to taxonomy term. I'm getting term name and I need to match it in vocabulary or add it if doesn't exist.

Any idea how to do that?

# Answer
> 2 votes
First, find the taxonomy term id by the term name as given below.

```
function getTidByName($name = NULL, $vocab_name = NULL) {
  $properties = [];
  if (!empty($name)) {
    $properties['name'] = $name;
  }
  if (!empty($vocab_name)) {
    $properties['vid'] = getVidByName($vocab_name);
  }
  $terms = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->loadByProperties($properties);
  $term = reset($terms);
  return !empty($term) ? $term->id() : 0;
}

```

Above function will return the term id and then pass this term id to your field like

```
// Assigning the entity reference value.
if ($tid > 0) {
  $entity->set('field_example', ['target_id' => $tid]);
}

```

---
Tags: 8, nodes
---


# Question
Title: How do I add my new Paragraph type to a content type?
I've made a new Paragraph type and it appears as an option in the Basic Page content type, but I'd also like it to appear in another content type.

Would anyone know where I set this?

# Answer
> 3 votes
Turns out I was missing a step:

1. Structure\>\>Content Types
2. Edit the content type you want to add the Paragraph to
3. Go to Manage Fields tab
4. Find the Paragraphs entry in the list and click edit
5. Check your bundle from the list

---
Tags: 7, nodes, paragraphs
---


# Question
Title: How do I block individual content items from search engines?
I need to create multiple landing pages for my food business running a Drupal 7 site, same page, different prices, offers, coupons, different OGP tags for Facebook posts etc.

So I will have dozens of multiple identical content pages, and I don't want to be penalized by Google. I could do this via Robots.txt or .htaccess, but is there a way to do this at the content page item level?

# Answer
> 0 votes
Use Metatag module for this purpose. Go to configuration page of metatag module and you can prevent google to index your node type.

Hope it will help.

---
Tags: meta-tags
---


# Question
Title: Why are some fields output wrapped in div and others a span?
I have been working with a View and I noticed an inconsistency in the way fields are output (unformatted list).

Most of the fields appear below their labels, but one (Post date) appears on the same line.

I looked at the source and I saw that the date was wrapped in a `span` and the other fields were wrapped in a `div`:

```
<div class="views-field views-field-field-last-name">
    <span class="views-label views-label-field-last-name">Last Name: </span>
    <div class="field-content">Thacker</div>
</div>
<div class="views-field views-field-created">
    <span class="views-label views-label-created">Post date: </span>
    <span class="field-content">Wednesday, April 9, 2014 - 14:39</span>
</div>

```

Why is this happening? Is it important for this to happen? How can I change this so that everything is wrapped in a `div`?

# Answer
If you click on a field in your view, you get the 'Configure Field' dialog. Look for "Style settings", because there you can customize the Field HTML, Label HTML and the wrapper. E.g. with 'Label HTML' option you can change the `<span>` to a `<div>`.
> 3 votes

# Answer
While the accepted answer shows you how to customize the field HTML, the answer might be simpler and might all be based on whether you are choosing to format fields in a view as an inline field or not. For example, your example shows this:

```
<div class="views-field views-field-field-last-name">
    <span class="views-label views-label-field-last-name">Last Name: </span>
    <div class="field-content">Thacker</div>
</div>
<div class="views-field views-field-created">
    <span class="views-label views-label-created">Post date: </span>
    <span class="field-content">Wednesday, April 9, 2014 - 14:39</span>
</div>

```

My guess is that if you were to open up that view to edit it, and click “Settings” under “Format -\> Show -\> Settings” you will see a list of your selected fields in that view under the heading “Inline fields” with checkboxes new to them like this; using the standard `@font-your-face` view as an example:

Any field you would set as an inline field by checking off those checkboxes would make the field render in a `<span>` element since that is an HTML inline element; unchecked the defaults to a `<div>` element which is a block-level element.
> 1 votes

# Answer
You can select the field and label html in views. By clicking on your field below popup will open. In this you can select the default field/label html or anything like label or span you want to use in display.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Get a taxonomy id(tid) from a node id (nid)
```
  if($node->type=='student')
    {
        $nid = $node->nid;
        print_r("The node id is: ".$nid.'<br/>');
        $tid =db_query('SELECT tid FROM {taxonomy_index} WHERE nid = :nid',
                  array(':nid' => $nid)
                )->fetchField();
        print_r('The tid is: '.$tid);exit(0);
    }

```

I tried but nothing is displayed...I just want to get the tid.

# Answer
> 1 votes
May be you can use field\_get\_items: It will return return the field items in the language they currently would be displayed.

```
// Pass the node object $node instead of $nid.
// Get the field name of taxonomy field from content type.
$term_id = field_get_items('node', $node, $field_name);

```

$term\_id will be array containing the term ids.

# Answer
> 1 votes
As commented by Neok, you can get the term id mapped with your node directly from node object like

$node-\>field\_example\['und'\]\[0\]\['tid'\];

# Answer
> 0 votes
```
    <?php
        $activities_name = "activities"; // suppose you created a vocabulary that is "activities" which is attach with a particular node.

//NOw I will fetch all the details for this vocabulary from database

        $activities_result = taxonomy_vocabulary_machine_name_load($activities_name);

        echo $activities_result->vid; // now print the attached vocabulary id

now fetch all the terms id tose are associated with this vocabulary

        $activities_term_data = taxonomy_get_tree($activities_result->vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE);

        foreach($activities_term_data as $k => $v)
        {
        echo $v->tid."=>".$v->name; // print the termid and term name.
        }

    //$v->tid will show the terms ids.

// by the help of code you can get the vocabulary id and associated terms ids ( actually its not clear to me what the user exactly want term id or vocabulary id)
         ?>

```

# Answer
> 0 votes
Instead of using db\_query simply use db\_select as

```
$tid = db_select('taxonomy_index', 'taxonomy_index')
  ->fields('taxonomy_index', array('tid', 'tid'))
  ->condition('nid', $nid)
  ->execute()->fetchAllKeyed();

```

So executing this would generate an array containing the list of tags a content is tagged with.

Thanks,

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


# Question
Title: Custom template file to use themes html/page.tpl
I have a custom module (using Drupal 7) that adds a page using `hook_menu()`. Its callback just prints the value returned from `theme('mytheme_hook')`.

If the content of my template file is simply `'hello world'` I get only a white screen with the text output.

Is it possible for this page to extend the theme's `html.tpl` (and even `page.tpl`) with `'hello world'` inserted in the 'content section' of the page?

This looks like a similar thing I am trying to achieve, but it doesn't offer a solution.

# Answer
If you want your content to be inserted in the content section of the page you just need to return it (as HTML, or render array) from your page callback function. Then you can override the template of any (html/page/node) level for this page by standard theme hook suggestion and customize it.
> 0 votes

---
Tags: theming
---


# Question
Title: How do I expose form elements as an API?
I have tried `drupal_get_form($form_id)` to get the form elements, but it didn't help me.

Is there a way to get all the form fields (type, label etc.,) so I can write a service to expose it as an API?

# Answer
> 1 votes
Since you are trying to get the node edit form (i.e. an entity edit form), you need to pass to `drupal_get_form()` also the node object to be edited, in the same way `node_page_edit()` does.

```
function node_page_edit($node) {
  $type_name = node_type_get_name($node);
  drupal_set_title(t('<em>Edit @type</em> @title', array('@type' => $type_name, '@title' => $node->title)), PASS_THROUGH);
  return drupal_get_form($node->type . '_node_form', $node);
}

```

Passing `NULL` as node object has the effect that some Drupal functions will *silenty* fail. For example, imagine the effect of the following lines when `$node` has been set to `NULL`.

```
  if (!isset($node->$key)) {
    $node->$key = (int) in_array($key, $node_options);
  }

```

The other effects of passing NULL to what Drupal expects to be a node object is that Drupal is not able to find which entity fields are attached to the content type of the node (which includes the body field), and it is not able to understand if the content type is set to show a title. The effect is Drupal not showing any form field to edit the title or any attached entity field.

---
Tags: forms
---


# Question
Title: Drupal site menu overlay stuck in Chrome Browser when scrolling down
I noticed a strange behavior in my drupal Portal when using Chrome. There is an overlay at the top of the page. In Chrome, that overlay gets “stuck” on the page and you can’t easily get rid of it, and it starts constantly flickering. If I refresh its fine and when I scroll down the problem appears again.

Any help or suggestions are appreciated. Thank you.

Please find the attached screenshot here:

```
enter code here

```

.fixed#header { position: fixed; top: 0; left: 0; padding: 18px 0; width: 100%; background-color: #fff; background-color: rgba(255,255,255,.95); -webkit-box-shadow: 0 2px 3px rgba(0,0,0,.2); -moz-box-shadow: 0 2px 3px rgba(0,0,0,.2); box-shadow: 0 2px 3px rgba(0,0,0,.2); transform: translateZ(0); } style.css?onmqdt:859

# header {

```
z-index: 99;
padding-top: 40px;
background-color: #fff;

```

}

# Answer
> 0 votes
i added these four lines of code to style.css file position: fixed; /\* apply these 4 lines only for chrome browser \*/ -bracket-:hack\[; position: sticky; position: -ms-sticky; \];

and reduce the speed in sticky.js file from 300 to 1. i have done these. now problem is resloved.

# Answer
> 0 votes
Hard to say without being able to inspect it, the `z-index` on `#header` won't work unless `position` is set to something other than `static` (the default value).

Try setting `#header` to be `position: relative;` or `position: absolute;` whichever is more appropriate and see if that helps, or at least helps narrow down the problem.

---
Tags: theming
---


# Question
Title: Entity field query pager only loads first page
How do I load any page other than the first page with Entity Field Query pager?

```
$query = new EntityFieldQuery();

$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->pager(4)
  ->execute();

```

This returns the first 4 nodes. If i have 12 nodes, how do I return page 2 nodes 4-8 or page 3 nodes 8-12.

The documentation states I can only pass `$limit` and `$element`. Have I missed something? What's the point of a pager that only loads the first page.

# Answer
> 2 votes
Here are some pointers:

* The query looks fine
* Try adding the parameter `?page=1` to your request and you should see different items. Page `0` is the one you see by default.
* You need to display the pager object while building your output, like: `$output['pager'] = array('#theme' => 'pager');` This will make the pager visible and allow users to click on back/next buttons to navigate through pages to see other items which are not on the current page.

---
Tags: 7, entities, database
---


# Question
Title: "PHP Fatal error: Call to undefined method Consolidation\AnnotatedCommand\Hooks\HookManager::getHookOptions()"
I just installed drush using "composer require drush/drush". It ran correctly and when it completes a navigate to vendor/drush/drush/ directory where the drush.php file is located

Then I run the following command: php drush.php status and I get the following error:

```
PHP Fatal error:  Call to undefined method Consolidation\AnnotatedCommand\Hooks\HookManager::getHookOptions() in
[...]/work/www/EnviePractice/vendor/drush/drush/includes/annotationcommand_adapter.inc on line 475
PHP Stack trace:
PHP   1. {main}() [...]/work/www/EnviePractice/vendor/drush/drush/drush.php:0
PHP   2. drush_main() [...]/work/www/EnviePractice/vendor/drush/drush/drush.php:12
PHP   3. Drush\Boot\BaseBoot->bootstrap_and_dispatch() [...]/work/www/EnviePractice/vendor/drush/drush/includes/preflight.inc:66
PHP   4. drush_dispatch() [...]/work/www/EnviePractice/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php:67
PHP   5. annotationcommand_adapter_add_hook_options() [...]/work/www/EnviePractice/vendor/drush/drush/includes/command.inc:170
Drush command terminated abnormally due to an unrecoverable error.                                                                      [error]
Error: Call to undefined method Consolidation\AnnotatedCommand\Hooks\HookManager::getHookOptions() in
[...]/work/www/EnviePractice/vendor/drush/drush/includes/annotationcommand_adapter.inc, line 475

```

Can anyone please guide me to what might be causing this?

Additional details:

1. I am on ubuntu 16.04
2. Drupal 8 installation
3. version of drush 8.1

# Answer
I think your installation or class registry might be broken. Try doing the following things:

* See if `drush rebuild` works (if it does not, go to the next point).
* Go to your Drupal install directory and try to run `composer install`.
* If `drush rebuild` didn't work in the first step, try running it again now.
> 0 votes

---
Tags: 8, drush
---


# Question
Title: Why does my node-type-specific hook not work
I have implemented a `hook_node_info()` as follows:

```
function mymodule2_node_info(){
  return array(
    'mynode1' => array(
      'name' => 'MyNode1',
      'base' => 'mynode1',
      'description' => t('A Description of MyNode1'),
      'has_title' => TRUE,
      'title_label' => 'Title',
    ),
  );
}

```

I'd specified the 'base' property as 'mynode1', So I would expect that an implementation of `mynode1_view()` would work when this node is viewed.

```
function mynode1_view($node, $view_mode){

}

```

But I get the error messages instead:

```
Notice: Trying to get property of non-object in node_build_content() (line 1413 of
C:\wamp\vhosts\mydrupal72\modules\node\node.module).
EntityMalformedException: Missing bundle property on entity of type node. in
 entity_extract_ids() (line 7880 of C:\wamp\vhosts\mydrupal72\includes\common.inc).

```

# Answer
> 3 votes
Be sure to return $node at the end of your `mynode1_view` function. (This is different from most hooks, which generally modify the variable by reference). You may have missed this. See this comment.

---
Tags: 7, nodes, hooks
---


# Question
Title: How do I enable editing the body of a block?
I have a block (in Drupal 7) with information in the body of it.

I want a specific user to be able to edit that information.

After assigning that user Administer blocks and Contextual links permissions the user can edit everything except the body and the following message shows:

Is there any way to enable the field for that user?

# Answer
You are facing this issue because you probably created the block as a user who has access to a text format like *Full HTML* but the other user doesn't have that permission :( Here's what you can do:

* Sign in as the root user (uid 1) who created the block;
* Change the text format to *Basic HTML* or *Restricted HTML*.
* Go to *Admin \> People \> Permissions* page and make sure the other non-admin user has the permissions to use the text format you applied.
* Depending on your requirements, you can ignore point 2 and give *Full HTML* permissions to the concerned user.
> 4 votes

---
Tags: blocks
---


# Question
Title: How to include a field's suffix when using its Token?
My user accounts have an integer field *Visits* with the suffix `visit|visits`. It is very handy to let Drupal automatically decide which suffix is appropriate. I would now like to use this field in a status message with the simple Rules action *Show a message on the site*. Unfortunately, when I set the message to `You currently have [site:current-user:field-visits].`, the suffix is not included, only the integer appears.

Is there a way to solve this? I would like to prevent a cumbersome Rule with an extra check on the value of *Visits* and an according adaptation of the message.

# Answer
AFAIK, field metadata isn't available in tokens. However, **Rules to the rescue!**

1. Create a rule set component which takes the field value as an integer parameter and two additional string parameters and provides a string value in return.
2. In your rule set, add a rule which checks to see if the value is one. If it is, set the provided string value with the integer value and the first string parameter.
3. Then, add another rule which does the same thing if the value is \> 1.
4. Now you have a string which is pluralized!

Here is an export:

```
{ "rules_pluralize" : {
    "LABEL" : "Pluralize",
    "PLUGIN" : "rule set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "integer" : { "label" : "Integer", "type" : "integer" },
      "string_one" : { "label" : "One", "type" : "text" },
      "string_many" : { "label" : "Many", "type" : "text" },
      "pluralized_version" : { "label" : "Pluralized version", "type" : "text", "parameter" : false }
    },
    "RULES" : [
      { "RULE" : {
          "IF" : [ { "data_is" : { "data" : [ "integer" ], "value" : "1" } } ],
          "DO" : [
            { "data_set" : {
                "data" : [ "pluralized-version" ],
                "value" : "[integer:value] [string-one:value]"
              }
            }
          ],
          "LABEL" : "Set string for one item."
        }
      },
      { "RULE" : {
          "IF" : [
            { "data_is" : { "data" : [ "integer" ], "op" : "\u003E", "value" : "1" } }
          ],
          "DO" : [
            { "data_set" : {
                "data" : [ "pluralized-version" ],
                "value" : "[integer:value] [string-many:value]"
              }
            }
          ],
          "LABEL" : "Set string for multiple items."
        }
      }
    ],
    "PROVIDES VARIABLES" : [ "pluralized_version" ]
  }
}

```
> 0 votes

---
Tags: 7, entities, rules, tokens, status-messages
---


# Question
Title: Adding logo to a custom theme as background image
I have a custom Drupal 8 theme that I'm working on. A requirement is that the client logo for this custom theme be a background image on an HTML object. I also need to add script that swaps the background image used between two different images depending on the background of the rest of the page.

Where do I add these CSS styles and the JavaScript code in Drupal 8 custom theme files?

# Answer
> -1 votes
Your custom theme will live in the folder themes/yourtheme

Inside your theme you can have a js and css directory and you can add your css/js files in those folders.

Inside your libraries.yourtheme.yaml file you can declare your library files

```

base:
  version: VERSION
  css:
    theme:
      css/style.css: {}
  js:
    js/script.js: {}

```

Inside yourtheme.info.yaml file you can call your declared libraries if you want them to load on every page:

```

libraries:
  - yourtheme/base

```

If you want the libraries to only load in some pages they can be called in the twig template files using the attach\_library() function:

```

{{ attach_library('yourtheme/base') }}

```

More in depth documentation can be found here

---
Tags: 8, theming
---


# Question
Title: how to make conditional fields work with MEDIA
I installed conditional fields for drupal 8 and i made a field be invisible or visible depending on the choice of another field which is an entity reference. but it doesn't work at all. It works for nodes , but not media. Any idea how to make it work for media?

# Answer
It was giving an error on getType when it was a media object.
I fixed it by changing line 208 in conditional\_fields.module to

```
if (method_exists($entity, 'getType')) {
      $bundle = $entity->bundle();

```
> 1 votes

---
Tags: 8
---


# Question
Title: Why is a URL alias messing up my view's contextual filter?
I'm having an issue configuring a URL alias that redirects content to a view with a contextual filter.

**Here's my working setup:**

1. I have a bunch of content of type SEEL Lesson Plan.
2. To display these lessons in a Library, I created a view with the path http://example.com/seel/
3. I set up a contextual filter (Content: Title) on the view. So, if you access http://example.com/seel/eat-an-apple, it will display the lesson with title "Eat an Apple" in the Library.

**Here's my objective:**

I want to override the "Save" button, so when clients edit any content of type SEEL Lesson Plan, it takes them to the library (http://example.com/seel/eat-an-apple) rather than the content page (http://example.com/content/eat-an-apple).

*How do I do that?*

---

**Here's what doesn't work:**

I added the following URL alias at http://example.com/admin/config/search/path/patterns:

I created a new content of type SEEL Lesson Plan that uses this URL alias. I can see it in my list of URL aliases (http://example.com/admin/config/search/path/list/seel):

But, when I go to http://example.com/seel/fdsa to test it out, it totally messes up. I'd include a screenshot if I could, but the HTML elements are literally all over the place -- displaying below the block on the left sidebar instead of in the main content pane, floating all over the footer, etc.

**Here's how I know it's a problem with URL aliases:**

When I go back and delete the URL alias seel/fdsa, and then go to http://example.com/seel/fdsa, it displays exactly how I set it up originally in the view.

As well: other lesson plans, for which there is no URL alias, display just fine. (For example: http://example.com/seel/eat-an-apple still works.)

*Why is this happening?*

# Answer
> 0 votes
At @Clive's suggestion, I ditched the idea of trying to do this with URL aliases, and instead set up a redirect with the Rules module.

This was done by going to /admin/config/workflow/rules, clicking "Add New Rule", and reacting on event "Content is viewed".

The final rule looks like this:

And it works :-)

---
Tags: views, nodes, path-aliases
---


# Question
Title: Send message to customer after the order has been created by administrator
I use Drupal Commerce version 7.x-1.x. I want to Send message to customer automatically after the order has been created by administrator on page admin/commerce/orders/add. How can i done it with rules or hooks (for example mymodule\_form\_commerce\_order\_ui\_order\_form\_alter) or other ways....

# Answer
> 0 votes
You could do that by adding a rule to fire on order update and checking to see if the order the order status was previously `somestate` and the current state now `processing` or `completed`.

Of course, you'd have to ensure that the states you wanted match your workflow.

---
Tags: 7, commerce, rules
---


# Question
Title: When I create a backup of a site, which directories and files should I include?
When I back up the files for a Drupal 8 site, which directories in the following list should be included?

* core
* modules
* profiles
* themes
* sites/default/
* Any directory matching sites/default/files/config\_\*
* sites/default/files/css
* sites/default/files/js
* sites/default/files/php
* sites/default/files/styles
* sites/default/files/field
* vendor

# Answer
The key directories are modules, themes, and profiles. You also want to backup all settings.php files, and uploaded files as well. Although, I would separate the two into two backup files, since, depending on the site, the uploaded files directory could be in the low MBs or hundreds to even GB of files. Give them both a readable date timestamp for a filename.

Also, backup your composer.json and composer.lock files. If you control your site build using Drupal Project or Acquia BLT which has a composer driven approach, composer.json will contain the information needed to rebuild your site (this does not include data, only code). Then it's just a matter of backing up custom modules and custom themes, since composer can fetch all the code and rebuild core.
> 1 votes

---
Tags: 8, backups
---