title: Role creation in drupal at multi level?

text:
# Question
Title: Role creation in drupal at multi level?
I want to create to some role as business manager,manager and last is handler. Business manager should have the role who can create manager user . Manager role should have the privilege who can create the handler user.

# Answer
Check once subuser or subs\_roles. May be helpful in your scenario.
> 1 votes

---
Tags: users
---


# Question
Title: What's difference between node_revision__field_X and node__field_X tables in Drupal 8?
I'm in the process of migrating a complex D6 site up to D8 using the Migration tool. An old table `content_field_gallery` seems to have been migrated to a `node_revision__field_gallery` table, but there is also a `node__field_gallery` table with about half as many rows.

I'm guessing that the `node__field_X` version has only the latest revision and the `node_revision__field_X` has ALL revisions. Is that correct? Isn't that redundant? And a good index should make a single table pretty efficient? Where can I read more about this?

# Answer
Yes, that is correct. This is the same data structure as in Drupal 7.

It would be possible to write a different backend that only uses one table, there was a project for that for Drupal 7 but I think it never really took off.

See https://www.drupal.org/node/2083451 for a discussion if that's still necessary or not.
> 4 votes

---
Tags: entities, 8
---


# Question
Title: Why doesn't hook_preprocess_node() get triggered?
I use the following code in a theme whose machine name is yokai.

```
// works like expected, output visible
function yokai_preprocess_html(&$variables) {
  dpm('yokai_preprocess_html');
  dpm($variables);
}

// does not work, no output visible
function yokai_preprocess_node(&$variables) {
  dpm('yokai_preprocess_node');
  dpm($variables);
}

```

Why doesn't `hook_preprocess_node()` get triggered?

# Answer
The problem is with `dpm()`. This uses `drupal_set_message()`, which uses the session variable to store messages:

```
function dpm($input, $name = NULL, $type = 'status') {
  if (\Drupal::currentUser()->hasPermission('access devel information')) {
    $export = kprint_r($input, TRUE, $name);
    drupal_set_message($export, $type, TRUE);
  }
  return $input;
}

```

When the node template is processed, the page is already built with the session variables at this point. Any messages that come later will not make it on the page. In this case better use kint(). dpm() is more usefull for debugging code that doesn't produce a page output, like form validation.
> 1 votes

---
Tags: theming
---


# Question
Title: User login API for social login from mobile apps
I have installed HybridAuth module for social login (Only Facebook & Google) and It is working fine.

I need the same functionality for mobile apps. Like the user can able to login using the social accounts from mobile apps also.

Please suggest me how to do. Is it possible to do with HybridAuth module or I need to do different way?

# Answer
I was also looking for functionality that you needs, but after wards i tried to implement service for social sign in using Hybridauth module and i succeed.

Try this https://github.com/rathodhiren9/hybridauth-service.git

**Note** : Its my own implementation and working fine using Poster/Postman. But you need to test in mobile application on your own.

1. Place this module folder in /sites/all/modules/custom and give full permissions if you are using Linux/Unix.
2. Look for Hybridauth Services in you all module list from Admin pannel of drupal 7 and install/activate it.
3. Now goto structure/services and add new endpoint if you don't have (remember Path to endpoint will be used in your URL call of service from mobile app).

4. After that you need to add Resources as per you requirement and for this service you need to check "hybridauth" resource and "connect" action from available resources and save the configuration.
5. Now this service will work from URL like **/domainname/path-to-endpoint/hybridauth/connect**. Be sure that url of your domain must match with your social media app's url that you are using for facebook or google
6. If your done well all the steps then you surly will test the service from Postman or Poster tools, But you need to get access token which will be an array of user data came from Facebook or Google and you will easily get it by debugging Hybridauth module's hybridauth.pages.inc file.

Hope this may be helpful.
> 3 votes

# Answer
Use Services Drupal module and use the hybridauth endpoint with JSON data.
> 1 votes

---
Tags: 7, users, services, authentication-authorization
---


# Question
Title: Architecture for login in. Accessing Drupal serivces from a phonegap mobile app
I want admins login in a drupal website to create nodes that are specific to clients. And clients login in using a mobile app to retrieve the node's info.

**I'm not a 100% sure of the best architecture practice for this. Any suggestions or tutorials?**

For the website, I've got Drupal 7 with services 3 using Rest and I'm creating some nodes. I've got the Oath module set up but using session could be easier.

For the app, I followed the phonegap tutorial until it showed the phonegap hello word, then I just started modifying index.html.

PS:JQuery's AJAX Post probably not a good idea because the requests can not successfully retrieve data from a different domain, subdomain, or protocol.

PSS: If it's possible, maybe I should include Drupal for the mobile part too instead of just the website that creates the services. This way I can use drupal\_http\_request

PSSS: Looks like I could use php's curl but would it work with a simple phonegap env

# Answer
> 1 votes
You are right to be using services.

I guess you've got this bit but i'll write it all the same: You need to obtain an anonymous user session via services and then use those details in the user login call.

Re the not being able to access across domains, its not jquery but actually the browser stopping this on your computer. But when you are using the webview component in your app it won't stop it.

Sounds like you are on the right track, just crack as your main problem shouldnt occur :)

Edit: On reflection maybe that isnt totally helpfull

You could consider using Sencha Touch for this purpose. http://www.sencha.com/products/touch/

It kind of pitches itself as something you could use instead of native code, but ibuilt some pretty chunky ipad stuff on it and it begun to chug. Don't expect all transitions to be as smooth etc.

However, it does give you some great data/store tools

Sencha 2 is just about out check the documentation for the rest proxy http://docs.sencha.com/touch/2-0/#!/api/Ext.data.RestProxy

this would make handling lists and viewing content very easy

a good example from sencha 1.1 is http://dev.sencha.com/deploy/touch/examples/oreilly/ as it shows how you might extend a 'panel' to be a node view equivalent for the webapp. The syntax will be different in 2.0 but its a good way of thinking

I'm beginning to ramble now. Take a look and i'll dig out some code snippets if you choose it

# Answer
> 0 votes
i think u can use this link http://drupal.org/project/phonegap and it allows you to authenticate and by default it allows you to add article node it works very well for me u just need to goto settings add your drupal site URL and than Authenticate with your Drupal site Credentials and than You can add articles its great module but definately expecting more and more functionality

# Answer
> 0 votes
DrupalGap is an open source mobile application development kit for Drupal websites. It uses PhoneGap and jQueryMobile, and takes much of the work out of creating mobile applications for Drupal websites.

# Answer
> 0 votes
You can use jdrupal.js to perform number of operation on Drupal site using services module.

---
Tags: 7, users, services, theming
---


# Question
Title: debugging an array while creating custom rule
I am trying debug a custom rule I am creating. In my helper function I am calling an array I want to work with. I want to dpm the contents of the array so that I can see what is available, but it is not working. To check that there wasn't a problem with my array. I set up a new one inside the helper function.

```
$array = [
      "foo" => "bar",
      "bar" => "foo",
  ];

```

and then try to dpm the array:

```
dpm ("array: " . $array);

```

but all that is shown in the status message is:

```
array: Array

```

I have been trying other methods of printing the array like print\_r but haven't had any success with these either. How should I be printing my array?

# Answer
> 1 votes
You can only have a *string* (not an array) as the second argument to `dpm()`.

Try:

```
dpm($array, "array: ");

```

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


# Question
Title: How can i display view specific content type based on dynamic term name in node page?
Hi i have a content type called "**Resource**" with 2 term reference fields, **branches (A,B,C,D)** other one is **resource category (rec cat 1,rec cat 2)** ,and i have created view called **branches list** displayed all branches like below in one node page.

```
A
B
C
D

```

and i have created another view called **resources list** it contains info based on resource category term reference it's ok but i need to display this view items based dynamic branch term name in my node page like when i click **A** need to display related branch info in my node page.

Please Advice.

# Answer
> 0 votes
The resource list view should accept the branch as ***contextual filter***. Have a look here: Views contextual filters taxonomy name

Maybe also consider using quicktabs for showing these views.

---
Tags: 7, views
---


# Question
Title: What's the purpose of the semaphore table?
I understand the purpose a semaphores in IPC programming but I'm not finding a good, or any, explanation as to the purpose of this table.

# Answer
> 15 votes
The semaphore table is used from the locking mechanism implemented by default from Drupal. It is not different from the usual mechanism of locking seen in programming: A value is used to verify an *operation* is already in progress, to avoid conflicts or race conditions. The difference is that, normally, the lock is stored in a file, while Drupal stores it in a database row.

In fact, the locking mechanism has functions to acquire a lock (`lock_acquire()`), or wait a lock is released (`lock_wait()`). In both the cases, the semaphore database is used.

```
// Optimistically try to acquire the lock, then retry once if it fails.
// The first time through the loop cannot be a retry.
$retry = FALSE;
// We always want to do this code at least once.
do {
  try {
    db_insert('semaphore')
      ->fields(array(
        'name' => $name,
        'value' => _lock_id(),
        'expire' => $expire,
      ))
      ->execute();
    // We track all acquired locks in the global variable.
    $locks[$name] = TRUE;
    // We never need to try again.
    $retry = FALSE;
  }
  catch (PDOException $e) {
    // Suppress the error. If this is our first pass through the loop,
    // then $retry is FALSE. In this case, the insert must have failed
    // meaning some other request acquired the lock but did not release it.
    // We decide whether to retry by checking lock_may_be_available()
    // Since this will break the lock in case it is expired.
    $retry = $retry ? FALSE : lock_may_be_available($name);
  }
}

```

