# Question
Title: How to make dynamic google map in block?
I want to make block with two links that lead to different gmaps position. Also gmaps is in that block. So, block haves address text with two location and by clicking on that location i want that gmaps change the position of marker without reloading all page. So it is need to be dynamic block. Any help?

# Answer
> 0 votes
you could start by creating a custom module if you want , there's plenty of tutorials on the drupal website to help you get started then , in the block template add the js you need to create that map with the coordinates you want . or using views , like in this post hope it helps

---
Tags: blocks, google-maps
---


# Question
Title: Passing NID argument from views to panelizer
I am working on a complex site using Views and Panelizer.

I am trying to use Panelizer to display Views generated data, filtered by NID, for each advertisement.

To do that, I created a view called **Advertisements** with a **content pane** called *Display* which takes an NID as a *contextual filter*.

The NID filter is set to *Provide default value* -\> *Content ID from URL*.

With that I am able to preview the field data of an existing article node when I provide it's NID as an argument.

However I have problems beyond this point :-(

I find my View content-pane in the **Views panes** section of the content area of Article's panelizer area - but there is no preview. This immediately suggest there is something wrong with the output.

This is confirmed when I save the configuration and visit an Advertisement node - my output does not display.

After some research, I return to Views and go into the *pane settings* -\> *argument input* section. I set it to **From context** -\> **Content ID**.

With the View saved, I return to my advertisement node to find the page still blank.

I am very stomped and a lot of time has been wasted on this.

Can anyone please advice what I'm doing wrong or missing.

# Answer
I had the exact same setup and issue. I could see the title of the view pane but no content even after I had made sure to set Argument input:Edit (in content pane view) to be:

* Argument source: From context
* Required context: Content ID

The reason I was not seeing content and only the title of view was simply because I'd forgotten I'd made a tpl of that view and had not yet cleared cache...
> 1 votes

---
Tags: 7, views, panels
---


# Question
Title: Using base_path and directory variables in twig template
I'm creating a Drupal 8 theme. I have overriden the menu.html.twig... and I need to add an image to the first menu item.

In the page.html.twig I have used `{{ base_path ~ directory }}` to get the url of image like this:

```
<img class="logo_inder" src="{{ base_path ~ directory }}/img/logo-inder.png" />

```

But I'm trying to insert an image in themes/(my\_theme)/templates/menu.html.twig like this:

```
<img src="{{ base_path ~ directory }}/img/inicio-icono.png" />

```

But is in this file, I can't print these variables:

```
{{ directory }}
{{ base_path }}

```

or

```
{{ base_path ~ directory }}

```

How can I print the base URL for use in my image?

# Answer
You can expose the `base_path` variable to all you templates by implementing `hook_preprocess()` in your theme `.theme` file.

e.g.

```
/**
 * Implements hook_preprocess().
 */
function mytheme_preprocess(array &$variables, $hook) {
  $variables['base_path'] = base_path();
}

```

where `mytheme` is the machine name of your theme.

You can use `{{ active_theme_path() }}` to get the path to the active theme.
> 7 votes

---
Tags: theming, media
---


# Question
Title: Can I use a theme done for the previous version in the latest core version?
Is it possible/advisable to use a Drupal 7 theme on a Drupal 8 installation?

I'm starting my first Drupal 8 project. Generally, I hit up a place like ThemeForest for a theme, but their D8 theme selection is depressingly slim. Can I use a (*highly rated and actively maintained*) D7 theme instead? Is there a better place to look for professionally built D8 themes?

# Answer
No. You *could* convert one if you have the time - which involves turning all tpl files to twig, updating the syntax, and making necessary changes to the template.php file (which gets renamed to template.theme). That also includes replacing any functions that don't exist anymore, and using the new D8 equivalent. Again, not too hard, but it can be if you are brand new to D8.

For smaller themes, this can take few hours to a day or two; for more involved themes, it can take longer.
> 5 votes

---
Tags: 8
---


# Question
Title: Upgrading Drupal 8 to a newer version from the command line using Drush?
Currently I have stable Drupal 8.1 release and I would like to uprgrade my site to 8.2 dev. How can I do this via the command line with Drush if that is even possible?

* If not using drush, can I just download 8.2 and extract it into 8.1 directory?

# Answer
To do it via the command line you can simply run the command `drush up drupal`

To do it manually, it's a bit more tedious as you need to be really careful about what you want to keep, templates.. modules... themes. Basically you need to replace all core files at the root level and note that the files that reside at the root level e.g. .htaccess.. robots.txt need to be compared and merged with the latest.

I hope this helps.
> 1 votes

# Answer
Try `drush pm-update drupal-8.2.0-beta2` for the beta2 release, or `drush pm-update drupal-8.2.x` for the dev release.
> 1 votes

---
Tags: 8, drush, upgrading
---


# Question
Title: Create/Update a commerce order using parameters passed via the url
Is it possible to Create/Update a commerce order using parameters passed via the url?

What options are out there to achieve this?

# Answer
As far as I know, the only way to do this is with a custom module. It should implement `hook_menu()` to accept as many parameters as you need, and invoke a callback that uses the Drupal Commerce API like in this example.

\[EDIT\] There are three modules that may help you do this if you don't want to create a custom module yourself:

1. Rules link. It attaches a link to entity displays that triggers a rule. It passes the entity to the attached Rule
2. Rules link event. In some ways similar to Rules link, but from what I can tell, you can actually use the SKU (or other parameters) as an argument in the URL link, accessible to the Rule through a token `[path:last]` and so forth. Main difference between Rules Link and Rules Link Event here.
3. Commerce cart link. Similar to Rules link event, but works with ctools to create a token for the link, which increases security.
> 1 votes

---
Tags: commerce
---


# Question
Title: Authenticated users can not see own Ubercart order detail
Using Drupal 7, Ubercart 7.x-3.10.

A user purchases product, gets a user id and logs in. He clicks on Orders tab in My Order History and sees the last order. But, when he clicks on the order number or View order icon, he gets `HTTP 500 error` (not access denied) instead of seeing order detail.

As admin, I can click on same link and see order detail.

In permissions, Authenticated user has checked:

`View own orders` `View own invoices`

They can see `uc_orders_user` view `/user/606/orders` but get `page not found` error when they click on link to view individual order `/user/606/orders/15`. Oddly enough, Print order `user/606/orders/15/print` does work.

Rebuilt permissions, same error.

In order settings, `admin/store/settings/orders`, I use the Customer On-site invoice template, but I don't see any options to allow users to view `orders/invoices` (as referred to in this answer to similar question: User cannot view their Orders in Ubercart)

Any suggestions?

# Answer
I found the offending code. It was the code for a block to display a link to "My Orders" if the user had any orders. I removed this code from the block, and the order detail now displays for authenticated user.

The offending code:

```
global $user;

$uid = $user->uid;

// print 'This is my user id ' . $uid;

        $count = 0;
        $args = array($uid);
        $view = views_get_view('uc_orders_user');
        $view->preview('page', $args);
        $count = sizeof($view->result);

// drupal_set_message($count);

  if ($count > 0) {
    return TRUE;
  } else {
    return FALSE;
  }

```

Do not know why this code causes the error, but it does. If I find a way to tweak it to work, I'll post it here.
> 0 votes

---
Tags: ubercart
---


# Question
Title: What are the reasons that the "Show block on specific pages" settings wouldn't work?
I have a site with a large number of blocks, but I just added a new one that's only supposed to show on one page but it shows on every page. If I exchange it with another block I have the same problem. If I remove a bunch of blocks the problem remains.

If I put in show on all pages except those listed, it will still show on the front page. If I only put something like about with "Only the listed pages" selected, it will still show on the front page. This is happening with different types of blocks.

I've disabled Context, and Display Suite. I've flushed the cache tons of times. What could be overriding this setting?

# Answer
> 0 votes
It turns out that the issue was that there was, at some point, a theme with the same name but with different capitalization. It looks like this led to inconsistent results when looking up which blocks should be displayed and when. Once I removed all the entries in the block table to the old theme the problem was resolved.

---
Tags: blocks
---


title: How to obtain foreign field values?

text:
# Question
Title: How to obtain foreign field values?
I am really new to drupal and struggle to find good tutorials for the issues I have. One of those issues is as follows:

How do I obtain values from foreign nodes. Specifically nodes that were created in a feature bundle.

As a concrete example I would like to load all Jobs from the Recruiter distribution and then extract the field information from them.

After reading through the Book Pro Drupal 7 Development and many online resource I still struggle to grasp how I am supposed to do this other than to do direct Database Queries.

# Answer
> 0 votes
There are a few options you have when it comes to exporting data from Drupal 7. A few have been mentioned in this post. Hope this helps!

How to export/import all nodes of a specific content type?

---
Tags: 7, nodes, entities
---


# Question
Title: How do I add body class on specific content_type who have specific field?
I need to add class in body when content type `article` and have image on it. How do I achieve this?

I checked in `theme_preprocess_html` only found content\_type as string. Don't know how to check image on it.

# Answer
> 5 votes
You will need to do a little work in the html preprocess:

```
/**
 * Implements template_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  $variables['has_image'] = FALSE;
  if ($variables['node_type'] == 'article' && ($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    $variables['has_image'] = empty($node->field_image->value) ? FALSE : TRUE;
  }
}

```

and the html template:

```
{#
/**
 * @file html.html.twig
 */
#}
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
...
  </head>
  <body{{ attributes.addClass(has_image ? ['has-image']) }}>

```

This will add the class `has-image` to the body tag of every Article type content node.

# Answer
> 3 votes
In case you don't want to touch your template file.

```
/**
 * Implements hook_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  if ($variables['node_type'] === 'article') {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node->field_image->getValue()) {
      $variables['attributes']['class'][] = 'has-image';
    }
  }
}

```

---
Tags: theming, 8
---


# Question
Title: What cause my 404 error for my user_picture thumbnail in template file?
I want to print user\_picture thumbnail in my page template. I am using the following code in `hook_preprocess_html()` in my .theme file.

```
$user = user_load(\Drupal::currentUser()->id());
$style = entity_load('image_style', 'thumbnail');
$variables['user_picture'] = $style->buildUrl($user->get('user_picture')->entity->url());

```

It's generating a URl but it is showing 404, what could be wrong here?

# Answer
> 2 votes
In `hook_preprocess_html()` add the following code.

```
  $user = user_load(\Drupal::currentUser()->id());;
  $variables['user_pic'] = $user->user_picture->entity->uri->value;

```

In your template file use code similar to the following one.

```
 <img width="62" height="62" class="image-responsive img-circle" src="{{ file_url(user.pic) }}" />

```

If you want to apply an image style, use the following code in `hook_preprocess_html()`.

```
$variables['user_pic'] = ImageStyle::load('thumbnail')->buildUrl($user->get('user_picture')->entity->uri->value);

```

In the template file, use the following.

```
 <img src="{{ user.pic }}" />

```

# Answer
> 0 votes
First you have to load your file. In Drupal 8 everything is based on entities, and so are files. Loading a file is the same as loading a node.

```
$file = File::load($fid);

```

If your file is valid, you can start by building the render array for the image. In the showed example, "thumbnail" is the used image style.

```
$variables = array(
  'style_name' => 'thumbnail',
  'uri' => $file->getFileUri(),
);

// The image.factory service will check if our image is valid.
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
  $variables['width'] = $image->getWidth();
  $variables['height'] = $image->getHeight();
}
else {
  $variables['width'] = $variables['height'] = NULL;
}

$logo_render_array = [
  '#theme' => 'image_style',
  '#width' => $variables['width'],
  '#height' => $variables['height'],
  '#style_name' => $variables['style_name'],
  '#uri' => $variables['uri'],
];

```

---
Tags: theming, 8, media
---


# Question
Title: Leaflet: how to display a unique marker per map
Normally people want to add multiple markers to a single map. In my case I'm attempting almost the opposite - create two maps from the same content type and using Leaflet assign each a unique marker to each. Try as I might I can't figure out how to do this. Instead, what happens is that both markers are displayed on either map (rather than one per map).

My current setup it like so -

**Content type**

* Has a geofield set to output Lat/ Long coordinates

**Page**

* Two pages based on the above content type (let's call them Page Map A and Page Map B) each have a unique set of coordinates.

**View**

* Individual View block for Page Map A and also for Page Map B. These are set to output the geofield data

(I originally had one View block and I was hoping that splitting them in two would solve the issue. It didn't.)

**Block**

* In blocks the View for Map A and the View for Map B is set to display only on their respective pages

Both of the Views are ordered by sort date (which might be the source of the problem) and only show 1 item. However, if only one item is set to show then it's always the marker for Page Map B that's displayed. Furthermore, if I increase the display to show 2 or more items then the popup text for both markers will only appear on Page Map B, and there are no popups for Page Map A.

# Answer
I would use a contextual filter (Advanced settings column) based on the content NID (node identifier). You will get a settings window where you choose "Provide default value" and Type : Content ID from URL (the nid is always available from URL even if you use an alias). Then, the Leaflet map will be filtered using this NID and you will get only one marker (display all results and remove your sort date) created with coordinates entered for this specific content (page). Finally, you will need only one block with this contextual filter, since it will be automatically modified according to page URL.

Hope this helps.
> 0 votes

---
Tags: views
---


title: WebForm CSS Styling - Radio Buttons

text:
# Question
Title: WebForm CSS Styling - Radio Buttons
Giving all of the other components are simple. However the radio button seems a bit challenging. I've added class to the following

```
.checkbox input[type="checkbox"], .checkbox-inline input[type="checkbox"], .radio input[type="radio"], .radio-inline input[type="radio"] {
margin-left: -20px;
position: absolute;

```

however doesnt seem to work. I'm looking for an HTML5 style layout.

# Answer
> 2 votes
It's pretty difficult to help you here. Are you trying to make your radio buttons inline?

If you are using Bootstrap theme with everything else working right, according to: W3Schools you should be able to just name it class="radio-inline" and then target .radio-inline class in CSS with what you are trying to achieve.

---
Tags: theming, webforms
---


# Question
Title: Drupal commerce payment callback endpoint
Currently I'm work for a payment gateway plugin, the payment gateway will returning data by using the post method to my Drupal site once the payment transaction occur. I would like to know is that any endpoint and what are the hook is able to handle this process.

# Answer
> 0 votes
so - this sounds like an IPN (instant payment notification), commerce payment does not handle that, so you have to pass the ipn url defined in hook\_menu to your gateway in the specific parameter when submitting the \_redirect\_form, or setting it in your gateway configuration - depends on the gateway ..

```
/**
 * Implements hook_menu().
 *
 * adds the callback uri
 */
function YOUR_MODULE_menu() {
  $items = array();

  // Define an always accessible path to receive IPNs.
  $items['some_uri/IPN/%'] = array(
    'page callback' => 'your_module_process_ipn',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

so - your ipn looks like this httpx://example.domain/some\_uri/IPN/What/ever maybe that the What/ever is set by the gateway. if nothing is set, adjust the item in hook\_menu !

then your callback function does take the action, like:

```
/**
 * Processes an incoming IPN.
 *
 * @param $uri
 *   dynamic URI
 * @param $debug_ipn
 *   Optionally specify an IPN array for debug purposes; if left empty, the IPN
 *     be pulled from the $_POST.
 *
 */
function commerce_postfinance_process_ipn($uri = NULL, $debug_ipn = array()) {
  $ret = 'IPN failed';
  if (ipn_valid($uri, $debug_ipn)) {
    $ret = 'IPN OK';
  }

  print $ret;
  exit(0); // hook_exit will not be invoked !
}

```

and in the ipn\_valid function you access the $\_POST array.

> don't forget to create a commerce payment transaction if the ipn is OK.

refer the paypal wps module for this (see funciton **commerce\_paypal\_wps\_paypal\_ipn\_process**)

---
Tags: commerce
---


# Question
Title: How To Display Node Tokens/Keys/Content Fields In Twig Template
I'm fairly new to theming with Drupal, especially using Templates and Twig. After a lot of searching and experimenting I seem that have accomplished my desired view mode the way I want...almost.

I have a field in my content type called Category. The machine name is field\_category. I have been able to output the field in my template using the key: {{content.field\_category}} But as you can see it also applies a CSS styling I have on the full default Node Page which I would prefer not to have it there.

Going at it a different way, I used a View along with the given replacement patterns and was given the token of {{ field\_category }}. After everything was done it does the same thing without any CSS styling since it's not pulling in the HTML markup of class="field field--name-field-category".

My question is I wonder if there is a way to grab the value without the markup? And if so how? Any steps in the right direction would be very much appreciated, I am a complete beginner at Drupal and even more so with Twig. Thank you.

# Answer
> 2 votes
With Drupal 8 you now have two ways to access to the data of a given node/entity.

The first is with the `{{ content.* }}` this will return the content that went through the display plugins/system (everything which you configure in the "Display mode" of the content type).

You also can access to the raw data with `{{ node.*.value }}`

It's preferably that you use the way `{{ content.* }}` as much as possible in order to be able to use the power of Drupal to quickly change the things with display mode.

---
Tags: theming
---


title: Alter views contextual filter field

text:
# Question
Title: Alter views contextual filter field
I have two content types, `Brand` and `Sector`. `Brand` have a `sector` field which is an Entity reference field.

I have views that display the list of Brands and it has a `sector` contextual filter which displayed as an input field where you have to input a node ID.

I was trying to make it a dropdown with sector titles for a user friendly experience but wasn't able to achieve this in views. So I decided to alter the views form but it seems like that it's not working the same as in D7.

What's the right way to alter the views field or is there a way to render a field as dropdown using views?

# Answer
OK, I managed to achieve this by implementing `hook_form_FORM_ID_alter()` in my `mytheme.theme` file.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mytheme_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($form['#id'] == 'my-views-exposed-form-id') {
    $query = db_select('node_field_data', 'n')
      ->fields('n', array('nid', 'title'))
      ->condition('type', 'sector')
      ->condition('status', 1)
      ->orderBy('title', 'ASC');
    $options = $query->execute()->fetchAllKeyed();

    // $form['sector'] is a type text, changing it to select.
    $form['sector'] = array(
      '#type' => 'select',
      '#options' => array('' => t('Filter by Sector')->render()) + $options
    );
  }
}

```

Hope it will help someone.
> 0 votes

---
Tags: views, 8
---


title: How to execute SQL query?

text:
# Question
Title: How to execute SQL query?
I have a text in $text, I need to do

```
select 'nid' from 'node' where 'title'=$text

```

later I need to do this

```
select 'column_name' from 'table_name' where entity_id = nid

```

then I need to print the column name. can you tell me how to do this.

# Answer
Please use below working code

```
$query = db_select('node', 'n');
$query->fields('n', array('nid'));
$query->condition('n.title', $text, '=');
$nid = $query->execute()->fetchField();

//get column name from nid
$query = db_select('table_name', 't');
$query->fields('t', array('column_name'));
$query->condition('t.entity_id', $nid, '=');
$column_name = $query->execute()->fetchField();

```
> 3 votes

# Answer
Something like this should work:

```
$result = db_query("SELECT nid FROM {node} WHERE title = :text", array(
  ':text' => $text)
)->fetch(PDO:.FETCH_OBJ);

$result = db_query("SELECT column_name FROM table_name WHERE nid = :nid", array(
  ':nid' => $result[0]->nid)
)->fetch(PDO::FETCH_OBJ);

```

You could also use a dynamic select query like this:

```
$query = db_select('node', 'n');
$query->condition('n.title', $text);
$query->fields('n', array('nid'));
$results = $query->execute();
// get the first nid from the resultset - I think this should work - not tested
$nid = $results->nid;

// select an entry based on the above nid
$query = db_select('table_name', 't');
$query->condition('t.entity_id', $nid);
$query->fields('t', array('column_name'));
$results = $query->execute();

```

A better approach might be to use one query if you only need the data from the second query:

```
$query = db_select('node', 'n');
$query->condition('n.title', $title);
$query->join('table_name', 't');
$query->condition('t.entity_id', 'n.nid');
$query->fields('t', array('column_name'));
$results = $query->execute();

```

Then you could loop through the results like this:

```
foreach ($results as $result):
  print $result->column_name;
endforeach;

```
> 1 votes

# Answer
1. `db_query("select 'column_name' from 'table_name' where entity_id = :nid", array(:nid => $nid));`
2. for eg.

`$result = db_select('node', 'n')
 ->fields('n')
 ->condition('nid', $node->nid,'=')
 ->condition('status', 0,'>')
 ->condition('uid', array(1,5,7),'IN')
 ->execute()
 ->fetchAssoc();`
> 0 votes

---
Tags: 7, forms, database, search
---


title: JSON returned from Memcache is invalid

text:
# Question
Title: JSON returned from Memcache is invalid
I have `Drupal 7` site. I am using `Memcache` for caching.

This is how I am storing the JSON into it

```
    //creating an object of Memcache
    $cache = new Memcache();
    $cache ->addServer('localhost', 11211);
    //adding a key
    $cacheKey = 'mobile';
    //delete old cache
    $cache ->delete($cacheKey);
    //refresh cache
    $cache ->set($cacheKey, serialize($jsonData));

```

No issue till here. But when fetching the JSON from this cache.

**returned JSON fails to validate**

I am using `http://jsonlint.com/` to validate my JSON.

Please note the however the JSON has correct data but issue is validation.

```
$Records = $cache->get($cacheKey);

echo '<pre>';
print_r(Records);
exit();

```

**JSON**

```
{
"defaults": [{
    "nid": "213",
    "public_url": "http:\/\/www.mywebsite.com",
    "HTMLStr": "layout and user interface.\
    r\ n\ t
    http: \ /\/mywebsite.com<\/a><\/p>\r\n"
}]

```

}

Any help highly appreciated.

# Answer
This is **not** really related to Drupal since you are not using the Drupal Memcache module API.

But based on your example. Here is my test code.

```
  // Creating an object of Memcache
  $cache = new Memcache();
  $cache->addServer('localhost', 11211);
  // Adding a key.
  $cacheKey = 'mobile';
  // Delete old cache.
  $cache ->delete($cacheKey);
  // Create a temp json data.
  $jsonData = "{
    'glossary': {
        'title': 'example glossary',
                'GlossDiv': {
            'title': 'S',
                        'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                                        'SortAs': 'SGML',
                                        'GlossTerm': 'Standard Generalized Markup Language',
                                        'Acronym': 'SGML',
                                        'Abbrev': 'ISO 8879:1986',
                                        'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                                                'GlossSeeAlso': ['GML', 'XML']
                      },
                                        'GlossSee': 'markup'
                  }
              }
          }
      }
  }";
  // Set the cache.
  $cache ->set($cacheKey, serialize($jsonData));
  // Fetch the cache.
  $Records = $cache->get($cacheKey);

  // Dump the cache.
  echo '<pre>';
  print_r($Records);
  echo '</pre>';

```

and here is the result

```
s:881:"{
    'glossary': {
        'title': 'example glossary',
                'GlossDiv': {
            'title': 'S',
                        'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                                        'SortAs': 'SGML',
                                        'GlossTerm': 'Standard Generalized Markup Language',
                                        'Acronym': 'SGML',
                                        'Abbrev': 'ISO 8879:1986',
                                        'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                                                'GlossSeeAlso': ['GML', 'XML']
                      },
                                        'GlossSee': 'markup'
                  }
              }
          }
      }
  }";

```

with `$Records = unserialize($cache->get($cacheKey));` here is the result.

```
{
    'glossary': {
        'title': 'example glossary',
                'GlossDiv': {
            'title': 'S',
                        'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                                        'SortAs': 'SGML',
                                        'GlossTerm': 'Standard Generalized Markup Language',
                                        'Acronym': 'SGML',
                                        'Abbrev': 'ISO 8879:1986',
                                        'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                                                'GlossSeeAlso': ['GML', 'XML']
                      },
                                        'GlossSee': 'markup'
                  }
              }
          }
      }
  }

```

The only reason why you are not able to see the result is because of this.

```
print_r(Records);

```

which is it should be

```
print_r($Records);

```

`Record` is a variable and therefore it must have a dollar sign before it.

**Test your connection to Memcache**

```
  $cache = new Memcache();
  $cache->addServer('localhost', 11211);
  $stats = @$cache->getExtendedStats();
  $available = (bool) $stats["localhost:11211"];
  var_dump($available);

```

If the result is `true` then you are connected to Memcache if `false` then you are not connected.

**UPDATE 1:**

I tested with your json.

```
  $arr = array(
    "nid" => "213",
    "public_url" => "http:\/\/www.mywebsite.com",
    "HTMLStr" => "layout and user interface.\ r\ n\ t http: \ /\/mywebsite.com<\/a><\/p>\r\n",
  );
  $jsonData = json_encode($arr, JSON_HEX_QUOT | JSON_HEX_APOS);

```

and here is the result

```
s:157:"{"nid":"213","public_url":"http:\\\/\\\/www.mywebsite.com","HTMLStr":"layout and user interface.\\ r\\ n\\ t http: \\ \/\\\/mywebsite.com<\\\/a><\\\/p>\r\n"}";

```
> 1 votes

# Answer
you probably need to deserialize the data with

> unserialize

like:

```
$Records = unserialize($cache->get($cacheKey));

echo '<pre>';
print_r($Records);
exit();

```
> 0 votes

---
Tags: 7, caching
---


# Question
Title: Drupal 8: Pdf (print) search results (search_api)
I am using the Entity PDF plugin in Drupal 8, that does a good job in exporting to PDF nodes, but seems to exclude other scenarios such as Search Result list.

Anyone can provide some hints how would a PDF export be implemented for search results?

# Answer
You can use hook\_entity\_view\_alter() to hidden PDF export link. Sample

```
<?php

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

function examples_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity->getType();
  $mode = $display->getMode();
  //Replace node type with text **page**
  if ($type == 'page' && $mode == 'search_result') {
    unset($build['entity_print_view']);
  }
}

```
> 1 votes

---
Tags: 8, search, files
---


# Question
Title: How to hide node title for specific content type using template file
I am trying to remove a node title on a specific content type (Core Article) using its template file.

I don't want to use preprocess\_node() hook that it's pretty straight forward but not of my liking due to I want to organize all my edited templates in my custom template folder.

What I did is this: I copied the node.tpl.php to my template folder under the folder "templates". I renamed that file to node--article.tpl.php. I edited the template file removing all the header section (which includes the title render function). Cleared the caches but the title is still there.

What am I doing wrong?

EDIT: Here is the code in my node--article.tpl.php

```
<article id="node-<?php print $node->nid; ?>" class="<?php  print $classes; ?> clearfix"<?php  print $attributes; ?>>
   <?php
      // Hide comments, tags, and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      hide($content['field_tags']);
      print render($content);
      ?>
      <?php
     if (!empty($content['field_tags']) || !empty($content['links'])):
      ?>
   <footer>
      <?php
         print render($content['field_tags']);
         ?>
      <?php
         print render($content['links']);
         ?>
   </footer>
   <?php
      endif;
    ?>
    <?php
      print render($content['comments']);
    ?>

```

PS: Sorry for the code styling but I guess html5 tags are breaking the lines in stack exchange editor.

# Answer
> 1 votes
Maybe you render article as full page then $title rendered in `page.tpl.php`

you just need override your content type page template, I mean duplicate `page.tpl.php` ( if you use bootsrap sub theme go to `boostrap` theme boostrap\template\system\page.tpl.php\` file to your subtheme template forlder and rename it to page--article.tpl.php and remove title form it.

I mean remove these lines from it

```
  <?php if (!empty($title)): ?>
    <h1 class="page-header"><?php print $title; ?></h1>
  <?php endif; ?>

```

**dont forget clear the cache**

---
Tags: 7, theming
---


# Question
Title: What is the equivalent of #page & #page-wrapper in Bootstrap theme?
In most of the Drupal themes I find the IDs `#page` and `#page-wrapper`, but it is not available in the Bootstrap theme.

I tried to find in theme, but maximum I could find is class `.container` but is covers only that particulate section i.e. header, main-content, footer.

Is there any ID or class in Bootstrap theme which covers entire webpage like `#page` does in almost all other themes OR if there is not how can I add that?

*To experiment*, I did try to add following to `page.tpl.php` like other themes,

```
<div id="page-wrapper">
  <div id="page">

```

And added following CSS to check,

```
#page {
    border: 5px solid red;
}
#page-wrapper {
    border: 5px solid blue;
}

```

But it applies to border of the browser not to actual width of the page as shown in the following image.

>

Hence looks like this way we can not add this to Bootstrap theme.

Any idea or suggestion how to apply #page and #page-wrapper to Bootstrap theme? Thanks.

# Answer
> 1 votes
After several try and error method, I did find the solution for this.

For a note, I am using LESS.

**Step-1:** Add a `<div>` to `page.tpl.php`

Add following code in the `page.tpl.php` file of your sub-theme.

```
<div id="page-wrapper">
  <div id="page">

```

**Step-2:** Add the following CSS in the `style.less` of your sub-theme.

```
@media(min-width:@screen-sm-min) {
      #page-wrapper {
      width: @container-tablet;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red; }
    }
@media(min-width:@screen-md-min) {
      #page-wrapper {
      width: @container-desktop;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red;}
    }
@media(min-width:@screen-lg-min) {
      #page-wrapper {
      width: @container-large-desktop;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red;}
    }

```

*So, this way, the added `<div>` will be in harmony of Responsive theme of bootstrap and it will not displace any other container in the site and will not interfere with the native responsive design of Bootstrap.*

>

**Further Any suggestion or comment are welcome.**

---
Tags: 7, theming
---


# Question
Title: Showing only one of the Field Collection fields through Views
I created a Field Collection field for a content type. This FC has two fields inside: an image field where I can upload unlimited number of image; and the other one is the title field to be used as a caption for these images.

Now the problem arises when I try to view this content type through Views where I can not modify each FC field but the whole FC. For example, if I had a content type with an image and a title field in Views I could manipulate the image field controlling the image style, the linking if the image links to the file or nothing etc. But since I use FC I can not access the image field settings anymore through Views.

The reason I want to manipulate the FC image field is that I want to use Colorbox inside my image gallery. But first I want to link all these images shown through Views to the node of each image gallery and then I want it to be seen with Colorbox.

Note: I tried to use in the FC settings Output this field as a link but it links only from the title field of FC not from the image field and, as I explained above, I can't manipulate the image field to make it have these settings.

Can someone help me out with this problem? Thank you!

# Answer
> 5 votes
Did you try to ad a new view with "Show: Field Collection Item" and then, you need different relationships and contextual filters. My Field collection Item is called Gallery and Caption

I've got the following relationships (right column of the views):

* "Field collection item: entity with the Gallery and Caption" (this one connects the field collection item with my contenttype gallery)
* "(Field\_gallery\_and\_caption) File Usage: File" "Field collection item: Gallery Image:fid"

And following Contextual Filters (also right column of the views):

* (field\_gallery\_and\_caption) Content: Nid
* Field collection item: Gallery Image:fid

I'm not sure about the order of adjustment, you have to try a little bit. But through relationships and contextual filters, you can get new fields for the views. And while configuring the fields (left column of views), there appears a dropdown called "Relationship", try different settings here, it changes the result.

Not the most detailed help but try to change the settings and you gonna get a result...

# Answer
> 2 votes
Old question so maybe you couldn't do that but now you can:

* Use the displays provided by Field Collection (Structure\>Field Collections\>Manage display). I used the token display for instance and put out the fields I didn' t want to show.
* Go to your View, and for the configuration of the Field Collection you want to use, put Formatter to "Fields only" and then choose your view mode (as I said, I used Token)

And that's it! =)

# Answer
> 0 votes
A very easy way to limit amount of field-(collection)-items to show (and also skip some) is using the module Field multiple limit. From the modules description:

> This is a simple module that provides settings to limit the number of values to display on fields with multiple values.
>
> The module extends the field display settings for fields which permit multiple values. Site administrators can specify how many values to display for each display mode (e.g. teaser). Optionally, an off-set can be specified to skip some values.

The Drupal 7 version depends on Field formatter settings API module.

---
Tags: views, media, entities, javascript
---


# Question
Title: How to get entity type from entity_metadata_wrapper
I can use

```
$entity = entity_metadata_wrapper('node', 1);
$entity->getBundle();

```

to get the node type of an entity. However, entity-wrappers can wrap other types of entities, e.g. users. When calling getBundle() on a user entity, 'user' is returned. What should I call to return the type of entity (should return 'node' in the example above)? I can see when I `print_r($entity)` that $entity-\>type is a protected field of the wrapper object.

# Answer
Hmmm, I seem to have found a way (unsure if this is the 'correct' way...)

```
$entity = entity_metadata_wrapper('node', 1);
$info = $entity->info();  // entity info as an array
$entity_type = $info['type']; // returns 'node' for node entities

```
> 4 votes

---
Tags: entities
---


# Question
Title: How to change a field value with a Rules Action?
I'm trying to set up a Rules Action that can change the value of a field. I created an Action Set with a data type of Node. When I go to create a Rules Action, I have access to every default Drupal node field, but no fields.

Is this simply not possible? Do I need some other module to make this work?

# Answer
You first need to add a condition to check if the field exist on that node, only then it is available to the actions. There is a specific condition to do this.
> 16 votes

# Answer
Using the "Entity has field" (or "content is of type") condition will make the fields become available with data selection in the Action "Set a data value".
> 7 votes

# Answer
Not to contradict both prior answers, but IMO they are both missing (ignoring?) a crucial part of the question, which is "***...I created an Action Set...***". True, part of the solution is, pretty sure, "`Entity has field`" (as in the answer from jcarballo). But, by design of a Rules *Action Set*, you cannot include any Rules Condition in it. Therefor, either of the following is needed to complete the answer to this question:

With the above in mind, you should be able to create a Rules Action like (e.g.) "Set a data value" for your field, if you also add a Rules condition `Entity has field` (related to the field for which you want to set a value). And make sure to add that `Entity has field` condition BEFORE other Rules Conditions in which you might want to refer to this field (if you have any such conditions in your rule).

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

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

---
Tags: 7, entities, rules, actions
---


# Question
Title: How cache tables are different from other normal tables in database?
I want to know, when all the cache tables are stored in database, then whats the logic behind keeping any data to cache, because whenever we query cache, it again hits the database, same as other normal tables exists in database do.

How cache tables are different from other normal tables in database? How cache boost performance when all cache tables also exists in database?

# Answer
Cache tables contain the results of expensive queries. Often more than one query in a single cache row.

As a contrived example, take a node. When you load a node, you have to join in all of the single field tables containing it's data, plus make a bunch of separate queries for extra data. That's a lot of db load.

Wouldn't it be quicker if you could make just one, single, light query and get all of that information in one go?

That's what cache bins are for. There may well be scenarios where querying from cache is as/more expensive than the original operation, but they'd be rare.

Also don't forget your cache doesn't have to be in the database, you can get considerable improvements moving it into memory.
> 5 votes

# Answer
Here is the logic behind it. The cache tables stores/saves the results of your queries. So instead of having to run query X every single time, you store the results of query X in the cache table. So all you have to do is retrieve the results.

Instead of saving the cache to your database, you could/should if you can, store them in memory using modules such as Redis (maintained by Berdir) or Memcached which will retrieve the values much faster than using/querying the database.
> 4 votes

---
Tags: 7, database, caching
---


# Question
Title: Add "Sale" or "Discount" text to a product display using drupal commerce?
I have been searching for an answer a long time with no success at all.

I am buildind a drupal commerce website and i would like to show on a specific products the word "Sale" or "Discount" as showing in the picture below (like the green Sale Tag).

I can do it using photoshop but is really a pain to go over hundred of product just to photoshop a "Sale" text on every product picture in question.

Can someone point me to a specific module that can do such job ?! Note that i know basic CSS so if this could be done using some CSS code, a starting push from any body will be appreciated !

Thank you,

# Answer
> 0 votes
Finally resolved...

For the sake of anyone having the same question, the trick is to add a "CSS Class" to the field in question and use some CSS codes to achieve whatever the design you like.

1) Create the **field in question** in the correspondant content type.

2) Goto manage display of that content type, select what "view" you want to use between the available views on the "manage display" page and then make the **field in question** visible and choose the format to be: **Linked and Wrapped** and then click on field settings where you should:

_ Wrap the title in tag: **DIV**

_ Link title to: **Nothing**

_ Add your class: **yourclass**

3) Use **yourclass** and add some CSS Code to design the content of the **field in question**.

