title: Are there changes to Views functions?

text:
# Question
Title: Are there changes to Views functions?
I am trying to update a old custom module written for Drupal 7 for Drupal 8. I have used a lot of view functions like `views_include()` and `views_get_view()`. Are they all dropped in Drupal 8?

```
function validate_email($email) {
    //pass the email to the filter
    views_include('view');
    $name = 'send_otp';
    $display = 'page_1';
    $alter = array('exposed' =>array('field_email_value' => $email));
    $view = views_get_view($name);
    $view->init_display($display);
    $view->preview=TRUE;
    $view->is_cacheable = FALSE;
    if(isset($alter['exposed'])) {
        foreach($alter['exposed'] as $key => $valor) {
            $view->exposed_input[$key] = $valor;
        }
    }
    $view->pre_execute();
    $output = $view->display_handler->preview();
    $view->post_execute();
    //if the result is empty
    if(empty($view->result)) {
        //return 0
        return 0;
    }
    else {
        //return node id
        return $view->result[0]->nid;
    }
}

```

> Fatal error: Call to undefined function views\_include() in /var/www/html/mdc-conference-backend/sites/all/modules/custom/rest/sendotp.php on line 43

# Answer
> 2 votes
views\_get\_view became Views::getView, and several others are now static methods on the Views class in the views module.

I don't think views\_include is necessary anymore.

---
Tags: views, 8
---


# Question
Title: SQLSTATE[42000]: Syntax error or access violation in drupal views query
When trying to preview a view containing references to three Field Collection module fields, I get the following error:

`SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS node_, node.created AS node_created, 'field_collection_item' AS field_data_fi' at line 1`

Here is the full attempted query:

`SELECT field_collection_item_field_data_field_obit_service.item_id AS field_collection_item_field_data_field_obit_service_item_id, node. AS node_, node.created AS node_created, 'field_collection_item' AS field_data_field_service_location_field_collection_item_enti, 'field_collection_item' AS field_data_field_service_time_field_collection_item_entity_t, '' AS field_data_field_service_type__entity_type
FROM
{node} node
LEFT JOIN {field_data_field_obit_service} field_data_field_obit_service ON node.nid = field_data_field_obit_service.entity_id AND (field_data_field_obit_service.entity_type = 'node' AND field_data_field_obit_service.deleted = '0')
INNER JOIN {field_collection_item} field_collection_item_field_data_field_obit_service ON field_data_field_obit_service.field_obit_service_value = field_collection_item_field_data_field_obit_service.item_id
WHERE (( (node.status = '1') ))
ORDER BY node_created DESC
LIMIT 5 OFFSET 0`

I don't know sql that well, but it appears as though some of the references are being truncated due to length. Also there is a reference to an empty string ('') as a column name. Any idea what's wrong and how to correct it?

# Answer
> 0 votes
Removing the fields and then adding them back resolved the issue, though I'm not sure how.

---
Tags: views, database, blocks, entities
---


# Question
Title: How to create a list of webform submissions for a particular webform
How to create a list of webform submissions for a particular webform. I have multiple Webforms on my site. I want to display list of Webform submissions for a particular webform only. Tried to Use View module but it shows all Webform submissions

# Answer
> 1 votes
To view the submissions for a particular form you can just click the `Results` tab on the webform node, and you will have a list of submissions for that form, or go to `node/1/webform-results` where `1` is the node id.

You can also go to `Administration > Content > Webforms` (`admin/content/webform`) and click the `Submissions` link for the form you want to see the submissions for.

This is for Drupal 7 and Webform 3, but I believe it's more or less the same for the other versions.

# Answer
> 0 votes
**View the list of all the Submissions**

* Login on the site as an Admin.
* From the Admin Menu, click on the Content link(admin/content)
* Click on the Webforms tab.
* It would list you all the Webforms that are there on the site.

* Click on the Submissions link (**node/\[nid\]/webform-results**)

\- Under Operations, we have the option to **Edit**, **View** and **Delete** the result.

Hope this answer help.

---
Tags: views, webforms
---


# Question
Title: 'TwitterException' with message 'Not Found'
Viewing the syslog, I see errors like for the Twitter Module 7.x-5.11

Do you have an idea of how to solve it?

'TwitterException' with message 'Not Found' in /home/superstar/public\_html/sites/all/modules/twitter/twitter.lib.php:164#012Stack trace:#012#0 /home/superstar/public\_html/sites/all/modules/twitter/twitter.lib.php(117): Twitter-\>request('https://api.twi...')#012#1 /home/superstar/public\_html/sites/all/modules/twitter/twitter.lib.php(1248): Twitter-\>auth\_request('https://api.twi...',

# Answer
This looks like it is failing in a portion of the code that has to do with authorization. Just starting with the simplest explanation, are you sure that your credentials/oauth settings are correct?
> 1 votes

---
Tags: social-network
---


title: Make node a revision of another node

text:
# Question
Title: Make node a revision of another node
I have migrated content from a non-Drupal system to a fresh Drupal site. Some of the content nodes however should in fact be revisions of another node, not a unique node of themselves. Is there any quick and easy way to turn a node into a revision of another node?

# Answer
I have not come across such a scenario. However, here's a fairly simple method to achieve it:

1. Install the Entity Reference module
2. Add an Entity Reference field to the content type of this node by navigating to Structure \> Content Type \> \[the content type of these nodes\] \> Manage Fields
3. Choose the Target type as 'Node' & choose the same content type as the 'bundle'
4. Label this field as 'Revision of' (say)
5. Now, you can either choose to manually enter the 'nid' of the original node here or run a query in the database to fill this entity reference field with the nid of the original node.
6. For example, lets say the content type is 'test' & the entity reference field is 'field\_revision\_of'

6.a. Write an insert query like this: insert into 'field\_data\_field\_revision\_of' set entity\_type = 'node',bundle='test',deleted=0,entity\_id = \[nid of revision node\],revision\_id = \[nid of revision node\],language='und',delta=0,field\_revision\_of\_target\_id=\[nid of original node\];

6.b. Since you should also update the database revision table of a field: insert into 'field\_revision\_field\_revision\_of' set entity\_type = 'node',bundle='test',deleted=0,entity\_id = \[nid of revision node\],revision\_id = \[nid of revision node\],language='und',delta=0,field\_revision\_of\_target\_id=\[nid of original node\];

Let me know if this helps.

Regards,

Supriya Rajgopal
> 0 votes

# Answer
I don't know if there is module for that, but it can be done with some custom coding. It is not quick and easy. It is also not a conventional way. You will have to write database queries to update data, which shouldn't be done if you don't know what you do. I won't write the whole code, but I'll outline the steps you need to take to convert a node's data into a revision of an another node.

### Definitions

Let's define the wording for the rest of the answer.

* **Revision node:** A node to be converted into a revision of another node (*target node*).
* **Target node:** A node which will be the current revision of the converted node (*revision node*).
* A *target node* can have multiple *revision nodes*.

### Outline

1. **BACKUP** your database and clear the caches.
2. At very first, you should have a list of node ids of *revision nodes*, and their *target nodes*. You'll need to map them in an array, with keys are the node ids of the *revision nodes*, and the values are the node ids of the *target nodes*.

Let's assume you want that the *revision nodes* `10` and `11` should be revisions of the *target node* `3`, and the *revision node* `12` should be a revision of node `5`. Your mapping array should look like that:

```
$revision_mapping = array(
  10 => 3,
  11 => 3,
  12 => 5,
);

```
3. Having your revision mapping at hand, you should find all `field_data_FIELD_NAME` tables in the database. A query as follows would do the job: `SHOW TABLES LIKE 'field_data_%';`. **Gotcha** if you have a db prefix, you should also bear in mind that in the queries.
4. After getting the field data table names into an array, you will loop through all those tables and query for the *revision nodes*. The query would look like as follows:

```
$field_data = db_select($field_data_table, 'data')
  ->fields('data')
  ->condition('entity_type', 'node')
  ->condition('bundle', 'YOUR_CONTENT_TYPE')
  ->condition('entity_id', array_keys($revision_mapping), 'IN')
  ->execute()
  ->fetchAllAssoc('entity_id', PDO::FETCH_ASSOC);

```
5. After getting the data for a field, you should (in the same loop) change the entity ids of the data into the node id of the *target node* and insert this data into corresponding `field_revision_FIELD_NAME` table.

```
if ($field_data) {
  // Field revision table name from field data table
  $field_revision_table = str_replace('field_data_', 'field_revision_', $field_data_table);

  // Build insert query for field revision table
  $insert_query = db_insert($field_revision_table)
    ->fields(array_keys($field_data[0]));

  foreach ($field_data as $entity_id => $data) {
    // Update entity_id with the target node's node id.
    $data['entity_id'] = $revision_mapping[$entity_id];
    $insert_query->values($data);
  }

  $insert_query->execute();

  // Delete field data from data table
  db_delete($field_data_table)
    ->condition('entity_type', 'node')
    ->condition('bundle', 'YOUR_CONTENT_TYPE')
    ->condition('entity_id', array_keys($field_data), 'IN')
    ->execute();
}

```
6. Update `node_revision` table:

```
foreach ($revision_mapping as $revision => $target) {
  $db_update('node_revision)
     ->fields(array('nid' => $target))
     ->condition('nid', $revision)
     ->execute();

```

### Notes

* Above instructions serve as an outline and takes only the field data into account. If your site has other modules enabled, which may also store the node ids in a separate table, those should also be updated. For example, if you have comments and flag modules enabled, you should consider to update `comment` and `flagging` tables respectively.
* I'd put this code in a `hook_update_N` of a custom module, and use Batch API, since this may a long taking process if there are many nodes to be converted.
* You may consider deleting the *revision nodes* after the update. Or, you can use `node_delete_multiple(array_keys($revision_mapping))`.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to add js in view created by interface
I want to create a new button control in my ip\_geoloc leaflet map. So, i created a view by using the drupal interface -\> /admin/structure/views/view/markers\_admin/edit

And now i want to set a custom JS wich execute only in this view. I've create a module to create custom form. And my goals are when the user click on the button control in the map, a modal pop with a form with lat/lng field to add dynamically the marker on the map.

I searched everything (how to create a modal -\> colorbox, how to create a custom button, how to add the marker...) but i don't know how to attach the javascript to this page.

