title: Loop through node reference

text:
# Question
Title: Loop through node reference
I want to send emails using email stored on node fields that are referenced twice by other two contents types. I have this content types relationship:

```
Content1
field1 (unlimited) - reference > Content2
                                 field2 (only 1) - reference > Content3
                                                               email

```

I want to send a email message to all itens on field1 using email field on Content3, after the node is created or updated.

I dont have experience with Rules looping. Ill appreciate any help.

Thanks!

# Answer
The Rule will react on event "After updating existing content of type Content1".

The Rule will have to utilize a component in order to reach the email field in Content3.

In short: Rule loops through Content1 reference field (may contain multiple references) and then component will process each referenced node of type Content2 and return a variable back to the Rule. Returned variable contains an email that is taken from the field of the node of type Content3.

**STEP 1 - Create Rules Component** (export below)

```
{ "rules_process_content2_return_email" : {
    "LABEL" : "Process Referenced Content2 Entity and Return Email",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "content2" : { "label" : "Content2", "type" : "node" },
      "email_address" : { "label" : "Email Address", "type" : "text", "parameter" : false }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "content2" ], "field" : "field_content_reference_2" } },
      { "entity_has_field" : {
          "entity" : [ "content2:field-content-reference-2" ],
          "field" : "field_email"
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : [ "content2:field-content-reference-2:field-email" ]
          },
          "PROVIDE" : { "variable_added" : { "email_address" : "Email Address" } }
        }
      },
      { "data_set" : {
          "data" : [ "email-address" ],
          "value" : [ "content2:field-content-reference-2:field-email" ]
        }
      }
    ],
    "PROVIDES VARIABLES" : [ "email_address" ]
  }
}

```

**STEP 2 - Create the Rule that uses Component above** (export below)

```
{ "rules_send_email" : {
    "LABEL" : "Send Email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update--content1" : { "bundle" : "content1" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-content-reference" ] },
          "ITEM" : { "content2_item" : "Content2 item" },
          "DO" : [
            { "component_rules_process_content2_return_email" : {
                "USING" : { "content2" : [ "content2-item" ] },
                "PROVIDE" : { "email_address" : { "email_address" : "Email Address" } }
              }
            },
            { "mail" : {
                "to" : "[email-address:value]",
                "subject" : "Test Email on Content1 Update",
                "message" : "[node:title] was updated",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

Replace "content1", "content2" and machine names of fields with your own content/fields machine names before importing. Modify to your liking.
> 5 votes

# Answer
I'm a bit confused by your example -- it might help if you said what your content types represent -- but I can tell you in general how to do this.

Let's assume that you want to send your email whenever a Content Type 3 is created or updated. I'm going to guess that Content Type 3 defines the content of an email somehow (i.e., data like the title from the email will be used in the email).

I'm also going to assume that somehow (again, a clearer example would help) that somehow, Content Type 1 and Content Type 2 define an email list to send to.

For your example to work at all, somehow your Type 3, when it changes, needs to have a field that somehow points back to your email list. Let's say that one of your types is an "email group", and one of your types are the emails that belong to each group (this is why we need you to be more clear). Then:

* You make a rule that triggers on the update and create events of the node.
* Using data selectors, you create an action loop under actions. Rules data selectors "drill down" into a data type. Since the update and create events get passed the node object, you'll see a "node" item. If you start selecting that node, the selectors will show you all of the node's fields. You want to select the multivalued field that points to, say, the email groups the message wants to send to. Now you have a loop that will take that field and go over each individual slot in that multi-valued field.
* Add an action to the loop (it's in the middle of the window in small print), OR add a sub-loop that goes from your Type 2 to your Type 1 (whatever makes sense in your example).
* The action of the inner loop is sending email. You can fill in the fields of the email using data selectors that pull the email fields from the node or one of the sub-items that you created from your loop(s). Note that you can also add tokens into your emails from the "Replacement Patterns" listed under each parameter of the emails.

This is a bit vague. If you'll make your example more concrete, I can make the answer more specific.

You can also send emails using Views Bulk Operations and Rules. But this does not appear to be what you want.
> 4 votes

---
Tags: rules, nodes
---


# Question
Title: Programmatically logout user without redirect
I have the following code in my module:

```
<?php

function MODULENAME_init() {
        if (!user_is_logged_in()) {
                global $user;
                $user = user_load(31);
                user_login_finalize();
        }
}

```

Purpose of this code is to log in all anonymous user as user with id 31. But with this code i can't even logout correctly:

```
if (user_is_logged_in() && request_uri() == '/user') {
    user_logout();
}

```

After i am visiting http://ggames.kz/user i am getting redirected back to the main page and so i am logged again as user 31. I want to log out any user when he's requesting http://ggames.kz/user and show a login form in order to log in as user with id 1.

# Answer
You need to change your hook code.

```
function MODULENAME_init() {
  if (!user_is_logged_in() && request_uri() != '/user') {
    // Log in the user as user #31.
  }
  elseif (user_is_logged_in() && request_uri() == '/user') {
    module_load_include('pages.inc', 'user');
    user_logout();
  }
}

```

Since `user_logout()` is defined in modules/user/user.pages.inc, you need to first load that file, and then call that function, or you will get an error about a not defined function. You don't need to first check the file has been already included, since it will not be included twice.

Keep in mind that http://ggames.kz/user could be directly accessed from users to see their user page, and that Drupal redirect logged-in users who try to access http://ggames.kz/user/login to http://ggames.kz/user.
> 8 votes

---
Tags: 7, users
---


# Question
Title: How to send after filtered views result in mail in drupal 7?
I have created a view in drupal 7 with filters.. View is working fine I need to send after filter view result in mail with ajax views. This time I am not using ajax so I am sending a filtered url in mail.. But I need to use ajax views. is it possible?

# Answer
I'm not totally sure what you mean by

> I need to send after filter view result in mail with ajax views

If you need to send to the list of items (e.g., the items are members with email addresses), then you should install Rules, and set up Views Bulk Operations as described in this Drupalize Me (i.e., Lulabot's teaching videos) series. Parts 18 through 21 describe how to take a view, and use Rules to make it do something like send an email.

If you'll expand a bit about what you're trying to do, I can be a bit more specific about this.
> 0 votes

---
Tags: views
---


# Question
Title: Redirect to custom URL while logging in user through Webform
I am hoping to register/login a user based on the values entered in Webform and then redirect to a URL based on a user type.

The problem is that everything works but the redirection. Seems like this line is the culprit:- `$form['#submit'][] = 'my_submit_handler_for_registration';`

Any help?

Thanks

Here is what I have done:-

```
function MYMODULE_webform_submission_insert($node, $submission) {

  $submitted_data = $submission->data;
    $full_name = $submitted_data[1][0];
    $user_name = $submitted_data[2][0];
    $password = $submitted_data[7][0];
    $fmno = $submitted_data[3][0];
    $role = $submitted_data[4][0];
    $where = $submitted_data[5][0];
    $when = $submitted_data[6][0];

    // For Redirection
    variable_set("redirect_to", $role);

    // Need to populate following data for registering the user.
    if ( empty($user_name)) {
      echo "<h2 style='font-size: 18px; font-family: Helvetica Neue, sans-serif !important; color: #A80C0C; '>No Username Found.</h2>";

      exit();
    }
    $user_data = array();
    $user_data['init'] = $user_name;
    $user_data['mail'] = $user_name;
    $user_data['name'] = $user_name;

    $user_data['field_full_name']['und'][0]['value'] = $full_name;
    $user_data['field_fmno']['und'][0]['value'] = $fmno;
    $user_data['field_interviewee_role']['und'][0]['value'] = $role;
    $user_data['field_where']['und'][0]['value'] = $where;
    $user_data['field_when']['und'][0]['value'] = $when;
    $user_data['pass'] = $password;
    $user_data['status'] = 1;

    $user_data['roles'] = array(); // You can specify any roles which you need

    $tomorrow_date = time() + (60 * 60 * 24);
    $date_after_two_days = time() + (60 * 60 * 48);

    // Check if any previous user with the same email exists?
    $previous_user = user_load_by_mail($user_name);

    if(!empty($previous_user)) {
      echo "<h2 style='font-size: 18px; font-family: Helvetica Neue, sans-serif !important; color: #0065bd; '>Another user exists with the same email. Please login or enter another user.</h2>";
    }
    else {

      //It'll add a new user here.
      $user = user_save('', $user_data);

      /*
      $arr = array ('name'=>$user_name,'pass'=>$password);
      // Finalize user login (modify $_SESSION, set login time in db)
      user_login_finalize($arr); */

      $form_state = array();
      $form_state['uid'] = $user->uid;
      //$form_state['redirect'] = 'registration';
      user_login_submit(array(), $form_state);
      //$new_user = user_load_by_mail($user_name);

    }

    return theme('register', array('output' => $submission));

}

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webform_client_form_31') {
     $form['#submit'][] = 'my_submit_handler_for_registration';
  }
}

function my_submit_handler_for_registration(&$form, &$form_state) {

  $redirecting_to = variable_get("redirect_to");
  if($redirecting_to == "McKinsey Solutions") {
    $redirecting_to = "frontmso";
  }
  else {
    $redirecting_to = "";
  }
  $form_state['redirect'] =  $redirecting_to;
}

```

# Answer
> 1 votes
Another current question here inspired me for this short solution within your hook\_webform\_submission\_insert():

```
 // Create user account.
 $my_user = user_save(NULL, $user_data);
 // Whether the user account was created successfully.
 if (!empty($my_user->uid)) {
   global $user;
   $user = $my_user;
   user_login_finalize($user_data);
   // Do the redirect here.
   drupal_goto('target_uri');
 }
 else {
   // User account could not be created. So do some error handling.
 }