NOTE: The good thing is that when the **field in question** is **empty** all the design just disappear and you will see nothing on your product which is awesome.

# Answer
> 3 votes
With Views Conditional you can make it that if `Label Discount Name` is equal to `Sale` then `<div class="sale"><img src="...."></div>` Otherwise output nothing.

Then do the same for Discount.

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> ```
> Equal To
> Not Equal To
> Greater Than
> Less Than
> Empty
> Not Empty
>
> ```
>
> Views conditional allows you to output text based on the result of the condition.

---
Tags: 7, commerce
---


# Question
Title: How to know that the user has completed a quiz?
Is there any function to pass the user id and the quiz node id and get true or false if the user has completed the quiz?

Or I have to write sql query for this?

# Answer
With this query:

```
SELECT * FROM quiz_node_results n;

```

You can get all the information about the quizzes:

```
+-----------+-----+-----+-----+------------+------------+----------+-------+------------+--------------+-----------+
| result_id | nid | vid | uid | time_start | time_end   | released | score | is_invalid | is_evaluated | time_left |
+-----------+-----+-----+-----+------------+------------+----------+-------+------------+--------------+-----------+
|         1 |   1 |   1 |   1 | 1472154665 | 1472482124 |        0 |   100 |          0 |            1 |         0 |
+-----------+-----+-----+-----+------------+------------+----------+-------+------------+--------------+-----------+

```

