# Question
Title: How to edit and theme Comments & Comments form?
I am building a drupal site using drupal 7 and the adaptivetheme.

I created some a content type called recipes. Than I created a content pane in views to present recipes in panels. I add the comments and comments form to the same panel.

Now I want to present beneath any recipe a comment form and all other comments. My problem is that I don't know how to edit the presentation of the comment form. When I checked the comment fields on my content type, I saw only the field "comment\_body".

How can I edit the fields and the way they will show on Comments & Comments form?

Below is a screenshot.
I want to remove the field "your name", and change the button "save" to "post comment". How can I do that?

Thanks!

# Answer
You can copy the file called **comment.tpl.php** from the folder where base AT theme is located (something like adaptivetheme\at\_core\templates) and paste it into sites\all\themes\YOUR\_AT\_SUBTHEME\templates.

Assuming recipes is the machine name of your content type, you can also name it **comment--recipes.tpl.php** if you want to theme specifically comments for recipes.

Then with the help of comment.tpl.php API (you can also find a lot of information in the php file itself), you can edit the way your comments will be displayed.

I.e instead of

```
print render($content);

```

You can display specific fields :

```
print render($content['comment_body']);

```

or hide specific fields

```
hide($content['author']);
print render($content);

```

To alter the form itself, you need to use `hook_form_alter()` in a custom module.

```
/**
 * Implements hook_form_alter().
 */
function YOUR_CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
  //get the form id
  drupal_set_message("Form ID is : " . $form_id);
  $print = '<pre>' . print_r($form, TRUE) . '</pre>';
  drupal_set_message($print);

  switch($form_id){
    case 'YOUR_COMMENT_FORM_ID':
      //alter your form (with the complete correct fields names)
      $form['YOUR_FIELD_YOUR_NAME']['#type'] = 'hidden';
      $form['YOUR_FIELD_SUBMIT']['#value'] = t('Post comment');
    break;
  }
}

```

You can also use `dpm($form)` if you have Devel installed, or make a

```
$print = '<pre>' . print_r($form, TRUE) . '</pre>';
drupal_set_message($print);

```

in order to retrieve the exact form fields
> 3 votes

# Answer
When using the solution form @Kojo, if you don't want to use your own module, create a function in `template.php`:

```
function THEMENAME_form_FORMID_alter(&$form, &$form_state) {
    //...
}

```

For example

```
function bartik_form_comment_form_alter(&$form, &$form_state) {
    //...
}

```

This code will change all comment forms, you can be more specific and provide an id of the form of some type. To get the *FORMID*, open the rendered page and find the following field in html:

```
<input type="hidden" value="HERE-WILL-BE-THE-FORMID" name="form_id">

```
> 1 votes

# Answer
you can do this by loading the comment form.

$comment = comment\_load($cid); // $cid is comment id $form = drupal\_get\_form('comment\_form', $comment); print drupal\_render($form);

url: https://api.drupal.org/api/drupal/modules!comment!comment.module/function/comment\_load/7.x
> 0 votes

---
Tags: views, panels, theming, comments
---


# Question
Title: How to pass argument from one view to another view?
I have filter in separate view and want to pass the value to another view and get the filter result in Drupal.

**Scenario:** I have two views, one for filter and another for filter result.

I want to filter based the `content: title`. In another view I have to fetch the result and display based on title filter.

My question: How can I argument from one view to another view?

# Answer
Here is how you can do it programmatically:

```
// load and display view A
$view_A = views_get_view('view_A_name');
// execute view
$view_A->execute();
// get all nids from the result
foreach ($view_A->result as $result) {
   // capture the result of your field in an array.
   $values[] = $result->field_machine_name;
}
// render view
print $view_A->render();

// now load view B
$view_B = views_get_view('view_B_name');
// set arguments for view
$view_B->set_arguments(array(implode(",", $values)));
// execute view
$view_B->execute();
// render view
print $view_B->render();

```
> 3 votes

# Answer
Use Views Field View module

> There are a lot of cases in views where you want to embed a list inside each row. One example could be, you have a list of groups, and for each groups you want to list the first and last name of all of their members.
>
> This can be achieved with this module, as views\_field\_view allows you to embed one view into another view and pass arguments along.

And Also if You are developer and you want to achieve it programmatically you can use views\_get\_view function.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How can I make my ubercart catalog content available to users?
I can't make my ubercart catalog content available to logged in users.

They can see the catalog **page title** but not the products.

This is what a logged in User can see:

This is my catalog views settings:

What I tried: I changed the rights for users already as shown below. Nothing happens.

What else am I missing?

# Answer
> 2 votes
Since you mention that authenticated users can't access your Product nodes, it's most likely that your nodes aren't published, or that there is a module interfering with the access check.

**First**, check if your nodes are actually published, on the Create or Edit form:

**Second**, go to `/admin/people/permissions` and check if anonymous users have the `View published content` permission.

**Third**, are you using any modules like Node Access that might alter the access permissions?

---
Tags: ubercart
---


title: What is wrong with hook_schema()?

text:
# Question
Title: What is wrong with hook_schema()?
```
    function recipe_submit_schema() {
  $schema['recipe_submit'] = array(
    'description' => 'Recipe base table.',
    'fields' => array(
      'recipe_id' => array(
        'description' => 'Primary identifier for recipe.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not_null' => TRUE,
      ),
      'recipe_title' => array(
        'description' => 'Recipe Title.',
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
      ),
      'author_name' => array(
        'description' => 'The author of the recipe.',
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
      ),
      'author_email' => array(
        'description' => 'The author email.',
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
      ),
      'recipe_description' => array(
        'description' => 'Recipe description.',
        'type' => 'text',
      ),
      'recipe_instructions' => array(
        'description' => 'Recipe instructions.',
        'type' => 'text',
      ),
      'recipe_ingredients' => array(
        'description' => 'Recipe ingredients.',
        'type' => 'text',
      ),
    ),
    'primary key' => array('recipe_id'),
  );

  return $schema;
}

```

gives me following error

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1171 All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead in /home/insasse/test_workspace/drupal7/includes/database/database.inc:2227                                                     [error]
Stack trace:
#0 /home/insasse/test_workspace/drupal7/includes/database/database.inc(2227): PDOStatement->execute(Array)
#1 /home/insasse/test_workspace/drupal7/includes/database/database.inc(697): DatabaseStatementBase->execute(Array, Array)
#2 /home/insasse/test_workspace/drupal7/includes/database/schema.inc(664): DatabaseConnection->query('CREATE TABLE {r...')
#3 /home/insasse/test_workspace/drupal7/includes/database/database.inc(2776): DatabaseSchema->createTable('recipe_submit', Array)
#4 /home/insasse/test_workspace/drupal7/includes/common.inc(7114): db_create_table('recipe_submit', Array)
#5 /home/insasse/test_workspace/drupal7/includes/module.inc(479): drupal_install_schema('recipe_submit')
#6 /home/insasse/.composer/vendor/drush/drush/commands/core/drupal/environment_7.inc(143): module_enable(Array)
#7 /home/insasse/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1167): drush_module_enable(Array)
#8 /home/insasse/.composer/vendor/drush/drush/includes/command.inc(422): drush_pm_enable('recipe_submit')
#9 /home/insasse/.composer/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#10 /home/insasse/.composer/vendor/drush/drush/includes/command.inc(199): drush_command('recipe_submit')
#11 /home/insasse/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#12 /home/insasse/.composer/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#13 /home/insasse/.composer/vendor/drush/drush/drush.php(12): drush_main()
#14 {main}

```

What am I doing wrong?

# Answer
Try replacing 'primary\_key' with 'primary key'
> 1 votes

# Answer
Change from `'not_null' => TRUE`, to `'not null' => TRUE`.
> 1 votes

---
Tags: 7, database
---


# Question
Title: How do I check a value when creating new content?
My rule fires after saving new content. The first condition to configure has to be **entity is of bundle** Src. I don't know how to setup this condition correctly. I chose Entity:node, Type: MY\_CONTENT\_TYPE, Bundle:Default. Which doesn't work.

What would I have to enter to make this work using the Rules module?

# Answer
> 0 votes
You should try to use the "entity has field" Rules Condition (instead of **entity is of bundle**). In my experience that one works to make that field available as a token in subsequent Rules Conditions and Rules Actions.

If you have other reasons why you need to add that **entity is of bundle** condition also (I doubt, but one never knows ...), that's fine too, but make sure to do so only after the "Entity has field" Rules Condition.

Refer to the answer to "How to specify a Rules condition related to select list values?" for an example rule.

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

PS: I'm assuming this question is about D7 ...

---
Tags: rules
---


# Question
Title: How to automatically assign a role based on email address domain?
How do I automatically assign a role to new users based on the email address domain?

For instance if the email address is `someone@examplecompany.com`, and the condition is that all users from `examplecompany.com` should always have the role `specialclient`. How do I acheive this?

I am using Rules, but there are no specific email conditions to be found. Can I create my own Rules Condition? If so, I would be very grateful for any tips on how to accomplish this.

# Answer
Yes you could create your own (custom) Rules Condition. But in this case I don't think that's needed. The clue to what you're asking for, is a Rules Condition which is a "text comparison".

In that comparison, you use a regular expression to indicate "the email address should end with "`@examplecompany.com`".

For an example rule which also uses such RegEx-expressions, refer to the answer to "How to use the Rules module to perform a simple anti-spam validation using specific keywords?".

Be aware: I'm not a RegEx expert ..., but here a few dozens of similar examples using a RegEx ...

**However**, I predict you'll have multiple domains/roles to be processed. So the real Rules fun starts when this (typical) question arises: "*I need to add something like a Rules Condition inside the Rules Actions, how can I do that?*"

To resolve this typical question, there are basically 2 approaches (that I am aware of):

* Use the Conditional Rules module. For an example using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".
* Rework the relevant part of your Rules Action(s) into performing a Rules Component. Because in a Rules Component, it is possible to also add Rules Conditions.
> 1 votes

---
Tags: 7, rules, hooks
---


title: How to dpm() an object value?

text:
# Question
Title: How to dpm() an object value?
If I run `dpm($form);` I get an array containing objets. Now I need to **just** dpm() the uid of the node object.

How do I do dpm() to isolate an object value?

I tried with `dpm($form['#node']['uid']);` but not working.

Please look the capture to make my question clear:

# Answer
You would use:

```
dpm($form['#node']->uid);

