# Question
Title: How to redirect user "back two pages" after login
My users are only able to log in on the mysite.com/user page (I don't use any of the login blocks). How can I redirect those users to their location "two pages ago"? For example, they might visit the about us page, then click login (taking them to the /user page). After they complete their login, I would like for them to be redirected back to the about us page.

I currently have it set to redirect to the previous page after login, but that will always be the "user" page, which is not particularly useful in this instance.

Thanks!

# Answer
> 1 votes
Append

```
?destination=[PATH]

```

to your login link.

You can do this with the Menu Token Module

# Answer
> 0 votes
If you have put the `user/login` in a menu you can you this theme function in your `template.php` file to override the links to add the `destination` parameter, here is a sample code.

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

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  // Add destination query parameter for login, logout and register menus
  if (in_array($element['#href'], array('user/login', 'user/register'))) {
    $element['#localized_options']['query'] = array('destination' => current_path());
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

---
Tags: 7, users, redirection
---


title: Search Drupal source/plaintext?

text:
# Question
Title: Search Drupal source/plaintext?
I'm looking for a simple way to search thru the plaintext/source of hundreds of nodes. I need to find-replace all the color settings for a certain font awesome icon (`fa-check`), but can't find any good way to check our source for which pages are using that icon. New Drupal admin here, haven't really done any dev work, so answer that doesn't require installing new modules would be great.

We're using Solr for search, incidentally.

# Answer
> 1 votes
You want to use the Scanner module:

> Versions 5.x-2, 6.x, and 7.x of Search and Replace Scanner can do plain text search-and-replace, or regular expression search-and-replace, against the title, body and text content fields on all nodes in your system. This is useful for finding html strings that Drupal's normal search will ignore. The module is very handy if you are fixing typos in a lot of content, changing the name of your company, or are changing the URL of a link included multiple times in multiple nodes, among other things.

---
Tags: search
---


# Question
Title: Controlling remote Drupal sites with Drush
For a couple of weeks now I have been watching various screencasts and envying those who can operate Drush on their sites, esp. when enabling/disabling of the modules, or clearing cache. The time savings seem to be immense.

However, as a more of a front-end developer, rather than a qualified, fluent console operator, I find myself completely lost as per the usage of Drush with remote sites. Most of the googled readings treat about local sites, they specify paths to local installations, or they assume that a site was created using site-install command. While I am interested in adding Drush to an existing remote site. How do I add Drush into play with that remote site?

Now that I'm trying to get the big picture of using Drush, I think I may have missed some principal knowledge about the environment and tools needed, which I haven't found anywhere.

1. Apart from having command line Drush installed on my desktop, do I have to install Drush module on my remote site? Or is Drupal core Drush-controllable out-of-the-box (if it is, what is the purpose of Drush module available at drupal.org/project/drush)
2. Do I have to configure SSH for communicating the server?
3. Do I need to provide db credentials anywhere (where)?
4. Do I need to define FTP credentials anywhere (where)?
5. aliases.drushrc.php: does it live only on my desktop, or should I define anything similar on the remote ftp?

My setup involves staging and production sites, the former also stored on a remote ftp server with its own domain. I would like both to be controllable via Drush. Is that feasible?

It'd be great if someone could shed some light on me.

# Answer
> 6 votes
You have a lot of questions there, but I'll try to give you the best overview of how to do this easily.

First, note that though Drush is listed as a module on Drupal.org, it is not technically a module as you don't "enable" or "disable" it like other modules.

1. Yes, Drush must be installed on the remote site. When you do so, make sure to install the same version that you have installed locally. It may still work if you're using different versions, but it can also cause strange bugs that are difficult to troubleshoot so always try to keep the same version.
2. It's certainly easier if you have SSH set up for some of the Drush commands. Your web host should be able to help you with getting SSH keys set up for your local machine.
3. Yes, you will need to provide DB credentials. This can be done by following the example in `drush/examples/example.aliases.drushrc.php` in the drush folder.
4. No, I don't think so.
5. You do not need to set up the alias on your desktop *unless* you are going to be logging in to your remote server and using aliases there.

Basically, if you have SSH working and have installed Drush on the remote server as well as your local machine, then, once you set up an alias, you can type something like drush @myremote status and it should work.

# Answer
> 2 votes
I created a write-up on how you can use drush with remote sites if you have FTP and database access to them, but not SSH access. It's a bit of setup, but if you can't live without drush, or work with lots of sites, it's worth it.

My writeup, if your local computer is Linux: http://eworldproblems.mbaynton.com/2014/07/drush-remote/

The same principle, if your local computer is Windows: http://classically.me/blogs/drush-synchronization-ftp

---
Tags: 7, drush
---


# Question
Title: Ajax call failing in Workbench email module
I'm having trouble with ajax in the workbench email module. On two nodes (out of hundreds), the ajax call to get a list of users to notify when the publication status changes will fail. The error is "Invalid form POST data". I added watchdog logging, and actually the entire $\_POST is missing when the ajax fires. Does anyone know what would cause that?

I can't reproduce this in our development environment. I copied the database down, and the codebase is the same, but the same node works just fine in dev.

I've turned off boost caching on the live site and deleted the cache, and that did not help (although it's a node edit form, so I didn't think caching should matter).

It's consistently happening to the same two nodes, but I can't see anything different about them than the other nodes that work without issue.

One more thing -- I am using the Ajax Debugger chrome extension, and postData is populated in the request object with all of the form data and sent to the server. So it must be something in the drupal\_bootstrap to remove $\_POST data, but I'm stumped.

# Answer
> 2 votes
Thanks to Clive's suggestions, I logged the request and post data before the Drupal bootstrap kicked in, and found that it was not Drupal causing the issue.

The root cause was two different mod\_security violations: PCRE limits exceeded and matching rule 300016 (Generic SQL injection protection). Increasing the PCRE limit and adding an exception for the SQL Injection rule:

```
<LocationMatch "/system/ajax">
  SecRuleRemoveById 300016
</LocationMatch>

```

Just for the record, I got the idea that Drupal might strip out $\_POST data from this comment: https://www.drupal.org/node/2209051#comment-8539311 I came across it trying to troubleshoot this issue earlier. Maybe I misunderstood or took it out of context. This was a hard one for me to figure out, and I was grasping for anything that sounded close to my issue. Thanks for the help, Clive!

---
Tags: ajax
---


title: access profile2 fields values

text:
# Question
Title: access profile2 fields values
How can I access fields values inside *profile2* main profile? Only on edit main profile page? I try to hide a field on profile2 edit page based on another value. Code is from my *template.php*

```
function my_theme_form_profile2_edit_main_form_alter

```

and then calling

```
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
$checkbox1 = $profile->field_checkbox_admin1['und'][0]['value'];

```

The problem is that profile variable is not accessible if all of the fields in profile are empty. dpm($profile) shows nothing and I get undefined variable error.

# Answer
> 2 votes
Just define the variable already before using it

```
$profile ="";
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
$checkbox1 = isseet($profile->field_checkbox_admin1['und'][0]['value']) ?      $profile->field_checkbox_admin1['und'][0]['value'] : "";

```

That is nature the profile 2 module, it doesn't create any entry for any field in the database untill it is not assigned any value actually. So it returns nothing if it is empty.

Hope it will help

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


title: Possible to change the url path?

text:
# Question
Title: Possible to change the url path?
Wonder how to make http://example.com instead of http://example.com/drupal? I want everything intact without changes.

Searched for an answer on Google, but there seems to not be one.

# Answer
Follow through these steps hope it could help.

1. Just copy all the data from drupal directory located on the server to one level up.
2. Now delete the drupal directory and check the site by running it directly by http://example.com
3. if it doesn't work, then check in the setting.php and search for the line if defined.

$base\_url= "http://example.com/dev";

// Now change this line to

```
 $base_url = "http://example.com";

```

OR the other way you can rewrite the base using .htaccess file located at the root.

Hope it will help you.
> 0 votes

---
Tags: uri
---


title: change background color in Drupal 7

text:
# Question
Title: change background color in Drupal 7
I have Drupal 7.14 and Zen 7.x-5.1. I cannot figure out how to simply change the background color. I have tried placing `background: red;` in several of the css pages but have had no luck.

# Answer
> 1 votes
The Zen theme uses many different CSS files. You need to create a subtheme for Zen and then you are supposed to choose which layout you want. Fixed or Liquid.

Within the subtheme there are many CSS files. Depending on your choice of Fixed or Liquid you have to edit that css file...

layout-liquid.css or layout-fixed.css

Within that file you can change the parameters you are trying to override. As long as you don't have css files aggregated in the performance settings you do not need to clear the caches, otherwise you do.

To create a Zen subtheme you need to follow a tutorial: http://drupal.org/documentation/theme/zen

I recommend going through that completely and reading and learning as much about Zen as possible. One thing to know is that you never want to alter the core files of Zen, you only want to override them in your own subtheme.

Lastly, adding your own custom CSS file can be useful, but for this situation it would not be recommended because there are already CSS declarations for your use. I use a custom Zen subtheme for this site: https://www.fdanconia.com/ \- I love the Zen theme structure and once you learn where everything is and how to override everything is a great theme to use.

# Answer
> 1 votes
Try to use `Firebug` and see if what CSS file you need to update to. The usual file is `pages.css`. Also see if the css is overridden (usually in strike-through).

You can try to use important if you are suspecting some css is overriding your css rule.

```
body {
  background: red !important;
}

```

# Answer
> 0 votes
I found that if you go into the Configuration -\> Development -\> Performance and disable bandwidth optimization and clear the cache it will reload the new css changes.

# Answer
> 0 votes
normalize.css line 121

```
background: url("localhost/zen/sites/all/themes/sub/images/bg.png") repeat scroll 0 0 #FFFFFF;
}

```

# Answer
> 0 votes
First make sure in which file you need to make css changes.

Just go to ***Appearance \> Settings*** links in Zen theme Now choose css that you are choosing

1. Fixed layout (layout-fixed.css)
2. Liquid layout (layout-liquid.css)

You can make the css changes in the file that you have chosen from this option.

Also still you need to firebug it to check which line you have to override for background change.

Hope it will help.

---
Tags: 7, theming
---


# Question
Title: creating menu items with children (sub items)
i want to have a menu option called Info in my 'main menu', which has children of Policies and Contact. how can i set it up so that when a user clicks on Info, it just shows the child options in the drop down underneath Info and doesnt display a node? I only seem to be able to achieve what I want by setting up a blank dummy node which Info is linked to. I'm using Superfish, but i dont think thats relevant.

# Answer
> 0 votes
How about installing Menu attributes. See if it's nofollow option works. If not, still use it by setting a class of 'no-follow' on this particular menu-item. Then add some jQuery to you pages wherein you target the anchor tag related to this class for its click event and disable the default action. I don't think there should be a conflict as Superfish opens up menus on hover, I think? But try. And also set up the menu so that it points to the first child so that Drupal menu UI will accept.

How to Disable/Inactivate Some of the Non-Leaf Menu-Items (but keep their children visible and enabled/active)

---
Tags: routes, navigation
---


title: Custom template suggestion

text:
# Question
Title: Custom template suggestion
I have this preprocess function:

```
function drisco_preprocess_page(&$vars) {
    $node = $vars['node'];
    $vars['theme_hook_suggestions'][] = 'page__node__' . clean_class($node->title);
    array_unshift($vars['theme_hook_suggestions'], 'page__node__' . clean_class($node->title));
    dpm($vars);
}

```

`dpm()` tells me my suggestion array looks like this:

```
0 (String, 26 characters ) page__node__hotel-overview
1 (String, 10 characters ) page__node
2 (String, 13 characters ) page__node__%
3 (String, 14 characters ) page__node__68
4 (String, 10 characters ) page__page
5 (String, 11 characters ) page__hotel
6 (String, 26 characters ) page__node__hotel-overview

```

My template file is called "page--node--hotel-overview.tpl.php" but isn't being used. I have page.tpl.php template file in my theme dir.

What am I doing wrong?

If I erase the template suggestions array and replace it with my own with only one file in it like thus, it loads the template. If I append or prepend the same suggestion, it just loads page.tpl.php.

```
$vars['theme_hook_suggestions'] = array('page__node__68');

```

This is a child theme; could that be making a difference?

# Answer
> 0 votes
1. Clear the caches to ensure your new template file is being picked up.
2. The template file should be in the "templates" folder inside your custom theme.

# Answer
> 0 votes
1. The naming of both your suggestion and template look legit.
2. If I read this correctly, the suggestions array should be sorted from more general suggestions (on the top) to more specific suggestions (on the bottom). Not sure why you are using array\_unshift to prepend the most specific suggestion to the beginning of the array. Also, could it be that putting the same suggestion in the array twice is throwing off the theming layer?
3. Did you check to make sure that the `'theme_hook_suggestion'` key is empty? It accepts a single value that takes precedence over the `'theme_hook_suggestions'` key. Just out of curiosity, what happens if you use it? If you populate `theme_hook_suggestion` and still your template does not get called, I would be more wary of #5 below. If it does get called, maybe I would be concerned about what I said on #2 above.
4. Where are you implementing that hook, in template.php or a module? There's a chain of preprocessing hooks called by theme() every time, and depending where your hook is it might or might not be getting overridden by another hook down the theme() preprocessor chain. Very unlikely your case I think, but it's not impossible. If your hook is being implemented in the module layer, move it to the theme layer and see what happens. The theme layer has higher precedence - it gets called after the module layer.
5. It looks like your problem is the location of the template itself. A) What is the value of $theme\_path and $info if you run this code below? B) Is your template currently located where $theme\_path below points to?