Once you start a new quiz a new entry will be created in the table:

```
+-----------+-----+-----+-----+------------+------------+----------+-------+------------+--------------+-----------+
| result_id | nid | vid | uid | time_start | time_end   | released | score | is_invalid | is_evaluated | time_left |
+-----------+-----+-----+-----+------------+------------+----------+-------+------------+--------------+-----------+
|         1 |   1 |   1 |   1 | 1472154665 | 1472482124 |        0 |   100 |          0 |            1 |         0 |
|         2 |   1 |   4 |   4 | 1472482245 |          0 |        0 |     0 |          0 |            0 |         0 |
+-----------+-----+-----+-----+------------+------------+----------+-------+------------+--------------+-----------+

```

In this case the user with uid 4 has started at 1472482245 (time\_start) the quiz with nid 1.

Once the user finish the quiz you will see a value in the time\_end column, in this case 1472482657.

```
+-----------+-----+-----+-----+------------+------------+----------+-------+------------+--------------+-----------+
| result_id | nid | vid | uid | time_start | time_end   | released | score | is_invalid | is_evaluated | time_left |
+-----------+-----+-----+-----+------------+------------+----------+-------+------------+--------------+-----------+
|         1 |   1 |   1 |   1 | 1472154665 | 1472482124 |        0 |   100 |          0 |            1 |         0 |
|         2 |   1 |   4 |   4 | 1472482245 | 1472482657 |        0 |     0 |          0 |            1 |         0 |
+-----------+-----+-----+-----+------------+------------+----------+-------+------------+--------------+-----------+

```