I've tried to implements these hooks (4th comments) in my custom module but this not work : https://www.drupal.org/node/1993228

Can you help me ?

# Answer
If you are following that 4th comment exactly the problem is probably that it is a hook for viewing a node, not for a 'view'. Ambiguous to be sure.

The accepted answer here should be helpful: How do I add JavaScript specific for a view?.

**EDIT**

Okay, this may be more helpful. The trick here is finding a place to hook in to check to the page before it is rendered to add the javascript to the render array. The assumption this code makes (which may not be accurate) is that you are looking at a views page. If the view is nested in a block or a panels pane this may not work as well. Here goes:

```
/**
 * Implements hook_page_alter().
 */
function food_truck_form_page_alter(&$page) {
  $views_page = views_get_page_view();

  if ($views_page->name == 'marqueurs_admin') {
    $path = drupal_get_path('module', 'food_truck_form' );
    $page['#attached']['js'][] = array(
      'type'=>'file',
      'data' => $path . 'js/food_truck_form.js'
    );
  }
}

```

This also assumes that you are implementing it in a module called food\_truck\_form and your view is named 'marqueurs\_admin'.

Also, as a side-note, it often works better formatting-wise to edit your post to add the additional info there rather than in the comments.
> 0 votes

---
Tags: 7, views, javascript, hooks
---


# Question
Title: Show field label when using tokens in "Global Custom Text" field in Views?
How can I show the field label when using tokens in Global field in Views.

To reproduce:

In a view:

1) Add field: **title-field** and enable to "Create a label" with value "My title".

2) Add field: **Global Custom Text**. In this field I use the token **\[title\_field\]** for the text.

In the result the label is not shown. The token just print out the value but not the label. Even when I checked "Create a label" with value "My title" for the **title-field**

Can I get this? I know that this can be done with the views\_php module but, I don't want to enable this module just to workaround this.

# Answer
A workaround would be to just create your own label by typing it in.

ex 1: `Title: [title_field]`

ex 2: `<b>Title:</b> <br>[title_field]`
> 1 votes

---
Tags: views, entities, tokens
---


# Question
Title: Views is ignoring my field .tpl.php file when the field is used as a replacement pattern in a rewritten field
I've been trying to modify a multiple-values field in a view. I thought I'd found the answer, creating a custom `.tpl.php` file using the naming structures detailed in Views UI's "Theme information" popup.

However, it seems that these `tpl.php` files are only respected when the field is output immediately, and not when it's set to be excluded from the display and then rewritten into another field using a replacement pattern. Views is seeing the file, and uses it if I don't have "exclude" ticked, but if I use a re-write pattern for the field, Views completely ignores the `tpl.php` file.

This happens regardless of whether "Use field template" is ticked for this field in Views UI's field Style Settings.

I almost always aggregate my fields like this to control the HTML output. How can I make Views respect my `tpl.php` file when re-writing the field content into another field?

# Answer
Have you tried using the other method? Using template.php. I don't have time to test this, so consider this as a *possible* answer.

Add the following code to the bottom of your **template.php** file (located in `/sites/all/themes/yourtheme/` folder)

```
function themename_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1"){
        $vars['fields']['field_name']->content = 'hello world';
      }
    }

```
* replace **themename** with your theme name
* replace **view\_name** with your view name
* replace **block\_1** with your machine name
* replace **field\_name** with your field name
> 0 votes

---
Tags: 7, views, entities
---


title: Non visible fields

text:
# Question
Title: Non visible fields
I'm extending a Drupal 7 theme with a new template file to be called by a view.

Here my simple my template file, called views-view--agendas.tpl.php

```
<?php
   // /sites/all/themes/stability/stability_sub/templates/views-view--agenda.tpl.php
   dpm($fields);
   print $fields['field_images']->content;

```

The view is called like it should as I can see the dpm result with all the article fields in it. Here a dpm output extract

```
  ... (Array, 8 elements)
    title (Object) stdClass
    created (Object) stdClass
    path (Object) stdClass
    field_images (Object) stdClass
        handler (Object) views_handler_field_field
        inline (Boolean) FALSE
        element_type (String, 4 characters ) span
        content (String, 187 characters ) <img src="http://mde.local/sites/default/files/...
        raw (String, 3 characters ) 139
        class (String, 12 characters ) field-images
        inline_html (Integer) 0
        wrapper_prefix (String, 0 characters )
        wrapper_suffix (String, 0 characters )
        label (String, 0 characters )
        label_html (String, 0 characters )
    name (Object) stdClass
    comment_count (Object) stdClass
    body (Object) stdClass
    field_event_date (Object) stdClass

```

But for some reason, the second line display nothing.

# Answer
> 0 votes
Did you use render? Try this.

```
<?php print render(content['field_images']); ?>

```

---
Tags: 7, theming
---


# Question
Title: Get created term entity after creating term programatically
I'm writing a custom Drupal Console command to import user data from a text file and create users, and as part of the process, I need to add data to a term reference field. In the case that a term in the data doesn't exist, I need to create the term and then add the new tid to the the field. I'm using the following code to create the term:

```
$term = Term::create([
  'name' => $member[$roster_key],
  'vid' => 'topic_area',
])->save();

```

The problem is the `save()` method only returns a boolean indicating if the save was successful, NOT the created term object. This means that now that my term has been created, I have to go do an entity query just to get the object I just created.

Is there a simple way to get the just-created term in my code above, or do I really have to do a separate query?

# Answer
`Term::create()` returns the entity that the `save()` method gets called on. So what you want to do is save that entity to a var before calling the `save()` method on it.

```
$term = Term::create([
  'name' => $member[$roster_key],
  'vid' => 'topic_area',
]);
$term->save();

//Retrieve the tid of the new term
$term->tid->getValue();

```
> 1 votes

---
Tags: users, 8, taxonomy-terms
---


# Question
Title: User select the filter criteria current_salary_range is 20000. I will show the results also salary range below 20000
I have created the content type named candidate\_profile, included fields like Current\_Salary\_Range.

I have created a view and also I am using better exposed filter for current\_salary\_range field.

My question is: When the user selects the filter criteria current\_salary\_range of 20000, I want to show the results who is having current\_salary\_range 20000 and also who is having current salary range below 20000.

how to proceed with this...?

# Answer
> 1 votes
In your Content type Manage Fields, what you need to do is make the Current\_Salary\_Range **FIELD TYPE** be a (number) **Integer** field and not a text field.

> **Note:** You will have to delete and create a new field, as you cannot change field type after the field has been created

Then when you add it as a filter in your view, you should get the option of **less than or equal to**

**Note:** picture is from Drupal 8, but should be the same in Drupal 7.

---
Tags: views
---


title: Combine 2 content types into view

text:
# Question
Title: Combine 2 content types into view
I am facing trouble with view having 2 content type without relationship.

content type 1: (toys) title, body, series\_taxomony, price

content type 2: (areas) title, area\_name, percentage

I'd like to have a view to display a form like series\_taxonomy and area\_name are exposed to user select from list and show detail

1. serias\_taxonomy
2. price
3. area\_name
4. percentage

In order to complete view, what should i do and is there any way to restructure content type to do easier

Thanks in advance

# Answer
> 0 votes
Well if I am getting you right, for this issue you should do this; Create a new view, and in filters option select type "toys" and again select type "areas", this will give you 2 content types into one view.

For exposed filters, in the filter criteria, select both the fields, "series\_taxonomy" and "area\_name" and select them as exposed filter.

Hope this helps.

---
Tags: views
---


title: Alter drupal 8 views in for each row

text:
# Question
Title: Alter drupal 8 views in for each row
I have a view and I want to alter the output in each row.
So I have tried hook\_views\_pre\_render(), and hook\_preprocess\_views\_view(), but with no luck. In both of the above hooks I got data in `$view->result`, but there seems to be no way to change the rendered output.

# Answer
> 3 votes
After a long a research and development, I came to an conclusion that this could be the answer:

```
foreach ($view->result as $result) {
  $result->_entity->set('field_name', array(0 => 'value'));
}

```

---
Tags: views, 8
---


title: is_flagged with Views

text:
# Question
Title: is_flagged with Views
Is it possible to to check is\_flagged in views ?

If I send POST request to this URL it works fine http://website/rest/flag/is\_flagged but I want do it in Views ?

I am creating REST API using Services Module and what I am trying to check is that whether a Node is flagged by current user or not. /rest/flag/is\_flagged this URL works fine but I want to do it in Views.

If its possible please tell me how I can do it ?

# Answer
> 1 votes
I managed to do it, here are the steps I followed :

1) Add a Relation `Add Relation : Flags: Content flag`

2) While adding above relation Uncheck `Include only flagged content`

3) If you have more then one Flag created, select one for which you want to check.

4) Under "By" select `Current User`

5) Then Add a Field `Flags: Flagged`

6) While adding field select Relationship which you created above in point 1

# Answer
> 1 votes
You could Create a Custom Service Resource for this, but IMO it's easier to do this:

1. Enable the Views JSON module (which is a sub module of the Views datasource module). This will allow you to get JSON output from a View.
2. Build a `JSON data document` **page display** for a View
3. Add a contextual filter for a node id, this value will be grabbed from the URL path
4. Add a contextual filter for a user id, this value could be grabbed from the URL path, or default to the current logged in user, that's up to you
5. Add a relationship to the flag in the View
6. Add your desired field output and watch the results preview to see your JSON assembled
7. Add the necessary filter(s) to limit the results to a certain user/flag/etc.

You then can consume this "resource" by doing a GET on the page path to your View.

---
Tags: views, services, flags
---


# Question
Title: How do I add the tertiary level from the main menu to my skin?
Let's say I have the following menu:

* Smartphones
    + Android
        - LG Nexus 4
        - Samsung Galaxy Note 2
        - HTC One
        - Motorola Droid RAZR MAXX HD
    + iOS
        - iPhone 4
        - iPhone 4S
        - iPhone 5
    + Windows Phone
        - HTC Windows Phone 8X
        - HTC Windows Phone 8S
        - Nokia Lumia 920
        - Nokia Lumia 820

I want a menu that will display all the third level items if I'm on the parent node. So, if I'm on the **Android** page, I should see *LG Nexus 4, Samsung Galaxy Note 2, HTC One, and Motorola Droid RAZR MAXX HD*.

