# Question
Title: Heartbeat module comments collapsed by default
I set my user's profiles with Heartbeat. At first moment they just look fine but when I open the web to the private beta I realized that when users started to comment nodes, the heartbeat logs of their profiles began to show too much information, they started to look overcrowded. So I have been asking to implement an option to the module core to show the log comments collapsed by default but none has replied.

There is another thread (Display a comment link instead of all the textareas.) on Drupal forums referring to something similar but I don't know how to use that information because I'm a rookie in Drupal hooking & custom modules writing.

Hint: maybe using this code (default option when clicking on Heartbeat comment count)

```
javascript:Drupal.heartbeat.comments.toggleComments(this, COMMENT_NUMBER); return false;

```

# Answer
In this case you can use Collapsible Comment module. This module will help you to collapse the threads of the comments.

Now if you want to collapse entire comment region in collapsible form then you can do this using javascript.

Create a js file and add below javascript in a js file and add it to your theme or module.

```
(function($) {$(function() {
      var $comments = $('#comments');
      if (!$comments.size()) return;
      var count = $comments.find('.comment').size();
      // if (!count) return; // Do nothing when there is no comment.
      var label = Drupal.formatPlural(count, '1 comment', '@count comments');
      var $legend = $(document.createElement('legend')).html('<span class="fieldset-legend">' + label + '</span>');
      var fsetclass = 'comments collapsible' + (location.href.search(/#(comment|new)/) == -1 ? ' collapsed' : '');
      var $fset = $(document.createElement('fieldset')).addClass(fsetclass);
      var $fsetwrap = $(document.createElement('div')).addClass('fieldset-wrapper');
      $fset.insertBefore($comments).append($legend).append($fsetwrap);
      $fsetwrap.append($comments);
      var attach = function() {Drupal.behaviors.collapse.attach($fset.parent(), Drupal.settings);};
      Drupal.behaviors.collapse ? attach() : $.getScript(Drupal.settings.basePath + 'misc/collapse.js', attach);
    });})(jQuery);

```

The above code will help you to collapse comments. Enjoy!!! :-)
> 0 votes

---
Tags: 7, hooks
---


title: My Groups OG Setup

text:
# Question
Title: My Groups OG Setup
I am not able to list My Groups for the authenticated users. so when they login and click on My Groups, they should see only those groups created by them. I am using D7 with OG and VIEW to create the My Group page.

# Answer
> 0 votes
Please check the url **yoursite.com/user-groups**.

This URL is created by View and it will return the group of the user who is logged in.

The reason that you are not getting is probably you are misssing panel and page manager module. Enable them and try again.

---
Tags: 7, organic-groups
---


# Question
Title: Cannot Logon to Drupal ("The website encountered an error while retrieving...")
I am trying to get a new Drupal site running on Ubuntu 12.10. I believe I have what is either an Apache or permissions error. I can get to the main logon page for the site, but after entering my credentials, I get the following error.

```
The website encountered an error while retrieving http://localhost/node?destination=node. It may be down for maintenance or configured incorrectly.

```

I set my permissions using the following script, and my apache setup is below that. Can anyone tell me where else to look?

```
!/bin/bash

FILES="/var/www/localdrupal/cms/sites/default/files"
SETTINGS="/var/www/localdrupal/cms/sites/default/settings.php"
SITES="/var/www/localdrupal/cms/sites"
DEFAULT="/var/www/localdrupal/cms/sites/default"
THEMES="/var/www/localdrupal/cms/sites/all/themes"
MODULES="/var/www/localdrupal/cms/sites/all/modules"
DSETTINGS="/var/www/localdrupal/cms/sites/default/default.settings.php"

# Paths for binary files
TAR="/bin/tar"
RM="/bin/rm"
CHOWN="/bin/chown"
FIND="/bin/find"
CHMOD="/bin/chmod"

# Change permissions to be secure

$CHOWN -R www-data:www-data ${SITES}
$CHMOD 775 ${SITES}
$CHMOD 775 ${FILES}
$CHMOD g+w -R ${FILES}
$CHMOD 440 ${SETTINGS}
$CHMOD 440 ${DSETTINGS}
$CHMOD 755 ${DEFAULT}
$CHMOD 755 -R ${THEMES}
$CHMOD 755 -R ${MODULES}

```

Apache:

```
    DocumentRoot /var/www/localdrupal/cms
    <Directory />
            Options FollowSymLinks
            AllowOverride  None
    </Directory>

    <Directory /var/www/localdrupal/cms/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

```

# Answer
Check your setup.php, probably you should set the baseurl variable there, since your drupal root is not the default /var/www
> 3 votes

---
Tags: authentication-authorization
---


# Question
Title: Way to prevent drush from eating custom profiles when updating core?
I use drush make with a stub .make file to download a custom profile via git.

that profile has all of the modules I want all of my sites to start out with.

If I then go into that site, and run "drush up drupal", it will update core, and remove my custom profile.

This is not good, since all of the modules I downloaded with my install profile's make file get stuck into the profiles/myprofile/modules folder. This basically removes all of my installed contrib modules, and drush doesn't give me a way to put them any where else, so basically, I can't update core with drush.

# Answer
Consider to use Aegir. It supports this usecase.
> -1 votes

---
Tags: drush
---


title: Hide Fields Based on Role

text:
# Question
Title: Hide Fields Based on Role
> **Possible Duplicate:**
> Is it possible to assign permission to fields?

I have a contact type called contact form, and I want to alter the fields that are visible when adding that contact type, based on the user role. I want admin to be able to change the value of fields such as 'status', 'date completed' etc but I don't want these to be visible to the anonymous role.

# Answer
> 4 votes
Sounds like the function of Field Permissions module.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

---
Tags: entities, users, nodes
---


title: Drupal address showing subfolder aswell

text:
# Question
Title: Drupal address showing subfolder aswell
I am having my site on www.abc.com which is hosted with hostgator. It is installed in public\_html, and I installed Drupal in a sub-folder.

Whenever I go to my site, the address bar of the browser shows www.abc.com/techspot, when I would like it to show just www.abc.com.

How can I achieve this?

# Answer
> 0 votes
In your htaccess file you can set the rewrite rule:

```
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /site

```

---
Tags: uri, multi-sites
---


# Question
Title: Form's submit and validate functions not being called
I can't submit any form. If I press *Submit* button on any form, the form page gets reloaded and nothing happens and no message is shown.

In the submit and validate functions of a form, I added an `exit()` command and found that they are not being called at all.

I cleared the cache and problem still exists. Any suggestion?

# Answer
> 0 votes
The problem was `post_max_size` in *.htaccess* file. I was using `MB` instead of `M` after the value.

---
Tags: 7, forms
---


# Question
Title: Updating the block region/pages settings for a NEW views block during an implementation of hook_update_N
I have a feature module which provides a view which has a block component.

To keep things simple, the module I'm writing a hook\_update for is 'mymodule' the feature which implements the view is 'myfeature', the view which contains the block is 'myview' and the block is just block\_1 of that view.

The block needs to be visible in the region sidebar\_second The block needs to be visible only on pages which match users/\* The following is my hook\_update simplified:

```
function mymodule_update_7001(){
 features_install_modules(array('myfeature'));
 drupal_flush_all_caches();
  //Change block settings
  db_update('block')
  ->fields(array(
      'pages' => "users/*",
      'visibility' => 1,
  ))
  ->condition('module', 'views')
  ->condition('delta', 'myview-block_1')
  ->execute();

  db_update('block')
  ->fields(array(
      'region' => 'sidebar_second',
      'status' => 1,
  ))
  ->condition('module', 'views')
  ->condition('delta', 'myview-block_1')
  ->condition('theme', 'mytheme')
  ->execute();
}

```

Unfortunately it doesn't work, and this is largely because at the point after running drupal\_flush\_all\_caches(); the block doesn't exist in the table yet.

drupal\_flush\_all\_caches() should run block\_flush\_caches() which should run \_block\_rehash() against each theme, expected behaviour is that this would cause the writerecord to occur putting the new views block in the 'blocks' table. (if i ran 9 flush all caches followed by a block flush cache and a rehash this would still not work)

I have experimented with varying combinations of these cache flushes to no avail, i have also tried giving 'mymodule' a higher weight.

Bizaarely using the following drush command directly after the update:

```
drush php-eval "_block_rehash('mytheme');"

```

causes the block to exist in the database. I have tried using this exact command in the hook\_update\_n and that did not work.

any advice would be appreciated.

# Answer
> 0 votes
This can be resolved by using db\_merge instead of db\_update, which effectively updates if it exists else creates the entry.

An alternative line of enquiry would be to look at using one of the new hooks available in the features module. In theory 'hook\_post\_features\_rebuild()' would reactively move the block after the features been rebuilt, and therefore the blocks been created.

http://drupal.org/node/1782492

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


title: Which Drupal Version Is Best

text:
# Question
Title: Which Drupal Version Is Best
I have a new site that I'm starting to build but I need help deciding what makes Drupal 7 better than Drupal 6.

# Answer
This should answer your question well enough: Choosing a Drupal version

> In deciding between Drupal 6 and Drupal 7, several factors should be taken into consideration. Drupal 7 is newer, will be supported longer, and contains more features and enhancements than Drupal 6; therefore, if all else is equal, use Drupal 7. However, the releases of contributed modules, themes, translations, and installation profiles compatible with each major Drupal release series sometimes lag behind Drupal itself, so if the functionality you need is not yet available for Drupal 7, this may affect your decision.

Drupal 6 is getting closer and closer to being completely unsupported (there are only two supported versions at any one time, and Drupal 8 *should* be out within 12 months - so 6 will become unsupported), and there are very few modules being made available for it.

Personally, I don't know of anybody who would want to start building a website/application in Drupal 6 over Drupal 7.

***tl;dr***

Everything makes D7 better than D6
> 2 votes

---
Tags: 7
---


title: Save a node via javascript

text:
# Question
Title: Save a node via javascript
I want to be able to save a node when certain events happen in the browser. I.E the user changes tab. Is it possible to save a node in drupal using javascript?

Is there a javascript api tfor drupal? If not are there any contrib modules that add this? If it is custom code is needed is there an web service that can be called or would I need to role my own?

# Answer
In order to achieve this on Drupal 7, you need to develop a custom module that does the following:

Register a menu hook that will act as the endpoint where your javascript will send the data for the node to be created.

Create a function that will be the callback of the hook and handle the actual creating and saving of the node. It can be something like this as mentioned in the answer above:

```
$data = json_decode($_REQUEST['title']);
$node = new stdClass;
$node->type = 'article';
$node->title = check_plain($data->title);
node_save($node);
echo json_encode(array('Status' => 'OK'));
drupal_exit()

```

Notice drupal\_exit() is needed otherwise you get the whole page rendering. In order to set other properties for example the body, you need to know the structure, it is usually something like

$node-\>fieldName\[language\]\[delta\]\['value'\] eg, $node-\>body\['und'\]\[0\]\['value'\]

That's all it needs on the php side, now on the javascript side you will be needing to create an array containing the values for the node and submit it via ajax. Using jQuery it can be done like this:

```
jQuery.ajax(
{
    url:  Drupal.settings.basePath + queryPath,
type: 'POST',
dataType: 'json',
data:  {'data': JSON.stringify(queryParameters)},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
    console.log(JSON.stringify(XMLHttpRequest));
    console.log(JSON.stringify(textStatus));
        console.log(JSON.stringify(errorThrown));
},
success: function (data)
{
    console.log(data);
    }
});

```

Data can contain anything returned from php...

Have fun

Update:

A more general and concrete solution is available through the use of the Services module that allows you to define a REST api over the various content types you create. This way you don't need to write any custom code on the php side,
> 6 votes

---
Tags: 7, javascript, nodes
---


# Question
Title: Creating a profile sub page and filling with Webform data
I'm looking to add an extra sub page to a user's profile that will contain the user's answers to a webform that they have previously submitted. I'm having trouble figuring out how to add this subpage.

Any direction appreciated.

# Answer
> 1 votes
If i understand well your question, what you want is a view that show the answer to a webform.

So you can create a view filtred by user, display it in a block and invoke it in the template of your profil page.

---
Tags: 7, users
---


# Question
Title: Drupal 7.16 started sending duplicate account activation emails
Could anyone help me debug why Drupal is sending two account activation emails when a new user account is activated?

I also see from the rules logs, that certain workflow rules are also sending two emails for each one.

I have looked in /admin/reports/dblog but there are no errors or warnings there.

Any idea where I can start looking?

thanks, Darren

# Answer
OK, not sure what was happening there! I changed the settings on admin/config/people/accounts and removed the need to confirm email address ("Require e-mail verification when a visitor creates an account.".

This didn't work - still duplicates being sent out when activated.

Then I de-selected "Notify user when account is activated." (Under "Account Activation" tab) and this stopped them being sent.

Then I re-enabled "Notify user when account is activated." AND modified the email template.

Now it's only sending the one email again!

For some reason, this also fixed the rule emails that were getting duplicated... Beezaaar!

Any ideas?
> 1 votes

---
Tags: 7, rules, emails
---


# Question
Title: What will happen at worst if I change the "Number of values" of CCK field
I have a CCK text field and set "Number of values" to a certain number. Now I want to change it to "Unlimited".

It says

```
Warning! Changing this setting after data has been created could result in the loss of data!

```

What will happen at worst if I change this? The values of already existing nodes might be really gone as it says? If yes, there is no way to change this to "Unlimited" if I already have some existing nodes?

# Answer
> 3 votes
Changing it to unlimited isn't going to cause an issue. It's a standard warning message for any change on that setting for a field.

So really the only time you would be concerned is if you took an already unlimited field and set it to a static value, which could potentially remove values if the delta of that field on a node exceeded the static value.

Edit: But always be sure to take a backup before doing those kinds of changes, and always do this on a development environment.

# Answer
> 2 votes
I can't think of any reason why you'd suffer any data loss if you're *increasing* the field's cardinality (I used to do it all the time in D6 and to the best of my recollection nothing ever went wrong).

The problems would start happening if you *decreased* the cardinality. For example if if it was previously at 3, and you decreased it 2, any nodes that had a 3rd value for that field would lose that data.

---
Tags: 6, entities
---


# Question
Title: How can I increase the 128 character limit of a menu path?
I know there are patches to core, but they were never backported to Drupal 6 from what I can tell.

How can this be overridden in a theme?

# Answer
> 0 votes
You should be able to fix this by using `hook_form_alter()` and override the default `maxlength` for the input field, and then change the field in the db to `varchar(255)` if it isn't already.

Another option would be to use a token value for the path and change the value on output using `theme_menu_item()`.

Perhaps the best option after all would be the Custom Tokens module. I haven't tried it so I can't say if it works.

The downside with tokens is that you would have to make one token per URL, or possibly use a part of the URL if it's generally the same.

---
Tags: 6, navigation
---


# Question
Title: How to use "user logged in" as an access argument for a MENU_CALLBACK?
I would like to require that users be logged in to access a particular MENU\_CALLBACK.

The following works, but only for the admin account. Regular users are still denied access:

```
'access arguments' => array('user_is_logged_in')

```

There must be an access argument that just checks for authenticated users?

# Answer
> 33 votes
`access arguments` is for the arguments that will be passed to the callback function...you need to use `access callback` instead:

```
'access callback' => 'user_is_logged_in'

```

Since `user_is_logged_in()` doesn't take any arguments, you can safely remove `access arguments` for your menu item.

Your current code works for the admin account only because the default `access callback` is `user_access()`, which bypasses the access check for user 1.

---
Tags: users, routes
---


# Question
Title: nice menus - how can I keep all sub-menu expanded in my <front> page?
On my front page, I want to have my sub-menus expanded and have them to act as it should on other pages.

I'm using the Nice menus module.

How can I achieve it?

# Answer
> 2 votes
Use Menu Block. Duplicate the menu with the children already expanded and then style it as the other one.

---
Tags: routes, javascript
---


# Question
Title: Which Drupal module support spatial filtering with apache solr module
Which Drupal module support spatial filtering with apache solr module. like either Location,geofield,geolocation,getlocation or any other.

# Answer
Have a look to the Search API Location module. There is also demo site.

> The Search API spatial module (7.x-2.x branch) adds the possibility of location based searching to the Search API module.
> Currently only Apache Solr is supported as server.
> You can find a demo on http://spatial.mollux.be.
> 1 votes

---
Tags: 7
---


# Question
Title: How to display contact form module in a block using drupal 7
> **Possible Duplicate:**
> Put Site-Wide Contact Form in a Block

I want to display the contact form in a sidebar of the website. Is it possible? Please help me.

# Answer
> 3 votes
Check this answer which recommends to use Form Block module.
This could also be useful.

# Answer
> -3 votes
I think this feature is not included in the contact module of Drupal. It means it is still possible, but you have to add code to the module, where you implement the contact form in a Drupal block.

---
Tags: emails
---


# Question
Title: What happened to the "menupath" token in the URL aliases for Drupal 7?
Again, am I blind? If my "Widgets" page is under "Products," I want the auto-alias to be /products/widgets. I can't seem to find that in Drupal 7.

# Answer
http://drupal.org/node/807032

```
[node:menu-link:parent:url:alias]/[node:menu-link]

```
> 2 votes

# Answer
This works for me: `[node:menu-link:parent]/[node:title]`.
> 1 votes

# Answer
If you install the Token module for Drupal 7, you will notice that the Pathauto module shows more tokens, some of which are for the menu link associated to the node, for example.

When the code to handle tokens have been moved to Drupal 7 core code, not all the code has been moved; the theme function that shows the list of all the available tokens is still part of the Token module, and some of the tokens are only available after installing it.
> 0 votes

---
Tags: uri, tokens
---


# Question
Title: Undefined index: und in mytheme_preprocess_page()
I created a custom image field for a banner in one of my content type. I wish to display this banner in the page.tpl.php instead of node template. Here's my code in template.php:

```
function mytheme_preprocess_page(&$vars, $hook) {

     $vars['banner'] = '';
    if (!empty($vars['node'])) {
        $node = $vars['node'];

        if (isset($node->field_banner)) {
                // Render the image as a variable in the page template
           $vars['banner'] = theme_image_style(array('path' => $node->field_banner['und']['0']['uri'], 'style_name' => 'mybannerstyle', 'height' => '200', 'width' => '700'));
        }
    }

```

.....

and in the page.tpl.php, i coded:

```
    <?php if(!empty($banner)){print $banner;} ?>

```

. This work perfectly in the node that has banner uploaded. But for nodes which have no banner, the following undefined messaged turn up:

**Notice: Undefined index: und in mytheme\_preprocess\_page() (line 33 of /home/xxxxx/themes/mytheme/template.php).**

I wonder how to solve this. Please advise. Thanks.

# Answer
> 1 votes
I think you should use `$node->language` over using 'und' when accessing your array. Second, to remove the warning you could simply do:

```
if (isset($node->field_banner, $node->field_banner[$node->language])) {
  $vars['banner'] = theme_image_style(array(
     'path' => $node->field_banner[$node->language]['0']['uri'],
     'style_name' => 'mybannerstyle',
     'height' => '200',
     'width' => '700'
   ));
}

```

To access all images in your field you would do something like this:

```
foreach ($node->field_banner[$node->language] as $key => $value):
  $vars['banner']['images'][] = array(
     'path' => $node->field_banner[$node->language][$key]['uri'],
  );
endforeach;

```

# Answer
> 2 votes
For a field, `$entity->$field_name['und']` is not always defined. Instead of the code you are using, you should use the following code.

```
if (isset($node->field_banner)) {
  // Render the image as a variable in the page template.
  $field = field_get_items('node', $node, 'field_banner');
  $vars['banner'] = theme_image_style(array('path' => $field[0]['uri'], 'style_name' => 'mybannerstyle', 'height' => '200', 'width' => '700'));
}

```

I would also consider using field\_view\_value(), instead of fields\_get\_items(), but the first function doesn't allow to customize the output, if not through the `$display` parameter. (See field\_view\_field() for a description of that parameter.)

`field_get_items()` and `field_view_value()` get the language ID from field\_get\_name(), which returns the correct value for the language to use for the field.

# Answer
> 2 votes
Hi Just change the line

```
'path' => $node->field_banner[$node->language]['0']['uri'],

```

to

```
'path' => $node->field_banner[LANGUAGE_NONE]['0']['uri'],

```

$node-\>language = LANGUAGE\_NONE; is default in D7.

never use 'und' directly use LANGUAGE\_NONE constant at place of und.

---
Tags: theming
---


# Question
Title: How to delete the bulk of custom data when the associated user is deleted
I'm one of the maintainer of Statuses(Social Microblog), As of now we are storing the status messages and comments to it in custom tables. We are also having hooks which needs to be invoked for the deletion of every status message,

Since this just a status update, we will have bunch of messages(even 2k+ also possible) associated with one user.

So when the user is deleted, we need to delete all the status messages and comments associated to that user. The problem I could see that I need to perform these deletions in hook\_user\_delete, so if I have more number of deletions it may give timeout error and also I need to consider performance here.

If I directly loop through the status messages to delete one by one then it will be a hectic process, because when a status message is deleted it needs to invoke several hooks.

I want a guidance on handling this situation.

# Answer
One approach would be to add a `deleted` column to your messages table, and mark the messages for deletion when a user is deleted, e.g.

```
function statuses_user_delete($account) {
  db_update('statuses_message')
    ->fields(array('deleted' => 1))
    ->condition('uid', $account->uid)
    ->execute();
}

```

Forgive the obviously incorrect table name, I'm not familiar with the statuses module.

Then in a cron hook, you could grab x number of the messages marked for deletion, and process them:

```
function statuses_cron() {
  $max = 50;
  $sql = 'SELECT message_id FROM {statuses_message} WHERE deleted = 1';
  $message_ids = db_query_range($sql, 0, $max)->fetchCol();

  statuses_delete_message_multiple($message_ids);
}

```

I'm making some assumptions about how things are set up in your module, but hopefully the principal is obvious enough. You could one step further and implement `hook_cron_queue_info()`, which will give you a finer grained control over the amount of time your worker can run for. I think some profiling with both methods would probably be appropriate to determine which which is better.

This is along the same lines as the logic the core field module uses to purge deleted data on the cron run, so I think it's safe to assume the principal at least is well tested...it's just whether this method will work for your use case.

I guess the only sticking point here would be the amount of code you need to change in the rest of the module to respect the new `deleted` column (i.e. not showing deleted messages to users). Again I can't really comment on that as I'm not familiar with the module, but if you take a methodical approach to implementing changes I can't imagine it being that much of a problem.
> 2 votes

# Answer
I think you have two options/aproaches that can be combined:

1. Use Cron. When a user is deleted, add an entry in a custom table with de deleted user or mark each deletes statuses in its own table with a new 'mark to be deleted' column. Then, when Cron is run, process N (or all) items (invoking the status deleted hook).
2. Group deleted statuses. statuses\_delete\_status could invoke statuses\_delete for just one status or for a bunch of them. The modules implementing your hook will be responsible of process the deleted statuses in a short period of time to avoid timeouts. Some implementing modules may prefer to haver all deleted statuses in one call if they don't need to process them one by one.
> 1 votes

---
Tags: 7, users
---


title: Display specific profile type in Views

text:
# Question
Title: Display specific profile type in Views
Hi I'm trying to setup a View with the following criteria.

Select style: 1) Yellow 2) Green 3) Blue