```

---
Tags: webforms, users, redirection
---


# Question
Title: Entity Reference multi value fields, filter on parent
I have two content types: Family and Members. Family content type has an entity reference field of type Member and can have unlimited values(multiple values). My question is: How to create a view that enables me to filter Members based on Family. Thanks

# Answer
> 0 votes
* Add a **Contextual Filter** in your view, use the "Member" field (Entity Reference guess) from your content type "Family".
* Then add a relation in Relationship section, using the same field (Member).
* Add a *Title* field and use that relation.
* Pass the NID of your family has an Contextual Filter in your preview... you might get all the members of that family.

Notice: in yout Contextual Filter you have to select how will you pass the Contextual Filter (Family's NID in this case). You can add it via URL, etc.

# Answer
> 0 votes
I am not very sure what you want to achieve, but you can approach it in 3 ways:

1. you can display members like any other field on family page;
2. you can create a block listing members on family page (or any page where you can provide family node id as contextual filter);
3. you can create a drop-down of family node titles and select the select the family and corresponding list of members would appear.

---

1. For the first situation you don't need views, you can do it with field UI: Goto Content Types \> Family \> Manage Display\> Set Entity Reference field format to Rendered Entity
2. For the second situation, you will have to create a block view ; his page has detailed instructions: https://www.drupal.org/node/1841004
3. For the third situation you basically need to display the list of family as exposed filters in views; you might find this screen-cast helpful: https://youtu.be/4Pdii7aFIvc?t=16m15s

---
Tags: views, entities
---


# Question
Title: Drupal 8 css and images relative to root
I have the challenge that I want my site to be cache-able by and external varnish cache provider.

Most of my page gets cached nicely, but elements like the ico file, images and css are written with the full url in code and hence doesn't use the cached version.

`www.domain.com` points to `internal.domain.com`

When I go to `www.domain.com` the urls for the images looks like this

```
http://internal.domain.com/sites/default/files/styles/hero_full/public/hero/image.jpg?itok=WiCUbqbj

```

What I wanted was that it just wrote a url relative to the root of the site.

```
/sites/default/files/styles/hero_full/public/hero/image.jpg?itok=WiCUbqbj

```

The issue is the same with files included from the THEME.libraries.yml file.

# Answer
> 1 votes
Core actually did exactly that change just a few days ago, it will be like that in 8.0.3.

That said, your set up looks problematic to me, that's not going to be the only thing that somehow relies on the domain name. Usually the same domain is used?

---
Tags: 8, caching, proxies, cdn
---


# Question
Title: How to output view content as grid in custom template?
I have **created a view** for content type xyz with **fields** F1, F2,F3,F4.

I open the group "**advanced**", clicked on "**Theme: Information**".

There are couple of template files, that are used by view.

**I chosen the desired template and copy it into to the template folder**.

Now, from views module, in theme folder, I opened `views-view-grid.tpl.php` and copy the content of this file to the file I have created in my template folder.

**But output is not coming in grid format.**

**Is there any way to customize the fields of view in html structure?**

# Answer
> **what if I want to use html and php**

Ok, now that I remember there is another method.

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

```
function themename_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1"){
        $vars['fields']['title']->content = // do php or whatever you want to it here
      }
    }

```
* replace **themename** with your theme name
* replace **view\_name** with your view name
* replace **block\_1** with your machine name

To add html, Ex:

```
function themename_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1"){
  $a = $vars['fields']['title']->content;
  $vars['fields']['title']->content = "<div class='others'>" . $a . "</div>";
  }
}

```

**With this method your grid should remain intact.**
> 1 votes

# Answer
> Is there any way to customize the fields of view in html structure?

There are various methods to add html to your fields.

One of them if you just want to add divs to your fields

Another would be to REWRITE RESULTS. You need to use the replacement pattern.

ex: `<div class="cool"><b>[field_example]</b></div>`

**Note:** If you have more fields, they are not showing because they are below the body. If you want to show in the replacement patterns, you must in views drag and place the body field below them.

Also:

Make sure your format is Grid
> 0 votes

---
Tags: views, theming
---


# Question
Title: How to exclude recursive module dependencies?
Is there a way to exclude dependencies of dependencies? For example: **my\_module.info** contains `dependencies[] = views`

`dependencies[] = ctools`

**my\_sub\_module.info** contains

`dependencies[] = my_module`

On the module display page my\_sub\_modue will have my\_module, views and ctools as dependencies. I know this is the desired outcome in 99% of all situations but I was curious to know if there were a way to have only my\_module (or items explicitly stated in the info file) as the dependency for my\_sub\_module.

Thanks

# Answer
In my opinion, the best is have always in mind solid and stable solution.

If you have this problem you should change your design, not your code.

Your module should have a display, and your submodule should have a display who modifies your module's display.
> 0 votes

---
Tags: 7, .info
---


# Question
Title: Request passphrase at user registration and automatically assign role to user
Is there a module that would allow us to request an optional predefined pass-phrase/password at user registration?

So if the user fills in the pass-phrase he would be registered as a premium user or something, if not he would be set as a simple authenticated user.

By the way, I'm using Drupal 7.

# Answer
> 0 votes
1. Download Rules module
2. Enable Rules and Rules UI
3. In user fields, add a new text field. Name it ex: Catch Phrase (check mark the show on user registration)
4. Add a new rule

* **React on** (under user) **After saving a new user account**
    * Add Condition: **Data comparison** \>\> account:field-catch-phrase \>\> \[enter catch phrase\]
    * Add Action: (under user) **Add user Role** \>\> premium role
5. (optional) Download and enable Field Permission. With this you can hide the catch phrase field so it doesn't show up when they edit their user account.

# Answer
> 1 votes
Use the Rules module to implement such feature, as further detailed below.

**Step 1**: Add a field to the registration form, which wil be used to have a user enter your passphrase. Even though you can use any "machine name" for that field, let's assume you call it "`field_optionlist`"

**Step 2**: Use a variation of the Rule included in my answer to "How to specify a Rules condition related to select list values?". Here is what you should tune in that rule:

* Replace the **Rules event** to something like "After a new user submits a registration request"
* Replace the "Value C" in the **Rules condition** to the value of your passphrase
* For debugging reasons, start with a Drupal message to be shown (imilar to the rule mentioned above. After the message shows up as you want it to show, replace the Rules Action with something like "Assign role to user".

---
Tags: 7, users
---


title: How to theme only top level menu?

text:
# Question
Title: How to theme only top level menu?
I have the following menus

```
about us
    company
    menu 2
our work
    menu 1
    menu 2
news
contact
jobs

```

I like to insert an extra li between each top level menus (about us, our work, news, contact, jobs) to make them look like "**about us | our work | news | contact | jobs** "

I looked at template.php and I have themename\_menu\_link, but I don't know how to compare the variable to check if it is a top level menu or not.

# Answer
The only way I can think of is as follows:

**template.php**

```
<?php

function YOURTHEME_menu_tree__YOURMENUNAME(&$variables) {
    global $cur_level;
    $cur_level++;
    return '<ul class="menu level-' . $cur_level . '">' . $variables['tree'] . '</ul>';
}

?>

```

**page.tpl.php**

```
<?php print render(menu_tree('YOURMENUNAME')) ?>

```

This will give each level an unique class for it's level. Though, there is one big problem with this approach, and that is that menu\_tree is working from the bottom up. So you will end up in the following level classes:

```
ul .level-3
li
li
    ul .level-2
    li
    li
        ul .level-1
        li
    li
li

```

So, you can never actually be sure about which classname the top level will have, only if you know for sure that there will **always** be an X count of levels.

**Edit** So, just to be clear about my solution here above, this is the only way I can think of doing this programatically at theme level. If you could use a module like Nice Menu's (like suggested above) you should really be using that, since this is more a kind of workaround than a real solution to Drupal's sturdy menu system...
> 4 votes

# Answer
The above solutions only works if the number and structure of the menu links remain the same. The problem is whenever you'd add a link the level number of the top most ul changes. Whenever the top most ul number changes, your css that targets a ul class with that number breaks:

Here is a solution that fixes this problem:

In the first function we output the UL class when the UL is created.

```
    function YOURTHEME_menu_tree__menu_secondary_menu($variables) {
      global $cur_level_menu_secondary_menu;

      $class = ($cur_level_menu_secondary_menu == 1) ? 'secondary-menu' : 'secondary-menu--submenu';
      $output = '<ul class="' . $class . ' ' . 'secondary-menu--' . $cur_level_menu_secondary_menu . '">' . $variables['tree'] . '</ul>';
      $cur_level_menu_secondary_menu--;

      return $output;
     }

```

In the second function we save the current depth in a global variable `$cur_level_menu_secondary_menu`.

```
  function YOURTHEME_menu_link__menu_secondary_menu(array $variables) {
    $element = $variables['element'];

     global $cur_level_menu_secondary_menu;
     $cur_level_menu_secondary_menu = $element['#original_link']['depth'];

     $sub_menu = $element['#below'] ? drupal_render($element['#below']) : '';
     $output = l($element['#title'], $element['#href'], $element['#localized_options']);

     return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . '</li>';
   }

```

Thus the top most UL will always have the number 1.

```
   <ul class="secondary-menu secondary-menu--1">
    <li>Menu Link</li>
      <ul class="secondary-menu--submenu secondary-menu--2">
        <li>Menu Link</li>
        <li>Menu Link</li>
          <ul class = "secondary-menu-submenu secondary-menu--3">
            <li>Menu Link</li>
          </ul>
        <li>Menu Link</li>
      </ul>
    <li>Menu Link</li>
  </ul>

```
> 1 votes

# Answer
Rather then doing it with jquery you should try with modules, there are already lots of modules for this requirement, try with "Nice Menu".
> 0 votes

# Answer
Looks like there's a 'depth' key for each links.

```
function yourthemename_menu_link(array $vars)
{
    $depth = $vars['element']['#original_link']['depth'];
}