_

```
  drupal_theme_initialize();
  $hooks = theme_get_registry(FALSE);

  $info = $hooks['page'];
  global $theme_path;
  $temp = $theme_path;
  // point path_to_theme() to the currently used theme path:
  $theme_path = $info['theme path'];

```

# Answer
> 0 votes
I am thinking it can't have a - in it anywhere, eg, in hotel-overview, because these could be theme functions as well, and obviously, php wouldn't like `function theme_page__node__hotel-overview()` so I'd change all the -'s to \_'s in your sanitized title and see if it finds it (but keeping the dashes in the template name)

# Answer
> 0 votes
For the template file:
**`THEME/templates/page--node--hotel-overview.tpl.php`**

try:
**`page__node__hotel_overview`**

Hyphens in templates filename are converted to underscores, both singles and doubles.

*Edit: Woops, this was acutally quite old. My bad.*

# Answer
> 0 votes
Let me explain you the template order

In this, you can alter the header and footer if you wanted it to be different than normal page layout that is set in the page.tpl.php

page--**\[content-type name\]**.tpl.php = page--lab.tpl.php It will be used to theme all contents of type lab including header and footer

page--node--**\[content-id\]**.tpl.php = page--node--12.tpl.php It will be used to theme content with 12 including header and footer

Secondly,

1. **node.tpl.php** Will work for all type of content on the site
2. node--**\[content-type name\]**.tpl.php (**node--lab.tpl.php**) will used to alter the content part only of lab type content excluding header and footer
3. node--**\[node-id\]**.tpl.php(node--10.tpl.php) will use to alter the content part of node 10 only excluding header and footer

Including and excluding meand control over header and footer.

Hope it will help you!

---
Tags: 7, theming
---


# Question
Title: If Profile2 fields are empty, problem in accessing data
I just found out that if ALL fields of certain *Profile2* profile ie. main are empty, I am not able to access data inside main profile. For example I want to do a check if a field is empty but can not access it using

```
global $user;
$account = user_load($user->uid);
$data = profile2_load_by_user($account);

```

How can I access the fields? thank you.

# Answer
I would suspect that profiles only get created when needed, hence when it is saved with field values.

You most probably then are trying to look at a profile of a user who does not yet have a profile. You should do a test on $data. If it is null or false, then you should assume that the user has no profile and that the fields are in effect empty. If you want to alter the fields then you must set up a profile object and save it after validation.

The docs for profile2\_load\_by\_user is misleading as it indicates that there will always be a profile returned, but looking through the source code I can see a return value of FALSE.

If there is a profile then return value is either a single profile or an array of profiles, so you must test $data for 3 things: false, object, or array of objects.
> 0 votes

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


# Question
Title: How to display Rate module widget by php
I'm using the Page Manager (Panel) to customize the node layout, and the Rate module to rate them.

How to print the rating widget of the current node using php ?

I've tried to use this code but no result.

```
<?php  print rate_embed($node, 'page_rating', RATE_FULL);  ?>

```

# Answer
print $node-\>rate\_NAME\['#markup'\];

Replace NAME by the widget's machine readable name.
> 1 votes

# Answer
**print rate\_embed($node, 'plus1', RATE\_FULL);**

Here, first parameter(**$node**) is the entity where you want to vote '**plus1**' is the type of widget that you want to add **RATE\_FULL** is the display type of widget . Either it can be full or mini.

Try by passing $node =node\_load(10). Where 10 is id of some node that exists in the site

Hope it will help
> 1 votes

---
Tags: 7, rating
---


# Question
Title: Better Exposed Filters: filter options display
I have created some BEFs as checkbox list to allow multiple selectios, the filtering options are many, so I want only limited filter options to appear say 5. If I click on more then only it should show the remaining.

for eg:

FILTER OPTIONS op1 op2 op3 . . . opn

I want them to appear as

FILTER OPTIONS op1 op2 op3 op4 op5 more on clicking more link it has to display the remaining options. How ca i achieve this?

# Answer
As i mentioned in comment you can do this with small custom JS without modifying Better exposed file any way. Create a custom module with `hook_form_views_exposed_form_alter()`

```
//MYMODULE.info

name = MY CUSTOM MODULE
description = custom module for hiding extra BEF checkboxes
package = Custom
version = VERSION
core = 7.x

// MYMODULE.module

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form['#id'] == 'YOUR_VIEWS_EXPOSED_FORM_ID') {
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'MYMODULE') . '/js/MYMODULE.js' => array(
       'type' => 'file',
     ),
    );
  }
}

// js/MYMODULE.js

(function($, Drupal, window, document, undefined) {
  $(document).ready(function(){
    // your js code goes here with logic to hide and show the extra checkboxes
  });
})(jQuery, Drupal, this, this.document);

```

Change **MYMODULE** with your custom module name every where in this code. check jquery api for show, hide functionality, and text for replacing `more` and `less` vice versa.

**UPDATE:**

Changed :

```
 if ($form_id == 'YOUR_VIEWS_MACHINE_NAME') {

to

 if ($form_id == 'views_exposed_form' && $form['#id'] == 'YOUR_VIEWS_EXPOSED_FORM_ID') {

```
> 0 votes

# Answer
You have to use javascript like show/hide jquery plugin/scripts show/hide jquery plugin/scripts . just take the id of dropdown list and then apply jquery where you want. include jquery script where you mostly write. its upto you.
> 0 votes

---
Tags: views
---


# Question
Title: Append an <i> tag to entity field view hook
On a field of field type = LINK and widget = LINK, I want to add an tag on the rendered output.

The reason is to be able to add a class, not to the whole tag output, but to append a FontAwesome icon.

Hook\_page\_alter, of course shows all of the rendered HTML. I really don't want to mess with that.

I tried hook\_entity\_view\_alter. That works in a clumsy fashion but two problems:

1) It only affects the output from the node displayed via a view 2) It appends the tag in new after the displayed link.

It appends the tag in new after the displayed link.

# Answer
> 1 votes
You can theme individual fields: https://api.drupal.org/api/drupal/modules!field!field.module/function/theme\_field/7

You can either have a theme function in template.php or a `tpl.php` template file, the former is preferred for performance reasons.

Using a theme function you could do something like:

```
THEMENAME_field__link($vars) {
  $output = '';
  foreach ($vars['items'] as $delta => $item) {
    $link = l($item['#title'], $item['#href']);
    $output .= '<div class="' . $vars['classes'] . '"' . $vars['item_attributes'][$delta] . '>' . $link . '<i class="fa fa-download"> </></div>';
  }
  return $output;
}

```