The only recommendation I keep seeing is to use the Menu block module, but I want to just create the menu myself in PHP. How?

# Answer
I figured it out. In **template.php**, I added the following function:

```
function MYTHEME_preprocess_page(&$variables) {
    $active_tree = menu_get_active_trail();
    $parent = array_pop($active_tree);
    if($parent['depth'] == 3) {
        $parent = array_pop($active_tree);
    }

    $parameters = array(
        'active_trail' => array($parent['plid']),
        'only_active_trail' => FALSE,
        'min_depth' => 3,
        'max_depth' => 3,
        'conditions' => array('plid' => $parent['mlid']),
      );

    $tertiary_menu = menu_build_tree($parent['menu_name'], $parameters);

    $links = array();
    foreach($tertiary_menu as $branch=>$link) {
        array_push($links, $link['link']);
    }

    $tertiary_links_vars = array(
        'links' => $links,
        'attributes' => array('class' => array('sub-nav')),
        'heading' => array(
            'text' => t('Tertiary menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
        ),
    );

    $variables['tertiary_menu'] = theme_links($tertiary_links_vars);
}

```

In my **page.tpl.php** file, I added the following:

`<?php print $tertiary_menu; ?>`
> 1 votes

# Answer
I follow cowgod in his solution, although I propose a slight tweak which allows a more flexibel rendering of the menu in the template:

```
function MYTHEME_preprocess_page(&$variables) {
    $active_tree = menu_get_active_trail();
    $parent = array_pop($active_tree);
    if($parent['depth'] == 3) {
        $parent = array_pop($active_tree);
    }

    $parameters = array(
        'active_trail' => array($parent['plid']),
        'only_active_trail' => FALSE,
        'min_depth' => 3,
        'max_depth' => 3,
        'conditions' => array('plid' => $parent['mlid']),
      );

    $tertiary_menu = menu_build_tree($parent['menu_name'], $parameters);

    $links = array();
    foreach($tertiary_menu as $branch=>$link) {
        array_push($links, $link['link']);
    }

    $variables['tertiary_menu'] = $links;
}

```

In **page.tpl.php** , you can then add:

```
<?php
    print theme('links', array(
      'links' => $tertiary_menu,
      'attributes' => array('class' => array('sub-nav')),
      'heading' => array(
        'text' => t('Tertiary menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    );
?>

```

This way, you'll have a more flexible solution.
> 1 votes

---
Tags: 7, routes
---


# Question
Title: Adding 'lang' attribute to language links in template.php
I am not a Drupal developer, but still I would like to know how to make the links in a language switcher HTML5 valid. It seems these links lack an attribute 'lang' (with as value the abbrevation of the language). How would I do that in template.php?

# Answer
I found the solution:

```
function MYTHEME_links__locale_block(&$vars) {

  foreach($vars['links'] as $language => $langInfo) {
    $name = $langInfo['language']->native;
    $lang = $langInfo['language']->language;
    $vars['links'][$language]['title'] = $name;
    $vars['links'][$language]['attributes']['xml:lang'] = $lang;
    $vars['links'][$language]['attributes']['lang'] = $lang;
    $vars['links'][$language]['html'] = TRUE;
  }
  $content = theme_links($vars);
 return $content;
}

```
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Supressing "Undefined variable: variables in module_block_view()" without hiding the notice
I tried to create a simple custom block inside a custom module. there is a notice that inform me about undefined variable, but the block rendered properly. I am not sure where the mistake in the code is, but any nudge in the right direction would be highly appreciated.

I know I can hide the error message by accessing `admin/config/development/logging` or by modules such as Disable Message, but that isn't what I desire since it essentially just hiding the problem under the rug and hiding other notices that I might be interested to look at.

**mymodule.module**

```
<?php
/**
* Declare what blocks are provided by this module
* Implements hook_block_info().
*/

function mymodule_block_info() {
  $block = array();

  $block['myblock1'] = array(
    'info' => t('Block number 1'),
  );

  $block['myblock2'] = array(
    'info' => t('Block number 2'),
  );

  return $block;
}

/**
* Define what our block is going to look like.
* Implements hook_block_view().
*/

function mymodule_block_view($delta='') {
  $block = array();

  switch ($delta) {
    case 'myblock1':
      $block['content'] = theme('myblock1', $variables);
      break;

    case 'myblock2':
      $block['content'] = theme('myblock2', $variables);
      break;
  }

  return $block;
}

/**
* Implementation of hook_theme().
*/

function mymodule_theme() {
  return array(
    'myblock1' => array(
      'variables' => array(),
      'template' => 'templates/block--myblock1',
    ),

    'myblock2' => array(
      'variables' => array(),
      'template' => 'templates/block--myblock2',
    ),
  );
}

?>

```

# Answer
The problem is with `$block['content'] = theme('myblock1', $variables);` and `$block['content'] = theme('myblock2', $variables);`: `mymodule_block_view()` doesn't define any `$variables` variable; just define it or use an array directly.

Since in `mymodule_theme()` you don't define any variable for your theme functions, just replace your `mymodule_block_view()` with the following one.

```
function mymodule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'myblock1':
      $block['content'] = theme('myblock1', array());
      break;

    case 'myblock2':
      $block['content'] = theme('myblock2', array());
      break;
  }

  return $block;
}

```

To make the question more complete: Drupal doesn't define any global `$variables` nor do `hook_block_view()` implementations receive any `$variables` as parameter. Therefore, `$variables` could just be a local variables for your function. That is why you are getting that error: You are using a variable without to first declare it.

Notice that if `$variables` were a global variable, you should still declare it as `global $variables` in your function, or use it as `$GLOBALS['variables']`. (Don't try it since it doesn't work because doesn't define any global variable with that name.)
> 2 votes

---
Tags: 7, blocks, hooks
---


# Question
Title: How to avoid Drupal redirecting my multilingual Views pages?
I've got a Views page in a multilingual website where I need a different url for each language, ie:

* es: mysite/apartamentos.
* en: mysite/appartments.
* fr: mysite/appartements.
* ru: mysite/arendu.

I created an url alias for each language (which is mysite/appartments although the default language of my site is spanish) so the spanish alias for `appartments` is `apartamentos` and so on. I created these aliases using `configuration >> Search and Metadata >> URL aliases >> add alias`.

I have to pass query parameters to the view to filter the results so my url is something like mysite/en/appartments/p/location\_field/2 and I've got a form where I manually put the action like :

`echo "/".$language."/".$translated_page`

where translated page may be apartamentos, appartments, appartements or arendu, making the action url :

/es/apartamentos , /fr/appartements , /en/appartments and /ru/arendu

My problem is that when this form is sent Drupal sends me to

> mysite/es/appartments/p/location\_field/2

instead of

> mysite/es/apartamentos/p/location\_field/2

and the same occurs for all the languages. The rest of the thing seem fine and even the breadcrumb (which is generated using the url) looks correct ( Inicio \>\> Apartamentos Costa Dorada, in Spanish).

When I use the language switch it redirects me to the correct translated page but without the query parameters (from `mysite/es/appartments/p/location_field/2` it sends me to `mysite/es/apartamentos`).

I don't know what can be causing this issue, maybe the query parameters interfering with the alias interpretation?

**Note**: I have a lot of translation modules enabled. For the i18n modules there are: block, field, menu, node, path, string, taxonomy, translation (translation sets), variable and views.

# Answer
> 6 votes
# i18n\_path submodule

I assume you're also using the i18n module. So make sure you also enabled the `i18n_path` submodule (= Path translation). More details about it, from the community documentation (bold markup added here):

> ... allows you to map together existing pages that are translations of each other. This will allow users to use the language switcher to navigate between the associated pages.
>
> The module is meant to be used as a last resort to translate paths that can't otherwise be mapped together as translations. For example, paths to translated nodes can already be linked with the Content translation module and paths to translated taxonomy terms can be linked with the Taxonomy translation module. **Path translations should be used to link generic paths, such as those provided by Views** or Panels.
>
> To set up translations of a particular path, you need to create a path translation set by going to Configuration \> Regional and language \> Translation sets \> Paths and clicking Add path translation.

# i18n page views

You may also want to check if you can get it to work using the i18n page views module. Some details from its project page:

> ... provides a new display of views, where you can select different paths for each language enabled on your site, so a view has a localized route for each language.

**Note 1**: "*if you cannot find any option in the view to translate the path*" (as in your comment below), then you may want to have a look at what's mentioned in Comment #1 of issue 2389535, which states:

> ... May be you have chosen a page display rather than a i18n page display when you created your view. Please be sure that you selected the correct views display. I attach some screenshots for helping:

**Screenprint 1**:

**Screenprint 2**:

**Note 2**: To answer the question about "*Will I have to create the whole view page again to make it as an i18n\_page?*" (as in one of your (now deleted) comments below this answer), I would give it a try using either of the approaches described in the answers to the question at How to duplicate a Views display (which is not the master) as a different display type? ... If that doesn't work / apply, then recreation of the whole view page seems like the only option left.

# Answer
> 3 votes
Remove the path-alias and try coding this special case yourself, using

hook\_url\_inbound\_alter and or hook\_url\_outbound\_alter

> or just do your own paths via custom page callbacks (hook\_menu) and then show the view with views\_embed\_view.

You could also alter the action of the exposed filter's form:

```
/**
 * Implements hook_form_alter().
 */
function foo_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['#action'] = current_path();
  }
}

```

Or:

```
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function foo_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-foo-default') { // Or: if ($form['#action'] === '/foo')
    $form['#action'] = '/bar';
  }
}

```

Taken form here How do I change submit URL for exposed search filter?

---
Tags: 7, views, i18n-l10n, redirection
---


title: Create basic server using Docker

text:
# Question
Title: Create basic server using Docker
I am trying to work out how to create a Drupal dev environment using Docker. I am trying to use the Docker containers for Drupal (https://hub.docker.com/r/library/drupal/) and MySQL (https://hub.docker.com/r/library/mysql/) to set up a Drupal server.

I am assuming that I need to link the MySQL container to the Drupal container. I have created a docker-compose.yml file which seems to run fine on `docker-compose up` (I am using a Mac).

**docker-compose.yml file:**

```
drupal:
  image: drupal
  ports:
   - "8080:80"
  links:
   - db
db:
  image: mysql
  environment:
    MYSQL_ROOT_PASSWORD: mysql
    MYSQL_DATABASE: drupal
    MYSQL_USER: drupal
    MYSQL_PASSWORD: drupal
    MYSQL_ALLOW_EMPTY_PASSWORD: yes

```

After docker-composer completes, I can access the Drupal site from my web browser. The Drupal installation works up to the point where I have to enter the database details. At this point it fails:

# Answer
> 6 votes
Make sure to put in the "Host" of the MySQL database under "Advanced Configuration" as `db` and not the default `localhost`.

# Answer
> 2 votes
When you link containers in docker compose, you still have to reference the database server in your configuration (in this case as 'db'); your database will be on db:3306.

Have a look at an example about doing it with Wordpress.

I suspect you are just not pointing it at the server.

You also set the database user as root, but in your yml that is drupal (which might be another issue).

# Answer
> 1 votes
**1. To get all container names and their ips in just one single command.**

```
docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress }}' $(docker ps -aq)

```

**Output:**
/drupal7\_drupal\_1 - 172.17.0.3
/drupal7\_db\_1 - 172.17.0.2
**2. Set up Database:
** Database name: drupal
Database username: drupal
Database password: drupal
Host: 172.17.0.2
**docker-compose.yml
**

```
drupal:
  image: drupal
  ports:
   - "8080:80"
  links:
   - db
db:
  image: mysql
  environment:
    MYSQL_ROOT_PASSWORD: drupal
    MYSQL_DATABASE: drupal
    MYSQL_PORT: 3306
    MYSQL_USER: drupal
    MYSQL_PASSWORD: drupal

```

# Answer
> 1 votes
I've been working on a dev env for Drupal specifically using Docker and recently open sourced the BETA version with the intention to help others as well as streamline my dev setup : https://www.4alldigital.io/docker-drupal

Supposed to be a single command install and away you go. would love feedback if it helps or hinders... and how it can better server Drupal devs who wanna spend less time on local devOps

---
Tags: 7
---


# Question
Title: How to organise content using public, private and semi-private groups?
I'm building a community website with Drupal Commons and I need to be able to create 3 kinds of groups:

* public groups : anyone can view content, group members only can post/edit/delete content
* private groups : group members only can view/post/edit/delete content
* semi-private groups : authenticated users can view content, group members only can post/edit/delete content

How can I achieve this?

# Answer
> 0 votes
The Group module 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 this specific question, you'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

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

# Resources

---
Tags: 7
---


# Question
Title: External javascript that contains jQuery
I have been asked to include an external js file into a site where I don't have direct access to modify it and the generated script has jQuery it that references $.

Is it possible to include this without modifying the source js file?

I've added it as below

```
drupal_add_js("www.domain.com/my.js", array(
      'type' => 'external',
      'scope' => 'header',
      'group' => JS_LIBRARY,
      'every_page' => TRUE,
      'weight' => -1,
    ));

```

But I get undefined errors due to the use of $

Cheers

# Answer
One way to circumvent this would be by installing the jQuery Dollar module.

This would allow you to avoid $ conflicts.
> 1 votes

---
Tags: javascript
---


title: How do I Convert time/date format?

text:
# Question
Title: How do I Convert time/date format?
I have created a View and added a filed Date. This Field have 4 type of Formatter

1) Date and Time 2) Time Ago 3) plain 4) Services Raw

