# Question
Title: How to create an article with "show on demand" part of the text of the article?
What I am trying to do is like in the picture. So I would have an article of same text of multiple language. When I click on the Flag/text link on top of the article, it should show particular part of the text of that language selected. All other texts should be hidden. Is that something easily achievable? Can anyone suggest how to go with it please?

# Answer
> 2 votes
For your use case, there is no module for it. You will need to use custom jQuery

### SEE MY DEMO

For Example:

### HTML

```
<span class="french-flag">
<img src="http://icons.iconseeker.com/png/128/rounded-world-flags/france-flag-2.png"/>
</span>
<span class="english-flag">
<img src="http://icons.iconseeker.com/png/128/rounded-world-flags/us-pacific-island-wildlife-refuges.png"/>
</span>

<br>

<div class="french-text">
Merci
</div>

<div class="english-text">
Thank you
</div>

```

### jQuery

```
$( document ).ready(function() {
 $('.french-flag, .english-flag').css("cursor", "pointer");
 $('.french-text, .english-text').hide();

$('.french-flag').click(function() {
  $('.french-text').show();
  $('.english-text').hide();
});

$('.english-flag').click(function() {
  $('.english-text').show();
  $('.french-text').hide();
});

});

```

**but in drupal you need to wrap your js code inside**

```
(function ($) {
   // code goes here
})(jQuery);

```

**So your Drupal JS code (example.js) needs to be**

```
(function ($) {
     $( document ).ready(function() {
     $('.french-flag, .english-flag').css("cursor", "pointer");
     $('.french-text, .english-text').hide();

    $('.french-flag').click(function() {
      $('.french-text').show();
      $('.english-text').hide();
    });

    $('.english-flag').click(function() {
      $('.english-text').show();
      $('.french-text').hide();
    });

    });
})(jQuery);

```

To add/load your jQuery/java script to drupal, there are various methods, see/read **Working with JavaScript and jQuery**

---
Tags: nodes
---


# Question
Title: What are the various steps to contribute my own module to Drupal.org?
I wrote a custom javascript thing for the Views module but I'm not sure how to go about publishing this on drupal.org.

I know there are a lot of requirements, but what are the steps to be completed and where to publish (contribute) this module?

It seems daunting since I never contributed a module before.

# Answer
The main pages you need to read are Best practices for creating and maintaining projects and Project application checklist. If you have never done this before, you need to read Creating a sandbox (experimental) project

In short, you need to

* Obtain git access on drupal.org
* Create your sandbox project
* Commit your code
* Submit it for review
* If approved, it will be promoted to be a full project

Keep in mind that your project will likely never be officially reviewed unless you get a review bonus. Participating in other reviews is also a good way to learn about best practices so you can get through the initial review smoothly.
> 11 votes

# Answer
An alternative for most of the steps in the procedure described in the first answer, is to find an existing project (namespace) that is obsolete, unsupported or looking for a new maintainer.

After you found a project that might fit (e.g. with a relevant namespace), the process to become the new maintainer typically takes between a few hours and about 2 weeks at max.

For way more details on that, refer to my answer to "Are there any alternatives to applying for a full project on drupal.org?".
> 1 votes

---
Tags: 7, community-official-site
---


# Question
Title: How to fix "GeoType" plugin does not exist
I'm following this tutorial. I've installed the geofield module and all needed for it wo work. I finally manage to create a content type "Place" with a field of type geofield. When i then create a new content of type "Place", i get the following message on drupal 8.0.3: The website encountered an unexpected error. Please try again later.

> Drupal\Component\Plugin\Exception\PluginNotFoundException: The "GeoType" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 57 of C:\wamp\www\drupal8\core\lib\Drupal\Component\Plugin\Discovery\DiscoveryTrait.php)

I'm using drupal 8.0.3 with geofield 8.x-1.0-alpha1 Note i also habe geoPHP enable. Any idea how i can solve this issue?

# Answer
> 0 votes
Alfter some reading and searching, i finaly found a solution. Just go here and apply patch #10. It's just one change that need to be done in the GeoConstraint.php file in src/Plugin/Validation/Constraint/GeoConstraint.php. In line 14,7 change "@Plugin(" to "@Constraint("

---
Tags: location
---


# Question
Title: Display field content in views single field template.. STUCK!
Welcome,

I'm working with Hero slider and views to display slider from nodes in custom type. Where I am now, is:

* created node type with fields like title, content, picture and background picture,
* created views for dysplay this content, hide all fields, last one is background field, in this field i wrote rewrite twig code do dysplay all fields with some if function to choose prefered slide type and display content right way in every slide,
* what I need is make wrap around every `li` element with slide content, because views filter out markup, and I can't get slide with responsive background.. life would so much easier with that filter go away.
* I work with views-view-field--slider.html.twig that is displayed correct from my template.
* I cant display my link to image for background in code:

> ```
> <div style="background-image: url( {{ HERE IS MY PROBLEM }} )">{{ output -}}</div>
>
> ```

I feel lost with `data = row[field.field_alias]` tried kint, dump and a lot of various combination of twig code.. looks like I am missing some basics or simple target code to this field. Help me..

# Answer
> 1 votes
Ok, so how I solved it... Maybe there is other, better solution?

1. I rearrangement my fields in view: first with content, title, pictures and links,
2. I've added one more custom text field with rewrite - then I put in this rewrtite all fields above with some twig function to display this in different ways and hide this field to.
3. Then I've added last field, field\_background which is one with slide background picture. I turn it to display just URL of picture and write rewrite inside to display:

{{ field\_background }} )"\> {{ nothing }}

wher nothing is my field with all content stuf inside.

4. I've edited twig template for last field and write something like this:

\<.div style="background-image: url( {{ output }}

so when views start rendering content it create code from my last field which is wrapprer with background image around content form other fields above.

Well, it's work, my slides run with background picture. But I dont fell good with that, I think there is better way to get it in one field.

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


# Question
Title: How to display like and dislike count in Drupal Web Services
I'm working with Drupal 7.x, for web services I'm using service & services\_views whereas for voting I'm using rate with votingapi as the dependency.

I'm unable to get the count of positive votes i.e. nothing but **like** and count of negative votes i.e. nothing but **dislike** below attached is my view code:

```
<?php
$view = new view();
$view->name = 'web_services';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Web Services';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  '_story' => '_story',
);

/* Display: List */
$handler = $view->new_display('services', 'List', 'list');
$handler->display->display_options['defaults']['relationships'] = FALSE;
/* Relationship: File Usage: File */
$handler->display->display_options['relationships']['node_to_file']['id'] = 'node_to_file';
$handler->display->display_options['relationships']['node_to_file']['table'] = 'file_usage';
$handler->display->display_options['relationships']['node_to_file']['field'] = 'node_to_file';
/* Relationship: Content: Vote results */
$handler->display->display_options['relationships']['votingapi_cache']['id'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['table'] = 'node';
$handler->display->display_options['relationships']['votingapi_cache']['field'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['required'] = TRUE;
$handler->display->display_options['relationships']['votingapi_cache']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => 'thumbs_up_down',
  'function' => 'count',
);
/* Relationship: Content: Votes */
$handler->display->display_options['relationships']['votingapi_vote']['id'] = 'votingapi_vote';
$handler->display->display_options['relationships']['votingapi_vote']['table'] = 'node';
$handler->display->display_options['relationships']['votingapi_vote']['field'] = 'votingapi_vote';
$handler->display->display_options['relationships']['votingapi_vote']['required'] = TRUE;
$handler->display->display_options['relationships']['votingapi_vote']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => 'thumbs_up_down',
);
$handler->display->display_options['relationships']['votingapi_vote']['current_user'] = 0;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['label'] = 'ID';
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = 'Title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title']['link_to_node'] = FALSE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['label'] = 'Summary';
$handler->display->display_options['fields']['body']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['body']['type'] = 'text_trimmed';
$handler->display->display_options['fields']['body']['settings'] = array(
  'trim_length' => '120',
);
/* Field: File: Path */
$handler->display->display_options['fields']['uri']['id'] = 'uri';
$handler->display->display_options['fields']['uri']['table'] = 'file_managed';
$handler->display->display_options['fields']['uri']['field'] = 'uri';
$handler->display->display_options['fields']['uri']['relationship'] = 'node_to_file';
$handler->display->display_options['fields']['uri']['label'] = 'mediaURL';
$handler->display->display_options['fields']['uri']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['uri']['empty'] = 'http://esakal/sites/esakal/files/default_images/Sakal_Media_Group_logo.jpg';
$handler->display->display_options['fields']['uri']['hide_alter_empty'] = FALSE;
$handler->display->display_options['fields']['uri']['file_download_path'] = TRUE;
/* Field: Content: Cover Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['label'] = 'thumbnailURL';
$handler->display->display_options['fields']['field_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => 'thumbnail',
  'image_link' => '',
);
/* Field: Content: Comment count */
$handler->display->display_options['fields']['comment_count']['id'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['label'] = 'numberOfComments';
$handler->display->display_options['fields']['comment_count']['element_label_colon'] = FALSE;
/* Field: Content: Post date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'node';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'CreateDate';
$handler->display->display_options['fields']['created']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['created']['date_format'] = 'long';
$handler->display->display_options['fields']['created']['second_date_format'] = 'long';
/* Field: Votes: Value */
$handler->display->display_options['fields']['value']['id'] = 'value';
$handler->display->display_options['fields']['value']['table'] = 'votingapi_vote';
$handler->display->display_options['fields']['value']['field'] = 'value';
$handler->display->display_options['fields']['value']['relationship'] = 'votingapi_vote';
$handler->display->display_options['fields']['value']['precision'] = '0';
$handler->display->display_options['defaults']['arguments'] = FALSE;
$handler->display->display_options['defaults']['filter_groups'] = FALSE;
$handler->display->display_options['defaults']['filters'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  '_story' => '_story',
);
$handler->display->display_options['filters']['type']['group'] = 1;
/* Filter criterion: Content: Appearance Status Tags (field_status_tags) */
$handler->display->display_options['filters']['field_status_tags_tid']['id'] = 'field_status_tags_tid';
$handler->display->display_options['filters']['field_status_tags_tid']['table'] = 'field_data_field_status_tags';
$handler->display->display_options['filters']['field_status_tags_tid']['field'] = 'field_status_tags_tid';
$handler->display->display_options['filters']['field_status_tags_tid']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_status_tags_tid']['expose']['operator_id'] = 'field_status_tags_tid_op';
$handler->display->display_options['filters']['field_status_tags_tid']['expose']['label'] = 'categoryAppearance';
$handler->display->display_options['filters']['field_status_tags_tid']['expose']['operator'] = 'field_status_tags_tid_op';
$handler->display->display_options['filters']['field_status_tags_tid']['expose']['identifier'] = 'categoryAppearance';
$handler->display->display_options['filters']['field_status_tags_tid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
);
$handler->display->display_options['filters']['field_status_tags_tid']['type'] = 'select';
$handler->display->display_options['filters']['field_status_tags_tid']['vocabulary'] = 'appearance_status_tags';
/* Filter criterion: Content: Site Section Tags (field_site_section_tags) */
$handler->display->display_options['filters']['field_site_section_tags_tid']['id'] = 'field_site_section_tags_tid';
$handler->display->display_options['filters']['field_site_section_tags_tid']['table'] = 'field_data_field_site_section_tags';
$handler->display->display_options['filters']['field_site_section_tags_tid']['field'] = 'field_site_section_tags_tid';
$handler->display->display_options['filters']['field_site_section_tags_tid']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_site_section_tags_tid']['expose']['operator_id'] = 'field_site_section_tags_tid_op';
$handler->display->display_options['filters']['field_site_section_tags_tid']['expose']['label'] = 'categoryID';
$handler->display->display_options['filters']['field_site_section_tags_tid']['expose']['operator'] = 'field_site_section_tags_tid_op';
$handler->display->display_options['filters']['field_site_section_tags_tid']['expose']['identifier'] = 'categoryID';
$handler->display->display_options['filters']['field_site_section_tags_tid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
);
$handler->display->display_options['filters']['field_site_section_tags_tid']['type'] = 'select';
$handler->display->display_options['filters']['field_site_section_tags_tid']['vocabulary'] = 'site_section_tags';
$handler->display->display_options['path'] = '-list';
$translatables['web_services'] = array(
  t('Master'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('List'),
  t('File'),
  t('Vote results'),
  t('Votes'),
  t('ID'),
  t('Title'),
  t('Summary'),
  t('mediaURL'),
  t('thumbnailURL'),
  t('numberOfComments'),
  t('.'),
  t(','),
  t('CreateDate'),
  t('Value'),
  t('categoryAppearance'),
  t('categoryID'),
  t('Detail'),
  t('User entity referenced from field_reporter'),
  t('Profile'),
  t('Content'),
  t('twitterHashTag'),
  t('00'),
  t('socialURL'),
  t('ReporterName'),
  t('ReporterEmailID'),
  t('ReporterTwitterHandler'),
  t('categoryName'),
  t('relatedArticles'),
  t('ReportedDate'),
  t('ReporterProfileURL'),
  t('Media'),
  t('mediaID'),
  t('timeStamp'),
  t('caption'),
  t('videoURL'),
  t('mediaType'),
  t('Comment'),
  t('Comments'),
  t('commentorName'),
  t('commentText'),
  t('completeTimeStamp'),
);

```

# Answer
Have you tried that module services\_votingapi instead of using views It will help achieve our goal

Also flag\_service will help you get flags count If you used in your side without having to build custom module or even use views
> 1 votes

---
Tags: views, services, rating
---


# Question
Title: Populate Dropdown list from a web service without code
I know that in Drupal a drop down list field can be populated with taxonomy terms, but is there a way without having to go custom (custom PHP development) to populate a dropdown list from the results of consuming a web service?

Say I consume a web service that returns the weather for the current week (7 days), I would like to populate the data returned into a dropdown list so that whenever the data is changed at the web service it is automatically reflected in my list.

Is there way to do this in the Drupal UI?

Many Thanks

# Answer
> 0 votes
I think you have to do it in code call the webservice in a custom module process the results and pass it to the template for display as you need

---
Tags: services, navigation
---


# Question
Title: Is there a way to style the main-container without it effecting ALL the site?
I am using the bootstrap subtheme.

I was wondering if there was a way to style the main-container in relation to a particular node or section of the site, rather than it styling it the same everywhere. The reason I want to do this is because I want to setup multiple small mini-sites with different themes. Sort of like a show-case of what I can do in web-design.

The problem though is I can style the main-container, but it will style it everywhere for every page. Is there a way I can make it target specific only pages?

In this example: I want to style the white space BUT it only be done on my "mech" page. To my current knowledge, if I target .main-container it will style it everywhere on every page, which is what I do not want.

# Answer
You can do it using the CSS. First on whichever node you want to do, find its specific class given when you create that node (How: right click on the page and Inspect element in the code ........., you will find the several class, one of which is specific for that node). Now take that class. Now suppose if you want to change the main-content with that node only and do not want to change other, use following selector in css,

```
.specific-page-node-class #main-content {your css code}

```

This will apply change to main content of that specified node only and do not change to other.

Credit: Link for detail question and answer which I asked on same topic on the Drupal answer, I have summaried above
> 0 votes

# Answer
Based on a specific `class` or `ID` you can target the container. Ensure that that class/ID isn't used elsewhere on the site to avoid conflicts.

Example

HTML

```
<div class="main-container" id="mechs">...</div>

```

CSS

```
#mechs {
  background:white;
}

```
> 0 votes

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


# Question
Title: How to get grid items to align center in Bootstrap views?
I'm using Bootstrap views Drupal 7.

**Live site is over here to have a look at the code:**

http://xuzo.com/testing/

When a 3 column grid gets minimized, the 3 items stack 2 on top and 1 on the bottom.

But the bottom one is left aligned.

How can I have them align in the center so I get a nice triangle?

This looks easy with css, but I can't get it to work, tried:

```
 margin: 0 auto;

```

And others but can't get it working for some reason...

# Answer
> 1 votes
If you can create div tag, you can use css as show below.

Example:

html: `<div class="secLayerContainer"><div class="secLayerContent">.....</div></div>`

css: .secLayerContainer { display: inline; float: left; width: 100% } .secLayerContent { display: block; float: none; width: 200px; margin: 0px auto}

note: 200px also can change 20%. (your preference)

---
Tags: views, theming
---


# Question
Title: Is there a D7 equivalent to the Unlimited Field module?
I need a field allowing either a numeric value or "unlimited".

The Unlimited Number module is exactly what I want, but it's D8-only.

Is there a way to do the same thing in D7?

# Answer
To implement ***a field allowing either a numeric value or "unlimited"*** in D7, you can define such field using the desired widget (like a textfield maybe?). And then use the Rules module to validate the actual data that is entered before the entity (like a node or user where you use that field?) is saved (created or updated).

Some more details about the validation part of such rules to be created:

1. Add the appropriate validations you want within the Rules **Conditions**.
2. You may want to specify multiple conditions and combine them with an "OR", eg to validate that the value entered is either the string "unlimited", or a digit equal to "0", "1", "2", "3" or "4".
3. If you have lots of allowed digits (say dozens), just use an appropriate regular expression (instead of a loooong list of digits).

Have a look at my answer to "How to make the permissions of a module more granular?", which you can use as examples of what might be needed to implement *Rules conditions* as in bullets "2." or "3." above.

Of course you'd also have to pick the most appropriate **Rules Event** for this rule to be triggered. But there are quite a few, straight forward, events you can pick from (depending on where exactly you want to use this field), just to mention a few:

* Before inserting a new node (optionally limited to content type ABC). E.g. if your field is used to "Store the maximum speed on highways in country X".
* Before saving an update to a user profile. E.g. if your field is used to "Store the duration (in days, months or years) of some type of membership subscription".

And your **Rules Action** is probably just a simple "Drupal set message". Though I can think of honeypot-scenarios where some specific values that got selected could result in a rules action like "block this user".

If you want even more granularity, you might also want to have a look at Conditional Rules, which allows for using "Rules Conditions" within "Rules Actions". Refer to my answer to "How to prevent a node being saved when using the Rules module?" for an illustration of using this module.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How can I style fields in custom content type
I am using **Drupal 8** and I've made a custom content type, and I've figure it out, that I can "style" this content type with **page--mycontenttype.html.twig** and with adding this code in **mytheme.theme**:

```
function mythemename_theme_suggestions_page_alter(array &$suggestions, array $variables) {

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

```

But with this I can only style page of custom content type, and not the fields of it. I try with this but it's not working:

```
{{ node.field_body.value }}
{{ node.field_title.value }}

```

# Answer
The body and title have no prefix `field_`, this should work:

```
{{ node.body.value }}
{{ node.title.value }}

```

But is not the preferred way to style the fields on the page level. If you access the field values in the database, which you basically do when you access the node object, you get the raw value, only escaped by twig for security reasons. Without the formatting, that is integrated into drupal for each field type, and that you can easily extend with additional modules.

To style the fields of the custom content type go to:

```
admin/structure/types/manage/mycontenttype/display

```

If you can't find all the options you need for your fields in the ui, you can make a copy of the field twig and apply the changes there.

```
field--field-myfield.html.twig

```
> 1 votes

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


# Question
Title: Get current taxonomy in template_preprocess_html()
I have a custom field on my taxonomy that I would like to access in template\_preprocess\_html(). How do I get the current taxonomy id, in Drupal 8, on a taxonomy listing page?

# Answer
> 18 votes
First, check if the route is for a taxonomy term; then, get the term ID.

```
if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
  $term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
}

```

---
Tags: theming, taxonomy-terms, 8
---


# Question
Title: How anonymous users are able to complete survey, even when webform is set only for registered users
I have used Webform module for gathering user data before accessing the content. Only authenticated users can access the webform, but in the webform submission reports there are some user names with name as anonymous who submitted the webform.

# Answer
> 0 votes
Admin menu --\> webform --\> Choose one of your webform and click component--\> form setting

Under SUBMISSION ACCESS untick anonymous user.

# Answer
> 0 votes
it is already set to be access only by authenticated users. in most of the cases username comes properly but in some of the cases the username comes as anonymous( not verified )

---
Tags: webforms, users
---


# Question
Title: What can cause duplicated XML sitemap links?
I have a site where I have XML Sitemap installed. I was using node-based sitemaps, and everything was working fine. I also enabled the menu sub-module, and now I see duplicate links for all of my content:

What can cause this?

# Answer
Please visit the feature request about "Remove duplicate links when using both menu and node sitemap". It has a patch which works fine.
> 2 votes

---
Tags: 7, xml-sitemap
---


# Question
Title: The Solr server could not be reached. Further data is therefore unavailable
I have installed a solr 5.2.1 in my windows 7 and I have created a solr core through SOLR Admin UI. It works fine. When, I trying to connect to solr by help of search\_api\_solr module in drupal 7.38 on my local host, The following error is coming.

"The Solr server could not be reached. Further data is therefore unavailable". What I have missed out, Anyone can Please help. Refer the below images.

# Answer
Maybe your path for solr is wrong. If you setup solr by drupal instructions then your solr path must be: /solr/drupal
> 2 votes

---
Tags: search
---


# Question
Title: Field variable customization in node.tpl.php
i have a website in which i am building a custom node page: `node--coupon.tpl.php` in which i want to render the body field only for which i used

> print render($content\['body'\]);

The result is shown as "BODY: this is my text".

but i want to use only 'this is my text' which is entered at the time of making a new custom content type of coupon.

is it possible to do so anyhow?

# Answer
> 2 votes
If you want to hide the label, go to Admin \> Structure \> Content types \> Coupon \> Manage display.

# Answer
> 0 votes
Using render function will always render the whole stuff. Print the exact variable that contains the body content. If you are aware of Devel module, it will hep you to find the exact variable.

For example, something like `print $node->body['und'][0]['value'];` will do the stuff.Sure it will include the html tags ( if made entry ).

---
Tags: entities
---


# Question
Title: How can I set the help text as an input placeholder on the user login form?
On the user login form, I am trying to take the "help text" and make it an input placeholder (so that the help text shows up in the input and disappears when the user enters their username and password).

Here's my code:

```
function mymodule_form_user_login_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['name']['#placeholder'] = $form['name']['#description'];
  $form['pass']['#placeholder'] = $form['pass']['#description'];
//  $form['name']['#description']['#access'] = FALSE;
//  $form['pass']['#description']['#access'] = FALSE;
}

```

This adds the placeholder correctly but it doesn't hide the help text, so the text appears twice (in the input and below the input). In Drupal 7, I just set access to false, but in Drupal 8 the description is an object so I don't know what to do.

# Answer
> 2 votes
```
unset($form['pass']['#description']);

```

or

```
hide($form['pass']['#description']);

```

is probably sufficient for the description element. I wouldn't use both above on form fields/controls though, because that may lead to unwanted validation errors and so forth.

---

```
$form['name']['#description']['#access'] = FALSE;

```

does not work for 'description' element as it is not a form control(field).

If anybody knows of better ways for removing description element, please chime in.

---
Tags: hooks, 8, users
---


# Question
Title: How can I add 'text/jsx' type to a script tag via libraries.yml?
I want to add some react js files to a theme's libraries.yml and I don't know how I can do this in drupal 8.

`<script type="text/babel" src="scripts/example.js"></script>` or `<script type="text/jsx" src="scripts/example.js"></script>`

I can't figure it out hot to make the `type="text/jsx"` appear when the file is added to the page.

Any ideas on how I can achieve this in Drupal 8?

# Answer
> 1 votes
I took a wild guess because I couldn't find absolutely nothing. Apparently this works:

```
my-libary:
  version: 1.x
  js:
    js/node.js: { attributes: {type: text/babel} }

```

---
Tags: 8, theming
---


# Question
Title: How to query all fields of the node that is tagged with taxonomy term from a specific vocabulary
I'm struggling to find a way to retrieve all the node fields where a specific taxonomy is implemented. I was close to find something with this query :

```
$query = db_query('SELECT fci.field_name
    FROM d7_field_config_instance fci
    LEFT JOIN   (SELECT tv.vid, tv.machine_name
    FROM d7_taxonomy_vocabulary tv
    LEFT JOIN d7_taxonomy_term_data ttd
    ON tv.vid = ttd.vid
    WHERE ttd.tid = 76) AS tax
    ON tax.machine_name LIKE fci.bundle'));

```

But it seems like `machine_name` and `bundle` have different values for a same technology.

The idea is : From a taxonomy id =\> find taxonomy vid (vocabulary id) =\> find machine name of the vocabulary =\> find the bundles where this vocabulary is used.

Any help would be appreciated.

**Solution** : Thanks to @Eugis' answer (Accepted answer), I came up with this solution :

```
db_query("SELECT fcf.field_name, fcf.data FROM
          (SELECT fc.field_name, fc.data FROM field_config fc
          WHERE fc.type LIKE 'taxonomy_term_reference') AS fcf
        INNER JOIN field_config_instance fci
          ON fcf.field_name = fci.field_name
          AND fci.bundle LIKE :bundle",
      array(':bundle'=> $bundle));

```

Hope it'll help someone else.

# Answer
> 0 votes
I think, you should check the `field_config` table where `type = 'taxonomy_term_reference'`. The vocabulary name where the field is referencing to is stored in the `data` column as `BLOB`. you can use the unserialize php function to extract the data stored in the `BLOB`. That's because you can't reach it with a single select query.

Try using loops and ifs :)

---
Tags: 7, entities, taxonomy-terms
---


title: Run hook update N in different batches

text:
# Question
Title: Run hook update N in different batches
I am trying to update drupal. I want to break the updates into 2 different runs/groups. I want run the second batch of updates after the first is done. The first batch contains the updates from the drupal update and the second should contain the custom ones. Is this possible in any way?

# Answer
> 1 votes
I think you can do this by Drush. Install drush

```
1. drush up drupal  ->> it will update only core drupal
2. drush pm-update --no-core <modulename>   ->> it will update only mentioned module.

```

---
Tags: hooks, updating
---


# Question
Title: How can I get multiple values in a RESTful endpoint from a field who points to other resource?
I have a Drupal 7.x site with RESTful installed (version 2.5) and I want have one endpoint which shows a node view, and add a field which show a index of nodes ,extracted from another endpoint, which have a entity reference field pointing to the first node.

I tried adding 'resource' key in *publicFields* method but I can only get the first result.

I saw restful obtain a resource view using ResourceFieldEntity class, calling allways *view* method inside of *singleValue* method, which only can return first value. It guess it's made in this way because singleValue don't need return more than one value, but in my case its needed, because i need the resource retrieve the complete result.

Here is where method is called, in line 336 of *ResourceFieldEntity* class.

```
   try {
     // Get the contents to embed in place of the reference ID.
     /* @var ResourceFieldCollection $embedded_entity */
     $embedded_entity = $embedded_resource
       ->getDataProvider()
       ->view($embedded_identifier);
   }

```

I solved this creating a custom resource getter class (extending *ResourceFieldEntity*), and overwrite singleValue method, and called index method instead of view method.

```
   try {
     // Get the contents to embed in place of the reference ID.
     /* @var ResourceFieldCollection $embedded_entity */
     $embedded_entity = $embedded_resource
       ->getDataProvider()
       ->index($embedded_identifier);
   }

```

Are there any other proper way to do this?

# Answer
I haven't used this module in a while, so I'm not sure if there's a major difference in the approach between 1.x and 2.x.

I would just implement a custom function for getting the single resource, so that you have full control over what is ret