Though you'll have to check `$vars` for specifics. As for checking the widget I think you can get a clue from `$vars['element']['#formatter']`

---
Tags: hooks
---


# Question
Title: Can I call two callback function in one ajax call?
I just want to know how we can achieve two ajax callback on one form submit.Is it possible?and how?

# Answer
No, it is not possible. Why would it be? Ajax callback can return a piece of HTML to replace your AJAX wrapper. If you will call two, which one would Drupal use? How should it decide? That's why `#ajax['callback']` is defined as a name of a function, not an array of names. with one function you avoid problems like that.

If you need to call two function in response to AJAX event, then write a callback that will include the logic I asked about in first paragraph, and call functions you need from that callback.
> 3 votes

# Answer
You can't do that directly. Instead, use a function that calls the two other functions.

```
'#ajax' => array(

  'callback' => 'my_callbacks_wrapper',
)
...

```

Then:

```
my_callbacks_wrapper($form, $form_state) {

  $first_callback_processed_form = first_callback($form, $form_state);

  $second_callback_processed_form = second_callback($first_callback_processed_form, $form_state);

  return $second_callback_processed_form;

}

```

Make sure your callbacks don't interfere.
> 4 votes

---
Tags: ajax, routes
---


title: Newsletter content aggregation

text:
# Question
Title: Newsletter content aggregation
I'm using the Simplenews module for creating newsletter and I would like to know if it's possible to aggregate different newsletter content into only one for the same subscriber. For example, one person subscribes to 3 different newsletters on the same website and receives only one newsletter containing the 3 content of those three newsletters.

# Answer
No, you can't do that with the current version of simplenews.

Some alternatives:

1. Use Mailchimp integration and create segments, groups, then use conditional merge tags (http://kb.mailchimp.com/article/all-the-merge-tags-cheatsheet#Conditional)
2. You could hack the simplenews module, but that is more shaky... Using the simplenews scheduler and the simplenews content selection module you could patch up a solution.
3. The newsletter module might be the best platform to do this as they are active and you might find people who want to collaborate. Also the architecture is more generic.

For the moment I will use #1, but in the future I will probably have to implement a neater solution with #3.
> 1 votes

---
Tags: emails
---


# Question
Title: how to get the count of total comments posted for specific content type including deleted comments too?
I want to get the total count of comments posted only for a specific content type including deleted to get the highest comment id no matter whether comment is been deleted. please help me or else suggest me other way to achieve this.

# Answer
> 1 votes
You can always dig around the database with a db query with something like:

```
$content_type = 'mycontenttype';
$query = db_select('comment', 'c');

$query->join('node', 'n', 'n.nid = c.nid'); //JOIN node with comment
$query->fields('c', array('cid')); //SELECT the fields from comment
$query->condition('n.type', $content_type, '=');
$query->orderBy('c.cid', 'DESC'); //ORDER BY comment id

$num_comments = $query->countQuery()->execute()->fetchField();
$latest_comment_cid = $query->execute()->fetchField();

```

**EDIT** In this example I assume you mean unpublished comments and not deleted. See Anil's answer if you want to track count of deleted comments as well.

# Answer
> 1 votes
You need to write a custom module to achieve this... I am afraid there won't be any contributed module which will give you stats even if comment is deleted... Please find steps below to solve your use case..

* Create a custom module
* Implement hook\_schema in .install file and create a table to track comment inserts so that even if a comment is deleted you have an entry of comment
* Implement hook\_comment\_insert in .module file to update above custom table you have created using hook\_schema

---

```
function hook_comment_insert($comment) {
  // Reindex the node when comments are added.
  $node = node_load($comment->nid);
  if ($node->type == "YOUR_CONTENT_TYPE") {
     // Use db_insert to make an entry to track comments into your custom table
  }
}

```

# Answer
> 0 votes
It is solved. this issue was there because I had replaced text-area with text-box on comment form. I just did revert it and it worked. But I don't think that just replacing fields this issue occurs.

---
Tags: views, comments
---


# Question
Title: Count number of values within a field that accepts unlimited values
I have an image field which can contain unlimited values. How can I display the number of image values contained within this field in views?

I'm using Drupal 7.

# Answer
> 4 votes
first install computed field module then you should write a for loop within variable which count the value of the field then you just output this variable.

# Answer
> 11 votes
There is a way of doing this natively in Drupal 7.

1. Set 'Use aggregation' to Yes
2. Add a field that contains multiple values, such as a file field
3. Set the aggregation settings for it to COUNT DISTINCT

Simple. This will however enable aggregation for all fields, but the default settings for other fields will make them behave normally.

# Answer
> 2 votes
Good question. There might be a better or built in way to do this, but if not, first check the `group multiple values together` configuration option in the field you are dealing with and then create a template for that view and field in question:

```
<?php
$foo=node_load($row->nid);
if (count($foo->field_photo)) {
  print 'There are ' . count($foo->field_photo) . ' photos in this node.';
}

```

By quickly throwing a view together named `foo` with a `field_photo` in it, this would be in a template called `views-view-field--foo--field-photo-fid.tpl.php`

# Answer
> 1 votes
Using Views, you want your view to show fields, and your view field will be the delta of the entity field.

'Delta' just means count.

So for instance on my site in the views 'add field' dialog, I see a field called 'Content: File attachments (upload:delta).' Adding this lets me show how many files have been attached to that node.

When you configure this field, you'll probably want to pay attention to the 'no results behavior' section, to hide it if delta = 0 or something.

HTH.

# Answer
> 0 votes
Using the Views PHP module I added the Photos/Images field as normal and then added a Global PHP field and added:

```
$photos = $data->field_field_images;
$count = count($photos);
//dsm($count);
print $count;

```

---
Tags: views, entities
---


# Question
Title: profile2_load_by_user Trying to get property of non-object
I use simple code to hide field from profile2 main profile based on another field inside the profile2 main profile. If field\_testcheckbox is not checked, hide field\_info.

```
function odbornik_fields_form_profile2_edit_main_form_alter(&$form, &$form_state){
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
$checkbox = $profile->field_testcheckbox['und'][0]['value'];
  if ($checkbox == 0) {
     $form['profile_main']['field_info'][LANGUAGE_NONE][0]['#type'] = 'hidden';
    };
}

```

This code works ok for all users browsing their profiles, except admin user browsing own or others profiles, where I get error: Notice: Trying to get property of non-object on line with this code.

```
$checkbox = $profile->field_testcheckbox['und'][0]['value'];

```

Admin has the main profile as well and the checkbox field is there too. What can be the problem? Thank you.

# Answer
> 1 votes
You are assuming there is a profile for all users and your admin user seems to not have one. Add a check if there is a profile for the current logged in user:

```
function odbornik_fields_form_profile2_edit_main_form_alter(&$form, &$form_state){
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
if($profile) {
  $checkbox = $profile->field_testcheckbox['und'][0]['value'];
    if ($checkbox == 0) {
       $form['profile_main']['field_info'][LANGUAGE_NONE][0]['#type'] = 'hidden';
     }
  }
}

```

---
Tags: 7, users
---


# Question
Title: redirect user to page where they clicked an "add node" link
In several places on my site I use an "add node" link that lets users add a node (I'm using organic groups). After saving the node, I'd like to redirect users back to the page on which they clicked the "add node" link.

I know how to redirect users to a specific page after saving a node, but that doesn't work in this case, as the add link shows up on several pages.

I've tried setting $form\_state\['redirect'\] = false, but that also doesn't help as it puts users back in the node edit page.

Would be wonderful if anyone could point me in the right direction. Thanks!

EDIT: 2 minutes after I posted this I came up with the following: `<a href="node/add/contact?destination=node/52">Add Contact</a>`

This redirects the user to node 52, which happens to be the group page on which this add link lives. This is a step in the right direction. Would be even better if I could use a token in the link.

# Answer
You can use Token Filter module and the following code should work:

```
<a href="node/add/contact?destination=[site:current-page:path]">Add Contact</a>

```

Make sure that the token filter is available in the text format you are using.
> 0 votes

---
Tags: redirection
---


# Question
Title: Why doesn't my token redirect to the previous url?
I thought I could use the following code:

```
<a href="user/login?destination=<?php print token_replace('[current-page:url]'); ?>a link</a>

```

to redirect users to the page they were on after log in, but it doesn't seem to work.

I can see the correct url on the login page, e.g.:

> mysite/user/login?destination=the url of the page I was on

but when I login I am still redirected to `mysite/users/my` user name.

# Answer
> 1 votes
If you want to Redirect to previous drupal page after login, you can try this.

```
print l("Login","user/login",array('query' => drupal_get_destination()));

```

see drupal\_get\_destination

# Answer
> 0 votes
You can use Token Filter module and the following code should work:

```
<a href="user/login?destination=[site:current-page:path]">a link</a>

```

Make sure that the token filter is available in the text format you are using.

---
Tags: users, tokens, redirection
---


# Question
Title: Pass multiple ids as Views Arguments in the Rule action Save PDF as file on server
I'm using views PDF to print out a list of nodes on a single PDF, one per page. Now I have more than 1000 nodes/pages on a single generated pdf, so I'm trying to use VBO and Rules to create a view where I can filter/select the nodes I need and execute a Rule component that saves the resulting pdf on the server and sets a field "printed" to "yes" on those nodes.

The problem is that every time I fire my Rule the saved PDF has just the last selected node via VBO. On the "Views Arguments" of the "Save PDF as file on server” action, instead of \[node:nid\] I've tried writing manually some node ids (eg. 1,2,3...) and it works fine: the saved PDF has all the written nodes printed out.

Probably I have to write some PHP code to print the VBO-passed ids as a single csv argument. I've tried something like this and doesn't work, blank pdf page. How to debug?

```
<?
$vboNids=arg(1);
echo implode(",",$vboNids);
?>

```

Thanx in advance.

# Answer
If I would like to save those files using vbo then I would try to create drupal action in your own module. And in this case you wouldn't need rules. Or you could revoke rules event if you would want to with rules\_invoke\_event function;

```
function mymodule_action_info() {
  return array(
    'dosomethinggoodfunction' => array(
      'type' => 'node',
      'label' => t('Do something'),
      'configurable' => FALSE,
      'triggers' => array('node_save'),
    ),
  );
}
function dosomethinggoodfunction($node) {
  // function to do some good stuff.
}

```
> 0 votes

---
Tags: 7, rules, views
---


# Question
Title: Webform: prepopulate fields through URL, "page not found"
I'm trying to prepopulate fields in a webform from the URL. I'm using Webform 7.x-3.20. I have a form named prepopulate. It has a field "First Name" which has the default value set to %get\[first\_name\]. I have tried to prepopulate the field from the following URL:

```
http://localhost/test_site/?q=content/prepopulate?first_name=miranda

```

This results in a "page not found" error. Does anyone know why this happens?

Thanks in advance!

\*UPDATE: I've figured out this happens because it is a rewritten URL (Pathauto). Still don't know how to fix it, though.

# Answer
Here is the answer.

It seems clean URLs are not enabled in your site. So here I'm giving the solution in both ways

Assuming that your **Field Key** for *First Name* field is `first_name`

**If clean URLS not enabled.**

> `http://localhost/test_site/?q=content/prepopulate&first_name=miranda`

**If clean URLS enabled**

> `http://localhost/test_site/content/prepopulate?first_name=miranda`

I've tested this on my environment and works perfect. Hope this helps
> 1 votes

---
Tags: webforms
---


title: Memcache integration is not loaded

text:
# Question
Title: Memcache integration is not loaded
I'm trying to setup memcache on my drupal 7 site. I have a memcache server setup and working and I've used setsebool -P httpd\_can\_network\_memcache 1 to allow apache to communicate with it. I've also confirmed that port 11211 tcp is open in ip tables.

I've installed the memecache drupal extension, the PECL extension in PHP and when I run phpinfo(); I see that memcache is loaded.

In settings.php on my drupal web server I have the following:

```
/**************************************************
 * MEMCACHE
 **************************************************/
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['memcache_servers'] = array(
        'memcacheserver.ourdomain.local:11211' => 'cluster'
);

$conf['memcache_bins'] = array(
        'bin1' => 'cluster'
);

$conf['memcache_key_prefix'] = 'sdrupal';

```

However when I go to the status reports page I see the following:

Memcache integration Memcache integration is not currently loaded. Check README.txt and ensure that memcache.inc is configured correctly in settings.php

I've read through the readme.txt file repeatedly and of course you can see I have memcache.inc specified above.

I thought perhaps I had a conflict with the varnish module, or the apc module as those also set cache\_backends - but its an array so I think thats ok. I also commented them out and I'm still seeing the error above.

I also confirmed that sites/all/modules/memcache/memcache.inc exists.

Why isn't drupal loading/finding memcache.inc?

Thanks Brad

# Answer
> 1 votes
You've got to add these lines to your settings.php file to run memcache proper:

```
$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

If you're on top of a multisite installation also don't forget to add this one:

```
$conf['memcache_key_prefix'] = 'unique_key';

```

More information about configuration and setting memcache for drupal you can find here.

# Answer
> 0 votes
To get this to work I had to comment out the following line:

```
//$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';

```

And add:

```
// the path to the core cache file
include_once('./includes/cache.inc');
// the path to the memcache cache file
include_once('./sites/all/modules/memcache/memcache.inc');

```

I'd love to know why this is necessary and what the difference is but at the moment it seems to be working.

# Answer
> 0 votes
You need to flush APC cache somehow to make the command work. Restarting Apache will do just fine. No need to manually use include\_once() to load the fields.

In my case, this was cased by the APC setting apc.ttl that was set to 0 to prevent the cache from expiring until Apache was restarted.

# Answer
> 0 votes
Please check the following example:

```
/**
 * Memcached Configuration
 */
if (class_exists('Memcache') || class_exists('Memcached')) {

  // Make memcache the default cache class.
  $conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc'; // NOTE: Just verify path where you've memcache module placed.
  $conf['cache_default_class'] = 'MemCacheDrupal';
  $conf['memcache_key_prefix'] = 'drupal_';

  // Ensure that the special cache_form bin is assigned to non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

  // Support for Memcached PECL extension
  // This new extension backends to libmemcached
  // and allows you to use some of the newer advanced features in memcached 1.4.
  if (class_exists('Memcached')) {
    // Enable the binary protocol, which is more advanced and faster.
    $conf['memcache_options'] = array(
        Memcached::OPT_BINARY_PROTOCOL => TRUE,
    );

    // Memcached takes options directly from Drupal.
    $conf['memcache_options'] = array(
        Memcached::OPT_COMPRESSION => TRUE, // Turn off compression, as this takes more CPU cycles than its worth for most users.
        Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT, // Allows you to add/remove servers easily.
    );
  }
}

```

It will automatically detect which memcache extension are you using and it'll load classes only it's present. In addition it has some common useful stuff.

---

Troubleshooting:

* check that your memcache module is enabled,
* go to /admin/reports/status/php and verify that you've section called memcache or memcached (if not, you've to properly install it, check your logs),
* when using command line, check your memcache via: `php -m | grep memcache`
* check at /admin/reports/status if you still having some issues,
* make sure that your memcached is up and running,

---
Tags: configuration, caching
---


# Question
Title: Entity Reference and Views to allow a nested structure
I'm trying to implement a nested structure in such a way as to get a table (within a view?) similar to this:

```
Parent      Child       Grandchild      Age     Sex
John                                    56      M
            Lisa                        29      F
                        Jim             4       M
                        Louis           6       M
            Mark                        24      M
            Sanda                       21      F
Marcela                                 45      F
            Sam                         21      M
            Andy                        18      M
...

```

For this I defined the following content types:

```
Parent:
+Title (name)
+Age
+Sex
+Child [entity reference]

Child:
+Title (name)
+Age
+Sex
+Grandchild [entity reference]

Grandchild:
+Title (name)
+Age
+Sex

```

The `+Age` and `+Sex` attributes are shared between the content types, and the nested structure is implemented with entity reference fields.

I tried using Views, but I couldn't find a way to achieve this.

Any hint ?

Note:

With Views I managed to get the following table:

```
Title       Age     Sex     Children
John        56      M       Lisa, Mark, Sanda
Marcela     45      F       Sam, Andy

```

which is a basic use of Views...

Actually I cannot manage to relate `Grandchild` to `Parent` entity, through `Parent > Child > Grandchild` structure.

# Answer
> 0 votes
You should be fine with a content type called person and then have an entity reference field called "children" that points at the content type person.

Then in Views create two relationships using your entity reference field. The second relationship should use the first as relationship setting.

Call the first relationship, child and the second grandchild.

Then output Content Title three times, the second should use the relationship child the second grandchild.

Under row settings set it to group by Content: Title (the first).

Set a filter that the entity reference field can't be empty.

This should list all persons that have children.

# Answer
> 0 votes
Create three content types:

1. The person
2. the child
3. the grandChild

by entity reference module set the appropriate reference from `child` and `grandChild` to the `person` content type. Now create one view from all of the content types and in filter Criteria set the content type for person DO NOT DO THIS WHEN YOU ARE CREATING NEW VIEW IN THIS PICTURE

download and install eva module, create two eva display of the view, one for the parent and one for the child and set the Relationship for each one in each view. in the end you will see that eva display of person is added in its manage display. like the picture

Visit this link , it is a very perfect tutorial of eva module and it solves your problem.

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


# Question
Title: how to change login destination to front page
I have disabled **user login** block. I use Menu link to **user/login** for login. I also used **CAPTCHA** for login page. But now when I log in to site it stays on **user/login** page not redirect to front page and gives me an error **The webpage cannot be found**. Then after refreshing page it shows **Access denied You are not authorized to access this page.** Any one has idea to set login destination after login.

# Answer
Check out the Rules module. This allows you to react on different events in your system. So it's also possible to redirect the user after he logged in successfully. I think this is the easiest way to achieve this without programming your own module.
> 2 votes

# Answer
I think the Login Destination-module is what you're looking for! Easy to configure and works perfect!
> 4 votes

# Answer
Use destination parameter in login links (if you use login form on separated page), you can set it in menu item settings (path change from `user/login` to `user/login?destination=path/to/page`).

This is better than using Rules because rule reacting on user login destroys Passwords reset process.
> 0 votes

# Answer
You can try to do it programmatically by editing your theme's template.php file.

```
function YourThemeName_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'user_login') {
        // on submit execute the YourThemeName_user_login_submit function
        $form['#submit'][] = 'YourThemeName_user_login_submit';
    }
}

function YourThemeName_user_login_submit($form, &$form_state) {
    // redirect use to the homepage (front) on login
    $form_state['redirect'] = '<front>';
}

```

Just change the *YourThemeName* bit of the two functions to your theme's name. I hope this helps.
> 0 votes

---
Tags: 6, users
---


# Question
Title: module_load_include loads file but also prints path to the file
I am using the api function `module_load_include` to include some markup in a custom module. The markup gets included and I indeed see it on my page but I am getting a side effect that the path to the include file also prints on the page along with my markup. Here is what I have that's working but with the unwanted path being printed out.

```
function mymodule_page_build(&$page) {

  if (!path_is_admin(current_path())) {
    $page['page_top']['mymodule'] = array(
      '#type' => 'markup',
      '#weight' => 25,
      '#markup' => check_plain(module_load_include('inc', 'mymodule', 'inc/markup')),
    );
  }

}

```

so the markup from my include file renders as HTML but I also see this on the page as well.

```
/sites/all/modules/custom/mymodule/inc/markup.inc

```

Just not sure what I am doing wrong, could not find any examples where this api function is used to include within the `#markup` context.

# Answer
module\_load\_include returns the file path not the html. However the reason you are seeing the html is due to module\_load\_include also doing a require\_once. An easy way to fix this would be something like the following

```
function mymodule_page_build(&$page) {
  module_load_include('inc', 'mymodule', 'inc/markup');

  if (!path_is_admin(current_path())) {
    $page['page_top']['mymodule'] = array(
      '#type' => 'markup',
      '#weight' => 25,
      '#markup' => get_my_html(),
    );
  }
}

```