If I select First it give HTML tags in output and if select 3rd or 4th it give output like these numbers "1439393400"

I need the simple date in output without any HTML tags. Please tell me how I can get rid of HTML tags if I select first option. If its not possible then how I can convert the output which I get from Plain Formatter so that I get simple date not these number.

# Answer
For creating a new date format to be used in views:-

Go to `yoursite.com/admin/config/regional/date-time` And create the new format.

Now, Go to the view you're working on, add date field, change its format. Yes, it's as simple as that.

Plus: You can use Date module, it has got amazing features.
> 1 votes

# Answer
In Drupal 7, when editing the view, you can click on the 'Advanced' link which will bring up a list of more advanced options for that view. There will be a 'Theme Information' link in that list that when clicked, will inform you of all the various template files that are being used and that can be created to override output from the view.

You can get as granular as the output of the field data itself by creating the recommended field level tpl.php file and performing the modifications you'd like for output.
> 0 votes

# Answer
**Steps to get the just the year for Delivery Date field**

* Navigate to /admin/config/regional/date-time/formats page.
* Click on Add Format button (/admin/config/regional/date-time/formats/add)
* In the Format string text field add Y and save it.
* Now add a date type by navigating to /admin/config/regional/date-time page.
* Add a new date type and use the the format that we have added in the previous steps.
* In the view select the type you want the date to be rendered.

So instead of **Rewriting the output**, you would directly get the year.

Hope that this will help you.
> 0 votes

# Answer
For date format, select **Custom**

For custom date format, if you put

`d/m/y` will result in 23/04/16

`M j, Y` will result in April 23, 2016

etc.. see the php date manual for all replacement characters

---

> Please tell me how I can get rid of HTML tags if I select first option

**If you're referring to div wrappers**
> 0 votes

---
Tags: 7, views
---


# Question
Title: Is it important to assign CSS injector and JS injector code snippets to specific pages instead of site wide?
**Is it important to assign CSS injector and JS injector code snippets to specific pages instead of site wide?**

If the code is a few lines, is there a REAL performance benefit to assign css and JS to only some pages?

Or does it only matter for very large code?

I'm just wondering if it's over kill to target the specific pages all the time?

An example code snippet combo I'm using is the first word for JS

```
$('p').each(function() {
var word = $(this).html();
var index = word.indexOf(' ');
if(index == -1) {
    index = word.length;
}
$(this).html('<span class="first-word">' + word.substring(0, index) +    '</span>' + word.substring(index, word.length));
});

```

And CSS:

```
.first-word { font-style:italic; }

```

So less than 10 lines of code...

# Answer
> 0 votes
For those amount of lines, it's no biggie, specially if you're caching, as those lines gets cached as HTML.

An alternative, the good practice, would be to add the css to your theme's **style.css** file and the JS to your **theme.info** file. That way you can aggregate and compress them along with your other files.

Aggregating and compressing makes a huge difference. You should do that if you aren't already. (speaking of all your css and js files).

---
Tags: theming
---


title: Risks to set permissions 777

text:
# Question
Title: Risks to set permissions 777
I set permissions 777 to **/www/sites/default/files** folder and all subfolders. I did this because Drupal 7 would not let me save content. Drupal said me: *The specified file temporary: //filetXbwF7 could not be copied, because the destination directory is not configured correctly*.

Originally, these folders have the permission 755. But that did not work.

What risks are there to set permissions 777?

Thanks in advance!

# Answer
Some things you should check:

* Check if the owner of the `sites/default/files` is the proper user and groups. The user and group usually is `www-data`, but it depends on your webserver.
* Since you mention temporary folder, you should check if the temporary directory at `admin/config/media/file-system` section of administrator interface is configured properly.

> What risks are there to set permissions 777?

It is a *very* ***very*** bad practice. There are tons of materials on the net you can look at, but long story short: Setting the permission to `777` means that anyone can write *and* execute anything in that folder, including malicious codes.
> 1 votes

---
Tags: files
---


# Question
Title: How can I programatically prevent users from saving the same entity twice in a row?
My server sometimes gets overloaded, and sometimes people press the "Save" button on an entity creation page several times, which results in multiple versions of the same entity being created.

So, I want to prevent users from saving the same entity (an entity that has the exact same field content as the immediately previous entity saved by the user).

One fix is to get a better server. I'm working on that.

Still, I would like to programmatically prevent users from saving the exact same entity twice in a row. In my specific use case, this entity is a new private message from the Private Message module.

Is there a "best practice" way to do this?

Here is what I have considered.

* On `hook_entity_presave()`, query the database and check if the last entity saved by the user had the same values.
* Add an entity reference to the user profile for the last saved entity, and update the user profile entity reference field with the value of the new entity every time it is saved. When saving a new entity, check it against the values of the entity reference entity.

# Answer
I find this to be a UX issue. 1 thing I would recommend is to allow certain high-traffic forms on your site to show a throbbing/progress/submit indicator upon click.

I believe you can do this using the Form API by overridding the default submit element on your site forms as needed. This is explained some in this related SO post with links to documentation: https://stackoverflow.com/questions/6100970/how-do-you-remove-the-throbber-from-drupal-7-ajax-link
> 3 votes

# Answer
You can use jQuery to change the save button to a loading gif when the save button is clicked. Thus, preventing any more clicks.

```
(function($) {
  $('.form-submit').click(function() {
     $('.form-submit').html('<img src="https://media.giphy.com/media/TtZqlvHid7BjW/giphy.gif">');
  });
})(jQuery);

```

JS Fiddle Example

When you edit nodes it uses the admin theme (seven), so you need to add the jQuery to the admin theme (seven).

Now I don't know if private message uses the admin theme. So you will have to check that. My guess it that it does, but if it doesn't, then you add the jQuery to your theme rather than the admin theme (seven)

> **Note:** The default **admin theme** for Drupal 7 is "Seven", if you have changed your admin theme, then just edit that theme instead.
> 2 votes

# Answer
This seems to be a classic question in the drupal world, did you search already for similar posts?

Here is what my research provided:

This is a two-fold issue, you can start by working on the Client-Side, but to avoid duplicates, you should ultimately work on the Server-Side. Here are what I found to be the "best practice" ways to go about this problem.

**Client-Side:**

Client-side solution: https://www.drupal.org/project/hide\_submit

*But what if the javascript is not there?*

**Server-Side:**

Closer to the direction you started out with:

https://drupal.stackexchange.com/a/152181/57183

I would apply both approaches, starting with the "Server-Side" approach.

Good luck!
> 1 votes

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


title: Advanced Forum Error When Posting

text:
# Question
Title: Advanced Forum Error When Posting
I have updated today to the latest version of Advanced Forum and when trying to post a new topic got the following error:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '329-node' for key 'PRIMARY': INSERT INTO {ip_posts} (type, id, ip) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 329 [:db_insert_placeholder_2] => 38932973 ) in ip_posts_insert() (line 162 of /home/thanatos/public_html/sites/all/modules/ip-7.x-1.4/ip/ip.module).