```
$lock = db_query('SELECT expire, value FROM {semaphore} WHERE name = :name', array(':name' => $name))->fetchAssoc();
if (!$lock) {
  return TRUE;
}
$expire = (float) $lock['expire'];
$now = microtime(TRUE);
if ($now > $expire) {
  // We check two conditions to prevent a race condition where another
  // request acquired the lock and set a new expire time. We add a small
  // number to $expire to avoid errors with float to string conversion.
  return (bool) db_delete('semaphore')
    ->condition('name', $name)
    ->condition('value', $lock['value'])
    ->condition('expire', 0.0001 + $expire, '<=')
    ->execute();
}
return FALSE;

```

In Drupal, different users can requests the same page, which means different threads or processes could execute the same code at the same time. This could cause problems when the code is, for example, updating a database table. Using locks is a way to avoid this could cause problems.

The reason a database table is used is simply that Drupal requires a database engine to work; using a database table also for the locking mechanism is a way to reduce the requirements. The locking mechanism could be implemented using the APCu extension too, and if I recall correctly, there is a module doing that.

# Answer
> 8 votes
The answer from @kiamlaluno is complete and perfect. But, I think it focuses on explaining (brilliantly) the concept/use of db locking using drupal's semaphores.

I would in turn venture getting closer to the OP:

The purpose of the semaphore table is (as described in the semaphore table creation description):

> Table for holding semaphores, locks, flags, etc. that cannot be stored as Drupal variables since they must not be cached.

So, the purpose of that table is more than just db locking mechanisms (so far I can understand from that comment), and it also addresses the technical requirement of avoiding caching of variables.

N.B.: Will be happy to be corrected by someone with more expertise on this topic if I got this wrong. Cheers!

---
Tags: database
---


# Question
Title: How to create programmatically menu links with just created nodes during installation profile in aegir ?can't get nid!
I am creating a set of nodes in an installation profile. When I try to create menu links for them in the same PROFILE\_NAME.install, the links don't get created.

I have also tried creating the menus links in a separate module, and using `hook_update_N()` to enable them, but that also does not work.

When I uninstall the module and reactivate it, it creates correctly my menu's links correctly.

I tried to use `hook_install_tasks()` and put it in MYPROFILE\_NAME.profile or MYPROFILE\_NAME.install, but this also doesn't work.

How can I create menu links for nodes created as part of an installation profile?

My code for creating the nodes in MY\_PROFILE\_NAME.install is:

```
// creation of my nodes (same content for all)
   $nodi = array(
       // i have other 14 nodes
      'title' => array('Home'),
       // i have other 14 paths for the nodes
      'path' => array('home'),
   );
$titoli = array();
$titoli = $nodi['title'];
$percorsi = array();
$percorsi = $nodi['path'];
//CREAZIONI DEL CONTENUTO PROGRAMMATICAMENTE
  for($i = 0; $i< count($titoli); $i++){
$testo_body = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec feugiat velit eget metus placerat,varius eros facilisis. Aenean aliquam imperdiet nisl ut dapibus...';
           $node = new stdClass(); // nuovo oggetto nodo
           $lingua = 'it';
           $node->type = "page"; //
           $node->title = $titoli[$i];
           $node->language = $lingua;
           $node->path = array('alias' => $percorsi[$i]); // i think here is the problem !!!
           $node->uid = 1; // admin
           $node->status = 1;
           // Body field
           $body_field_info = field_info_field('body');
           if (field_is_translatable('node', $body_field_info)) {
              $body_lingua = field_valid_language($lingua);
           }else{
              $body_lingua = LANGUAGE_NONE;
           }
           $node->body[$body_lingua][0]['value'] = $testo_body;
           $node->body[$body_lingua][0]['summary'] = 'text...';
           $node->body[$body_lingua][0]['format'] = 'full_html';
           $node = node_submit($node); // Prepare node for a submit
           node_save($node); // After this call we'll get a nid

```

And my code for creating the menu links is:

```

    // Create a Home link in the main menu.
  $path = drupal_lookup_path('source', 'home');
  $item = array(
    'link_path' => $path,
    'router_path' => $path,
    'link_title' => st('Home'),
    'menu_name' => 'main-menu',
    'weight' => -50,
    'customized' => 1,
    'plid' => 0, // Parent menu item, 0 if menu item is on top level
  );
  menu_link_save($item);
  menu_rebuild();

```

# Update 2

The menus are created in the menu\_links table but with empty **link\_path** so i can't get the nid created nodes. *I treid also to override the install\_finished() and put my function for creating menus in .install or in .profile files, but it's the same.* Any ideas?

# Answer
> 0 votes
```
$nodi = array(
        'title' => array(
                 'Home' ,
                 'Presentazione' ,
                         'Obiettivi' ,
                         'Comitato organizzatore' ,
                         'Patrocini' ,
                         'Edizioni passate' ,
                        // 'Calendario eventi' ,
                 'Materiali' ,
                         'Cartelle stampa' ,
                         'Documentazione' ,
                         'Video' ,
                 'Dove siamo' ,
                 'Contatti',
        ),
        'path' => array(
                 'home' ,
                 'presentazione' ,
                         'obiettivi' ,
                         'comitato-organizzatore' ,
                         'patrocini' ,
                         'edizioni-passate' ,
                  //'calendar-node-field-date/month' ,
                 'materiali' ,
                         'cartelle-stampa' ,
                         'documentazione' ,
                         'video' ,
                 'dove-siamo' ,
                 'contatti',
        ),
    );
    $titoli = array();
    $titoli = $nodi['title'];
    $percorsi = array();
    $percorsi = $nodi['path'];
    $miei_path = array();
    $alias = array();

    //CREAZIONI DEL CONTENUTO PROGRAMMATICAMENTE
      for($i = 0; $i< count($titoli); $i++){
        //SE È IL CALENDARIO O GALLERIA DELLE IMMAGINI NON CREARE LE PAGINE PERCHÉ CI SONO GIÀ

               $testo_body = 'Lorem ipsum dolor ..';
               $node = new stdClass(); // nuovo oggetto nodo
               $lingua = 'it';
               $node->type = "page";

               node_object_prepare($node); // Set some default values.

               $node->title = $titoli[$i];
               $node->language = $lingua; //non settato LANGUAGE_NONE
               $node->path['pathauto'] = 0;
               $node->uid = 1; // admin
               $node->status = 1;
               $node->comment = 0;
               $node->promote = 0;
               $node->moderate = 0;
               $node->sticky = 0;
               // Body field
               $body_field_info = field_info_field('body');
               if (field_is_translatable('node', $body_field_info)) {
                  $body_lingua = field_valid_language($lingua);
               }else{
                  $body_lingua = LANGUAGE_NONE;
               }
               $node->body[$body_lingua][0]['value'] = $testo_body;
               $node->body[$body_lingua][0]['summary'] = 'Questo è un testo esempio.';
               $node->body[$body_lingua][0]['format'] = 'full_html';
              $node = node_submit($node); // Prepare node for a submit

               $node->path = array('alias' => ('content/'.$percorsi[$i]));         // Setting a node path
              node_save($node); // After this call we'll get a nid

              $mio_path = $node->nid;
              $miei_path[$i] = $mio_path;
              $mio_alias[$i] = $node->path['alias'];
              watchdog(WATCHDOG_INFO, "E' stato creato il nodo " . $titoli[$i] . " correttamente, con alias  ".$percorsi[$i] ."---- " . $mio_alias[$i]. "   ".var_dump($node->path), $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL);
              $fornt = "node/".$miei_path[0];
              variable_set('site_frontpage', $fornt);
        }

```

# Answer
> 1 votes
You can add a menu item using this

```
$item = array(
        'menu_name' => 'menu-name',
        'link_title' => 'Link title',
        'link_path' => 'node/'. $nid,
      );
menu_link_save($item);
//don't forget to clear menu cache after saving menu item
menu_cache_clear_all();

```

Hope this will help

**Updated Answer** As I looked into Drupal 7 standard profile installation file, that is standard.install (Line no 413), you can see "Home" link creation there.

```
// Create a Home link in the main menu.
  $item = array(
    'link_title' => st('Home'),
    'link_path' => '<front>',
    'menu_name' => 'main-menu',
  );
  menu_link_save($item);

  // Update the menu router information.
  menu_rebuild();

```

---
Tags: 7, routes, path-aliases, aegir, installation-profiles
---


title: Drupal 8 - Can't link custom CSS files

text:
# Question
Title: Drupal 8 - Can't link custom CSS files
We're trying to create our very first theme in drupal 8 and we're having some problems with it.

When we try to link our custom css and try to load the page it gives us

> The website encountered an unexpected error. Please try again later.

We've tried different solutions, but none of them worked and we're kinda lost.

here's our **Fubiz\_NJ.info.yml file**

```
name: Fubiz_NJ
description: Website homepage reproduction
type: theme
core: 8.x
libraries:
  - Fubiz_NJ/global-styling
  - Fubiz_NJ/global-scripts
stylesheets-remove:
  - core/assets/vendor/normalize-css/normalize.css
  - core/modules/system/css/system.module.css
  - core/modules/system/css/system.theme.css
  - core/modules/views/css/views.module.css

# Define regions
regions:
  header: 'Header'
  primary_menu: 'Primary Menu'
  secondary_menu: 'Secondary Menu'
  slideshow: Slideshow
  page_top: 'Page Top'
  content: 'Main content'
  footer: 'Footer'

```

and here's our **Fubiz\_NJ.Libraries.yml file**

```
global-styling:
    version: 1.0
        css:
            theme:
                css/style.css: {}

global-scripts:
    version: 1.0
        js:
            js/script.js: {}

```

We're both new to drupal so we don't really know where to look at this point, Hope you guys can help!

# Answer
> 3 votes
The libraries YAML file is not correct. In YAML, indentation matters. Additionally, spaces should be used instead of tabs.

```
global-styling:
    version: 1.0
    css:
        theme:
            css/style.css: {}

global-scripts:
    version: 1.0
    js:
        js/script.js: {}

```

---
Tags: 8, theming
---