And with this query:

```
SELECT n.pass_rate FROM quiz_node_properties n WHERE n.vid = 1;

```

You can get the pass rate (in this case for the vid 1)

```
+-----------+
| pass_rate |
+-----------+
|        75 |
+-----------+

```

So, if the `score` is lower than the `pass_rate` the user has not passed the quiz with the minimum of points required.
> 1 votes

---
Tags: 7, quiz
---


# Question
Title: How to change property 'string' in object with class Drupal\Core\StringTranslation\TranslatableMarkup in my hook?
The property 'string' is protected as I can see here https://api.drupal.org/api/drupal/core!lib!Drupal!Core!StringTranslation!TranslatableMarkup.php/class/TranslatableMarkup/8.2.x

but I need to change word "- Any -" in my exposed filter form to my string "All terms"?

I cannot do this cause I do not know how to use this class and how to change output.

This hook says: cannot get value of protected property.

```
function MYtheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ( ( $form['#attributes']['class'][0] == 'views-exposed-form' ) &&
       ( $form['#info']['filter-field_color_target_id']['operator'] == 'field_color_target_id_op' ) )
  {
      dpm($form['color']['#options']['All']->string);
      //$form['color']['#options']['All']->string = t('All terms');
  }
}

```

# Answer
The object `TranslatableMarkup` is the result of `t()`. It's not possible to modify the content of this object. You overwrite the object with a new instance:

```
form['color']['#options']['All'] = t('All terms');

```
> 8 votes

---
Tags: forms, 8
---


# Question
Title: how to stop annoymous users to login in drupal
In wordpress, I have been disabling unknown people from accessing my `wp-login.php` using a script in the `.htaccess`.

```
RewriteCond %{REMOTE_ADDR} !^154\.70\.159\.2
RewriteRule ^wp-(login|register)\.php http://www.example.com [R,L]
RewriteRule ^wp-(admin)\.php http://www.example.com [R,L]

```

Meaning only the user with that above IP will b allowed to Login.

How can I do this with Drupal, so that I redirect unknown user with different IP to my homepage. Those who try to visit the `www.example.com/user` link.

# Answer
> 3 votes
There is the restrict by IP module, which can solve the use-case pretty fast. For the second part, depending on if you are in 7 or 8, you would want to write code to handle a request to either of the routes, evaluate the allowed IPs against the user IP, and do a redirect. Would be easier and more manageable vs the htaccess route, in my opinion.

You can disable user registration by disabling it in the admin (only admins can create accounts).

Furthermore, no one can even get to /admin or administrative pages without the right permissions anyway, so if they are not logged in, it isn't really an issue. That just leaves the login and forgot password page. Forcing a redirect within admin paths might also interfere with things like AJAX actions as well - I would probably leave that alone.

# Answer
> 1 votes
You can use roughly the same rewrite rules in your .htaccess:

```
RewriteCond %{REMOTE_ADDR} !^154\.70\.159\.2
RewriteRule ^user/ http://www.example.com [R,L] // Prevent access to any user/* URL
RewriteRule ^admin/ http://www.example.com [R,L] // Prevent access to any /admin/*

```

The second rule should prevent access to most admin page, but some admin pages/features are no behind such URLs and cannot be easily protected this way.

---
Tags: redirection, .htaccess
---


title: Add custom value in session

text:
# Question
Title: Add custom value in session
How can I add value in drupal session. I am adding value using $\_SESSION = 'my value', but once trying to print $\_SESSION variable it return blank.

# Answer
> 2 votes
Drupal bootstrap takes care of session\_start for you, so you should be able to define sessions like...

```
$_SESSION['my_data'] = 'my value';

```

You can also add the following in settings.php to determine the life span of the session

```
ini_set('session.cache_expire',     200000);

```

---
Tags: sessions
---


# Question
Title: Exposed filter value into the session and cookie?
I want users visit my site regularly. And I need to store their settings to session (cookie). These settings are: Views Exposed Filter on the FrontPage (like to hide materials from the black list users).

So I have the FrontPage View and Taxonomy Term View. These views have exposed filter.

Once visitor selected values in this filter they should to store during he browsing the site and more when he visit site again.

I do not want to use JavaScript. I want to store cookie with php and to get it with php.

And I want drupal cache all pages for all possible filter values.

Please, have I to write a new Drupal CMS or where have I to get the answer?

# Answer
There is a setting in the "Configure filter criterion" form.

Test this one. I guess it will write a cookie for the user.
> 0 votes

---
Tags: views, caching
---


# Question
Title: How to add a class for different fields of a view?
I have created the view for image slider as below:

>

I want to get the structure for the image slider as below:

```
            <ul id="image-slider" class="image-slider">

                <li>
                    <a href="#" target="_blank">
                        <img src="images/1.jpg" alt="image1"/>
                    </a>
                    <div class="image-description">
                        <h3>This is is title</h3>
                        <p>This is description</p>
                    </div>
                </li>

                <li>
                    <img src="images/2.jpg" alt="image2"/>
                    <div class="image-description">
                        <h3>...</h3>
                    </div>
                </li>

                <li><!-- ... --></li>

                <!-- ... -->

            </ul>

```

My template files are the following:

* ### views-view-unformatted--main\_slider.html.twig

```
        {#
        /**
         * @file
         * Theme override to display a view of unformatted rows.
         *
         * Available variables:
         * - title: The title of this group of rows. May be empty.
         * - rows: A list of the view's row items.
         *   - attributes: The row's HTML attributes.
         *   - content: The row's content.
         * - view: The view object.
         * - default_row_class: A flag indicating whether default classes should be
         *   used on rows.
         *
         * @see template_preprocess_views_view_unformatted()
         */
        #}

        <ul id="image-slider" class="image-slider">
            {% for row in rows %}
              {%
                set row_classes = [
                  default_row_class ? 'views-row',
                ]
              %}
                {{ row.content }}
            {% endfor %}
        </ul>

```
* ### views-view-fields--main\_slider.html.twig

```
{#
/**
 * @file
 * Theme override to display all the fields in a row.
 *
 * Available variables:
 * - view: The view in use.
 * - fields: A list of fields, each one contains:
 *   - content: The output of the field.
 *   - raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - class: The safe class ID to use.
 *   - handler: The Views field handler controlling this field.
 *   - inline: Whether or not the field should be inline.
 *   - wrapper_element: An HTML element for a wrapper.
 *   - wrapper_attributes: List of attributes for wrapper element.
 *   - separator: An optional separator that may appear before a field.
 *   - label: The field's label text.
 *   - label_element: An HTML element for a label wrapper.
 *   - label_attributes: List of attributes for label wrapper.
 *   - label_suffix: Colon after the label.
 *   - element_type: An HTML element for the field content.
 *   - element_attributes: List of attributes for HTML element for field content.
 *   - has_label_colon: A boolean indicating whether to display a colon after
 *     the label.
 *   - element_type: An HTML element for the field content.
 *   - element_attributes: List of attributes for HTML element for field content.
 * - row: The raw result from the query, with all data it fetched.
 *
 * @see template_preprocess_views_view_fields()
 */
#}

<li>
{% for field in fields -%}
      {%- if field.element_type -%}

          {{ field.content }}

      {%- endif %}
{%- endfor %}
</li>

```

When I inspect the element, I get the following, in the browser.

```
            <!-- THEME DEBUG -->
            <!-- THEME HOOK: 'views_view_unformatted__main_slider' -->
            <!-- FILE NAME SUGGESTIONS:
               * views-view-unformatted--main-slider.html.twig
               * views-view-unformatted--main-slider.html.twig
               * views-view-unformatted.html.twig
            -->
            <!-- BEGIN OUTPUT from 'themes/custom/law_advice_theme/templates/views/views-view-unformatted--main_slider.html.twig' -->

            <ul id="image-slider" class="image-slider">

            <!-- THEME DEBUG -->
            <!-- THEME HOOK: 'views_view_fields__main_slider' -->
            <!-- FILE NAME SUGGESTIONS:
               * views-view-fields--main-slider.html.twig
               * views-view-fields--main-slider.html.twig
               * views-view-fields.html.twig
            -->
            <!-- BEGIN OUTPUT from 'themes/custom/law_advice_theme/templates/views/views-view-fields--main_slider.html.twig' -->

            <li>

            <!-- THEME DEBUG -->
            <!-- THEME HOOK: 'views_view_field__main_slider' -->
            <!-- FILE NAME SUGGESTIONS:
               * views-view-field--main-slider.html.twig
               * views-view-field--main-slider.html.twig
               * views-view-field.html.twig
            -->
            <!-- BEGIN OUTPUT from 'themes/custom/law_advice_theme/templates/views/views-view-field--main_slider.html.twig' -->

             <div class="image-description">

            <a href="/my_project/lorem-ipsum-dolor-sit-amet-falli-noster-constituam" hreflang="en">Lorem ipsum dolor sit amet, falli noster constituam</a>
           </div>

            <!-- END OUTPUT from 'themes/custom/law_advice_theme/templates/views/views-view-field--main_slider.html.twig' -->

            <!-- THEME DEBUG -->
            <!-- THEME HOOK: 'views_view_field__main_slider' -->
            <!-- FILE NAME SUGGESTIONS:
               * views-view-field--main-slider.html.twig
               * views-view-field--main-slider.html.twig
               * views-view-field.html.twig
            -->
            <!-- BEGIN OUTPUT from 'themes/custom/law_advice_theme/templates/views/views-view-field--main_slider.html.twig' -->

             <div class="image-description">

            <p>sea in discere feugiat, modus moderatius intellegebat ad pro. Tantas indoctum ut eum, eirmod consequuntur est id, id partem euripidis qui. Wisi fastidii concludaturque te vim, ei wisi quaerendum est. Nam an option hendrerit, ius nulla viris similique ad, nam apeirian delicatissimi ad. Id autem harum adipiscing cum, duo eu hinc nibh inani.</p>
           </div>

            <!-- END OUTPUT from 'themes/custom/law_advice_theme/templates/views/views-view-field--main_slider.html.twig' -->

            <!-- THEME DEBUG -->
            <!-- THEME HOOK: 'views_view_field__main_slider' -->
            <!-- FILE NAME SUGGESTIONS:
               * views-view-field--main-slider.html.twig
               * views-view-field--main-slider.html.twig
               * views-view-field.html.twig
            -->
            <!-- BEGIN OUTPUT from 'themes/custom/law_advice_theme/templates/views/views-view-field--main_slider.html.twig' -->

             <div class="image-description">

            <!-- THEME DEBUG -->
            <!-- THEME HOOK: 'image_formatter' -->
            <!-- BEGIN OUTPUT from 'themes/custom/law_advice_theme/templates/field/image-formatter.html.twig' -->

            <!-- THEME DEBUG -->
            <!-- THEME HOOK: 'image' -->
            <!-- BEGIN OUTPUT from 'themes/custom/law_advice_theme/templates/field/image.html.twig' -->
            <img src="/my_project/sites/default/files/2016-08/u215_a_0.png" width="1200" height="431" alt="Lorem ipsum dolor sit amet, falli noster constituam" typeof="foaf:Image" />

            <!-- END OUTPUT from 'themes/custom/law_advice_theme/templates/field/image.html.twig' -->

            <!-- END OUTPUT from 'themes/custom/law_advice_theme/templates/field/image-formatter.html.twig' -->

            </div>

            <!-- END OUTPUT from 'themes/custom/law_advice_theme/templates/views/views-view-field--main_slider.html.twig' -->

            </li>
            <!-- END OUTPUT from 'themes/custom/law_advice_theme/templates/views/views-view-fields--main_slider.html.twig' -->

```