I created an exposed filter for that. Easy so far.

I have created a Color content type that contains each color style in a different View Mode. Let's say the user picks Yellow. Now i want all the Color nodes to be displayed with only the Yellow View Mode.

It's probably a simple solution but i can't figure it out. Thanks in advance!

# Answer
> 1 votes
1. Add a filter on the relevant "style-field".
2. Change it's settings to be "Exposed"

And that's all you need. See Taming the beast: Learn Views with NodeOne for a good intro to the Views module.

---
Tags: views
---


# Question
Title: Is there a way to set the active menu's text as page title?
I would like to set the active menu's text as the page title in drupal7. I tried using the page title module and found no replacement patterns to set the active menu as the page title. Any help is widely appreciated.

Thanks

# Answer
I found the answer with this link http://sivaji.drupalgardens.com/how-set-custom-page-title-drupal-7.

There exists no way to dynamically set the active menu as the page title, but with the Classes\_array from the vars, we can check the page's id and then set the page title as per our need.

In my case I used a if check to check the page id (Page-contact's page title to Contact) and so. It worked for me though, but still found no way to dynamically set the title from the active menu !
> 0 votes

---
Tags: 7
---


title: Where does $rows come from in views?

text:
# Question
Title: Where does $rows come from in views?
Let's say I have a simplest "unformated list" view.

I see that "views-view-unformatted.tpl.php" is outputting $rows in a loop.

When I open my view page on a browser, I see that the following codes are generated by $row.

```
<span class="field-content"><a href="/node/264">test1</a></span>

```

What template can I edit to remove anchor part?

# Answer
Non need to edit template in this case. Just edit title field and uncheck "Link this field to the original piece of content" option.
> 0 votes

---
Tags: views
---


# Question
Title: Error on module admin configuration page
I cannot find any documentation or similar problem with mine.

Whenever I am trying to go to the configuration page of some installed module like "Pagetitle" module and Add menu links module.

The page is at unformatted layout, doesnt seem to load the css or javascript, and some links in the configuration page are not showing

Here is the screen shot of the configuration page of page title module (I am logged in as administrator).

I dont know whats causing this, I have disabled modules Im not using and updated the core files as well as all installed modules I can not configure the module.

Please any idea to solve this?

# Answer
> 3 votes
This is because the page rendering stopped when an error occurred. By default, Drupal does not display such kind of errors.

Enable your error reporting by temporarily editing your index.php file (normally located in your root directory) directly after the first opening PHP tag to add the following:

```
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

After you edited the file, run your site and see what error came out.

WSOD is not directly related to this question, but it may be useful for you to tackle down your problem. It will help you to find out invisible errors.

---
Tags: 7
---


# Question
Title: CCK field related to non-drupal table columns
I need to define a CCK field that contains data from a non-Drupal table called Customers; i would like the field to show the list of Customers and saving the id\_customer inside the node. Is there a way to do it without having to create Customers as node?

# Answer
Well, one of the possible ways to do that is to create a cck field of type integer and use "select list" as a widget. And then in your implementation of hook\_form\_alter you need to extract data from Customers table and populate the select with this data.

You might find the following piece of code useful:

```
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_CONTENT_TYPE_NAME_node_form') {
    $sql = 'SELECT id, name FROM Customers';
    $result = db_query($sql);
    $options = '';
    while($row = db_fetch_array($result)) {
      $options .= $row['id'] . "|" . $row['name'] . "\n";
    }
    $form['#field_info']['field_YOUR_FIELD_NAME']['allowed_values'] = $options;
  }
}

```
> 1 votes

---
Tags: 6, entities
---


# Question
Title: How to add additional class to an imagecache preset?
Tried:

```
function ruh_imagecache_formatter_default($element) {
  // Inside a view $element may contain NULL data. In that case, just return.
  if (empty($element['#item']['fid'])) {
    return '';
  }

  // Extract the preset name from the formatter name.
  $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  $style = 'linked';
  $style = 'default';

  $item = $element['#item'];
  $item['data']['alt'] = isset($item['data']['alt']) ? $item['data']['alt'] : '';
  $item['data']['title'] = isset($item['data']['title']) ? $item['data']['title'] : NULL;

  $class = "imagecache beautytips imagecache-$presetname imagecache-$style imagecache-{$element['#formatter']}";
  return theme('imagecache', $presetname, $item['filepath'], $item['data']['alt'], $item['data']['title'], array('class' => $class));
}

function ruh_imagecache_formatter_imagelink($element) {
  // Inside a view $element may contain NULL data. In that case, just return.
  if (empty($element['#item']['fid'])) {
    return '';
  }

  // Extract the preset name from the formatter name.
  $presetname = substr($element['#formatter'], 0, strrpos($element['#formatter'], '_'));
  $style = 'imagelink';

  $item = $element['#item'];
  $item['data']['alt'] = isset($item['data']['alt']) ? $item['data']['alt'] : '';
  $item['data']['title'] = isset($item['data']['title']) ? $item['data']['title'] : NULL;

  $imagetag = theme('imagecache', $presetname, $item['filepath'], $item['data']['alt'], $item['data']['title']);
  $path = file_create_url($item['filepath']);
  $class = "imagecache beautytips imagecache-$presetname imagecache-$style imagecache-{$element['#formatter']}";
  return l($imagetag, $path, array('attributes' => array('class' => $class), 'html' => TRUE));
}

```

I've added class - beautytips - but its not appearing on when im firebugging and imagecache image.

# Answer
> 2 votes
Add it as an array,

```
$class = array('imagecache', 'beautytips', 'class3');

```

---
Tags: media
---


# Question
Title: How to add a user-friendly option to link to nodes from body text or text-field?
I'm looking for an option or module that provides the possibility to link to other internal nodes avoiding the usage of full html in a text field. Users should be able to highlight a term and assign a link to it. It would be nice to have a kind of select-list containing the available nodes to link to.

I have done this before, but only for external links and with a minified editor. But i have no idea how to put a list of nodes there. Is there an alternative to achieve this?

# Answer
> 1 votes
Sounds like you're looking for the LinkIt module.

> Linkit provides an easy interface for internal and external linking. Linkit links to nodes, users, managed files, terms and have basic support for all entities by default, using an autocomplete field. In 7.x-2.4 there is also support for fields (text, textarea, and link).

If you have pretty paths I'd also suggest combining it with Pathologic, that way your links will have their path aliases applied rather than their direct links (i.e. *node/123* will become *about-us*)

---
Tags: 7, nodes, navigation
---


title: Theming with css classes

text:
# Question
Title: Theming with css classes
First of all I apologize for my stupid question...I am a new user in drupal and I don't know very much about php and css... My trouble is the following:I have many elements in my website with class "field set" , all I want to do is to have a background and a border style for some of such field set, but I want to set differents style for a specific "fieldset" element! I try with firebug to find the elements and I found this:

```
<div class="content"><div class="view view-home-lista-completa-con-openlayer view-id-home_lista_completa_con_openlayer view-display-id-page view-dom-id-4812ec06a9a1759846345be18533fa6b">
  <div class="pannelloricerca">
    <div class="view-filters">
      <form action="/completa-proximity" method="get" id="views-exposed-form-home-lista-completa-con-openlayer-page" accept-charset="UTF-8">
      <div>
        <div class="views-exposed-form">
          <div class="views-exposed-widgets clearfix">
            <div id="edit-circle-wrapper" class="views-exposed-widget views-widget-filter-circle">
              <div class="views-operator">
                <input type="hidden" name="circle_op" value="<" />
              </div>
              <div class="views-widget">
                <fieldset class="openlayers-proximity-filter-exposed form-wrapper" id="edit-circle">
                <div class="fieldset-wrapper"><div class="form-item form-type-textfield form-item-circle-value">
                  <span class="field-prefix">È a meno di</span>
                  <input type="text" id="edit-circle-value" name="circle[value]" value="" size="3" maxlength="128" class="form-text" />
                  <span class="field-suffix">Chilometri </span>
                </div>
                <div class="form-item form-type-textfield form-item-circle-location">
                  <span class="field-prefix">da</span >
                  <input type="text" id="edit-circle-location" name="circle[location]" value="" size="20" maxlength="128" class="form-text" />
                </div>
            </div>
            </fieldset>