```

you can check depth to see if it is the first level.
> -1 votes

---
Tags: 7, routes, theming
---


# Question
Title: Submit button not triggering a form submit
I have a strange phenomenon. The code seams to be correct but the submit button is not triggered. dpm says the callback functions are loaded correctly in the $form value like this:

When I pressed one of the buttons nothing happened. I do not get any error message or log entry.

Any solution or ide for debuging?

CODE:

```
/**
* Implements hook_menu().
*/
function payu_ui_menu() {
  $items = array();
  $items['admin/config/services/payu/merchant'] = array(
    'title' => 'PayU merchant settings',
    'access callback' => 'user_access',
    'access arguments' => array('payu_administer'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('payu_merchant_settings_form'),
     'description' =>  '',
    //'type' => MENU_NORMAL_ITEM,
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/services/payu/merchant/%payu_merchant'] = array(
    'title callback' => 'payu_merchant_edit_form_title',
    'title arguments' => array(5),
    'access callback' => 'user_access',
    'access arguments' => array('payu_administer'),
    'page callback' => 'payu_merchant_edit_form',
    'page arguments' => array(5),
    'description' =>  '',
    //'type' => MENU_VISIBLE_IN_BREADCRUMB,
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/services/payu/merchant/%payu_merchant/delete'] = array(
    'title' => 'Delete',
    'access callback' => 'user_access',
    'access arguments' => array('payu_administer'),
    'page callback' => 'payu_merchant_delete_confirm_form',
    'page arguments' => array(5),
    'description' =>  '',
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
  );
  return $items;
}

...

/**
 * Payu merchant settings form validate.
 */
function payu_merchant_settings_form_validate(&$form, &$form_state) {
  drupal_set_message('Settings validate');
  $form_state['values']['merchant_id'] = trim($form_state['values']['merchant_id']);
  $form_state['values']['secret_key'] = trim($form_state['values']['secret_key']);
  $merchant_id = $form_state['values']['merchant_id'];
  if (substr($merchant_id, 0, 1) === 'P' && !ctype_digit(substr($merchant_id, 1, 6))) {
    form_set_error('merchant_id', t('Merchant ID always start with "P" and 6 digits'));
  }
  elseif (substr($merchant_id, 0, 1) === 'P' && strlen($merchant_id) != 7) {
    form_set_error('merchant_id', t('Merchant ID length is always 7 character!'));
  }
  if (!isset($form['#merchant'])) {
    // new item from "add merchant" form
    $merchant = ($merchant_id);
    if (!empty($merchant)) {
      form_set_error('merchant_id', t('Merchant ID is unique!'));
    }
  }
}

/**
 * Edit merchant settings.
 */
function payu_merchant_edit_form($merchant) {
   $form['#merchant'] = $merchant;
   $form['merchant_id'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => t('Merchant ID'),
    '#default_value' => $merchant->merchant_id,
    '#value' => $merchant->merchant_id,
    '#size' => 7,
    '#maxlength' => 7,
  );
  $form['secret_key'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => t('Secret key'),
    '#default_value' => $merchant->secret_key,
    '#value' => $merchant->secret_key,
    '#size' => 32,
    '#maxlength' => 32,
  );
  $form['currency'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#title' => t('Currency'),
    '#options' => variable_get('payu_currencies'),
    '#default_value' => $merchant->currency,
    '#value' => $merchant->currency,
  );
  $form['name'] = array(
    '#type' => 'textfield',
    '#required' => FALSE,
    '#title' => t('Merchant name'),
    '#default_value' => $merchant->name,
    '#value' => $merchant->name,
    '#size' => 64,
    '#maxlength' => 64,
  );
  $form['actions'] = array(
    '#type' => 'actions',
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Save'),
      "#executes_submit_callback" => TRUE,
      '#validate' => array('payu_merchant_settings_form_validate'),
      '#submit' => array('payu_merchant_edit_save_submit'),
    ),
    'delete' => array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      "#executes_submit_callback" => TRUE,
      '#submit' => array('payu_merchant_edit_delete_submit'),
    ),
  );
  return $form;
}

/**
 * Save edited merchant data.
 */
function payu_merchant_edit_save_submit($form, $form_state) {
  drupal_set_message('saving');
  $currencies = variable_get('payu_currencies', array());
  $result = db_merge('payu_merchants')
    ->key(array(
      'merchant_id' => $form_state['values']['merchant_id'],
    ))
    ->fields(array(
      'merchant_id' => $form_state['values']['merchant_id'],
      'secret_key' => $form_state['values']['secret_key'],
      'currency' => $currencies[$form_state['values']['currency']],
      'name' => $form_state['values']['name'],
    ))
    ->execute();
  switch ($result) {
    case MergeQuery::STATUS_INSERT:
      drupal_set_message(t('PayU merchant: %merchant_id added.', array('%merchant_id' => $form_state['values']['merchant_id'])));
      break;

    case MergeQuery::STATUS_UPDATE:
      drupal_set_message(t('PayU merchant: %merchant_id updated.', array('%merchant_id' => $form_state['values']['merchant_id'])));
      break;
  }
  $form_state['redirect'] = array('admin/config/services/payu/merchant');
}

/**
 * Delete merchant: menu callback function.
 */
function payu_merchant_edit_delete_submit(&$form, &$form_state) {
  $merchant = $form['#merchant'];
  $form_state['redirect'] = array('admin/config/services/payu/merchant/' . $merchant->merchant_id . '/delete');
}

/**
 * Delete merchant data: confirm form.
 */
function payu_merchant_delete_confirm_form($merchant) {
  $form['#merchant'] = $merchant;
  dpm($merchant);
  return confirm_form($form, t('Are you sure delete "%merchant_id" merchant?', array('%merchant_id' => $merchant->merchant_id)), 'admin/config/services/payu/merchant');
}

/**
 * Delete merchant data.
 */
function payu_merchant_delete_confirm_form_submit(&$form, &$form_state) {
  $merchant = $form['#merchant'];
  //drupal_set_message($merchant->merchant_id);
  db_delete('payu_merchants')
    ->condition('merchant_id', $merchant->merchant_id)
    ->execute();
  drupal_set_message(t('PayU merchant: %merchant_id deleted.', array('%merchant_id' => $merchant->merchant_id)));
 //$form_state['redirect'] = array('admin/config/services/payu/merchant');
}

```

# Answer
> 1 votes
You need to update your merchant edit form menu callback to use `drupal_get_form`, just like your first one. Or have your menu callback properly build the form.

```
  $items['admin/config/services/payu/merchant/%payu_merchant'] = array(
    'title callback' => 'payu_merchant_edit_form_title',
    'title arguments' => array(5),
    'access callback' => 'user_access',
    'access arguments' => array('payu_administer'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('payu_merchant_edit_form', 5),
    'description' =>  '',
    //'type' => MENU_VISIBLE_IN_BREADCRUMB,
    'type' => MENU_CALLBACK,
  );

```

Drupal is properly rendering your Form API array because it's a render array. However, it is not attaching regular form interaction because it was not built properly.

EDIT: You need to update your form function, as well, for the new parameters.

```
/**
 * Edit merchant settings.
 */
function payu_merchant_edit_form($form, &$form_state, $merchant) {
...
}

```

---
Tags: forms
---


# Question
Title: How to programmatically create a add to cart form with quantity input?
I want to programmatically create an add to cart form with quantity input and default as 1. I tried to use the code:

```
$form_id= commerce_cart_add_to_cart_form_id(array($product_id));
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1);
$line_item->data['context']['product_ids'] = array($product_id);
$form = drupal_get_form($form_id, $line_item);

```

But it just get a hidden field quantity with value 1 and I cannot change the quantity value. How can I get a quantity input instead of the static value?

# Answer
Interesting. I would have never thought to do this. A quick search in the commerce module produced this example:

```
<?php
// line 2649 of commerce_cart.module

// Extract the drupal_get_form() arguments array from the element.
$arguments = $element[$key]['#arguments'];

// Add the display path and referencing entity data to the line item.
if (!empty($entity_uri['path'])) {
  $arguments['line_item']->data['context']['display_path'] = $entity_uri['path'];
}

$arguments['line_item']->data['context']['entity'] = array(
  'entity_type' => $context['entity_type'],
  'entity_id' => $entity_id,
  'product_reference_field_name' => $field_name,
);

// Update the product_ids variable to point to the entity data if we're
// referencing multiple products.
if (count($arguments['line_item']->data['context']['product_ids']) > 1) {
  $arguments['line_item']->data['context']['product_ids'] = 'entity';
}

// Replace the array containing the arguments with the return value of
// drupal_get_form(). It will be rendered when the rest of the object is
// rendered for display.
$output[$field_name][$key] = drupal_get_form($arguments['form_id'], $arguments['line_item'], $arguments['show_quantity'], $cart_context);
?>

```

Which means you could do this:

```
<?php
$product_id = 1;
$form_id= commerce_cart_add_to_cart_form_id(array($product_id));
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1);
$line_item->data['context']['product_ids'] = array($product_id);
$form = drupal_get_form($form_id, $line_item, true);
dpm($form);
?>

```

And you will see how it affects the quantity (makes it become a proper field). You're also missing the $cart\_context that the core module uses to determine what to do with displaying/hiding fields.
> 1 votes

---
Tags: 7, forms, commerce
---


# Question
Title: loop view fields inside views-view--[view-name]--page.tpl
I'm within the template views-view--\[view-name\]--page.tpl and I want to fully style the fields within the templates. So I do var\_dump($variables) and within this I can see all my nodes seem to be there, but there so deep within the structure it's impossible to see where exactly, plus this can't be the correct way to loop around it as I'd have a crazy long query!

So how do I simply loop around the view in the template I mentioned and get lets say the title and the body for the nodes in my view?

# Answer
> 1 votes
Use views-view-fields--.tpl.php and render the field with your custom markup

For example:

```
<div class="product-item">
    <div class="row clearfix">
      <div class="product-image"><?php print $fields['field_images']->content; ?></div>
    </div>
    <div class="row clearfix text-center">
      <div class="product-attributes"><?php print $fields['title']->content; ?></div>
    </div>
    <div class="row clearfix text-center">
      <div class="product-attributes"><?php print $fields['title_1']->content; ?></div>
    </div>
    <div class="row clearfix  text-center">
      <div class="product-attributes price"><?php print $fields['another_field']->content; ?></div>
    </div>