The class `image-description` is added to all the fields. I want to add that class only for the title and description fields, but not for the image to get the structure for image slider. How do I remove the parent `<div>` from image? Is there any hook to get this structure?

# Answer
In **views-view-fields--main-slider.html.twig**

```
<div class="image-description">{{ fields.title.content }}</div>
<div class="image-description">{{ fields.field_slider_description.content }}</div>
<div>{{ fields.field_slider_image.content }}</div>

```

If you need the `<li>`'s you should use `HTML List` as your format instead of using `Unformatted list`.
> 2 votes

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


# Question
Title: After enabling utf8mb4 on 7.50, cannot enable update module
I upgraded to 7.50, ran the utf8mb4 convert drush commmand, and enabled utf8mb4 in settings.php. Before running the utf8mb4 convert drush command, I did have to convert several columns manually like this:

```
ALTER TABLE commerce_order CHANGE order_number order_number VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

```

I tested my site and as far as I can tell everything is working fine.

However, when I try to enable the update module (which had been uninstalled on the site), I get the following error:

```
cpu:update pk$ drush @mysite en update
PTY allocation request failed on channel 0
The following extensions will be enabled: update
Do you really want to continue? (y/n): y
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1071    [error]
Specified key was too long; max key length is 767 bytes in
/srv/bindings/d767913ee30941f3847c9361d2d787ba/code/includes/database/database.inc:2204
Stack trace:
#0
/srv/bindings/d767913ee30941f3847c9361d2d787ba/code/includes/database/database.inc(2204):
PDOStatement->execute(Array)
#1
/srv/bindings/d767913ee30941f3847c9361d2d787ba/code/includes/database/database.inc(683):
DatabaseStatementBase->execute(Array, Array)
#2
/srv/bindings/d767913ee30941f3847c9361d2d787ba/code/includes/database/schema.inc(664):
DatabaseConnection->query('CREATE TABLE {c...')
#3
/srv/bindings/d767913ee30941f3847c9361d2d787ba/code/includes/database/database.inc(2753):
DatabaseSchema->createTable('cache_update', Array)
#4
/srv/bindings/d767913ee30941f3847c9361d2d787ba/code/includes/common.inc(7109):
db_create_table('cache_update', Array)
#5
/srv/bindings/d767913ee30941f3847c9361d2d787ba/code/includes/module.inc(479):
drupal_install_schema('update')
#6 /opt/pantheon/drush-8/commands/core/drupal/environment_7.inc(143):
module_enable(Array)
#7 /opt/pantheon/drush-8/commands/pm/pm.drush.inc(1167):
drush_module_enable(Array)
#8 /opt/pantheon/drush-8/includes/command.inc(366):
drush_pm_enable('update')
#9 /opt/pantheon/drush-8/includes/command.inc(217):
_drush_invoke_hooks(Array, Array)
#10 /opt/pantheon/drush-8/includes/command.inc(185):
drush_command('update')
#11 /opt/pantheon/drush-8/lib/Drush/Boot/BaseBoot.php(67):
drush_dispatch(Array)
#12 /opt/pantheon/drush-8/includes/preflight.inc(66):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#13 /opt/pantheon/drush-8/drush.php(12): drush_main()
#14 {main}

```

When I enable the update module, it isn't able to create the update or cache\_update tables. How can I fix this?

# Answer
> 0 votes
**Hacking core, not a great answer. This is just the best I have found so far.**

In `modules/update/update.install`:

```
/**
 * Implements hook_schema().
 */
function update_schema() {
  $schema['cache_update'] = drupal_get_schema_unprocessed('system', 'cache');
  $schema['cache_update']['description'] = 'Cache table for the Update module to store information about available releases, fetched from central server.';
  return $schema;
}

```

So I went to `modules/system/system.install`:

```
  $schema['cache'] = array(
    'description' => 'Generic cache table for caching things not separated out into their own tables. Contributed modules may also use this to store cached items.',
    'fields' => array(
      'cid' => array(
        'description' => 'Primary Key: Unique cache ID.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'data' => array(
        'description' => 'A collection of data to cache.',
        'type' => 'blob',
        'not null' => FALSE,
        'size' => 'big',
      ),
      'expire' => array(
        'description' => 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'created' => array(
        'description' => 'A Unix timestamp indicating when the cache entry was created.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'serialized' => array(
        'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
        'type' => 'int',
        'size' => 'small',
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'indexes' => array(
      'expire' => array('expire'),
    ),
    'primary key' => array('cid'),
  );

```

And I changed the length of the varchar for the primary key from `255` to `191`. Now I can enable and disable the update module properly.

---
Tags: 7, database
---


title: How to remove reply link?

text:
# Question
Title: How to remove reply link?
I've installed the AJAX Comments module in my Drupal site.

Am unable to find the configuration to remove the **reply** Link from the comment reply, kindly suggest.

Attaching a screenshot below:

# Answer
You can implement template\_preprocess\_comment() in your module file or theme's template.php file. And check if comment has Parent Comment ID (pid), if yes then remove reply link.

```
/**
 * Implements template_preprocess_comment().
 */
function [MODULE/THEME_NAME]_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  if (!empty($comment->pid)) {
    unset($variables['content']['links']['comment']['#links']['comment-reply']);
  }
}

```
> 4 votes

---
Tags: comments
---


# Question
Title: How to hide menu item from high level roles but show for low level
I have 3 roles on site:

1. anonymous user
2. authenticated user
3. admin

I created a new page:

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

    $items['learning'] = array(
        'page callback'    => 'learning_output',
        'access callback' => 'learning_access',
        'type' => MENU_CALLBACK,
        );

    return $items;
}

```

I manually created a menu item for this page in the top menu. This item should be displayed only for authenticated users, but not admins. Unfortunately, admin as also an authenticated user. So I had to use a trick to disallow access to this page to admins using this access callback:

```
function learning_access()
{
    global $user;

    $n = count($user->roles);
    if ($n === 1)
    {
        $data = array_values($user->roles);
        if ($data[0] === 'authenticated user')
        {
            return true;
        }
    }

    return false;
}

```

It works but when I uploaded this module to server, I was unable to manually add a menu item for this page. Because admin doesn't have access to it.

How can I allow an admin to access this page? In the same time the menu item shouldn't be shown for him.

# Answer
As per the discussion above,

Remove `'access callback' => 'learning_access',` add `drupal_access_denied()` in page call back

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

  $items['learning'] = array(
    'page callback' => 'learning_output',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function learning_output() {
  global $user;

  $n = count($user->roles);
  if ($n === 1) {
    $data = array_values($user->roles);
    if ($data[0] === 'authenticated user') {
      drupal_access_denied();
    } else {
      //YOUR code Here
    }
  }
}

```

And Use Roles for Menu module to hide the `learning` menu.

> This module allows you to restrict access to menu items based on user roles. It is used when you don't want to copy your whole menu just because for one specific role you want to hide one menu item.
>
> The module will add a fieldset with options for restricting access or gaining access to menu link for a specific role/roles
> 1 votes

---
Tags: 7, routes, users
---


# Question
Title: How to put a Slider widget into the Better Exposed Filters for Ubercart price and other product features?
How to put a Slider widget into the Better exposed filters and product search result view in Drupal 7 for Ubercart price and other product features?

I have developed an ecommerce shop, and need to a add slider widget to search products.

# Answer
Jquery UI and most of its widgets are embedded with D7 core, in *misc/ui* folder. First add these lines to your theme template file (`sites/all/themes/YOUR_THEME/template.php`) :

```
/**
 * Implements template_preprocess_views_view().
 */
function YOUR_THEME_preprocess_views_view(&$vars) {//replace YOUR_THEME by your theme name
  $view = $vars['view'];
  switch($view->name) {
    case 'YOUR_VIEW' : //replace YOUR_VIEW by your view name

      drupal_add_library('system','ui.slider');
      drupal_add_css('/misc/ui/jquery.ui.slider.css');
      break;
  }
}

```

Don't forget to clear cache.

Your filter must be compatible with is between, lower, greater operators. This is fine for numeric fields. In the filter setup, set it as exposed and choose "is between" operator.

Last, in views advanced settings, in the BEF setup screen, select Jquery ui slider for your filter and adjust other settings like range at convenience.

## EDIT

To answer your comments, **don't edit Bartik or other core files**. You can easily **create a subtheme** as following :

1. Create the folder: `/sites/all/themes/vassia`
2. Create the file `/sites/all/themes/vassia/vassia.info`
3. put this code in `vassia.info`

```
name = vassia
description = my first subtheme
core = 7.x
base theme = bartik

stylesheets[all][] = css/vassia.css
stylesheets[all][] = css/colors.css

regions[header] = Header
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[highlighted] = Highlighted

regions[featured] = Featured
regions[content] = Content
regions[sidebar_first] = Sidebar first
regions[sidebar_second] = Sidebar second

regions[triptych_first] = Triptych first
regions[triptych_middle] = Triptych middle
regions[triptych_last] = Triptych last

regions[footer_firstcolumn] = Footer first column
regions[footer_secondcolumn] = Footer second column
regions[footer_thirdcolumn] = Footer third column
regions[footer_fourthcolumn] = Footer fourth column
regions[footer] = Footer

settings[shortcut_module_link] = 0

```
4. Create a file named: `/sites/all/themes/vassia/css/vassia.css` for your future css custom
5. If you need colors features, copy the file `/themes/bartik/css/colors.css` to `/sites/all/themes/vassia/css/colors.css` and copy the folder and its contents `/themes/bartik/color/` to `/sites/all/themes/vassia/color/`
6. Go to the the Administration \> Appearance page to enable your new subtheme called Vassia