```

As you rightly say the `#node` variable is an object, and object properties in PHP are accessed using the `->` operator.

Have a peek at the PHP Objects documentation for a few more details.
> 6 votes

# Answer
In your `dpm()` output, you can simply double-click the line of interest and the correct concatenation will expand just beneath that line. See the example on `dpm($node)` below.

Before double-click:

After double-clicked `target_id`:
> 0 votes

---
Tags: debugging
---


# Question
Title: How to add country suffix to the hreflang tags?
I am working on a multilingual site. In which I am using Alternate hreflang module and everything working as expected.

But it should look like

```
    <link href="/es" rel="alternate" hreflang="es-ES" />
   <link href="/es" rel="alternate" hreflang="es-MX" />
    <link href="/es" rel="alternate" hreflang="es-AR" />

```

Means in *hreflang* need to add country name as suffix like **es-ES**, **es-MX** etc.

Tried like below but its not working.

# Answer
> 0 votes
This cannot be achieved in the Alternate Hreflang module or any other Drupal module. They all use the language code as the hreflang code which is incorrect as hreflang contains 2 parts - the language "es" and the country "ES" (Spanish, Spain) or in your example es-MX (Spanish, Mexico).

I've had three or four contributors (metatag, Alternate Hreflang) come back to me and state that you need to create custom languages for this to actually work. So for Mexico create a new language and use the code es-MX then this will show the appropriate hreflang code es-MX. However it will a) create an unnecessary language b) probably require Language Hierarchy to avoid superflouous translations c) also show in the URL as es-MX which in my opinion is also not ideal (the MX is in UPPERCASE and the URL will always be flattened to lowercase on output not ideal for SEO or asthetics...)

Off the shelf them's your options me thinks.

I would suggest coding some simple patch to the Alternate Hreflang module to include the ISO list of country codes so through a UI you could add whatever country you liked alongside the any *enabled* language into the hreflang code.

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


# Question
Title: How can I access untranslated field values in a translated view row?
If you add the title field to a view you can use the token `title__raw` as a pattern. I just created a custom field for use in view named dossier\_status and I need to create something a like `dossier_status__raw` token. The reason is that the status can be translated to different languages but I need the status always in english to use it as a css class. How can I accomplish this?

For the moment I have another field named `dossier_status_machine_name` (with the status always in english) But I think that this is not the best approach.

# Answer
It seems not to be possible to access untranslated field values in a rewrite token pattern for text fields. You can get the untranslated value from the field in a template by using the row entity and getting the untranslated entity `{{ row._entity.getuntranslated().field_dossier_status.value|clean_class }}`, but using templates in Views I would avoid if possible. So this may be a better approach:

**Static**

Supposed that there is a limited number of CSS classes, in most cases CSS is static, use a field `field_dossier_status` of the type *list (text)* with a allowed values list:

```
dossier-status-class-1| Dossier Status Class 1
dossier-status-class-2| Dossier Status Class 2
...

```

You can translate the second part of the allowed values in *Translate content fields*.

Now if you access the raw value from this list field in a Views token pattern `__value` you get the untranslated first part

```
<div class="{{ field_dossier_status__value }}">

```

and this result:

```
<div class="dossier-status-class-1">

```

**Dynamic**

If the CSS is dynamic you can use a dynamic method for the allowed values, see Dynamic Default and Allowed Values for List Fields in Drupal 8, which btw. gave me the initial idea for this answer to the question you asked some days ago. You could even parse the dynamic CSS for the classes it provides and fill them in the allowed values list.
> 2 votes

# Answer
Lets pretend your status is `open` and `closed`

Give this a try (untested) in rewrite results of your dossier status field.

```
{% if field_dossier_status == 'open'|t %}

<div class="dossier-open">{{ field_dossier_status }}</div>

{% elseif field_dossier_status == 'closed'|t %}

<div class="dossier-closed">{{ field_dossier_status }}</div>

{% endif %}

```

If it does not work, then try with a views fields template file, **views-view-fields--\[view-name\].html.twig**

```
{% if fields.field_dossier_status.content|striptags == 'open'|t %}

<div class="dossier-open">{{ fields.field_dossier_status.content }}</div>

{% elseif fields.field_dossier_status.content|striptags == 'closed'|t %}

<div class="dossier-closed">{{ fields.field_dossier_status.content }}</div>

{% endif %}

```

Hopefully one of these will work.
> 1 votes

---
Tags: views, 8, tokens
---


# Question
Title: Render a field from an entity reference in twig template?
I have a node that has an entity reference field to a Media entity. That media entity has a field on it "caption". I want to render this caption directly in my twig template, so instead of doing this:

```
{{ content.field_media_item }}

```

Which would output the entire rendered media entity, I just want to output a field from that media entity. I've tried this:

```
{{ content.field_media_item[0]['#media'].field_caption.value }}

```

Which works, but since it's already rendered output, all the HTML from that value is escaped. So `<p>` tags appear as literal `<p>`. I could tack on a `|raw` at the end, which actually seems safe to me since I know the output has already been rendered and passed thru the field formatter, but seems wrong?

What's a better way of doing this? Using a pre-processor to access the field data from the reference media entity and passing it through a field formatter again or something? That actually seems inefficient since the caption field data was already rendered properly, and I'd be passing it thru the formatter again.

# Answer
After some more thought and research, I think the best approach to this problem is to use a theme pre-processor function to manually prepare the entity reference field.

The main issue is that the referenced entity has a formatted text field that I need to output. That means it needs to run through the formatter before it's considered safe for output.

Manually accessing the value through the entity object in Twig is not a good solution because it will just print the raw value from the database, which twig will by default escape. Tacking on `|raw` makes it unsafe because it still hasn't run through the text processor.

Here's a preprocessor snippet that does what I need:

```
/**
 * Implements hook_preprocess_node().
 */
function MY_THEME_preprocess_node(array &$variables) {
  $node = $variables['node'];
  if ($node->bundle() == 'news') {
    // Extract the caption from the cover image media entity and prepare it manually. We do this because in our template, we render the caption separately from the image.
    if (!$node->field_news_cover_image->isEmpty()) {
      $image_media_entity = $node->field_news_cover_image->entity;
      $caption_field = $image_media_entity->field_media_caption;
      // Caption is formatted text, so we must output a render array that will
      // process the text with the appropriate filter.
      $variables['cover_photo_caption'] = [
        '#type' => 'processed_text',
        '#text' => $caption_field->value,
        '#format' => $caption_field->format,
        '#langcode' => $caption_field->getLangcode(),
      ];
    }
  }
}

```

This allows me to simply print `{{ cover_photo_caption }}` in the twig template.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Variables / settings configurable in Admin UI?
I need a simple way to make some custom variables / settings configurable for an Editor in Drupal 8. They are not related to Drupal, only to the custom project. For instance, the editor shall be able to set an **Affiliate ID** that will be used in the external links of the site.

In Drupal 7, I would have used Variable: I would have defined some variables and they would have been editable under `admin/config/system/variable`.

Since Variable has not been ported yet to Drupal 8, I am looking for a simple way to get this done in D8.

One idea I came up with was to define some "Magic Nodes", like `node/1` for my first variable, and then use its title to set the value. However, that looks very hacky and unintuitive to me.

Do you have any better idea?

# Answer
> 1 votes
According to the change record The variable\_get/set/del API is now removed you would need to store the settings in configuration. You can make this configuration available to an Editor by providing a Configuration Form or if you only want to add a few fields you can extend an existing configuration form in a form alter hook. For example add the *Affilate ID* to the *Basic Site Settings*. Similar to this example for the menu configuration: How to add field to menu

---
Tags: 8, configuration
---


# Question
Title: How can I access database variables in my custom module
I have used PDO DB connection in my custom module. I wanted to know how can I access the Database variables from (settings file) in my custom module. Or is there any way to make PDO DB connection globally so that it can be used every where it needed in custom module.

My code is below:

```
function my_module_init() {

    $path_val=request_path();

    $exploded_val=explode("/",$path_val);

    $value1=$exploded_val[4];

    if($value1=='test')
    {

    $servername ="host";
    $username = "test1";
    $password = "test2";
    $dbname = "test3";

    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $query = $conn->exec("TRUNCATE TABLE table_name");

    $sql = "INSERT INTO table_name (test_id)
    VALUES ('$test_id')";
    $conn->exec($sql);
    $conn = null;

    }
    }

```

# Answer
You don't need to access the connection variables directly. Drupal 7 comes with a full database API that handles the connection for you, and can be used from anywhere in your module. Some common functions in the API are db\_query(), db\_select(), db\_insert(), db\_update, db\_delete() and db\_merge()

You can read all about the Database API here: https://www.drupal.org/docs/7/api/database-api/database-api-overview
> 2 votes

---
Tags: database
---


# Question
Title: Cache busting for images in Drupal 7 and lightbox 2
Scenario: I have content type with a field 'images' (Widget: plupload). View created and displayed on Home page. View has **Formatter: LightBox2, LightBoxType: Single Lightbox, Image-Style: *thumbnail* image-style for the images.** Whenever user click on image, LightBox2 shows original image.

Problem: Everything working fine. But the images are getting cached in browser cache. Hence I followed https://www.drupal.org/node/2313539 Cache Busting discussion and changed theme.inc theme\_image() function. Now the thumbnails have time(cache busting string) in their name but lightbox still the same. I get the point that i have write or hook the formatter as well to make it work in views. Not sure where and what should change in LightBox module or elsewhere.

This is what HTML looks like on page