# Question
Title: 8 - How to programmatically add terms to an existing Node
After loading a node with `Node::load` with an existing taxonomy field `abc` do I add a new term and save? Something like?

```
  $term = Term::load(123);
  $node->get('abc')->appendItem($term );

```

# Answer
> 6 votes
This is the correct long form, as in the comment of mradcliffe:

```
$node->get('abc')->appendItem(['target_id' => 123]);

```

You don't need to load the term, use the term id.

You can use shorter versions:

```
$node->abc->appendItem(['target_id' => 123]);
$node->abc[] = ['target_id' => 123];
$node->abc[] = '123';

```

# Answer
> -1 votes
Just check the following code, its a dummy code need to be test

```
use \Drupal\node\Entity\Node;

$node = Node::create([
      'type'        => 'article',
      'title'       => 'Druplicon test',
    ]);
    $node->set('myterm_field', 'NEW TERM');
    $node->save();

```

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


# Question
Title: How to count the number of posts by a author? D8
I see how to do this in D7. I tried to do something similar in D8.

I tried using Entity instead of Content because there is no content:nid option in D8 my view looked like this

```
(author) COUNT(File Usage: Entity ID) (Count by User) | Aggregation settings

```

but my results where all 0

# Answer
> 1 votes
There is no difference between Drupal 7 and Drupal 8 on how to accomplish this.

From a default Content view:

1. Add the "Content: Authored By" field to the view.
2. Click "Use Aggregation" and change to yes.
3. Click "Aggregation Settings" to the right of "Content: Title".
4. Change to COUNT and Entity ID respectively.

View export:

```
langcode: en
status: true
dependencies:
  module:
    - node
    - user
id: content_with_author_count
label: 'Content with author count'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: none
        options:
          offset: 0
      style:
        type: default
        options:
          grouping: {  }
          row_class: ''
          default_row_class: true
          uses_fields: false
      row:
        type: fields
        options:
          inline: {  }
          separator: ''
          hide_empty: false
          default_field_elements: true
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: count
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: false
          group_column: entity_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
        uid:
          id: uid
          table: node_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: author
          settings:
            link: 0
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          set_precision: false
          precision: 0
          decimal: .
          format_plural: 0
          format_plural_string: "1\x03@count"
          prefix: ''
          suffix: ''
          entity_type: node
          entity_field: uid
          plugin_id: field
      filters:
        status:
          value: true
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
      sorts: {  }
      header: {  }
      footer: {  }
      empty: {  }
      relationships:
        uid:
          id: uid
          table: node_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: author
          required: true
          entity_type: node
          entity_field: uid
          plugin_id: standard
      arguments: {  }
      display_extenders: {  }
      group_by: true
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }

```

# Answer
> -3 votes
Drupal 8 is new and many things still unclear. It will take some time before sufficient information will be available. If you need a quick solution I recommend to inspect database tables and get the needed information using db\_query and SQL select. Should be straightforward.

---
Tags: views, 8
---


# Question
Title: How to include most specific tpl files in a less specific tpl file?
I created a view with fields. I want to print the values of the fields. So I use `views-view-feilds.tpl.php` . Also I created a `views-view.tpl.php` to show the outer html elements. I performed `<?php
 include('views-view-fields.tpl.php');
?>` in `views-view.tpl.php` file. I got the output as my requirement. But I need to know if its the right method according to drupal or any other method is available?

# Answer
It can be difficult to track the way different template files are used. First, I recommend turning on theme debugging by putting this in your settings.php

```
$conf['theme_debug'] = TRUE;

```

See this documentation for more information about theme debugging: https://www.drupal.org/node/223440 The main thing to know about that option is that it will print out the file names of the templates being suggested.

For your specific question, php includes are not the mechanism by which themes reference other themes. Rather the variables in one template are often "render arrays" (arrays with a very particular structure that sets up certain template files to be called). Here is the documentation on Render arrays in Drupal 7: https://www.drupal.org/node/930760 Ultimately, changing the template file selected involves working with render arrays in one form or another.
> 1 votes

---
Tags: views, theming
---


# Question
Title: Drush sql-sync not placing file in specified dump-dir
I have a dev and staging alias setup for drush and they are both working correctly. I included a reference to where I want the dump file placed during a `drush sql-sync` using

```
  'path-aliases' => array(
    '%dump-dir' => '/home/.drush/db_dumps'
  )

```

However, when I run the command it runs successfully but it doesn't use my dump directory. Instead it uses */home/user/drush-backups*. I tried changing the location of my dump-dir to a location inside of the drupal site folder, but it still doesn't work.

One of the solutions that I found was to include the `--source-dump` option (which points to the same location as I have in `%dump-dir`) when running `drush sql-sync`. It seems like if that's the case, then why even bother adding it in my alias file.

Another solution states to also include a reference to the actual dump file using `%dump`in the path-aliases array. I tried that and it still doesn't work.

Is there a solution to this or is it not suppose to work at all?? Because the example.aliases.drushrc.php file doesn't mention dump-dir at all.

Using: Ubuntu 14.0.4, Drush 8.0.5, Drupal 8 site

Thanx

# Answer
I actually posted the same question in the Drush GitHub and they did in fact tell me that `sql-sync` was rewritten (removed in `e89c7c4`) and it no longer includes the option for a `dump-dir`.

As per GH #2125, they've said:

> It gzips and transfers the full dump every time. It uses a temp file in your specified temp dir for the transfer. Files are deleted right after rsync.

So I guess all documentation that is out there is old.
> 3 votes

---
Tags: drush
---


# Question
Title: Having trouble understanding private files in Drupal 7
I'm trying to set up private files on Drupal 7 using Organic Groups. So far, I have

**(1)** one group type that although I appear to have set it up as such

>

**(2)** have private files set up in as below. (The webroot is /var/www/html.)

>

**(3)** Ensured the link on the OG's page is `/system/files/test.example.doc`,

>

(4) I inspected the database entry and this appears to be good.

```
MariaDB [s7data]> select * from file_managed \G

*************************** XXX. row ***************************
      fid: 357
      uid: 103
 filename: test.pwww_.doc
      uri: private://test.pwww_.doc
 filemime: application/msword
 filesize: 9
   status: 1
timestamp: 1460390385
     uuid: 3a9877fc-77b2-47bc-8d4f-e8bc349f4c74

```

I am still able, using this link path do download that doc in a new browser without being logged in. In effect, this file is not private and does *not* require an authenticated session to download.

**Question:** Did I miss something? How does one set up private files correctly on Drupal 7?

# Answer
> 1 votes
> Whenever possible it's recommended that you choose a directory located outside of your Drupal root folder (or actually outside your web root), which may be tricky if you are on a shared host. If you do have access though, you can choose a private directory which will be on the same level as your web root directory (often called public\_html or www or similar).

From Working with files in Drupal 7 and Drupal 8.

The best practice is to place your private files outside of your webroot, so they should not be inside `/var/www` as that would make them accessible over the web. Place them in `/var/somefolder` instead, make sure your webserver has read write access to that folder. After that you should only be able to access them via `/system/files/test.example.doc` and it should not work for anonymous users.

UPDATE:

Above is based on the assumption you were accessing the file via `example.com/drupal-private-file-system/test.example.doc`. this can be prevented by using the linked best practise guide.

If an anonymous user can access your files with on url like `example.com/system/files/test.example.doc` you have a problem with your permissions and anonymous users are given the permission to download private files.

---
Tags: 7, files
---


title: How to debug custom node type

text:
# Question
Title: How to debug custom node type
I am following this guide to build a custom node type in Drupal 7:

http://www.sitepoint.com/creating-a-new-drupal-node-type/

Unfortunately, my code is not working and drupal is not outputting any error either. The module is there, is enabled, but the new custom type is not showing up. I have double checked the code several times and I'm sure I wrote it right, the same way of the guide.

How can I debug this kind of issue? I have installed the debug module, I am looking at the documentation here:

http://ratatosk.net/drupal/tutorials/debugging-drupal.html

but I'm a bit lost on where exactly should I up the debugging code to find the issue. I was hoping drupal has some kind of error log (like wordpress does) where I can see anything that goes wrong.

EDIT: I made the custom type work, now I can make a new custom type, but the code about the custom fields is ignored, like it's not there. Here the source of productcustomtype.install:

```
<?php
/**
 * Implements hook_install().
 */
function productcustomtype_install() {
    node_types_rebuild();
    $types = node_type_get_types();
    node_add_body_field($types['product']);
    productcustomtype_add_custom_fields();
}
/**
 * Implements hook_uninstall().
 */
function productcustomtype_uninstall() {
    $ournewtype = 'product';
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
    $result = db_query($sql, array(':type' => $ournewtype));
    $nodeids = array();
    foreach ($result as $row) {
        $nodeids[] = $row->nid;
    }
    node_delete_multiple($nodeids);
    productcustomtype_delete_custom_fields();
    node_type_delete($ournewtype);
    field_purge_batch(500);
}

function productcustomtype_delete_custom_fields() {
    foreach (array_keys(_productcustomtype_installed_fields()) as $field) {
        field_delete_field($field);
    }
    $instances = field_info_instances('node', 'product');
    foreach ($instances as $instance_name => $fieldinstance) {
        field_delete_instance($fieldinstance);
    }
}

function _productcustomtype_installed_fields() {
    $t = get_t();
    return array(
        'productcustomtype_price' => array(
            'field_name' => 'productcustomtype_price',
            'label' => $t('Price of the product'),
            'type' => 'text'
        ),
        'productcustomtype_quantity' => array(
            'field_name' => 'productcustomtype_quantity',
            'label' => $t('Quantity of the product'),
            'type' => 'text'
        )
    );
}

function _productcustomtype_installed_instances() {
    $t = get_t();
    return array(
        'productcustomtype_price' => array(
            'field_name' => 'productcustomtype_price',
            'type' => 'text',
            'label' => $t('Price of the product'),
            'widget' => array(
                'type' => 'text_textfield'
            ),
            'display' => array(
                'example_node_list' => array(
                    'label' => $t('Price of the product'),
                    'type' => 'text'
                )
            )
        ),
        'productcustomtype_quantity' => array(
            'field_name' => 'productcustomtype_quantity',
            'type' => 'text',
            'label' => $t('Quantity of the product'),
            'widget' => array(
                'type' => 'text_textfield'
            ),
            'display' => array(
                'example_node_list' => array(
                    'label' => $t('Quantity of the product'),
                    'type' => 'text'
                )
            )
        )
    );
}
function productcustomtype_add_custom_fields() {
    foreach (_productcustomtype_installed_fields() as $field) {
        field_create_field($field);
    }
    foreach (_productcustomtype_installed_instances() as $fieldinstance) {
        $fieldinstance['entity_type'] = 'node';
        $fieldinstance['bundle'] = 'product';
        print_r($fieldinstance);
        field_create_instance($fieldinstance);
    }
}

```

