# Question
Title: Views change "Exclude from display" at run-time
Main question: How to change the value for "Exclude from display" on runtime, programmatically ?

Background: I am rendering a View programmatically. The View has attached Data Export to it (exporting to CSV) The view has multiple fields (42 actually).

On some action (hook\_node\_update, etc.), I load a node object. The node object has 2 fields of interest.

* `field_views_filter` = field that is using the Field Embed Views module and stores exposed filter settings
* `field_export_select_fields` = list(text) field that selects which of those 42 fields should be exported to csv. Sometimes all fields will need to be displayed, sometimes only 5 fields will have to be displayed.

Scenario: What I have tried:

```
<?php
function test () {
      // Loading arbitrary node
      $node = node_load(44165);

      $select_fields = array();

      $displayed_fields = array();
      foreach ($node->field_export_select_fields[LANGUAGE_NONE] as $key => $value) {
        $select_fields[] = $value['value'];
      }

      $name = 'MY_VIEW_NAME';
      $display = 'views_data_export_1';
      $view = views_get_view($name);
      $view->set_display($display);

      // Gets the exposed filters.
      $exposed_filters = $node->field_views_filter[LANGUAGE_NONE][0]['settings'];
      $view->set_exposed_input($exposed_filters);

      foreach ($view->display['views_data_export_1']->display_options['fields'] as $key_field => $value_field) {
        // This sets the value of "Exclude field from display to 1", but it is not working.
        $view->display['views_data_export_1']->display_options['fields'][$key_field]['exclude'] = 1;
      }
      $view->display['views_data_export_1']->display_options['fields']['title']['exclude'] = 0;

      $output = $view->preview();

      $file_string = 'sites/default/files/private/' . time() . '.xls';
      file_unmanaged_save_data($output, $file_string, FILE_EXISTS_REPLACE);

      $view->destroy();
    }

```

# Answer
You need to save your view with hidden fields and then load it again

```
<?php

function test () {
  // Loading arbitrary node
  $node = node_load(44165);

  $select_fields = array();
  foreach ($node->field_export_select_fields[LANGUAGE_NONE] as $key => $value) {
    $select_fields[] = $value['value'];
  }

  $name = 'MY_VIEW_NAME';
  $display = 'views_data_export_1';
  $view = views_get_view($name, TRUE);

  // Hide selected fields.
  foreach ($view->display['views_data_export_1']->display_options['fields'] as $key_field => $value_field) {
    if (in_array($key_field, $select_fields)) {
      $view->display['views_data_export_1']->display_options['fields'][$key_field]['exclude'] = 1;
    }
    else {
      $view->display['views_data_export_1']->display_options['fields'][$key_field]['exclude'] = 0;
    }
  }

  // Save view.
  views_save_view($view);
  // Load updated view.
  $view = views_get_view($name, TRUE);
  $view->set_display($display);

  // Gets the exposed filters.
  $exposed_filters = $node->field_views_filter[LANGUAGE_NONE][0]['settings'];
  $view->set_exposed_input($exposed_filters);

  $output = $view->preview();

  $file_string = 'sites/default/files/private/' . time() . '.xls';
  file_unmanaged_save_data($output, $file_string, FILE_EXISTS_REPLACE);

  $view->destroy();
}

```
> 1 votes

# Answer
Your question is still unclear to me, but anyway I recommend to use different `theme_hook_suggestion` for the `view` and based on the condition use the appropriate suggested hook. in `template.php`:

```
function YOURTHEME_preprocess_views_view_fields(&$variables)
{
    $view = $variables['view'];
    if($view->name == "your_view_name")
    {
          if($view->current_display == "some_custom_display"){
            $variables['somefield'] = $variables['fields_somefield'->content;
            if($condition_1 == true)
                $variables['theme_hook_suggestions'][]='views_view_fields__1ththeme';
            if($condition_2 == true)
                $variables['theme_hook_suggestions'][]='views_view_fields__2ththeme';
              ...
    }
}

```

now create files `views-view-fields--1ththeme.tpl.php` and `views-view-fields--2ththeme.tpl.php` in your theme directory. the `$somefield` is available in there and it returns the value of the `fields_somefield` field. In these files just print any field you want and no matter if they are set to be excluded from display or not, The output of the view is what you print in the theme file.

The is it possible to have one views-view--VIEWNAME--page.tpl for multiple views? is also helpful.

**As I said I didn't fully understand your question, if some thing is wrong with my answer just let me on it.**
> 0 votes

---
Tags: views
---


# Question
Title: How do I delete content (nodes) that a user no longer has the right to create?
Suppose a user of my site has had the right (the correct role with sufficient permissions) to create content of a certain type.

If the right (role) is taken away from them, how could I make the users content **automatically** be deleted? (the deletion doesn't have to be instant, eg. once a day is fine) i.e the content will be deleted from the moment they no longer have permissions to edit it or create such content.

# Answer
> -1 votes
This code gives you the basic idea:

```
$nodes = node_load_multiple(array(), array('type' => 'my_type'));// load node by certain type
foreach ($nodes as $node){
    $uid= $node->uid;//get the node author id
    $nid = $node->nid;// get the node id
    $author = user_load($uid);//load the author of the node
    if (!in_array('your_role', $author->roles)) { //the author has not your_role role
        node_delete($nid);
    }
}

```

if you copy this code in the `theme_preprocess_html` of your `template.php`, for every page it checks the nodes and its author roles and delete the node id its author has not the role.

If you need to run this code once a user role is updated, you can use Rules module :

I am not able to run this code right now, but it should work correctly. You can use devel module to correctly get the `$node` properties (`$nid` and `$uid`).

---
Tags: nodes, users
---


# Question
Title: Need clarification on adding JS to content item with JS injector and drupal_add_js
I want to put some js on my article. Original code form http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery\_hide\_p

is:

```
    <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").hide();
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me</button>

</body>
</html>

```

My article is at: http://xuzo.com/testing/node/44

**Here is what I have done**

1. put this code in content item source code:

```
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Click me</p>

```
2. Put this in JS Injector box:

```
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});

```

and this for URL:

```
node/44

```
3. put this in my /public\_html/testing/sites/all/themes/xuzo/template.php file:

```
drupal_add_js('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', 'external');

```
4. Flushed all cache
5. Not working!!! ;)

***Additionally...for this line of code to load JS files locally:***

```
drupal_add_js('misc/collapse.js');

```

Where to put the JS file? I take it misc can be any folder name? But where to put the files in relation to root? Sites/all ?

# Answer
1)Create a **scripts** named folder **sites/all/themes/script**

2)Create a file in script folder **your-theme-name.js**

3)Paste this **scripts\[\] = scripts/your-theme-name.js** in **.info** file of your theme

4)Put this code in content item source code:

```
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Click me</p>

```

4)In **your-theme-name.js** put this code

Try to give some unique classes to paragraph elements like:

```
If (jQuery("body").hasClass("some-unique-class-in-bodytag-of-your-page"))
{
jQuery("body").find("p").addClass("abc");
}

```

5)Again In **your-theme-name.js** put this code

```
   jQuery(document).ready(function() {
jQuery("button").click(function() {
   jQuery("p").hasClass("abc").hide();
   });
   });

```
> 1 votes

# Answer
### 1. Like Shrish mention your code needs to be like this

```
(function($) {
    // your code here
    $(document).ready(function() {
        $("button").click(function() {
            $("p").hide();
        });
    });

})(jQuery);

```

### 2. your code says `$("button").click(function() {` but in your html there is no button:

```
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Click me</p>

```

So change this to:

```
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>

```

### 3. Checkmark inline js in JS Injector
> 1 votes

# Answer
The problem is in your jquery code:

This is the error on your site: (Check browser console for this)

> TypeError: $(...).once is not a function

This is how you should be adding jquery code

```
(function($) {
    // your code here
    $(document).ready(function() {
        $("button").click(function() {
            $("p").hide();
        });
    });

})(jQuery);

```

OR, change your code to,

```
jQuery(document).ready(function() {
    jQuery("button").click(function() {
        jQuery("p").hide();
    });
});

```
> 0 votes

---
Tags: javascript
---


# Question
Title: Set exposed filter date programmatically
I would like to programmatically set an exposed filter for a field date (field\_date) in a view.

Date has to be \> of a specific date or between to dates.

I tried this, but it does not work. It ignores the filter.

```
$view = views_get_view('myview');
$view->set_display("default");
$view->get_exposed_input();

$exposed_filters["field_date_value_op "] = "between";

$exposed_filters["field_date_value"]["value"]["day"] = "";
$exposed_filters["field_date_value"]["value"]["month"] = "";
$exposed_filters["field_date_value"]["value"]["year"] = "";

$exposed_filters["field_date_value"]["min"]["day"] = 1;
$exposed_filters["field_date_value"]["min"]["month"] = 1;
$exposed_filters["field_date_value"]["min"]["year"] = 2014;

$exposed_filters["field_date_value"]["max"]["day"] = 1;
$exposed_filters["field_date_value"]["max"]["month"] = 12;
$exposed_filters["field_date_value"]["max"]["year"] = 2015;

$view->set_exposed_input($exposed_filters);
$view->execute();

```

Any idea? Thank you in advance.

# Answer
Use the below after set\_display line.

```
function mymodule_views_pre_view(&$view) {
  if ($view->name == 'myview_user'){
    $view->get_exposed_input();
    dsm($view->exposed_input['created']['min']);
    $view->exposed_input['created']['min'] = "2015-01-01";
    $view->exposed_input['created']['max'] = "2016-01-01";

    //$view->set_exposed_input($exposed_filters);
    $view->execute();
  }
}

```

Please refer the example
> 0 votes

---
Tags: 7, views
---


# Question
Title: Changing commerce_line item quantity to 3 decimal places
I need to change the precision of Drupal commerce quantities to 3 decimal places.

To do this I edited *drupal\_commerce\_line\_item* and changed the *quantity* field from `decimal(10,2)` to `decimal(11,3)`.