```

I want to set a specific background for the element: \< fieldset class="openlayers-proximity-filter-exposed form-wrapper" id="edit-circle"\> but I cannot find how to tell in the css to apply new style to this one and only this !! I tried to set attribute to the class: .openlayers-proximity-filter-exposed .form-wrapper .fieldset but nothing happened .. Can anybody help me, please?? just tell me how it works when you have to customize classes into div as per this example. Thank you all!!!!!

# Answer
> 1 votes
If you want to add a style to a particular element in CSS, you should use the ID of the element rather than the class as IDs are unique.

e.g

```
#edit-circle {
}

```

# Answer
> 0 votes
We call it `CSS Selector` and your selector failed because it select something else:

`.openlayers-proximity-filter-exposed .form-wrapper .fieldset` select elements with `fieldset` class within element with `form-wrapper` class and wrapped with elements with `openlayers-proximity-filter-exposed` class.

In your way, your selector should be:

```
fieldset.openlayers-proximity-filter-exposed.form-wrapper

```

it means fieldset elements with both `openlayers-proximity-filter-exposed` and `form-wrapper` CSS classes.

---
Tags: theming
---


# Question
Title: Problem with product page (sidebar goes down)
I am using Drupalcommerce (CommerceKickstart 7.x-2.0-rc2).
There is an issue with the display of the product page. The product page is composed of a content and a right-sidebar. Every page that uses this configuration is well displayed but not the product page : the sidebar goes down.
First I thought about a css problem but I found that it is a problem with the htlm structure :
\- For good pages the markup "aside", that contains the sidebar", is included in the div "zone-content" that is included in the div "zone-content-wrapper".
\- For product page the markup "aside" is included directly in the div "zone-content-wrapper".
I looked at the files tpl.php of the theme but found no issue (I don't have a good knowledge about templates...).

Does someone already faced with this issue?

# Answer
> 0 votes
Ok, mine is inside an article container. Go to Appearance -\> Commerce Kickstart -\> Settings -\> Zone and Region Configuration and check Content Section -\> Content Zone -\> Regions.

There should be Sidebar First, Content, Sidebar Second in order. Make sure all of those are in there.

I do know I ran into this issue but mine was CSS related (I changed the width of the content region). Check your settings above and make sure everything looks good. No unassigned regions etc. Try a full wrapper if you don't have one and try without if you do and see if that changes anything.

# Answer
> 0 votes
I noticed the same thing after updating from Commerce Kickstart RC1-\>RC4; the problem seems to be caused by a wrong structure of the DIV containers. The region-sidebar-second should be a child of columns-inner, but on the product page it's on the same level.

The culprit *might* be the template

`profiles/commerce_kickstart/modules/commerce_kickstart/commerce_kickstart_product_ui/theme/node--product--type.tpl.php`

Which lacks an opening \<div\> tag. Copying this file to my at-commerce theme and inserting said tag right after the \<article\> tag helped.

Caution: I didn't investigate that thing further and I am not sure if the structure of the containers is correct right now!

---
Tags: commerce
---


# Question
Title: Render a custom region inside node template
I am attempting to render a menu assigned to a block right next to the body of a custom content type. I am using Drupal 7.

I have a custom region defined within my template `.info` file. I would like to render this region and the block assigned to it from within a custom node template ...

`node--<my custom content type>.tpl.php`

I needed to do this within the custom node template because I needed to break out the individual fields of the content type rather than just using

`print render($content);`

This is what I was trying to do ...

```
<div class="content">
  <?php
    print render($content['title']);
    print render($content['field_banner_image']);
    print render($content['body']);
  ?>
  <div><?php print render($page['MY-CUSTOM-REGION']); ?></div>
  <div><?php print render($content['body']); ?>div>
</div>

```

However, my menu block does not render and I get the following error ...

`Warning: Cannot use a scalar value as an array in include()[PATH TO MY CUSTOM NODE TEMPLATE]`

Is it possible to render a region from within a custom node template?

# Answer
> 0 votes
You should load your menu yourself inside node, use:

1. hook\_node\_load
2. hook\_node\_view
3. hook\_preprocess\_node

---
Tags: nodes, theming
---


# Question
Title: Student TV channel - taxonomising YouTube videos
This question has been created to break up a previous question; see there for more detail.

As you can guess from the title, I'm the new webmaster for a student TV channel and I need to update the site.

The site needs to pull in YouTube videos from a channel, embed the video player and display a brief description of the video, along with information about the cast & crew involved in the production. Similar videos (such as those in a series) need to be linked together in a "playlist" style, while other videos should be browsable through a gallery based on genre.

Does anyone know what the most effective way to taxonomise these videos would be? I'm thinking of fields `genre` and `series` at the moment, but I don't know how I could list cast & crew members. (Videos need to be organised so you can quickly find all of the videos with a cast/crew member involved with)

# Answer
I suggest using series and genre as the main taxonomies as you've said and then using Tags to generate a taxonomy for cast and crew.

You can use the Taxonomy Manager module to bulk add and edit taxonomies, including tags.
> 0 votes

---
Tags: taxonomy-terms, files
---


# Question
Title: How to use hook_menu_link_alter() on taxonomy term view?
When viewing a taxonomy term, I want to change the 'Edit' link (in the admin tabs) to say 'Edit this term' instead.

In taxonomy.module, the menu item is defined like this:

```
function taxonomy_menu() {
    $items['taxonomy/term/%taxonomy_term/edit'] = array(
        'title' => 'Edit',
        'page callback' => 'drupal_get_form',
        // Pass a NULL argument to ensure that additional path components are not
        // passed to taxonomy_form_term() as the vocabulary machine name argument.
        'page arguments' => array('taxonomy_form_term', 2, NULL),
        'access callback' => 'taxonomy_term_edit_access',
        'access arguments' => array(2),
        'type' => MENU_LOCAL_TASK,
        'weight' => 10,
        'file' => 'taxonomy.admin.inc',
      );
}

```

So in my module, I try to do this:

```
function mymodule_menu_link_alter(&$item, $menu) {
  if ($item['link_path'] == 'taxonomy/term/%taxonomy_term/edit') {
    $item['link_title'] = 'Edit this term';
  };
}

```

After clearing cache and rebuilding menus, the menu item still says 'Edit'.

Is this because the menu item type is MENU\_LOCAL\_TASK? Or perhaps I am missing something else?

# Answer
You're just implementing the wrong hook...you need `hook_menu_alter()` instead

```
function mymodule_menu_alter(&$items) {
  $items['taxonomy/term/%taxonomy_term/edit']['title'] = 'Edit this term';
}

```
> 1 votes

# Answer
hook\_menu\_link\_alter() is invoked from menu\_link\_save(), which is the function called when a menu link is saved. The code you wrote for that hook would be invoked when, for example, you add a menu link from admin/structure/menu/manage/main-menu/add, and use taxonomy/term/%taxonomy\_term/edit as value for *Path*.

As Clive said, `hook_menu_alter()` is the hook you should use to change the menu item defined in `hook_menu()` from a module.
> 2 votes

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


# Question
Title: How can I know that node is created or updated?
I had configured Drupal 7. I'm going to run cron when a node is saved/updated/deleted. How I know that node is changed?

Thanks.

# Answer
Modules that need to execute code during cron tasks, and for nodes that have been created/updated/delete already implement code to do that. If you need something similar for your own module, you could use the following code.

```
function mymodule_node_insert($node) {
  $queue = DrupalQueue::get('mymodule_cron_queue');
  $queue->createQueue();
  $queue->createItem($node);
}

function mymodule_cron_queue_info() {
  $queues['mymodule_cron_queue'] = array(
    'worker callback' => 'mymodule_cron_worker',
    'time' => 10,
  );

  return $queues;
}

function mymodule_cron_worker($node) {
  // Code that uses $node.
}

```

With this code, `mymodule_cron_worker()` is called during cron tasks for every node that has been created; if you need to execute code during cron tasks for updated nodes, or deleted nodes, then you need to implement `hook_node_update()`, or `hook_node_delete()`. The code I shown for `hook_node_insert()` is the same code you would use for the other node hooks.

### References
> 2 votes

# Answer
I think you mean `trigger` node insert/update/delete events. use:

1. hook\_node\_insert
2. hook\_node\_update
3. hook\_node\_delete

And if you need to know status of node (newly created or modified), you can check node's properties: `created` and `changed`
> 1 votes

---
Tags: 7, nodes, cron
---


# Question
Title: How to use different domains for multilingual sites and keep users logged in?
I have a site that is in French and English. I am able to successfully setup so that users can switch back and forth between the two domains to view either language, however I cannot seem to keep users logged in. When they are logged into the english domain and then switch to the french domain they are required to login again. However if they switch back to the english domain they are still logged in.

As an example we'll use www.english-domain.com as the base (default) domain and www.french-domain.com as the secondary domain

In settings.php I have modified the following, however it doesn't seem to be keeping them logged in. Am I missing something?

```
/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on its full domain name. If you have multiple domains pointing at the
 * same Drupal site, you can either redirect them all to a single domain (see
 * comment in .htaccess), or uncomment the line below and specify their shared
 * base domain. Doing so assures that users remain logged in as they cross
 * between your various domains.
 */
$cookie_domain = 'english-domain.com';