So now your #markup is a function call. Just make sure your html is wrapped in the function name you want and then use your function name in the #markup key.

Also, you function that contains the markup will be something like this.

```
function get_my_html() {
  $output = '';

  $output .= '<div><p>Here is some of my HTML OR ALL of my HTML';

  return $output;
}

```

Hope this helps!
> 2 votes

# Answer
Part of the `module_load_include` code that's responsible for your issue seems to be:

```
  if (function_exists('drupal_get_path')) {
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
    if (is_file($file)) {
      require_once $file;
      return $file;
    }
  }

```

This function:

* Includes file when it is called. If that's a markup file, not PHP code, it gets rendered or causes error (depends on your luck)
* Return file's path and name - and that's what you put into your `#markup`

Consider using `file_get_contents` instead, with `drupal_get_path` to get proper module directory.
> 2 votes

# Answer
`module_load_include()` is just a wrapper around php's `require_once`, its purpose is to decipher the path required to include a file.

`require_once` doesn't *return* what's in the file, and can't be used to assign file contents to a variable; the directive literally pulls the other PHP file into the current request and executes it there and then.

`module_load_include()` returns the path that was included, which is why you're seeing that in the markup. The include is still processed, so if your .inc file contains `print '<p>markup</p>';`, it'll be printed at the top of the page (probably why you're not noticing the difference, as you're assigning to `page_top`).

To stay within the 'proper' bounds of Drupal, you should declare a theme function for your markup (see `hook_theme()`), and use that theme function in place of what you've already got for `'#markup'`. The theme system will let you specify what file the markup function is in, so you won't even need `module_load_include()` any more.
> 2 votes

# Answer
Because module\_load\_include returns the filename/path if successful.

That said, i highly doubt that's the expected way to use that function.

You should use it to include functions, hooks etc etc, not to print the content of a file.
> 1 votes

---
Tags: theming
---


title: Drush and batch

text:
# Question
Title: Drush and batch
i got an array of items. On each item, a process is executed wich manipulates data, write things to the database,...

When i execute my drush script (ex: drush mycommand) i start a batch process:

```
$batch = dms_notification_mail_sendout_batch($nid);
batch_set($batch);
$batch =& batch_get();
$batch['progressive'] = FALSE;
drush_backend_batch_process();

```

Now i was wondering why i would use a batch process here. Does it have any advantages? Because you with drush you don't have to consider PHP timeouts.

In short: If you don't have to consider with PHP timeouts, is batch process still usefull?

Thx!

# Answer
> with drush you don't have to consider PHP timeouts.

That's a false assumption. True, timeouts for PHP CLI are usually significantly larger, but they can be set and you can't assume they will not be.

If you own all machines it is supposed to ever run on, that assumption may work at the moment you write your script, but one change in php.ini may cause your scripts to suddenly fail, and that would be a nasty surprise, especially a year or two after you wrote your code, when you will no longer remember where you gave up on using batch processing.
> 4 votes

---
Tags: 7, drush, batch-operations
---


# Question
Title: Drupal PHP filter being overwritten in Lexicon Module
I've been using the PHP code text format on my Drupal website and I have been encountering a frustrating issue with the Lexicon Module. I bet the answer is dead obvious, but I haven't been able to figure it out.

After I write my PHP code in the appropriate text format (php code) in the Lexicon modules "optional introductory text field", I hit save, and everything displays as it should on the page (great!). Problem is when I go back to make changes, "Full HTML" is selected as the text format and the PHP code has been replaced with HTML. When I then choose PHP Code as the text format, I can see some of the code I wrote (not all) but it's commented out with HTML comments. I know that my PHP code has been converted and replace with HTML not only in the input field because if I hit save again, then there is no PHP script saved - just garbled HTML gets displayed on the page.

Does anyone know how to use the PHP text format and make sure their PHP code actually sticks around if the content type is revisited? The reason I need to put PHP code in this field is because I want to do a language check of the current user and display text in either English or French.

# Answer
> 0 votes
I have been able to get a fix - but not an ideal one. I moved the PHP text format to be displayed as a first priority at admin/config/content/formats. Doing this preserves the PHP code after hitting save. The reason I say it's not ideal is because now PHP code will be displayed as the default format for making new pieces of content - fine for me, but I'm sure the client will wish they could get their WYSIWYG right away.

If anyone knows a way to target the display order of text formats for just one specific module, I'm sure that would be the solution.

---
Tags: input-formats
---


# Question
Title: Get path parameter in views-view-fields--portfolio.tpl.php file
I am working on project. In project I am using view. **print $field-\>content;** parameter print image with link. I want path variable value in variable.

# Answer
borrowed from here

// field\_video\_image is the name of the image field

// using field\_get\_items() you can get the field values (respecting multilingual setup)

```
 $field_video_image = field_get_items('node', $node, 'field_video_image');

```

// after you have the values, you can get the image URL (you can use foreach here)

```
 $image_url = file_create_url($field_video_image[0]['uri']);

```
> 0 votes

---
Tags: views
---


title: How to activate empty user profile?

text:
# Question
Title: How to activate empty user profile?
I am struggling with this for a while. In my setup, every user gets to have the main profile. However if there are all fields empty, the profile is not created. Problem: It is not possible to access fields in user profile, for example using rules or php. Rules gives error - The variable or parameter is empty.

After editing any of profile fields, the profile is created and available for extracting data. So is this any sort of bug or is it somehow possible to save/enable even empty profile, to be able to work with fields?

Thank you

# Answer
> 0 votes
A quick fix is to use a bit of custom code to save the profile fields in the time of user creation as empty. Say you have a profile of type of "main". This have to be done while creating the users, find the appropriate hooks here.

Now just create the user's profile with empty values.

```
// create profile object
  $profile = profile_create(array('user' => $account, 'type' => 'main'));
  // populate profile fields
  $profile->field_firstname[LANGUAGE_NONE][0]['value'] = '';
  $profile->field_lastname[LANGUAGE_NONE][0]['value'] = '';
  $profile->field_gender[LANGUAGE_NONE][0]['value'] = '';
  // save profile
  profile2_save($profile);

```

Ref: here and here

This may solve your problem. if now then let me know.

---
Tags: 7, users
---


title: Alter taxonomy autocomplete value

text:
# Question
Title: Alter taxonomy autocomplete value
I need to alter the element value of a taxonomy autocomplete field before it is processed and can't seem to find a way of doing so.

taxonomy autocomplete fields have an element validator attached, that replaces the String value with an array of terms:

```
[$form] (array)
  [field_myautocomplete] (array)
    [und] (array)
      [#element_validate] (array)
        [0] => "taxonomy_autocomplete_validate" (string)

```

I need to alter the String before the validator `taxonomy_autocomplete_validate() // taxonomy.module:1747` passes it to `drupal_explode_tags() // common.inc:7416`. Thus I attach my own element validator via `hook_form_alter()`:

```
[$form] (array)
  [field_myautocomplete] (array)
    [und] (array)
      [#element_validate] (array)
        [0] => "MYMODULE_validate" (string)
        [1] => "taxonomy_autocomplete_validate" (string)

```

My validator is executed first and uses `form_set_value()` to update the value (exactly what `taxonomy.module:1782` does in its validator).

However, this only updates the value for `$form_state` and not `$element` which is the value used by `taxonomy_autocomplete_validate()`. Thus, the altered value is completely ignored and gets overwritten by the second validator, based on the original string.

Any suggestions beyond hacking core (make `taxonomy_autocomplete_validate` use `$form_state`) are most welcome.

# Answer
the simple solution to this issue, is to pass $element by reference to the first element validator:

```
function MYMODULE_validate(&$element, &$form_state) {
  (...)
  form_set_value($element, $new_value, $form_state);
  $element['#value'] = 'new_value';
}

```

This way, the $element\['#value'\] (used by the taxonomy\_autocomplete\_validate) can be modified and the following validators will.

The form\_set\_value() is not required, but since the form value has changed, it makes sense to update the state as well.

* *many thanks to @ciss for helping troubleshoot the issue on #drupal and suggesting the pass by reference.*
> 1 votes

---
Tags: 7, taxonomy-terms, forms
---


# Question
Title: Solution how to import contents of a .txt file into a body field?
Are any solution how we can import **content of text** (.txt) file with feeds into **body field**?

We don't have any problem with standard feeds import with CSV file and files into field file. We just need solution how we can import content of separate text file into body field.

Thanks

# Answer
I believe you can accomplish this with Feeds Tamper and a custom plugin.

Take one of the existing text plugins and clone it to a new one. Then inside the plugin callback, take the cell value (your text file name), build up a proper path, do a `file_get_contents()`, and stuff the contents into the result.

If you end up going this route, it may be a decent patch to Feeds Tamper for inclusion in the project itself.
> 1 votes

---
Tags: feeds, importing-exporting, nodes
---


# Question
Title: Different styling for each teaser display
How to style Teasers differently in different displays and pages?

I am struggling very much with Drupal's CSS classes for teasers....Is there anyway to add them separate class name for each case?

Now, if I'm styling Teasers on Taxonomy page - the same class applies to Teasers on Front Page Promoted teasers, in Teaser blocks in Views, etc....

Well, I removed "promoted" teasers and put them in Views block and assigned a class; and it's separate on Taxonomy page....

BUT - what would I do if I would wish to have a separate template on some other (taxonomy) page for...teasers?

All those Teasers are in one big pot, named **.node-teaser** and the same field names...

//Using D7 and Zen 7.x.5x.