Is this OK? (don't want repercussions) and is there anything else I need to do?

# Answer
In theory, changing the `commerce_line_item` field's SQL (schema) definition ought to be enough. However, a cursory review of a few modules shows that some of them will round the value to 2 decimal places before using it, negating the change. You'll probably need to change it and then test it to ensure that every module you're using it with will work as you intend.
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Unable to update content or enable / disable module via Drupal Admin once migrate to live server
I have moved my website from local machine to live server, but after migration I can not save or update contents. After clicking on 'Save' button page refreshes without any changes. Also I can not enable or disable the drupal modules, and there aren't any errors displayed. Please help me out in this and do let me know solution in isolating this issue.

# Answer
problem was server firewall called mod\_security. It's purpose is to stop hackers from inserting mysql\_query type commands into your website. So, I solved this problem by disabling the mod\_security service.
> 1 votes

---
Tags: nodes, users, .htaccess
---


# Question
Title: Change page URL structure based on node field value
I'm using Pathauto to produce nice URLs for my Drupal 7 site, and have run into the need to edit the URLs based on a node field value.

Specifically, when the content is archived on my website, the URL needs to be automatically changed to include the substring 'archive'. So when editing this page:

```
www.mysite.com/mypage

```

and `node:field-status` is changed from `none` to `archived`, I need the URL to become:

```
www.mysite.com/archive/mypage

```

Also, pages that already feature a substring, such as `mysite.com/blog/mypage` would ideally have the new substring prepended to the relative URL, so:

```
www.mysite.com/archive/blog/mypage

```

I have tried using Flags and Rules to rewrite the URL pattern based on the field value, but with no luck. Any ideas?

# Answer
> 0 votes
You can build a small module, called `myalias` and use this code to generate custom alias

```
<?php
function myalias_node_insert($node){
    //here you can access the $node variable and get its fields value
    $node->path['alias'] = 'your_custom_path';
}

```

You can also change the hook to `myalias_node_update($node)` to alter the node alias once it is updated.

# Answer
> 0 votes
You can use `hook_pathauto_pattern_alter()`. Something like this should work for a boolean field (untested)...

```
/**
 * Alter the pattern to be used before an alias is generated by Pathauto.
 *
 * This hook will only be called if a default pattern is configured (on
 * admin/config/search/path/patterns).
 *
 * @param string $pattern
 *   The alias pattern for Pathauto to pass to token_replace() to generate the
 *   URL alias.
 * @param array $context
 *   An associative array of additional options, with the following elements:
 *   - 'module': The module or entity type being aliased.
 *   - 'op': A string with the operation being performed on the object being
 *     aliased. Can be either 'insert', 'update', 'return', or 'bulkupdate'.
 *   - 'source': A string of the source path for the alias (e.g. 'node/1').
 *   - 'data': An array of keyed objects to pass to token_replace().
 *   - 'type': The sub-type or bundle of the object being aliased.
 *   - 'language': A string of the language code for the alias (e.g. 'en').
 *     This can be altered by reference.
 */
function MYMODULE_pathauto_pattern_alter(&$pattern, array $context) {
  // Exit if we don't care about this entity type and bundle.
  if ($context['module'] != 'node' || $context['type'] != 'article') {
    return;
  }

  // Exit if the archive field doesn't exist or isn't set.
  $node = $context['data']['node'];
  assert('$node');
  $items = field_get_items($context['module'], $node, 'FIELDNAME');
  if ($items === FALSE || empty($items[0]['value']) {
    return;
  }

  // Modify the pattern.
  // (I'd try to avoid hardcoding any patterns in this code, but rather use
  // variables. These can either be updated programatically or tied to a UI
  // element.)
  $pattern = '...';
}

```

---
Tags: 7, uri
---


# Question
Title: How to fix Admin Menu that's broken on live site, working on identical dev site
I've got an installation of Drupal Commerce Kickstart, and I've been developing it on my LAMP stack on my computer. The admin menu's working perfectly there. I recently migrated the site to the live server (also a LAMP stack), and Admin Menu simply doesn't work. Everything else works.

**Specifically**, it's being displayed (unstyled) at the bottom of the page on front-end pages (Zen subtheme) and admin pages (Seven subtheme). Sometimes it doesn't even show up at the bottom (it's completely missing).

**More info**: The version of PHP and MySQL are recent on both sites.

I used Backup and migrate to do the DB migration, with no issues. I've also just updated to the latest core version (7.37), and that made no difference.

Strangely, every other module seems to be working fine, except Admin Menu. And I've never encountered this before on any other Drupal sites I've built.

I have a feeling it's something to do with Commerce Kickstart's interference in the Management menu.

**Updates:** things I've tried that didn't work:

* I've cleared Drupal cache, browser cache, site-specific cookies.
* changing all the Admin Menu settings.
* uninstalling and re-installing the module.
* using a different browser: tried Firefox and Chrome.

# Answer
> 1 votes
It was a file permission problem!

It turns out that, as per Apache's and Drupal's recommendations, I had set the permissions for all folders/directorys in my sites/all/\* folder to be 750, and 640 for files. So for those who don't know, that means that 'others' (people who don't 'own' the files or folders) can't access them in any way.

It seems that my web host had incorrectly not assigned Apache to the correct group so that it would be able to run using those safe permissions (I know why, and I'm going to send them an irritated email asap).

I simply used Filezilla to recursively change the permissions to 755 and 644 respectively. Not quite safe, but I can change them back later.

# Answer
> 0 votes
From issue nr 2322605:

> This is rather a common problem, particularly if you are using the contributed admin\_menu rather than the Toolbar module in core. Clearing caches may help. (If you have alternative caching such as memcache that can make a normal cache clear fail in part.) You may also check whether it works when you switch theme to a Drupal core theme.

Another potential solution is to uninstall/reinstall the Admininistration menu module (as Clive also suggested in the comment).

Exceptionally, it may also be caused by a php memory limit problem (increase the limit in that case).

# Answer
> 0 votes
If the admin menu has issues it could be because of the following 3 points:

1. If you get warnings about not being able to store temporary items you may need to change the temp location. Do this on the File System settings page at admin/config/media/file-system
2. If site appears funny – with content but not styled try deleting (they will be remade automatically)

Sites/default/files/css

Sites/default/files/js

Sites/default/files/ctools

3. Try disabling and re-enabling the CSS and JS caching in the performance page admin/config/development/performance

---
Tags: migrations
---


# Question
Title: Disqus not showing on panel page only (panel set as homepage)
Version Disqus `7.x-1.12`
Drupal `7.38`
Disqus is only not showing on my panel page. On all the other pages, Disqus is shown. It has shown before on the same panel. I wish I knew all the things I did between the last time it appeared and when I noticed, but I don't.

# Things I tried to no avail:

in the configuration settings (`admin/config/services/disqus`)

I tried adding the block into a region
* **Visiblity-** All node types selected; *Location:* Block
* **Default options-** All node types selected
* **Behaviour-** *Localisation support:* unchecked; *Inherit User Credentials:* checked
* **Advanced-** *User Access Token:* correct value; *Public Key:* correct value: *Secret Key:* correct value;
**Visibility** also set it to *content area* and weight tried 0, 50, 100, -100

### Drupal Issue 1159690:

Doesn't correlate entirely to my issue because the HTML seems to be there (and not with me), but I suppose it was worth trying some ideas still.

Comment #9 insert `<?php
print render($content['disqus']);
?>` into template

Comment #60 suggest to simply hit save again on said configuration page and somehow that would be all it took.

### Drupal issue 928354

About panels integration. Patch at comment #17 no worky.

### panel config:

Tried inserting the disQus block in every possible region of my Panel to no avail.

I also tried this (as mentioned in above issue )

> \# in /admin/settings/disqus underneath the Visibility section, choose the Block option in the Location dropdown menu.
>
> Then you just select the "Disqus Comments" block from within the panels interface under the Miscellaneous tab.

On my panel page, when I do a `dpm()` of `$node` inside of the `node.tpl.php` file, there are 2 node objects in my *Krumo*. In each object there actually is an array for Diqus. This makes sense, because it is Disqus applied to the nodes *inside* of the panel. These comments don't show either though, but I don't want them to of course. I want 1 Disqus applied to my panel obviously instead.

### Blocks configuration

I put the Disqus comments block in different regions of my theme, still same problem: showing up in other regions

Tried activating a different theme, same problem: Disqus shows on every page except the panel.

Updated the module to `7.x-1.12+5-dev`, flushed cashes. Nothing changed.

# Answer
A workaround I found in this comment #5 out of the Disqus issuequeue adding disqus on the frontend.

```
    function HOOK_preprocess_page(&$vars) {
  if (module_exists('disqus')) {
    $identifier = $_GET['q'];
    if (strstr($identifier, 'path/to/add/comments/to')) {
      $domain = variable_get('disqus_domain', ''); // A.K.A. short name
      $url = url($_GET['q'], array('absolute' => true));
      $title = drupal_get_title();
      drupal_add_js(drupal_get_path('module', 'disqus') . '/disqus.js');
      drupal_add_js(array('disqus' => array('domain' => $domain, 'url' => $url, 'title' => $title, 'identifier' => $identifier)), 'setting'); // Add to the Drupal.settings for the script above to be able to pick it up.
      // Add the div to the page for the Disqus embed script to be able to drop in the comments code dynamically.
      $vars['page']['content']['system_main']['main']['#markup'] .= '<div id="disqus_thread"></div>';
    }
  }
}

```

Still curious about what it is in the backend that made the comment box disappear below the Panel though. I also disabled all the modules apart from the Disqus, panel en core, but still nothing.
> 0 votes

---
Tags: 7, panels, comments
---


# Question
Title: Views single field themeing with custom variables
How do I pass a variable from a preprocess hook to a template file for a single field, that is view files starting with

> views-view-field--

I want to know what are the preprocess functions that can be used for this purpose. Because, whenever I try to set a variable using `hook_preprocess_views_view_fields` it is only renderable at sytle/row level, but never at single field level.

Hope Im clear with my query. Any help appreciated.

# Answer
> 1 votes
I think it's just that there are two similarly-named theme implementations: `views_view_field` and `views_view_fields` (trailing *s*). Generally you can take the name of the template file before the first double-dash to find the theme implementation name, so if the template starts with `views-view-field--` you'd expect the preprocess to be `hook_preprocess_views_view_field()`. (That naming pattern's not guaranteed though.)

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


# Question
Title: Taxonomy List with Node Count, exclude those with 0
I have a view that is used to display blog categories on a blog with the corresponding count of blog posts in that category. In cases where there are 0 blog posts, I want to exclude that item from the list. Here is my view:

```
$view = new view();
$view->name = 'blog_categories';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Blog Categories';
$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['title'] = 'Blog Categories';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$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'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Header: Global: Unfiltered text */
$handler->display->display_options['header']['area_text_custom']['id'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['table'] = 'views';
$handler->display->display_options['header']['area_text_custom']['field'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['content'] = 'Categories:';
/* Relationship: Taxonomy term: Content with term */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: COUNT(DISTINCT 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']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count_distinct';
$handler->display->display_options['fields']['nid']['label'] = '';
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['nid']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['nid']['prefix'] = '(';
$handler->display->display_options['fields']['nid']['suffix'] = ')';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'blog_categories' => 'blog_categories',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['block_description'] = 'Blog Categories Menu Block';
$translatables['blog_categories'] = array(
  t('Master'),
  t('Blog Categories'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Categories:'),
  t('node'),
  t('Block'),
  t('Blog Categories Menu Block'),
);

```

Here is a screenshot of the view config page and one of the output:

How do I configure the view to exclude terms with a 0 count?

# Answer
> 0 votes
Added the count NID field as a filter:

1. Add new filter
2. Select Content: Nid
3. Set Aggregation type to Count DISTINCT
4. Set Relationship to node (should be default)
5. Set Operator to Is greater than
6. Set Value to 0

Here is the new view:

```
$view = new view();
$view->name = 'blog_categories';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Blog Categories';
$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['title'] = 'Blog Categories';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$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'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Header: Global: Unfiltered text */
$handler->display->display_options['header']['area_text_custom']['id'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['table'] = 'views';
$handler->display->display_options['header']['area_text_custom']['field'] = 'area_text_custom';
$handler->display->display_options['header']['area_text_custom']['content'] = 'Categories:';
/* Relationship: Taxonomy term: Content with term */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: COUNT(DISTINCT 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']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count_distinct';
$handler->display->display_options['fields']['nid']['label'] = '';
$handler->display->display_options['fields']['nid']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['nid']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['nid']['prefix'] = '(';
$handler->display->display_options['fields']['nid']['suffix'] = ')';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'blog_categories' => 'blog_categories',
);
/* Filter criterion: COUNT(DISTINCT Content: Nid) */
$handler->display->display_options['filters']['nid']['id'] = 'nid';
$handler->display->display_options['filters']['nid']['table'] = 'node';
$handler->display->display_options['filters']['nid']['field'] = 'nid';
$handler->display->display_options['filters']['nid']['relationship'] = 'nid';
$handler->display->display_options['filters']['nid']['group_type'] = 'count_distinct';
$handler->display->display_options['filters']['nid']['operator'] = '>';
$handler->display->display_options['filters']['nid']['value']['value'] = '0';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['block_description'] = 'Blog Categories Menu Block';
$translatables['blog_categories'] = array(
  t('Master'),
  t('Blog Categories'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Categories:'),
  t('node'),
  t('Block'),
  t('Blog Categories Menu Block'),
);

```

---
Tags: 7, views, taxonomy-terms
---


title: Migrate Dimensions

text:
# Question
Title: Migrate Dimensions
I am trying to migrate to a physical dimensions field with no success. I will prepare the data in prepareRow but before that I was just trying to figure out how it should work. I tried setting default values like this:

```
$this->addFieldMapping('field_productdimensions')->defaultValue(4);
$this->addFieldMapping('field_productdimensions:width')->defaultValue(1);
$this->addFieldMapping('field_productdimensions:length')->defaultValue(2);
$this->addFieldMapping('field_productdimensions:height')->defaultValue(3);
$this->addFieldMapping('field_productdimensions:unit','cm');

```

The above did not insert any data. I also tried with values in prepareRow like this:

```
    $current_row->dimensions = array(
      'length' => 1,
      'width' => 2,
      'height' => 3,
      'unit' => 'cm'
    );

```

All other fields are inserted properly. Any idea what I am doing wrong?

# Answer
> 1 votes
I figured it out, although it seems weird that width gets the length value, this is how it works in my case. Nothing else was needed in prepareRow function.

```
    $this->addFieldMapping('field_productdimensions','width');
    $this->addFieldMapping('field_productdimensions:width','length')->defaultValue(null);
    $this->addFieldMapping('field_productdimensions:length','length')->defaultValue(null);
    $this->addFieldMapping('field_productdimensions:height','height')->defaultValue(null);
    $this->addFieldMapping('field_productdimensions:unit','length_units');

```

# Answer
> 0 votes
As I struggeled with this issue today, you actually need to leave out the length mapping, otherwise your migration will fail and all your fields will be empty.

```
$this->addFieldMapping('field_productdimensions','length')->defaultValue(null);
$this->addFieldMapping('field_productdimensions:width','width')->defaultValue(null);
$this->addFieldMapping('field_productdimensions:height','height')->defaultValue(null);
$this->addFieldMapping('field_productdimensions:unit','length_units')->defaultValue('mm');

```

Also note that the value you try to put in is strictly an integer. A value with a space behind it will not work.

---
Tags: migrations
---


title: Setting up REST post request

text:
# Question
Title: Setting up REST post request
I am having issues sending a POST request to create a node with Drupal 8 Core REST. Here are the steps I have went through several times. Note that these steps are in effort to produce a working example, I am not worried about the security implications as of yet.

1. Install latest version of drupal 8
2. Enable all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization)
3. Go to permissions page. Find RESTful Web Services permissions and allow delete, get, patch, and post for all users. Find Node Article permissions, allow create, delete and edit for all users.
4. Launch Dev HTTP Client in Chrome. Input the following request:

After hitting Send, I receive the following message which I believe should be a 201 and not a 200 if a node were to successfully be created. I think the REST part is working, its just I cant seem to figure out how to get POST to create a node.

I am having trouble finding any documentation on making post requests to Drupal 8 REST. Insight into how to construct these requests so that Drupal can parse them successfully would be very helpful.

# Answer
> 1 votes
I posted the solution on the (identical) issue on drupal.org: https://www.drupal.org/node/2472451#comment-9903259 Also see the Dev HTTP Client screenshot attached in that comment.

Basically there are a couple of things wrong in your example:

* endpoint is /entity/node
* add Accept header "application/json"
* add CSRF token (which can be requested via /rest/session/token)

# Answer
> 6 votes
As I still ran into a lot of 403 errors, I'll summarize my overall solution (Drupal 8.0.1).

## Setup and configuration

Enable all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization). Enable the relevant permissions of RESTful Web Services and for creating the relevant Nodes.

## Get a CSRF token

`GET http://your-drupal8/rest/session/token`

## POST to create a new node

`POST http://your-drupal8/entity/node?_format=hal+json`

Note that the URL for POST seems to be /entity/node rather than /node.

### Headers

```
Authorization: Basic QWRt...
X-CSRF-Token: zCf...

```

### Data

```
{
"title": [
  { "value": "atest2" }
],
"type": [
  { "target_id": "article" }
],
"_links": {
  "type": { "href": "http://your-drupal8/rest/type/node/article" }
}
}

```

---
Tags: 8
---


title: code change alert/email

text:
# Question
Title: code change alert/email
Is there a module to help me receive email for any change in drupal site ?

https://www.drupal.org/project/logging\_alerts this module help a lot in log in / log out and add content .. but I need to know about any change even without login to Drupal CMS ..

thanks in advance.

# Answer
First off, it sounds like you should install the Paranoia module, as it will reduce the likelyhood of changes happening.

Then, since you already have logging\_alerts, you could program a hook\_cron to md5 hash all your files, and send to watchdog a high-severity message when one changes. This would then get kicked forward to your email. Unfortunately, most configuration settings are stored in the database (that is changing in Drupal 8) so just hashing your files will only find code alterations. Because your question asks "for any change" I will add the features module to my answer. Features lets you package up configurations (views, panels, content types, etc) and export them to coded modules. Then, in that same hook\_cron, add a features-revert to force the removal of any changes to the parts that you have exported to a feature. There is more that can be done, but after this point the effort to accomplish it overshadows the benefit. If that is not enough, read Greggles' work or watch some of the security sessions from a drupalcamp

P.S. Welcome to StackExchange
> 0 votes

---
Tags: files, emails, security
---


# Question
Title: Getting the value of a checkbox in form api
I'm creating a form using Drupal's form API. This form includes about 50 or so checkboxes that I'm creating using the type 'checkbox'. The checkboxes are grouped using several fieldset elements. The checkbox is created from a look using an XML file that decides what checkboxes will appear.

```
$ageKey = '08';
$course = 'y';

$form['events'][$ageKey][$course] = array(
  '#type' => 'fieldset',
  '#title' => 'Set of checkboxes'
}

foreach($xCourse->event as $event) {
  $eventKey = (int)$event['distance'] .'-' . (int)$event['event'];
  $form['events'][$ageKey][$course][$ageKey . ' ' . $course . ' ' . $eventKey] = array(
    '#type' => 'checkbox',
    '#title' => (int)$event['distance'] . ' ' . $top5->dispStroke((int)$event['stroke']),
    '#default_value' => 1,
  );
}

```

I'm using hook\_submit to process the form

```
function import_form_submit($form, &$form_state) {
  $checkboxes = $form_state['values'];

  //do stuff here
}

```

However, I find that the value for all my checkboxes is 0, regardless if the checkbox was unchecked by me or not. If I remove `'#default_value' => 1` from the checkbox definition, none of the checkboxes are checked by default. The values array also appears to ignore the hierarchy I set up.

How do I get the checked state of the checkbox in my submission code? What am I missing here?

# Answer
I found the answer. I added `'#tree' => TRUE,` to the fieldset and suddenly things are working correctly. I think because of the eventKeys were repeated so overwriting others. By adding the tree attribute, all the checkboxes were seperated into their respective fieldsets in the `$form_state['values']` array.
> 1 votes

# Answer
It would be better if you use the `variable_get($ageKey . ' ' . $course . ' ' . $eventKey)` for setting default values.

For more you can see this
> 1 votes

# Answer
I searched for a long time to find a comprehensive answer for this and arrived at this solution:

First declare your checkboxes associative array. This particular array has a fieldset component which uses the Drupal 7 `#states` property. My project is a module for D7 which uses FAPI to create a node and save it to the database unpublished.

```
    $form['major']['field_intern_agency_type'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Agency Type'),
    '#options' =>  drupal_map_assoc(array(
      t('Arenas, Stadiums, Venues, and Convention Centers'),
      t('Corporate Enterprises, Communications, Event Planning, and Travel'),
      t('Municipalities, Visitors’ Bureaus, and Departments of Parks & Rec'),
      t('Museums, Aquariums, Zoos, and Historical and Cultural Sites'),
      t('National and State Parks, DCNR, and Fish and Boat Commissions'),
      t('Nature Centers, Wildlife Reserves, and Conservancy'),
      t('Nonprofit Organizations and Festivals'),
      t('Outdoor Adventure and Experiential Education'),
      t('Resorts, Hotels and Hospitality, Amusement Parks, and Country Clubs'),
      t('Sports Management, Teams, Sport Associations, Merchandising, and Fitness'),
      t('Summer Camps, YMCAs, Family/Youth Recreation, Campgrounds, and Military'),
      t('Therapeutic Recreation'),
      t('Universities and Colleges including Athletics'),
      )
    ),
    '#default_value' => array(),
    '#states' => array(
     'visible' => array(   // action to take.
       ':input[name="field_majors"]' => array('value' => 'Recreation Park and Tourism Management'),
         ),
       ),
  );

```

---

I use the `array_values()` function to turn the form array (specifically the checked checkboxes) into a simple numerically indexed array, then use `foreach()` to iterate over the array and copy each value to the new checkboxes array which is then saved when the form is submitted with whatever boxes are checked being saved also. Hope this helps someone!

```
$agencytypevalues = array_values($form['major']['field_intern_agency_type']['#value']);
$i = 0;
foreach ($agencytypevalues as &$value) {
  $node->field_intern_agency_type[$node->language][$i]['value'] = $value;
  $i++;
};

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Exposed filter : search term with select which 'field' to search by
I have a view which displays a list of nodes with exposed filters. Everything works perfectly.

I would like to add a filter like this:

* one input text
* one drop-down.

The list items represent fields of content type.

The user can write a search term in the input text and select which 'field' to search by. i.e. All, Title, Summary, ...

Is that possible? How I can do this?

# Answer
I have created a custom module inspired by your question. You can find it here

It is not created/approved as a full project on Drupal.org. But it will approved soon. Download the module, enable it. Under filter add a filter that says `Exposed fields Filter` then select the fields you want to expose to visitors. Only those field will appear to visitors which you select here.

I hope it helps you for now.
> 0 votes

---
Tags: views
---


title: D7 - Whitespace before printed fields

text:
# Question
Title: D7 - Whitespace before printed fields
How to get rid of the whitespace in printed fields?

Here's my source code in node.tpl:

```
<div class="banner" style="background-image:url('<?php print render($content['page_banner']); ?>');">

```

And here's the result (whitespace before http://)

```
<div class="banner" style="background-image:url('  http://localhost/files/styles/1180x300/public/banners/test.jpg?itok=5LPh1ZdQ');">
</div>

```

Any ideas?

# Answer
Have you tried adding a trim() ? Like :

```
<div class="banner" style="background-image:url('<?php print trim(render($content['page_banner'])); ?>');

```

It should just do the trick...

Beyond that, whatever is generating the `$content['page_banner']` content is probably adding the unnecessary spaces.
> 1 votes

---
Tags: theming, entities
---


# Question
Title: Show repeating event just once in Views while sorting by date
When using repeat date API on a field, Drupal allows you to group events so they don't appear multiple times.

However, when sorting by date it seems like Drupal ALWAYS shows all of the entries no matter what.

How can this be avoided?

# Answer
> 14 votes
I just ran into this issue myself. The solution is to add a filter of the date delta field =0. This means only show the 0th (first) matching item and hide any repeating values.

Hope this helps someone. Selwyn

# Answer
> 3 votes
the delta option only works when you display fields, but if your displaying a display content node it wont work. I'm using display suite to manage the output of the display so the delta field wont work. What i did was create a views specific template file:

**views-view-list--event-calendar.tpl.php**

I basically detect if there is a duplicate and just make a conditional to bypass the output of it.

The live page is here: http://www.xcubicle.com/events

```
  1 <?php
  2
  3 /**
  4  * @file
  5  * Default simple view template to display a list of rows.
  6  *
  7  * - $title : The title of this group of rows.  May be empty.
  8  * - $options['type'] will either be ul or ol.
  9  * @ingroup views_templates
 10  */
 11
 12
 13
 14
 15 $rows = array_unique($rows);
 16
 17 ?>
 18 <?php print $wrapper_prefix; ?>
 19   <?php if (!empty($title)) : ?>
 20     <h3><?php print $title; ?></h3>
 21   <?php endif; ?>
 22   <?php print $list_type_prefix; ?>
 23     <?php foreach ($rows as $id => $row): ?>
 24         <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?></li>
 25     <?php endforeach; ?>
 26   <?php print $list_type_suffix; ?>
 27 <?php print $wrapper_suffix; ?>

```

# Answer
> 1 votes
This worked for me in the Views field configuration for the Date field:

1. Hide Repeat Rule
2. In the "Multiple Field Settings" fieldset, remove the checkbox for "Display all values in the same row".

# Answer
> 0 votes
When in the views edit screen, make sure that you are displaying fields, and configure the date field in question to 'Hide Repeat Rule' and under 'Multiple Values' set it to show 1 value.

# Answer
> 0 votes
this can also be achieved by going to views Advanced settings, under OTHER settings you will find Query settings just open it and check the "Distinct" option. Only single value will be shown.

# Answer
> 0 votes
I have been playing around with these settings and have stumbled upon an answer:

1. In the View, under Advanced, mark the checkbox to Aggregate the results.
2. In Advanced, under Query View, mark the checkbox for Distinct.
3. Go back to your list of Fields, and click the Aggregation Settings and aggregate the distinct fields in the view.

I also removed the Filter Criteria for Date Delta, which I was trying (unsuccessfully) to use for creating distinct records.

---
Tags: views, datetime
---


title: Duplicates in a View with Taxonomy

text:
# Question
Title: Duplicates in a View with Taxonomy
I created a view that has a global combined fields filter setup to search through node's title and a set of taxonomy terms. It works fine but only if I include a "Taxonomy term: Name" field.

This field currently causes each node to appear in the results for each term that is assigned to it. I checked Aggregation Settings for that field but only have these options:\[\]

I also tried the Views Distinct module which worked but at a great performance cost. Is there either:

1. a way I can include terms in the global combine fields filter that I haven't thought of or
2. a way to prevent the duplicate results?

Thanks for your help

# Answer
> 0 votes
You can apply **GROUP BY** or **DISTINCT** by enabling views aggregation settings to remove duplicate records.

1. Go and edit your view
2. In Advanced » OTHER section by enabling Use aggregation: Yes
3. In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.

# Answer
> 0 votes
**Put this code in your themes template.php file:**

```
function your-theme_views_pre_render(&$view) {
 $used_nids = array();
$new_view_result = array();

 if ($view->name == 'Name_of_your_view') {
foreach ($view->result as $row) {
    if (!in_array($row->nid, $used_nids)) {
      $new_view_result[] = $row;
      $used_nids[] = $row->nid;
    }
  }

$view->result = $new_view_result;
 }
}

```

---
Tags: 7, views, taxonomy-terms
---


title: Changing text-format for body field

text:
# Question
Title: Changing text-format for body field
I've installed Drupal 8 in a minimal installation; I've enabled CKeditor and created a text-format called "Full". I've also created a role named as "Administrator" and gave it all permissions available whatsoever; After that, I've attached my user "Admin" to that role "Administrator" and associated it with my newly created text-format ("Full"). I than decided I'm good to keep on:

After I did all of this I went to my content type and clicked to edit it's body field... When I went in to the edit screen I didn't see any place to attach the new text format I created to it, so where is the right place to set the field for other text-format rather than the default "plain text"?

# Answer
> 1 votes
You're already using it, default text-only shows up when there is no other choice.

If you add another format: ie: "test", now you will see in the drop down CKEditor and test.

Also, you probably did not select CKeditor as your text editor. Did you enable the CKeditor module?

**I highly recommend not using minimal installation. I just tried it and a lot of the modules are disabled, just figuring this stuff out it's quite the headache.**

**Normal installation is the way to go IMO.**

---
Tags: 8, wysiwyg
---


# Question
Title: Installing Drupal patches in Ubuntu terminal
I'm new to Ubuntu and I never ran Drupal patches before and now is my first to do so: I've searched here in the Drupal answers with the phrase: "Patches, Ubuntu" But I didn't find instruction on how to run patches for a module in a local site via the Ubuntu terminal. I've also searched some in Google in Youtube but I found ways for many other CLIs, but not for the Ubuntu terminal.

Is it possible to run the patches there as I would run Drush commands?

# Answer
> 1 votes
As far as I know there is nothing in specific about applying patches for drupal in ubuntu.

If you are already using git for managing your project code then you can apply a patch to a project's repository by using following code:

```
git apply -v path/file.patch

```

If you are not using git, or if the repo isn't a local checkout of the project you wish to patch:

```
patch -p1 < path/file.patch

```

For more information, check https://www.drupal.org/patch/apply

**Live example for patching in Drupal 8:**

1. Download the .patch file (in this case: `Add_rtl_support.patch`)
2. Copy it into the particular module's directory (since the patch is relative to the module directory).
3. Change the destination directory in the Ubuntu terminal to the module's folder - In this case it should be cd `modules/admin_toolbar`.
4. Apply the patch using 2nd method `patch -p1 < Add_rtl_support.patch`

---
Tags: version-control
---


# Question
Title: Facebook auto post module not posting to my FB page
When user comments on a particular node the comment title and comment body should be automatically posted to my Facebook page. For this I have used Facebook autopost. I have added my appid in fb\_autopost configuration page and it displays the list of pages I manage and I have selected required page. Used below rules for auto posting comment in facebook

```
{ "rules_facebook_autopost_" : {
    "LABEL" : "Facebook Autopost ",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "fb_autopost_entity", "comment" ],
    "ON" : { "comment_insert--comment_node_theme_display" : { "bundle" : "comment_node_theme_display" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "facebook_publication",
            "param_type" : "link",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-message" ],
          "value" : "[comment:title]"
        }
      },
      { "publish_to_facebook" : {
          "USING" : { "publication" : [ "entity-created" ], "pages" : "1575855786569558" },
          "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
        }
      },
      { "drupal_message" : { "message" : "success" } }
    ]
  }
}

```

After saving the comment it throws below error and comment not posting in Facebook.

> Facebook SDK threw an error: OAuthException: (#200) The user hasn't authorized the application to perform this action

How can I achieve this or Is there any other way to do this. Thanks

# Answer
Finally found the answer.

In `admin/config/services/fbpermissions` need to give Publish pages permission for users.
> 3 votes

# Answer
I never used this module before, so i just found this.

Please follow this page instruction for configuration https://www.drupal.org/node/1914896
> 0 votes

---
Tags: 7, rules, social-network
---


# Question
Title: location fields are not appearing on feed mapping while location module is used inside field collection
I want to import field collection through feeds but since I’m using location module inside the collection module due to this it’s not appearing on target list as you can see the below screen short.
**Field collection**

**Feeds Mapping**

Guy can you please help me and I'm using Drupal 7.

# Answer
I found the solution, in `location_feeds.module` under function(`location_feeds_feeds_processor_targets_alter`) under first 'if statement' there is only mention that when node is selected in feeds on that case show all location fields so for solving this issue we just need to add when node or `field_collection_item` is selected on that case location fields should be appear... steps: Go to

> path= modules/location\_feeds/location\_feeds.module

add `$entity_type == 'field_collection_item'` || to first statement of "if condition" like this:

```
function location_feeds_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {

if ($entity_type == 'field_collection_item' || $entity_type == 'node') {

```

// location.module logic

```
$settings = variable_get('location_settings_node_'. $bundle_name, array());

```

// Only add fields when collecting locations

```
if (isset($settings['multiple']['max']) && $settings['multiple']['max'] > 0) {
_location_feeds_location($targets, $settings);
}

```

Save and clear all caches(`admin/config/development/performance`) and then check it...
> 0 votes

---
Tags: feeds, entities, location
---


# Question
Title: How to capture value of a field in a node
I am nearly a complete newbie when it comes to writing modules (Drupal 7). I have a module that successfully calls an OpenStates API and retrieves information about a member of the legislature. The key is a custom field called leg\_id. In testing this, I hard coded the leg\_id in the module that creates the block I want to display.

I now have a node that has a custom field for leg\_id. When that node is displayed, I want to pass the value of the leg\_id to the module that retrieves the information from OpenStates and display it in a block in the right sidebar.

I need a simple example of how to get the value of the leg\_id field and pass it to the module that creates the block.

Here is an example of how the page should look: http://dev-thecivithing.pantheon.io/node/1

**Block creation Module Code**

```
<?php
// $Id$

/**
 * Implements hook_help().
 */
function committees_help($path, $arg) {
  if ($path == 'admin/help#committees') {
    return t('A demonstration module.');
  }
}

/**
 * Implements hook_block_info().
 */
function committees_block_info() {
  $blocks = array();

  $blocks['list_committees'] = array(
    'info' => t('A listing of all of the committees for the member'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function committees_block_view($block_name = '') {
  if ($block_name == 'list_committees') {
    $list = get_committees();
    sort($list, $sort_flags = SORT_STRING);

    $theme_args = array('items' => $list, 'type' => 'ol');
    $content = theme('item_list', $theme_args);

    $block = array(
      'subject' => t('Committee Membership'),
      'content' => $content,
    );

    return $block;

  }
}

/**
 * Web service to list committees for the member
 */

function get_committees() {

$leg_id='NCL000208';
$apikey='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$list = array();

$request_url = "http://openstates.org/api/v1/legislators/$leg_id/?apikey=$apikey";
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$legislator = json_decode($result);
$roles = $legislator->roles;
    foreach ($roles as $role) {
        if (isset($role->committee))
            $list[] = $role->committee;

    }
    return $list;
}

```

**Working Module**

```
<?php
// $Id$

#print $body . PHP_EOL;

/**
 * Implements hook_help().
 */
function committees_help($path, $arg) {
  if ($path == 'admin/help#committees') {
    return t('A demonstration module.');
  }
}

/**
 * Implements hook_block_info().
 */
function committees_block_info() {
  $blocks = array();

  $blocks['list_committees'] = array(
    'info' => t('A listing of all of the committees for the member'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function committees_block_view($block_name = '') {
  if ($block_name == 'list_committees') {
    $list = get_committees();
    sort($list, $sort_flags = SORT_STRING);

    $theme_args = array('items' => $list, 'type' => 'ol');
    $content = theme('item_list', $theme_args);

    $block = array(
      'subject' => t('Committee Membership'),
      'content' => $content,
    );

    return $block;

  }
}

/**
 * Web service to list committees for the member
 */

function get_committees() {

if (arg(0) == 'node' && is_numeric(arg(1)))
$nodeid = arg(1);
$node = node_load($nodeid);
$field_leg_id = $node->field_leg_id['und'][0]['value'];

$apikey='a1e620771b1d463cb726eda33e8f3102';
$list = array();

$request_url = "http://openstates.org/api/v1/legislators/$field_leg_id/?apikey=$apikey";
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$legislator = json_decode($result);
$roles = $legislator->roles;
    foreach ($roles as $role) {

        if (isset($role->committee))
            $list[] = $role->committee;

    }
    return $list;
}

```

# Answer
> 1 votes
What u can do is, pass leg\_id in the function definition, like:

```
function get_committees($leg_id = '') {
if(empty($leg_id)) {
$leg_id = 'NCL000208';
}
...

```

and in the content of block inside block\_view, u can call this function, with leg\_id, if u are sending leg\_id through url, then u can get the leg\_id from url using arg() function, and then passing it to function.

But since u want to get Leg\_id from node, what u can do is:

```
if (arg(0) == 'node' && is_numeric(arg(1)))
$nodeid = arg(1);
$node = node_load($nodeid);
$field_leg_id = $node->field_name_field_leg_id['und'][0]['value'];

```

and sending $field\_leg\_id to function get\_committees($field\_leg\_id)

// Edited

You can do the same by calling menu\_get\_object(), it will return you an array, what u can do is:

```
$menu_obj = menu_get_object();
$leg_id = $menu_obj->field_name_field_leg_id['und'][0]['value'];

```

---
Tags: entities, blocks
---


# Question
Title: Router can't find route in LanguageNegotiation plugin route name
I'm having to write a new LanguageNegotiation plugin for an API because the language is not the first part of the URL (it's the third). But D8 refuses to recognise the route to the plugin for the config menu item.

I have been following the Language module itself as a model and there is no other mention of an equivalent route name for any of the other LanguageNegotiation plugins. I have tried replacing 'doublespeak' with 'language' in the route name (no change).

```
Symfony\Component\Routing\Exception\RouteNotFoundException: Route "doublespeak.negotiation_api_url" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName()

```

So the `doublespeak.routing.yml` looks like this:

```
doublespeak.negotiation_api_url:
  path: '/admin/config/regional/language/detection/apiurl'
  defaults:
    _form: 'Drupal\doublespeak\Form\NegotiationApiUrlForm'
    _title: 'API URL language detection configuration'
  requirements:
    _permission: 'administer languages'

```

And the start of the plugin is this:

```
namespace Drupal\doublespeak\Plugin\LanguageNegotiation;

use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Url;
use Drupal\language\LanguageNegotiationMethodBase;
use Drupal\language\LanguageSwitcherInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class for identifying language in an API URL via an infix value.
 *
 * @LanguageNegotiation(
 *   id = \Drupal\doublespeak\Plugin\LanguageNegotiation\LanguageNegotiationApiUrl::METHOD_ID,
 *   types = {\Drupal\Core\Language\LanguageInterface::TYPE_INTERFACE,
 *   \Drupal\Core\Language\LanguageInterface::TYPE_CONTENT,
 *   \Drupal\Core\Language\LanguageInterface::TYPE_URL},
 *   weight = -10,
 *   name = @Translation("API URL"),
 *   description = @Translation("Language from an API URL (/api/<channel>/<market-language>/refdata/<>)."),
 *   config_route_name = "doublespeak.negotiation_api_url"
 * )
 */
class LanguageNegotiationApiUrl extends LanguageNegotiationMethodBase implements InboundPathProcessorInterface, OutboundPathProcessorInterface, LanguageSwitcherInterface {

```

I've tried all sorts of options but can't make it work, and yes, I've cleared caches :-)

# Answer
Okay, the problem was not in either of these two files.

As suggested by @Berdir I checked the router table and found that my route was not there. However there is nothing wrong with the file.

So the problem must be somewhere else. What if a bad class/method reference could cause this?

As an experiment I replaced the '\_form' property with one that was known to work and cleared the caches. Suddenly the route was there in the table.

Checking my Drupal\doublespeak\Form\NegotiationApiUrlForm file I discovered that in my copy/paste haste I hadn't changed the namespace so the form class effectively did not exist. And the route was not loaded into the table.

Fixed. (Phew.)
> 0 votes

---
Tags: 8, i18n-l10n, routes
---


# Question
Title: Drupal patch files - Why do Drupal patches have complicated file names?
I know almost nothing on Drupal patches but it is important for me to ask this for others and myself: Why almost every Drupal patch I've seen in discussions in Drupal.org has a long complicated file name? For example, I've seen this one yesterday:

> \[Add\_rtl\_support\]-\[2635832\]-\[1\].patch

Why is the \[\]-\[\]-\[\] structure, why 3 words in the first structure(?), what is the medium-number, and what is the 1 (first patch release from the same committer)?

Two more examples, which are different from the above and one from another:

> * metatag\_by\_path\_consequences\_fix-2184979-12.patch
> * metatag-n2564483-190.interdiff.txt

And there could be more I guess...

I would thank any experienced dev who could shed some light in this context...

And also a subtle question: If I download a file with a long name and than changed the name to something like "fix1.patch" just for navigation comfortability, Will it still work as normal as it should have been?

# Answer
> 16 votes
It just provide good information about the patch.

Here is the proper way to name a patch

```
[project_name]-[short-description]-[issue-number]-[comment-number].patch

```

Why? Here is a list of why these name are useful...

* \[**project\_name**\] - We use the project name to distinct the patch from other projects. Sometimes some project have multiples sub-modules and it just nice to have a name in front of the patch.
* \[**short-description**\] - This is just a well practice from git, which is adding a small description about the patch.
* \[**issue-number**\] - With unique issue number we can make sure what this patch is trying to solve because we can visit drupal.org/node/\[issue-number\] and see what is trying to solve.
* \[**comment-number**\] Usually, there are multiple patch in the same issue queue and we need way to distinct different patch for this reason we add the comment-number so we do not get confuse when we are reviewing patches.

For more information about patches naming visit - Making a Drupal patch with Git

> And also a subtle question: If I download a file with a long name and than changed the name to something like "fix1.patch" just for navigation comfortability, Will it still work as normal as it should have been?

Patches names does not have any affect to the patch content. This been said, it will work, it just that developer was very lazy and did not want to name it the proper way (or he/she did not know how to in Drupal we name patches).

---
Tags: version-control
---


# Question
Title: How to create a view with contextual filters and then make menus to filter it?
I have created a content type that I want to list and filter on taxonomy terms. For example I want to show all posts of that content type on the frontpage. Then I want to be able to create menu items with name of all the existing taxonomy terms I have to choose from. Then i want those terms to link to a page with the filtered content for only that term.

I can create this by making a new view for every taxonomy term but it must be a better way to do this since if I have around 40 terms it's gonna get really messy.

# Answer
> 0 votes
I managed to figure this out. With help from this tutorial http://www.metaltoad.com/blog/using-drupal-contextual-filters-views and the reason why the links in the menus dind't work for me were because I was using the same url as the taxonomy term had so I only got a term list. So I just changed the view url to something else than the taxonomy and it worked.

It now works if I write the view adress/any termreference without having to create a separate view for all of them.

---
Tags: panels, views
---


# Question
Title: What is the correct way to setup Drupal file permissions on a VPS?
I am testing a Drupal site on Google Compute Engine. I have a problem with file permissions.

I would like to be able to access and edit my files trough SFTP and still have Drupal functioning as it's supposed to.

Letts say my user for SFTP is 'user'. If I do **sudo chown user:www-data -R /var/www/** I can edit files via SFTP. But then I can not make changes or add files in Drupal (for example add a new module trough Drupal, even clearing caches doesn't seem to work).

If I do **sudo chown www-data:www-data -R /var/www/** evrything in Drupal works, but I can not make changes to files trough SFTP.

I have tried adding both users ('user' and 'www-data') to a group called 'drupal' and running the command **sudo chgrp drupal -R /var/www/** but this doesn't fix the problem.

# Answer
> 0 votes
`user:www-data` are the correct permissions IMO. For security reasons, the web server should not be able to write to the file system, except for files and temp folders. You haven't mentioned suhosin or anything so I'm assuming you have a typical setup.

Drupal have unfortunately made the above a bit confusing by including a method to update modules via the UI (v. bad idea IMO, swapping security for convenience).

If you still want to do it, it can be solved with \*nix permissions on most platforms; the exact nature will depend on your server's architecture and setup. There's an example here and in the comments of the official docs page to get you going, but generally speaking just search for how to manage these permissions for your server type generically - there's nothing Drupal specific about the commands you need to run, so you're closing off a lot of potential help if you include Drupal as a keyword in your searches.

---
Tags: files
---


# Question
Title: How one can display the file path once it is successfully uploaded
How one can display the file path in node/add page, once it is successfully uploaded, before saving the node.

# Answer
> 0 votes
Please try below: **file\_create\_url($file-\>uri)**

```
function import_form_submit(&$form, &$form_state) {
  // Load the file.
  $file = file_load($form_state['values']['file_fid']);
  // Change status to permanent.
  $file->status = FILE_STATUS_PERMANENT;
  // Save.
  $uploaded = file_save($file);
  if ($uploaded == TRUE) {
    drupal_set_message(t('The file has been uploaded.'));
    dpm(file_create_url($file->uri));
  }
  else {
    drupal_set_message(t('The file could not be uploaded. Please contact the site administrator.'), 'error');
  }

}

```

Also, refer the answer for pre-node save function

---
Tags: 7, files
---


title: Add a URL as filter criteria in Views

text:
# Question
Title: Add a URL as filter criteria in Views
I have a page of content type insert which adds images to my website. It currently just displays images in rows when you click to view the **album name** pages.

I have installed FlexSlider as I want to use that module to display all images that are on pages that contain ***/Album/AlbumName*** in the URL as a slideshow automatically. How do I do that in Views?

# Answer
If you have a content type which has a photo filed and you want to show the photos in the form of slider, Than I will suggest to use FlxSlider.

1. Go to your\_seite/admin/structure/types/manage/your\_content/display/
2. Change the photo filed form to flexslider
3. Click the setting icon to customize the slider options
4. Click Save

**If your want to have some sort of photo album** in your site than I will suggest to use Juicebox HTML5 Responsive Image Galleries

This module provides an integration between the popular Juicebox HTML5 responsive gallery library and Drupal. Juicebox is in many ways the successor of Simpleviewer and offers a powerful cross-device solution for image galleries, sliders and more.
> 0 votes

---
Tags: 7, views, media, uri, javascript
---


# Question
Title: Ajax rebuild form is calling all the code from my form function
I have a form which when I click on on radio rebuild an element of the same form. Somehow when the ajax is called it's recalling everything from my form function. How can I force him to reload only a part of the code, in that case the $form\['container'\]\['network'\] and not the whole $form.

There must be some strange behavior during the callback, could it be reloading the whole form and get the part it wants then replace the old by the new?

```
$form['container']['ZoneId']['#ajax'] = array(
    'callback' => 'change_countries',
    'wrapper' => 'networks-list',
    'method' => 'replace',
    'effect' => 'fade',
);

$form['container']['network'] = array(
    '#type' => 'fieldset',
    '#prefix' => t('<div id="networks-list" class="checkbox-styling">'),
    '#suffix' => '</div>',
);

function change_countries($form, $form_state) {
    $form_state['rebuild'] = TRUE;
    return $form['container']['network'];
}

```

# Answer
> 1 votes
You shouldn't need:

```
$form_state['rebuild'] = TRUE;

```

Otherwise your callback looks correct.

---
Tags: 7, forms, ajax
---


# Question
Title: Failed patching both manually and with Git in Ubuntu terminal
I am very new to both Patches and Ubuntu and I try to run this patch which fixes RTL problems for Admin\_Toolbar module (8.x-1.11).

I've downloaded the patch file and putted it in the module's folder.

When I tried to run it manually in the terminal i didn't succeed:

Later, similar situation occurred with Git:

Where my commands accurate? What can cause it to fail? For the creator of this patch it did work... Please give me a clue or any advice you can how to solve it... Is there even anything I could do in my end?

# Answer
> 2 votes
The patch you have doesn't apply to the version of the module you have.

You either need to get a version of the module that the patch applies to, or look for/create a patch that applies cleanly to the version of the module you have installed.

Might be worth checking the patch and target files manually, the patch may well have been applied and just not have fixed the problem in the way you were expecting. I can't tell what order you've run commands in/what you've done to clean up after each and so on so it's just a guess, but the "Reversed (or previously applied) patch detected!" message suggests the patch has already been applied at some point.

---
Tags: version-control
---


# Question
Title: Managing display of articles promoted to front page
How do we manage the way that blog items that are promoted to the front page are displayed? Currently using Bootstrap theme, we promote some of our articles, these are displayed in a scroller, but just showing one article at a time. How would I manage this so that the scroller showed 3 articles?

# Answer
> 0 votes
1. Go to yoursite/admin/config/system/site-information
2. Change the Number of posts on front page to 3 or whatever you want.

Please note your allow to display up to 30 post, however if you want to show more then 30 than i suggest to use View module, to create page of your article list

---
Tags: theming, nodes
---


# Question
Title: How to remove all commerce coupon from database?
Hi I have used commerce coupon module. I have lot of entries of used coupon. So, right now I want to delete all commerce coupon from database. I have 860000 coupon entries in database. How can I delete all entries using custom module functionality?

# Answer
> 3 votes
Since coupons are entities, you'll want to delete them using the entity functions. As an example, if I want to delete all disabled coupons, something like this should work:

```
$disabled_coupons = commerce_coupon_load_multiple(array(), array('status' => 0));
$disabled_coupon_ids = array_keys($disabled_coupons);
commerce_coupon_delete_multiple($disabled_coupon_ids);

```

If you need to batch them, you may want to try doing them in batches of 250-1000... not sure how many can be deleted successfully per batch. Then just let it run.

---
Tags: commerce, hooks
---


# Question
Title: How do I use the Commerce Coupon module?
Does anyone know how to use the Commerce Coupon module?

I created a coupon discount (%) type with Product\_reference field; then, I created one coupon of that type, and selected the products to wich it should apply. This seems not to work.

# Answer
The key to creating the coupon rules are two events: "Validate Coupon," and "Redeem a Coupon."

In this case, you need to create a rule with the "Redeem a coupon" event; in it, you need to add the actions "Create coupon line item," and "Set granted coupon amount" (in that order). The "Set granted coupon amount" action requires a number that is the discount to be applied. You need to calculate this in the rule by finding the percentage of the order total.

This video may help.
> 1 votes

# Answer
For anyone coming across this question, please make sure you are using Commerce Coupon 2.x. Much of the functionality has changed and the process of creating coupons is much more simplified by being more tightly integrated with Discounts.

Essentially, 2.x leaves the discount logic and actions in the hands of the Discount module and focuses solely on tying those discounts to coupons and providing the necessary UI and functionality around that.

*Note: as of current writing, a discount without a coupon **will always apply to any order which meets the conditions** whereas a discount with a coupon will only apply if the coupon is attached to the order. A discount with only disabled coupons will function as if it has no coupons attached to it. There are bugs floating around that discuss changing this.*
> 1 votes

# Answer
You should create a rule yourself for that coupon type. You can check how the module created their default rules and learn from there.
> 0 votes

---
Tags: 7, commerce
---


title: What is FID and how does it works?

text:
# Question
Title: What is FID and how does it works?
I could not find a clear explanation about what is a 'fid'. I got is an identifier for file in drupal, but no more than that. How it is generated? Is unique for any file? When it is used and why? Could someone give a clear explanation of this entity?

# Answer
> 3 votes
1. You can find `fid` under the table name `file_managed`.
2. It is unique id for files. In files you can include images, .txt, .pdf etc extension files.
3. This `fid` is unique for the site and `auto incremented`
4. By using `file_load($fid)` function. Where `$fid` is file id.

Fid is only valid for managed files. Files uploaded as unmanaged does not have records in database, so no fid.

# Answer
> 2 votes
Once file gets uploaded it stores the record to Database. The fid is file ID of the uploaded file.

Refer file\_load

---
Tags: 7, files
---


title: Check if certain line item type exists

text:
# Question
Title: Check if certain line item type exists
I am using Commerce Userpoints to award points based on purchases and then customers can use those rewards on future purchases for a discount.

I'd like to customize the checkout pane if the user has already applied a discount. Commerce Userpoints Discount creates a line item type of `userpoints`. My initial idea was to check if the current order contains a line item of type `userpoints`, but I'm not sure how to do that. Any help would be appreciated!

# Answer
> 3 votes
You can check for a certain type of line item on an order using one of the two following methods.

Given an order, let's look for a shipping line item.

```
// Load your order.
$order = commerce_order_load(/* Order ID */);

```

### Without Metadata Wrappers

```
if (!empty($order->commerce_line_items)) {
  // Iterate over the line items.
  foreach ($order->commerce_line_items[LANGUAGE_NONE] as $line_item_data) {
    $line_item = commerce_line_item_load($line_item_data['line_item_id']);
    // Check the type.
    if ($line_item->type == 'shipping') {
      // Shipping line item found. Do the things.
    }
  }
}

```

### With Wrappers

```
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
// Iteration is a bit simpler here.
foreach ($order_wrapper->commerce_line_items as $line_item) {
  // We have to access it using ->value().
  if ($line_item->type->value() == 'shipping') {
    // Shipping line item found. Do the things.
  }
}

```

---
Tags: userpoints, commerce
---


title: Turn Tags into Links in Search Results

text:
# Question
Title: Turn Tags into Links in Search Results
When a user searches for a certain tagged iamge I want them to be able to click on the tag and re-direct them on a page which contains all the images with that tag. E.g. if I click Italy, all the pictures which have ***Italy*** as tags will be displayed. Can I use Views module for it?

# Answer
You can do this in two ways,

1. Using the module Similar By Terms
2. Using views, Read more here
> 0 votes

---
Tags: 7, views, taxonomy-terms, search
---


# Question
Title: Adding Background image in Views template file
How to add background in Drupal 8 views-view-fields.html.twig' files.

I try like this but it's don't work. Using views I just output image paht.

```
 <div class="cover-img" style="background:url('{{ field_image }}');">
    </div>

```

Thank you

# Answer
Adding CSS background image hardcoded in the Twig (or TPL in D7 sites) isn't a best practice. You should do this via your theme's css file like `style.css`, or via a module (some theme's give you the opportunity to add it directly on your site).

I would suggest to restore any such changes in the Twig and redoing it in the css file.
> 1 votes

# Answer
Download Image URL Formatter module

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

Once enabled, views will give you an option to change the formatter to url when you edit or add your image field.

After you select url as your formatter, `{{ field_image }}` will output url instead of picture.
> 0 votes

---
Tags: views, theming
---


title: HTML in QuickTab Titles

text:
# Question
Title: HTML in QuickTab Titles
I've programmatically created some quicktabs in Drupal 7, however I require html tags within the title.

For e.g:

```
    $tabs_project['backers'] = array(
        'title' => t('Backers').'strong'.$backers_total.'strong',
        'contents' => 'backer information..',
        'weight' => 2,
    );

```

But this prints out the strong tags too.. Any ideas? (couldn't work out how to put the correct html tags in the pre tags, so left it as 'strong')

Cheers in advance,

# Answer
> 1 votes
Turns out you can apply something like so:

```
$qt_project['content']['content']['tabs']['tablinks']['backers']['#options']['html'] = TRUE;

```

thanks to **`comment on drupal forum`**

cheers

# Answer
> 0 votes
A solution that avoids patching the module would be to override the appropriate theme function that outputs the "tabset" tab titles. For the quicktab style, a solution would look like this:

```
/**
 * Overrides Theme function to output tablinks for classic Quicktabs style tabs.
 */
function YOUR_THEME_NAME_qt_quicktabs_tabset($vars) {
  $variables = array(
    'attributes' => array(
      'class' => 'quicktabs-tabs quicktabs-style-' . $vars['tabset']['#options']['style'],
    ),
    'items' => array(),
  );
  foreach (element_children($vars['tabset']['tablinks']) as $key) {
    $item = array();
    if (is_array($vars['tabset']['tablinks'][$key])) {
      $tab = $vars['tabset']['tablinks'][$key];
      $tab['#options']['html'] = TRUE; // Added this to override to allow HTML in titles.
      if ($key == $vars['tabset']['#options']['active']) {
        $item['class'] = array('active');
      }
      $item['data'] = drupal_render($tab);
      $variables['items'][] = $item;
    }
  }
  return theme('item_list', $variables);
}

```

See the Quicktabs.module theme functions for reference here: http://drupalcode.org/project/quicktabs.git/blob/refs/heads/7.x-3.x:/quicktabs.module#l591

I crossposted this in this comment on d.o: https://drupal.org/comment/8343639#comment-8343639

# Answer
> 0 votes
You can implement a "process" function for the qt\_quicktabs\_tabset theme-hook in your custom module like this:

```
function MYMODULE_process_qt_quicktabs_tabset(&$vars) {
  // Allow HTML in quicktab titles.
  foreach (element_children($vars['tabset']['tablinks']) as $key) {
    if (is_array($vars['tabset']['tablinks'][$key])) {
      $vars['tabset']['tablinks'][$key]['#options']['html'] = TRUE;
    }
  }
}

```

---
Tags: theming, blocks
---


title: Jquery after ajax loaded in view

text:
# Question
Title: Jquery after ajax loaded in view
So I created a view listing all the users. I implement a search form with autosubmit function.

The autosubmit works with an ajax script.

Into my page view, I changed a few things in Jquery like this (main.js) :

```
$(document).ready(function(){
    //code for others pages.....
});

$(document).ajaxComplete(function(){
   $('h2').text('filters');
});

```

**But when I filter my list of users, the ajax script is loading and after that, Jquery changes do not appear due to ajax load.**

Do you know a trick to keep Jquery changes when ajax script is loading ?

Thanks for your help !

# Answer
Try this:

Add an ajaxComplete function

```
   $( document ).ajaxComplete(function() {
      $('h2').text('filters');
    });

```
> 3 votes

# Answer
Find the solution below:

```
(function($) {
  Drupal.behaviors.events = {
    attach: function(context, settings) {
      $('#views-exposed-form-recherche-artiste-page', context).ajaxSuccess(function(){
         $('h2').text('filters');
      });
    }
  };
})(jQuery);

```
> 3 votes

---
Tags: views, javascript, ajax
---


# Question
Title: Adding translation files to install profile?
I am building a Drupal installation profile to make deployment of my site easier, ideally I would like to include the translation files to the install profile as well. But apart from adding the core translation files download to the makefile, is there a way to somehow add the translation files for the modules that are in use and for the custom fields as well?

Ideally I would like to add the needed .po files to the makefile or the profile's .install-file. Any ideas on how to do it?

# Answer
> 0 votes
Have you seen http://zgadzaj.com/drupal-installation-profile-with-multiple-languages ?

Also you can try to export it with Features

> Features
>
> The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.

And for more especific export data

> UUID Features Integration
>
> The UUID Features Integration module provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. What's that you say? You thought features was only for configuration? This module is meant to be used in the cases where certain pieces of content straddle the line between pure content and configuration. You've to configure the entity types / bundles to be exportable. Read the Documentation for further information.

---
Tags: 7, i18n-l10n, installation-profiles
---


# Question
Title: Where are .po translations supposed to go?
I have .po file with translation and I have it in modulename/translation/xy.po

When I installed profile in XY language the file was not loaded. I did a little digging and found that \FileTranslation::getTranslationFilesPattern looks for drupal-8.xy.po pattern so I renamed the file, reinstalled my profile but the language still was not picked up. The interface translation was downloaded just fine though. If I manually import the file it works. So it looks to me like the directory for translations has changed maybe?

---

I have checked the installer and it looks like Drupal only looks into the site's files/translations directory. So how are modules supposed to ship with translations?

---

So it looks like the translations ARE being imported just fine(entries are present in the locales\_source table), but for some reason not everything is displayed translated.

---

Ok, so I came to a conclusion that my translation file is not imported at all. The reason for incomplete translation is because it comes from downloaded Drupal localization and not my file. I am looking at installer and there is nothing that would suggest po files discovery mechanism in any way, only the drupal core(or any po file) in the files/translations directory(which is where the drupal translation is downloaded into).

# Answer
> 2 votes
OK, so it looks like this change https://www.drupal.org/node/1352228 is cause of all the hell with translations. I'm not sure how I'll handle this for multisite but at least I know where the issue came from.

---

As a follow-up in order for local .po files to be used one needs to add new records into module's info file or implement the hook\_locale\_translation\_projects\_alter. The description of this hook basically explains everything.

But still, it is not working. I had to manually run locale\_system\_update(array('module' =\> array('mymodule'))); and CC'd afterwards in order for the translation file to be successfully imported and used. I am not sure if this is a bug or not but it is a huge PITA.

I need the translation to work when the site is installed(I have custom profile) so I have to implement this as additional installation task but am not sure if it will work sin in the locale\_system\_update function it says not to do this while installing. If anyone has figured this thing out, please leave an answer or a comment, thanks.

---

**Final solution:** I had to create two additional installation steps in my profile. Basically I have split the locale\_system\_update() since it defines two batches. I am running them as last two steps so install\_finished() runs before them.

One more info: I had to replace the locale\_translation\_batch\_update\_build with manually importing the file since it was not working as expected. So now in my first step I will import desired .po files(see \Drupal\locale\Form\ImportForm::submitForm()) and in the seconds step I am updating config translation since installation handler cannot handle multiple batch configurations even if it says it does(maybe it is not working only in this case).

# Answer
> 2 votes
Be sure the directory sites/default is writable, so that during installation the translation files can be copied to the translations directory at sites/default/files/translations

---
Tags: 8, i18n-l10n
---


# Question
Title: Views Dynamic Fields checkboxes to dropdown select
I'd like to know if there is a way to modify the exposed check-boxes filter of Views Dynamic Fields module and convert it to a multi-select dropdown menu (like an ordinary exposed filter).

Unfortunately Better Exposed Filters module which makes that kind of modification possible, does not seem to apply on dynamic fields exposed filters.

Could anyone guide me how to make this kind of change on own?

# Answer
> 0 votes
U can do it through hook\_form\_alter, just check the form\_id, and change the type of form element to that of select, it will create select list from checkboxes.

However for making it working u have to write some jQuery.

```
$("#<form_element_id>").on('click', function(){
$(this).closest('form').trigger('submit');
});

```

---
Tags: theming, navigation, views
---


# Question
Title: How to migrate products display nodes with multiple product references?
I have a site being migrated from Drupal 6 to 7. The old site had a home grown system for adding payments to signups for event nodes. We plan to use commerce module to selling the registrations for events going forward.

In the new site, we are planning to import the preexisting SKUs from the old site with feeds but I want to include the product references with the event migration we have written. This migration is already working and just needs to have the product references added to it.

My question is about how to prepare the source data to be mapped when it looks something like this:

```
nid | sku
---------
1   | a
1   | b
1   | c
2   | a
2   | d

```

When it seems like it would be better if the data was like this:

```
nid | sku
---------
1   | a,b,c
2   | a,d

```

I think if I had the like the second table, I could join the source table

```
// Join payment_options_skus table
$query->join('payment_options_skus', 'pos', 'pos.nid = n.nid');
$query->fields('pos', array('sku'));

```

and then map like so:

```
$this->addFieldMapping('field_registration', 'sku')
     ->separator(',');

```

Is there a better way to do it using the existing data in the first example table? I would like to limit the number of manual massaging steps needed. Thanks.

# Answer
I'm in a similar boat, but doing an import for a content type. If data is prepared with multi-value fields as in your second table, I can import the data using Feeds and the plugin 'Feeds Tamper'. So I'm also looking at repeatable and efficient ways to arrange data with multi-fields in CSV format. Saw a post about using Drupal 7 'Feeds Tamper PHP' to do create the multi-valued fields here, https://www.reddit.com/r/drupal/comments/2tumv9/drupal\_7x\_feeds\_tamper\_column\_values\_to\_single/co2hesj. \<-- Untested, just a reference. HTH.
> 0 votes

# Answer
I was unable to find a way to import the product references as they were in the original data structure. Instead, using Libreoffice Calc, I wrote some concatenate functions to merge the rows so that I had one rows per event node. Also, I found that I needed the "product\_id" of the product, not its SKU. For that, I imported the commerce\_products table into my spreadsheet and then did a VLOOKUP to find the product\_id for each SKU. I then exported the worksheet to a CSV file with this structure:

```
|nid|product_ids
----------------
|1  |100,101,102
|2  |100,105

```

Then my mapping looked like so:

```
$this->addFieldMapping('field_registration', 'product_id')
     ->separator('|');

```

And may source looked like:

```
// Join payment_options_skus table
$query->leftJoin('payment_options_skus', 'pos', 'pos.nid = n.nid');
$query->fields('pos', array('product_ids'));

```
> 0 votes

---
Tags: commerce, migrations
---


# Question
Title: Can I invoke a template for print media?
I have a node type that is usually viewed as a web page but the client requires that occasionally it is also printed out in hard copy.

There is quite a lot I can do with css and media queries for print media but I would ideally like greater control over the content through the page templates.

As far as I can tell, there are no special theme suggestions for print and that theme functions, hooks, and templates are not aware of the target medium, be it screen or print.

This is a Drupal 8 project and whereas there were some Drupal 7 modules for print that might have been worth investigating, there doesn't seem to be anything right now for D8.

I any case, getting control over the content in a twig template would be quite sufficient if only I could tell that it was being rendered for print rather than screen.

# Answer
> 2 votes
You cannot tell in drupal, if your page is going to be printed.

CSS and media queries is browser based. You deliver the same content (html) and the browser will generate different output for display and print.

If you want to do deliver a special print version, you have to provide a different url for this and link it on your page, for example a print button. You can then check in the twig for the special url and change the html.

---
Tags: 8, theming
---


# Question
Title: How to set a menu link to user/edit in Drupalgap?
I do not need the profile view tab and would like to link from a menu directly to user/%/edit/. In settings.js below I tried different paths, none of which worked.

```
// User Menu Authenticated
drupalgap.settings.menus['user_menu_authenticated'] = {
 options: menu_popup_get_default_options(),
 links: [
{
  title: 'My Account',
  path: 'user',
  path: 'user/%/edit', //not working
  path: 'user/edit', // not working
  options: {
    attributes: {
      'data-icon': 'user',
      'class': 'ui-btn ui-btn-icon-right'
    }
  }
},

```

Is there a (simple) way to set such a direct link?

# Answer
When the `settings.js` file is loaded in DrupalGap, the framework isn't yet aware of who the current user is, so it is not possible to place this type of dynamic link into traditional DrupalGap menus. Instead you can use a block to simulate a dynamic menu.

http://docs.drupalgap.org/7/Menus/Menus\_with\_Dynamic\_Links

```
/**
 * Implements hook_block_info().
 */
function my_module_block_info() {
  try {
    var blocks = {};
    blocks['my_module_user_menu'] = {
      delta: 'my_module_user_menu',
      module: 'my_module'
    }
    return blocks;
  }
  catch (error) { console.log('my_module_block_info - ' + error); }
}

/**
 * Implements hook_block_view().
 */
function my_module_block_view(delta, region) {
  try {
    var content = '';
    switch (delta) {
      case 'my_module_user_menu':
        var uid = Drupal.user.uid;
        var html = theme('popup', {
            content: theme('jqm_item_list', {
                items: [
                  l('View profile', 'user'),
                  l('Edit account', 'user/' + uid + '/edit'),
                  l('Logout', 'user/logout')
                ]
            }),
            attributes: {
              id: drupalgap_get_page_id() + '_my_module_user_menu'
            },
            button_attributes: {
              'data-icon': 'bars',
              'data-iconpos': 'notext',
              'class': 'ui-btn-left'
            }
        });
        return html;
        break;
    }
    return content;
  }
  catch (error) { console.log('my_module_block_view - ' + error); }
}

```
> 3 votes

---
Tags: users, javascript
---


# Question
Title: How to place blocks in code with zen theme?
I've been tasked with maintaining a site I didn't make and I don't have access to the original developers.

The site is built with a custom zen theme. The block that I'm interested in is listed in the disabled section of blocks and is configured to the "None" region of the enabled themes and is set to be displayed on all pages with no restriction for users or content types. There doesn't appear to be any obvious settings in the page that the block is on or in the block itself that would determine it's placement. So, I'm a little lost as to how to proceed. Any advice would be appreciated.

# Answer
> 1 votes
Add the following function in your template.php

```
function THEMENAME_render_block($module, $delta, array $options = array()){
  $default_options = array(
    'title' => '<none>',
    'region' => -1,
  );

  $options = array_merge($default_options, $options);

  $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  if($block) {
    $block = block_load($module, $delta);
    $block->title = $options['title'];
    $block->region = $options['region'];
    $blocks = array($block);
    $rblocks = _block_render_blocks($blocks);
    $render_array = _block_get_renderable_array($rblocks);
    return drupal_render($render_array);
  }
  return "";
}

```

then in your tpl file of your specific page/node

```
<?php print THEMENAME_render_block('<moduleName>', 'delta', array('title' => t('Block Title'))); ?>

```

---
Tags: blocks, theming
---