```
<a href="sites/default/files/images/3.jpg" rel="lightbox[field_images][<p><a href="sites/default/files/images/3.jpg" title="Download Original" download="">Download Original</a></p>]" title="" class="lightbox-processed">***<img typeof="foaf:Image" src="sites/default/files/styles/app-thumbs/public/images/3.jpg?itok=-OKZ8zZW&hash=2563415" width="200" height="200" alt=""></a>

```

where `<img>` tag has `src` url appended with '`&hash=2563415`' i.e. cachebust string, but anchor-element doesn't have the same. Any ideas how to make Lightbox2 anchor element to include cachebust string element as well. Drupal version:7.41, LightBox2

# Answer
> 0 votes
OK, I solved it. Cachebuster can be implemented as discussed in shared url for drupal 7 by editing includes/theme.inc, and theme\_image function. Just add `attributes['src']`with a random string say time(). Further, lightbox2 module can be tweaked to append random string in a href, by editing lightbox2/js/lightbox.js, just edit `start: function(imageLink, slideshow, lightframe, lightvideo, lightmodal) {}` and append `anchor.href` with `new Date().getTime()`.

These two tweaks will make sure that drupal is giving img src appended with time and lightbox2 inserting time() in anchor href. Browser will never cache these images.

---
Tags: media, javascript, theming
---


title: Accessing fields in views twig template

text:
# Question
Title: Accessing fields in views twig template
I've got a content type `article`. I display them on a view `blog`.

I'm customising the display via `views-view-fields--blog.html.twig`. I'd like to display the author and date fields (they are configured in the view). The other fields display fine, but how do I access those two?

```
<div class="blog-article">
  <div class="blog-image">
    <a href="blog-single-right-sidebar.html">{{ fields.field_image.content }}</a>
  </div>
  <div class="blog-details">
      <!-- Here is where I need the author and date fields -->
      <div class="blog-date">
        Posted by <a href="blog-masonry-2columns.html">{{ ??? }}</a> | {{ ??? }}
      </div>
      <div class="blog-title">{{ fields.title.content }}</div>
      <div class="blog-short-description">{{ fields.body.content }}</div>
  </div>
</div>

```

# Answer
I've added both node created and node changed fields to my views before, this is how I output them:

```
<span class="label">Date Created:</span> {{ fields.created.content }}
<span class="label">Date Modified:</span> {{ fields.changed.content }}

```

I assume user would work the same way. It will render in whatever way the view field is configured.

For example: `{{ fields.uid.content }}`
> 3 votes

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


# Question
Title: Displaying one node for each unique field reference in View (e.g. one videogame for each developer)
I have an view that display my custom content type (e.g. covers of video game titles).

Lets assume that I have this structure for my content types:

```
developer
|--title
|--country
...

video game
|--title
|--body
|--developer_ref (term reference, as choice list)
...

```

It works ok except for one thing. I want to display only one video game per developer here (the newest one).

So for example, if we have 3 different developers I want to display 3 items and each of it its the latest node referenced to each developer.

I know how to display 3 latest nodes, but that way they can e.g. all come from one developer.

I have already tried with agreegation on `video game.developer_ref` field:

But I don't know why it doesn't change a thing (I still see multiple games for some developers).

# Answer
UPDATE:

This unfortunately only works if your developers were users. After reading your question again, it appears you have created them as content, in which case my answer does not work.

---

Views has a built-in feature for this called 'Representative node'. This can be used to

> Obtains a single representative node for each user, according to a chosen sort criterion.

So how to use this:

* Start off by creating a view that lists `users` and add the `Representative node` relationship (in the advanced section).
* Configure the selection criteria; in your case this would be 'Content: Authored on'.

This adds a relationship to Views, allowing you to add fields to the view. If you want to show the rendered node instead of individual fields, add the `Rendered entity` field instead:

No need for aggregation.

*Do note that this will always fetch the last node the user has created of every content type. You should add additional filters to the view to limit this to game-nodes, etc.*
> 0 votes

---
Tags: 7, views
---


# Question
Title: Disable form or block cache for anonymous users?
I have two forms in Drupal 8 that I am prepopulating values with *if* a value exists in the query string.

```
$keywords = Xss::filter($this->requestStack->getCurrentRequest()->get('keywords'));

$form['keywords'] = [
      '#type' => 'textfield',
      '#maxlength' => 128,
      '#size' => 64,
      '#default_value' => Unicode::strlen($keywords) ? $keywords : '',
      '#prefix' => '<div class="search-box__input js-search-input">',
      '#suffix' => '</div>',
      '#required' => TRUE,
      '#attributes' => [
        'placeholder' => Unicode::strlen($keywords) ? $keywords : t('Search Site'),
      ]
    ];

```

Works great for authenticated users, but for anonymous users, they are always seeing the last term entered, despite the query string having nothing in the URL. Even if I close the browser and come back, the term is still in the input field. I assume it gets cached.

The form is being attached as a twig variable to a block containing other content:

```
/**
 * Implements hook_preprocess_block().
 * @param $variables
 */
function mytheme_preprocess_block(&$variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $variables['block_content'] = $variables['elements']['content']['#block_content'];
  }

  // inject main nav search form to block template for main_nav only
  if ($variables['elements']['#id'] == 'main_nav') {
    $variables['main_nav_search_form'] = \Drupal::formBuilder()->getForm('\Drupal\mymodule_search_forms\Form\MainNavSearchForm');
  }
}

```

Is there a way to change this so that does not happen? Any cache tag I could use?

# Answer
What you need need to do, is not to use a cache tag but a cache context. In your specific scenario you want to use `url.query_args:keywords`. In code that would look like this

```
$form['keywords'] = [
   '#cache' => ['contexts' => ['url.query_args:keywords']],
   ...
];

```

### For reference.

Cache **tags** are used to invalidate cache. Like if a cache element is tagged with `node:1` and node with nid 1 is updated, then all cache containing `node:1` cache tag is invalidated (other tags are also invalidated).

Cache **contexts** are used if cached element exists in multiple variations based on something like the query arg. What happens is that multiple cache entries are created and they will all be invalidated based on the same logic (cache tags).
> 9 votes

---
Tags: 8, forms, caching
---


title: Drupal 8 Apply Custom Theme To View

text:
# Question
Title: Drupal 8 Apply Custom Theme To View
I have a Drupal 8 installation set up that is using a custom Bootstrap theme as the default theme. I have a View created to be a blog, and want to give it a different custom theme than the default. I have the path set as "/blog". Is there a simple way of doing this through code (specifically referencing either the URL or the view) or a menu option I've overlooked?

I've looked at other related questions on here such as: How to apply theme to Drupal view or block

But in my View display settings there is no "Theme : Information" option available.

Any help is greatly appreciated! If there is more details I can provide for a solution, please let me know!

# Answer
> 0 votes
Drupal 8 views doesn't have a Theme: Information section, or at least it doesn't have information about themes.

Twig is the themeing engine, so you'll need to get information there. You can enable twig debugging in a `services.yml` file:

```
parameters:
  twig.config:
    debug: true

```

This will print out theme-able names for views in the html. On a site I'm looking at the print out only gives one option for the view:

```
<!-- BEGIN OUTPUT from 'themes/custom/sitename/templates/block--views-block--our-leadership-senior-management.html.twig' -->

```

But the block that holds the view has a number of options:

```
<!-- FILE NAME SUGGESTIONS:
x block--views-block--our-leadership-senior-management.html.twig
* block--views-block.html.twig
* block--views.html.twig
* block.html.twig
-->

```

The `x` indicates that's the template I'm using.

---
Tags: views, theming
---


# Question
Title: From a custom module. How can I get the typed value from a textfield and put it in a variable?
In a drupal page, I have a form where I need to read a text field value of an element, via javascript, when it is typed by the user, just after the input field lost the focus and before submit is done, I need to save it in a variable.

# Answer
> 2 votes
All entered values are in the `$form_state` array on submit. It is up to you to process that data and store it in a variable.

For example...

```
function mymodule_myform_submit($form, $form_state) {
  $text = $form_state['values']['myfield'];
  variable_set('mymodule_var', $text);
}

```

Then wherever else in the site you want to show it...

```
$myvar = variable_get('mymodule_var', '');

```

Of course, be sure to validate your input in the validate handler and anything else you want to process and save. This is pretty much the most basic approach in 7 to collect and store variables (especially not knowing the rest of your setup).

---
Tags: 7, forms
---


# Question
Title: $base_url variable in settings.php is not being read. How do i set this variable?
On my laptop I recently moved my Drupal sites from Acquia Dev Desktop server to a standard MAMP setup. Problem is the root dir folder isn't being read. The root dir folder name would be, by default part of the base url. For example, the mission page URL should be `http://localhost:8888/mywebsite/mission`. But instead it's trying to load as `http://localhost:8888/mission`.

Since using Drupal I haven't had to once set a base url variable. In the settings.php file I found a variable for this which I uncommented and set. On line 282 in the settings file it now reads as like so:

```
$base_url = 'http://localhost:8888/mywebsite';

```

but this is having no effect whatsoever.

How or where can this be set? Or is there something I should do within the MAMP set up?

# Answer
Add a virtual host to the web server and use the directory where Drupal is installed as its document root directory.

```
<VirtualHost *:8888>
  DocumentRoot "/var/www/website"

    # Other directives
</VirtualHost>

```
> 1 votes

---
Tags: migrations
---


# Question
Title: How to prevent a View from rendering via a hook?
I want to prevent an attached view from running depending on some coding parameters.

I've tried using `hook_views_pre_view()` to prevent it from running, but I can't figure out what options to set on the view to accomplish that. Tweaking `attached` or `rendered` doesn't seem to do anything.

```
function ding_eresource_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'eresource_list' && $display_id == 'attachment_1') {
    // Prevent rendering if parent view has some option set.
    if (!empty($view->old_view[1]->barr)) {
      // This does not work. How can it be done?
      $view->attached = FALSE;
      $view->rendered = TRUE;
    }
  }
}

```

How can it be done?