Everything is very well explained in Creating a subtheme DO page. **Now the slider part**

1. Create a file `/sites/all/themes/vassia/template.php`
2. Write exactly this code in your template.php file :

```
<?php
/**
 * Implements template_preprocess_views_view().
 */
function vassia_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  switch($view->name) {
    case 'productviewwithsliders' :

      drupal_add_library('system','ui.slider');
      drupal_add_css('/misc/ui/jquery.ui.slider.css');
      break;
  }
}

```
3. Double check the view name. Clear all caches

Enjoy
> 2 votes

# Answer
Can you try Slide Field Views Module

> The sliderfield module provides a new widget for number fields (decimal, float, and integer) and a form element. When creating a numeric field, select the slider widget.
>
> This project uses the jQuery UI slider included with core.

Or this Module Select with Style

> The Select with Style project download contains two modules containing three styleable widgets:
>
> Slide with Style, contains a field widget to enter numbers or list values via sliders when creating content and also to filter using this widget in Views. This includes double-handled sliders to input "in-between" ranges. Select with Style, comprises two widgets to enter taxonomy fields, in particular hierarchical taxonomies, when creating content and also to filter by these taxonomy fields in Views These are light-weight solutions that have no external dependencies. No external libraries are required. Only minimum configuration, no permissions, no coding. Just style!
> 1 votes

---
Tags: 7, ubercart, javascript
---


title: Website consuming more memory

text:
# Question
Title: Website consuming more memory
I have nearly 150 Panel pages and different template files. I generated lot of blocks using Node Block module to be used in the Panel pages.

I guess this is causing memory issues in both MySQL and Apache configuration. Any solution for this memory issues?

My global memory\_limit is 128M. Only after setting 512M in **settings.php**, my custom Drupal View is generating the output (otherwise, it generated a 502 error).

Is there a way so that I can set memory\_limit only for my custom View?

# Answer
Refer to the Changing PHP memory limits document, you can use

```
ini_set('memory_limit', '64M');

```

which should be in your `settings.php` file.
> 1 votes

---
Tags: nodes, blocks, panels, views
---


# Question
Title: How to get values from $form_state with webform
I'm using webform for submission and trying to simulate GET parameters (though by default it uses POST).

Here's my code implementing `hook_form_alter()`:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $nid = 2;
  if ($form_id == 'webform_client_form_' . $nid) {
    $option['query'] = array(
        'name' => $form_state['values']['name'],
        'email' => $form_state['values']['email'],
        'gender' => $form_state['values']['gender'],
        'birthday' => $form_state['values']['birthday'],
        );
    $form['#action'] = url('path/to/myViewsPage', $option);
  }

```

Above code should take me to

```
'path/to/myViewsPage?name=tom&email=tom@gmail.com&gender=male&birthday=12/21/2013'

```

But I got following error:

> Undefined index: values in mymodule\_form\_alter()

Could someone tell me where to define the `$form_state['values']`? Isn't it predefined by Webform?

# Answer
> 1 votes
In your form\_alter() you should ADD a new submission handler.

```
function mymodule_form_alter($form, &$form_state, $form_id) {
 $nid = 2;
  if ($form_id == 'webform_client_form_' . $nid) {
    $form['#submit'][] = 'your_submit_handler';
  }
 }

```

In your\_submit\_handler() these values will be available

```
function your_submit_handler(&$form, &$form_state) {
   $option['query'] = array(
    'name' => $form_state['values']['name'],
    'email' => $form_state['values']['email'],
    'gender' => $form_state['values']['gender'],
    'birthday' => $form_state['values']['birthday'],
   );
   $url = url('path/to/myViewsPage', $option);// (valid path or whatever)
   $form_state['redirect'] = $url;
}

```

You dont care about the webform node being saved you only need to redirect, right? This will run alongside with yout default webform submit handler.

# Answer
> 1 votes
It's a bit hackish, but I think it would it be better if you set the path to your View in `$form['#action']` and post the form directly to your View. Then on your Views page you grab the posted values from the form, in a contextual filter if you need that. In that way you also completely bypass the submission handling and nothing is saved.

# Answer
> 1 votes
```
//  echo"<pre>"; print_r($form_state); die;
/*** here you check all values of webform which is submitted ***/

$fname = $form_state['input']['submitted']['Your_field_ID'];

```

# Answer
> 0 votes
Webform has its own hook to access the submit and all. You could use hook\_webform\_submission\_presave().

> Modify a Webform submission, prior to saving it in the database.
>
> **Parameters**
>
> **$node:** The Webform node on which this submission was made.
>
> **$submission:** The Webform submission that is about to be saved to the database.

See All Webform Module Hooks.

# Answer
> 0 votes
Try this:

```
 $form_state = form_state_defaults();
 $form_build_id = $_POST['form_build_id'];
 // Get the form from the cache.
 $form = form_get_cache($form_build_id, $form_state);

```

or by providing the form id:

credits: How do I load the $form\_state for a form loaded with drupal\_get\_form?

```
// Get the form.
$form = drupal_get_form('my_form_id');
// Get the default form state.
$form_state = form_state_defaults();
// Get the form and form state from the cache for the form you just got.
form_get_cache($form['#build_id'], $form_state);

```

---
Tags: 7, forms, webforms
---


# Question
Title: Can I use taxonomy term as relationship in view?
I created a content type called 'Job' in which I added:

* a 'Company name' field of term reference type
* a vocabulary 'Organizations' containing company names as terms

I want to create a view of nodes of type 'Job' in which I want to display the email of the user who have created it?

How can I do so?

**Notes**:

* When I try to create a relationship using the company name field, it does not show user email in fields and when I use author as relationship its showing?
* I have both relationships (ie relationship on user + relationship on taxonomy term), but is it possible to use only one i.e company name?
* I have created 'company page' as content type containing email id and user reference field so it can relate to this?

# Answer
> 0 votes
You can create a view of `jobs`:

with a taxonomy term relationship on your `field_company_name` in order to show the taxonomy term name and any other fields it might have.

In order to show the email of user that is referenced from the taxonomy term you will also need a relationship (via the field\_company\_name relationship) on `user` so that you can access the user fields (eg email). The option to add this relationship will now be available from the relationships list, if you filter by user.

---

Sidenote: You may want to consider using an additional email address on the user for this in case the user does not want to receive job applications at their own personal email address, but wants to use their personal email address to manage the account.

---
Tags: views
---


# Question
Title: How to change the entity view display configuration programmatically?
In a hook\_install implementation, I need to change the entity view display configuration of certain bundle / view mode combinations. For instance, I would like to change the 'teaser' view mode of the 'article' bundle and hide 'field\_image'.

When you export the configuration, you'll see those settings stored in `core.entity_view_display.node.article.teaser.yml`. I know it's possible to load the configuration like this:

```
$view_mode_config = \Drupal::configFactory()->getEditable('core.entity_view_display.node.article.default');

```

This would allow you to change and save the config object, but I suppose that is not the correct way to do it. I'm guessing there must be some kind of view mode manager class I should use to do this, but I haven't been able to find it.

So how do I change the entity view display configuration programmatically?

Bonus question: When you find yourself in a situation like this, what are your strategies to explore the code and find the classes you need?

# Answer
> 5 votes
There are two configuration types. Simple configuration and configuration entities. In this case this is a configuration entity. The class name is in camelCase:

**EntityViewDisplay.php**

```
class EntityViewDisplay extends EntityDisplayBase implements EntityViewDisplayInterface

```

If you have a config entity for the configuration, you can load the config entity,

```
$storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
$view_display = $storage->load('node.article.default');

```

modify it and save it:

```
$view_display->save();

```

Why you want to use config entities?

You can get the array of the configuration:

```
$config = $view_display->toArray();

```

This is not different from what you get in the yml file or config api.

The advantage is, that config entities usually have method for special configuration tasks. With displays this is for example to add or remove components:

```
$view_display->setComponent('body', [
     'type' => 'text_summary_or_trimmed',
     'settings' => ['trim_length' => '200'],
     'weight' => 1,
   ])
   ->removeComponent('field_image')
   ->save();