```

Note: That I have also flushed both site and browser cache as well as deleted any cookies left on my machine.

Update:

Here are my language settings:

# Answer
> 3 votes
Cross domain cookies are not allowed; this means that english-domain.com cannot set a cookie for french-domain.com.
Cookies can be shared between sub-domains, though: english.example.com can set a cookie that is seen from french.example.com, and vice versa.

To allow users to be logged-in on sub-domains of the same domain, you can use the Bakery Single Sign-On System module.

As far as I know, there aren't Drupal SSO modules for different domains. There are web sites that allows SSO between different domains, such are the ones that are part of Stack Exchange network, where users having an account on Stack Overflow can be automatically logged in on Drupal Answers, or Super User, if they have an account on those sites.
The code to write is more complicated, in this case. What Stack Exchange sites do is the following:

### Initial login

* Login proceeds as usual
* At the end, the user is given a global login token (attached as a cookie)
* The next page the user visits takes that token, and (via an IFrame) shovels it to StackAuth
* StackAuth verifies the token, and attaches a session key via localStorage

### Visiting a different site

* JavaScript is used to hit StackAuth via an `<iframe>`
* StackAuth checks localStorage for a session, and sends it to itself if it is
* StackAuth validates the session and passes a login token to the Stack Exchange site via `postMessage` when the session is valid
* The Stack Exchange site validates the token, looks up the user, and logs the user in

Using cookies, and sub-domains is much simpler. The code used by Stack Exchange requires a browser supporting localStorage, but it works for every domain, not just sub-domains.

# Answer
> 3 votes
A cookie can only be read from the same domain that set it. This is a fundamental security feature in browsers to prevent other sites from potentially stealing login sessions, and there is nothing simple you can do about it.

With that said, the comment in the settings.php file seems to contradict my statement, and I'm honestly not really sure how to intrepret that. Perhaps it's only meant to be relevant to *sub*-domains, which are allowed to share cookies, but if so the comment should probably be re-phrased.

There are a number of ways to work around this, where the easiest is to use language prefix sub-domains instead of separate domains.

Baring that, I believe the "best" one is to use a Single sign-on system. There's a comparision of different SSO modules here. This *could* be a Drupal based solution, which is the way that is most likely to "nicely" integrate with your current Drupal sites, but that's not really necessary.

The Bakery module which is used by \*.drupal.org itself is relevant to mention, as well as this related DA answer How drupal.org single sign on works

More info about cross-domain cookies in a Stack overflow question.

---
Tags: i18n-l10n, configuration
---


# Question
Title: Site off-line with correct data in settings.php
I'm trying to set up a development folder for a Drupal6 already existing website.

Under `htdocs/sites/<website>/settings.php` I have the following line in order to connect to the drupal6 DB:

```
$db_url = 'mysql://root:<mysql_password>@localhost/<drupal_db_name>';

```

If I try to enter mysql using the same login data, I can do it without any problems, so I know this data is correct.

But I still keep getting the "Site off-line" message.

I've also tried using settings.php in the "default" folder under `htdocs/sites/`, but it didn't solve the problem.

Any suggestions of what could I try in order to fix or debug this?

UPDATE: I have not taken the site down through admin. I've taken the folder from a production server (where it's working correctly), and I've placed it into another server. I've also made the same thing with the DB.

# Answer
> 2 votes
You probably haven't installed and/or enabled the PHP MySQL extension (it's a requirement). You can check by creating a `phpinfo()` page and searching for 'mysql'. If it's not there, you need to install and enable it. You don't say what server you're using, but if it's Ubuntu or a similar Debian-based variant, you can do this:

```
$ sudo apt-get install php5-mysql
$ sudo /etc/init.d/apache2 restart

```

If you're on another platform, the steps will be a bit different, but you get the idea.

---
Tags: 6, deployment, configuration
---


title: Webform for Contact Information

text:
# Question
Title: Webform for Contact Information
What html code can I use to create a form for readers to submit their contact information (e.g., phone number, email address, etc.) and type a question?

# Answer
If the Contact module doesn't suit your needs (comes with Drupal core and can be enabled on the Modules page), then your best option is to use the Webform module.
> 1 votes

---
Tags: webforms
---


# Question
Title: Drupal 7 views: Get NID in views using contextual filters
Does anybody know how to get the nid from a node using contextual filters or filter criteria in views

WITHOUT using "Get id from url"? I was thinking about using PHP or getting it from a node-field.

My view is a block of comments that is to be placed together with a node. The comments needs to belong to the node and linked by node ID. In this case the "Get ID from url" wont work since the node itself is listed in another view.

It is a view-block (containing comments) inside of a node that is listed in a view.

# Answer
> 1 votes
If you are loading and displaying your view in the `node.tpl` or `node--<content-type>.tpl` file, you could supply the current node nid as an argument to your block view, then you can setup a contextual filter for Content: Nid. I would do something like this:

```
// get view
$view = views_get_view('YOUR_VIEW_NAME');
// set display for view
$view->set_display('YOUR_VIEW_BLOCK_NAME');
// set current node nid as argument to view
$view->set_arguments(array($node->nid));
// execute view
$view->execute();
// render view
print $view->render();

```

---
Tags: 7, nodes, views
---


# Question
Title: Different entity types for one field value
I have a content type "Application". And "Site Administrator" and "Developer" users are allowed to add it.

If logged-in user is "Site Administrator", the value of "Author" field will be the reference of other content type. So, in the respective field table,

**entity\_type** : node, **bundle** : {content-type-name}

If logged-in user is "Developer". I'd like to save current logged-in user id as the value of "Author" field.

**entity\_type** : user, **bundle** : user

How could I get it with drupal?

Thanks in advance.

# Answer
1. The "author" field would be a User Reference field.
2. You can use hook\_form\_alter to limit this fields allowed `$options` to be either the logged in user, or the list of users of Developers.

Something similar too ...

```
function MYMODULE_hook_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'node_add_application') {
    if (in_array('Developer', $user->roles)) {
      // Set the default value of the author field to the logged in users uid.
      $form['field_AUTHOR_FIELDNAME']['options']['#default_value'] = $user->uid;
    }
    if (in_array('Site Administrator', $user->roles)) {
      // Overwrite the general users list with UIDs only of a specific role.

      // Get uids of a specific role.
      $query = 'SELECT DISTINCT(ur.uid)
          FROM {users_roles} AS ur
          LEFT JOIN roles r on ur.rid = r.rid
          WHERE r.name = :role';
      $result = db_query($query, array(':role' => 'Developer'));
      foreach ($result as $row) {
        $developer_uids[] = $row->uid;
      }
      foreach ($form['field_AUTHOR_FIELDNAME']['options'] as $uid => $label) {
        if (!in_array($uid, $developer_uids)) {
          unset($form['field_AUTHOR_FIELDNAME']['options'][$uid];
        }
      }
    }
  }
}

```

This is a rough example of the logic and code it would take to alter the select list of user names for the author field to either default to the logged in developer, or show "site admins" only developers.

I have written such code before, this exact code is only an example based upon the details given in your question. It is un-tested.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Implement Field API Pane Editor into Views
I have a View which shows nodes from a content type. I need user to be able to edit only one field from these nodes. I installed FAPE module and read its instructions but cat figure out how to implement it into views. I can't ever find out how links should look. Any help would be appreciated. 10x

# Answer
For editing single-field values in views, there's the editable fields module rather than FAPE. However, this edits a single row at a time, rather than bulk updating all nodes or entities in the view at the same time.
> 1 votes

---
Tags: 7, views, entities, navigation, nodes
---


title: No change upon editing node.tpl.php

text:
# Question
Title: No change upon editing node.tpl.php
I have a view where I am displaying nodes using row style Node. I want to edit the way the Node row style.

I edited the file /modules/node/node.tpl.php and **commented the line**

`print $picture;`

just for testing.

I was expecting that the picture field of each node would vanish. **But I saw no change in the view display.** Why is this?

# Answer
The documentation for the plugin says:

> The **node** row style will display each item of the view through Drupal's standard `node_view()` function. Views has very little control over this output, except for the options you see. You can choose from different **Build modes**. By default there are "Teaser" and "Full node". You can also decide if you want to "Display links" and/or "Display node comments".
>
> Because the output is run through the standard node template mechanism (typically **node.tpl.php** or a variant thereof), any decisions about what is output may be done there.
>
> Views does add an extra 'suggestion' to the list of possible node templates: **node-view-VIEWNAME.tpl.php**—you may use this to theme a node specifically for the view. This can be handy for creating very small teasers and the like.

The template file could be different from node.tpl.php if there are other template files suggested for the content type, or a node in particular; the Views module itself suggests a template file whose name depends from the view name. Then, between the node.tpl.php defined from the Node module, and the same file defined from the theme, the latter is the used one.

The rendering method use for that plugin is views\_plugin\_row::render(), which contains the following code.

```
return theme($this->theme_functions(), $this->view, $this->options, $row, isset($this->field_alias) ? $this->field_alias : '');

```

With Drupal 7, the method is views\_plugin\_row\_node\_view::render(), which contains the following code.

```
  if (isset($this->nodes[$row->{$this->field_alias}])) {
    $node = $this->nodes[$row->{$this->field_alias}];
    $node->view = $this->view;
    $build = node_view($node, $this->options['view_mode']);

    return drupal_render($build);
  }

```

### References
> 2 votes

---
Tags: views, nodes, 6
---


# Question
Title: How to migrate Link Fields ('title' and 'url') involving local variables?
I have performed the following query:

```
$query = db_select('sage.USER', 'USER')
  ->fields('USER', array('USER_ID', 'OFFICE_ID', 'USER_PASSWORD'))
  ->range(0, 1);
$result = $query->execute();
...
$url = '/sage/office-' . $result->office_id;
$arguments = MigrateLinkFieldHandler::arguments(array('source_field' => 'office_id'));
$this->addFieldMapping('field_office_id', $url);
  ->arguments($arguments);

```

However, the above is not working. I would like to manipulate the 'office\_id' field to be used as the 'title' and the variable $url to be used as the URL that was linked. I have followed what's on this post

Could someone please point out my mistakes?

EDIT: Updated question to reflect jdu's answer.

# Answer
The `link.migrate.inc` file is not included in the Migrate Extras module, it's part of the Link module.

The file doesn't exist in the stable version of Link, but it *does* exist in the dev release. I think you're going to have to install the dev version of Link if you want this to work.

If you install the dev version and still get the error it's most likely because the file is not being automatically included. If that's the case try adding this to the top of your code:

```
module_load_include('inc', 'link', 'link.migrate');

```

**EDIT**

As I mentioned in your other question there's a slight error in your code, you should change this line:

```
$result = $query->execute();

```

to:

```
$result = $query->execute()->fetchObject();