# Answer
You can create different Entity View modes instead of the single teaser. While you can do that via a custom module in Drupal 7, there is a nice little module for that (https://www.drupal.org/project/entity\_view\_mode) too.

Create different modes like `'teaser_front'`, `'teaser_sidebar'` and theme them differently using the standard theming convention (can also be found in the module page).
> 0 votes

---
Tags: taxonomy-terms, theming, nodes
---


title: Changing position of product fields

text:
# Question
Title: Changing position of product fields
I'm learning Drupal Commerce with a Commerce Kickstart installation. I understood in part the way products are displayed, with variation types and content types.

Have made some changes like visible/hidden product fields, and change the order product fields are displayed. But didn't get how, for example, in

http://demo.commerceguys.com/ck/bags-cases/commerce-guys-laptop-bag

the bag image stay positioned left side and others product fields right side.

I'm running Drupal 7 and Commerce Kickstart 2

Edit: See that image go left side because the variation type field is *images*. I've created variation type with variation type field *image*. If set do that way, the image stay in the same column as the other fields.

# Answer
> 0 votes
If you look at the `View Source` of the webpage in your browser you will see that the CSS says `class=" ... grid-N ... "` so part of the answer is that they are using a Grid based CSS framework to layout the node content.

This type of stuff is easily achieveable with Field Group, Display Suite or Fences to layout a content type in this fashion.

---
Tags: nodes
---


# Question
Title: How to add "rel=nofollow" to ALL external links?
How to add "rel=nofollow" attribute to ALL external links....in Drupal 7?

So far I can find only with different filters and what not....

Before I was working with Joomla - I had a single plugin which was once set up - and wrapped ALL, completely all external links, wherever they would be - in Menus, articles, modules, social buttons, advertisements, etc....

I just cannot understand why would I need some Filter - the only Filtering option should be - it is an External link...

If I would know all external URL some scripts or users may add to my site - it would be great. But my experience shows - external URLs are almost always added secretly without me being aware of it; but it still should have "rel=nofollow"..

# Answer
> 1 votes
Have you tried this module : Noindex External Links

Module let's you take full control of external links indexing. Pages could also pass HTML-validation.

> **Features**
>
> Two methods of indexing control:
>
> * Wrap links with NOINDEX tag. NOINDEX tag is used to deny indexing part of page. Only Yandex and Rambler considers this tag but Google and others doesn't. There is also an attribute NOINDEX in meta-tag Robots.
> * Add attribute rel="nofollow" to links. This link's attribute has no effect on indexing. Only Google really do not follow this links but others do. Attribute is used to say to search engine that links no longer constitute a "vote" in the PageRank system.

---
Tags: navigation
---


# Question
Title: How to efficiently check if taxonomy has children
I am checking if a taxonomy term has children using taxonomy\_get\_children and I wonder if this is the most efficient way of doing it. Since the function returns all the term objects, I believe it is not very efficient.

# Answer
As arpitr says `taxonomy_get_children()` loads the child terms, so you are better of with a fork of this function.

I wanted to know whether a term a) is connected to any nodes and b) has any child terms.

```
/**
 * Helper function to check whether a term has no child terms and is not
 * connected to any node.
 *
 * @see taxonomy_get_children()
 */
function YOURMODULE_is_term_empty($tid, $vid) {
  $children = &drupal_static(__FUNCTION__, array());

  // Is term connected to node?
  if (!isset($children[$tid])) {
    // Get id's of connected nodes. Make query lighter by using no pager,
    // setting limit to 1 and sending an empty array with fields to order on.
    $node_ids = taxonomy_select_nodes($tid, FALSE, 1, array());

    if (!empty($node_ids)) {
      $children[$tid] = false;
    }
  }

  // Does term have child terms?
  if (!isset($children[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.parent', $tid);
    $query->condition('t.vid', $vid);
    $query->addTag('term_access');
    $query_result = $query->execute()->fetchCol();

    $children[$tid] = empty($query_result);
  }

  return $children[$tid];
}

```

NB: I did not make this work recursively.
> 2 votes

# Answer
Yes the reason it returns terms object is because of

Check function definition here

```
$children[$tid] = taxonomy_term_load_multiple($tids);

```

If you think copy the function to a custom module rename it and return tids instead of loading terms and return the objects.
> 0 votes

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


# Question
Title: How to use pager or term limit for taxonomy_get_tree($vid)?
How to use pager or how to limit terms, when using `taxonomy_get_tree($vid)`?

I have this code for terms generation:

```
<?php
$vid = 2;
$terms = taxonomy_get_tree($vid);
$max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;

foreach ($terms as $term) {
if ($term->depth == 0)
{
print "" .l("<b>Auto Insurance for  </b> " .$term->name,'taxonomy/term/'.$term->tid, array('attributes' => array('title' => $term->name, ), 'html' => TRUE) ). "";

}}

?>

```

But there are thousands of terms or sub terms. Some pages are then loading more then 20 seconds. I need to improve this situation.

Can you advice me please? Do you know some solution? Pager, Jquery, Ajax?

# Answer
Add a counter into your for each statement that counts the array index and terminates after X number of items. That'd fix it.
> 0 votes

---
Tags: taxonomy-terms, paging
---


title: Listing a Members of a Household

text:
# Question
Title: Listing a Members of a Household
I am building a Church Management System, I am working on the members database at the moment. I have 2 contact types, Individual & Household.

The individual has fields for personal details & contact details one of which is a field for selecting which Household they belong to. The Household has fields for the address of the household & contact details for the household.

When viewing the content for an Individual, I want to be able to click the listed Household which takes me to a page that shows me the details of the Household. e.g. Location, Contact Details & a list of the members of the household.

**Is there a way to just put this into the Household Content type as a field, or how do I do this in Views?**

I can set up the View to display the general details, but I cannot work out how to have it to show only the clicked household from the individual page and the individuals associated with the Household.

Thanks in advance.

---

Im still a bit confused I attempted pizzasynthesis suggestion and couldnt get it to work, and I have changed my thinking a bit. I am including screenshots of my config if anyone can give me ideas and/or suggestions on what to do would be awesome.

I am now thinking of using a block view that is only shown in the Household content type page and lists the Individuals of that Household(not sure it is possible to do but please tell me how best to do it).

Individual Content Type:

Test Member Edit Contact Details:

Household Content Type:

Household Edit Details:

Household Members View Block:

Individual:

Household:

I only want to be able to see the Individuals listed for that specific Household.

Any help would be greatly appreciated.

---

OK Heres where I am at now.

Block View:

Household:

Ive done what pizzasynthesis said and this is what Ive got.

# Answer
When you want to create relationships between various Content Types, the first solution many go to is Entity reference.

> Provides a field type that can reference arbitrary entities:

It creates a new field type available on all entities that can reference entities of other types. You can specify, with granularity, what types of bundles to reference (in this case you'd want to select the bundle 'Node').

Once you've created this field, you can now reference the Household directly through the node edit form. From that point forward, in Views, you can create a Relationship to the Content being referenced through the entity reference field (search entity after Adding a new relationship to find this), and then you can render any type of attached Content you wish (the Title as a link to the Node, via field settings; the entire rendered Node, etc.) through either Fields (in Views) or using Display Suite.
> 1 votes

---
Tags: views
---


title: Multi-index searches without Solr?

text:
# Question
Title: Multi-index searches without Solr?
I'm struggling to set up a decent search using Search API. By "decent" I mean a small block that performs a multi-index search (nodes and taxonomy terms). I want to free visitor from defining what they want to search through, instead I want to provide a no-brainer which does the search and displays results in categorized, paged manner.

Even though I installed the multi-index submodule, when creating a search apge, I'm still limited to select one index. Then I found kind of confirmation in the README file that currently only Solr can take advantage of that. So the question is: is it possible to create a multi-index search without Solr?

# Answer
> 1 votes
Only Solr supports that functionality. What you need is:

1. Create a server in Search API, call it, for example, "solr\_server".
2. Create two indexes, one for nodes another for taxonomies. Make sure both indexes belong to "solr\_server"
3. In views (make sure that search\_api\_views module is enabled), select 'solr\_server' from Show dropdown list.
4. Now you can add fields from every index, that belongs to "solr\_server".

Hope this helps.

# Answer
> 0 votes
Current dev version of Search API multi-index searches can make multi-index searches for any server, not only Solr.

---
Tags: search
---


# Question
Title: connecting words with a integer field in a content type
I would like to have a content type with the following behavior.

A dropdown list with words that can be selected, when a user selects on or more words these words are added to the node. But every word should have an integer value connected to it, and these values should also be stored in the node.

The problem i'm having is i don't know how to connect the word with the integer value.

This is for a site where there is a periodic maintenance to equipment. The used spare parts in the maintenance would be the words, the integer is the price of the maintenance part. Afterwords i would create a view to add the total value of the integer so the technician can easily see how much the total value is of the used spare parts.

# Answer
> 1 votes
It's quite simple, really. Create a content type for parts. Use title for part name, remove body, add integer field for price.

In your "maintenance" content type, create Entity reference to parts. That's all. Views are able to use Entity references ad views relationships, so sum of prices will be doable.

---
Tags: views, nodes
---


# Question
Title: Drupal 7 I need to style the title attribute
Here is link to what I am trying to accomplish in drupal.

```
 http://70.169.1.219/hijo/css3_test.html

```

In order to get the mouse over to work the title tags where changed to data tags and styled by the css.

In drupal, it deletes the data tags that I put in block to render the affect.

```
 http://70.184.177.183/Uptown/home

```

If I style the title block, I get the double affect. I don't think there is a way to suppress the browser rendering of the title tag.

Looking for any suggestion.

**UPDATE:**

What I ended up getting to work was that in the CKEditor, I remember you use to be able to make an editor and call it PHP which would allow anyone to introduce PHP code into the block. So I created a new CKEditor profile and to my suprise it did not really offer any config. So I gave it the minimum config that it requiried and named it PHP. I went back in and switched to that profile an opened the block and was able to type in any HTML code I so choose and now my project is back on schedule. ! screenshot of the image overlay

# Answer
> 0 votes
It doesn't work because in test file you are using 'HTML5' doctype, and on other page (in Drupal) doctype is 'XHTML + RDFa' and you can't use data attribute.

Why don't you ignore data tags and use only CSS? There is an example:

```
a {
  color: #900;
  text-decoration: none;
}

a:hover {
  color: red;
  position: relative;
}

a[title]:hover:after {
  content: attr(title);
  padding: 4px 8px;
  color: #333;
  position: absolute;
  left: 0;
  top: 100%;
  white-space: nowrap;
  z-index: 9;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -moz-box-shadow: 0px 0px 4px #222;
  -webkit-box-shadow: 0px 0px 4px #222;
  box-shadow: 0px 0px 4px #222;
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #eeeeee),color-stop(1, #cccccc));
  background-image: -webkit-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -ms-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -o-linear-gradient(top, #eeeeee, #cccccc);
}

```

You can play around with this CSS and stylize your tooltip as you like.

Also, you can use CSS to stylize title tooltip form an anchor tag, but it won't work on img tag title.

This is how provided example looks like on your site (of course you can set 'width' for tooltip and it will look exactly like yours at test page):

I hope that this is helpful.

---
Tags: theming, wysiwyg
---


# Question
Title: How to add a checkbox for contact page in drupal?
I added a checkbox in my register form in drupal name **"do you want a contact form?"**

If the user checked it then in profile page a menu for contact is shown but if it says no then in the same page **"Contact:Not Reachable "** is shown.

# Answer
> 0 votes
You can do this with Drupal core `Contact` module and with small custom code. As Drupal 7 contact module provide personal contact form and site wide contact form. See here Working with the Contact Form. **You can enable Personal contact form by default for each user and hide the `Contact Settings` under `/user/[uid]/edit` which will be enabled for all users. Then with custom code you can show and hide Contact form Based on the Checkbox you added.**

The setting shown in below screenshot will be enabled for all users by default then you will hide this setting with custom code. Because there is no configuration to show this setting on user registration form.

Steps:

1. Enable Drupal core `Contact` module.
2. Then Goto `admin/config/people/accounts` and enable `Enable the personal contact form by default for new users.` setting.
3. Give the following permission to Authenticated Users
    1. View user profiles
    2. Use users' personal contact forms
4. Add the checkbox field in User profile and enable that on registration form. Assuming the field name is `field_do_you_want_contact_form`.
5. Then in custom module with `hook_form_alter` hide the **personal contact form setting** and show/hide the contact form based on the value of checkbox.

```
//custom.module
function custom_form_alter(&$form, &$form_state, $form_id){

  // Hide the personal contact form setting under /user/[uid]/edit

  if ($form_id == 'user_profile_form') {
   $form['contact']['#access'] = FALSE;
  }

 // Show the Contact form Or custom message under contact tab based on checkbox value.
  if ($form_id == 'contact_personal_form') {
    $user = $form['recipient']['#value'];
    $wrapper = entity_metadata_wrapper('user', $user);
    $do_you_want_contact_form = $wrapper->field_do_you_want_contact_form->value();

    if (!$do_you_want_contact_form) {
    // hide all the contact form element.
        $form['name']['#access'] = FALSE;
        $form['mail']['#access'] = FALSE;
        $form['to']['#access'] = FALSE;
        $form['subject']['#access'] = FALSE;
        $form['message']['#access'] = FALSE;
        $form['copy']['#access'] = FALSE;
        $form['actions']['#access'] = FALSE;

    // Add custom message
        $form['not_rechable']['#markup'] = t('Contact: not rechable');
    }
  }
}

```

---
Tags: users, emails
---


# Question
Title: Bulk change radio button setting in admin/content using database
I am using a paywall module called TinyPass where I have to check a radio button in order to activate the paywall for a specific node. I now have a situation where I want to uncheck (or deactivate) this button for a lot of nodes that I have.

Instead of doing this for every individual node I would like to do this for a large selection of nodes (or even all of them).

Is it possible at all to change the value of these radio buttons setting in a node using the database or some other solution? This would save me a ton of time.

# Answer
> 0 votes
Have you tried bulk operations? You can select a bunch of nodes from the content overview page, and use bulk operations to change values on all of them. https://www.drupal.org/project/views\_bulk\_operations

---
Tags: 7, nodes, database
---


title: Block configuration per region

text:
# Question
Title: Block configuration per region
Anyone ever accomplished building a module that manages to have block configuration per instance?

The main issue with blocks is that each block does only one thing no matter where it shows up, you can't have the same block taking different parameters based on eg region.

# Answer
If you just need the functionality, you can try MultiBlock to see if it fits your needs:

*"Each block has a 1:1 relationship with its region, weight, visibility (and other) settings. This means that it is impossible to have blocks in multiple regions or to have blocks that have different settings on different pages. MultiBlock module solves this problem by allowing you to create multiple Block Instances of already existing blocks."*

However, you question is about being able to accomplish building a module that manages this. So, yes, I recently did something similar. I needed a homepage with blocks displaying a list of articles, each one with custom options (e.g. different categories, with / without images, etc.) and also in different regions across the site. I created one module, and then instead of having each block with a harcoded-fixed name, I generate the block's names ($delta) dynamically, like this:

```
function MY_BLOCK_block_info() {
  // Instead of having a static number of blocks, let's choose how many
  // we want, via the administration.
  $blocks_qty = variable_get('MY_BLOCK_blocks_qty');
  for($i = 1; $i <= $blocks_qty; $i++) {
    $blocks['MY_BLOCK-' . $i] = array(
      'info' => t('My block ' . $i),
      'cache' => DRUPAL_CACHE_PER_ROLE,
      'region' => BLOCK_REGION_NONE,
    );
  }
  return $blocks;
}

```

Then you will have different names for each block (MY\_BLOCK-1, MY\_BLOCK-2, etc). So you can individually configure them like this:

```
function MY_BLOCK_block_configure($delta = '') {
  $form = array();
  $parts = explode('-', $delta);
  $block_number = $parts[1];

  // Your form here...
  $form['MY_BLOCK_' . $block_number . '_title'] = array( ...

```

So, in the general Configuration page you get to choose how many blocks you want to generate. And then, in the individual block's configuration page you choose the individual block's settings.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Can't set default value with hook_field_widget_form_alter()
```
function mymodule_field_widget_form_alter(&$element, &$form_state, $context){
if ($context['field']['type'] == 'node_reference' &&
  empty($element['#default_value'])) {
$element['#default_value'] = 51113;
  }
}

```

the above does not work - I'm simply trying to set a default value through hook\_field\_widget\_form\_alter. The hook works - I can alter options and so forth, but not the default value. Any ideas?

# Answer
solved - I noticed my default values worked on node-edit forms, so I tried raising my custom module's weight, which seemed to do the trick :-)
> 0 votes

---
Tags: forms
---


# Question
Title: Drush ard is working for D6, not for D7 > bootstrap error
Noticed something strange today:

`drush ard @sites` is working in the folder /drupal6/sites/, but not in /drupal7/sites/. When i go to a specific folder, the command runs as expected (`drush ard foobar.com` in /drupal7/sites/foobar/) So, Drush is working ;-), it's working in Drupal 6 but not in 7. Can someone advice me where to look? Did some googling, but i can't find a good answer.

Drush status gives

```
Drupal version                  :  7.26
Site URI                        :  http://foobar.com
Database driver                 :  mysql
Database username               :  [username]
Database name                   :  [databasename]
Database                        :  Connected
Drupal bootstrap                :  Successful
Drupal user                     :  Anoniem
Default theme                   :  Garland
Administration theme            :  Garland
PHP executable                  :  /usr/bin/php
PHP configuration               :  /etc/php5/cli/php.ini
PHP OS                          :  Linux
Drush version                   :  6.1.0
Drush configuration             :
Drush alias files               :
Drupal root                     :  [path to root]
Site path                       :  [path to site]
File directory path             :  [path to files]
Private file directory path     :  [path to files]
Temporary file directory path   :  tmp

```

The error with `drush -d ard @sites` is:

```
Command archive-dump needs a higher bootstrap level to run
- you will need to invoke drush from a more functional Drupal
environment to run this command*

```

# Answer
This seems like a permissions' issue on your server. Make sure that the user that you are running the command as, has the appropriate permissions in the Drupal 7 directory.

An easy way to fix it is change the owner of the Drupal7 dir by using something like:

```
chown -R username:usergroup /path/to/drupal7/dir

```

or if you are working in a debian based environment you can run the command with super-user-do like:

```
sudo drush ard

```
> 0 votes

---
Tags: drush
---


# Question
Title: How to resolve the error when posting a new node with Image Field and Entity Reference?
I'm trying to create a new node using Drupal 7 + Services 3. The node type is 'activity\_photo' has an image field, and a reference to a node. This is what I'm posting to the service

```
{
 "type":"activity_photo",
 "field_node_reference":{
 "und":[{
 "target_id":"x (1273)"
 }]
 },
 "field_photo":{
 "und":[{
 "fid":"20077"
 }]
 }
}

```

The response is status 200:

```
{"nid":null,"uri":...}

```

My error log shows the following:

> Notice: Undefined index: display\_field in file\_field\_widget\_value()
>
> Warning: end() \[function.end\]: Passed variable is not an array or object in file\_managed\_file\_validate()
>
> Notice: Undefined index: nid in \_node\_resource\_create()

Any help on how to proceed?

# Answer
In the end I changed the entity reference field to select list and posted like this:

```
{
 "title":"test",
 "type":"activity_photo",
 "language":"und",
 "field_node_reference":{
 "und":[1273]
 },
 "field_photo":{"und":[{"fid":"8880"}]}
}

```

also, I found my own modules was implementing `hook_form_alter` for this form, and this had further complications to be addressed to get it to work. So any `hook_form_alter` is something to remember when looking for similar problems.
> 1 votes

---
Tags: 7, services
---


# Question
Title: Is there any 'advanced' debugging available for Views?
I know Views can show you an SQL preview, various performance statistics, and other SQL queries performed for live previews; I'm looking for something a bit closer to the bone.

The use case...

I'm writing some custom handlers for various entity/field properties (doesn't matter which types, it's all very generic stuff). I'm trying to get these handlers applied to fields in a Search API view, and the 'standard' method of implementing `hook_views_data_alter()` and changing the field handlers to the new ones isn't working. I think perhaps because `$data['commerce_product']['title']` (for example) isn't what the Search API view actually ends up using, so replacing the handler for the entry does nothing.

So I need to know what fields are using what handlers, and preferably anything else that would help me to understand why Views has chosen one and not the other.