```

That is much easier than to do this in the configuration array.

---
Tags: 8, configuration, entities
---


# Question
Title: Is there any drupal module to export/import all ubercart products with product details(attributes)
I am looking for the module which having the option to import all ubercart products including all information like product images, price, sale price and other attributes. After exporting the information how we can import these to other drupal setup.

If there is no single module to do this then what will be the right approach to do the same.

# Answer
I would use start by having a look at UberCart Feeds with uc\_feeds\_product\_importer they should help you get the job done.
> 1 votes

---
Tags: 7, ubercart
---


title: Flag content once seen in a slideshow

text:
# Question
Title: Flag content once seen in a slideshow
Is there a way with either flags or rules or another module to make content being displayed in a slideshow flagged/marked as "viewed"? Then on refresh that content wouldn't display again to that user. Functionality of swiping for the mobile experience is key here. Think of it as a simplified tinder functionality.

# Answer
> 1 votes
I think No Sssweat comment is right in that this requires custom code.. And you should include some extra details regarding Pierre's questions.

Assuming that you want it like Tinder, I think triggering a hidden flag on each node for each swipe event could be the easiest option. Then on refresh, a views filter would hide flagged content by that user.

This answer describes a method for doing similar. I haven't tested it myself yet but it's an accepted answer and quite recent so it should still work.

It's hard to give a more thorough answer for this without knowing more about the slideshow. And my jQuery is rudimentary at best. If this is a viable approach, post some more details and hopefully myself or another user can help with getting the event. If not, I'll remove this.

---
Tags: flags, javascript
---


title: Content type with webform

text:
# Question
Title: Content type with webform
Hi All I have I issue for my content type like

1. I have content type of property user can add property fields this is ok
2. My problem is i have to add static form every time . i want it default of every content type is it possible please give me suggestion for this

# Answer
> 2 votes
There is a setting in Webform "Available as block" so, it will be Available as block, you can use this block in all node pages

---
Tags: 7, webforms
---


# Question
Title: View block - show only field content from own page
I am creating a view block to be displayed on every page of a specific content-type. Among other things, this view shows a field from that content type. How can I configure the view so that it will only display the field data **from the page it is on**? Right now it shows the data from **every** instance of that content-type field. Is there a way to reference the 'parent' page only?

# Answer
You van do this with a contextual filter on your block view.

There is a very gold tutorial located here: http://dannyenglander.com/blog/using-views-contextual-filters-create-related-content-block-drupal-7

If anything is unclear dont hesitate to ask! ;-)
> 1 votes

# Answer
Add a **contextual filter** on your block view for **Node Id**. Then Under "**When the filter value is NOT available**", select **Provide default value** and choose in the select list, **Content ID from URL**.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Prevent rule from triggering on Entity Reference Fields
I am trying to add a rule that does something when the user views my content type "contacts", so I used the "Content is viewed of type" event to trigger the rule.

Contacts can also be added to other nodes via the Entity Reference Field. Eg. for the content type "events" you can add the contact in charge of it.

Problem is now that this rule also triggers for content type "events", cause of the "contacts" reference.

How can I prevent that?

# Answer
> 1 votes
It shouldn't fire because of an entity reference field..

Have you added a `Content is of type` condition to the rule?

Data selector: node
Value: Contacts.

Edit:

It could be that the display mode of the referenced entities is counting as a view.

Add a condition, `data comparison` for `site:current-page:url` and `node:url`

This will force rules to check the page url which will return FALSE for every page except the nodes's pages.

---
Tags: entities, rules
---


# Question
Title: Locating the source of Forbidden message
When I login I see these "Forbidden" messages. How to track the source of this message?

Also I've enabled these settings:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

# Answer
> 0 votes
I started disabling modules one by one and rest\_auth was actually causing it though it was not being used. Simply disabling solved it. And yes it does not contain any word "**forbidden**".

---
Tags: 7
---


# Question
Title: How to perform bulk operations on a view when the view is displayed but without the need to select rows?
I would like to execute certain Rules based bulk operations on a view (using the VBO module). But not the way they are normally done when using VBO, i.e selecting the rows in the view and then clicking the operation to execute.

Instead I want VBOs to get executed when the view page is displayed. So that I dont need to select the rows and execute VBO operations on them.

Any suggestions?

# Answer
To "*trigger the execution of certain Rules when visiting the view page*" (as in your question), is something you can do by using a special feature of the Rules module, i.e. a technique that is similar to what is described in the answer to "How to execute VBO list of nodes in Rules on After updating an existing user account event?". Read on for more details about the steps to be completed, specific to your question here.

Create a custom Rules that will ***execute the VBO list*** that you already have, and which looks similar to this example (which was used to process a VBO view of unread messages, with a path like `user/%/messages/unread`):

```
{ "rules_mark_all_unread_messages_read" : {
    "LABEL" : "Mark all unread messages read",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "views_bulk_operations" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "user\/\\d+\/messages\/unread",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "views_bulk_operations_action_load_list" : {
          "USING" : { "view" : "messages_by_user|page_3" },
          "PROVIDE" : { "entity_list" : { "unread_msgs_list" : "A list of unread messages" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "unread-msgs-list" ] },
          "ITEM" : { "current_msg" : "Current message" },
          "DO" : [
            { "component_rules_flag_a_message" : { "message_to_flag" : [ "current-msg" ] } },
            { "drupal_message" : { "message" : "The message with ID [current-msg:mid] (created [current-msg:timestamp]) was marked as read." } }
          ]
        }
      }
    ]
  }
}

```

Some more details about the rule above:

* Rules Event: Drupal is initializing
* Rules Condition: Check if the path being visited is `user/%/messages/unread` (adapt this path to use your path).
* Rules Actions:

+ Create a list of unflagged messages (replace this list by your VBO list).
    + Loop over each of the unflagged messages found, and flag those messages (replace this action by the "execution of certain rules", as in your question).

This rule also performs an extra "set message" action, so that you can see what it does if you want to try it in your own site (it shows a message for each entry in the list). Remove that message after QA-testing if you want.

**That's it, works like a charm!**
> 1 votes

---
Tags: views
---


# Question
Title: Getting data from a view to populate a select drop-down
I am trying to implement a feature of a fancy drop-down select box. I am going to use the Chosen module to get the functionality I want for the select box. I have a view that lists the data that I want to populate the select box. All I need to do is render a plain old HTML select box with the fields and rows from this view.

How can I do this? Is there a style plugin or anything out there? I personally haven't found one after searching.

# Answer
Going off of argiepiano's excellent suggestions, this is what I came up with: a module that provides a block with the select box populated by the view.

```
/**
 * Implements hook_block_info
 */
function my_module_block_info() {

  $blocks['my_module'] = array(
    'info' => t('Puts the values of My Taxonomy Term view into a select box')
  );

  return $blocks;
}

/**
 * Implements hook_block_view
 */
function my_module_block_view( $delta ) {

  $view_name = 'my_taxonomy_term_view';
  $display_name = '';

  $content = '<select>';

  $results = views_get_view_result($view_name, $display_name);

  foreach ( $results as $result ) {
    $content .= '<option value=\'' . $result->tid . '\'>'
      . $result->taxonomy_term_data_name . '</option>';
  }

  $content .= '</select>';

  $block['content'] = $content;

  return $block;
}

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: Overwrite menu.twig only for specific node types
I've worked with twig and have overriden most of elements in my application. However, I it is not clear to me how I can overwrite the menu template for specific node-types. The suggestions I get from the theming debug are too general and not node specific. Any ideas on how to register a twig template for menu for specific node types?

# Answer
> 4 votes
Menus do things a little differently then, so you have an option or two...

```
/**
 * Implementation of hook_theme_suggestions_alter().
 */
function mymodule_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if ($hook == 'menu' && ($node = \Drupal::routeMatch()->getParameter('node'))) {
    $content_type = $node->bundle();
    $suggestions[] = 'menu__node_type__%';
    $suggestions[] = 'menu__node_type__'.$content_type;
  }
}

```

This will give you give you the following suggestion in this order:

* menu--MENU-NAME.html.twig
* menu--node-type--page.html.twig
* menu--node-type--%.html.twig
* menu.html.twig

With this the `menu--MENU-NAME` template still takes preference over the node type, so we need a trick to add suggestions after.

```
/**
 * Implementation of hook_theme_suggestions_HOOK_alter().
 */
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  $key = array_search('menu__'.$variables['menu_name'], $suggestions);
  if ($key !== FALSE && ($node = \Drupal::routeMatch()->getParameter('node'))) {
    $content_type = $node->bundle();
    array_splice($suggestions, ++$key, 0, array('menu__node_type__%', 'menu__node_type__'.$content_type));
  }
}

```
* menu--node-type--page.html.twig
* menu--node-type--%.html.twig
* menu--main.html.twig
* menu.html.twig

Targeting your placement within the array of suggestions can be helpful, but it can be over kill, so you may just want to keep it simple and place your new suggestion at the end of the list and have the highest override

```
/**
 * Implementation of hook_theme_suggestions_HOOK_alter().
 */
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'menu__node_type__%';
    $suggestions[] = 'menu__node_type__'.$content_type;
  }
}

```

You can even throw `$variables['menu_name']` into the mix with:

```
$suggestions[] = 'menu__'.$variables['menu_name'].'__node_type__%';
$suggestions[] = 'menu__'.$variables['menu_name'].'__node_type__'.$content_type;

```

# Answer
> 0 votes
I did not try it myself, but the tip described in https://www.drupal.org/node/2521876 explains how to add a custom suggestion based on the node type, using the hook\_theme\_suggestions\_HOOK\_alter hook:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page__'.$content_type;
  }
}

```

The solution above seems to work for adding page suggestions. You might want to adapt it to add menu suggestions instead, with `THEME_NAME_theme_suggestions_menu_alter` as the function name.

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


# Question
Title: Show all revisions with entity reference field referencing a specific entity
Here is what I am after:

I have an entity reference field that references nodes.

I want to build a view that shows a list of all revisions that have this field referencing a given entity.

Here is what I have tried so far:

New view displaying content revisions. New relationship: `Referenced entity`. New contextual filter `NID` using the relationship.

Now this works, but only returns one result: the *current* node that is referencing the nid argument in the contextual filter. I want it to list all revisions that have historical data referencing the NID in the argument of the contextual filter.

Has anybody built a view that uses a contextual filter to show revisions that reference a given NID by an entityreference field?

# Answer
> 1 votes
So if I am reading this correctly, Content Type A references Content Type B. You want to show all revisions of Type A nodes that reference a certain Type B node.

1. Contextual Filter: `Content: Reference Field for Type B` Provide Default: \___
2. There are two revision relationships.. ID and NID. The one with ID is provided by default. Add the one for NID and for its relationship, choose the one with ID.
3. After it's added, **move it above the ID relationship**. This is vital and I don't even know why..
4. Make sure your Title field doesn't use any relationship.

Now, all revisions that reference Type B will show and be linked properly.

If anyone can explain the significance of reordering the relationships, please post in the comments. I spent far too long working on this a few months ago and a reason would be great!

---
Tags: nodes
---


# Question
Title: How to implement something to differentiate nodes?
I wonder how I could implement something in my Drupal site where nodes can be different and managed separately.

For example, in my site I want to add to nodes as shops, and every vendor must manage his/her shop, post news, add images, etc.

Any suggestions

# Answer
> 1 votes
You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

# Resources

---
Tags: 7, users
---


# Question
Title: How do I programmatically get the field type of a specific field?
I'm able to get a list of the field types with the following code.

```
$defs = \Drupal::service('plugin.manager.field.field_type')->getDefinitions();

```

I want to get the field type of a specific field. How do I get it?

For example, I'd like to check if the field type of field\_image is \_image. Is there code similar to the following one?

```
$fieldType = \Drupal::service('plugin.manager.field.field_type')->getDefinition('field_image');

```

# Answer
With "get the field type of a specific field" you probably mean a specific field of an entity. There can be fields with the same name that have different types in different entities.

For example the field type of a field in a node:

```
$field_type = $node->get($field_name)->getFieldDefinition()->getType();

```

can be different than that of the same field in a comment:

```
$field_type = $comment->get($field_name)->getFieldDefinition()->getType();

```
> 11 votes

---
Tags: entities, 8
---