```

Could this be related to php timeout? I'm asking this because I took quite a while typing the Topic before posting it, because I was working it in HTML in Dreamweaver. However when I went back and created a new topic and posted it instantly, I had no issues.

Thanks in advance.

Miguel

# Answer
The error has nothing to do with the Advanced Forum module, the error is coming from the IP address manager module. From it's error message, it looks like it's trying to insert a record that already exists. It could be a problem with how you upgraded that module (your dir suggests its version 1.4, but the line number matches the latest 2.0-beta) or it could be a bug.

Either way, if you're not concerned with preserving historical data in the module, uninstalling, removing, and reinstalling the IP address manager module would be one way to get rid of the error.
> 0 votes

---
Tags: nodes
---


# Question
Title: Why is a new post not shown in the Latest Topics Block after updating Advanced Forum?
I updated the version of the Advanced Forum module today. I posted a new topic and now it doesn't show on a block I have in the side bar where latest created topics always used to show up.

What can be happening?

# Answer
Some problems get resolved just by being patient for a while. Some of those problems are caused by either of the following:

* You should have cleared the cache.
* Something required a cron job to run.

If such kinds of actions are not performed (eg because you're not aware they are needed), it is just a matter of time to get such problems resolved automagically ... as illustrated in this specific comment (last paragraph) also.
> 0 votes

---
Tags: blocks, nodes
---


# Question
Title: How do I get a double top boostrap nav with bootstrap template?
I want a secondary bootstrap navbar on my site, a black one on top of the blue one.

Now when resizing, there is a hamburger menu and so on, so stacking 2 bootstrap menus on top of each other, even of different colors may cause problems.

How do I have a double bootstrap menu with 2 colors?

>

# Answer
> 1 votes
You can create a region in yourtheme.info or use *Block Group* Module. If you're using Bootstrap theme for Drupal, you can simply write code for your *Top Links* Navbar in page.tpl.php and use CSS to design it as you wish. Now in the template code, include your navbar if not empty:

```
if (!empty(primary_nav)||!empty(top_links)||!empty(user_nav)||!empty(navigation))
{ //..Code to include your top_links navbar .. /}

```

You can also hard-code your menu in page template of your theme but it's not the best practice.

Plus: Always use the child theme.

If you want to add hamburger menu then use JQuery pluggin for same and remove the default responsive behavior of bootstrap from the menu you want to display hamburger on smaller screen. I advice JQuery plugin as it's open source, clean and very beautiful.

Play here.

---
Tags: 7, theming
---


title: Query - Content type

text:
# Question
Title: Query - Content type
I want to get all created content of some content type by query. By now I can access nodes by their ID.

`$MyNode = \Drupal\node\Entity\Node::load(1)`

I tried some query, but none of them worked for me. Maybe wrong conditions. My content type is 'beacons'.

```
$query = \Drupal::entityQuery('node')

```

Cant find it in my d8 book too.

# Answer
> 3 votes
The following should suffice:

```
$query = \Drupal::entityQuery('node')
  ->condition('type', 'beacons');
$entity_ids = $query->execute();

```

Here is a drush one-liner to test this on my D8 instance, where I have one article node:

```
 drush ev "var_dump(\\Drupal::entityQuery('node')->condition('type','article')->execute());"

```

Gives me:

```
array(1) {
  [101]=>
  string(3) "101"
}

```

where 101 is the nid of the article node.

Good luck!

---
Tags: database, 8, entities
---


# Question
Title: How to set value for multivalue field in drupal 8 programmatically
I was saving poll choices Programmatically in Drupal 8. I have used Drupal8 Poll choices module.

```
$node_poll = Poll::load($pollid);
//print_r($node_poll);exit;
$i = array(13,14,15);
foreach($i as $key => $value){
  $node_poll->choice->setValue(
        [
            ['target_id' => $value]
        ]
  );
// But I want to save multiple target ids. now this is saving 15 all the time.

}
$node_poll->question->setValue([
  'value' => 'test',
]);
$node_poll->save();

```

The following snippet is working fine.

```
$node_poll->choice->setValue(
        [
            ['target_id' => 13]
       ],
       [
            ['target_id' => 14]
       ],
        [
            ['target_id' => 15]
       ]
    );

```

How can I, make target ids to be saved dynamically?

# Answer
> 26 votes
I would rewrite your code like this.
N.B.: This an edited version of the original answer, following some helpful points coming from the comments.

```
$poll = Poll::load($pollid);

$poll->question->setValue(['value' => 'test']);

$target_ids = array(13,14,15);
foreach($target_ids as $target_id){
  $poll->choice->appendItem($target_id);
}
$poll->save();

```

Hope this does it!

# Answer
> 10 votes
You can work with multi value fields like an array. The field interface will translate this to store it in the database. To simplify it even more:

```
$target_ids = array(13,14,15);
$node_poll = Poll::load($pollid);
foreach($target_ids as $target_id) {
  $node_poll->choice[] = $target_id;
}
$node_poll->question->value = 'test';
$node_poll->save();

```

This will add the id's to the field, not overwrite the existing ones. If you want to do this, you can set an empty array at the beginning.

---
Tags: 8, polls
---


title: Global view footer not replacing tokens

text:
# Question
Title: Global view footer not replacing tokens
I am having a problem with token replacement in a views footer. I added a "Global: Unfiltered text" footer, and checked "Use replacement patterns", and added `[title]`. However, it shows up as the literal string `[title]` on the view, not the title from the first row.

Here's the footer I've created:

And here's the view preview:

And here's the actual view, where we should see "Sample Article" instead of "\[title\]". Note that "Sample Article" is the title of an article node, so there is one record showing in this view:

I can't tell what I've done wrong. FWIW, I put an export of the view here.

How can I get the tokens to render properly in my view footer?

# Answer
> 1 votes
I did use the link you provided and noticed that you are not using fields.

> The selected style or row format does not utilize fields.

Now, if you simply select the "Force using fields" in your "Unformatted List" \>\> "Settings" panel, you will get this to work.

Cheers!

# Answer
> 1 votes
I can't tell from the examples provided ... but if a View has no results from the database, then tokens are not replaced.

---
Tags: views, tokens
---


# Question
Title: Modify metatag description programmatically Drupal 8
I modified the meta-tag title for a view in `hook_preprocess_html()` using the following code.

```
if (isset($variables['head_title'])) {
    $variables['head_title'] = $variables['page']['#title'] . " | My web";
}

```

Is it possible to modify the description in the same hook?

# Answer
That depends on your theme and its use of $variables in combination with the description meta tag.

A code snippet for Drupal 8 that does what you want for the Bartik Theme would be the following:

```
function bartik_page_attachments_alter(array &$page) {
  $description = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'description',
      'content' => 'your description content',
    ),
  );
  $page['#attached']['html_head'][] = [$description, 'description'];
}

```

This was inspired by this post =\> https://drupal.stackexchange.com/a/134145/57183

Maybe this does solve your problem!
> 3 votes

---
Tags: views, meta-tags
---


title: Add content links for Organic Groups

text:
# Question
Title: Add content links for Organic Groups
I'm using OG and OG Extra to make some kind of community website.. but unfortunately I don't see the group content block even when I added it to a region. . Please what could be the solution for that and is there any alternative Here's images from my configuration:

# Answer
Make sure you also install the eva module, in addition to clearing your caches via admin/config/development/performance.

Also, og\_extras only works with og 7.x-2.\*.

For the "create content" block, look for "Node content links" under blocks. You also need to configure the *Organic Group* module to work with the entityreference\_prepopulate module, to make it work properly. See here for guidance.
> 1 votes

---
Tags: blocks, organic-groups
---


# Question
Title: How to hide empty blocks supplied by the User Relationship module?
I am trying to hide a module supplied block (User Relationships action block) from appearing on nodes posted by the logged in user. The block shows as **empty** on those pages.

I have tried php in the block visibility rule, I have tried the Context module, I have tried a template, to no avail except that with a template the block no longer shows anywhere regardless of the template having code inside it or not.

Otherwise, the visibility rules work if I limit visibility to specific paths.

It also looks like I am having problems hiding other module supplied blocks like the search block.

Interestingly enough, when I enable the Devel Themer module, the action block no longer shows on posts by the logged in user as it should but appears on others (this is the result I am trying to achieve.) Unfortunately, this module has other serious issues and I cannot leave it enabled permanently.

Combined with the fact that I haven't found any other complaint about this situation, this leads me to believe that the UR action block, by design, should not appear on the logged in user's posts and that I should not be facing this problem.

Does this mean I have a broken database somewhere?

Can anyone guide me on the diagnosis and possible repair of this situation --like, maybe, going into the database for a manual fix?

P.S.: In the database, the action block shows a size of NULL and a sort of NULL. Is this normal?

# Answer
# Rules block visibility

Have a look at the Rules block visibility module. Here is a quote from its project page:

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

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules check situations such as "***is this a node posted by the logged in user***" (so that the block is not to be shown).

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

# Advanced debugging options

To futher investigate the "*The website encountered an unexpected error, please try again later*" (as in your comment to this answer), keep in mind that such errors originate from some PHP exception that occured somewhere. To get more details about such error, check your 'Recent log messages' (within "Reports", located at `/admin/reports/dblog`), which is available if the ***Database logging*** module is enabled.
> 1 votes

---
Tags: 7, blocks, users
---


title: A error creating filter - filter tips

text:
# Question
Title: A error creating filter - filter tips
I want to create a filter text module for drupal 8.

### emtfilter/src/Plugin/Filter/emtfilter.php

```
/**
 * @file
 * Contains \Drupal\emtfilter\Plugin\Filter\emtfilter.
 */

namespace Drupal\emtfilter\Plugin\Filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Text filter for highlighting PHP source code.
 *
 * @Filter(
 *   id = "emtfilter",
 *   module = "emtfilter",
 *   title = @Translation("Tipograf"),
 *   description = @Translation("Tipograf"),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_HTML_RESTRICTOR,
 * )
 */
class emtfilter extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function tips($long = FALSE) {
    if ($long) {
      return t('text1r-');
    }
    else {
      return t('text2r-');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
        return new FilterProcessResult($text);
  }
}