# Answer
> 0 votes
To make sure the changes apply and work, it is needed to disable the module and unistall it. This important step was missing on the guide.

---
Tags: 7, nodes, debugging
---


title: drupal field list data

text:
# Question
Title: drupal field list data
I have created a custom field list, but of all documentation I have read, I can't find a clear example on how to add data on the list.

The code so far is this:

```
/**
 * Adds field.
 */
function _my_installed_fields() {
  $t = get_t();
  return array(
    'my_dropdown_list' => array(
      'field_name' => 'my_dropdown_list',
      'label' => $t('Select an item'),
      'type' => 'list_text'
    )
  );
}
/**
 * Adds instances.
 */
function _my_installed_instances() {
  $t = get_t();
  return array(
    'my_dropdown_list' => array(
      'field_name' => 'my_dropdown_list',
      'type' => 'list_text',
      'label' => $t('Select an item'),
      'widget' => array(
        'type' => 'options_select'
      ),
      'display' => array(
        'example_node_list' => array(
          'label' => $t('Select n item'),
          'type' => 'list_text'
        )
      )
    )
  );
}

```

I need to let only one value to be selected and saved.

# Answer
Try to add cardinality and settings parameters:

```
  function _my_installed_fields() {
    $t = get_t();
    return array(
      'my_dropdown_list' => array(
        'field_name' => 'my_dropdown_list',
        'label' => $t('Select an item'),
        'type' => 'list_text',
        'cardinality' => 1,
        'settings' => array(
          'allowed_values' => array(
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
          ),
        ),
      )
    );
  }

```
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to "close" from view standard taxonomy page
I made several taxonomy dictionaries and all of them have terms. I use terms for Views generations. But standart drupal functionalaty lets end-user to enter as URL: "site/dictionary name/term name" and get list of materials which were marked by this term. How I can "close" this page? I do not want end-user to see my materials by this hack.

# Answer
Luckily there is module for that: Disable Term Node Listings

> By default, on taxonomy term pages, Drupal will display a list of nodes (teaser build mode) that are tagged with that term. Disable Term Node Listing allows you to selectively disable node listings on taxonomy term pages by vocabulary.
>
> Disable term listings for a particular vocabulary by going to the edit page \[/structure/taxonomy/\[vocab\_machine\_name\_here\]/edit\].
> 0 votes

# Answer
1) In hook menu alter:

```
/**
 * Implements hook_menu_alter().
 */
function yourmodule_menu_alter(&$items) {
  $items['taxonomy/term/%taxonomy_term']['access callback'] = FALSE;
  $items['taxonomy/term/%taxonomy_term/feed']['access callback'] = FALSE;
}

```

2) If you use Panels module:

* enable `Taxonomy term template` page
* create variant with type `HTTP response code`
* chose 403 of 404 `Responce code`
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Can we add the destination query parameter to a link from yml configuration?
When creating a link from yaml

ie: mymodule.links.action.yml

```
my_module.my_entity.add:
  route_name: node.add
  title: 'Add My Entity'
  route_parameters:
        node_type: 'my_entity'
  appears_on:
    - my_module.my_entity.admin_content

```

Is there a way that this links would be generated with the **?destination=path/to/redirect** ?

# Answer
Yes, you can add the destination query directly in the yml file. @see : \Drupal\Core\Menu\LocalActionDefault::getOptions

ie: mymodule.links.action.yml

```
my_module.my_entity.add:
  route_name: node.add
  title: 'Add My Entity'
  route_parameters:
        node_type: 'my_entity'
  options:
    query:
      destination: '/path/to/redirect'
  appears_on:
    - my_module.my_entity.admin_content

```
> 17 votes

# Answer
The query string is not part of the route. The controller fetches the query parameters from the webserver request and does the processing, in this case returns a redirect:

```
$request = \Drupal::request();
$destination = $request->query->get('destination');
return new RedirectResponse($destination);

```

When generating an url for the example mentioned in the question, the `node_type` is a parameter that goes into the route as configured in the routing yml file and the destination is a query parameter that is appended to the url and is not part of the route:

```
$url = \Drupal\Core\Url::fromRoute(
    'node.add',
     array('node_type' => $type->id()),
     array(
       'query' => array('destination' => $destination),
       'absolute' => TRUE,
     )
);

```

On both sides the routing system ignores whatever you put in the query of the url, you have to handle this in the code yourself.
> 13 votes

---
Tags: navigation, 8
---


# Question
Title: How should the content structure for a Comparison website look like?
What is the "right way" to build a community-oriented comparison system in Drupal 7? My primary question is do I need to hand-roll the DB code for this or is there a way to do it with existing Drupal techniques? My secondary question is how would you structure this in Drupal?

The entities of my site are as follows.

### User classes:

* *Administrators* (me \<=1)
* *Analysts* (trusted community moderators \<100)
* *Authenticated Users* (untrusted community content creators \<2000)
* *Anonymous* site visitors can view all of the reviews (billions of people :)

### Products:

* *product classes*. (e.g. Cameras, Laptops, Mobile Phones, etc). There will be \>500 product classes. *Analysts* can edit and manage *product classes* by adding *product feature types*, etc.
* *products* (e.g. Nikon D7000, Canon EOS Rebel, etc) are an instance of a *product class*. *Authenticated Users* can add/edit *products*.
* *product features* are the pre-defined set of features of a product class (e.g. Exposure Metering, Exposure Modes, White Balance, Max Shutter Speed, etc). These are administered by *Analysts*.
* *product feature types*. Each *product feature* must be of a certain type like a star rating, text, price, number, url, etc.

My initial solution was to create a custom content-type for each *product class*, then use Drupal fields for the *product features*. My concern with this approach is that I don't know how to allow semi-trusted *Analysts* to create and manage their own *product classes* and *product feature types* without giving them administrator privileges. Also, I imagine having hundreds of *product classes* and so it feels weird to have a custom content-type for each * product class\*.

I'm happy to do it the php-module way, or the pointy-clicky way. How would you approach this?

# Answer
> 1 votes
Your initial solution, having own content types, can also support that content editors can only edit their own content. Define an content type, setup user role for "Analysts", and set the appropriate user permissions for them.

Look at http://www.example.com/admin/people/permissions and http://www.example.com/admin/people/permissions/roles.

I'm assuming you have Drupal 7, but Drupal 6 has more or less the same functionality.

# Answer
> 1 votes
By using the Group module you might be able to get this to work. Below are some more details to match your content structure and users to the Group module's functionality.

# Part 1 - User classes

### Administrators

That's just the typical Drupal admin user (like user/1).

### Analysts

These "trusted community moderators" could be implement using a Group "role" named (eg) "Analysts".

### Authenticated Users

These "untrusted community content creators" are to be considered as the "members" of the Groups. Using Group "permissions" you'd grant them the appropriate authorizations they'd need to be able to create the content of the Group they belong to.

### Anonymous

These "site visitors" can view all of the reviews by using Group roles "anonymous" (if not logged in) and/or "outsiders" (logged in, but not considered as "members" of the Groups, like what you call "authenticated users"). You would grant them the permissions to view the actual Group content.

# Part 2 - Products

### Product classes

Create a Group "Type" for each of your "Product Classes", like Cameras, Laptops, Mobile Phones, etc. And create 1 Group (with a similar name?). So you would have like \>500 Group Types. And create a Group Role like "Analysts". That will give you the flexibility to tune the various permissions of each Group Type to fit your needs.

### Products

Products (e.g. Nikon D7000, Canon EOS Rebel, etc) can be implemented using content types. So that Authenticated Users can add/edit them. While such products (nodes) are being created and/or edited, they get stored within the appropriate group.

### Product features

A possibly implementation for the pre-defined set of features (e.g. Exposure Metering, Exposure Modes, White Balance, Max Shutter Speed, etc) might be to use another content type for them, so that they can be used (referred to) from within a "product" via an "entity reference" field. And by storing them in appropriate groups, you could set the Group permissions so that the administration of them is limited to the Analysts.

### Product feature types

These type like a star rating, text, price, number, url, etc. seem to just be an appropriate field for your content type used for Product Features.

---
Tags: 7, views
---


# Question
Title: How do I get the menu ID based on the menu title?
I am looking for a function to call like in the following snippet:

```
get_menu_id("my menu title");

```

Do you have any tips?

# Answer
> 2 votes
In short, you can't.

The title you see on the page and the title in the database are the same only in the case you are running an English-only website and the title\_callback is `t()`. If you are using Drupal 7, you aren't overriding string in settings.php.
Otherwise, the title is generated dynamically and it's literally impossible to find its value in the database.

# Answer
> 1 votes
I guess you could loop through the results of `menu_get_names()`, as in:

```
function get_menu_id($menu_title) {
    $menu_names = menu_get_names();
    foreach ($menu_names as $menu_name) {
        $menu = menu_load($menu_name);

        if ($menu['title'] == $menu_title) {
            return $menu_name;
        }
    }
}

```

---
Tags: routes
---


# Question
Title: how to add dropdown checkbox list in to the search api(facet api) display widget?
I want to have a checkbox list in search api(facet api) display widget.  links with checkboxes not user friendly when you have many items, but checkbox list is user friendly. I mean dropdown checkbox list. how can i do it?

# Answer
> 2 votes
What you need to do is:

* In your search api configuration (screen you attached), select "MultiSelect element".
* Install an appropriate dropdown widget, the jQuery UI MultiSelect Widget is probably the best option for what you need.
* Configure the jQuery UI MultiSelect Widget to target your Search API's MultiSelect element:
    1. First, figure out what the id or class of that MultiSelect field is. You can use your browser's "Inspect Element" function to figure that out while viewing the standard Search API Facets on a search page.
    2. Once you have the right class or id, go to the configuration page of the jQuery UI MultiSelect Widget (URL is sth like your.drupal.localhost/admin/config/user-interface/jquery\_ui\_multiselect\_widget) and add it in the "JQuery subselector" text box.

That's it, now you should have a the jQuery MultiSelect Widget rendering your standard Search API Facets MultiSelect field.

Here is a screenshot of the end result (search api block facet rendered as a jQuery UI MultiSelect Widget):

Let me know how this goes!

Appendix A: jQuery UI MultiSelect Widget Configuration

Appendix B: jQuery Update Configuration

---
Tags: search
---


# Question
Title: Adding components to a feature via Drush
I understand using 'drush fu' to look for changes to any components of an existing feature, but is there a way to add a component to an existing feature using drush? Right now I have to use the /admin tools to recreate, download the files, upload, etc. Would be nice if there was a way to do this process via drush.

# Answer
**Update:** there is a direct way to add components via Drush.

First, to list components `drush fc` (for *features components*) will list out all exportable components, including which, if any, feature they are currently exported to.

Next, `drush fe foo_feature variable:foo_var views_view:foo_view` will update, or create, a module named `foo_feature`. The output from `drush fc` can be used to populate the required `component:name` syntax.

**Original answer**

While there is no direct command, the quickest way to add components is by editing the `.info` file.

For example, to add a view `foo_view`, you would add this line:

```
features[views][] = "foo_view"

```

or, to add a variable that hadn't been added, you would add this line:

```
features[variable][] = "my_variable"

```

Once these have been added to the `.info` file, you can then run `drush fu`, and the additional components will be exported with your feature.

Update:

There *is* a command. See the below answer about the `drush fe` command.
> 39 votes

# Answer
There's been an on-going discussion about this topic, but it seems that drush features-export (drush fe) is the accepted solution.

To find the components (views, pages, etc.) you want to add to your feature, use `drush features-components`; this command has a relatively easy-to-use interface that should be familiar to anyone who has created Features through the admin graphical interface.

Once you've found the component you want, enter it in the pattern `drush fe [feature_name] [component_name]`, as in the following:

```
drush fe feature_name views_view:user_questions

```

### HISTORICAL INFO (deprecated)

Drush formerly used `drush features-add` for this functionality; the maintainers seem to have settled upon `drush features-export`.
> 17 votes

# Answer
*drush features-add* is deprecated. Use *drush features-export* instead. It will add components to existing features as well.

To get a list of exportable components first use

```
drush features-components --not-exported [pattern]

```

See *drush features-components --help* for how to use *\[pattern\]* to filter the components to be listed.
> 4 votes

# Answer
It's worth noting that quotes are required for permissions that have spaces in them. For example `drush fe fcc_user_config user_permission:"edit own content_type content"`
> 2 votes

---
Tags: drush, features
---


# Question
Title: How can an address database be converted to an account profile?
I imported an address database into Drupal as a content type and I want to convert into an account profile, with users having the ability to make changes it, and use some of the fields in it to link to other content. Are there some modules which can help accomplish that?

At the very least, after creating a Drupal account for each entry of the database, I should be able to link the user account to a particular record of that content type, or import some of the records fields into the profile.

# Answer
> 0 votes
If you want to keep current content type, add Reference field to your user and reference your type via reference field.

If you don't want to keep current content type, it is better to import the data directly into user fields.

---
Tags: 7, users
---


title: Get all instances of a content type

text:
# Question
Title: Get all instances of a content type
Is there a function in Drupal 7 to pull all instances of a specific content type to store in an array? Ex: Say I have a content type called "us\_states" and I want to pull each instance of that type (with it's saved data so the title, description, and the custom content I created) and store them into an array. How should I go about doing that?

# Answer
> 1 votes
Two options: `node_load_multiple()` function (deprecated) or `EntityFieldQuery` Class (preferred).

1. Example `node_load_multiple()`:

```
$nodes = node_load_multiple(array(), array('type' => 'us_states'));

```

> The second argument (`$conditions`) is marked as deprecated; and you can see that in the Drupal 8 documentation for the same function, it has been removed. I only included this example because I'm sure someone else would have pointed it out had I not and the fact that you specifically asked for a function.
2. Example `EntityFieldQuery` (Use this):

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'us_states');
$nodes = $query->execute();

```

In both examples, `$nodes` will be an array containing all nodes of the content type 'us\_states'. (Note that the nodes within the array will be objects per usual.)

If you really need to use a function (that won't be deprecated in Drupal 8), you can pass an array of Node IDs as the first param to `node_load_multiple()` that contains the Node IDs of all of the 'us\_states'.

# Answer
> 0 votes
You need to get an array of node ids from the database first. Simple `db_select` query will do the job.

```
$nids = db_select('node')
    ->fields('node', array('nid'))
    ->condition('node.type', 'us_states')
    ->execute()
    ->fetchCol();

```

And then pass that array to `node_load_multiple($nids)`.

You should be OK memory-wise when loading 50 nodes all at once. But you should be cautious when the total number of nodes is significant (more than 100 I'd say).

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


# Question
Title: How to change a fields label name based on another fields value?
I have a content type and it has two fields:

* Field One (select list)
* Field Two (text area)

What I want to do is to change Field Two's label name based on Field One's value in node add/edit page and node dipslay. If `Option 1` selected in Field One field, then make the Field Two's label name **Option 1** etc.

**How can I do this?**

# Answer
Using jQuery is the way to do go.

Since when you edit nodes it uses the admin theme (seven), we need to add the jQuery to the admin theme (seven).

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

Go to the folder `drupal/themes/seven` and edit **seven.info**

After `stylesheets[screen][] = style.css` add the following line

```
scripts[] = cool.js

```

Create cool.js inside the seven folder (path would be `drupal/themes/seven/cool.js`)

### cool.js

```
(function ($) {

   (function Forever(){ // we create a function called Forever

   var grabselectedtext = $('#edit-field-test-und option:checked').text();

     $('label').each(function(){
      if ($(this).attr('for') == 'edit-body-und-0-value') {

         if (grabselectedtext != '- None -') {
           $(this).text(grabselectedtext);
         } else {
             $(this).text('Field Two');
           }
         }

     });

   setTimeout(Forever, 1);

   })();

})(jQuery);

```

In this example the select list field is named `test` and the field to change label is the `body` field.

---

The above does exactly what you asked, but perhaps it might be even better (depending on your use case) if you hide the `body` field if the `test` field is equal to None. Then if the person selects something the body field reveals itself by sliding down.

### cool.js (option 2)

```
(function ($) {

  (function Forever(){ // we create a function called Forever

    var grabselectedtext = $('#edit-field-test-und option:checked').text();
    $('label').each(function(){
       if ($(this).attr('for') == 'edit-body-und-0-value') {

         if (grabselectedtext != '- None -') {
         $(this).text(grabselectedtext);
         $('#body-add-more-wrapper').slideDown(2000); // slides down in 2 seconds
         } else {
           $(this).text('Field Two');
           $('#body-add-more-wrapper').slideUp(2000); // slides up in 2 seconds
          }
     }

    });

  setTimeout(Forever, 1);

  })();

})(jQuery);

```

Then add this CSS to Seven's **style.css**

```
#body-add-more-wrapper { display: none; }