</div>

```

# Answer
> 0 votes
I noticed I never explained how I solved this, for anyone who comes across this. The best way I found of doing this was if you go into the view, under fields select the field you want to change and then choose rewrite results and then select 'Rewrite the output of this field'. You can see what tokens you can use by clicking 'replacement patterns'. If you want to mix and match different fields you select 'exclude from display' on each field but the bottom one in the list which will then make it available as a token within the last field on the list. Simples!

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


# Question
Title: Alphabetical sorting of terms (not using a view)
I'm using the templates to display my terms rather than views but I'd like to change the order that the items are sorted. Currently it appears to be sorted by date. I would like to sort them alphabetically. Is this something I can do in the temeplate.php or within anywhere else?

# Answer
The easiest way indeed is using views.

If you really don't like to do so, you could create a custom module, implement hook\_menu\_alter() to alter the page callback of the taxonomy page:

```
/**
 * Implements hook_menu_alter()
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['taxonomy/term/%taxonomy_term'])) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] => 'MYMODULE_my_taxonomy_page';
  }
}

```

Then write your own version of the taxonomy module's function taxonomy\_term\_page($term) (using the above example, you would call it MYMODULE\_my\_taxonomy\_page).

Within this function you can alter the call of taxonomy\_select\_nodes and add a fourth parameter, specifying the desired sort order:

```
$order = array('t.title' => 'ASC')

```

Note that this is working only, if you did not use a field replacement for the title property (e.g. using the title module). Then you would have to write an own version of the taxonomy\_select\_nodes function as well.
> 0 votes

---
Tags: taxonomy-terms
---


title: Link to other nodes

text:
# Question
Title: Link to other nodes
I am starting a Drupal 8 website, with five custom Node types. These Node types need a field that can link to an arbitrary number of Nodes of any type. All information that I've found online is pertinent to Drupal 7 only. For instance, the Entity Reference module (included already in Drupal 8, but in D8 does not support Node references), or the References module (not available for D8).

**How can I create a field to link to an abitrary number of Nodes in Drupal 8?**

# Answer
> 4 votes
In Drupal 8 this is built in. You probably don't find it, because drupal 8 uses the name "content type" not "node type".

You go to manage fields in the content type, add a new field, in select a field type choose Reference - Content. In the field settings you can choose which content type you want to link to.

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


# Question
Title: How do I get the value of fields in a template?
I have created a custom template for a view called, say, "Example":

```
views-view-fields--example--page.html.twig

```

This works fine. I can display the title of each item in the template thus:

```
{{ fields.title.content }}

```

Also works fine. However, I've been unable to work out how to display the individual fields in my content type. How do I do that?

# Answer
Putting this in my template was very helpful:

```
<ol>
{% for key, value in _context  %}
  <li>{{ key }}</li>
{% endfor %}
</ol>

```

From here: https://www.drupal.org/node/1906780
> 0 votes

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


title: Count number of nodes to be output

text:
# Question
Title: Count number of nodes to be output
I'm trying to figure out how many articles( nodes? ) will be displayed in a listing on our website, to use it to add classes to the elements that are rendered, so one can easily have different styling depending on the number of frontend elements. Right now there are six elements, so `preprocess_node(&$variables)` is called 6 times in template.php in my theme, but: How can I obtain the number of nodes in the `preprocess_page()` \- hook?

The nodes seems to be produced by a Promoted articles - type of listing.

# Answer
I found the answer, and I'm posting this for reference:

```
$nid = $variables['node']->nid;
$arr =
  $variables['page']['content']['system_main']['nodes'][$nid]['field_uib_profiled_article'];
// counting number of elements with numeric keys:
$num_elements = count(array_filter(array_keys($arr), 'is_int'));
// $num_elements contains the number of profiled articles.
// this approach is similar to that of Adrians answer.

// Nodes could also be found with
$num_elements =
  count($variables['node']->field_uib_profiled_article['und']);

```

The main page had a single node containing a profiled\_article - field. This field had a list of nodes that are displayed on the front page. Sorry for the incomplete description in the question, but I simply did not know where to look...
> 1 votes

# Answer
No need to modify template files. Instead create a view of Article content type and then follow the below steps.

1. Into view **Header** part add field **Global: Result summary**
2. Now into above field configuration, inside **Display** text area add **@total** token.
> 2 votes

# Answer
You can use the following code inside your `THEME_preprocess_page()`:

```
function THEME_preprocess_page(&$variables) {
  $content_type = 'article';
  $total = 0;
  foreach($variables['page']['content']['system_main']['nodes'] as $nid => $node) {
    if($node['#bundle'] == $content_type) {
        $total++;
    }
  }
  //if you have installed the devel module you can use dpm() to see the result;
  dpm($total);

}

```

Remember clean the cache.
> 2 votes

---
Tags: nodes, hooks, theming
---


# Question
Title: Select only if row not exists in joined table
I have a db\_select that selects row from t\_project\_proposal\_writer table only if in joined t\_project\_milestone table row with milestone\_id 10 is found:

```
$query = db_select('t_project_proposal_writer', 'p')->fields('p');
$query->innerJoin('t_project_milestone', 'm', 'p.id=m.proposal_id');
$query->condition('p.initiative_nid', $node->nid)->condition('m.milestone_id', 10);

```

One project row can have 10 milestone rows. Now I need to do another query that selects only the rows from t\_project\_proposal\_writer where milestone\_id 10 **not exists** in joined t\_project\_milestone.

Is there any other possiblity to do that, instead of query all the projects and iterate throught them while checking if milestone 10 exists?

# Answer
You can use isNull() method :

```
$query = db_select('scald_atoms', 'a');
$query->fields('a', array('sid','title'));
$query->leftjoin('table_name','table_alias','table_alias.entity_id = a.sid');
$query->isNull('table_alias.mon_field_value');
$query->execute();
$query->fetchAllAssoc('nid');

```

with your example something like that should do it :

```
$query = db_select('t_project_proposal_writer', 'p')->fields('p');
$query->leftjoin('t_project_milestone', 'm', 'p.id=m.proposal_id');
$query->isNull('m.milestone_id');

```
> 2 votes

---
Tags: 7, database
---


# Question
Title: Unsupported operand types in system.module line 2134 when trying to add product with drupal commerce
I'm trying to add a product to my commerce store, and anytime I navigate to the add a product page I get hit with the following error:

```
Fatal error: Unsupported operand types in C:\Users\Nick\Sites\devdesktop\psr3\modules\system\system.module on line 2134

```

I have googles around, and this looks like a common error with contrib or custom modules.

The error happens in this if statement:

```
  if (!isset($item['mlid'])) {
    $item += db_query("SELECT mlid, menu_name FROM {menu_links} ml WHERE ml.router_path = :path AND module = 'system'", array(':path' => $item['path']))->fetchAssoc();
  }

```

My php isn't good enough to know what might be causing the error. How can I solve this?

# Answer
> 1 votes
Either `$item`, or the return value from the `db_query()` statement, are resolving as something other than an array. Drupal is expecting them both to be arrays, so you get an error when it unconditionally tries to combine them.

It's not possible to debug something like this without access to the site; I'd recommend stepping through the code with a proper debugging tool to see exactly which side of the equation is failing.

At a guess, I'd say `$item` is the problem. You'd expect to see more notices about undefined array indexes if it was simply that `$item['path']` was missing or something like that.

One low-tech debugging approach is to temporarily disable custom/contrib modules one by one and see if you can find something responsible.

# Answer
> 0 votes
So, googling around further I saw that several people hit up against this pretty recently, and that there was some issue with the menus. The last comment on this thread Unsupported operand types system module gave me what I needed. I ran the following code

```
db_update('menu_links')
    ->expression('router_path', 'link_path')
    ->condition('menu_name', 'management')
    ->condition('link_path', db_like('admin/commerce') . '%', 'LIKE')
    ->where('link_path <> router_path')
    ->execute();

```

In the devel execute php window and it solved my problem.

---
Tags: commerce
---


# Question
Title: How to get "User ID From URL" with contextual filter in Pfofile2 page
I'm using Drupal7.

I wanted to display some fields from user account in profile2 page by using Views. I tried to do this by using views block and views\_embed\_view() coded in profile2--ProfileType.tpl.php for profile2 page.

So, I created a view and set contextual filter like below.

```
-"USER:UID"
-the default value is "User ID From URL"

```

But that doesn't display View in profile2 page even though the URL is "Mydomain.com/profile-My\_Profile\_Type/User\_ID". On the other hand, that View works in the user account page. So, this means that it may be because contextual filter of "User ID From URL" doesn't work in the profile2 page even though its URL has User ID. I changed the contextual filter from "USER:UID" to "(Profile) Profile: User uid", but it doesn't work either...

Can anybody give me the advice how to make it work?

Thank you

# Answer
> 0 votes
If the url schema is alway the same, you can use the default value "Raw value from url" instead of "User Id from URL" and set the 'path component' in your example to '3' to get the user id.

---
Tags: views
---


# Question
Title: How to redirect to frontpage when a node is deleted?
In my client's site it is normal to delete some posts (or old posts), but I don't want a 404 error page. Instead I want the user/visitor to be redirected to the frontpage with a 301 error code.

I have installed the Redirect module, but I have not found any option for this.

I have the Rules module installed and I can create custom module rule if I need.

# Answer
> 1 votes
I found the module Save Redirect on Delete which looks like it addresses your problem. From the description:

> The Save Redirect On Delete module gives the functionality for saving redirects after deletion of entity(supported by pathauto module) having some url alias.

I haven't tried it myself but would be interested to know if it helps.

# Answer
> 0 votes
There must be a better way, but one way will be to create a page with script to redirect your page.

```
<script>
  alert("A message for visitor if you want to show");
  window.location.replace("http://your_site.whatever");
</script>

```

After creating the page with javascrip code, Go to admin/config/system/site-information and change the Default 404 (not found) page to point your page with javacript code.

# Answer
> 0 votes
If the question here can be translated to something like "**How to redirect to frontpage when trying to visiting a node that has been deleted before?**", then there are 2 options to do so, as detailed below.

# Option 1: Use the Rules module

Assume the path of the "Default 404" page is set to `not_found` (via admin). And assume your homepage has a path like `my_homepage`.

Then create a rule using the Rules module, with as **Event** something like "After visiting node `not_found`". So that the entire rule would look something like so:

* **Rules Event:** After visiting node `not_found`
* **Rules Action:** *Page redirect* \- `Parameter: URL: my_homepage`

Should you want to do so, you could also add another **Rules Action** to also display some (informational) message in the Drupal message area, with something like "*You tried to visit a page which has been deleted, which is why we're showing you the homepage instead*".

# Option 2: Use the CustomError module

The CustomError module allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without creating nodes for each of them. Some of its features are like so (from its project page):

> * Configurable page title and descriptions.
> * There are no author and date/time headers as with normal nodes.
> * Any HTML formatted text can be put in the page body.
> * The error pages are theme-able.
> * Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
> * Allows custom redirects for 404s.

Note the part about "*Allows custom redirects for 404s.*", which I believe is what you're looking for.

---
Tags: redirection
---


# Question
Title: How do I upload a PDF for users to download?
I am very new to Drupal. I simply want to provide a link in an article for users to download a pdf document. How do I upload the document on the admin side and then link to it in an article?

# Answer
> 3 votes
It's easy, in `admin/structure/types/manage/article/fields` **make file field** like so:

All other stuff is logical:

Don't forget to put PDF as an allowed extensions:

---
Tags: 8, navigation, files
---


# Question
Title: Is it necessary to cache external api requests?
I am working on a custom module to pull tweets. Is it necessary for me to cache my request to Twitter's API, if I have both Drupal 8's Internal Page Cache and Dynamic Page Cache enabled? Can I just rely on the Page Cache?

For instance, if I set some data to cache for every 3 minutes, but the page cache is set for every 5 minutes, my custom data cache time will be ignored, and my data will be cached every five minutes, correct?

For reference, I meant to set my custom cache like so:

```
$cid = 'my_custom_module_id';
if ($cache = \Drupal::cache()->get($cid)) {
  $mydata = $cache->data;
} else {
  $mydata = [DO MY API CALL STUFF!]
  \Drupal::cache()->set($cid, $mydata, 180);
}

```

# Answer
Depends. Do you display this on a specific page? Or on multiple pages? Is it a page, a block... ? Do you have many authenticated users?

If it's a single page callback or a block that's always the same, then it's possibly fine to not cache it yourself. That only makes sense when you call your code on many different pages.

If you also have a lot of users, especially with different roles, multiple languages or or cache contexts that might vary but always the same API call, then it might make sense again to cache it yourself.
> 4 votes

---
Tags: 8, caching
---


title: Drush does not work on my Mac

text:
# Question
Title: Drush does not work on my Mac
I use MAMP on Mac.

When I try to use `drush en omega` command on drupal root directory to install omega, But the terminal throw me an error:

```
drupal-7.23 tangmonk $ drush en omega

Command pm-enable needs a higher bootstrap level to run - you will   [error]
need to invoke drush from a more functional Drupal environment to run
this command.

The drush command 'en omega' could not be executed.                  [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]

Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.

Drush was attempting to connect to:
 Drupal version         :  7.23
 Site URI               :  http://default
 Database driver        :  mysql
 Database username      :  root
 Database name          :  drupal
 Default theme          :  garland
 Administration theme   :  garland
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush version          :  7.0-dev
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/tangmonk/Sites/drupal/drupal-7.23
 Site path              :  sites/default
 File directory path    :  sites/default/files
     * connect the database through a socket. The socket file may be
    wrong or the php-cli may have no access to it in a jailed shell. See
    http://drupal.org/node/1428638 for details.

```

It seems mysql issue. But my site run perfect.

# Answer
I run drush command as MAMP Integrated PHP, It works!

I add alias command to my shell:

```
$ vim ~/.bash_profile
alias drush='/Applications/MAMP/bin/php/php5.5.3/bin/php /opt/drush/drush.php'

```
> 4 votes

# Answer
This is what worked for me

```
sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

```

Changing to 127.0.0.1 in settings.php worked for quite a few too, but not for me.

Infact I had to make sure, it was localhost.
> 3 votes

# Answer
I solved this by adding this to my .bash\_profile

```
export PATH=$PATH:/Applications/MAMP/Library/bin

```

See: http://www.webbykat.com/2012/06/solving-sh-mysql-command-not-found-mamp-pro-2

Before after running `drush status -d` I had:

> sh: mysql: command not found.
> 2 votes

# Answer
I HAD the same problem. I think there may be different causes but in mycase I run

```
drush status -d

```

and got

```
Bootstrap to phase 0. [0 sec, 1.88 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 2.01 MB] [bootstrap]
Cache MISS cid: 6.5.0-alias-path--895a900da5a848eb4b6977657b24c58f       [debug]
[0.01 sec, 2.01 MB]
Cache HIT cid: 6.5.0-commandfiles-0-82a4097a58b8537b29e63894fab2597c     [debug]
[0.01 sec, 2.03 MB]
Bootstrap to phase 0. [0.08 sec, 5.38 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.13 sec,    [bootstrap]
6.22 MB]
Initialized Drupal 7.34 root directory at                               [notice]
/opt/lampp/htdocs/fish-nn.dev [0.14 sec, 6.22 MB]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.14 sec,    [bootstrap]
6.23 MB]
Initialized Drupal site default at sites/default [0.14 sec, 6.23 MB]    [notice]
Cache HIT cid: 6.5.0-commandfiles-2-062e26fa8ebdd8c444d688ab9447c986     [debug]
[0.14 sec, 6.24 MB]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.14[bootstrap]
sec, 6.24 MB]
mysql extension for PHP PDO is not installed. Check your php.ini to  [bootstrap]
see how you can enable it. Proceeding with the mysql PDO extension.
[0.15 sec, 6.25 MB]
could not find driver [0.15 sec, 6.26 MB]                            [bootstrap]
Found command: core-status (commandfile=core) [0.15 sec, 6.25 MB]    [bootstrap]
Loading outputformat engine. [0.22 sec, 6.28 MB]                        [notice]
Calling hook drush_core_status [0.22 sec, 6.33 MB]                       [debug]
Returned from hook drush_core_status [0.22 sec, 6.34 MB]                 [debug]
 Drupal version         :  7.34
 Site URI               :  http://default
 Database driver        :  mysql
 Database username      :  root
 Database name          :  fishnn
 Default theme          :  garland
 Administration theme   :  garland
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush version          :  6.5.0
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /opt/lampp/htdocs/fish-nn.dev
 Site path              :  sites/default
 File directory path    :  sites/default/files

```

through all these lines I was interested by

```
mysql extension for PHP PDO is not installed. Check your php.ini to  [bootstrap]
see how you can enable it. Proceeding with the mysql PDO extension.
[0.15 sec, 6.25 MB]
could not find driver [0.15 sec, 6.26 MB]                            [bootstrap]

```

so I run

```
yum install php-pdo php-mysqli

```

And got the profit
> 1 votes

# Answer
If you've already tried various methods for installing drush without success, such as Composer, Brew, etc., you may have collected some conflicting settings. Check your ~/.drush directory and bash profile files for files and settings left over from prior attempts.
> 0 votes

# Answer
I'm running Windows/Git Bash. For me, the issue was that mysql wasn't in the PATH. St.Cremer's suggestion was actually helpful.

Running

```
drush status -d

```

got me a different error showing me that mysql wasn't recognized as an internal command. So, if you haven't found a solution yet, chances are that this command might lead you to a solution like it did me.
> 0 votes

# Answer
I needed to add this to my `~/.profile` file:

`alias mysql='/Applications/MAMP/Library/bin/mysql'`
> 0 votes

---
Tags: drush
---


title: Drupal go to with destination

text:
# Question
Title: Drupal go to with destination
I have a page with two links visible to people, but on clicking of either of two, user needs to log in to view, so in case user is not logged in, i am sending users to login page with `drupal_goto('user')`, i want that if the user clicked 1st link and is redirected to login page, after successful login, he should be redirected again to that 1st link i tried with this code but did not work,

```
$query = array('destination' => 'node/id');
drupal_goto('user',$query);

```

# Answer
> 2 votes
You need to use `drupal_goto` the same way you use `url`.

So what you need to do is this:

```
$query = array('destination' => 'node/id');
drupal_goto('user', array('query' => $query));

```

---
Tags: users
---


# Question
Title: Sharing the same code base and one database
I would like to have multi-sites that share the some code base and one SQL database in Drupal 8.

Is this possible and recommended? I am interested also in security concerns. Is this safe?

# Answer
This is very much possible using the domain module:

> "The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database."

Which is currently under development for Drupal 8 here:

https://github.com/agentrickard/domain

This of course assumes you are not talking about actual Drupal multi-sites which are intended to share the same codebase but always have separate databases.
> 3 votes

---
Tags: 8, multi-sites
---


title: Extra aliases in the url_alias table

text:
# Question
Title: Extra aliases in the url_alias table
In a module, entity\_save is being called 2 times. Each time it's called, an extra alias row is being added to the url\_alias table. I couldn't find any paths being saved in node\_save.

Is this expected behavior?

The entity type I'm dealing with are nodes.

# Answer
> 0 votes
I found some code within the module that was placed as a work around for issue https://www.drupal.org/node/936222. Now that it's fixed, all is well.

---
Tags: 7, entities, path-aliases
---


# Question
Title: How can I hook into an entityform submission?
I've got entity forms installed, and I'd like to use some db\_queries when a particular entity form is submitted, as to make use of the information filled out on that entity form.

Is this possible, and which hook should I use?

# Answer
If I understand your question right, you should use the following hook to capture a submission:

```
hook_entityform_insert($entityform)

```

As described in the comments at the top of entityform.api.php:

```
* Entityform and Entityform type are standard entities using the Entity API module.
* The standard Entity hooks are availabe for them.
* Including
*  ...
*  hook_entityform_insert

```

Hope this helps

Addition:

here is the sample code I used:

```
function mymodule_entityform_insert($entityform){
  dsm($entityform);
}

```

and it did get triggered as soon as I submitted an EntityForm.
> 5 votes

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


# Question
Title: Let authenticated users (non-admin) reorder uploaded images using the 4-way arrow
Currently, the admin is able to reorder uploaded images (field), using the 4-way arrow, like so:

But other authenticated users(not admin) can only reorder images through "Show row weights":

but it gets tedious when there is more images. Is there a way to enable the 4-way arrow for them?

# Answer
> 0 votes
Turns out the draggable link is present, but only the bottom 10% of it, and the 4-way icon does not get rendered, even though the background is set in css.

This problem is due to the import of scaffolding in the the bootstrap scss file.

---
Tags: 7, media
---


# Question
Title: Can I suppress PHP error messages for authenticated users, BUT display all of them for an admin?
I would like to suppress all the PHP error messages (errors, notices) for a regular authenticated user, BUT display ALL of them for an administrator (`$user->uid == 1` or user with an "*administrator*" role).

This way I have the opportunity to set "*Error messages to display*" to "*None*" at `admin/config/development/logging`, but unfortunately this is a GLOBAL setting, which is not the right one for me.

# Answer
I haven't tested this but I would think you could turn that setting off completely, and enable it again yourself in a custom module:

```
function MYMODULE_init() {
  if (user_access('a permission only admins have')) {
    error_reporting(E_ALL);
  }
}

```

**Update**

Per your comments, it looks like this way doesn't work, but what *does* work is to do exactly the reverse of the above. That is, to set the error reporting to "All messages" in the UI, and then use `hook_init()` to surpress the unwanted levels of error message.

I would say your suspicions are correct, that Drupal is handling the errors at a lower level and so turning them off all together stops calling `error_reporting()` in `hook_init()` from having any effect.
> 4 votes

# Answer
Use my Error Level Permission module.
> 0 votes

---
Tags: 7
---


# Question
Title: What is causing Drupal to return a 404 HTTP header, but correctly return the page?
I have a Drupal 6 site that is correctly returning site content (like the home page), but if you look at the response headers every page has a 404 header, instead of a 200.

Things I've tried:

1. Rebuilt the node access table (/admin/content/node-settings/rebuild)
2. Cleared the cache
3. Run update.php

Do you have any idea on what might be causing this?

# Answer
Complete bone-headed cause here: The home page path was set incorrectly and the 404 page was identical to the home page layout. Doh!
> 1 votes

# Answer
Are you using clean urls?

It is possible that Drupal is called through the 404 error handler which results in the 404 header.

Make sure your .htaccess configuration is correct and that mod\_rewrite is enabled and you're allowed to override the relevant settings.
> 4 votes

# Answer
This just plagued me for a few days. We had a working dev-staging-production workflow and we started getting 404s on only the production system, but the pages still rendered. This lead to a nightmare situation where to us the site was functional, but google began dropping our page results.

We were getting 404s on all of the aliased urls (which are handed to drupal by this line in the .htaccess):

```
ErrorDocument 404 /index.php

```

After much digging around, cloning, even php xdebugging, it turned out that the production apache VHost config was not allowing overrides for the drupal root dir, so even though all of the .htaccess directives were placed in the VHost config, apache wasn't considering directives contained further down the filesystem.

However that in itself doesn't explain the problem because we had no additional .htaccess files further down the file structure, save for the default drupal files dropped in the sites/default/files\[/public\] directories, and 2 libraries. They had nothing to do with the 404s.

So, perhaps this is another cause. I'm still at a loss as to:

A. Why this happened suddenly with no apache configuration changes, system package updates, or drupal module updates (pathauto\_persist was upgraded recently to 7.x-1.4 but after downgrading the problem 'persisted').

B. Why opening up the AllowOverride fixed it.
> 0 votes

---
Tags: 7
---


title: Users to choose how to view images

text:
# Question
Title: Users to choose how to view images
Is it possible to offer viewers different options on how to view an image?

Currently, it just defaults to a flexslider that I have put as default on my image style.

Looking for instructions on how to achieve this functionality by using views.

I know there is a similar post here but that is **WHILST** creating the content type - I want the user to choose how to see a set of images after the images have been added to the website!

# Answer
> 0 votes
Use different view modes for your entity (node). Each view mode (also called a build mode) can have different template (.tpl.php) files. Use hook\_entity\_view\_mode\_alter to decide which view mode to use (based on your user's selection).

You can use the View Modes module to create custom view modes.

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


title: Multiple urls of same node

text:
# Question
Title: Multiple urls of same node
This seems duplicate content, how can i send a header 410 for the incorrect version of the url and make sure only the correct url is used on the whole website.

This is the original URL: http://www.traveldudes.org/node/2504/ This is the alias: http://www.traveldudes.org/travel-tips/climate-and-best-time-visit-serengeti-tanzania/2504 But what’s this URL? http://www.traveldudes.org/node/2504/gallery Or what’s this URL= http://www.traveldudes.org/node/2504/map

# Answer
There are a couple of easy to use modules that will help you manage your URL aliases. They include,

The first two aliases you have sounds like the 'default' ones. You may have created (or one of the modules you have installed automatically) created the other aliases.

All the same, you can manage your aliases (and re-directs) using the modules I mentioned.
> 0 votes

---
Tags: redirection
---


# Question
Title: How to Add Taxonomy description or other field value in a textarea with WYSIWYG?
I want a content editor to be able to create re-usable content, then have access to that content through the WYSIWYG editor when editing the node body or other text field. The idea is that the information gets used in multiple locations through the site, and they want to both cut down on copy/paste errors and only have to edit this information in one place.

The best analogy I can give here is, think of a hotel chain that has several properties each with it's own page, and they wish to have a table on each page that has the room description, occupancy, and price, and based on those parameters, they want to set the price for all properties listed on different pages at the same time.

I'm thinking taxonomy is the simplest way to create re-usable content, so the question is, is there a module that allows simple selection/insertion of a taxonomy description directly into say a table that's being edited with the WYSIWYG editor?

There will be hundreds of items I believe, so the interface should ideally be as simple as possible (like a taxonomy reference autocomplete widget).

# Answer
You have to add any wysiwyg module and enable it. Follow the installation instruction on your site (/admin/config/content/wysiwyg). You can use a wysiwyg editor like ckeditor. Then on same configuration page, for Filtered HTML select your editor.

Once an editor is set for a particular text format. You can follow these steps:

1. Add a Vocabulary to your taxonomy like Hotel Properties (hotel\_properties). Edit it and add new fields to it like price.
2. Now in your content type, you can use Hotel Properties (hotel\_properties) as term reference and widget type: autocomplete.
3. Now you can alter the node tpl or use panels (Node Template) to display information from taxonomy.

**Note**: To get the wysiwyg editor, use filtered text editor.
> 0 votes

# Answer
> I'm thinking taxonomy is the simplest way to create re-usable content, so the question is, is there a module that allows simple selection/insertion of a taxonomy description directly into say a table that's being edited with the WYSIWYG editor?

sounds like a job for:

### Editable Fields

> This module allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

**Video tutorial/demo**
> 0 votes

---
Tags: 7, taxonomy-terms, wysiwyg
---


# Question
Title: What is the most drupal-like way to bring the title of a single node page into the rest of the content?
This is similar to Considerations displaying page titles in page or node template which in turn claims to be similar to another question, but the questioner doesn't mention how they achieve what they are doing, and what they are doing may be different from what I'm doing.

In my case, on single node view pages, for certain (most) content-types, there is an optional image field, that needs to be floated left of the title.

I'm not sure if it would be best practice to move the title output down into the node.tpl.php template or to keep it in the page.tpl.php template and load the relevant field for the node in the page template.

This is what I've done:

template.php:

```
function enviroscope_preprocess_page(&$variables, $hook) {
  if (isset($variables['node']->field_doc_cover)) {
    $node = node_load($variables['node']->nid);
    $output = field_view_field('node', $node, 'field_doc_cover', array('label' => 'hidden'));
    $variables['field_doc_cover'] = $output;
  }
}

```

page.tpl.php:

```
<?php print render($title_prefix); ?>
<?php if ($title): print render($field_doc_cover); ?><h3 class="title" id="page-title"><?php print $title; ?></h3><?php endif; ?>
<?php print render($title_suffix); ?>

```

This gets the image field printed before the title, but I'm not sure if there is an equivalent here to **`hide($content['field_doc_cover']);`**? Currently this has `field_doc_cover` printing twice.

So the main question is,

> Is this the right approach?

but this breaks down into some more specific questions:

* Should the title definition stay in page.tpl.php for single node pages?
    + If so, is there a good way to exclude the field\_doc\_cover field from being rendered in the node.tpl.php file without messing with that template too?
* Is there a good reason not to handle the title in the node.tpl.php, and remove it from the page.tpl.php file for these content\_types?
    + If there is a good reason for it to not be in nodes, would it be sensible to render the element in page.tpl.php and send it as a variable to be used in node.tpl.php?

I'm pretty new to drupal theming as is probably obvious, so examples with your answers would be very helpful!

**Update:** I was asked to create a visual representation of what I'm trying to do, which was a good call because it reminded me of one more issue: The last modified date should be printed above and to the right of the title.

I guess one of the main things I don't understand is whether there is some good reason why the title needs to be part of the page.tpl.php template. It sure would be easier if it were down in the node template.

# Answer
> 3 votes
It is valid to do it the way you are doing it and it would also be valid to not print the title in the page tpl for certain nodes and instead print it in the node template.

It's subjective as to which is preferable (if one is even better than the other) and the preferred solution may change based on your specific requirements for a given project.

One thing to consider is anything that usually prints out between the title and the content in your page template. Will moving the title into the content (in this case the content is essentially the node template) mean these nodes will be inconsistent to the rest of the site (for example, will messages/tabs/help/etc. be in a different place on these nodes)?
If they were to be different would it matter to you?

Yes, you can still use `hide($content['field_doc_cover']);` in your node template in this case.

There are also alternatives depending on your site and requirements. For example the Panels module allows you to assign specific fields to different regions and there are a number of ways to get a block to show parts of a node so that you can assign that to a different region using Drupal core or the Context module or similar.

---
Tags: 7, theming
---


# Question
Title: How to make a particular role user and their content not accessible/viewable to other users?
How do I make the user page (/user/uid) of a particular role (PendingFreelancer) and the content they create not accessible/viewable to other users?

# Answer
## Content Access

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Video Tutorial

I think content access is only for content type nodes. So for the **user page** umm.... I can't think of anything of the top of my head. I will edit this if I can think of something. Perhaps the only solution is doing it with a custom module programmatically.

---

If you use pathauto you could make so the user page path is user/\[user:role\]/\[user:name\]

then you could use

### Path Access

> Path\_access provides the means to restrict pages based on their path alias - meaning you can lock out certain user role groups from whole sections of a site using wildcards.

and lock them out from certain \[user:role\] paths.
> 1 votes

# Answer
Check out the Group module which help to build community based drupal sites.

> The Group module allows you to create arbitrary collections of your content and users on your site and grant access control permissions on those collections

I believe Group works with any Drupal 7 entity.
> 1 votes

# Answer
If you are already using rules, then adding redirect rules for certain roles if they don't match the viewed user's role or a node's author's role would work.

Combine this with views filtering per role / block visibilities and panel varients per role would allow you to lock down a site pretty effectively.

I found that "content is viewed" rules add less than 10ms to a page load (or that's what rules debugging shows me). I think that's acceptable for the large majority of sites.
> 0 votes

---
Tags: 7, users
---


title: Manually post to search results page

text:
# Question
Title: Manually post to search results page
I have a section in my theme where I'd like to manually include a search input. I do not want to use the search block as I have some additional customizations I'm integrating outside of the scope of this question.

It looks like the default search form posts to the existing page and redirects to the results page (/search/node/query). How can I manually trigger this to happen?

I've tried to mimic the `form_id` but it doesn't seem to pick it up:

```
<form method="post" action="">
    Search:
    <input type="text" name="search_block_form" ng-model="query" />
    <input type="submit" value="Search" />

    <input type="hidden" name="form_token" value="">
    <input type="hidden" name="form_id" value="search_block_form">
</form>

```

There is an additional field in the default block called `form_build_id` but it changes each time the form is rendered.

How can I accomplish manually creating a POST to go to search results?

# Answer
> 2 votes
Drupal core search result pages do not listen to URL Parameters or HTTP POST content. Instead, it takes the third part from the `search/node/QUERY` URL format, and shows results for `QUERY`.

This unfortunately makes it not possible to use a standard HTML form created without Drupal's form API. There are of course workarounds.

Basically what we try to do is route the user's search query to the `search/node` path. I can see you are using Angular. You might be able to make it send the user to the proper path.

Alternately, you can make Drupal listen to URL parameters or the HTTP post request content.

https://www.drupal.org/project/query\_parameters\_to\_url \- this module I just found (and did not try personally) appears to rewrite URL parameters to a path query. I'm not sure this will work for search forms though.

If not, you will have to create a custom module, and take over the search result page callback. Then, it can show appropriate results or call the old page callback function with the search query taken from alternative sources.

---
Tags: forms, search
---


# Question
Title: Why can't I add an existing field to the user accounts on Drupal 8?
On Drupal 7, you can add fields that have been added to nodes to user accounts. At `admin/config/people/accounts/fields`, scroll down to **Add related fields** and simply select the field, easy.

But in Drupal 8, at `/admin/config/people/accounts/fields`, I see no option to add an existing field, just **Add Field**, which adds a new field.

Has this option been removed from Drupal 8, and if so, why?

# Answer
Yes this option has been removed, a field cannot be shared across entity types.

You can, however, add the same field again, I.e. use the same name. Whilst they will share a name, they will be separate fields.

The reason for this is storage. In drupal 7, field storage was separate to entity storage, which meant a mismatch. In drupal 8, entity storage also handles field storage. This means if for example mongodb wants to store an entity and it's fields as a single blob/document - it can. On drupal 7 this would have required two blobs, one for the entity and one for the fields.
> 8 votes

---
Tags: entities, 8, users
---


title: How to add alt tag to image from views

text:
# Question
Title: How to add alt tag to image from views
I have created views with image gallery. Now I want to add alt tag to image how can I do it. I have not enabled alt field in content type configuration.

I want add alt tag to already existing images. Kindly provide the solution to achieve this.

# Answer
> 0 votes
There is no way to add **unique** alt text using views, unless... you use:

### Editable Fields

> This module allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). **It also works within views** etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).

Video tutorial/demo

You would have to enable the alt in your content type, then you should be able to edit it in your view.

---

> I have more than 150 content. So i am asking for alternative

I take it you're looking for an easy & quick way so you don't have to edit 150 nodes one by one.

### Another method

would be to find the alt field in your database and export the table as .csv file.

Then edit it using excel, and add your alt text here, save.

Import back in and clear the Drupal cache.

---
Tags: 7, views, media
---


title: Token for field in field collection

text:
# Question
Title: Token for field in field collection
I have a field collection with 3 fields (title, image and link). I'd like to link the title and image to the value of the link field.

I'm using the linked field module to make the fields linkable and enabled the token module. Yet the fields from my field collection aren't in my available tokens list. They also can't be found in admin/help/token

How do I link a field from a field collection to the value of another field from that same collection? Or how do I find the correct token?

# Answer
I found the solution in enabling the entity\_token module. This expanded my available tokens list to include the fields within the field collection.
> 0 votes

---
Tags: tokens, entities
---


# Question
Title: How to make booking calendar for accommodation facility
I have web, let's call it `AccomovationInSkyResort.com`. It has 2 facilities with 3 entities which can be booked out (reserved):

1. Appartment house:

a) 1th floor **(1)**

b) 2nd floor **(2)**
2. Cottage **(3)**

How to make "booking (reservation) calendar" for accommodation facility?

By "*booking calendar*" I mean calendar showing available (not booked out) nights. I need 3 calendars at all.

I did some experiments with calendar module but it isn't so nice solution.

How did you solved this problem?

# Answer
I think the module you mentioned is good for it. Each of the entity can have a boolean field "Booked". So it could have values 0 or 1. You can filter out nodes according this field value in you calendar view.

I suppose, " Apartment house 2nd floor" is just one entity, not a type of entity.
> 0 votes

# Answer
Below is a summmary of the modules you may want to look at for managing reservations. These modules have a stable release, and can be used for either D6 or D7 (quotes are from their project pages):

* Availability Calendars.

> ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
>
> An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.
* Simple Reservation.

> ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
>
> The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
>
> There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.
* MERCI.

> ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.
* Resource Conflict.

> ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.
> 0 votes

---
Tags: 7, datetime, bookings
---


# Question
Title: No sub theme folder inside bootstrap theme folder
I just installed Bootstrap 3 theme in Drupal 7, but the subtheme folder is missing. I am new to Drupal and am following online tutorials but no result. All instructions direct me to a sub theme folder in themes\>bootstrap\> bootstrap-subtheme, but there is no such folder. I removed the theme and reinstalled but still no folder.

# Answer
Have a look in the `starterkits` folder then choose between `less` or `cdn`.

For more information, have a look on files within `docs` folder
> 1 votes

# Answer
Just create the sub-theme folder manually. The folder name you'd use for it will be the machine name of your subtheme.

For more details, refer to:

If you prefer to look at a great (I think) example of a (contributed) Bootstrap sub-theme, then have a look at the Bootstrap Business theme.

Note: the question about "Right way to start with a Bootstrap subtheme?" contains a lot of details to get started with such sub-theme ...
> 0 votes

# Answer
See http://drupal-bootstrap.org/api/bootstrap/docs!subtheme!README.md/group/subtheme/7.

> To start with, you need to choose an Existing Starterkit.
>
> * CDN Starterkit \- uses the "out-of-the-box" CSS and JavaScript files served by the jsDelivr CDN.
> * LESS Starterkit \- uses the Bootstrap Framework source files and a local LESS preprocessor. Create a New Sub-theme
>
> Then follow these steps:
>
> * Copy over one of the starterkits you have chosen from the `./bootstrap/starterkits` folder into `sites/all/themes` or a respective `sites/*/themes` folder.
> * Rename the folder to a unique machine readable name. This will be your sub-theme's "name". For this example and future examples we'll use subtheme.
> * Rename `./subtheme/cdn.starterkit` or, if using the LESS Starterkit, `./subtheme/less.starterkit` to match the folder name and append .`info` (e.g. ./subtheme/subtheme.info).
> * Open `./subtheme/subtheme.info` and change the name, description and any other properties to suite your needs.
>
> > WARNING: Ensure that the .starterkit suffix is not present on your sub-theme's .info filename. This suffix is simply a stop gap measure to ensure that the bundled starter kit sub-theme cannot be enabled or used directly. This helps people unfamiliar with Drupal avoid modifying the starter kit sub-theme directly and instead forces them to create a new sub-theme to modify.
> 0 votes

---
Tags: theming
---


# Question
Title: What are the pros/cons/alternatives to creating a number of identical content types to allow for divergence?
I hope this counts as an answerable question.

A publications database I'm migrating from another content management system to drupal, has different types of publications. In the current system those publications are kind of the equivalent of a taxonomy. It is clear from talking to people familiar with the history, and from looking at the state of the database and code, that every couple of years they rearrange things, adding or removing content types and changing the fields available. They used to try to dynamically change the fields available on the form depending on the content type. (peer-reviewed journal articles would have volume/Issue, pages, publication name, etc, where books would have different requirements, and online publications would be still different. This seems to have become very hard to maintain, so the current system now makes all fields available for all content types, and sometimes the same field is used for different types of data (total pages and page range for example). There are thousands of publications and sorting it all out programmatically seems quite difficult, so the thought is to bring everything over using the same fields (cleaning up the data where it can be done programmatically). Having differing fields per publication type is desirable, and in the future they would like to have an approvals process built into the system with differing approval paths per publication type.

Initially my approach was going to be much like theirs, to have one publications content type, and a publication type vocabulary to categorize them. Thinking of the need for future divergence of fields, and the likelihood of a requirement to change the display depending on the publication type, I've modified my approach to start with an identical content type per publication type to allow for things to change over time.

Is this going to cause terrible problems for me down the road if they decide that two types of report are now one publication type? I'm already seeing a little bit of difficulty in the ability to make dynamic templates that cover the entire set of publication types. It has been quite painful to move any changes made in one content type over to all the others.

Would it be more sensible to try the approach of having all the fields we need in one content type and trying to dynamically hide or show those fields depending on the publication type selected?

Is there some other more sensible way of going about this that I haven't thought of? It seems like somewhere along the line I'm going to run into pain either changing the fields or with changing publication types, I'm just not sure which kind of pain is likely to be better.

# Answer
> 2 votes
> Initially my approach was going to be much like theirs, to have one publications content type, and a publication type vocabulary to categorize them.

The problem with this approach is that you won't be able to use pathauto to give them different paths per type. Ex: You want the books type to be `/books/title-goes-here` and the cars type be `/cars/title-goes-here`

If books and cars are the same content type then node author would have to manually type in the url alias.

Also, how do you plan on theming them? If each type needs to be themed differently, I don't know how you're going to pull that off since they are all the same content type.

I think making 16 different content types is the way to go. You can always re-use existing fields whenever you can.

> I'm already seeing a little bit of difficulty in the ability to make dynamic templates that cover the entire set of publication types.

You could use the Panels module which allows you to theme all 16 content types differently or the same. With panels you won't have to deal with tpl (template) files.

Checkout this Panels Video Tutorial series

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


title: add a template file to custom theme

text:
# Question
Title: add a template file to custom theme
I've added a new theme to my site and I've added a new content type called code\_excerpt. Now, I've created a new template called `code_excerpt.tpl.php` and added it to my theme folder but when I created a new page using the newly created code\_excerpt as content type it appears that the template used is still `page.tpl.php` as opposed to `code_excerpt.tpl.php`. As I'm pretty new to drupal, is there anything else that I need to do in order to get my content type to utilize that template? Any suggestion would be much appreciated.

# Answer
I believe it needs to be `node--code-excerpt.tpl.php`

don't forget to clear the cache.

Copy `node.tpl.php` to `node--code-excerpt.tpl.php` then modify code as necessary.

Here is my node.tpl.php file

```
<?php
/**
 * @file
 * Default theme implementation to display a node.
 *
 * Available variables:
 * - $title: the (sanitized) title of the node.
 * - $content: An array of node items. Use render($content) to print them all, or
 *   print a subset such as render($content['field_example']). Use
 *   hide($content['field_example']) to temporarily suppress the printing of a
 *   given element.
 * - $user_picture: The node author's picture from user-picture.tpl.php.
 * - $date: Formatted creation date. Preprocess functions can reformat it by
 *   calling format_date() with the desired parameters on the $created variable.
 * - $name: Themed username of node author output from theme_username().
 * - $node_url: Direct url of the current node.
 * - $terms: the themed list of taxonomy term links output from theme_links().
 * - $display_submitted: whether submission information should be displayed.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. The default values can be one or more of the following:
 *   - node: The current template type, i.e., "theming hook".
 *   - node-[type]: The current node type. For example, if the node is a
 *     "Blog entry" it would result in "node-blog". Note that the machine
 *     name will often be in a short form of the human readable label.
 *   - node-teaser: Nodes in teaser form.
 *   - node-preview: Nodes in preview mode.
 *   The following are controlled through the node publishing options.
 *   - node-promoted: Nodes promoted to the front page.
 *   - node-sticky: Nodes ordered above other non-sticky nodes in teaser listings.
 *   - node-unpublished: Unpublished nodes visible only to administrators.
 * - $title_prefix (array): An array containing additional output populated by
 *   modules, intended to be displayed in front of the main title tag that
 *   appears in the template.
 * - $title_suffix (array): An array containing additional output populated by
 *   modules, intended to be displayed after the main title tag that appears in
 *   the template.
 *
 * Other variables:
 * - $node: Full node object. Contains data that may not be safe.
 * - $type: Node type, i.e. story, page, blog, etc.
 * - $comment_count: Number of comments attached to the node.
 * - $uid: User ID of the node author.
 * - $created: Time the node was published formatted in Unix timestamp.
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 * - $zebra: Outputs either "even" or "odd". Useful for zebra striping in
 *   teaser listings.
 * - $id: Position of the node. Increments each time it's output.
 *
 * Node status variables:
 * - $view_mode: View mode, e.g. 'full', 'teaser'...
 * - $teaser: Flag for the teaser state (shortcut for $view_mode == 'teaser').
 * - $page: Flag for the full page state.
 * - $promote: Flag for front page promotion state.
 * - $sticky: Flags for sticky post setting.
 * - $status: Flag for published status.
 * - $comment: State of comment settings for the node.
 * - $readmore: Flags true if the teaser content of the node cannot hold the
 *   main body content.
 * - $is_front: Flags true when presented in the front page.
 * - $logged_in: Flags true when the current user is a logged-in member.
 * - $is_admin: Flags true when the current user is an administrator.
 *
 * Field variables: for each field instance attached to the node a corresponding
 * variable is defined, e.g. $node->body becomes $body. When needing to access
 * a field's raw values, developers/themers are strongly encouraged to use these
 * variables. Otherwise they will have to explicitly specify the desired field
 * language, e.g. $node->body['en'], thus overriding any language negotiation
 * rule that was previously applied.
 *
 * @see template_preprocess()
 * @see template_preprocess_node()
 * @see template_process()
 */