```

That will return an object representing the first result that was returned by the query.
> 3 votes

# Answer
This is how I imported nodes:

* Download link.migrate.inc from link 7.x dev version and add this file to your module
* Add file entry in your .info module (files\[\] = link.migrate.inc)
* Apply this patch link-migrate\_subfields.patch
* Then you can use the following code:

```
$this->addFieldMapping('field_portrait_affiliation_link', 'field_portrait_affiliation_link');
$this->addFieldMapping('field_portrait_affiliation_link:title', 'field_portrait_affiliation_link:title');
$this->addFieldMapping('field_portrait_affiliation_link:attributes', 'field_portrait_affiliation_link:attributes');
$this->addFieldMapping('field_portrait_affiliation_link:language', 'language');

```
> 3 votes

# Answer
Fill a new variable with the results of executing your query:

```
$result = $query->execute();

$url = 'office-' . $result->office_id;

```
> 1 votes

# Answer
Have you checked: /admin/content/migrate/configure

There check the Field handlers for the link field:

\[x\] link MigrateLinkFieldHandler link\_field

Install the dev version of the Link module. Then this should work:

```
....
$arguments = array('title' => array('source_field' => 'office_id'));
$this->addFieldMapping('field_office_id', 'field_office_id_path')->arguments($arguments);
...

function prepareRow($row) {
    $row->field_office_id_path = '/sage/office-' . $row->office_id;
}

```
> 0 votes

---
Tags: 7, entities, navigation, migrations
---


# Question
Title: Problems Installing Colorbox Module "Requires: Libraries (2.x) (incompatible with version )"
I followed the instructions and installed the Colorbox plugin, the Colorbox module, and the Libraries API module. For some reson, when I go to the Modules pages and try and enable the Colorbox module, it says `Requires: Libraries (2.x) (incompatible with version ).` Even though libraries 2.x has been installed. I can't figure out what I'm doing wrong.

# Answer
It should just happen when the Libraries API doesn't contains the version line in libraries.info. That would explain why the message doesn't report the Library API version.

I made a test on my test site. On the .info file for a custom module I added the following line.

```
dependencies[] = libraries (2.x)

```

In the libraries.info file, I removed the following line.

```
version = "7.x-2.0+5-dev"

```

When I visited the module page, I saw the following message for my custom module:

> Requires: Libraries (2.x) (incompatible with version )

I thought it would happen when the installed module was a development snapshot, but it's not true. If I add the line I removed, all back to normality, even if I installed the development snapshot of the Libraries API module.

If you copied the Libraries API files from a Git repository, the libraries.info file is missing the version line, and that would explain the message error you see.

Removing the version from the dependency line is fine, as long as you don't install the Libraries API module 1.x by mistake.
> 5 votes

# Answer
I'm not sure why, but I was able to fix it simply be changing the module requirements from `dependencies[] = libraries (2.x)` to `dependencies[] = libraries` for some reason, even though I had libraries 2.x installed, colorbox thought I didn't
> 1 votes

---
Tags: javascript
---


title: Dynamic URL aliasing?

text:
# Question
Title: Dynamic URL aliasing?
Let's say we have a section `/latest-projects` with a menu block listing nodes sorted descending by their post date. Thus, the first item will often change and be the freshest one. Is it possible to make the `/latest-projects` alias always link to (= open) the top-most node?

# Answer
Indeed it is.

Steps you will need to do:

1. Create a custom module
2. Implement hook\_menu()
3. Define the route 'latest-projects', and make the menu callback a function
4. In the custom menu callback function do SQL or whatever to find the latest project (maybe use EnityFieldQuery in Drupal 7)
5. Use drupal\_goto() to then redirect the user to the latest project node

Note in the above solution, a redirect is used to send the user to the project node, but if needed you can also simply render the node on the page as another idea.
> 2 votes

---
Tags: path-aliases, uri
---


title: Changing Field Display Properties

text:
# Question
Title: Changing Field Display Properties
I'm using Drupal 7, and I have a node type that has an image and body text. I want the display for this node to display the image inline with the text (ie, apply float:left to the image).

Is there any way for me to do this through the frontend, or will I have to manually change the CSS for the image field's class?

# Answer
Some themes can do this for you out of the box. See AdaptiveTheme as an example -- you can float an image field inline the body field.

I believe with DisplaySuite you can also show fields inline.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Where to use the php functions when adding fields to existing nodes?
I'm new to Drupal and PHP. I've found many answers on stackexchange to the question of bulk adding fields to existing nodes. I need to add a field, like a tag or date (for future facet filtering), to existing nodes. I've been successful with creating a content type and setting up the default fields for users, but now we'd like to figure out how to do this if the nodes have already been created. The VBO module may be the best answer, however, we may have a few hundred of these nodes.

I see plenty of great example code, however, I am unsure of where to use this code. Do I do this on phpmyadmin? I'm more familiar with SQL, but I've read advice here that SQL should only be used if very familiar with Drupal. I'm using Drupal 7.

# Answer
> 0 votes
Fields are attached to Entities, not Nodes. So the field is either attached to bundle that is your node (for all nodes, pre-existing or not), or it hasnt been attached to that bundle yet.

You can use field\_info\_field and look at the element `bundles` to see if your given field is attached to the given Entity. If it isn't you can use field\_create\_instance to add the field to your entity.

You can get a list of all entity types and inspect their bundle types with the `bundles` key returned from entity\_get\_info by calling `$site_entity_list = entity_get_info(NULL)`.

Entities and fields are cached, so be sure you use something like `drush cc all` to be sure you're looking at up-to-date values for all these function calls.

EDIT: You use these functions and PHP from essentially a small php script. Such business logic could be in a small module with hook\_update\_n() for instance. Or, you could use Drush and write a very simple PHP snippet using hte above 3 functions and some loops and call it using drush like: `drush php-script your-script-filename.php`

---
Tags: nodes, entities
---


# Question
Title: How to create absolute url for a page/node?
I think that I need to use the l() function as seen here: How do I get the absolute URL when using l()?

I just need a bit more clarification. What's the best way to create links on pages? I would like to link them correctly so that if my domain changes then the link will be updated (for example going from a local host to an online host). Let me also know if this is not the best way to do it.

I guess I need to know what would go into HTML tag and then also do I need to place any code anywhere else?

# Answer
You should use the `l()` and `url()` functions as specified in the answer to the question you link to. Those are core Drupal functions so nothing else is needed.
> 1 votes

---
Tags: theming, navigation
---


title: Theming individual menus

text:
# Question
Title: Theming individual menus
Let me fully describe the problem I am trying to solve as there may be a better way of doing what I am trying to do.

On my Drupal 7 install, when a user is logged out, the Main menu shows Home / Log In and a few other links I've added. This is $primary\_nav in the theme.

When a user is logged in, a Log Out link is added.

What is confusing however, is that there is still a login link in the Main menu.

My solution was to create a second menu that would replace the Log in link with a link to the user's account page when they are logged in. All other links would remain the same.

In the template, I am doing the following:

```
<?php // show different menus depending on if the user is logged in ?>
<?php if ($user->uid): ?>
<?php $menu = menu_navigation_links('user-menu'); ?>
<?php print theme('links__menu_user_menu', array('links' => $menu)); ?>
<?php else: print $primary_nav; ?>
<?php endif; ?>

```

And this correctly shows the right menu depending on whether the use is logged in or not.

However, the styles are completely different. $primary\_nav is a horizontal menu and user-menu is a vertical menu.

According to http://drupal.org/node/254940#theme-suggestions-for-menus, I should be able to create a function in my theme's template.php file and style it. However, I tried doing the following:

```
function MYTHEME_menu_tree__user_menu(&$variables) {
  echo 'Success'; exit;
}

```

But that code is not run.

So my questions are these:

1) Is this the best approach to replace Log In with a link to the user account page when the user is logged in?

2a) If so, what's the best way to get the menu styled the way I want it?

2b) If not, how can I achieve the effect listed in 1)?

Thanks!

# Answer
> 1 votes
If you use `user` as login path, it will visible after login.

You should replace `user` with `user/login` it will gone after login.

Also user's profile link is available in `User menu`, just edit it and change its parent menu to your `primary nav`.

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


title: External link in views slideshow

text:
# Question
Title: External link in views slideshow
I have a views slideshow where an image is linking to the node. Now I want one of the slides to link to an external site. How do I get this to work? Maybe I can rewrite the output for the image field in a tpl.php file, but I don't know how to do it. Any suggestions is appreciated. Thanks

# Answer
> 1 votes
If you are in Drupal 7, all you need is using Link and Linked field modules

---
Tags: media, views
---


# Question
Title: How to populate a node reference field that has multiple values?
I'm using the rules to create a new node upon changing the current node publishing status to published. And populate some field based on the updated node field. Im trying to populate a node reference field in the new created node based on the node reference field multiple values from updated node. I wasn't able to use the tokens since it returns single value. How do I get all the values using tokens and return the values in an array (using the php code)?

# Answer
I managed to get multiple value node reference field using the Array Tokens module, an extension to the Token module, providing tokens for multiple-value CCK fields and taxonomy terms.

```
$authors = array([node:field_op_author-default-array-nid]);
$options = array();

foreach ($authors as $author) {
  $options[] = array('nid'=>$author);
}

return($options);

```
> 0 votes

---
Tags: entities, rules
---


# Question
Title: Is it possible to force Views to collect a minimum count of nodes per group?
I have a View that collects nodes of a certain type, grouped by term.

```
Term 1
 Node 1
 Node 3
 Node 4
 ...
Term 2
 Node 2
 Node 5
 ...

```

Can I force Views to list exactly 10 nodes per each term, rather than total of ten per entire query?

# Answer
Check out Views Grouping Row Limit module.

From the project page:

> This is a basic Views style plugin that allows for a limit on the number of rows displayed within a grouping field.
> 1 votes

---
Tags: search, views
---


title: Add div to checkboxes only

text:
# Question
Title: Add div to checkboxes only
I would like to add a `<div>` containing only checkboxes. The output I want is similar to the following.

```
<div class="a">
  <label for="check1">1</label><input type="checbox" id="check1" name="check1">
  <label for="check1">1</label><input type="checbox" id="check2" name="check2">
  <label for="check1">1</label><input type="checbox" id="check3" name="check3">
</div>
<div class="text"><input type="text" id="text" name="text"></div>
<div class="submit"><input type="submit" value="submit"></div>