```
/*
* Overrides \RestfulEntityBase::controllersInfo().
* Allows us to specify custom functions for different HTTP actions.
*/
public static function controllersInfo() {
  return array(
   '^.*$' => array(
     \RestfulInterface::GET => 'customGetSingleExample',
   ),
  );
}

/**
* Return custom data for getting single resource result
*/
public function customGetSingleExample() {

  //grab request values
  $request = $this->getRequest();
  static::cleanRequest($request);

  //do stuff with request (EntityFieldQuery etc)

  .....

  return $result;
}

```

This is within a **custom resource class**, which **extends RestfulEntityBaseNode**

```
class RestfulCustomResource extends RestfulEntityBaseNode {

```
> 2 votes

---
Tags: 8
---


# Question
Title: Content type migration using the Feature module?
We have to upgrade Drupal 6 site to Drupal 7. We know that we can use migrate module for importing Drupal 6 content. But I'd like to know if we can use Features module for importing content types, taxonomies and blocks from Drupal 6 to Drupal 7?

# Answer
This is already included in the core. You don't need to install Features in order to migrate all that.

Here's what you need to do in a nutshell: disable all contrib modules, make backups of everything, plug D7 into the D6 database and update the site. Drupal will take care of all basics, such as content types and fields.

Refer to the documentation for more information.
> 1 votes

---
Tags: 7, features
---


# Question
Title: Is it necessary to have a separate voting tag for each rating when using Fivestar?
By design I will have a ratings page with many things to rate - 30 different Fivestar ratings altogether in the same content type.

Is it necessary to have a separate voting tag for each of these 30 ratings? Because I see there is a character limit on the field in Fivestar tags configuration and I can't input all my voting tags.

# Answer
The answer to the question in your **title** is YES, for reasons explained in Adrian's answer already.

As a workaround to your challenge about "**there is a character limit on the field in Fivestar tags configuration and I can't input all my voting tags ...**" (as in your question details), you may want to have a look at the feature request "Increase size of admin textfield", which is like so:

> When you have a lot of voting tags the 128 character limit isn't enough. I suggest increasing.
>
> Adding a `'#maxlength' => 256`, should do in `fivestar.admin.inc` should do.

The last phrase in what I quoted above might possibly be an acceptable compromise for your case: shouldn't be too tough to implement this change to that **maxlength** ... If you do, consider contributing an appropriate patch back to that issue I mentioned here. That way, and assuming it gets accepted, you would no longer have to maintain/re-apply that patch with future versions of this Fivestar module.
> 1 votes

# Answer
Yes, you need a separate voting tag for each ratings in the same content type, if you use the same for multiple fields, each field will recieve the same rating.

You can make a test, create two fields with the same tag, go to create one node and rate one field, refresh the page and you will see the same rate in the other field.
> 2 votes

---
Tags: rating
---


title: Images can not be changed

text:
# Question
Title: Images can not be changed
This seems strange to me, but everything worked fine before i made my site live. I set up all the content and made a backup. Uploaded everything to its server but now i can't change my images. When i remove the current image this comes up (see image) instead of being able to upload a new image

And console throws this error:

I have tried all the versions of jquery and my jquery\_update in contrib is 7.x-2.7

Could it be something with the permissions? i have site/default/files-775

# Answer
> 0 votes
if you installed any module that alters with the drupal paths or jquery\_update module version can cause the issue.

# Answer
> 0 votes
Make sure that before making the site live `cache` was disabled in development server.If not try disabling `cache` in live site.

---
Tags: nodes, media, files
---


title: Redirect user after node add/edit

text:
# Question
Title: Redirect user after node add/edit
I want to redirect users to a custom page, after they create a node or edit it.

# Answer
You can use `hook_form_alter` to add a custom submit handler where you can set the redirection path.

See the FAPI for more details about form redirection.
> 6 votes

# Answer
You can create a rule that redirects the user to any page when they create or edit a specific content type. When you add a rule select "After Creating New Content" add also a condition of "Content Has Type". You Do section will give you the option to redirect a user to any page you want.

For a redirect after editing a node, just create a new rule and select "After updating Existing Content" as your first option.
> 4 votes

# Answer
When doing this, ensure to also unset a possible existing destination which normally is added to the URL when you click the edit button to edit an existing node.

Replace `article` in `MYMODULE_form_article_node_form_alter` with your content type's machine name.

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_article_node_form_alter(&$form, &$form_state, $form_id) {

  $form['actions']['submit']['#submit'][] = '_MYMODULE_node_form_redirect';
}

/**
 * Submit callback.
 */
function _MYMODULE_node_form_redirect($form, &$form_state) {

  // Unset destination first.
  unset($_GET['destination']);
  unset($_REQUEST['edit']['destination']);

  $form_state['redirect'] = 'FOO/BAR';
}

```
> 3 votes

# Answer
The documentation is not very clear on it, but you should modify `$_GET['destination']` variable, not `$_REQUEST` or `$form_state['redirect']`.
> 1 votes

# Answer
in Drupal 7 you can alter the node edit form to 'attach' your own submit function, in which you can alter form\_state of the node delete confirmation form to include the 'destination' parameter... just did this in a custom theme i've been developing as a subtheme of the 'seven' admin theme...

Documentation for hook\_form\_FORM\_ID\_alter

You can add this hook to a template/theme, not just to modules.

so in your theme's `template.php`, add this form alter hook:

```
function yourtheme_node_delete_form_submit( &$form, &$form_state ) {
    $form_state[ 'redirect' ][ 1 ][ 'query' ][ 'destination' ] = "admin/content";
}

```

and then, voila. no longer redirected to homepage after a node is deleted.
> 1 votes

# Answer
Solution from here http://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7#comment-18139

```
<?php
  function FORM_NAME_form_submit($form, &$form_state) {
    $form_state['redirect'] = array(
      // $path
      'path/to/redirect/to',
      // $options
      array('query' => array('key' => 'value')),
      // $http_response_code
      302,
    );
  }
?>

```
> 0 votes

---
Tags: 7, redirection
---


# Question
Title: Insert some data in comment upon comment submit
For some reason I cannot find answer to relatively simple question. How to insert some data (for example the "title" filed value) into comment body upon the comment submit. Finally I'd like to have in comment body something like this:

* Node title (with some CSS markup) -
* Comment body -

Could you please advice the right way to do this?

# Answer
> 0 votes
Since you didn't say which version of Drupal are you using, I'll assume that you're talking about D7.

You need to use `hook_comment_presave()`.

```
function YOUR_MODULE_comment_presave($comment) {
  // Do this only for new comments.
  if (!$comment->cid) {
    // This code will insert the subject as heading.
    $subject = '<h2>' . $comment->subject . '</h2>';
    $comment_text = $comment->comment_body[LANGUAGE_NONE][0]['value'];
    // Set the value.
    $comment->comment_body[LANGUAGE_NONE][0]['value'] = $subject . $comment_text;
  }
}

```

However, do bear in mind that you will need to handle somehow editing existing comments as well.

Hope this helps.

---
Tags: comments
---


title: Cache error message

text:
# Question
Title: Cache error message
My Drupal 6 website has been working fine for many months. All of a sudden, it displays the following error messages:

> Warning: Can't find record in 'cache' query: SELECT data, created, headers, expire, serialized FROM cache WHERE cid = 'variables' in /home/olo000/public\_html/\<\>/includes/database.mysql.inc on line 135
>
> Warning: Cannot modify header information - headers already sent by (output started at /home/olo000/public\_html/\<\>/includes/database.mysql.inc:135) in /home/olo000/public\_html/\<\>/includes/bootstrap.inc on line 729
>
> Warning: Cannot modify header information - headers already sent by (output started at /home/olo000/public\_html/\<\>/includes/database.mysql.inc:135) in /home/olo000/public\_html/\<\>/includes/bootstrap.inc on line 730
>
> Warning: Cannot modify header information - headers already sent by (output started at /home/olo000/public\_html/\<\>/includes/database.mysql.inc:135) in /home/olo000/public\_html/\<\>/includes/bootstrap.inc on line 731
>
> Warning: Cannot modify header information - headers already sent by (output started at /home/olo000/public\_html/\<\>/includes/database.mysql.inc:135) in /home/olo000/public\_html/\<\>/includes/bootstrap.inc on line 732

How shuld I go about solving this?

Steps I have tried: I've search extensively for other threads that discuss the same problem, but I've not found any.

# Answer
You can fix it by upgrading to Drupal 7 or 8

**Drupal 6 end-of-life announcement**
> 0 votes

---
Tags: 6, status-messages
---


# Question
Title: Simulate submission of custom form as a webform
I've a custom module that generate a form, it allows user to submit some data to website. I'm looking for a nice way to display those submit and I would very much like to use webform module for this (because it is already used a lot in company).

I would appreciate any help especially with some snippets.

I found only this post: Submit a custom form as a webform submission but that is almost nothing.

# Answer
Here's how to create a Webform submission programmatically:

```
global $user;
$node = node_load(YOUR_NODE_ID);

// Prepare the data. Do note that the keys in this array must match the elements
// in your webform.
$data = array(
  1 => array('Field one value'),
  2 => array('Field two value'),
  3 => array('Field three value'),
);

// Create the submission object.
$submission = new stdClass();
$submission->uid = $user->uid;
$submission->nid = $node->nid;
$submission->submitted = REQUEST_TIME;
$submission->remote_addr = ip_address();
// This is necessary to mark the submission as complete.
$submission->is_draft = FALSE;
$submission->data = $data;

// Store the submission.
module_load_include('inc', 'webform', 'includes/webform.submissions');
webform_submission_insert($node, $submission);