# Answer
> 3 votes
`$view->executed = TRUE;` worked for me but I'm not sure it is a correct way to stop Views from rendering.

# Answer
> 4 votes
Wanted to do similar but just `$view->executed = TRUE;` made the query in the view still run. Looking at `view::build()`, I understood you need the following code, to prevent anything running further in the view (displays and query).

```
$view->executed = TRUE;
$view->built = TRUE;

```

To make it clearer, the code you should use is the following one.

```
function ding_eresource_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'eresource_list' && $display_id == 'attachment_1') {
    // Prevent rendering if parent view has some option set.
    if (!empty($view->old_view[1]->barr)) {
      // This does not work. How can it be done?
      $view->executed = TRUE;
      $view->built = TRUE;
    }
  }
}

```

# Answer
> -1 votes
Options for `hook_views_pre_render`:

```
$view->result = array();

```

That destroys the array, preventing any data from rendering.

Or, the plain PHP option:

```
die();

```

---
Tags: views
---


# Question
Title: Alter Commerce Line Item Order Edit Form
I would like to add a column on the line item table on the orders edit page. I've tried to use `theme_registry_alter($theme_registry)` to override the commerce line item `theme_commerce_line_item_manager`, but it seems like it's not working. Below is my code:-

```
function MODULE_theme_registry_alter($theme_registry) {
  if (isset($theme_registry['commerce_line_item_manager'])) {
    $theme_registry['commerce_line_item_manager']['theme path'] = drupal_get_path('module', 'MODULE');
    $theme_registry['commerce_line_item_manager']['function'] = 'MODULE_commerce_line_item_manager';
  }
}

function MODULE_commerce_line_item_manager(&$variables) {
  return 'Print something';
}

```

Am I missing something? Or is there any other way to alter the display or add a new column on the table?

I've also created a patch, but I don't feel it's the solution to alter the display. Please help. Thank you in advance.

# Answer
If you want to add an editable column, you cannot do that just through the theme layer (though I think the same would hold true even for a non-editable column). Instead you need to alter the form element that gets created, even if it's just through an order edit form level alteration. First you need to create the elements you need in the form array and then you can override the theme function to ensure they get rendered into the table in the right column.

You should also look up documentation on how to override theme functions in general. You shouldn't need to alter the theme registry, just place the theme function in your theme's template.php, copy the functionality of the default theme function, and alter it to your need.
> 2 votes

---
Tags: commerce
---


# Question
Title: Notification when a shopping cart is abandoned
How to create a notification when a shopping cart is dropped ?

I wish that the user who has not completed his / her order, receives an email 1 day after, to tell him that he has a basket in progress.

I think this should be possible with the "Rules" module.

Thank you

# Answer
I'd start by trying the existing Commerce Abandoned Cart Notification module. This module was specifically designed to send abandoned cart notifications.

> This module allows you to notify your customers by email about their abandoned their cart.
>
> *Abandoned Shopping Cart mailings generate more than 55% more conversion compared to regular email campaigns. –SeeWhy research (2011)*
>
> Features
>
> * List your customers abandoned carts
> * 100% integration with Commerce VBO
> * Edit the notification email directly from the Rule component
> 1 votes

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


# Question
Title: Why does drush en node_clone end up in a circle
this pretty much says it all:

```
drush en node_clone
node_clone was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                                             [ok]
node_clone
Would you like to download them? (y/n): y
Install location /xxx/sites/all/modules/node_clone already exists. Do you want to overwrite it? (y/n): y
Project node_clone (7.x-1.0) downloaded to /xxx/sites/all/modules/node_clone.                            [success]
Project node_clone contains a module named clone.
node_clone was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                                             [ok]
node_clone
Would you like to download them? (y/n): y
Install location /xxx/sites/all/modules/node_clone already exists. Do you want to overwrite it? (y/n): n
Skip installation of node_clone to /xxx/sites/all/modules/node_clone.                                    [warning]
node_clone was not found.                                                                                [warning]
The following projects provide some or all of the extensions not found:                                                                             [ok]
node_clone
Would you like to download them? (y/n): n

```

# Answer
> 1 votes
Seems this has been well answered in drupal.org

Commands need to be

drush dl node\_clone

but

drush en clone

Discussions about the 'naming standards' are here

---
Tags: 7, drush
---


# Question
Title: Is there a token for the key of a text list?
I need to get the key of the key|value pair from a text list field in a token.

Say the field configuration shows the following options:

```
no|No Way Jose!
yes|Why yes, that'd do nicely!

```

and the field is named `field_doc_textlist`

the token \[node:field\_doc\_textlist\] is returning a value like '*No Way Jose!*' when what I want is '*no*'. Is there a way to get that from tokens. I'm using this in the filefield paths module if that matters.

I saw other similar answers here, with no real answers, but I've tried \[node:field\_doc\_textlist:key\] \[node:field-doc-textlist\] \[node:field\_doc\_textlist:machine\_name\] \[node:field\_doc\_textlist:machine-name\] all to no avail

Some additional information: All of the above result in an error similar to

> The File path is using the following invalid tokens: \[node:field-doc-type-book\].

A lot of the information I've found suggests using the hyphenated version of the token name instead of the underscore version, but that seems not to work at all.

# Answer
You could use roborew's sandbox: Entity Token Display

> This simple module was created to handle the formatting of entity tokens.
>
> When using certain field entities the entity token module will provide formatting and data sanitisation for display. However, there are times when you need the default value of the original field.
> 1 votes

# Answer
Say you have field\_textlist on node\_mytype.

* Go to admin/structure/types/manage/node-mytype/display and in the *custom display settings* tab, enable the *token* display mode
* Go to admin/structure/types/manage/node-mytype/display/token, go to field\_textlist and and set *key* as formatter
* Use \[node:field\_textlist\] (underscores) provided by token module, not \[node:field-textlist\] (dash) provided by entity api module.
> 1 votes

---
Tags: 7, tokens, entities
---


# Question
Title: Programmatically get a list of all fields?
How to retrieve a list of fields, similar to what is available at `admin/reports/fields`, but so that I can have them in an array that I can stuff in a select dropdown.

# Answer
> 8 votes
You should use field\_info\_fields(), which returns an array containing information about all the defined fields. Its output is similar to the following one.

# Answer
> 2 votes
You can also use field\_info\_field\_map() it returns a lightweight map of fields across bundles. field\_info\_fields() also return fields list but its document suggesting us **"Use of this function should be avoided when possible, since it loads and statically caches a potentially large array of information.".**

The function only returns active, non deleted fields.

$field\_list = field\_info\_field\_map();

dsm($field\_list);

---
Tags: 7, entities, log-messages
---


# Question
Title: How to access date value from a datelist form element for validation?
I have a simple form element using *datelist* as the type. I need to validate this to make sure the date is in the future. But I cannot work out how to access the date itself in the validation method.

Form:

```
public function buildForm(array $form, FormStateInterface $form_state) {

  $form['date_field'] = array(
    '#title' => $this->t('Expiry'),
    '#type' => 'datelist',
    '#date_part_order' => array('month', 'year'),
    '#date_year_range' => '2017:2027',
    '#date_increment' => 1
  );

  return $form;
}

```

Validation:

```
public function validateForm(array &$form, FormStateInterface $form_state) {

  $date_input = $form_state->getValue('date_field');

  if(strtotime(date($date_input)) < strtotime(date('now'))) {
    $form_state->setErrorByName('date_field', $this->t('The date must be in the future.'));
  }
}

```

From the above, $date\_input currently returns an object (see below). Essentially, I want to access $date\_input-\>dateTimeObject-\>date; but doing exactly that will return a fatal error.

> Fatal error: Cannot access protected property Drupal\Core\Datetime\DrupalDateTime::$dateTimeObject

$date\_input object:

```
stdClass Object
(
    [__CLASS__] => Drupal\Core\Datetime\DrupalDateTime
    [formatTranslationCache] =>
    [dateParts] => Array
        (
            [0] => year
            [1] => month
            [2] => day
            [3] => hour
            [4] => minute
            [5] => second
        )

    [inputTimeRaw] =>
    [inputTimeAdjusted] =>
    [inputTimeZoneRaw] =>
    [inputTimeZoneAdjusted] =>
    [inputFormatRaw] =>
    [inputFormatAdjusted] =>
    [langcode] => en
    [errors] => Array
        (
        )

    [dateTimeObject] => stdClass Object
        (
            [__CLASS__] => DateTime
            [date] => 2027-12-01T00:00:00+11:00
            [timezone] => Australia/Sydney
        )

    [stringTranslation] =>
)

```

I could do something like:

```
$form_state->getValue('date_field')->format('d m Y');

```

But I suspect there is a better way?

# Answer
Yes, to compare the date it's better to use the unix timestamp. You can get it by using the method `getTimeStamp()` and compare it to the current date:

```
      $value = $form_state->getValue('date_field');
      if ($value->getTimeStamp() > REQUEST_TIME) {
        drupal_set_message('Time is in the future');
      }

```
> 1 votes

---
Tags: 8, forms, datetime
---