```

After clearing cashe everything is ok. But when I visit some forms with textfields second time, Drupal generates this error:

> Notice: `_filter_tips()`: The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "Drupal\emtfilter\Plugin\Filter\emtfilter" of the object you are trying to operate on was loaded *before* `unserialize()` gets called or provide a `__autoload()` function to load the class definition in `_filter_tips()` (line 350 of core/modules/filter/filter.module).
> `_filter_tips('full_html', )` (Line: 378)
> `template_preprocess_filter_guidelines(Array, 'filter_guidelines', Array)` (Line: 293)

And my tips disappear. What am I do wrong?

# Answer
I made a mistake in the letter case in the class file (`emtFilter.php` -\> `emtfilter.php`)
> 0 votes

---
Tags: 8, input-formats
---


# Question
Title: How do I add a Javascript library to a field formatter?
I'm trying to include a Javascript gallery (jQuery lightGallery) on my new Drupal 8 site and wrote a field formatter for this purpose.

Now I need to add the jQuery lightGallery to pages using this field formatter and call the library when the page is ready. I am confused about how I am supposed to do this, though.

I defined the library in the module containing my field formatter, but I'm not sure how I attach it only on sites that contain the field.

The documentation of the library uses the jQuery `$(document).ready` function to call the libary, how would that work inside a Drupal module?

# Answer
> 6 votes
So for Drupal 8, in order to add JS or CSS files you first needs to defined a library that defines which files should be include. You need to create a *module\_name.libraries.yml* file. That file could look something like this:

```
library_name:
  js:
    js/path.to.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

```

There is documentation about the libraries files. Basically you list the files you want to include (along with some optional settings) and add depencies to other libraries that your library depend on if any (like jQuery).

After your library has been defined (remember to clear cache), you should add the library where needed. In your case that would be the form definition. You can add the library to any render array and Drupal will find them and add the needed js files to the page.

To add a library all you need to do this:

```
$render_array['#attached']['library'][] = 'module_name/library_name';

```

This can be done anywhere in the render array.

There is detailed documentation about this on Drupal.org documetation area.

# Answer
> 12 votes
In your formatter's viewElements

```
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
  $elements[$delta] = array(
    '#theme' => 'theme_name_if_any',
    '#variablenametobepassed' => $this->viewValue($item) * 20, // any other preprocessing
    '#attached' => array('library'=> array('module_name/library_name')),
  );
}

return $elements;
}