// If necessary, invoke the email sending for this Webform.
webform_submission_send_mail($node, $submission);

```

Hope this helps.
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: How to calculate the sum of 2 fields in a content type and display the result in a 3rd one when the node is saved?
Could anybody figure out to me how i could create a field that computes the sum of values in 2 other fields.

In other words how to do a simple addition (say of `price` and `vat`) like so:

```
price
+
vat
======
result

```

The `result` should be displayd after the editor saved the node.

# Answer
Another answer to this question (without accepted answer ...), is to use the (fairly new) Math Field module (for D7), instead of the Computed Field module (as suggested in all 3 previous answers ...).

Some more details about this module (from its project page):

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

**Bonus**: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...

**Known issues**

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:
> 0 votes

# Answer
Computed Field is a good solution. You can achieve a similar results without an additional module (provided you already have a custom module).

If you need to store the result when the node is saved, you can implement `hook_node_presave()` to set the value of the third fields just before the node data is saved to the database.

```
MODULE_node_presave($node) {
  $value = 0;
  $price_items = field_get_items('node', $node, 'field_price');
  if ($price_items) {
    $value += $price_items[0]['value'];
  }
  $vat_items = field_get_tems('node', $node, 'field_vat');
  if ($vat_items) {
    $value += $vat_items[0]['value'];
  }
  $node->field_value[LANGUAGE_NONE] = array(array('value' => $value));
}

```

Because the value is always calculated and simple, there is really no need to store it in the database. If your are already using the Entity API module and its entity metadata wrappers, this is easily doable with a `hook_entity_property_info()` implementation.
> 4 votes

# Answer
You can use Computed Field module to achieve this.

About Computed Field

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

**How to use:**

Here are the steps to achieve your case.

Add computed filed type (say result) to your content type to compute **price** and **Vat** filed values.

Here are the settings for result field (to compute **price** and **vat**)

In the **Computed Code (PHP)** textarea, paste the following code.

(Assuming that **price** and **vat** are machine names for price and vat fields)

```
$entity_field[0]['value'] = $entity-> field_price['und'][0]['value'] + $entity->field_vat['und'][0]['value'];

```

In your case, You may not have to change the code in **Display code (PHP)** textarea

```
$display_output = $entity_field_item['value'];

```
> 3 votes

# Answer
you can use http://drupal.org/project/computed\_field. Computed fields are populated with PHP code. You may choose to store your computed field in the database , or have them "calculated" on the fly during node views.
> 1 votes

---
Tags: entities
---


# Question
Title: How to display the blocks to display in certain page in Drupal?
Consider a module deserts:

* page1:- `deserts/*`
* page2:- `deserts/*/*`
* page3:- `deserts/*/*/*`

A dynamic content ...

I have three blocks, namely a,b and c:

* **Block a** should be displayed only in page1
* **Block b** should be displayed only in page2
* **Block a** should be displayed only in page3

How should do that restriction?

# Answer
Use the context module. Though I'm not generally a fan of this module, this is one of the cases where it comes in handy.

Add a condition for a path. So if I want a block on page 1, but not page 2 or 3, I would write the paths like so, one for each block:

Case 1 - Block A

```
deserts/*
~deserts/*/*
~deserts/*/*/*

```

Case 2 - Block B

```
~deserts/*
deserts/*/*
~deserts/*/*/*

```

Case 3- Block C

```
~deserts/*
~deserts/*/*
deserts/*/*/*

```

The ~ means to exclude in this case. After that, add the block to the region you would like for it to show up. You can also add back in specific paths that might otherwise be excluded, and vice versa.
> 18 votes

# Answer
You can use the "Pages on which this PHP code returns TRUE (expert only)" visibility option. But putting PHP code in the database is, IMHO, a bad practice. Instead, consider using something like the Extended block visibility module or implementation of `hook_block_list_alter()` such as

```
function MODULE_block_list_alter(&$blocks) {
  global $theme_key;
  foreach ($blocks as $key => $block) {
    if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
      // This block was added by a contrib module, leave it in the list.
      continue;
    }
    switch ("{$block->module}_{$block->delta}") {
      case "moduleA_deltaA":
        if (arg(0) != 'deserts' || !arg(1) || arg(2)) {
          unset($blocks[$key]);
        }
        break;
      case "moduleB_deltaB":
        if (arg(0) != 'deserts' || !arg(1) || !arg(2) || arg(3)) {
          unset($blocks[$key]);
        }
        break;
      case "moduleC_deltaC":
        if (arg(0) != 'deserts' || !arg(1) || !arg(2) || !arg(3)) {
          unset($blocks[$key]);
        }
        break;
    }
  }
}

```

Note: There is probably a smarter way to implement your visibility rule.
> 4 votes

# Answer
You should be able to get this to work using 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 intercept the various URLs corresponding your page1, page2 and page3.
> 0 votes

---
Tags: blocks, 7
---


# Question
Title: How to display a block only for an article with a specific node id?
I have quickly seen view reference and context module. Though they can display a view or block to a specific content type, I'm not sure if they can do it within a specific node.

As an example: I want to display a block only for an article with node id 3.

Can that be done?

# Answer
I would steer clear of using PHP for block visibility. If you type something wrong you can break any number of things.

Just go to your block settings, and take a look at the vertical tabs at the bottom of the page. The first option is *Pages*. Just change the radio button to "*Only the listed pages*" and enter *node/3* in the box.

**EDIT**

If you use the Views Reference module mentioned in your question, then you can quite easily embed a Views block as one of your fields just as any other field. The field itself can't be exclusive to a node ID, only an entity type. However, you could just leave it blank for the other entities of the same type and use Field Permissions if you are worried about other people using the field incorrectly/at all.

One unrelated helpful hint with Views Reference - I generally tag my "reference-able" views with the same tag (i.e. Embeddable, Referenceable e.t.c.). then you can easily select which Views to make available to the Views Reference field.

You MIGHT be able to embed blocks with Entity Reference combined with BEAN or Boxes, but I'm not 100% sure. Failing this you are probably looking at breaking up the entire `$content` variable in the template and embedding it yourself (which would mean much more maintenance if fields get added or removed), using Views and turning the whole content types into blocks that can be positioned (MUCH effort).
> 3 votes

# Answer
To render something inside a node body, you need an *input filter* to be able to write something like `[block:foo:bar]` and have the `bar` block from the `foo` module rendered. Unfortunately, a dedicated module does seems to exists on Drupal.org. Actually, one exists but is for Drupal 5 and has only a development release.

Using the PHP filter as suggested in others answers is an easy option. But this is a hacky one and not recommended. It opens to gate to a lot of abuses and potential headache debugging code stored in the database.
> 1 votes

# Answer
You could try the Insert Block module. Still in dev, but may be useful.
> 0 votes

# Answer
You should be able to get this to work using 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 intercept the URL corresponding to your article, which appears to be a node, with `node id = 3`.

Adding a Rules Condition like "if it is `/node/3`" is really like a getting started with Rules Conditions. If needed, just copy (import) the Rules example included in my answer to "How to make the permissions of a module more granular?" and finetune it a bit to fit your needs.
> 0 votes

# Answer
**NEW**

Enable `php filter` module , `add new content` in `body` section do something like this picture

(load your module accrding below notes)

---

if we wanted to place this custom block into a page, we would simply substitute these values into our PHP code snippet (which we place in a node (page or other content type)) as follows:

```
Drupal 7

<?php
$block = module_invoke('block', 'block_view', 26);
print render($block);
?>

```

Drupal 6 And Earlier

```
<?php
$block = module_invoke('block', 'block', 'view', 26);
print $block['content'];
?>

```

Notice that the middle two terms ('block', 'view') always stay the same. You're simply updating the first and last term.
> -2 votes

---
Tags: nodes, blocks
---


# Question
Title: MathJax(LaTex) equation shows in the CKeditor body area but not on the final webpage?
I am using CKEditor module and have enabled MathJax option. When I use MathJax it works in the CKeditor and shows teh eqiation, but on the final display webpage instead just showing equations it is showing all code. What could be the reason and solution?

# Answer
Check Manage Display in your content type and ensure it's using the proper text format. I think Mathjax has to be at the bottom of the list as well in the format settings.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Access denied when enabling or setting by default a theme (on Nginx)
I get an *Access denied* error page when attempting to **enable** or **set by default** a theme. It is kinda weird as I am allowed to perform other admin tasks.

I checked that my user is an administrator and it has all the permissions granted. I also made other checkings that I found in Drupal's forums and Drupal Answers but everything seems to be OK.

I have a *standard* install with no additional modules. Watchdog logs show the access denied warnings from `http://drupal-testing/admin/appearance/enable?token=<...>&theme=encoreweb`. In addition to check the permissions of my user, I reviewed `settings.php` to verify `$cookie_domain` was commented.

I've found that I'm not the only one with this problem, but I couldn't come to a conclusion.

# Answer
I've got a solution after several hours working on it.

I am using **Nginx** instead of Apache and I did not configure it to add the query string in the rewriting to `index.php`. So neither the `token` nor the `theme` parameters were reaching the script and `system_theme_enable()`/`system_theme_default()` (located in `/modules/system/system.admin.inc`) always returned `MENU_ACCESS_DENIED`, which I consider to be a very confusing behavior by the way.

This is how the server config looks like now and makes it work:

```
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

```
> 3 votes