# Question
Title: How to bulk add information to the profiles of users?
I have hundreds user profiles where I want to add a one or two fields like the adress of the company they work for. For some group of users this adress will be the same and for others it will be different. How do I mass bulk add these kind of informations? Through the database? (I'm on phpmyadmin)

# Answer
> 1 votes
### Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to **Set a data value**, for each of those fields you want to be updated.

### Step 2

Create a view of the group of users for which those fields should be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.

### Tutorial

To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

PS: this answer is for D7 ...

---
Tags: users
---


# Question
Title: Why only first of two jquery files loaded is running?
In my theme **Basic**, I'm loading 2 jquery files. Both two are loaded at front page, but only first loaded run. If I change loading order, again only first file do anything. Here are the examples:

1) Drupal.behaviors.basic = { ...some jquery stuff...

2) Drupal.behaviors.basic = { ...some other jquery stuff...

# Answer
> 2 votes
They both have the same name, both "basic". Rename one of the 2 and you should be fine. Change

```
Drupal.behaviors.basic = {

```

To for example

```
Drupal.behaviors.modifications = {

```

The name should be something descriptive about what the underlying functions do.

---
Tags: javascript
---


# Question
Title: How to disable the comment for a specific node programmatically?
I'm using Drupal 8. I would like to close the comment for the node, once someone commented on that node. But I don't know how to disable the comment for a specific node programmatically.

```
my_module_comment_insert ($entity) //implement the comment insert hook
{
    $node = $entity->getCommentedEntity();//get the attached comment node.
    // How to implement code here to disable comment for the $node?
}

```

# Answer
In D8, the comments are stored as field containing various comment properties including comment `status`.

You can disable node/entity comments using something like below:

```
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;

/**
 * Implements hook_comment_insert().
 */
function [MODULE_NAME]_comment_insert($comment) {
  // Get comment field name, default comment.
  $field_name = 'comment'; // $comment->getFieldName();

  // Get entity.
  $node = $comment->getCommentedEntity();
  $node->get($field_name)->status = CommentItemInterface::CLOSED;
  $node->save();
}

```
> 4 votes

---
Tags: 8
---


title: How to delete a custom view mode?

text:
# Question
Title: How to delete a custom view mode?
I have a site that had display suite installed, but the custom view mode I'm trying to delete is not listed in the display suite admin page (admin/structure/ds/view\_modes).

So I tried disabling/uninstalling all DS modules, and that didn't seem to help. I re-installed the module and confirmed the ds\_view\_modes table is indeed empty.

I know I can uncheck the checkbox to disable it for a given content type, but I want it gone completely so it doesn't cause confusion.

In the image, you can see the extra display is called "Classified Ad"

How can I accomplish this?

# Answer
Check the source code. It could be a module iis registering it via `hook_entity_info_alter()`.
> 2 votes

---
Tags: 7
---


# Question
Title: How to change the product type of selected Drupal Commerce products (without direct DB updates)?
In order to apply a price calculation rule for certain products only, I have created a new product type. But I am having problems changing the product type for the selected products. Right now it seems to me that the only way to apply the new product type to these products is to delete them and then re-import them (using Feeds) with the new product type selected. This works as expected.

But there are hundreds of products and it seems to me that there should be an easier way. I have read this post How Can I change the machine name of product type but I am a bit wary that I might break something by changing things in the database.

Does anybody have a cleaner solution for this?

# Answer
> 1 votes
For sure I'd not use the approach of changing things in the Database directly. Instead I would try to use the Rules module to create a clone (using the new product type) of the selected products. A solution that could possibly work is to (also) get the Views Rules module involved. Some details about this module (from its project page):

> Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (yet), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

1. Create a view (using Views) so that you have 1 Views result (row) for each product of old product type and for which you want to create a similar one with the new product type. This view should have fields (columns) for each of the fields from your old products that you want to use to create your new product (with your new product type). Important: use a Views display type of "Rules".
2. Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop". If you're not familiar with Rules Loops, then have a look at the tutorial titled "Lists and loops".
3. For each iteration step in your Rules Loop, perform a Rules Action to create an entity which corresponds to your product but with the new product type. At that point you'll have all data from each column of your Views results available as so called Rules Parameters (remember: they are the values used in your products with the old product type). So at that point it's a piece of cake to populate the various fields of your product with the new product type.
4. The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

Possibly, you also want to delete the product (of the old product type), e.g using a variation of this rule (to delete those products instead of creating new entities). I would definitely do that in a separate rule (not as an extra Rules Action in the same rule), to be able to verify that the new products are created (correctly) before deleting the products with the old product types (better safe then sorry ...).

**Note**: Refer to my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?" (the option 2-part of it) for an example (with screenprints) about how to use the Views Rules module.

---
Tags: 7, commerce
---


title: Title in node--article twig template

text:
# Question
Title: Title in node--article twig template
In `node--article.html.twig`

```
<article{{ attributes.addClass(classes) }}>
  {{ created.content | date("d/m/Y") }}
  {{ content.title }}
  {{ content.body }}
</article>

```

The title is not displaying. How do I do this?

# Answer
You can use:

`{{ label }}` or `{{ node.label }}` or `{{ node.getTitle() }}`.
> 17 votes

---
Tags: theming, 8, entities
---


# Question
Title: How to execute rules action programatically
Is it possible to execute a rule action upon form submission? I've created a rule and disabled it, so it'll be only called if it meets the condition I've set. Below is a sample code I've been using:-

```
function hook_form_FORM_ID_alter(&$form, &$form_state) {
  if ($form_state['values']['field_name'][LANGUAGE_NONE][0]['value'] == 1)
    rules_invoke_component('rules_uncheck_update_checkbox', $form_state['commerce_order']);
  }
}

```

Not sure what are the other options as I've been stuck to make it work. Please help. Thank you.

EDIT:

Rules export

```
{ "rules_uncheck_update_checkbox" : {
"LABEL" : "Uncheck checkbox",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"REQUIRES" : [ "rules", "entity" ],
"ON" : { "commerce_order_update" : [] },
"IF" : [
  { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "field_update_checkbox" } }
],
"DO" : [
  { "data_set" : { "data" : [ "commerce-order:field-update-checkbox" ], "value" : "0" } }
]
}
}

```

# Answer
rules\_invoke\_component is used to invoke a Rules Component.

In your case, it seems like you should invoke a Rules Event, using rules\_invoke\_event.
> 1 votes

---
Tags: 7, rules
---


# Question
Title: Determine if an entity is a certain content type
I'm using drupal 8.

Lets assume the following. I have created a content type called `Foo`. Using the presave hook(`hook_entity_presave`), I'm modifying some fields in that content type.

Firstly I want to determine if the entity I'm modifying is a `Foo` content type.

I've tried using `Drupal\Core\Entity\EntityInterface $entity->getEntityType()` however the return is `object(Drupal\Core\Entity\ContentEntityType)`. So basically an object.

Since my knowledge of drupal 8 is not that great(yet) I assumed initially that it would return something more quantifiable like a string or something of the sort. Obviously I was wrong.

Secondly I want to NOT modify some fields if the fields already have a value. Again, I assume a simple `isset` or `empty` will do the trick. I could be wrong. If there are some other ways to do that, more drupal-like way, I'd be more than happy to understand it better.

# Answer
You should be able to check the entity type and content type like this:

```
use Drupal\Core\Entity\EntityInterface;

function hook_entity_presave(EntityInterface $entity) {
  if($entity->getEntityTypeId() == 'my_entity_type' && $entity->bundle() == 'my_content_type') {
    // Do your stuff here
  }
}

```

Where `my_entity_type` is the entity type and `my_content_type` is the content type.

Adding Clive's answer, since the entity type you want to work with is already known to be a node, you can use `hook_node_presave()` instead of `hook_entity_presave`:

```
use Drupal\Core\Entity\EntityInterface;

function hook_entity_presave(EntityInterface $node) {
  if($node->bundle() == 'my_content_type') {
    // Do your stuff here
  }
}

```
> 8 votes

---
Tags: 8
---


# Question
Title: How can I roll the database back to the backup
I have a problem with a module the site functions but I need to roll the database back to the backup I took before deploying the module. How can I do that?I am using D8

# Answer
You can use Drush.

All you need to do is to run, inside a Drupal instalation, the following command:

`drush sqlc < path/to/backup.sql`

\*You may want to drop your current database before that. The command is:

`drush sql-drop -y`
> 1 votes

---
Tags: 8, backups
---


# Question
Title: How to use Rules to limit the number of searches to pull data from a remote API?
I have a custom views query plugin that pull data from a remote API. I use this plugin to save all information so user don't have to enter all details anymore.

User inputs `value` to search filter and all mapped data is displayed on the page.

I want to limit the number of attempt allowed to a user of 3 searches every 24 hours. So in a day, user can have 3 attempts to make a successful query of data from the remote api. Then, there might me a warning message that appears on the page after those failure attempts. Each day is equivalent to a calendar date.

`$vats` is where user input value is set in the view search filter. This value is an integer.

```
$vats = isset($filters['vat']) ? $filters['vat'] : NULL;
$Vid = $vats[0];

$result = CVRClient::get($Vid, $country, 'Unit Testing');

```

Here's the path of my view page with arguments: `query/query?vat=12345678`, 1st 'query' is the sitename and 2nd is the menu path name.

Can this be achieve by Rules? If yes, I would appreciate if someone can guide me ways to do it.

# Answer
> 1 votes
### Preface

You added an interesting comment below your question, part of it is like so:

> All users is registered via Keycloak and page will redirect to Drupal site after its successful registration. This redirected page is the custom view plugin created. For users to be able to add its company details. And so users will enter their VAT # to get data from the CVR Register. ...

Followed by this extra comment:

> `query/query?vat=12345678`. First 'query' is the sitename, then 2nd is the menu path name

So you have a relative path like in this example `/query?vat=12345678`. And therefor the answer to your question (= ***Can this be achieve by Rules?***) is Yes, Si, Oui, Ja ... Read on for more details to *guide you* ...

### Solution

You may want to try the "Rules URL argument" module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

So with that you can use Rules to (let's say) "monitor" the usage of that path by an authenticated user. Some more details about the custom rule you could create for this:

* Rules Event: drupal is initializing (sorry, that's probably the only one that you would be able to use).
* Rules Conditions (pick whatever fits, and/or mix however you want):

+ user has a specific role (or the negation of it).
    + check the current path (verify if it starts with `query`).
    + check if URL argument `vat=` is present.

The only thing left to do is to think of something appropriate for some Rules Action(s) to be performed, knowing that you do have these crucial data available:

* the current user who tries to use this path again.
* the actual value (=`12345678`) that was used.

Obviously, at a minimum you'd want to add a Rules Action to perform an appropriate "redirect" if the 3 attempts have been used on the same day already.

You'd have to do some more homework/refinements, but here is a blueprint of a basic solution that could work:

* **Solution 1** (easiest approach to implement):

+ Use the Flag module (eg with 3 none-global flags labeled like attempt 1, attempt 2 and attempt 3).
    + Add a Rules Action to flag the user with the relevant flag (corresponding to the number of succeeded attempts before).
    + Add an extra Rules Condition to verify that not all flags have been used (with the same flagging date!).
* **Solution 2** (= my recommended approach, though a bit tougher to implement): Use the Message module to create a **custom activity log**, to log each event where the actual URL has been used (with success). And improve the Rule above to add a rules condition to count the number of such messages (= custom activity log records) created already in the last 24 hours.

PS: I'm assuming this is about D7 ...

---
Tags: rules, search
---


# Question
Title: How can I trigger a javascript function when a Drupal ajax call is complete?
I need to do some extra things after Drupal ajax is done inserting some stuff into the DOM. With jQuery this was brain-dead simple, but I can't for the life of me figure out how to do it in Drupal 7 :s

Do I add something to my ajaxified link? I read something about attaching a behavior...confusion is setting in...

# Answer
I ended up adding some additions commands to the page that is being returned by the ajax handler like this:

```
$commands = array();
$commands[] = ajax_command_invoke(NULL, 'grid_content_loading', array('argument1', 'argument2'));
$commands[] = ajax_command_append('#grid-content-target', $html);
$commands[] = ajax_command_invoke(NULL, 'grid_content_loaded', array('argument1', 'argument2'));
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

```

And on the client side I created 2 javascript funtions through jQuery:

```
(function($) {
$.fn.grid_content_loading = function($argument1, $argument2) {
   ...
};

$.fn.grid_content_loaded = function($argument1, $argument2) {
   ...
};
})(jQuery);

```
> 6 votes

# Answer
In my project, I had already written well-defined JavaScript code that updated the page stats after an AJAX call.

Since I wanted to reuse the functions without going to the extent of "extending jQuery", I ended up with the following solution, using an existing jQuery function, instead of defining a new one. This was inspired by what the 'flags' module does -- it simply triggers an event, and allows many Javascript event listeners to act in response, as opposed to having just a single hard-coded, custom jQuery plugin/extension as in the solution explored in the previous answers.

In a Drupal Module:

```
// in_some_ajax_function()

$commands[] = ajax_command_invoke('html', 'trigger', array('MY_EVENT'));

```

In Javascript:

```
// Added an event binding to my $(document).ready();

$(document).ready(function(){

  $(document).bind('MY_EVENT', function() {
    alert('MY_EVENT');
  });

});

```

I had to note that the first parameter for ajax\_command\_invoke is NEVER any native JavaScript objects, so the following never works, because it translates into a 'document' (element) selector:

```
// This tries to select $('document')
// ... which is nothing, since there are no 'document' elements.

$commands[] = ajax_command_invoke('document', 'trigger', array('MY_EVENT'));

```

Curiously, binding on `$(document)` and triggering on `$('html')` are compatible. I suppose you can get very creative, and bind/trigger on more specific, deeper-level elements. If you can think of a scenario where doing so makes more sense than a top-level event trigger, please comment!
> 3 votes

# Answer
Code sample:

```
$commands = array();
$commands[] = array(
    'command' => 'your_js_callback', // the name of your javascript callback
    'value1'  => 'My first value',
    'value2'  => 'My second value',
);
ajax_render($commands);

```

JS Code:

```
(function($, Drupal) {
    Drupal.ajax.prototype.commands.your_js_callback = function(ajax, response, status) {
        alert(response.value1);
        alert(response.value2);
    }
})(jQuery, Drupal);

```
> 3 votes

# Answer
I think that the best option is use the jQuery `ajaxComplete` function:

```
(function($){
   $(document).ajaxComplete(function(e, xhr, settings)
   {
     alert(settings.url);
   });
}(jQuery));

```

And if you want use the function for specific ajax function you can use the identified `settings.url` for your field and change that to:

```
(function($) {
    $(document).ajaxComplete(function(e, xhr, settings){
    if (settings.url == "the path from step 1") {
        // Code to populate your fields here
    }
 });
}(jQuery));

```

This worked for me for Drupal 7 and 8.
> 2 votes

# Answer
Quick hack solution: Place an image inside the loaded content and give it the `onload="[javascript function]()"` attribute. Not sure this is actually what you're looking for... Or if this is easier than the correct way... But maybe better than nothing?
> 0 votes

# Answer
I've posted an answer to this question on so

https://stackoverflow.com/a/19404566/894487

I'm not sure of the real differences between extending `Drupal.ajax.prototype.commands` or `$.fn`

I imagine the former would be more efficient as their is no dom traversal required to hit your function. Not sure if that is important.
> 0 votes

# Answer
I wrote a tutorial on how to do this in Drupal 7: https://www.jaypan.com/tutorial/calling-function-after-ajax-event-drupal-7
> 0 votes

---
Tags: 7, ajax, javascript
---


# Question
Title: How to prevent subsequent Rules to be executed if a previous rule is executed?
I am using Rules to get the price in Drupal Commerce and I have three different rules to apply when I am calculating product price. The problem is that if the first one is executed I don't want to execute neither second nor third. Second one is executed if first one is not executed and the third one shouldn't be executed neither. The third one is only executed if first one and second one are not executed.

Summing up, I would like prevent the execution of subsequent rules if a previous rule is executed. How can I do that in Rules?

# Answer
As far as your question title says "Execution Order", rules have weight which you can set in the settings tab which you will find on rule manage page.

> Order rules that react on the same event. Rules with a higher weight are evaluated after rules with less weight.

As far as your query concern, it seems you need to pick up he right condition while setting up those three rules,you can also use php in the condition if your condition is quite specific.The rules automatically execute their actions based on if condition get satisfied.
> 2 votes

# Answer
As a variation to the prior answer, you could also try to combine the three rules in a single rule, by using the Conditional Rules module, which allows to include the equivalent of a Rules Condition within a Rules Action. Have a look at part 2 of the answer to "How to correct my rule to prevent duplicate taxonomy terms to be created?" for a pretty advanced Rules example that uses this technique.

By using this technique, you can implement pretty complicated Rules Logic in a ***single*** rule, which possibly prevents the need for multiple rules. Moreover, it makes it possible to group related business logic in a single rule (instead of having to look at 3 different places in the admin UI to get the big picture of those rules).

Be aware however that by using this alternative solution, you better also pay attention to the correct usage of ***AND*** and ***OR*** constructs inside such custom rules (to prevent Rules from not behaving as you would expect). If you're struggling with these constructs, you may want to look at the answer to "Which is the difference of combining rules with AND or just leave them follow one each other?"

PS: I'm assuming this question is about D7 ...
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: Enforce rule on Sticky to the top of lists
I have x amount of nodes of content type "job", all of which are presented on page using two views, one that sits at the top "job-highlighted" and one that sits at the bottom "rest-of-jobs".

One job is selected to be displayed in the top view. It is selected using the "Sticky at top of lists" option in the back end.

The rest are displayed in the "rest-of-jobs" view.

The problem is that the user can set a number of jobs to have the sticky at the top of lists selected.

My question is, is there a way to enforce the content type job to have only one node with the sticky at the top of lists functionality. Can I implement a procedure that updates these or is there a module that already introduces this functionality?

Can anyone offer a solution. Thanks in advance.

# Answer
> 0 votes
Do you have a node for the overview page? If so: Instead of using the sticky to top button add a relationship field to the job overview node and set that to allow 1 value, and show the selected job in the highlight field.

# Answer
> 0 votes
Allow only 1 value in your view "job-highlighted". That should do it for you.

---
Tags: views, nodes, 8
---


title: How to get the current viewed users uid

text:
# Question
Title: How to get the current viewed users uid
If I am viewing a users profile page, how do I obtain and display (in a block) their uid? NOTHING to do with the current logged in user. I need to display the users id in a block on their page.

# Answer
> 6 votes
If you are showing a standard drupal user profile page this should get you going:

```
  $user = user_load(arg(1));
  $user->uid; // access user id

```

This assumes the path is `user/uid`. If your path looks different adjust the `arg(position_in_path)` to your needs.

# Answer
> 3 votes
A better option would be to use `template_preprocess_user_profile(&$variables)` and add the user id from here - that way you're not relying on any URL arguments (`arg()` is a recipe for fail).

Pop the following in your `template.php`

```
function MYTHEME_preprocess_user_profile(&$variables) {

  $account = $variables['elements']['#account'];
  //Add the user ID into the user profile as a variable
  $variables['user_id'] = $account->uid;
  // Helpful $user_profile variable for templates.
  foreach (element_children($variables['elements']) as $key) {
    $variables['user_profile'][$key] = $variables['elements'][$key];
  }

  // Preprocess fields.
  field_attach_preprocess('user', $account, $variables['elements'], $variables);

}

```

This will make the UID available to the `user-profile.tpl.php` template as a variable called `$user_id`.

This means that you can then copy `user-profile.tpl.php` from the *modules/user* directory to your theme directory and change it to the following:

```
<div class="profile"<?php print $attributes; ?>>
  <?php print $user_id; ?>
  <?php print render($user_profile); ?>
</div>

```

Obviously you'll want to style it and add extra DIVs and whatnot, but at it's most basic this will put the user id at the top of the user profile page.

# Answer
> 1 votes
You can use this function menu\_get\_object('user')

# Answer
> 0 votes
probably not the best approach in drupal 8 but this work

```
$current_path = \Drupal::service('path.current')->getPath();
    $exploded_path= explode('/',$current_path);
    $uid=end($exploded_path);
    if (prev($exploded_path) =='user')
      $user=User::load($uid);

```

# Answer
> -3 votes
as BetaRide in the page profile you can use arg(1) it will give you user profile and then you can use user\_load()

---
Tags: 7, users
---


# Question
Title: How to replace Operations links (dropdown) by icons?
I'd like to have something like that (icons as buttons) instead of text links in dropdown

# Answer
There is probably a better way, but you could use CSS to hide the text and display an image background over the space instead.
> 0 votes

---
Tags: views, 8
---


# Question
Title: Creating a views reference list to be used in a node reference
I am using a view to create a limited list of nodes of a certain node type in a node reference. E.g. A logged in user may only select nodes she has created.

I am using a contextual filter in a references view. The contextual filter is set to: Provide default value = User ID from logged in user and: Exception value = 1

So while a user may see her nodes only, the super user may see everything.

I like to add a third condition so that any user with the role of editor can see everything as well. Can anybody tell me how or point me in the right direction on how to approach this? I am running out of ideas.

Update: The exception actually doesn't work either. So the questions is: How can I create a references list where:

* the owner can see only her nodes
* UID 1 can see all nodes
* a user with role editor can see all nodes

# Answer
> 0 votes
You can use entity reference module (https://drupal.org/project/entityreference). It provides the forward and backward reference of views.

# Answer
> 0 votes
I think there is a way to filter by permission so that the user sees all nodes on which they have Edit permission. You may need to add a relationship to the user in the view.

---
Tags: views, nodes
---


title: Drupal 7 regions

text:
# Question
Title: Drupal 7 regions
So I am getting acquainted with Drupal and it hasn't been a smooth ride so far. What I understand is that Drupal 7 has a few regions such as Header, Navigation, sidebar first and sidebar second.

Essentially Sidebar first and Sidebar second manage to create some space around the content and navigation and footer. I do not want these sidebars because I want my content and navigations to occupy the full width, essentially I have no use for Drupal sidebars and don't want them to exist.

However, I am clueless on how I can remove these, anybody have a clue how we can remove the sidebar regions. This also grows another question, how can I manipulate the width and breadth of a region ?

Thanks much guys!

# Answer
When you add content in Drupal, the sidebar regions will not be expressed unless you place content in them. You define what goes in each region using Admin/structures/blocks in Drupal 7.

Drupal is not easy to understand for the uninitiated, and documentation on Drupal site is not a comprehensive tutorial. The best way to get a handle on Drupal is to get an introductory book at Amazon or your library. If you are video oriented, I recommend the series on Lynda.com (but it is subscription based). There are other tutorials scattered around the web and maybe some other readers of this question can provide suggestions.

This site is very active and is a great resource for getting answers regarding Drupal. As you get into Drupal, I'm sure there will be more questions :) People on this site are very helpful and you can thank them by recognizing good answers by clicking the 'Up' button or giving them a check mark if you recognize their answer as the one you accept.

Good Luck
> 1 votes

# Answer
If you're looking into theming your site, try playing with Framework or Zen. These are base themes from which you can build upon (and starting out, you will want to :)

You can easily switch between themes from the Appearance admin page (http://example.com/#overlay=%3Fq%3Dadmin%252Fappearance) so feel free to install a few and look at the differences.

When you're moving content around, be sure to look at the Admin Bar/Structure/Blocks page that JoeS talked about (links in comments)

A word of caution though: Templates have a LOT of power opened up to them in Drupal, don't go too far without becoming accustomed to "the Drupal way" first. Trust me :) (Ex: install some modules, like Views)
> 1 votes

# Answer
In the .info file of your (active or un-active) theme folder you can set your regions, and also delete them.

For example this code below simply does not display the sidebars since it is not declared in the .info file.

```
regions[header]       = 'Header'
regions[main_prefix]  = 'Main Region Prefix'
regions[content]      = 'Main Region'
regions[main_suffix]  = 'Main Region Suffix'
regions[footer]       = 'Footer'

```
> 1 votes

---
Tags: 7, blocks, theming
---


# Question
Title: How Can I restrict a date picker in a date field, to disable a list of specific days from the calendar widget?
I need to let the user choose a day from a datepicker in a date field, but disabling a list of specific days from the calendar picker, so the user can't select a not available day.

(Just for explain my use case. I am using Date field and Form api. My Disabled days are in a field in several nodes, and I can get the list of disabled days easily from a View listing this date field. If it is needed it can be exported too as json, xml, plain text or any other format, to serve as entry in the calendar picker.)

(After the user choose an available Day, I will have to do the same to let him select an available Time from a time picker. This will be an appointment for a Photography Session.)

# Answer
> 1 votes
Using this answer: https://stackoverflow.com/a/15400806/1475662 and a bit of custom coding to add the js and the list of available (or not available) dates to the page.

---
Tags: 7, datetime
---


title: Attaching library to form isn't working

text:
# Question
Title: Attaching library to form isn't working
I'm using hook\_form\_alter. I'm having a weird situation where attaching my library works only if I do what I would think is incorrect:

`$form['#attached']['library'] = array('somemodule/somelibrary');`

But not if I do this:

`$form['#attached']['library'][] = array('somemodule/somelibrary');`

What could cause a thing like this? I debugged to see what was happening in the FormBuilder, but it seems like the library is added either way. It's not removed by any other module or anything.

# Answer
Those two statements are not equal.

`$form['#attached']['library'] = array('somelibrary');`

Resets the library array to only contain "somelibrary". This would remove anyone else's library that may need to get loaded.

`$form['#attached']['library'][] = 'somelibrary';`

This adds "somelibrary" to the existing libraries array for inclusion. (this is correct)

`$form['#attached']['library'][] = array('somelibrary');`

This is the wrong structure.

**For Drupal 8**

`$form['#attached']['library'][] = 'somemodule/somelibrary';`
> 5 votes

---
Tags: 8, forms
---


# Question
Title: Dynamically change widget type in node edit form
I have a content type with a geofield. I'm using an Openlayers Map as the input Widget. The map allows the user to place a marker and it populates the geofield with the lon/lat coordinate. In some cases, however, it would be preferred to input the lon/lat manually as opposed to using the map.

How would you provide an option in the node edit form to dynamically switch the display widget for the geofield from the Openlayers map to lon/lat, or from lon/lat to a map?

# Answer
> 2 votes
The use case you describe is specific in nature, but the question you actually asked in the title is more general purpose. I’m answering the question in the title.

To the best of my knowledge, there is not at present an Input Widget Switcher module for Drupal 7 or earlier, but there really needs to be. There are similar modules such as Display Suite for altering the displayed *output* of a node, including using different *display formatters* (example: showing the same date field as a short date format in a Teaser and as a long date format in a full node display), but nothing analogous for node input form widgets.

Drupal 8 has the underlying structure needed to implement something like this, known as Form Modes (basically the input form equivalent of View Modes such as Full *vs.* Teaser, which Display Suite builds on). But while there is a UI for creating them, there is not at present to the best of my knowledge an ability to use them or switch between Form Modes in core.

That said, the Form Mode Control module for D8 does seem to provide this ability. It allows switching between Form Modes based on Role or Permission and on Node (or Entity) Creation *vs.* Modification (for instance, on Creation the Widget for a GeoField might be Lat/Long with HTML5 GPS Geolocation enabled, but on Modification switch to a different Form Mode that uses, say, OpenLayers Map Widget so that the already-existing location marker can be moved on a map).

There’s also the similar Form Mode Manager module (also D8 only) that works a bit differently, but it’s only in Alpha at the time of this writing, while Form Mode Control is in Release Candidate 2 and thus better for production sites.

# Answer
> 0 votes
I'm not sure you are looking for the exact same thing but have a look here https://drupal.org/sandbox/GwenMahe/2055375 I am still developing it, so if you notice some bug it's because it's not perfect yet !

---
Tags: 7, entities, javascript, location
---


# Question
Title: Webform views - creating a filter using date from user-submitted data
We have a job submissions webform. In the form, there is a "closing date" field with a calendar picker (yyyymmdd format). When the closing date passes, the submission should be removed from view.

1. I created a relationship for the *Submission Data: Expiry Date* field so it can be used as a Filter.

2. Now that I have the data available as a filter, this is where I get stuck; I need the view to filter out the submission if the *Expiry Date* has passed. How can I do this?

# Answer
> 2 votes
I just found a patch for this exact functionality. Out of the box, you are right, it acts as its a straight up text field. If you were to use entityform instead of webform, I believe you would be able to do this as it uses normal drupal fields.

https://www.drupal.org/node/2527608

# Answer
> 1 votes
\*Set the operator to 'is greater than'

\*Select 'An offset from the current time such as "+1 day" or "-2 hours -30 minutes"'

\*Set the value as "now"

---
Tags: views, webforms
---


# Question
Title: How to set up a View in Drupal that shows recent posts relative to post date of node it is on?
I want to set up a View that shows all the nodes that were updated within 7 days of the node that is being viewed

So if the node being viewed has a post date of January 15, 2014, I would see posts that were published between January 8-15, 2014.

I know there is a contextual filter involved, but it eludes me how to do this so the date used is relative to the node it is being viewed on.

# Answer
> 0 votes
No idea if possible in Views, but I created a custom block to achieve this.

```
function relative_posts_block_info() {
  $blocks['relative_posts'] = array(
    'info' => t('Relative Posts'),
  );

  return $blocks;
}

function relative_posts_block_view($delta = '') {
  switch ($delta) {
    case 'relative_posts':
    $block['subject'] = t('Block Title Goes Here');

    $node = menu_get_object();
    $formatted_date = date('m/d/Y H:i:s', $node->created);
    $start_date = strtotime('+2 weeks', strtotime($formatted_date));
    $end_date = strtotime('-2 weeks', strtotime($formatted_date));

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'story')
    ->fieldCondition('taxonomy_vocabulary_1', 'tid', $node->taxonomy_vocabulary_1['und'][0]['tid'])
    ->propertyCondition('created', array($end_date, $start_date), 'BETWEEN')
    ->propertyOrderBy("created", "DESC")
    ->propertyCondition('status', 1)
    ->range(0, 25)
    ->execute();

   $block['content'] = '<ul>';

  foreach($entities['node'] as $obj) {
  $node = node_load($obj->nid);
    $block['content'] .= '<li>' . l($node->title, "node/" . $node->nid) . '</li>';
  }
  $block['content'] .= '</ul>';

   break;
 }

 return $block;
}

```

---
Tags: views
---


# Question
Title: How can I access block metadata from custom plugin instance?
Using the block\_example module, I created two instances of the example\_configurable\_text block in the UI and would like to now access their underlying metadata, specifically uuids. By looking at the config table in the database, I can see that there is a record for each (`select * from config where name like "%example%";`). However, when I debug `ExampleConfigurableTextBlock::build`, I can't seem to access any of it.

I'm aware that configuration can be loaded via `\Drupal::config('<name>')`, but I need to be able to access the configuration dynamically from with my plugin class instance.

Is extending BlockBase the right way to go? Do I need to use derivatives? What is the connection between a block instance in the config table and an instance of a block plugin? So many questions.

# Answer
> 2 votes
Generate unique form ID based on context contains the answer you're looking for.

Short answer is, you have to make this unique id yourself. See the mentioned simplenews project and how I solved it there.

Keep in mind that block plugins are *not* only usable by core block entities, they can also be used by Page Manager/Panels, where you have many blocks in a single variant and even by projects like block\_field, which allow to use block plugins on content entities. You must not rely on anything but your own configuration array.

I think I once opened a core issue about this, to introduce a method so that a unique ID can bet set on a block plugin, but I can't find it anymore, only another core issue (https://www.drupal.org/node/2405879) where I mentioned that I can't find that issue anymore :)

# Answer
> 1 votes
When you create an instances of the block you see in the *Configure block* window a machine name (in the first line to the right of the title). This is the id of the block configuration entity.

In code you can access the block configuration by loading this entity:

```
$block = Block::load($block_id);

```

To get all of the configuration use `$block->toArray()`.

By using the method `getPlugin()` on the block you can get the block plugin:

```
$plugin = $block->getPlugin();
$configuration = $plugin->getConfiguration();
$plugin_id = $plugin->getPluginId();
$base_plugin_id = $plugin->getBaseId();
$derivative_plugin_id = $plugin->getDerivativeId();

```

The plugin\_id is the base\_plugin\_id (ID from the block class) + the derivate\_plugin\_id, for example the menu name or the uuid from a custom block.

If you don't have data in other places like configuration or content you don't need a derivative for the block. You store all information you need in the configuration of the block itself.

---
Tags: 8, blocks, configuration, plugins
---


# Question
Title: hook_views_query_alter creating additional OR statements
I am attempting to add some "OR" statements to my Drupal view (to accomodate a grouping of taxonomy terms).

I am able to replace a tid one for one without an issue using the following code:

```
function customedm_views_query_alter(&$view, &$query) {
      if ($view->name == 'course_catalog') {
            dpm($query);
            foreach($query->where[1]['conditions'] as &$condition){
                if ($condition['value'] == 422){
                    $condition['value'] = 311;
                }
            }
        }
}

```

The problem is, I need to replace this value with several values (311,316,and 326)

I've tried replacing the $conditions variable with the proper or statement e.g.:

```
$condition = "WHERE field_data_field_course_subject.field_course_subject_tid = '311' OR field_data_field_course_subject.field_course_subject_tid = '326'";

```

Or creating a second $query-\>where\[\] array with the seemingly appropriate entries into the array:

```
function customedm_views_query_alter(&$view, &$query) {
      if ($view->name == 'course_catalog') {
            dpm($query);
            foreach($query->where[1]['conditions'] as &$condition){
                if ($condition['value'] == 422){
                    $newconditions = array(
                    conditions => array(
                        array(
                            field => 'field_data_field_course_subject.field_course_subject_tid',
                            value => 311,
                            operator => '='
                            ),
                        array(
                            field => 'field_data_field_course_subject.field_course_subject_tid',
                            value => 326,
                            operator => '='
                            ),
                        array(
                            field => 'field_data_field_course_subject.field_course_subject_tid',
                            value => 316,
                            operator => '='
                            )
                        ),
                        args => array(),
                        type => "OR"
                    );
                    $query->where[] = $newconditions;
                }
            }
        }
}

```

Neither of these approaches seem to product the desired outcome (though I was able to verify that the array creating approach created the appropriate fields in $view-\>query... can someone show me how I can add OR statements to my query using this hook?

# Answer
Thanks to iLLin I was able to figure out an acceptable answer to this question by using the in operator, and replacing the entire array for the condition.

```
function customedm_views_query_alter(&$view, &$query) {
  if ($view->name == 'course_catalog') {
        foreach($query->where[1]['conditions'] as &$condition){
            if ($condition['value'] == 422){
                $newvalue = array(
                    field => 'field_data_field_course_subject.field_course_subject_tid',
                    value => array(311, 316, 326, 321),
                    operator => 'in'
                );

                $condition = $newvalue;
            }
        }
    }
}

```
> 1 votes

---
Tags: database, views
---


# Question
Title: Drush 8 throws unknown error on Drupal 8 install
UPDATE: I have managed to update Drush using Wim Mostrey's help as seen below. Drush is now at version 8, and continues to work with my Drupal 7 sites, but when I try to use it on my Drupal 8 site, I get this:

```
Drush command terminated abnormally due to an unrecoverable error.
Error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home1/[uname]/public_html/_d8/core/lib/Drupal/Component/Serialization/Yaml.php, line 54 Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home1/[uname]/public_html/_d8/core/lib/Drupal/Component/Serialization/Yaml.php

```

Does anyone know what this issue is?

---

Original Question: I want to upgrade from Drush 6.5 to 8, even though current Drush is ver 9 because I want to keep backwards compat. I'm not understanding the instructions on github very well, and concerned about it getting gummed up. Is there a clear, simple guide for this?

# Answer
> 0 votes
After much pain and frustration on this, I finally found the answer and have it working. The info on drush.org (http://docs.drush.org/en/master/install/) about Drush version + PHP compatibility is completely misleading if not simply wrong. I went through a lot of careful testing, teardown and rebuild... and Drush 8 does NOT work with Drupal 8(.2) under CLI PHP 5.4 as the chart at the bottom of the linked page plainly indicates it should.

Drush.org says Drush 8 will work under CLI PHP 5.4, and technically, it does - if you are using a Drupal 6 or 7 site. Drupal 8 was running just fine - it had its required PHP 5.5 running on the webserver. But apparently, when I use Drush, the REAL required version of PHP at the CLI is defined by Drupal, NOT some minimum requirement set by Drush itself. This distinction - Drush's real PHP version requirement being defined by the Drupal PHP requirement - that is not at all explained. I was under the impression that if Drupal was happily running, and Drush had met its own PHP requirement, then the problem must lie elsewhere. Hence all of my wasted time. Hopefully, someone else finds this and saves him/herself a bunch of headache.

So there you have it. I set DRUSH\_PHP to point to PHP 5.5 or greater, and everything is happy. I went to see how I could comment on drush.org to let them know to correct this, but can't find a way to, and after burning so much time already on this, I am not willing to burn more looking. I'm posting the answer here, in hopes it will help people, and that someone else will tell them their reqs page is very misleading.

# Answer
> 1 votes
Looks like the version of PHP you are using does not meet the minimum requirements for Drush and/or Drupal. Check your PHP version, and compare against the Drush supported versions matrix.

# Answer
> 0 votes
Since you installed Drush using Composer, you will now be fine by running the following command:

```
composer global require drush/drush:8.*

```

# Answer
> 0 votes
Firstly, remove drush 6.5 version using

> sudo apt-get autoremove drush

then, follow these commands -

```
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
composer global require drush/drush:8.0*
export PATH="$HOME/.composer/vendor/bin:$PATH"

```

Then you can check the update has been successful by executing:

```
$ drush --version

```

---
Tags: 8, drush
---


# Question
Title: How to get taxonomy term by description, programatically
In a D7 custom module, I wish to retrieve a taxonomy term by it's description (and not it's name or TID).

Right now I do have it working, but I feel the code is a bit clunky, and I feel like there is a more elegant / Drupally way of doing it.

Is there a better way of doing it then this?

```
$vocabulary = taxonomy_vocabulary_machine_name_load('my_vocabulary');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

foreach ($terms as $term) {
  if ($term->description == 'my_term_description') {
    // Do stuff when there is a match.
  }
}

```

Ideally, I feel like there is a better way I cannot find through Google / Drupal API etc. Something like:

```
$term = taxonomy_by_description_load('my_vocabulary', 'my_term_description');

```

Thanks everyone.

# Answer
> 0 votes
Using the EntityFieldQuery (this is untested)

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', array('my_vocabulary'))
    ->propertyCondition('description', 'my_term_description');
  $result = $query->execute();
  $tids = array_keys($result['taxonomy_term']);

  return $tids;

```

More information https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-use-entityfieldquery-for-drupal-7

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


# Question
Title: template.php hook to add variable to view
I'm trying to include the total count of a given node type into a view tpl.php file. I would like to set this variable in the template.php file, so that it is available in the tpl.php file (that way I also don't have sql queries gumming up my template files, which I'm trying to avoid.)

I'm trying to set them the variable with template\_preprocess\_views\_view, but the reference variable never seems to be getting updated. I did some sleuthing and threw in some dpm statements, one in the preprocess function, one in the template, and the result looks like this:

```
template
preprocess views_view
preprocess_views_view__home_image

```

(The thrid line prints out the preprocess function with the view name attatached)

So it looks like the issue is the template is being called before my preprocess functions, which means the variable hasn't been updated it yet, but is that correct? Shouldn't the preprocess function be called BEFORE the template is called? Is there another hook that I can use to add a variable to views-view-fields.tpl.php?

# Answer
> 0 votes
I think you want to use views hooks, not template preprocess functions. The views query will be run before the template is processed. You can find a list of views hooks here: https://api.drupal.org/api/views/views.api.php/group/views\_hooks/7.x-3.x

and from that link, and alex.designworks the hook firing order:

```
- hook_views_pre_view
 - hook_views_pre_build
 - hook_views_post_build
 - hook_views_pre_execute
 - hook_views_post_execute
 - hook_views_pre_render
 - hook_views_post_render

```

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