```

In template.php I have `THEME_form_alter()` with the following code.

```
  $form['basic'] = array(
    '#prefix'=> '<div class="a"><ul>',
    '#suffix'=> '</ul></div>'
  );

  $form['basic']['keys']['check1'] = array(
    '#prefix' => '<li><label for="check1">Check1',
    '#suffix' => '</li></label>',
    '#type'=>'checkbox',
    '#value' =>'0',
    '#pre_render' => '',
    '#id' => 'check1',
    '#name' => 'check1'
  );

  $form['basic']['keys']['check2'] = array(
    '#prefix' => '<li><label for="check2">Check2',
    '#suffix' => '</li></label>',
    '#type'=> 'checkbox',
    '#value' =>'0',
    '#pre_render' => '',
    '#id' => 'check2',
    '#name' => 'check2'
  );

  $form['basic']['keys']['check3'] = array(
    '#prefix' => '<li><label for="check3">Check3',
    '#suffix' => '</li></label>',
    '#type'=> 'checkbox',
    '#value' => '0',
    '#pre_render' => '',
    '#id' => 'check3',
    '#name' => 'check3'
  );

  $form['basic']['keys']['text'] = array(
    '#prefix' => '<div class="text">',
    '#suffix' => '</div>',
    '#type'=> 'textfield',
  );

```

How should I write `THEME_form_alter()` to be obtain the HTML output I want?

# Answer
> 1 votes
With the form elements you are using, the output you obtain is the following one.

```
<div class="a">
  <ul>
    <li>
      <label for="check1">
        Check1
        <div class="form-item form-type-checkbox form-item-check1">
          <input type="checkbox" id="check1" name="check1" value="1" class="form-checkbox">
        </div>
      </label>
    </li>
    <li>
      <label for="check2">
        Check2
        <div class="form-item form-type-checkbox form-item-check2">
          <input type="checkbox" id="check2" name="check2" value="1" class="form-checkbox">
        </div>
      </label>
    </li>
    <li>
      <label for="check3">
        Check3
        <div class="form-item form-type-checkbox form-item-check3">
          <input type="checkbox" id="check3" name="check3" value="1" class="form-checkbox">
        </div>
      </label>
    </li>
    <div class="text">
      <div class="form-item form-type-textfield form-item-text">
        <input type="text" id="edit-text" name="text" value="" size="60" maxlength="128" class="form-text">
      </div>
    </div>
  </ul>
</div>

```

`<div class="a">` is wrapped to all the elements because it's a prefix for `$form['basic']`, which contains all the form elements.

I would use the following code.

```
  $form['basic']['keys']['check1'] = array(
    '#type'=> 'checkbox',
    '#title' => 'Check1',
    '#value' => '0',
    '#pre_render' => array(),
    '#prefix'=> '<div class="a"><ul><li>',
    '#suffix' => '</li>',
  );

  $form['basic']['keys']['check2'] = array(
    '#type'=> 'checkbox',
    '#title' => 'Check2',
    '#value' => '0',
    '#pre_render' => array(),
    '#prefix' => '<li>',
    '#suffix' => '</li>',
  );

  $form['basic']['keys']['check3'] = array(
    '#type'=> 'checkbox',
    '#title' => 'Check3',
    '#value' => '0',
    '#pre_render' => array(),
    '#prefix' => '<li>',
    '#suffix' => '</li></ul></div>'
  );

  $form['basic']['keys']['text'] = array(
    '#prefix' => '<div class="text">',
    '#suffix' => '</div>',
    '#type'=> 'textfield',
  );

```

Its output is the following one.

```
<div class="a">
  <ul>
    <li>
      <div class="form-item form-type-checkbox form-item-check1">
        <input type="checkbox" id="edit-check1" name="check1" value="1" class="form-checkbox">
        <label class="option" for="edit-check1">Check1 </label>
      </div>
    </li>
    <li>
      <div class="form-item form-type-checkbox form-item-check2">
        <input type="checkbox" id="edit-check2" name="check2" value="1" class="form-checkbox">
        <label class="option" for="edit-check2">Check2 </label>
      </div>
    </li>
    <li>
      <div class="form-item form-type-checkbox form-item-check3">
        <input type="checkbox" id="edit-check3" name="check3" value="1" class="form-checkbox">
        <label class="option" for="edit-check3">Check3 </label>
      </div>
    </li>
  </ul>
</div>
<div class="text">
  <div class="form-item form-type-textfield form-item-text">
    <input type="text" id="edit-text" name="text" value="" size="60" maxlength="128" class="form-text">
  </div>
</div>

```

---
Tags: theming, forms
---


# Question
Title: How to remove a views template file in theme folder?
I put .tpl.php file inside my theme folder to override views output. Then I deleted this file because it was no use for me. And did "Rescan template files". Now it cannot find this file and gives errors on the page.

> File not found, in folder sites/all/themes/mytheme/templates/

I also cleared all my caches.

How can I remove this file for good?

# Answer
> 0 votes
It looks like my problem is related with APC or some sort of caching. After removing the file, I run

> $ httpd restart

from the command window on the server, then the errors are gone. Probably it cleared the APC cache.

---
Tags: 7, views
---


title: Blocks not shown in /user/logout page

text:
# Question
Title: Blocks not shown in /user/logout page
Users must be logged in to see anything on my site; so it's important the user login block is always shown to anonymous users.

When users log out, they are normally redirected to the front page. A user has reported an issue where this doesn't happen; the user is kept at /user/logout, where the blocks are not shown.

If I manually navigate to that address, the redirection to the front page doesn't always happen to me, and I can also see that no blocks are shown.

# Answer
> 0 votes
If there aren't modules that avoid the redirection happens, the only case the redirection from user/logout to the front page doesn't happen is when the user is already logged out. user/logout is defined as the following, in user\_menu().

```
  $items['user/logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'menu_name' => 'user-menu',
    'file' => 'user.pages.inc',
  );

```

When a menu is accessed from the users, Drupal first calls the access callback; if the access callback returns `TRUE`, then Drupal calls the page callback. In this case, the redirection is done from the page callback, which is never called when the user is logged out. (In that case, user\_is\_logged\_in() returns `FALSE`.)

For a page like user/logout, the login block is not shown. In fact, user\_block\_view() contains the following code, used to render the login block.

```
  // For usability's sake, avoid showing two login forms on one page.
  if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
    $block['subject'] = t('User login');
    $block['content'] = drupal_get_form('user_login_block');
  }
  return $block;

```

What you can do is implementing hook\_block\_view\_MODULE\_DELTA\_alter() to show the login block also on user/logout, in the case the redirection to the front page doesn't happen for any reason.

```
function mymodule_block_view_user_login_alter(&$data, $block) {
  if (!$GLOBALS['user']->uid && $_GET['q'] == 'user/logout') {
    $data['subject'] = t('User login');
    $data['content'] = drupal_get_form('user_login_block');
  }
}

```

---
Tags: blocks
---


# Question
Title: Content added in article tags, doubling content, even without article content
I am displaying a content type through a view, using a contextual filter to limit results to one per page (nid). I believe this is a simple/standard way of displaying content, but being new to drupal I could be wrong.

My problem is that the content is duplicated. First within an 'article' tag, and then where I'd expect it to show up (inside the view tags). I find it completely baffling because I don't even use the article content type. It's a problem I've had from the start, but I took the easy way out and simply hid the article content with display:none. But now, for some equally baffling reason, drupal has placed a new view I created inside the article tags - which of course means it doesn't show either. :-(

Why would drupal decide to send along my content inside the article tags?

I'm not sure if this is enough to go on, but I would be more than happy to provide more information.

Thanks for your time, Tobias

# Answer
As per comments, I found my error:
I was talking about HTML tags. Sorry for not being precise there. I found my error though, which was incredibly stupid.
I had given the content an url alias so as to function as a page, which would of course send along the content. I had then added a view as described above, adding the content once again.
Silly me. Sorry for the inconvenience.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Is there an hook_node_access() equivalent for users?
Is there any way in Drupal to control access to users like it's done in `hook_node_access()` for nodes? I'm looking for something like `hook_user_access()` or `hook_entity_access()`.

I have an entity reference field (user reference). I want that users can only select users from their organic group, in the entity reference field.

I wanted to do it by implementing some hook like `hook_entity_access()`, but this hook doesn't exist.

# Answer
There isn't an equivalent of `hook_node_access()` for users, or generically for any entity.

To check which user accounts can be selected from the Entity reference autocomplete, you could change the menu callback for the autocomplete.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['entityreference/autocomplete/single/%/%/%'])) {
    $items['entityreference/autocomplete/single/%/%/%']['page callback'] = 'mymodule_entity_autocomplete';
  }
}

function mymodule_entity_autocomplete($type, $field_name, $entity_type, $bundle_name, $entity_id = '', $string = '') {
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $matches = array();

  if ($type = 'user') {
    // Populate $matches with the matching users the currently logged-in user can select.
    return $matches;
  }

  return entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id, $string);
}

```

Probably you need to change the access callback of the autocomplete path too, with `$items['entityreference/autocomplete/single/%/%/%']['access callback'] = 'mymodule_entity_autocomplete';`. The access callback defined from the module is the following one.

```
function entityreference_autocomplete_access_callback($type, $field_name, $entity_type, $bundle_name) {
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);

  if (!$field || !$instance || $field['type'] != 'entityreference' || !field_access('edit', $field, $entity_type)) {
    return FALSE;
  }
  return TRUE;
}

```

If then you want to avoid users can view a user account directly using the link to the account, you can change the access callback for user/%user/view.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user/view'])) {
    $items['user/%user/view']['access callback'] = 'mymodule_user_view_access';
  }
}

```

The default access callback is user\_view\_access(), which contains the following code.

```
  $uid = is_object($account) ? $account->uid : (int) $account;

  // Never allow access to view the anonymous user account.
  if ($uid) {
    // Admins can view all, users can view own profiles at all times.
    if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
      return TRUE;
    }
    elseif (user_access('access user profiles')) {
      // At this point, load the complete account object.
      if (!is_object($account)) {
        $account = user_load($uid);
      }
      return (is_object($account) && $account->status);
    }
  }
  return FALSE;