```

---
Tags: javascript, 8, entities
---


# Question
Title: How would I store a reference in a custom FieldType in Drupal 8?
I am developing a module for Drupal 8 and want to make a field on one entity that references another along with some additional data. e.g. Library A has a copy of Book B (of Edition 2). There will be multiple values stored in the field for each source entity. In the above example Libraries will have multiple books.

I know how to implement a new FieldType and the widget and formatter for it, but I am wondering whether this is the best way for a reference. Would it be better to create a new entity to hold the relationship with the two endpoints and additional data (like I would create an xref table in MySQL)

If I do go with a FieldType, when it comes to implementing the storage of the new field, would I just store the id of the referenced entity and then have to wrap the access in a method to change id \<-\> entity?

Thanks in advance for your help! Jamie

# Answer
> 5 votes
So you're actually asking two questions.

1. Should I use a field type or a relation?

Both works. Field type requires much less storage (everything is in the field table), but it's hardcoded to one specific use case. The alternative is basically https://www.drupal.org/project/relation or you could also use something like https://www.drupal.org/project/paragraphs, https://www.drupal.org/project/field\_collection if you only have a source -\> target reference (relation can to n-n references). For all, you'd create a relation/paragraph/collection type with your additional fields. More flexible, can be configured and doesn't require custom code, but each reference is another entity that has to be stored and loaded.

You will have to decide what's better for your case, depends on performance vs. flexibility requirements, how many variations (you probably don't want to create 10 field types..) and so on.

2. If a field type, how do I create it.

That's actually fairly easy in Drupal 8. You just extend from the default entity reference field type (EntityReferenceItem), override methods like schema() and propertyDefinitions() to define what properties you have and how they are stored. Then you write a widget and formatter for it, extending from the widget/formatter that's closest to what you want (e.g. autocomplete or select for the reference selection).

The advantage is, all the actual reference things will just work through the parent classes, you just have to implement your additional properties.

---
Tags: entities, 8
---


title: How do I address the checkout button?

text:
# Question
Title: How do I address the checkout button?
I need to add a custom function to the *Confirm Order* button on a Commerce Checkout form. I can't figure out how to call it. The button ID is *#edit-continue* and its displayed text is *Confirm Order*. I thought this would show up in the `$form[submit]` array, but that array is empty. So I checked `$form['buttons']['continue']['#submit']`, which seems to be where Drupal Commerce stores the submit functions.

I created a module and two functions.

```
function MYMODULE_form_commerce_checkout_form_checkout_alter($form, $form_state, $form_id){
   drupal_set_message('ALTERING CHECKING OUT! THIS WORKS' . $form_id);
   $form['buttons']['continue']['#value'] = 'Send Me A Quote!';
   $form['buttons']['continue']['#submit'][] = 'MYMODULE_submit';

function MYMODULE_submit_function($form, &$form_state) {
  die('Triggered submit');
}

```

`drupal_set_message()` shows the message, but the submit function isn't invoked, and the text in the button is not altered. So clearly, the problem is that I am not targeting the button properly. How do I "address" that button?

To make it clearer, I need to overload that button, not replace the commerce checkout functionality.

PS: I have no access to the console or Devel. So I'm limited to debugging with `var_dump().`

# Answer
Your changes to $form here are lost because you are passing by value. Pass by reference using `&$form` instead:

```
function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {

```
> 1 votes

# Answer
You must be using hook form alter so do a dpm($form) before adding the custom function to the submit handler and then do dpm($form) again after adding your custom handler and see if it shows your custom handler over there or not. dpm() will work if you have devel module installed otherwise do a var\_dump() instead of dpm(), debugging the code should take you to the answer.
> 0 votes

# Answer
Based solely on the code you gave above, you've got at least one glaring issue. This code is okay:

```
function MYMODULE_form_commerce_checkout_form_checkout_alter($form, $form_state, $form_id){
   drupal_set_message('ALTERING CHECKING OUT! THIS WORKS' . $form_id);
   $form['buttons']['continue']['#value'] = 'Send Me A Quote!';
   $form['buttons']['continue']['#submit'][] = 'MYMODULE_submit';

```

However, in this block:

```
function MYMODULE_submit_function($form, &$form_state) {
  die('Triggered submit');
}

```

`MYMODULE_submit_function` should actually be the same as the handler you added in the form alter (i.e. `MYMODULE_submit` without the `_function`).

It's looking for that exact function name and won't add anything else to it like it does with the other form submit handlers that are called in `drupal_get_form()`.
> 0 votes

---
Tags: commerce, forms
---


title: Help with this rule

text:
# Question
Title: Help with this rule
How can I do this rule:

Before adding a product to the cart:

if there is a product in the cart with the same title name plus a character "-". then set the price of the product with the name ending in "-" to 0 euros.

# Answer
If a customer adds "Y-" (costing $5) to the cart and then adds a "Y" (costing, say, $6) to the cart, then set the price of "Y-" to ($0).

You'll need to use the `Calculating the sell price of a product` event since that's actually what you're doing and you're actually calculating the sell price of the "Y-" product and not of the "Y" product. When dealing with Rules, it's important to make these distinctions.

Anyway, what you'll then need to do is create a few custom conditions (which you can do using rules). It's a bit long to review over here but the logic is roughly the same to the answer in this question: Exclude Items from Flat Rate Shipping Calculation.

The differences are that:

* Instead of testing for an amount, you're testing to see if a product is in the cart, so it's a boolean.
* You're not setting free shipping, you're setting the price of the product.
* You're comparing the title based on some arbitrary string (title + '-').
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: Hidden form values updated with multiple submission
I'm writing a backend validation function to prevent multiple submission for comments by logged in users in Drupal. Following is my code:

```
function MYMODULE_form_comment_form_alter( &$form, &$form_state, $form_id ) {
        if( user_is_logged_in() ) {
          $unique_bytes = openssl_random_pseudo_bytes( 8 );
          $unique_id = bin2hex( $unique_bytes );
          $session_key = 'comment_form_token_' . $form['form_id']['#id'];
          $_SESSION[$session_key] = $unique_id;
          $form['one_time_token'] = array(
              '#type' => 'hidden',
              '#value' => $unique_id,
          );
          $form['#validate'][] = '_MYMODULE_comments_validate_one_time_token';
        }
}
function _MYMODULE_comments_validate_one_time_token( $form, &$form_state ) {
  if( user_is_logged_in() ) {
    $form_id = $form['form_id']['#id'];
    $session_key = 'comment_form_token_' . $form_id;
    $one_time_token = $form_state['values']['one_time_token'];
    if( isset( $_SESSION[$session_key] ) && $_SESSION[$session_key] === $one_time_token ) {
      unset( $_SESSION[$session_key] );
    }
    else {
      form_set_error( 'comment_body', t( 'Please make sure that you have submitted this form only once.' ) );
    }
  }
}

```

The problem is that when the user submits the form multiple times by clicking the Submit button extremely fast, the one\_time\_token field's value gets updated automatically rather than submitting the original value.

To elaborate further, if my initial field value on form load was e8ac1824bf894e12, session value for that was also e8ac1824bf894e12 and submitted value was also e8ac1824bf894e12. But on processing second submission, my session value is 153695ec028bf151 but I expect my submitted values to stay e8ac1824bf894e12 but somehow that also changes to 153695ec028bf151.

Is there a way I can prevent that?

# Answer
You can use jQuery to change the submit button to a loading gif when the save button is clicked. Thus, preventing any more clicks.

```
(function($) {
  $('.form-submit').click(function() {
     $('.form-submit').html('<img src="https://media.giphy.com/media/TtZqlvHid7BjW/giphy.gif">');
  });
})(jQuery);

```

JS Fiddle Example
> 1 votes

---
Tags: comments, forms
---


# Question
Title: How do I use an OR condition in an exposed filter?
I have a view with more than 10 checkboxes for the multiple selection in exposed form with some field. Using the Drupal exposed filter for the multiple fields make the query of AND, but somehow I need the multiple selections in OR condition.

Is there any way to change the query to use a OR condition?

# Answer
> 2 votes
You can make view filter with OR condition by clicking on **And/Or, Rearrange** link.

# Answer
> 0 votes
Sometimes we use Drupal `view_query_alter` to add or modify the view's where clause. To add a new WHERE clause we may use `add_where` property. Whenever we use an a`dd_where`, it will create a WHERE clause along with an AND condition. There will be some cases were we need to use OR instead of AND. So if you want to know more about how to use OR clause in `hook_view_query_alter`, read on to know more.

We can use `db_or` to add a new OR condition with `add_where`. For example see the sample code

```
function mymodule_views_query_alter(&$view, &$query) {
  if ('yourviewname' == $view->name && 'page' == $view->current_display) {
    $weight_parent = array(29,31);
    $or = db_or()
    ->condition('taxonomy_term_data_taxonomy_term_hierarchy.weight', 'NULL', 'IS')
    ->condition('taxonomy_term_data_node.weight', $weight_parent, 'IN');
    $query->add_where(1,$or);
  }
}

```

---
Tags: views
---


# Question
Title: Custom block created with GUI stripping some <a> tags, not all of them
I am creating a custom block in D8; the block includes the following HTML:

```
<div class="header__action-items">
  <a class="btn btn-large" href="help">Donate Now</a>
  <a class="btn btn-large" href="me">Connect With Us</a>
  <a class="nav-toggle nav-toggle-menu icon-menu" href="#nav">Menu</a>
</div>

```

I have saved the block using the Full HTML format and placed it into the header region, here is a screenshot of what is added to the page:

I have disabled JS and re-loaded the page to make sure nothing else was happening. Here is a screenshot of the edit screen:

# Answer
> 0 votes
There was a similar question recently and the problem was CKEditor, could be the same here.

If you want to be sure that your markup is not altered in any way, create a text format without ckeditor and use that.

---
Tags: 8, blocks
---


# Question
Title: Insert multiple checkbox value from webform into table
I created:

* a webform named **Test Number checkboxes**
* checkboxes named **Number** with values **one**, **two** and **three** using Form Builder
* a table named **checkbox\_check**

**Aim**: When the webform is submitted, the values selected are placed in a string and saved into the table. Example: **If "one" and "two" are selected** from the checkboxes, they will be **saved like "one,two"** in the table when the webform is submitted.

The table name is **checkbox\_check** with field **Number** (Vachar 11)

**EDITED**: I just added these codes within the **function webform\_webform\_submission\_insert($node, $submission)** from the webform.module file in my drupal project:

```
$accessnode=$node->nid;
if($accessnode==11)// the **Test Number checkboxes** webform containing the checkboxes
{
    $lastestSub=db_query("SELECT MAX(sid) FROM {webform_submitted_data}")->fetchField(); //retrieving the highest number of sid which is the lastest submission
    $selectedData=db_query("SELECT data FROM {webform_submitted_data} WHERE nid = :nid AND cid =:cid AND sid= :sid",array(':nid'=>$accessnode, ':cid' => 1, 'sid'=>$lastestSub))->fetchAll();

    $text='';// This will be used to concatenate the different values into a string and placed in the table afterwards
    foreach($selectedData as $valD)
    {
            $text=$text.$valD.",";
    }
        db_insert('checkbox_check')
        ->fields(array(

        'Number' => $text,
        ))
        ->execute();

}

```

When I submitted the webform, I got this error message:

Can you guys help me with this?

# Answer
It works if I replace these codes:

```
$selectedData=db_query("SELECT data FROM {webform_submitted_data} WHERE nid = :nid AND cid =:cid AND sid= :sid",array(':nid'=>$accessnode, ':cid' => 1, 'sid'=>$lastestSub))->fetchAll();

```

by this:

```
$selectedData=db_query("SELECT data FROM {webform_submitted_data} WHERE nid = :nid AND cid =:cid AND sid= :sid",array(':nid'=>$accessnode, ':cid' => 1, 'sid'=>$lastestSub))->fetchCol();

```
> 0 votes

---
Tags: 7, database, webforms
---


title: Installing drush for use with Drupal 8

text:
# Question
Title: Installing drush for use with Drupal 8
I have now found two instances where it seems I will finally need to learn how to install and use drush for my new drupal 8 site. I've been avoiding drush the last 5 years working with drupal 7 because I couldn't find a clear tutorial on how to download, install and run (or even how or where to dl, install and run) drush.

For the record - the two use cases I seem to need drush for are:

* running a migration command to import the csv I've already prepared with content I exported from a wordpress site. I'm trying to use the migrate Migrate Source CSV and the example listed on github.
* running the command entity-updates per the mismatched entity question I posted.

So, I've now plunged back into trying to suss drush out, and I have some questions with my understanding thus far. My knowledge has been limited to logging into my host server to use cpanel (file manager, backups) and using the filezilla ftp client.

According to \[this tutorial by digitalocean\]\[4\] I need to install LAMP stack and pear. This is the first point of confusion.

1. Is this still the correct method for drupal 8?
2. How do I install LAMP on my server - I'm using a Bluehost dedicated server, so it should already have Linux Apache MySQL PHP, correct? Or is this an application of some kind for those components I'm already using on my server to run my sites?
3. How do I install pear? From the command line I can access through my cpanel?

Then, trying to follow this Toronto Website Developer by Peter Yaworski tutorial it seems I also need composer?

1. Do I need to install the composer module?
2. Or do I install the \[full composer here\]\[7\] - and do I install it to my server via cpanel command line as well?

That's about as far as my spaghetti understanding goes as to how what is needed to actually get drush up and running as a command line I can use. Oh, and finally, when I see videos or examples of people using drush, I assume they're running it from their server unless they have a local drupal install, correct?

Thanks in advance for any clarification - can't help but feel I'm in over my head here.

# Answer
> 1 votes
Drush is an incredibly helpful tool, you are going to enjoy it. There are a lot of other benifits you'll get from installing it as well.

I'm going to assume you are on a Mac.(There are other ways to do this on a Windows machine, but you'll have to look for them.)

1. Drush installation is independent of your Drupal version. The only variable is which version of Drush you install. This shows that you'll want version 8.x for Drupal 8.
2. Yes, your Bluehost server already has Linux, Apache, PHP & MySql. The LAMP stack that is referred to in the digital ocean tutorial is one that you install on your home computer. This will allow you to work locally much faster than making changes locally, uploading them to your Bluehost server and seeing if they worked. I'd recommend using homebrew to set it up. Here's a great article to help you out.
3. Here's some info on installing pear on your Bluehost server.

As for the other questions...

1. No, you don't need the composer module. (I haven't used it & I've been using drush for years. I'm not dissing the module, I just know it isn't needed.)
2. Try this go to see how to install composer. This will tell you how to install Composer on both your

You haven't specifically asked about this but I hope you take the time to install LAMP on your home computer. It'll be a hassle but end up in a huge leap in your productivity. BTW You can also use homebrew to install drush. Here's a Drupal article that explains how.

Good luck!

---
Tags: drush, composer
---


# Question
Title: Redirect exclusion rule in .htaccess does not work
I have a rule in my .htaccess to redirect all HTTP traffic to HTTPS, and I'm trying to exclude some specific URL from redirect, so I added the negation exclusion rule:

```
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/my_url
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

But this doesn't work, http://example.com/my\_url redirects to front page example.com. Is it interfering with some other rules? All are standard Drupal core .htaccess.

# Answer
> 1 votes
You're right, there's interference with other Drupal rewrite rules. If you have clean URLs enabled, you're rewriting each request as an argument to index.php. Add an additional check to exclude this other rule.

```
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/my_url
RewriteCond %{REQUEST_URI} !index.php
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

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


# Question
Title: Move Acquia dev destop sites to another local enviroment
What would be the easiest way to move all websites from my old Mac to new Mac or Pc that are done in Acquia Dev Desktop ?

Also, downloading new version just overwrites old installation leaving websites in place, or it will create new version of DevDektop where i have to import all sites from old one ?

# Answer
> 1 votes
(Just saw your comment that you are not using Acquia Cloud so I'm editing my answer.)

* Copy the current location of your local sites to your new computer.
* Download the latest version of Dev Desktop.
* Click on the plus sign at the lower left side of the Acquia Dev Desktop window and select Import local drupal site. In the following dialog, select Change... in the top right corner and select the root folder of your site.

FWIW: The default location of dev-desktop sites is:

> ~/Sites/devdesktop/(site root folder)

You may want to keep this convention for convenience/clarity's sake

I seem to remember having to import my sites individually after upgrading my Acquia Dev Desktop. As you can see from the above, it's really easy.

---
Tags: acquia-dev-desktop
---


# Question
Title: How do I display a help text with field form?
Is there a way to bring up a help message next to a form field as below?

*FooForm.php*

```
$form['field_foo'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Foo'),
    '#required'      => true,
    '#default_value' => 'foo',
    '#help_text' => 'Help text for Foo field',
);

```

# Answer
> 10 votes
Use **#description** attribute.

```
$form['field_foo'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Foo'),
  '#required'      => true,
  '#default_value' => 'foo',
  '#description' => t('Help text for Foo field'),
);

```

---
Tags: 8, forms
---


# Question
Title: What is the first parameter of this db_query call for?
I've inherited some code. It works, but I'm wondering what the "5" does in this db\_query statement.

```
$result = db_query(5, "SELECT * FROM {foo} WHERE bar = '%d'", $bar_val);

```

# Answer
> 0 votes
The first argument taken from `db_query()` is the query string to execute; the next parameters are the values of the placeholders used in the query strings.

If you see code similar to the one you show, it means the content of includes/database.mysql-common.inc, or includes/database.pgsql.inc (depending on the database engine used) has been changed to alter the first parameter used from `db_query()`. If you are using third-party database drivers, check the `database.<database-engine>.inc` file that should come with that database driver.

---
Tags: 6, database
---


# Question
Title: How can I display the value of a variable inside a condition?
I have created a rule using the Rules UI. My rule is not working, and I need to debug it, displaying the values of my variables inside a condition where I make a comparison.

I see within Rules Actions that I can add a system message, but in condition how could I debug variable values?

Rules debug log doesn't show value of variables.

How can I do so?

# Answer
> 1 votes
You might have a combination of Rules Conditions that need some debugging. Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging (further detailed below), but a **K**eep-**I**t-**S**uper-**S**imple technique I often use, is my ***BINGO***-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

Also, if you have multiple Rules Conditions in a single rule, you should try to see what happens (if you get a "bingo") for each of the individual Rules Conditions. This by simply (temporary) removing 2 out of the 3 Rules Conditions you are using, and verify if they each result in the Rules Action you'd expect (also just a simple Bingo-message should be sufficient).

If the above doesn't help, then there are typically 2 ways of more advanced debugging, as further detailed below.

# Rules Evaluation Log

Within the Rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "***Rules Evaluation Log***" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Here is an example of such Rules Evaluation Log:

# Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value". That's not within Rules Conditions (as in your question), but if you add that as your first Rules Action, then you can be sure that the values displayed are identical to the value of these variables at the end of the Rules Conditions.

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

# Resources

# Answer
> 2 votes
Try cloning the rule, and adjust the clone, remove your condition & add a system message action that shows the two variable values you are trying to debug.

BTW, Eventually you may want to install a debugging environment like xdebug. This is likely a longer process than you'd want to tackle for a quick fix. However, if you are planning to keep working in the field, it's incredibly helpful.

You'll find a good start here: https://stackoverflow.com/questions/7303912/setting-up-xdebug-for-drupal-site

# Answer
> 2 votes
For debugging of rules in Drupal you can use `ddebug_backtrace` function but before use this function you have to install `devel` module (because `ddebug_backtrace` is dependent to this module). Please click here for more info.

---
Tags: 7, rules, debugging
---


# Question
Title: How to wrap a contact form with another block?
Is there a method to wrap a contact form with another block and make them together a new block or something?

I want to put some information next to the contact form and put them together in a container. Furthermore I want to place other blocks above and under it, so I prefer not to edit in the region twig file.

**Note**: I want to have some text next to my contact form. So it doesn't neccesary have to be a block, but that was the first that came up to me.

# Answer
Have a look at either of the contributed modules below (quotes are from their project pages).

# Contact Block

> ... provides contact forms in a block. It uses the contact forms that can be created using the Drupal 8 core Contact module.

**Release info**: only for D8.

# Entityform block

> Allows to load a specified entity form as a block.
>
> Usage: Go to the Block layout admin page (`admin/structure/block`), press Place block in the desired region and select Entity form.

**Release info**: Either for D7, or D8 (but only an alfa release for D8 right now).
> 1 votes

---
Tags: 8, blocks, emails
---


title: Entity query returns wrong NID

text:
# Question
Title: Entity query returns wrong NID
I have the following query:

```
$query = \Drupal::entityQuery('node')->condition('type','article');
$result = $query->execute();

```

Then I want to access all content:

```
$nodes = \Drupal\node\Entity\Node::loadMultiple(array_keys($result));

```

But in variable $results, there are wrong NIDs. My first article ID is '12' and second article '13'. But in $result are '9' and '10'

Do you have an explanation for this?

Ok, I found out I can't use array\_keys... because keys are not same as IDs. Proved just now in an easy example... in my $result\[9\] there is the right id '12'.

# Answer
The return value of Query::execute,

> int|array Returns an integer for count queries or an array of ids. The values of the array are always entity ids. The keys will be revision ids if the entity supports revision and entity ids if not.

Nodes support revisions so the keys will be revision ids and not entity ids.

```
$nodes = \Drupal\node\Entity\Node::loadMultiple(array_values($result));

```
> 1 votes

---
Tags: database, entities
---


# Question
Title: How to save dynamic select list value into config table in Drupal 8?
I wanted to show list of fields per content type in admin config form. After saving the form, selected list value should get save into **config** table.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  foreach (node_type_get_types() as $content_type) {
    $entity_type_id = 'node';
    $fields = \Drupal::entityManager()->getFieldDefinitions('node', $content_type->get('type'));
    if ($fields) {
      $options = array();
      foreach ($fields as $field_name => $field_definition) {
        if (!empty($field_definition->getTargetBundle())) {
          $options[$field_name] = $field_definition->getLabel();
        }
      }
      $form['test']['test_' . $content_type->get('type') . '_field'] = array(
        '#type' => 'select',
        '#title' => $content_type->get('name'),
        '#options' => array_merge(array('0' => t('Auto')), $options),
        '#default_value' => $config->get('test_' . $content_type->get('type') . '_field') ? $config->get('test_' . $content_type->get('type') . '_field') : '',
      );
    }
  }
}

```

Here is submit handler

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

foreach (node_type_get_types() as $content_type) {
  $this->config('test.settings')
  ->set('test_' . $content_type->get('type') . '_field', $form_state->getValue('test', 'test_' . $content_type->get('type') . '_field'))
  ->save();
}
parent::submitForm($form, $form_state); }

```

After saving admin form, **test\_article\_field** and **test\_page\_field** is getting saved instead of selected field.

Any help would be appreciated?

# Answer
There is some problem in the submit handler.

Replace

```
$this->config('test.settings')
 ->set('test_' . $content_type->get('type') . '_field', $form_state->getValue('test', 'test_' . $content_type->get('type') . '_field'))
 ->save();

```

line with

```
$this->config('test.settings')
  ->set('test_' . $content_type->get('type') . '_field', $form_state->getValues('test_' . $content_type->get('type') . '_field'))
  ->save();

```

Hope that this helps you.
> 1 votes

---
Tags: 8
---


# Question
Title: Related Content View with multiple Entity Reference Fields
I am trying to create a View to display related content based on shared taxonomy terms from multiple vocabularies.

For example:

I have two content types called **Car** and **Parts**.

I have two vocabularies called **Type** and **Country**.

Content Types:

* Car

+ Entity Reference: Type
    + Entity Reference: Country
* Parts

+ Entity Reference: Type
    + Entity Reference: Country

Vocabularies

* **Type**: sedan, convertible, coupe, van, suv
* **Country**: usa, japan, germany

I would like to display a view of related Parts when viewing a Car node. Furthermore, I only want to display if both Type and Country match.

I’m able to get either Type or Country matches to display by adding the following relationships.

* Content: Taxonomy terms on node
* (term) Entity Reference: Referencing entity (type)
* (term) Entity Reference: Referencing entity (country)

and a contextual filter of:

* (Content referencing Taxonomy term from field\_country) Content: Nid

Basically, switching the relationship on the contextual filter determines whether or not Type or Country matches should be displayed. I am having trouble figuring out how to display Parts that match both the Type and Country of the Car.

# Answer
Basically you need to do the following.

1. Create a view based on content of type parts (as a block I'm guessing)
2. Add a relationship "Content: Country (field\_country)" using the defaults
3. Add a relationship "Content: Type (field\_type)" using the defaults
4. Add a contextual filter for "Taxonomy term: Term ID" with the following settings.
    * **Relationship:** country
    * **Provide default value:** Taxonomy term ID from URL
    * **Load default filter from node page, that's good for related taxonomy blocks**
    * **Limit terms to vocabulary:** Vocabularies country.
    * **Multiple-value handling:** Filter to items that share all terms
5. Add another contextual filter for "Taxonomy term: Term ID" with the following settings.
    * **Relationship:** type
    * **Provide default value:** Taxonomy term ID from URL
    * **Load default filter from node page, that's good for related taxonomy blocks**
    * **Limit terms to vocabulary:** Vocabularies type.
    * **Multiple-value handling: Filter** to items that share all terms.

Now just place your block on all car pages.
> 1 votes

# Answer
**I finally got it working by adding the following Relationships:**

1. A bridge to the Taxonomy term entity that is referenced via field\_type
2. A bridge to the Content entity that is referencing Taxonomy term via field\_type (add relationship to #1)
3. A bridge to the Taxonomy term entity that is referenced via field\_country
4. A bridge to the Content entity that is referencing Taxonomy term via field\_country (add relationship to #3)

**And the following Contextual Filters:**

1. (Content referencing Taxonomy term from field\_type) Content: Nid
2. (Content referencing Taxonomy term from field\_country) Content: Nid

All relationships need to be required. And all contextual filters need to have a default value of "Content ID from URL".
> 0 votes

---
Tags: taxonomy-terms, entities, views
---


# Question
Title: Username converted to us-ascii (unix-style)
I want to convert unicode characters in user names to us-ascii. I.e my first name is Søren and my last name is Sjøstrøm. It should be converted to soren.sjostrom (unix style) as the user name. How do I do that?

# Answer
If you only want to transliterate non-ASCII *European* characters (like those used in Nordic, German and French names), you can use the PHP function strtr. E.g:

```
$name = strtr($name,
   'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ',
   'AAAAAAACEEEEIIIIDNOOOOOOUUUUYTsaaaaaaaceeeeiiiidnoooooouuuuyty');

```

If you want to do romanization of a wider range of non-ASCII alphabets (cyrillic, greek, etc.) take a look at the contributed project **Transliteration**.

While this is specifically to transliterate file names to US-ASCII, at its core is UTF-8 normalization (based on UtfNormal.php from MediaWiki) and transliteration (based upon Sean M. Burke's Text::Unidecode). You should be able to use the same libraries for romanization of names and other strings.
> 1 votes

---
Tags: users
---


# Question
Title: How do I modify default labels of the location module?
How can I modify the field names of the location widget that I use to collect addresses and phone numbers. I am using Drupal 7 with the Location Module: https://drupal.org/project/location

Below a screenshot of the fields I would like to rename ('Street Location' to 'Address Line 1' as an example).

Thanks!

# Answer
> 2 votes
https://www.drupal.org/node/381458#comment-6699162 worked for me

```
/**
 * Implements hook_location_element_alter().
 */
function update_personal_info_location_element_alter(&$element) {
  $element['additional']['#title'] = "Address line 2";
}

```

# Answer
> 0 votes
The *location* is essentially a custom table `location` in the database with all those columns (ew). Having looked through the code they make Drupal form elements for each column in the table as needed.

I suggest hook\_form\_alter to simply change the title disabled where needed when displaying the `location` on page forms.

there are a zillion examples here on stackexchange of how to use hook\_form\_alter.

# Answer
> 0 votes
Here's the suggestion.

There are various options to do so.

1. Use "String Overrides" module
2. Make a module that implements hook\_form\_alter() to change the help text.
3. In location.module, change: '#title' =\> t('Street Location'), to '#title' =\> t('Address Line 1'),

Though 3rd one is not best practices since it makes updating the module harder.

Let me know if you face any query/concern regarding this.

Thanks!

---
Tags: entities, location
---