?>
<?php if (!$page): ?>
  <article id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php endif; ?>
    <?php if (!$page): ?>
      <header>
    <?php endif; ?>
      <?php print render($title_prefix); ?>
      <?php if (!$page): ?>
      <h2 class="title" <?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
      <?php endif; ?>
      <?php print render($title_suffix); ?>

      <?php if ($display_submitted): ?>
        <span class="submitted"><?php print $submitted; ?></span>
      <?php endif; ?>

    <?php if (!$page): ?>
      </header>
  <?php endif; ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php
      // Hide comments, tags, and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>
  </div>

  <?php if (!empty($content['links'])): ?>
    <footer>
      <?php print render($content['links']); ?>
    </footer>
  <?php endif; ?>

  <?php print render($content['comments']); ?>
<?php if (!$page): ?>
  </article> <!-- /.node -->
<?php endif; ?>

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How do I get a field translated in Drupal 8
I have a multilingual site in Drupal 8, and several node, some translated and others not. As I can programmatically get the translated field or by default they give it back from the original language.

I got this:

```
$service_entities = entity_load_multiple_by_properties('node', array('type' => 'service'));

$services = [];
foreach ($service_entities as $entity) {
  $services[] = [
    'title' => $entity->title->value,
  ];
}

```

This code work fine, but when the title is translated Drupal give back in the default language in which it was created.