```

Drupal 8 uses `hook_entity_access()` to control access to any entity (including users) to various operations, `hook_ENTITY_TYPE_access()` to check the access to specific entities on various operations (for which `hook_node_access()` is the implementation for nodes), and `hook_entity_create_access()` to check which users can create an entity.
Drupal 8 code is much simpler than the Drupal 7 code, as as a single hook implementation does the task.
> 3 votes

# Answer
Here is one solution.

Entity reference widget can filter values by using view. So in this way there is no need to use any access hook. For other cystom needs we can create custom filter for the view.
> 0 votes

---
Tags: 7, users, organic-groups
---


# Question
Title: Changing the field separator for multivalue fields
I have a problem which should have a simple solution, but I simply can't figure it out. Perhaps I'm overthinking it or missing some piece of information. Being new to drupal it's not unlikely at all.

I'm trying to output a list of links through a View. No matter which Format I chose (unformatted list, grid, etc.), Drupal never fails to add a comma between each link. I'm having a great deal of trouble removing this comma.

Setting a separator under Field Settings have no effect, but I guess that's only applicable if I had another list of links.

I have tried editting 'views-view-field.tpl.php' by adding the line:

```
<?php $field->field_associated_quicklinks->separator = ""; ?>

```

But it doesn't seem to work. PHP and I aren't on friendly terms, so I'm loathe to start messing too much with the scripts - unless I got some helpful tips from you guys.

All in all I'm stuck on this, and frustrated that I'm having this problem in the first place. Drupal shouldn't go around adding content to my output.

------ EDIT: Well, after several hours and a few tufts of hair, I found this great vid: http://www.youtube.com/watch?v=sxZQqgvJk3s
I believe it's exactly what I needed to know, but I still can't make it work.

I did as prescriped:
1) Copied the field.tpl.php file, removed the comment and changed the mark-up a bit.
2) I named the file 'field--field\_associated\_links.tpl.php' and copied it into the templates folder of my sub-theme.

I get no reaction whatsoever. Could it be confused by the fact that my field name starts with 'field' as well?

Any and all suggestions are very welcome!

# Answer
> 3 votes
Normally you can control this separator directly in the views field option in the *multiple field settings*. Have you tried to change this ?

---
Tags: views
---


title: Tabs and Form Submit

text:
# Question
Title: Tabs and Form Submit
I have an app that has multipla page tabs. One of the tabs has a form that does a search. The issue I am running is that when I do a search on the form, and then go to a different tab, and then come back, it does the search again. How can I make it so that when I switch tabs and come back that the form is in its default state.

Thanks much for the help.

# Answer
> 1 votes
Include the following within the submit button tag:

```
onclick="return false"

```

---
Tags: forms
---


# Question
Title: How to create an entity-reference field programmatically?
I'd like to know how to create an entity-reference field programmatically, and where should I put this script. Could I call `field_create_instance()` in `hook_form_alter()`?

# Answer
> 3 votes
> Could I call `field_create_instance()` in `hook_form_alter()`?

field\_create\_instance() is normally called in `hook_install()`, or `hook_enable()` from a module, or an installation profile.

You don't call it in `hook_form_alter()`, especially if the hook is altering the node edit form: Fields are attached to bundles (content types), not to single nodes. When a node is created, its content type is already created, and any field that content type requires is created before its nodes are created.
If there is a setting form that allows users to decide which fields to attach to a content type, then `field_create_instance()` is called in its submission callback.

A call to `field_create_instance()` is normally coupled with a call to field\_create\_field(). To be sure the field doesn't exist, you should first call field\_info\_field(). It returns `NULL` when the field doesn't exists.

---
Tags: 7, entities
---


title: Avoid duplicated external links

text:
# Question
Title: Avoid duplicated external links
I would like to add a section on my website (*Drupal 7*) which consists of *articles* with *external links* (as source). To avoid spam and duplicated content, I would like to avoid that users may add a URL more than one time. Basically, I need something which checks if the external URL is unique and not being used more than once.

I've looked for modules on Drupal.org, and tried googling some information. But I couldn't really find a solution. The Link checker module seems fine for checking if the URL is still available, but it doesn't avoid the same URL is used more than once.

# Answer
> 4 votes
You should take a look at the Unique Field module:

> This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.

---
Tags: nodes, navigation
---


# Question
Title: How to create a link with l() function that jumps to specific part of page?
Hoping to create a link that jumps to a specific part of another page. For example in a block I have this:

```
<?php print l(t('About Me'), 'node/55#FIRST', array('absolute' => TRUE));?>

```

But in the browser it outputs the "#" as "%23":

```
http://www.site.or/node/55%23FIRST

```

Anyway to do this?

# Answer
The last parameter of l() accepts also the same options accepted from url(). This means you can use the following code since Drupal 6.

```
<?php print l(t('About Me'), 'node/55', array('absolute' => TRUE, 'fragment' => 'FIRST')); ?>

```

On my test site, the output is the following one.

```
<a href="http://tero.local/dr72/node/55#FIRST">About Me</a>

```
> 4 votes

---
Tags: theming, blocks
---


title: Alter Exposed filter form

text:
# Question
Title: Alter Exposed filter form
I would like to know how to get parent terms only, for example "Ages 0-2" and also print in dropdown.

This is the structure of the form array.

```
Array(
  [#info] => Array(
    [filter-tid] => Array(
      [operator] => tid_op
      [value] => tid
      [label] => Term
      [description] =>
    )
  )
  [tid] => Array(
    [#type] => select
    [#options] => Array(
      [All] => - Any -
      [0] => stdClass Object(
        [option] => Array(
          [367] => Ages 0-2
        )
      )
      [1] => stdClass Object(
        [option] => Array(
          [2378] => -Infant
        )
      )
    )
  )
)

```

This is the code I am using.

```
  if ($form['#id']== "views-exposed-form-quick-find") {
    $test = $form['tid']['#options'];
    foreach ($test as $tid) {
      // It prints "Array" and the "Trying to get property of non-object" message.
      print $tid->option;
    }
  }

```

I do not understand why the "Array" text repeats; it could be I am not pointing to right array.

How do I remove all children which do not have "age 12 - 14" (see "-" in the middle not from start)?

# Answer
What you obtain from that code is exactly what you should obtain.

The values you are getting from that control statement are:

* `$form['tid']['#options']['All']` is a string, and not an object. Trying to access `$form['tid']['#options']['All']->option` gives you a warning about accessing a property for something that is not an object.
* `$form['tid']['#options'][0]` is an object, and it doesn't raise an error, but `$form['tid']['#options'][0]->option` is an array, and `print $form['tid']['#options'][0]->option` converts it in a string. That is why you see *Array*.
* The same is true for `$form['tid']['#options'][1]`.

To remove the array element that contains `'Age 12 - 14'` from `$form['tid']['#options']`, I would use the following code.

```
foreach ($form['tid']['#options'] as $index => $tid) {
  if (is_object($tid) && !empty($tid->option) && is_array($tid->option) && in_array('Ages 12-14', $tid->option)) {
    unset($form['tid']['#options'][$index]);
  }
}

```

Notice that `in_array()` is case-sensitive. If you are searching for `'Age 12 - 14'`, but the string is `'age 12 - 14'`, the code doesn't remove the option.
> 0 votes

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


# Question
Title: Maintenance page is not loading anything in the head tag
I have a template based on the Basic theme.

I have created the `maintenance-page--offline.tpl.php`, and `maintenance-page.tpl.php` templates in my template folder, using a similar markup as in the `page.tpl.php` file.

These pages are not loading anything in the `<head>` tag.

What did I do wrong?

# Answer
Here is the full source of a typical maintenance-page.tpl.php

```
<?php

/**
 * @file
 * Default theme implementation to display a single Drupal page while offline.
 *
 * All the available variables are mirrored in html.tpl.php and page.tpl.php.
 * Some may be blank but they are provided for consistency.
 *
 * @see template_preprocess()
 * @see template_preprocess_maintenance_page()
 *
 * @ingroup themeable
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">

<head>
  <title><?php print $head_title; ?></title>
  <?php print $head; ?>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>">
  <div id="page">
    <div id="header">
      <div id="logo-title">

        <?php if (!empty($logo)): ?>
          <a href="<?php print $base_path; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
            <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />
          </a>
        <?php endif; ?>

        <div id="name-and-slogan">
          <?php if (!empty($site_name)): ?>
            <h1 id="site-name">
              <a href="<?php print $base_path ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a>
            </h1>
          <?php endif; ?>

          <?php if (!empty($site_slogan)): ?>
            <div id="site-slogan"><?php print $site_slogan; ?></div>
          <?php endif; ?>
        </div> <!-- /name-and-slogan -->
      </div> <!-- /logo-title -->

      <?php if (!empty($header)): ?>
        <div id="header-region">
          <?php print $header; ?>
        </div>
      <?php endif; ?>

    </div> <!-- /header -->

    <div id="container" class="clearfix">

      <?php if (!empty($sidebar_first)): ?>
        <div id="sidebar-first" class="column sidebar">
          <?php print $sidebar_first; ?>
        </div> <!-- /sidebar-first -->
      <?php endif; ?>

      <div id="main" class="column"><div id="main-squeeze">

        <div id="content">
          <?php if (!empty($title)): ?><h1 class="title" id="page-title"><?php print $title; ?></h1><?php endif; ?>
          <?php if (!empty($messages)): print $messages; endif; ?>
          <div id="content-content" class="clearfix">
            <?php print $content; ?>
          </div> <!-- /content-content -->
        </div> <!-- /content -->

      </div></div> <!-- /main-squeeze /main -->

      <?php if (!empty($sidebar_second)): ?>
        <div id="sidebar-second" class="column sidebar">
          <?php print $sidebar_second; ?>
        </div> <!-- /sidebar-second -->
      <?php endif; ?>

    </div> <!-- /container -->

    <div id="footer-wrapper">
      <div id="footer">
        <?php if (!empty($footer)): print $footer; endif; ?>
      </div> <!-- /footer -->
    </div> <!-- /footer-wrapper -->

  </div> <!-- /page -->

</body>
</html>

```

**Recheck your page against any missing variables.**
> 1 votes

# Answer
Your page.tpl.php template should include all the header, footer, etc code to build a regular page. So if you're missing any of that, I'd start by copying and pasting everything from the **page.tpl.php** file from your theme. Then just modify the middle content portions to create the maintenance page template.
> 0 votes

---
Tags: 7, theming, maintenance-mode
---


# Question
Title: How to programmatically create a product display(node) with reference to the product?
I want to programmatically create a product display, product and link them.

How can I do it?

# Answer
Try this function in a custom module

```
function commerce_display_product_create_method($product){
    $node = new stdClass();
    $node->type = 'product_display';
    node_object_prepare($node);

    $node->title    = $product->title;
    $node->language = LANGUAGE_NONE;

    $node->field_product['und'][0]['product_id'] = $product->product_id;
    node_save($node);
}

```
> 4 votes

---
Tags: commerce
---