I know I could theoretically do this by looping through the field definitions in a pre\_render hook or similar, but I'd rather have a solution in place for this any time I need it, as opposed to having to write/copy code for it every time. It feels like such a thing should exist and that I just haven't come across it yet.

Is there anything either included with, or that can be tacked on to, Views (version 3 specifically) that will help with this?

# Answer
The `admin/reports/views-plugins` show a table with every plugin used by Views, noting which views use them. And if you want to figure it out programmatically, you can check the code for that page.
> 2 votes

---
Tags: 7, views, debugging
---


# Question
Title: How to migrate Webform data from Drupal 6 to Drupal 7?
I have a Drupal 7 installation with the Webform module enabled. I recreated a Drupal 6 webform and now want to migrate data from the Drupal 6 installation to the Drupal 7 installation. Is this possible?

# Answer
You can migrate Drupal 6 webform data to 7 using the Mirgrate Webform module.

> It will migrate all nodes of the webform node type (with the default D6 fields using migrate\_d2d backend), all the configuration\* of the webform's settings, the form components, email destinations, submissions and associated submission data, in addition to any validation configuration you have (from webform\_validation module). It grabs the "last downloaded" data too, in case your users were downloading sequential batches since the last time they were on the site.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: Taxonomy hierarchy in filter block of views isotope?
How can I set the filter block to show a hierarchical taxonomy? As far as I can see there is only a flat list being built by default. How can I change this and apply the hierarchy of a taxonomy?

This is the link of the module, of course do not answer if you do not know what is views isotope Module.

# Answer
First, I'm confused about what you mean by views isotope?

But if you're asking to build a hierarchical taxonomy in view select, there's Simple hierarchical select module.

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.
> -1 votes

# Answer
Try the Views Term Hierarchy Weight Field module

> This module allows you to display, filter or sort terms according to their hierarchical order or hierarchical depth.
> -2 votes

---
Tags: 7, blocks, views
---


# Question
Title: How to make accordion menu expand smoother?
I installed accordion menu on Drupal 7. The menu work perfectly fine but it does not expand that smooth. How can I make it smoother? How do I replace JavaScript to on module?

**Note**: I tried slide and bounceslide. they are not smooth at all. The animation option say ("bounceslide" requires UI Effects Core)". Is there something I need to enable?

# Answer
> 0 votes
I would recommend updating your jQuery version using the jQuery Update module and enabling the module jQuery UI theme to have smoother effects. I think this is what you need for the UI Effects Core.

---
Tags: 7, navigation
---


title: Bootstrap sub-theme navbar buttons

text:
# Question
Title: Bootstrap sub-theme navbar buttons
It looks like when you use the default Bootstrap subtheme, it renders a navbar with the Main Menu links at the top of the page, as `<li><a>...</a></li>` elements inside of a navbar-nav block. How can one, instead of using `<li><a>...`, instead use `<li><a href="#" class="btn btn-default navbar-btn">...</a></li>`, so that my navbar has links styled as buttons instead of normal links?

I'm using the Bootstrap 7.x-3.0 subtheme. Thanks in advance!

# Answer
> 1 votes
Why do you need to add a class btn just to make it a button? Can't you just use the following css:

```
#navbar ul a {}

```

and style that to make it look like a button?

---
Tags: navigation
---


# Question
Title: Field Relation Between Content Types and Some Questions
I have two content types (Movies and Actors), both with picture and name fields.

In Movies I have a field collection with two fields: name and character. This name field is a node reference to Actors content type. I created a view block for the Movies nodes which lists the cast (a list of Actors nodes).

What I want is the actor's pictures. The picture is automatically added to the Movies nodes; I would want the same for my block.

# Answer
**(1)** The only way of *not* writing a custom script I can think of would be to use the Display Suite module. Out of the blue I would try the following.

* Create a new display mode (besides content and teaser) for the actor content type. Call it something like "just image" or "photo only". It should be set to only display the image field.
* Create a new display mode for the movie content type, maybe called "actors". It should only display the field collection and the name (reference field) should use the previously created display mode "just image".
* Create a (views) block that shows the original node (Contextual Filter: Nid, default parameter in URL). Display type of that view should be Node and use the "actors" display mode.

What I would expect is to get a block that shows the actors' photos along with their characters' names.

**(2)** An easier way (if you are able to program Drupal modules) would be to write custom scripts. Also, this would allow you to fine-tune your output. I would create a custom module which creates the block you want by using the \_block hooks to define the available blocks and their contents.

**(3)** Another way of accomplishing what you want would be to restructure your website's architecture. This might not be suitable for you if you already have a lot of entries. Instead of field collections you would then use an additional content type (character). Character would then have relationships with both movies and actors.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: How to get entity from transliterated argument in URL?
I have panel, where I have argument: taxonomy term name

term names are transliterated (like "My custom taxonomy title" into my-custom-taxonomy-title)

path is like this: my-custom-list-of-nodes/my-custom-taxonomy-title

How can I get in PHP code (in some hook) original taxonomy term name from argument "my-custom-taxonomy-title"?

Original string can have diacritics, uppercase, spaces. How can I detect Term ID from transliterated argument "my-custom-taxonomy-title" ?

# Answer
## Short answer:

You can't do what you are asking.

**Why is that?**
While transliterating is a pretty simple procedure that follows a very specific number of steps:
\- Replace every character with the corresponding-transliterated version
\- If the resulting URL exists, add a -{Insert Number here} at the end until you find a URL that does not exist

reversing the transliteration is not that easy. Think of the extreme case where 5 different nodes/terms/entities have the exact same title. Their transliterated paths would be: /common-title /common-title-0 /common-title-1 /common-title-2 /common-title-3.

In this case, how do you know which transliterated title corresponds to each entity? Creation date (first one created gets the smallest index)? Besides the fact that this is extremely complex to predict, there may still be problems if a path was updated manually or one of the entities was deleted and a new one was added.

---

## Long answer:

Even though what you are asking is not feasible, you can use a number of different approaches in order to solve the specific problem that you are facing.

**Possible Solution 1:**
You can use the current\_path function. This will return the **unaliased** path of the currently viewed Drupal page. I am not exactly sure how the panels' pathing system works, but there is a very good chance that you will get something with the term id in it (that's what you need in your hook, right?).

In order to investigate this further in your code, assuming you have devel installed, you can do something like:

```
dpm(current_path());

```

**Possible Solution 2:**
If the above-mentioned solution does not work, you will need to do some more digging in order to figure out which variables are available. Something that can get you started is a simple:

```
dpm(get_defined_vars());

```

Depending on the results that you will get, you may be able to find the term name somewhere in the defined variables and use taxonomy\_get\_term\_by\_name() function to retrieve the tid.
> 0 votes

---
Tags: 7, transliteration
---


title: Get IP of the Author only

text:
# Question
Title: Get IP of the Author only
I use this solution for now which works great: It's with Computed fields, and I use this line: $`entity_field[0]['value'] = ip_address();`

So basically what it does, it's when a user submits a new node, it also attach his IP address to the node, which is great.

The problem is that if another user decides to edit the node, the IP field is being updated with the editors IP. Which is bad.

The IP should be printed only of the author of the node. And no matter how many other IPs edits the node, those should be ignored.

So, I was thinking maybe there was possible to do this by editing the PHP line or am I looking in wrong direction?

# Answer
> 1 votes
Another option is to use Rules on new content creation then run the php code.

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

EDIT:

* Enable the module 'PHP Filter'
* In Rules, use the 'After Saving New Content' React on Type - this will trigger each time content is published for the first time
* Optionally, add a condition Restrict by Type, choose the content type in which you want this to appear
* Add a new action 'PHP: Execute custom php code' with your own code

# Answer
> 0 votes
Use the hook\_node\_insert, it respond to creation of a new node, not when you edit it.

```
function YOURMODULENAME_node_insert($node) {
  if ($node->type == 'nodetype') {
    // Action
  }
}

```

Greetings.

---
Tags: 7, entities
---


# Question
Title: Rules: Do action on the field of referenced node
I have an "Authors" Content-type, that users can add to their "Article" node while adding a new content as Co-Authors.

Note that it's a seperate content-type not users.

in "Authors" content-type I have an "Email field" which contains the email of the co-author.

What I want to do is using rules, send an email to the `referenced node's email field`

I juggled around in rules but couldn't really make it work, I'd really appreciate a step-by-step process of rules to achieve this, thanks.

# Answer
> 1 votes
If your rule is set to **React on event**: `Before saving content` or `After saving new content` of type `Article`, then do this:

Add condition: **Entity has field**

**ENTITY**: `node:field-your_reference_field`

**FIELD**: `field_email`

This makes the referenced node's email field available in to Actions. So then you can

Add action: **Send email**

**To**: `node:field-your_reference_field:field_email`

This should get you where you need to be.

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


title: Wordpress comment form in Drupal?

text:
# Question
Title: Wordpress comment form in Drupal?
Wordpress comment form contains a text field where visitors can enter a link to their website. Is there any module ( or simple way )to achieve the same thing in Drupal ?

What I'm really looking for is a solution that:

* adds a new field to the comment form that needs to be validated as a link
* when the comment is displayed , the username needs to link to the website entered in the form , not to the user profile as it does by default.

# Answer
I would use the URL field module to create the website field on the comment entity. You can then use function theme\_comment\_submitted in your theme's preprocess functions to override the `$submitted` variable that is used in `comment.tpl.php` from the Drupal root folder `/modules/comment/` (you can also copy this file into your theme's templates folder for further customization of the comment display).

The idea would be to alter `function theme_comment_submitted` (shown below) to include the username hyperlinked with an `href` provided by your URL field.

```
function theme_comment_submitted($comment) {
  return t('Submitted by !username on @datetime.', array(
    '!username' => theme('username', $comment),
    '@datetime' => format_date($comment->timestamp),
  ));
}

```
> 0 votes

# Answer
This is indeed very simple. You can add fields to the comment entity. Have a look at these explanations of how o achieve this:

http://kps3.com/thots/adding-new-fields-to-comments-in-drupal-7

https://www.ostraining.com/blog/drupal/entities/
> 0 votes

---
Tags: comments
---