# Answer
You can get a specific translation with `$translation = $entity->getTranslation('de')`, then you can use $translation exactly the same as $entity.

Usually, you don't want to get a specific translation, but the best translation that is available for the current language. For that, use getTranslationFromContext() like this:

```
 $translation = \Drupal::service('entity.repository')->getTranslationFromContext($entity);

```
> 30 votes

# Answer
Loading all help\_page and return it in the current language:

```
$elements = [];
$ids = \Drupal::entityQuery('node')
  ->condition('type', 'help_page')
  ->execute();
$nodes = Node::loadMultiple($ids);
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

foreach ($nodes as $node) {
  $translation = $node->getTranslation($language);
  $elements[] = [
    'title' => $translation->title->value,
    'url' => $translation->url(),
    'img' => $translation->field_imagen->entity->url(),
    'text' => $translation->body->value,
  ];
}
return $elements;

```
> 5 votes

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


title: How to handle translation correct way?

text:
# Question
Title: How to handle translation correct way?
Some background: On the site I'm maintaining, I installed Internationalization module and also enabled `Node Translation`. I added a few languages, then set a node's language to French and site default language to English.

When the site's current language is set to French, the node shows up as `en/node/28`, however shows up as `fr/sous-specialites` when the current language is French. How do I work this around?

UPDATE: Detection and Selection page has URL, Session, User and Browser enabled.

# Answer
I guess you want the url alias to be `/sous-specialites` for the english node. If so, I think you can use Global redirect module.

> From the documentation,
>
> What?
>
> GlobalRedirect is a simple module which…
>
> * Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
> * Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
> * Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match.
> * Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
> * Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
> * Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.
> * Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect\_admin module. In Drupal 6, the settings page is bundled into the module.
> 0 votes

# Answer
# Option 1:

The order specified at `Configuration -> Languages -> detection and selection` could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. But in my experience, I often get these kind of issues to work by using an order like "`URL, Default, User`", and not something like "`Default, URL, User`". So try to experiment a bit with the various combinations in this order to check if it helps.

# Option 2:

Another reason why such issue / problem may occur, is because Language detection by domain only works on port 80 and/or URL generation only works on port 80. Those issues have 'some patches' attached to it, and status = *Needs review*.

So if you're not using port 80, then you may want to try/consider experimenting with any of the patches in these issues.
> 0 votes

---
Tags: 7, i18n-l10n
---