# Answer
Adding to this question my specific scenario. I had installed Drupal 8.0.3 on Debian 8 (jessie), with php5-fpm and nginx. The install seemed to go flawlessly, until I tried to add a theme. I got "Access Denied" when attempting to set default theme from the administration page.

I had followed some guides for NGINX/Drupal installs, and wound up with the following section in my nginx.conf:

```
location / {
    try_files $uri $uri/ /index.php;
}

```

Per this answer on drupal.org, the `$args` parameter worked for me, updating the section to:

```
location / {
    try_files $uri $uri/ /index.php?$args;
}

```
> 0 votes

---
Tags: installation
---


# Question
Title: How to use form_set_value for a select list field?
Drupal 7. in my validate form function, I use form\_set\_value to set the value for the field "statut\_metier" to 'draft'

If my field is a text field, this code works :

```
form_set_value($form['field_statut_metier'][LANGUAGE_NONE][0]['value'], 'draft', $form_state);

```

If my field is a list(text) field, with the key for the value 'draft' = 5

I can't manage to have the form\_set\_value function work.

Using Devel and dpm() I have search to reach this field value :

I have tried :

```
form_set_value($form['field_statut_metier2'][LANGUAGE_NONE]['#value'][0], '5' , $form_state);

```

but it doesn't work.

Any idea ?

# Answer
> 1 votes
```
<?php form_set_value($form['field_statut_metier2'][LANGUAGE_NONE], array(0 => array('value' => 2)), $form_state); ?>

```

From the form\_set\_value() documentation on the first argument:

> you can just pass in the element from the $form array, although the only component that is actually used is '#parents'

Alternatively you can do:

```
<?php $form_state['values']['field_statut_metier2'][LANGUAGE_NONE][0]['value'] = '2'; ?>

```

... which is what form\_set\_value() does anyways.

---
Tags: forms
---


# Question
Title: Token [commerce-order:payment-method-information] does not display anything
I 've tried adding a token \[commerce-order:payment-method-information\] for emails , but the token does not work or does not display anything in the email sent . Please help

# Answer
A couple of things.

1. Have you updated removed the text in the **Information** field on the payment's configuration page:
2. Do you have a `filtered_html` text-format? Is it configured correctly?
3. If you're not using this in tandem with Commerce Message, you'll need to be using it.
> 1 votes

---
Tags: commerce, rules
---


# Question
Title: Is there a way in D7 that allows for multiple links in an image in a slider?
Is there a way in Drupal 7 that allows for multiple links in an image in a slider?

# Answer
> 1 votes
### Views Slideshow

> Views Slideshow can be used to create a slideshow of any content **(not just images)** that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create

Then add a custom field to your view and put the links there.

---
Tags: 7, javascript
---


# Question
Title: Commerce Order id as seletion list in view filter and limit to 10
I am trying to make Order id as selection list exposed filter but couldn't make it possible.
I modified default order view by making clone, added block to view.This view block will be presented to the authenticated user where he can view his/her last 10 orders.

In views sort criteria order date is added which is in descending so that only most recent orders are fetched
Pager setting - Use pager: Display a specified number of items | 10 items

Order's details has to be shown when user selects any order no from select list.
Is it possible to make selection list of Order id?Is there any module for that?

# Answer
You can do it in views.

* Add a new view for the product display type.
* Add a relationship under "Advanced -\> RELATIONSHIP" with the product, something like "Content: Referenced product", check "Require this relationship".
* Add a filter in "FILTER CRITERIA" & choose "Commerce Product: Product ID" by help of added relationship, expose this filter.
* Show it wherever you want, like you can make tab in the profile page etc.
> 0 votes

# Answer
I was able to do this using the Views Selective Filters module.

* Install the module.
* Add the field to Filters using the (selective) version.
* And there you go.
> 0 votes

---
Tags: commerce, views
---


# Question
Title: How to restrict editing some node properties (like title / URL) for some users (roles)?
I would like to know how I can restrict editing some property of nodes (like title / Url) for some users (roles).

So if I give -moderator access- to some users, they don't start messing with urls and I have to make 301.

# Answer
If you want finer control over any field then you can implement `hook_field_access($op, $field, $entity_type, $entity, $account`) and provide/deny access.

> Determine whether the user has access to a given field.
>
> This hook is invoked from field\_access() to let modules block access to operations on fields. If no module returns FALSE, the operation is allowed.
> 2 votes

# Answer
There's a couple of modules that might suit your needs, like Automatic Nodetitles:

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

```

This depends on your permissions and set up of course...
> 0 votes

# Answer
In the Admin menu navigate to admin/people/permissions

Set the following tick boxes as you like...

Path\>Administer URL Aliases

Path\>Create and edit URL Aliases

You can do this with almost any aspect of your site...
> 0 votes

# Answer
You can also do that with a simple implementation of `hook_form_BASE_FORM_ID_alter()`.

```
function YOURMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'YOUR_NODE_TYPE') {
    $form['title']['#type'] = 'value';
    $form['title']['#required'] = FALSE;
  }
}

```
> 0 votes

# Answer
You can Use Title module to restrict changes on Title field. You could also try the WikiTools module for Node Title restrictions.

Here is one of the WikiTools module feature

> Move Protection: Disallow change of node titles for users without administer nodes permission.

As @iain maitland suggested you can give permissions to roles for URL Aliases.
> 0 votes

# Answer
Implementing such restrictions is pretty forward by using the Rules module for this. As a sample, consider this scenario:

* Don't allow updates to the title of a node of type "Article".
* But do allow users with a specific role (such as "*administrators*", but it can be any role) anyhow. So updates to the title should be allowed by such role (only).
* If an attempt to update a title of an article is discovered by a user who does not have the administrator role, then just ignore the attempted update to the title (but do save all other updates to the node).

To implement this scenario, just use this rule for it:

```
{ "rules_verify_updates_to_node_properties" : {
    "LABEL" : "Verify updates to node properties",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      },
      { "NOT data_is" : { "data" : [ "node-unchanged:title" ], "value" : "[node:title]" } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Tampering rejected ... An attempt to update the title of node with ID \u0022[node:nid]\u0022 was discovered (from \u0022[node-unchanged:title]\u0022 to \u0022[node:title]\u0022), by user \u0022[site:current-user]\u0022, who does not have the authorization to do so. The attempted update of the title has not been saved (all other updates were applied).",
          "type" : "error"
        }
      },
      { "data_set" : { "data" : [ "node:title" ], "value" : "[node-unchanged:title]" } }
    ]
  }
}

```

If somebody who is not an administrator (the role that corresponds to role id = "3") tries the above scenario (with the above rule enabled), that user will get a Drupal error message similar like this one:

> Tampering rejected ... An attempt to update the title of node with ID "`X`" was discovered (from "Original title of this article" to "Attempted update of title of this article"), by user "`Some.Userid`", who does not have the authorization to do so. The attempted update of the title has not been saved (all other updates were applied).

Obviously, `X` and `Some.Userid` will be replaced by the actual node ID and username.

Works like a charm ... Similar approach for any other node property ... And straight forward to apply for any other content type (instead of "Article"), or just all content types.
> 0 votes

---
Tags: 7, users
---


title: Latest Article Popup

text:
# Question
Title: Latest Article Popup
I've seen this functionality being used quite often especially on news sites where latest articles snippets/calls-to-action pop out of the side of the browser - See image below:

Any idea what is the most common way this implementation is handled in Drupal?

I had a look at a couple of Drupal modules but didn't strike it lucky.

# Answer
> 2 votes
Install Flippy module.

```
 1. Go to desired content type -> admin/structure/types/manage/<content_type>
 2. Click on Flippy Settings tab
 3. Select "Build a pager for this content type"
 4. Customize the module or template, theme as you want.

```

# Answer
> 0 votes
I'm pretty sure what you're looking for is slidebox. It's working quite well. AFter the install make sure you clear your cache and rebuild your registry. You'll also need to create some content (likely via blocks) and then drop that content into the right region. You could also likely use context.

---
Tags: 7, javascript, notifications
---


# Question
Title: Display field in views-view-field--field_title.html.twig
If I have view with fields:

```
field title [hidden]
field text [hidden]
field image [hidden]
field display

```

and I make rewrite in "display" field with "title" and "text" field added, how can I print content of field "image" (url of this image) with views-view-field--field\_display.html.twig? I need wrapper with image url from this field. I see all available variables (view, field, row, output) in template and suggestion to fetch output with construct:

```
data = row[field.field_alias]

```

but when I try to write twig code with my field\_image alias it's not showing me anything. Field with image is set up to display just url to image. I translated few code lines from drupal 7 to twig, but I am unable to see anything in kint, just dump show me some key strings. Views create block and I am placing this block on my page.

What I am doing wrong?

# Answer
> 1 votes
### URL FORMATTER module

> This module add a url formatter for image field. Then you can output image url directly.

Enable the module, then in views, click on your image field, and change the Formatter to Image url.

```
{{ fields.field_image.content }}  // will display url instead of picture