```

> **PS:** Not a good idea to use the body field for this, better create your own custom field, otherwise all body fields will be hidden. I didn't because I was lazy as this is just for example purposes.

### Result:
> 2 votes

# Answer
Consider using the Conditional Fields module. Excerpt from its project page:

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
>
> You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

So if you have like 6 possible values (Option 1, ... Option 6), as in your comment below the question, you could create 6 fields with label "Option 1", ..., "Option 6".

Not sure if it is acceptable to "split" your "Field Two" in like 6 separated fields, but at least it would change the field labels as you are asking for.
> 2 votes

---
Tags: entities
---


# Question
Title: How to display data from external tables in Drupal without coding?
I want Drupal users to be able to display data from external databases. There is no processing involved, just listing the results based on filters. What Drupal 7 techniques are capable of accomplishing this?

I am not interested in anything that requires coding, just using the admin modules. A little coding at the start to configure access to the external databases is fine, but the main linking and displaying shouldn't require coding.

# Answer
Have a look at the Forena module. You would use its report writing features (such as its WYSIWYG report writer and/or it's query builder) to first create a report that fits your needs. The result of it could be a tabular output and/or graph. After the report content matches the specifications, you could save it as (e.g.) a CSV file.

# Samples

1. Refer to this online example in the Forena demo site for a report you could (easily) create:

* Using Forena's **Query builder** you would create the required SQL statement (if you'd rather want to write the SQL with your favorite SQL editor that's another option).
    * Using forena's **WYSIWYG report writer** you would develop your custom report (if you'd rather want to write that report with your favorite XHTML editor that's another option).

Some more details about the sample report mentioned above:

* Use the "Parameters" pulldown option, to select any other state.
    * Note the **PDF** hyperlink: using that link, you'll get a PDF version of that report. When creating such report, you could as well ask for other (or additional) report export formats, one of them is **CSV** (or XLS, DOC, HTML, ...). This is how the CSV equivalent version of that sample report looks like.
2. The Master Summary with drill down sample report demonstrates how you can also "link" various reports together (while it also shows some of the charting features of Forena). Click on either any of those bars in the chart, or on the total-hyperlink in tabular report below the chart. Doing so will bring you to the report "for the selected state" (= the first sample report mentioned above).

# Direct access to data blocks

All *data blocks* are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at `/reports/sample.states`:

# Video tutorials

The Forena Video demos and tutorials contain quite some links to live demos. They should help a lot to get you started.

Disclosure: I'm a co-maintainer of Forena.
> 1 votes

---
Tags: 7, views, database
---


title: Anonymous cannot see cart in cart page

text:
# Question
Title: Anonymous cannot see cart in cart page
I need to debug an issue and don't know how to start.

If I'm logged in the cart works just fine but, if I log out and put something in my cart I see the object in the cart widget but not my cart page.

And this is the markup in the page.

I need a hint to understand where to start searching the issue because the cart page permission and the view permission I think are fine because I see them, but the content is wrong..

If I go in admin/structure/views/view/commerce\_cart\_form/edit page and I insert the order ID, I can see the right cart displayed in the right way..

Where can I start to debug this? Do you have a clue to where can the bug be?

I tried to put a couple of prints in the view header and the cart page remains blank. But why is the empty cart sentence not displayed if the order\_id is empty?
And why 2 different carts views in the same page act so differently?

# Answer
> 6 votes
My guess is you're experiencing a common issue with product permissions due to a relationship you've added from the line item to the referenced product. Open your View's advanced settings fieldset, and in the Query settings menu disable SQL rewriting. This will bypass the normal entity access check to see if a customer has the permission to directly view the related product data, which is fine for this View since we know the products in the cart will always come from line items the customer has created through Add to Cart forms.

See also: https://drupal.org/node/1276450

# Answer
> 0 votes
Another reason that other people might have is that anonymous user does not exist, got deleted somehow. So even if permissions allow anonymous to access cart, add orders, the cart remains empty because there is no anonymous role for users.

That is, uid=0 has to be in users table.

This fellow had a detailed answer that helped me, thanks to him: Commerce: anonymous checkout not working properly

---
Tags: views, commerce
---


# Question
Title: How to set file upload directory by parent node content type and node id
I am trying to set the upload directory for a file field to contain the content type (and node id) as part of the path.

The desired path for my public files field is `publication_documents/pub/content_type/node_id_of_node_this_was_uploaded_to/filename`

I have tokens installed, but it doesn't seem to offer me tokens related to the parent node in the upload directory setting:

Slide 30 of This slideshow seems to indicate that it is possible, but how can I do it?

In case it matters, I'm using the media and file\_entity modules.

# Answer
File (Field) Paths module should help you.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Does the $form['element']['#disabled'] = TRUE guarantee that the user cannot edit the field or is it just a UI setting
I have a form element like this:

```
$form['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Subject'),
  '#default_value' => $node->title,
  '#size' => 60,
  '#maxlength' => 128,
  '#disabled' => TRUE,

);

```

Does this make the field 100% non-editable by the user or is it still possible to set a value for this field using manual form submission using jQuery / Postman to the action URL?

# Answer
If you disable field in backend, the field value won't be actually changed even if you change it in HTML or by JS.
You can test it:
\- disable element in form alter
\- open element in Chrome inspector (or other) and remove `disabled` attribute
\- change value in field and save the form
\- changed value will not be saved
> 4 votes

---
Tags: forms
---


# Question
Title: How to set the value of a date field via Rules?
One content type in my Drupal page has a **date field**. After importing start hour, start minute and duration (*Integer values*) from an XML file, I want to set date field of the node via Rules. It seems that I cannot access the start date and duration of the date field.

Is there a solution to set the *start date, end date, repeating, etc.* ?

# Answer
Before you will be able to create a Rules Action like "Set a data value" for your date field, you have to make sure to add a Rules condition `Entity has field` (related to the field for which you want to set a value). And make sure to add that `Entity has field` condition BEFORE other Rules Conditions in which you might want to refer to this field.

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says:

> *The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*.

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

# Answer
I've been able to do something similar to this using Rules, Rules Link and VBO, wherein I alter the date field (using the Date module) of an Entity with a custom input used as a parameter in Rules when executing the rule via VBO, I did have to check that the Entity had the required field (as a condition) before being able to populate that field with the parameter input.

I hope that helps.
> 1 votes

---
Tags: 7, nodes, entities, rules, datetime
---


# Question
Title: Autocomplete views exposed textbox for Entity reference field
I've got 2 content types "Equipment" and "Machine" , "Equipment" content type consists of an entity reference field targeting "Machine" content types.

My goal is to provide an exposed filter for user so he/she can filter equipments based on Machine's model. If "`- Enable Render Views filters as select list`" is checked in field settings exposed filter type changes to "select list" but cause I've got more than 11000 different models of machines , this is not an appropriate tool for selecting the proper model.

so the question is how can I provide an autocomplete textbox widget for this field (like what is provided in node creation form)?

# Answer
> 0 votes
I found an answer here : Drupal 7 Views Autocomplete Filter | Code Karate

Following this solution I installed Views Autocomplete Filter module and then in the view, I added a relationship based on field machine model and then a filter of type title of machine was provided .

Everything works great now.

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


# Question
Title: Views adds "nid" to SELECT and GROUP BY when trying to aggregate by title
I tried to create a simple aggregated View, but Views added nid, even though I did not select it as a field, and also ruined my GROUP BY making the view unusable.

Any tips how to avoid this nid addition?

```
SELECT node.title AS node_title_1, node.nid AS nid, COUNT(node.title) AS node_title
FROM
{node} node
WHERE (( (node.type IN  ('my type')) ))
GROUP BY node_title_1, nid
LIMIT 10 OFFSET 0

```

# Answer
> 0 votes
Try to enable checkbox Query settings -\> Distinct in your view settings.

# Answer
> 0 votes
I get this too and I suspect it's because I'm using the Content row format. If it is an option for you, try switching the format to Fields.

---
Tags: views, css-js-aggregation
---


# Question
Title: How can I find user role based on user id?
There are many user list. My need is to find out user role based on their user id.

# Answer
Use user\_load() or global $user.

```
global $user;
$account = $user;
$role = $account->roles;// returns user role.

```

or

```
$user = user_load(uid);
$role = $user->roles;//return user role

```
> 3 votes

# Answer
If this is a common task on your website you could also use the administration views module. With this module you can create and manage user-lists and you can modify the view to your needs, with all the power of views (exposed filters, relationships ecetera):

> Filter all administrative views via AJAX. Perform any kind of bulk/mass operations on items in administrative views. Filter content by title, node type, author, published status, and/or vocabulary. Filter comments by title, author, node title, or published status. Filter users by name, ban/blocked status, or user roles.
> 1 votes

---
Tags: users
---


title: Mailchimp with Rules

text:
# Question
Title: Mailchimp with Rules
I installed MailChimp module and i am using Rules module to send emails to subscribed users. For gmail this emails are going in spam. But when i send an email from mailchimp, it's ok, no spam. There are 3 ways i see now -

1. Use rules and fetch subscribed users, then send email to them programmaticaly(worst)
2. Configure rules to send emails from mailchimp.
3. Find another way to send emails and not get to spam.

Can i somehow make campaigns for mailchimp and send them with rules automaticaly, or you can suggest another mail module for such task?

# Answer
> 2 votes
I'm not 100% sure how this works with your setup and Mailchimp, But i have all of my site emails sending through SendGrid using the SMTP Authentication Support module. So far none have been sent to spam.

One thing to note about SendGrid: Their free account sends your emails through a shared IP. Sometimes they can get blacklisted from time to time. But you can eventually purchase a private ip through them to ensure even better spam protection.

# Answer
> 0 votes
Try using the Mandrill module to deliver your Drupal email. Mandrill uses the same engine as Mailchimp (although you need a separate account). It will do a much better job of delivering email, and will also let you track bounces, opens and clicks within your email.

---
Tags: rules, emails
---


# Question
Title: How I can alter this form using another module?
```
function client_form($form, &$form_submit) {
  $form['Client_name'] = array(
    '#title' => t('Client Name'),
    '#type' => 'textfield',
    '#value'=> nameget(),
    //'#required' => TRUE,
  );
  $form['Address'] = array(
    '#title' => t('Address'),
    '#type' => 'textfield',
    '#required' => FALSE,
  );
  $form['City'] = array(
    '#title' => t('City'),
    '#type' => 'select',
    '#options'=> getcitylist(),
    //'#required' => TRUE,
  );
  $form['Cityadd'] = array(
    '#title' => t('Enter a new city'),
    '#type' => 'textfield',
    //'#required' => TRUE,
  );
  return $form;
}

```

# Answer
> 1 votes
Check if `$form['form_id']['#value']` is set using dpm(). or simply by visiting form display and using element inspection in browser. Most of the time it is like this:

```
<input type="hidden" name="form_id" value="search_block_form">

```

If yes, then you can implement in two ways:

* hook\_form\_FORM\_ID\_alter(): If you have less forms to alter. This is specific avoiding checking form\_ids and long switch statements to alter multiple forms as in hook\_form\_alter().
* hook\_form\_alter(): If you have many form that needs alter. This runs for all forms. This is global.

Else set it up on form.

# Answer
> 0 votes
By using hook\_form\_alter you can alter a form.

```
function MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
   //Check with your form_id
   if ($form_id == 'your_form_id') {
        //Alter fields here
   }
}

```

---
Tags: forms
---


# Question
Title: What is the best order of content deletion on Drupal sites?
Whenever I try to clean up a site.

I delete stuff in the wrong order, and then the site breaks.

Any guidelines on how to do this?

Content first, then content type? Blocks, views, what to delete first and in what order so things don't break?

# Answer
> 4 votes
Yes, delete content first, before you delete the content type. It won't actually break anything in core Drupal if you do delete the type first, but you'll end up with orphaned content; which can be a pain.

Beyond that it comes down to what custom/contrib modules you have installed, and how they're being used. There are hundreds of modules that make use of nodes/content types, all in different ways, so whether or not you would need to do anything specific for each of those depends on the module itself, and what it's expecting.

For example, deleting content and content types may or may not break a particular View, depending on how it's configured (maybe there's a custom preprocess function relying on the content type field not being empty).

Deleting a content type provided by a Feature might break something in that feature if there's custom code relying on it.

Blocks don't have any relation to nodes/content types by default, so if you have something installed which connects them, you might need to do something specific to avoid that module producing errors.

TLDR; there's no single answer - list out the modules you have installed, work out which ones of those have interaction with nodes and content types, and come up with a basic plan of action for each that you follow before deleting.

If that's too much work, then just make sure you remove *everything* in your site that relates to those nodes or content types before deleting them.

# Answer
> 1 votes
This question is a typical "tough topic" in the context of configuration management (not just in the context of a Drupal site). What makes it more challenging is that Drupal doesn't offer many facilities to perform "impact analysis", something like "*I want to remove this thing, so before doing so, how can I find out where it is being used?*". And the more critical your site (system) is, the more important it becomes to be able to predict, 100% sure, what the answer.

So if you're not sure/comfortable enough, then another approach that will prevent your site from breaking because of such cleanup operations is to try to "*copy everything-that-is-not-to-be-deleted to a (temporary) staging site, QA-test this staging site until it looks OK, and then use that staging site as your cleaned-up version of your site*".

To perform such copy operation, there are some typical Drupal modules / facilities you can take advantage of, as further detailed below.

*Attention*: this approach is going to take (way) more effort, but the quality of the ultimate result is (should be) way better also. And pretty sure it will prevent all kinds of situations that typically breaks your site when deleting things in your real site.

# Export/import functions

Use the typical export/import functions to copy all sorts of configuration related objects, such as views, rules, etc. The Features module is going to be a great help to at least create an inventory of all sorts of configuration items (fields, content types, etc) you should take into consideration.

While using functions such as import, Drupal error messages may tell you about the missing pieces you forgot. Such as in the question about "What may be causing 'fails the check integrity' in Rules?". Too bad, but that's what the purpose is of a staging site, right? And your real site should not be impacted by that ...

Using this approach, you're going to have a hard time to create "orphan" situations, such as a menu link that points to nowhere.

# Migrate D2D

Perform a Drupal-to-Drupal data migration. Here is a quote from that community documentation:

> The Drupal-to-Drupal data migration module (migrate\_d2d) extends the framework provided by the Migrate module to support migration of content and data from one Drupal installation to another. It understands the core schemas of Drupal 5, Drupal 6, and Drupal 7, as well as the contributed CCK module for versions 5 and 6.

Make sure to have a look at the **migrate\_d2d\_ui** submodule also. Here are some details about it (from the Drupal-to-Drupal data migration project page):

> With migrate\_d2d 2.1, we introduced a wizard-based UI for defining your Drupal-to-Drupal migrations. The wizard is appropriate for non-technical users to configure and run the Drupal-to-Drupal migration, and/or when you don't have to do any special manipulation of data along the way.
>
> Enabling the migrate\_d2d\_ui module will add an "Import from Drupal" subtab to the Migrate dashboard - visit that tab, enter the credentials for your source Drupal database (versions 5, 6, or 7), and follow the steps to define how your legacy content maps to the destination Drupal 7 site.

Obviously, in your case you'd only want to migrate the content that is not to be deleted.

**Note**: This Migrate module is now also part of core in Drupal 8. So the time invested in learning about it to get to Drupal 7, will increase your Drupal 8 readiness for later on also.

---
Tags: 7, views
---


title: Solr 5 incompatible schema.xml

text:
# Question
Title: Solr 5 incompatible schema.xml
An error kept showing after installing Search API for solr and after creating a server on drupal. (Solr 5.x)

***You are using an incompatible schema.xml configuration file. Please follow the instructions in the handbook for setting up Solr.***

Already copied alll configuration files from drupal module into: /opt/solr/server/solr/my-core/conf

what else to check?

# Answer
On Centos systems Solr assumes your cores will be stored in `/var/solr/data/[core-name]`.

So if your core is named `my-core`, Solr might already have created the folder `/var/solr/data/my-core` for you. Simply place the `conf` directory in that folder, overwriting anything that might already be in `conf`. No need to touch any of the other files.
> 1 votes

---
Tags: search
---


title: 7 - Add CSS to a LIST items in a block

text:
# Question
Title: 7 - Add CSS to a LIST items in a block
I'm trying to display a block on a left side bar with few links. I've created a block and it shows up with the links but NO CSS applied:

```
<div class="vertical-tabs">
    <ul class="ul.vertical-tabs-list">
        <li>
            <a href="/">Home</a>
        </li>
        <li>
            <a href="itemInfo">Site Info</a>
        </li>
        <li>
            <a href="jobs">Career</a>
        </li>
        <li>
            <a href="aboutus">About Us</a>
        </li>
    </ul>
</div>

```

When I check the elements in UI, it doesn't show the vertical-tabs class being applied.

I'm not looking for any custom form. I need to know how the CSS should be applied in this case.

Thanks.

# Answer
There's a template hook for this: `template_preprocess_block`

Use `$variables['classes_array']` to add classes to the block.
> 2 votes

# Answer
Try this

```
$block['content']['#attached']['css'][] = drupal_get_path('module','mymodule') . '/mymodule.css';

```
> 0 votes

# Answer
Try this for custom block

```
function my_module_block_view($delta = '')
{
  if($delta == 'my_module_delta')
  {
    drupal_add_js('path/to/file.js');
    drupal_add_css('path/to/file.css');
    $block = array
    (
      'subject' => t('My block title'),
      'content' => '<p>' . t('This is some text that will go in the block.') . '</p>',
    );
    return $block;
  }
}