```

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


# Question
Title: How to get collapse text to open below admin menu?
I use the collapse text module on my site, when the collapsed text is longer than the screen the collapsed text header gets hidden under the admin menu when you open the collapsible. How can I make it so that it opens and then focuses the header to be just under the admin menu?

if you go to https://arupconsult.com/content/immunoglobulin-disorders/?tab=tab\_item-2 and open one of the collapsibles you will see that the header is at the very top of the screen, and when I am logged in to the site the admin menu sites on top of it.

This is a screenshot of one of the collapsibles just opened while logged off. Notice how IgM is right at the top of the screen.

This is a screenshot of the same collapsible just opened, but I am logged on. Notice how IgM is now hidden below the admin menu.

# Answer
> 0 votes
This is a CSS issue; what you need is to move the named anchors up a bit for administrators.

Here's a sample code:

```
/* If you are using the core Toolbar module. */
body.toolbar a[name],
/* If you are using the contrib Administration Menu module. */
body.admin-menu a[name] {
  position: relative;
  display: block;
  visibility: hidden;
  /* This value will be different for Toolbar/Administration Menu modules. */
  top: -30px;
}

```

---
Tags: 7, theming
---


# Question
Title: hook_node_update hitting a wall with a loop I created
I have a taxonomy multi-select list that is used to create/delete entries in a field collection in my node. I'm trying to make it so that if the user deselects an item from the taxonomy list, the corresponding field collection item is removed from the node. I'm running into an issue when the user deselects a single option because of the way my code runs but I can't figure out how to get around it:

* I compare the selected options in my taxonomy list
* I look for them in the field collection
* If they don't match, I add the differences to two arrays
* I loop through one array to remove the field collection item if it's not selected in the taxonomy list AND
* I loop through the other array to add the field collection item if it's on the taxonomy list but not the field collections

With one option difference, my code seems to delete and add it back so there is no visible change. It works if I make multiple selection changes. I believe the issue is that -\>delete() and -\>save() save the node as well so my code runs more than it needs to.

```
function commitments_node_update($node) {

    if($node->type == 'commitment') {
        if (!empty($node->field_conditions['und'])) {
            $condition_name = array();
            $fc_name = array();
            //Create array of all FC conditions
            foreach ($node->field_conditions['und'] as $key => $value) {
                $fc = entity_load('field_collection_item', array($value['value']));
                foreach($fc as $condition) {
                    $fc_name[] = $condition->field_condition_title['und'][0]['value'];
                }
            }

            //Create array of all selected conditions
            foreach ($node->field_commitment_conditions['und'] as $conditions){
                $tid = $conditions['target_id'];
                $term = taxonomy_term_load($tid);
                $condition_name[$tid] = $term->name;

            }
            $fc_diffs = array_diff($fc_name, $condition_name);
            $condition_diffs = array_diff($condition_name, $fc_name);

            //Remove deselected conditions from FC
            foreach ($fc_diffs as $fc_diff) {
                foreach ($node->field_conditions['und'] as $item) {
                    $fc = entity_load_single('field_collection_item', $item['value']);
                        $fc_name_search = $fc->field_condition_title['und'][0]['value'];
                        if ($fc_diff == $fc_name_search) {
                            $fc->delete();
                        }
                }
            }

            //Add new conditions to FC
            foreach ($condition_diffs as $key => $value) {
                $term = taxonomy_term_load($key);
                $condition = $term->field_condition['und'][0]['value'];
                $condition_name = $term->name;

                $condition_fc = entity_create('field_collection_item', array('field_name' => 'field_conditions'));
                $condition_fc->setHostEntity('node', $node);
                $condition_fc->field_condition_title[LANGUAGE_NONE][0]['value'] = $condition_name;
                $condition_fc->field_condition[LANGUAGE_NONE][0]['value'] = $condition;
                $condition_fc->save();
            }

        }
    }
}

```

# Answer
> 0 votes
Thanks to #drupal on IRC, I now only run the code once by creating a static cache:

```
function commitments_node_update($node) {

    if($node->type == 'commitment') {
        if (!empty($node->field_conditions['und'])) {
            static $cache = array();
            if(array_key_exists($node->nid, $cache)) {
                return;
            }
            $cache[$node->nid] = true;
            $condition_name = array();
            $fc_name = array();
            //Create array of all FC conditions
            foreach ($node->field_conditions['und'] as $key => $value) {
                $fc = entity_load('field_collection_item', array($value['value']));
                foreach($fc as $condition) {
                    $fc_name[] = $condition->field_condition_title['und'][0]['value'];
                }
            }

            //Create array of all selected conditions
            foreach ($node->field_commitment_conditions['und'] as $conditions){
                $tid = $conditions['target_id'];
                $term = taxonomy_term_load($tid);
                $condition_name[$tid] = $term->name;
            }

            $fc_diffs = array_diff($fc_name, $condition_name);
            $condition_diffs = array_diff($condition_name, $fc_name);

            //Remove deselected conditions from FC
            foreach ($fc_diffs as $fc_diff) {
                foreach ($node->field_conditions['und'] as $item) {
                    $fc = entity_load_single('field_collection_item', $item['value']);
                        $fc_name_search = $fc->field_condition_title['und'][0]['value'];
                        if ($fc_diff == $fc_name_search) {
                            $fc->delete();
                        }
                }
            }

            //Add new conditions to FC
            foreach ($condition_diffs as $key => $value) {
                $term = taxonomy_term_load($key);
                $condition = $term->field_condition['und'][0]['value'];
                $condition_name = $term->name;

                $condition_fc = entity_create('field_collection_item', array('field_name' => 'field_conditions'));
                $condition_fc->setHostEntity('node', $node);
                $condition_fc->field_condition_title[LANGUAGE_NONE][0]['value'] = $condition_name;
                $condition_fc->field_condition[LANGUAGE_NONE][0]['value'] = $condition;
                $condition_fc->save();
            }
            unset($cache[$node->nid]);
        }
    }
}

```

---
Tags: nodes, hooks, entities
---


title: load one-off page fast

text:
# Question
Title: load one-off page fast
I want to create a landing page for my Google Ads on my site so that potential customers will be able to download and see the page very quickly. My site can be a bit heavy with CCS and javascript and other stuff sometimes.

All I want is to avoid losing potential clients due to a slow website. So I wonder if there's a simple way of the landing page being a light version of my site (with links to the "real" drupal site).

Many thanks

Oli

# Answer
If you want your website to load fast, you need to cache.

Go to Performance (/admin/config/development/performance)

and enable caching and aggregate css and javascript
> 1 votes

# Answer
I agree with No Sssweat. You also can use Google Page speed to guide you.

Some other comment problem is images. You can use this link to help you solve the problem as well.
> 0 votes

---
Tags: theming
---


# Question
Title: How can one run drush from project root when using multiple site configurations?
I have projects configured with multisite configuration, with folder structure as follows: `sites/local.domain`,`sites/staging.domain.com`, `sites/domain.com`.

All is well, except for one detail: I cannot run drush from project root directory anymore. I need to cd up to the current configuration folder.

Is there a way around this?

# Answer
> 3 votes
Try `drush --uri=http://local.domain status` from the root directory.

Also, you can create a file `$HOME/.drush/aliases.drushrc.php`, and define site aliases for each of your site. Then, `drush @local status` can be used.

Your aliases file would look something like this:

```
$aliases['local'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'http://local.domain',
);
$aliases['staging'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'http://staging.domain.com',
);
$aliases['live'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'http://domain.com',
);

```

However, although it is off topic for your question, I must also mention that the multisite configuration you have set up here fails to meet the basic requirements for a viable dev -\> test -\> live workflow. In this configuration, your code is shared between all three environments. This means that when you update Drupal core on your dev site, the updated code will also be immediately applied to the live site, which affords no opportunity for testing. A propper dev -\> test -\> live workflow should use completely separate codebases for each environment, so that you may publish code on a controlled schedule.

Multisite can be useful in certain environments where you have a very large number of copies of the same code, e.g. separate live sites that want to share the same opcode cache. For simpler setups, it's easier to stick with single codebases for each environment.

---
Tags: 7, drush
---


# Question
Title: Automatic nodetitles and location tokens?
In a Drupal 7 site, I want to have automatic node titles taken from user contributed content.

I have Location 7.x-3.x-dev (enabled Location and Location CCK) and Automatic Nodetitles 7.x-1.x-dev.

The problem is location tokens in the automatic title generation tab of the content type are returning empty input. I have tried `[node:location:city:?]`, `[node:location:city:0]` and `[node:location:city]`, but all three return nothing.

Tokens from the other fields are showing their input properlu.

Any help will be greatly appreciated.

# Answer
> 0 votes
I have taken some good looks at your issue. At the moment I find that the code for Location CCK is problematic, I managed to make it work with the following modification:

```
diff --git a/contrib/location_cck/location_cck.module b/contrib/location_cck/location_cck.module
index b302960..443b6a0 100644
--- a/contrib/location_cck/location_cck.module
+++ b/contrib/location_cck/location_cck.module
@@ -657,9 +657,9 @@ function location_cck_tokens($type, $tokens, array $data = array(), array $optio
   $replacements = array();

   // Make sure we have a node.
-  if (isset($data['entity_type']) && $data['entity_type'] == 'node') {
+  if ($type == 'node') {

-    $node = $data['entity'];
+    $node = $data['node'];

     // Get the available fields from the location module.
     $available = location_field_names(TRUE);

```

The token that worked after this patching was specific to the CCK field I added to my content type:

```
[node:field_my_location_field:city]

```

**Alternatively**, for your goal "...to have automatic node titles taken from user contributed content...", you can use the Node Locations submodule, this works as expected out of the box. The following tokens

```
[node:location:city]
and
[node:location:city:0]

```