```
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: How to create flexible number of columns in a Views table display?
I have created a content type where each user is allowed to post exactly one comment on each node.

Now I want to create a table with UserID and all the node title as columns so that the table will look something like this:

Any suggestions?

# Answer
To my knowledge you can't do this with (only) the Views module. But your question seems like a variation of something related to processing log messages. Digesting these messages is quite a challenge. That's why I've come up with my own "custom" report, as illustrated in this screenprint:

Within the "Report Execution Parameters" (collapsed in the screenprint above), I specify the search criteria of the log messages to be retrieved (like severity, User name, etc). And the red numbers are hyperlinks to get a drill down report of the specific messages for which I wanted more details (= to display the actual watchdog entries).

Some more details about the above table (to explain why it is similar to your question):

* Think of the columns (with headers starting with "Msg Type:...") as your "***Title XX***". While each row (= different message) is like your User "***1***", "***2***", "***3***".
* If there wouldn't have been any errors with (say) "Msg Type: Ajax" or "Msg Type: page not found", then the corresponding column wouldn't have been created.
* The red numbers (hyperlinks) are aggregated data, which in your case would correspond to commentXY (blank cells in your case would indicate that there is no such comment for user X and title Y).
* Some columns (like "Msg Type: Error" or "Msg type: PHP") contain a value for multiple rows.

Refer to my answer to "How to gets analyts and generate visual reports from sessions?" for more details about creating reports (tabular displays) as in the above screenprint.

In case you wonder "How did you do that?" (without checking out my answer in the above link): ***There's a module for it*** ... it's called Forena ... And the clue in this specific case is to use Forena to create a "Crosstab table".

Disclosure: I'm a co-maintainer of the Forena module.
> 0 votes

---
Tags: views
---


title: How can I add auto_increment field?

text:
# Question
Title: How can I add auto_increment field?
My requirement I want to create one custom module with some form field like id(auto\_increment),first name,last name,date of birth.

I want to store all the information in Drupal database through but id will be auto\_increment.

# Answer
> 2 votes
Have a look at hook\_schema()

The field you enter for the primary key will automatically become an auto\_increment field. Example from node module. As Vishal Kumar mentioned you need to register the field as `serial` as well. Both aspects combined make the field suitable for use as an identifier field.

```
function hook_schema() {
  $schema['node'] = array(
    // Example (partial) specification for table "node".
    'description' => 'The base table for nodes.',
    'fields' => array(
      'nid' => array(
        'description' => 'The primary identifier for a node.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),

      // ... (Any other fields)

    ),
    'indexes' => array(
    ),
    'unique keys' => array(
    ),
    'primary key' => array('nid'),
  );
  return $schema;
}

```

# Answer
> 1 votes
The code provided by @Neograph734 works.

Making field `serial` makes it `INT auto_increment`.

> Use 'serial' for auto incrementing fields. This will expand to 'INT auto\_increment' on MySQL.

Check the link: https://api.drupal.org/api/drupal/includes%21database%21schema.inc/group/schemaapi/7

---
Tags: forms
---


# Question
Title: Saving a data to two different nodes with same node id?
I am having this problem , i want to save the same data into two tables with the same node id. I want to use both the tables on two different places because data is changing in the first table and i want to keep a track to the older data in my second table.

```
$node->field_call_response['und'][0]['tid'] = $call_response;
$node_new->field_log_response['und'][0]['tid'] = $call_response;

```

# Answer
As Paul commented, there is already a system to keep track of changes. You can enable node revisioning through the UI by going to Config \> Structure \> Content types \> \[Content Type\] \> Edit and select the `Create new revision` option under `Publishing options`. Now every on-site node edit will be registered as a revision and the previous values are logged in the Revisions tab (next to edit).

If you need to programmatically create a new revision, you can do it as follows:

```
$node = node_load($nid);

$node->field_call_response['und'][0]['tid'] = $call_response;

$node->revision = 1; // Save new revision
$node->log = "Explain what you changed";
node_save($node);

```
> 0 votes

---
Tags: nodes
---


title: how to get row field for each node

text:
# Question
Title: how to get row field for each node
i created a field called : (sitename\_ar) and i have two rows (two domains) in {domain} field :

and i have in my database these two fields {node} and {domain\_access} :

and i want display in view page:

node : Title

node : Domain (sitename\_ar)

i have created a view and i added a Title field and a Global:php field to call rows from database :

and i addedd those lines :

but always it display the same field (the first row) :

How i can Join all those 3 fields and display for each node her domain (with sitename\_ar)

# Answer
> 0 votes
The error is in your php snippet. You request all rows, but `$query->fetchObject();` only returns the first one, as you do not iterate over them. Use something like `$query->fetchAll()` or `$query->fetchAllAssoc('domain_id');` instead to access all rows.

But, I think there must be smarter ways to handle this. Can't you add a `relationship` from the node to the domain? (I never used domain before). Such relationship would give you the domain entity associated with the node, so you always have the right one.

---
Tags: views, database, domain-access
---


title: How do I assign 'all' term to a node?

text:
# Question
Title: How do I assign 'all' term to a node?
I have a vocabulary (lets name it as 'Brands') which is getting filled by adding terms while creating a nodes.

I have a view which shows me the list of those nodes. This view has an exposed filters including the one filters nodes by Brand. There are nodes which must relate to all 'Brands'.

It is not possible to assign manually all existing brands to node while creating it because the vocabulary is kinda dynamic. That means they should pass filter with any term checked. Not when 'All', but when any of existing. It seems to be obvious but I can't see any way I can do that.

# Answer
> 2 votes
it was so stupidly simple... Just don't add any term and add a filter to the view

`having Brand one of .... OR having Brand empty(NULL)`

I should definitely stop looking for a complex solutions for a simple questions. Thanks anyway

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


# Question
Title: How to change date repeat display format
I am using date module & date repeat API but now i want to change repeat date format.Now repeat date is display in "Repeats 5 days " but i want to show only "5 days " instead of "Repeats 5 days"

# Answer
> 0 votes
Similar question was raised before. There is still no way to override the format of the Repeat rule via theme functions. The answer that was given for the linked question provides a possible workaround (quoted below).

> you may override `theme_date_repeat_field()`, which calls `date_repeat_rrule_description()`. You could call your own version of that function to customize the display.
>
> This would leave the contrib modules untouched, but you would be duplicating some effort and have more code to maintain.

There is an active issue for Date Repeat sub-module - Make Repeat Date Format/Display More Flexible which did not receive enough attention.

You can also patch the `date_repeat.module` directly and keep track of it during updates, but that is obviously not a desired way to go about this.

The function that constructs the output of the string you need to change is

```
function date_repeat_rrule_description()

```

check `$output` variable - that is what you are trying to modify.

---
Tags: 7, datetime
---


# Question
Title: After registration, store email address and redirect to to another page
I have this code working:

```
function custom_form_alter(&$form, &$form_state,$form_id) {
switch ($form_id) {
case 'user_register_form':
      $form['#submit'][] = 'custom_user_register_submit';
  break;
}
}

function custom_user_register_submit($form, &$form_state) {
$form_state['redirect'] = 'content/welcome';
}

```

This is working great no problems.

The node I'm redirecting to has a typical welcome message. Part of the message has: Your verification has been sent to (user's email address).

How do I get the registration email address for the welcome message?

I've created a custom template for the content/welcome node. Just not sure what to do from here.

# Answer
> 1 votes
In your submit handler, you could use `drupal_set_message` to set the message like this:

```
function custom_user_register_submit($form, &$form_state) {
  $form_state['redirect'] = 'content/welcome';
  drupal_set_message('Your mail is @mail', array('@mail' => $form_state['user']->mail));
}

```

You could also save it in the `$_SESSION` if you don't want to use drupal\_set\_message and get it from there.

---
Tags: redirection
---


# Question
Title: What are the minimum requirements for a custom Drupal 8 theme that can be enabled
I'm testing creating new themes in Drupal 8 and I'd like to know the very minimum it takes to create one that can be enabled. I'm not worried about any actual styling yet.

I've created a theme folder in themes called uktheme and I currently have a uktheme.info.yml file in that folder.

the contents of that file are

```
name: UK Theme
type: theme
description: 'Test theme'
package: Core

regions:
  header: Header
  primary_menu: 'Primary Menu'
  feature: 'Feature'
  content: 'Content'
  page_bottom: 'Page Bottom'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'

```

However I receive

```
The website encountered an unexpected error. Please try again later.

```

when attempting to go into the appearance settings. I do not believe it's my folder structure and location because I successfully created another theme copying the content of Bartik.

# Answer
Perhaps you've missed `core`.
Required params in `*.info.yml` are:
`name`
`description`
`type`
`core`
`regions:content`

Also you can check your `*.info.yml` for using tabs instead of spaces:

> Tabs are NOT allowed, use spaces ONLY.
> You MUST indent your properties and lists with 1 or more spaces.

See more in official docs: https://www.drupal.org/theme-guide/8/defining-a-theme
> 3 votes

# Answer
There is a space in your name, that should be wrapped in quotes: `name: 'UK Theme'`. That space could be causing an error as it produces invalid code.

And also I am pretty sure your theme does not ship with core ;)
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Send an email notification to admin prior to poll close date
I'm using Advanced Poll module and it has a nice "Time management" feature. We can schedule when to open or close the poll.

I want to send an email notification to the administrator one day prior to poll close date. So that, admin gets notified and create an another poll.

Is there any way to make this possible with Rules module or hooks?

# Answer
> 1 votes
You will need to create a Rule that will schedule component evaluation (send email).

**CREATE COMPONENT**

1. Create component plugin of type Rule (`admin/config/workflow/rules/components/add`) - name it "***Notify admin about poll closure***".
2. Provide a variable for the component to act on. Variable `Data type = Content`, `Label - Poll Node`, `Machine name = poll_node`, `Usage = Parameter`.

3. Add Conditions if you need any
4. Add Actions -\> Send HTML e-mail. Set you email parameters *below is the export of the component*

```
{ "rules_notify_admin_about_poll_closure" : {
    "LABEL" : "Notify admin about poll closure",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_i18n", "rules", "mimemail" ],
    "USES VARIABLES" : { "poll_node" : { "label" : "Poll Node", "type" : "node" } },
    "DO" : [
      { "mimemail" : {
          "key" : "poll_closure_notify_admin",
          "to" : "adminemail@email.com",
          "subject" : "Poll will close tomorrow",
          "body" : "Poll [poll-node:title] will close tomorrow",
          "plaintext" : [ "" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

---

**CREATE RULE**

1. React on Events: "`After saving new content of type Advanced Poll`", "`After updating existing content of type Advanced Poll`"
2. Add Conditions "Entity has field": Entity: `node`, Field: `advpoll_dates`
3. Add action "***Schedule component evaluation***" - select the component that you created "***Notify admin about poll closure***".

Scheduled Evaluation date -\> `node:advpoll-dates:value2`. Add offset "`-1 days`". This will schedule the email 1 day before poll closing.

Set an identifier to something like "*`Poll closure notification: [node:nid] - [node:title]`*". It should have unique values everytime new scheduled task is added in queue, that is why you should use `node:title` and `node:nid`.

Set Poll Node field to `node`.

Save your rule and test.

```
{ "rules_schedule_notification_about_poll_closure" : {
"LABEL" : "Schedule notification about poll closure",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_scheduler" ],
"ON" : {
  "node_insert--advpoll" : { "bundle" : "advpoll" },
  "node_update--advpoll" : { "bundle" : "advpoll" }
},
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "advpoll_dates" } }
],
"DO" : [
  { "schedule" : {
      "component" : "rules_notify_admin_about_poll_closure",
      "date" : {
        "select" : "node:advpoll-dates:value2",
        "date_offset" : { "value" : -86400 }
      },
      "identifier" : "Poll closure notification: [node:nid]",
      "param_poll_node" : [ "node" ]
    }
  }
]}}

```

---

I provided an export of the component and the rule that you can use and modify to your preference. Hope this helps.

P.S. Cron should be enabled and configured on your website in order for scheduled events to work properly.

---
Tags: 7, rules, polls
---


title: Custom navigation menu

text:
# Question
Title: Custom navigation menu
I'm developing a new theme for my Drupal 8 site. As below picture shows, I defined a **header** region and when I add navigation menu to that region, I have both **navigation menu** and default theme navigation in one place.

How can I show drupal navigation menu with the theme of my template and eliminate the menu of template?

Thanks

# Answer
> 0 votes
Okay, I found it and have this task done.

I went to `/core/themes/stable/templates/menu.html.twig` and put my style (taken from my html template) around followng part of twig file:

```
{% for item in items %}
  <li{{ item.attributes }}>

    {{ link(item.title, item.url) }}

    {% if item.below %}
      {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
    {% endif %}
  </li>
{% endfor %}

```

# Answer
> 0 votes
I suppose your theme is forcing a menu there through it's page.tpl.php (assuming Drupal 7). It is basically the same as what Bartik does in Bartik page.tpl.php on lines 127- 138.

Bartik however offers a setting for this on the theme configuration page Configuration \> Appearance \> Bartik \> Settings \> Main Menu checkbox.

Your theme might offer a similar checkbox. If it doesn't you'll need to remove the code snippet manually.

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