both worked fine in combination with Automatic Nodetitles.

Hope this helps!

---
Tags: tokens, location
---


# Question
Title: Is there any way not to use the Drupal Image-style system?
I upload mainly light images (around 40 kb's) to my site and also want to save room on my server and don't use 4 different folders for images --- is there any way to avoid using the Drupal image styles system? Can I safely remove the image style folders (or most of their files) and that's it? --- I will check all site pages afterwards and re add images if needed, I just don't have many pages (I have about 30). Thx.

# Answer
> 3 votes
The Drupal image style system let you upload an image in whatever form you choose, and the image style will transform it into the size, shape, etc. of the selected style according to preset rules that you find in the configuration for image styles.

One of the benefits of the Image style system is that it allows reuse of images in different styles. You just upload the image once, and than you can use a thumbnail size version in the teaser, and a large size in the main article - or two different styles of the same image in two different nodes, etc.

There is one folder per style (I believe there are 4 default styles, but you can create and add your own styles if you want to, and this will add more folders below the styles directory).

Drupal does not create a *copy* of the image for a particular style until that style is requested. While there are 4 folders, if you *don't* reuse an image, it will only be created in one style - meaning that there will be two copies of that image on your disk: The original, and the scaled, cropped, whatever, copy that Drupal has created for that style.

In other words, you need to condsider the (IMHO) substantial benefits of Drypal's image style system before you decide to get rid of it.

But if you don't want to use it, you can do without.

However it is a bit more involved than just removing the image style folder.

Basically, what you do is to resize, crop, etc. the image yourself, *before* you upload it to the site. Then you create (by hand) a link to the *original* that you've uploaded from whereever you want to use it. If you do this with all images, Drupal will never attempt to create a copy for a particular image style and the image style folder will be empty.

If you're *sure* you're never is going to allow Drupal to style an image, I suppose you can remove the image style folder at this point, but I would leave the empty folder it in place to avoid breaking the site if I at some point forget that I'm not supposed to use Drupal's image styles.

If you think that a lot of unused copies of images are living below the image styles folder, you can flush all (or a subset) with the following Drush CLI command:

```
drush image-flush

```

This leaves the file structure below the image styles folder in place, so if a flushed image is requested, it will automatically be recreated in the requested style.

# Answer
> 0 votes
If you don't want to use image styles, then you can change the display settings on each image field to use the "Original image" style.

Go to admin \> Structure \> Content types \> Page \[or your type here...\] \> Manage display.

For any image field, click the cog-wheel at the extreme right of the row, and select "Original image" from the drop down.

This will prevent Drupal from using it's image styles for any post of this (Page \[or your type here...\]) type.

Additionally, you *could* disable the image module to prevent the use of image styles. However, this will also have the (likely unwanted) effect of removing the upload-an-image ability - and will delete any existing images you have uploaded this way when the module is uninstalled.

I recommend, instead, leaving the image module enabled and instead configuring your posts not to use image styles where they are not wanted.

---
Tags: media
---


# Question
Title: How to allow visitors add option in poll?
I would like to have a poll for logged in and anonymous users to vote. In the poll, users are allowed to add in their own poll option and vote. (Just like how Facebook poll is working previously)

Is there any drupal way which I can do this? Or I need to use some combination of ways to achieve this?

# Answer
### Advanced Poll

> Advanced Poll is a replacement to Drupal's poll module and provides multiple voting systems, decision-making tools, and management options.

Then in permissions (`/admin/people/permissions`), allow anonymous and authenticated users to vote and add write in votes.
> 2 votes

---
Tags: 7, polls
---


# Question
Title: Warning to user for including cursing words in private message
Drupal 7. Drupal 6 had a way to configure a rule to check for disallowed words inside the body or subject line of a private message.

I am trying to adapt that rule to Drupal 7. The purpose of this check is to send a warning message to the sender (email or private message) if banned words are found in his message. This can be expanded to various actions, including a temporary ban then a permanent ban if the user persists.

Here is an export of the first rule (but I can't get it to work:)

```
{ "rules_warning_to_privatemsg_sender_about_curse_words_" : {
    "LABEL" : "Warning to privatemsg sender about curse words.",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_i18n", "privatemsg_rules" ],
    "ON" : { "privatemsg_insert" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "privatemsg-message:body" ],
          "match" : "word1|word2|word3",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Bad word!", "type" : "warning" } } ]
  }
}

```

Word1, word2, and word3 are the words to check for. They are separated by the "|" (pipe or vertical bar) character.

This format was agreeable with Drupal 6 but I am not sure if that still works with Drual 7.

**UPDATE:** After studying the Regex website, I was able to get the rule to work changing the expression. See my answer below.

# Answer
Finally found a format that works.

Contrary to what the Drupal documentation says, the format:

```
word1|word2|word3

```

does not work.

The proper syntax is:

```
^.*(word1|word2|word3).*$

```

i.e.: **caret** then **dot** then **star** then **open parenthesis** then **the words to search separated with a vertical bar** then **closed parenthesis** then **dot** then **star** then **dollar sign**.

Many words may be added between the parenthesis. No need to add the plurals as regex will match the singular inside the plural.

Reminder: Regex stands for REGular EXpression so this value must be selected at the bottom of the condition page.
> 1 votes

---
Tags: 7, rules, privatemsg
---


# Question
Title: Create drupal node programatically and set custom select list field
I have a Drupal 7 node with custom fields. I have no problem setting values to the single text fields but I'm not sure how to set my select list field to one of the allowed keys of the field.

This is the code I've tried to assign the select list to the 'pending' key.

```
$node->field_referee_status['und'][0]['tid'] = 'pending';

```

**Node creation code:**

```
// CREATE NODE
$node = new stdClass;
$node->type = 'referee';
$node->title = 'Referee report for xx';
$node->uid = $user->uid;
$node->status = FALSE;
$node->field_referee_status['und'][0]['tid'] = 'pending';
$node->field_referee_id['und'][0]['value'] = 'test';
$node->field_testff['und'][0]['value'] = "testworked";
node_object_prepare($node);
node_save($node);

```

**Question:** Does anyone know the correct way to assign the key value to a custom select list field when creating Drupal nodes programmatically?

# Answer
> 1 votes
With a select list, you need to store the key value of the custom field.

I just noticed that you're storing taxonomy term reference value, which means you should be storing the ***term ID*** and ***not the actual text value of pending.***

Theres a handy function which allows you to grab the TID based on a term name:

```
$term = taxonomy_get_term_by_name('pending');
$node->field_referee_status[LANGUAGE_NONE][0]['tid'] = $term->tid;

```

See the docs here.

**EDIT**

To save into a normal textfield select list:

```
$node->field_referee_status[LANGUAGE_NONE][0]['value'] = 'pending';

```

---
Tags: nodes, entities
---


title: Assign a workflow to a content type

text:
# Question
Title: Assign a workflow to a content type
I had defined a new workflow which has 3 states and I want to assign it to a content type. I had tried to make a workflow file type in manage field but when I try to edit it I can not choose my workflow type.

I only can select "-Select a value-" but my workflow type defined don´t appear.

Thank you in advanced.

# Answer
First, I have to make a configuration in "transition" tab (in the same place where I have defined states for my workflow). After that I can choose it.
> 0 votes

---
Tags: 7, workflows
---


title: Force page open in overlay

text:
# Question
Title: Force page open in overlay
I want to force admin pages open **only and only** in overlay. As you know if a link with an admin path is clicked it opens in overlay (if enabled). But if you write the URL to the browser, or use some deep link, or you are already in administration theme, the links expectedly wouldn't open in overlay.

How could I **force** the pages, even if the URL is entered to the browser's path, to open in overlay.

For example, if I type in the browser:

> www.example.com/admin/people

It should always open as:

> www.example.com/#overlay=admin/people

# Answer
> 1 votes
I really do not recommend doing this.

However, you can use a custom rewrite rule. You will have to create this in your .htaccess file yourself.

Rewrite anything with /admin/ to use the overlay.

# Answer
> 0 votes
You can use the context overlay module to achieve this, this way you can easily configure what pages should be opened in an overlay.

You'll need to install:

---
Tags: 7, modal-dialogs
---


# Question
Title: newsletter with export email to csv and import from csv features
i had use simplenews before, but there is no function to export or import email to csv file.

anyone know any module have such functions?

# Answer
Here's how to do that:

1. Install Views (you probably have this installed already).
2. Install Views data export module.
3. Create a new view that will show either "Simplenews subscriber" or "Simplenews subscription".
4. Add a new display of "Data export" type to that view. There you can choose the format (`.csv`, `.doc`, `.txt`, etc.) and configure other settings. Don't forget to set "Attach to" value to the page display you created in step #3.
> 0 votes

---
Tags: emails
---


# Question
Title: Editable field in view to display editable form only
I'm using the Editable Views module to create a view in which the user can edit the values of numerous fields.

Currently picking an editable table formatter and adding an editable field results in showing the current value of the field above and an editable form below it.

I would like to show only the form with the current value editable, is it possible?

If its possible with another module, please feel free to suggest.

# Answer
I was informed lately that another module fits better my requirements so instead of Editable Views, I had to use editablefields module.

Editable Fields provides you with an editable formatter which allows you to display the field as an editable form only.

Unfortunately it appears to be only on alpha2 for Drupal 7, but seems ok for my expectations.
> 2 votes

---
Tags: views
---