# Question
Title: Form value not submitting for a function called from ajax
I have created a form for creating some beaches. In that I have to give the value of continents,country ,name of beaches. Names of the countries and continent are stored in the taxonomy table. so if the user selects the continets, by using ajax it displays the list of countries belonging to the continent. my code look like..

```
function iks_beaches_create($node, &$form_state) {

drupal_set_breadcrumb(array(
    l('beaches', 'beaches'),
    'Add New Beaches'
));
    $form['iks_beaches_continents'] = array(
    '#title' => 'Continents',
    '#description' => 'Taxonomy vocabulary defining Continents',
    '#type' => 'select',
    '#options' => iks_beaches_getTerms(variable_get(IKITESURF_BEACHES_CONTINENT, '')),
    '#required' => true,
    '#ajax' => array(
    'callback' => 'countryDisplay',
    'wrapper' => 'countryDisplay',
    'event' => 'change',
     ),
     );
    $form['countryDisplay']['iks_beaches_country']= array(
     '#type' => 'select',
     '#options' =>iks_beaches_getTerms(variable_get(IKITESURF_BEACHES_REGIONS, '')),
     '#title' => 'Country',
     '#required' => true,
     '#description' => 'Taxonomy vocabulary defining Country',
     );
     $form['regionDisplay']['iks_beaches_regions'] = array(
     '#title' => 'Regions',
     '#description' => 'Taxonomy vocabulary defining Regions',
     '#type' => 'select',
     '#options' => iks_beaches_getTerms(variable_get(IKITESURF_BEACHES_REGIONS, '')),
     '#required' => true,
     );

     $form['countryDisplay'] = array(
     '#type' => 'markup',
     '#prefix' => '<div id="countryDisplay">',
     '#suffix' => '</div>',
     );

```

the corresponding ajax function is

```
 function countryDisplay($form, &$form_state){
    $city = isset($form_state['values']['iks_beaches_continents']) ?        $form_state['values']['iks_beaches_continents'] : 'default';
    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'taxonomy_term')
                      ->propertyCondition('vid', variable_get('iks_beaches_countries'))
                      ->fieldCondition('field_continent', 'tid', $city)
                      ->execute();
    if(isset($entities['taxonomy_term']) && count($entities['taxonomy_term'])) {
    $countries = taxonomy_term_load_multiple(array_keys($entities['taxonomy_term']));
    foreach($countries as $coutry){
   $options[$coutry->tid]=$coutry->name;
   }
    }
    $form['countryDisplay']['iks_beaches_country'] = array(
         '#type' => 'select',
         '#options' => $options,
         '#title' => 'Country',
         '#required' => true,
         '#description' => 'Taxonomy vocabulary defining Country',
        );
return  $form['countryDisplay'];
}

```

But countries value is not displaying on form submit

```
function iks_beaches_create_submit($form, &$form_state) {
echo "<pre>";print_r($form_state['values']);echo "</pre>";exit; }

Array
(
    [iks_beaches_continents] => 673
    [iks_beaches_regions] => 783
    [location_name] => hdnffgh
    [description_location] => fgdh fgh fg hrt yry bnmbv mbcsd rty
    [travelling_details] => fh ty vcrsw t ytrywswe5
    [location_facilities] => ry  yuf d sdaf sa warewe svbvcber
    [tags] => e
    [longtitude] => 23.536343
    [latitude] => 45
    [images0] => 13803
    [images1] => 0
    [images2] => 0
    [images3] => 0
    [images4] => 0
    [images5] => 0
    [images6] => 0
    [images7] => 0
    [images8] => 0
    [images9] => 0
    [submit] => Publish Beach
    [form_build_id] => form-ZpuHlTPwSjJ2ElN_nPlSTsmHdQC6mmvSyKQOfMy4xvM
    [form_token] => n6vBuvZLJJNdcjdYERIsOm2REge8JoJMOSMmEuzpom8
    [form_id] => iks_beaches_create
    [op] => Publish Beach
)

```

# Answer
> 1 votes
Your mistake is a misconception about AJAX callback function. In Drupal, all permanent changes to a form needs to be done in form creation function, in your case `iks_beaches_create`. Function pointed in `['#ajax']['callback']` has the only purpose to determine what part of form is supposed to be updated. It can change `$form`, but these changes are one-time only, and preparing form to save values counts as a second time. Move all your form assembly logic to `iks_beaches_create`, so you could trim callback to

```
function countryDisplay($form, &$form_state){
  return  $form['countryDisplay'];
}

```

and it will work.

---
Tags: taxonomy-terms, ajax, forms
---


# Question
Title: Adding a dependencies in theme info file
Can I use dependencies\[\] = module name in the theme.info file? I want to create a drupal theme where I using some dependencies module, if I able to mention the dependencies in theme info it will easy to install the theme.

# Answer
> 9 votes
Nope, themes do not have such a directive in their info files.

Themes are supposed to be module independent. The "designed" way to do it is to move all module-dependent code to a custom module, and in relevant parts of your theme simply test for existence of data your custom module was supposed to provide.

---
Tags: 8, .info
---


# Question
Title: How to change the query for content type in d6 to d7?
I have a code in D6 which is as given below

In Drupal 6 for each content type we had seperate table like content\_type\_\[content\_name\] --------------Drupal 6---------------------

```
    SELECT nid, field_id_value, field_oid_value,field_sts_value
    FROM {content_type_bstatus} fsa INNER JOIN
    ( SELECT MAX(nid) as maxnid , field_oid_value  // subquery
      FROM {content_type_bstatus}
      GROUP BY field_oid_value
    ) fsb
    ON fsa.nid = fsb.maxnid
WHERE fsa.field_sts_value <> 'success'

```

---

In Drupal D7 we have seperate table for each fields within the content type like
field\_data\_\[field\_name\]
and content\_type is included only in nodes table
So, I am trying to implement the above code in D7

In Drupal D7 what i have tried is as follows but could not the exact solution

------------------Drupal 7---------------------------------- For the subquery above I have implemented the code below

```
SELECT MAX( entity_id ) , field_oid_value
FROM  `field_data_field_oid`
GROUP BY field_oid_value

```

How can I add the rest of code ..I have tried something which does not work
How can I write the code in d6 to d7 . I am using db\_query in d6 and would use db\_query or db\_select but
HOW CAN I USE THE CONTENT TYPE FIELDS WHICH ARE HAVING SEPERATE TABLES in d7 database structure??

# Answer
> 3 votes
You should add a new view by the UI. Then, you can display the generated SQL query, by activating the sql display below the views UI:

```
admin/build/views/tools (D6)
admin/structure/views/settings (D7)

```

You'll see live, what the sql query is :

Copy/Paste the sql and rearrange it

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


# Question
Title: "Notice undefined index" for an existing element in $form array
Basically This is my Array

```
 array(
        [product_id] => Array
        (
         [#type] => hidden
         [#value] => 39
        )
      )

```

and I am trying to get the value which is '39'

```
$cartId = $form['product_id']['#value'];

```

and yes I get the value without any issues, but in my site it gives me a notice saying "Notice: Undefined index: product\_id in ..."

This is my entire code

```
function MyModule_form_alter( &$form, $form_state, $form_id )
{
    $cartId = $form['product_id']['#value'];
    print_r ($form['#value']);
    if ($form_id == 'commerce_cart_add_to_cart_form_'.$cartId)
    {
        $form['add_to_wishlist']['#weight']= 49;
    }
}

```

any ideas how to fix this? because I couldn't figure the cause of it as it works well!

# Answer
> 4 votes
Your function is called for all forms in your Drupal. `$cartId = $form['product_id']['#value'];` is called outside `if`, so it's also executed on all forms. And most of them does not have `$form['product_id']` defined at all. Move that part inside `if` block.

---
Tags: commerce, forms, theming
---


# Question
Title: How to restrict node access based on user roles?
How can I allow only specific nodes to be displayed based on user roles?

Basically, I do not want to allow nodes to be accessed by users of some specific role.

# Answer
> 3 votes
Have you tried the content access module

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

# Answer
> 17 votes
What you're talking about is Drupal node access control, which is a huge subject.

The core's built-in support for node access control is rather coarse, and to control access to view a node by role, you must use some sort of node access control module.

There is a page at Drupal.org listing all node access modules, with a capsule review of each. I suggest you take a look at that page to see if you can find a suitable module to control access based upon roles.

When working with access control, it helps to understand how Drupal access control modules actually work, here is a quick description:

1. Users granted permission to administer nodes are never restricted by node access control. Users who do not have permission to View published content can never be granted access by a node access module. Only users who have 'access content' and not 'administer nodes' are eligible for the wild world of node access module control.
2. Node access control in Drupal is as a rule *additive*. This means that any module doing access control in accordance with the “the Drupal philosophy” should only allow access, not deny it. An administrator who wants to fine tune access to a node must first make sure nobody has access, and then add access grants to anyone that shall have access.

This means that it may be rather cumbersome to *restrict* access to individual with a module like Content Access, since you must start by denying *everyone* access, and then add it back to those nodes you don't want restricted. However, I think it is the best option if you really need to do it node by node. Its primary resolution is content types, but it allows you to override this for single nodes.

Unfortunately, you shall not be able to use Deny access since it only works on content types, with no override for individual nodes.

NB: Using more than one node access module is *not* recommended.

Note that if you can change your requirements so that you can use content type as your basic unit for node access control, then Deny access would be ideal. For instance, if you have a role "student" and you want to deny access to nodes with answers, then you can create a content type "Answer" (which can just be a clone of the default "Article") and Deny access will take care of protecting all nodes of the type "Answer" from being viewed by the role "student".

---
Tags: users
---


title: Drupal 7 .htaccess redirects

text:
# Question
Title: Drupal 7 .htaccess redirects
I'm trying to redirect some old urls to the new Drupal ones with .htaccess rules.

This works

```
Redirect 301 /oldurl http://mysite.com/new-url

```

But this gives me a Drupal error

```
Redirect /people/details.aspx?id=1234 http://mysite.com/name-surname

```

Is it possible to perform a redirect like this?

The errors I get are

```
Warning: array_flip() expects parameter 1 to be array, string given in DrupalDefaultEntityController->load() (line 178 of /var/www/includes/entity.inc).

Warning: Invalid argument supplied for foreach() in DatabaseCondition->compile() (line 1854 of /var/www/includes/database/query.inc).

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 2: SELECT revision.vid AS vid, base.uid AS uid, revision.title AS title, revision.log AS log, revision.status AS status, revision.comment AS comment, revision.promote AS promote, revision.sticky AS sticky, base.nid AS nid, base.type AS type, base.language AS language, base.created AS created, base.changed AS changed, base.tnid AS tnid, base.translate AS translate, revision.timestamp AS revision_timestamp, revision.uid AS revision_uid FROM {node} base INNER JOIN {node_revision} revision ON revision.vid = base.vid WHERE (base.nid IN ()) ; Array ( ) in DrupalDefaultEntityController->load() (line 196 of /var/www/includes/entity.inc).

```

My new rules begin before the Drupal rules of

```
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

```

As suggested I have tried redirecting to non clean URLS. This works

Redirect 301 /oldurl http://mysite.com/?q=new-url

But the URL stays as that which isn't any good as there will then be duplicate URLs of http://mysite.com/?q=new-url http://mysite.com/new-url

I tried

Redirect 301 /people/details.aspx?id=1234 http://mysite.com/?q=name-surname

But I still get the same errors as before

# Answer
> 2 votes
I've experienced that in Drupal 7 you must *not* rewrite to a clean URL destination, even if you have clean URLs enabled.

(This is possibly a duplicate of: Rewrite URL not working.)

---
Tags: 7, .htaccess
---


title: fb social comments

text:
# Question
Title: fb social comments
I am using fb social module and have enabled comments for all content types. All works fine cept i cant find a way to see all comments in one place to manage them all. I have to go to each node manually and check for spam etc. which takes huge amount of time.

So question is, how to check all comments on site generated by fb social comments ?

# Answer
> 2 votes
The problem is that those comments are actually not stored directly on your Drupal site (they're not in your database), so you can't currently list them using views or the regular comment administration screen.

You can look here about some additional information on how facebook plug-ins work: http://www.facebook.com/help/social-plugins (Especially that second paragraph "How do social plugins work?")

Essentially it explains that what you're seeing with the facebook comments plugin is an iframe on your website that is pulling data from facebook directly...

Hope that helps!

# Answer
> 2 votes
As of now, you can use the Facebook Comment Moderation tool available here: Facebook Comment MOderation tool, you will need to create a Facebook App by creating a new App from this page at Facebook: Facebook Developers.

Make sure that you add the "App Domains" under Basic Info and Site URL under "Website with Facebook Login" so that you can use the tool effectively.

Once you have configured it, all the comments will be visible at the page for the specific app that you have connected to the site.

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


title: Override orders page with a panel page

text:
# Question
Title: Override orders page with a panel page
How can I create a panels page for path admin/commerce/orders/\*

I've set a existing page override

And created the panel with selection rules.

It still doesnt work. Is this the correct way to do this?

# Answer
> 0 votes
**Deactivate** the view with the same URL so there is no collision. Clear the cache and it should work.

---
Tags: panels
---


title: How should I order custom blocks?

text:
# Question
Title: How should I order custom blocks?
I have two blocks in a custom module.

```
function THEME_block_info(){
    $blocks = array();

    $blocks['contact_info'] = array(
        'info' => t('Contact Info Block'),//admin ui block name
    );
    $blocks['contact_form'] = array(
        'info' => t('Contact Form Block'),//admin ui block name
    return $blocks;
}

function THEME_block_view($delta = ''){
    $block = array();

    switch($delta){
        case 'contact_form':{
            $block['subject'] = t('');
            $block['content'] = build_contact($delta);
            break;
        }
        case 'contact_info':{
            $block['subject'] = t('');
            $block['content'] = build_contact($delta);
            break;
        }

}

```

These blocks show up in the admin UI where we are able to order them. However, the order set in the admin UI doesn't work.

How should I set the order of these custom blocks to make it match the one sets in through the UI?

# Answer
You can use 'weight' for every block.

```
$blocks['contact_info'] = array(
  'info' => t('Contact Info Block'),//admin ui block name
  'weight' => 0,
);

$blocks['contact_form'] = array(
  'info' => t('Contact Form Block'),
  'weight' => 1,
);

```

I hope this will work for you :)
> 1 votes

---
Tags: theming
---


# Question
Title: Counting the number of rows returned from db_query() with the "SELECT" statement
How do I find the total number of rows returned in `db_query()` for the `SELECT` statement, or the equivalent of `mysql_num_rows()`?

I'm using MySQL.

# Answer
> 6 votes
If you look at the `db_result()` documentation for Drupal 6:

```
function db_result($result) {
   if ($result && mysql_num_rows($result) > 0) {
    // The mysql_fetch_row function has an optional second parameter $row
    // but that can't be used for compatibility with Oracle, DB2, etc.
    $array = mysql_fetch_row($result);
    return $array[0];
   }
   return FALSE;
}

```

I also saw that you could do this in Drupal 6:

```
$num_rows = db_result(
  db_query("SELECT COUNT(*) FROM {node} WHERE type = '%s'", $type->type)
);

```

It looks like you could simply do:

```
// Execute your query.
$result = db_query($your_query);
// Use mysql_num_rows() on the result set.
$num_rows = mysql_num_rows($result);

```

# Answer
> 6 votes
```
$res = db_query("SELECT title FROM {node} WHERE  status = '%d'",  1);

```

`db_query()` returns an object, and you can check the total number of rows using `$res->num_rows`.

# Answer
> 1 votes
It depends if you needs the number of rows before looping on the result set or not.

If you need it before, you generally make a `SELECT COUNT(*)` query with the same arguments as your first query and use `db_result()` to retrieve it.

If you need it after, just put a variable you'll increment during your loop:

```
$result = db_query("SELECT nid, title FROM {node} WHERE status = 0");
$total_rows = 0;

while ($row = db_fetch_array($result)) {
  //Process your results here

  //Increment your counter
  $total_rows++;
}

```

# Answer
> 1 votes
For Drupal 7 you can use

```
$result = db_query($query);
$result->rowCount();

```

---
Tags: 6, database
---


# Question
Title: Using Infinite Scroll module with Views paging: Detrimental to Google SEO?
I love using the Infinite Scroll module with Views. But does Google limit indexing to to only those first bunch of nodes which appear in the view?

I'm guessing that when using a regular pager, Google will dig deeper and index all subsequent pages in the view. But what does it do when ajax is used to move forward to the next batch of nodes as is the case with Infinite Scroll?

# Answer
> 6 votes
No it's not detrimental (well, not in the way you're thinking at least) - the standard pager links are hidden with infinite scroll, but still in the markup, so there's no problem from that perspective. Google will find and visit the subsequent pages as with a normal views pager.

The only question is whether Google apply some sort of penalty to the pages linked to *from* those hidden links. But that's something you'd need to get out of Google :)

---
Tags: views, ajax, paging
---


title: Dynamic view title from node title

text:
# Question
Title: Dynamic view title from node title
How to set a view title from page title dynamically, as if the page node title is About the Company I want the corresponding view title to be the same as node title.

any suggestions

# Answer
> 7 votes
Hope this will help you.

In Drupal 7 you can use **VIEWS CONTEXTUAL FILTER** for your requirement

Steps

* Add **VIEWS contextual filter** for node ID

item
* **Contextual filter settings** for node ID

+ Provide the **default argument** from the URL
    + Also **override** the **TITLE** and the **BREADCRUMB**
* Open browser and type **Base\_url/view\_path/NODE\_ID** you can see both the **TITLE** and the **BREADCRUMB** will be changed based on the **NODE ID**.

# Answer
> 0 votes
You should use the `THEME_preprocess_page(&$vars)` function in your theme's `template.php`

# Answer
> 0 votes
From the Context part of the panel page pick out **%node:title** and put it in the settings of the view.

---
Tags: views
---


title: RSS item list in block with dates

text:
# Question
Title: RSS item list in block with dates
I need a module which can fetch rss titles + publish dates and show them in a block/teaser. I tried aggregator and it does some of the job, but you cannot show publish dates in the list. The "read more" link should go to the original RSS or custom URL. It is important that all links link to the original url in the RSS and not to any view in drupal. Any suggestions for modules or other solutions?

# Answer
> 0 votes
If you're just trying to display an RSS feed (rather that import the entries into your site's actual database and then show in a view), then I would use Feedburner, which will help you get the html code to publish any RSS feed.

* Get a Feedburner account
* Create a new feed to manage, using the feed's URL on the front page screen
* Under the 'Publicize' tab, go to 'BuzzBoost' and activate that service at the bottom of the page
* Once it's activated, you can get the embed code. Just paste that code into a brand new block, and place the block whereever you want!

p.s. Further down that same page (the Publicize -\> BuzzBoost page, I just cut off my screenshot too early), you can customize the feeds settings, such as should you display a date, and if so in what format, and how many characters of the post teaser to display, etc. Play around with them to get the feed listing you want!

---
Tags: 7, feeds
---


# Question
Title: function name to be called by another module via drupal_alter?
I need to alter data of a contrib module, which does a call `drupal_alter('workbench_access_user', $access, $account);`.

How must my function look like? My module's name is workbench\_access\_crud\_by\_state.

Is the following OK? What about the parameters? I am confused about that data and context stuff.

```
function workbench_access_crud_by_state_workbench_access_user_alter($access, $account) {
  //do sth
  $bla = 'test';
  debug($bla);
}

```

It seems that my hook implementation is not being called at all and there are no error messages.

# Answer
> 8 votes
A hook implementation is always prefixed by the short name of the module implementing it; alter hooks need to have `_alter` appended. So, in your case, since workbench\_access\_crud\_by\_state is the machine name of the module, `workbench_access_crud_by_state_workbench_access_user_alter($access, $account)` is the correct signature for that alter-hook implementation.

As for the parameters, `drupal_alter()` accepts:

* `$type` is the type of the alter hook, without the `_alter` part; in your case, that is `workbench_access_user`
* `&$data` is the reference to the variable which contains the value to alter

There are other three parameters, which are optional and normally used to give context to the operation being performed.

In Drupal 8, the call to `drupal_alter()` is replaced with a call to `\Drupal::moduleHandler()->alter()`; in this case, the number of context parameters has been reduced to 2.

---
Tags: hooks
---


# Question
Title: Compare form input with user password in drupal 7
I'm trying to compare the user password from different databases so users of other drupal sites can also login. I'm switching from the main database to other databases and then trying to compare the passwoord input field to the stored hash value.

I did not found a answer on this site maybe because my situation is a bit different.

I did found this question and tried user\_check\_password() and user\_hash\_password() returns nothing and `user_hash_password` returns a new hash every time I run it so I don't think I can use that to compare that to the stored value in the database.

# Answer
> 0 votes
If I copy the user from the other database and save it to the main database user\_check\_password() does work. While I don't like this it does work…

If you have a better answer please submit it.

---
Tags: users
---


# Question
Title: Hide the email address when searching for users
When using the Drupal custom search form, and searching for users (search/user), the user's email address is displayed to administrator users. I want to hide it, even to the administrator users.

How can I do this?

# Answer
I think there is no such an option to hide email addresses from drupal system. You can create your own search-results.tpl.php in your theme or use `template_preprocess_search_results()` in your `template.php` to alter the user names.
> 2 votes

# Answer
Only user with the *Administer users* permission are able to search user by email and and view email on user search result. This permission also give them many right like editing the users' profiles, including seeing and editing their email address.

If you really want to grant this permission the some administrative users, allow them the access the other features requiring the *Administer users* permission but hide the email address in the user search results, then implementing `HOOK_preprocess_search_result()` (without the 's') in your custom theme or module is a good way to remove the email addresses. In your hook implementation, you will want to remove the email addresses from `$variables['title']` which contains the username followed by the email address. You can retrieve the user object in `$variables['result']['user']` and use `$variables['result']['module'] == 'user'` to check if the result is a user search result.
> 0 votes

---
Tags: search
---


# Question
Title: Set default selected radio button on webform
I have a standard contact page created using webform, which has a set of radio buttons. How can I make one of the radio buttons selected by default?

This quesion is similar, but it relies on the refering link, which I would rather not. Set default radio button on webform

# Answer
> 0 votes
There should be an option to set a default value when you go to edit that field in the webform. You have to set it to the "key" of the value you want selected by default. Your options should be listed as key|value under the field options.

---
Tags: 7, webforms
---


# Question
Title: What is the difference between t() and @Translation()?
When writing a (translatable) plugin in Drupal 8, you have to `use Drupal\Core\Annotation\Translation;`, and then wrap your value in `@Translation("value")`, however when implementing the `FormInterface`, you can use `t()` freely as you would in Drupal 7.

I found Annotation-based plugins on Drupal.org, but it just mentions the fact that you should use it, and the Doctrine reference doesn't seem to include `@Translation`

I assume it is because the plugin system is part of doctrine, and not part of core, whereas `t()` is -is this the correct assumption?

Basically, what is the difference between `@Translation();` and `t()` \- is it just because plugins are Doctrine based?

# Answer
> 9 votes
In short, `@Translation()` is a string used in annotations, meta data written in PHP comments and pertinent to a Drupal 8 class.

For example, this is the annotation for the PathItem entity field class.

```
/**
 * Defines the 'path_field' entity field item.
 *
 * @DataType(
 *   id = "path_field",
 *   label = @Translation("Path field item"),
 *   description = @Translation("An entity field containing a path alias and related data."),
 *   list_class = "\Drupal\Core\Entity\Field\Field"
 * )
 */

```

When Drupal loads the class annotations from a file, and it finds `@Translation("Content")` in the annotation, it creates an instance of the Translation class whose constructor receives the `"Content"` string; the instance is then used to get the value of `t("Content")`.

As for the differences, they are the following ones:

* `@Translation()` is a **string** used in class annotations: plain text that follows a specific format and it is written in PHP comments before the class that is being annotated. You cannot use it in code similar to the following one, except in the case a module defines a `Translation()` function. In that case, the `@` before it would be understood from PHP as the error control operator.

```
$form['salary'] = array(
  '#type' => 'textfield',
  '#title' => @Translation('Salary'),
  '#size' => 10,
  '#maxlength' => 10,
  '#description' => @Translation('Please enter a valid number'),
);

```
* `t()` is a **Drupal function**. It cannot be used inside class annotations like the following one, since it doesn't follow the syntax annotations follow. If it were used in an annotation as in the following, it would not cause Drupal to call `t()` and use its return value.

```
/**
 * Defines the 'path_field' entity field item.
 *
 * @DataType(
 *   id = "path_field",
 *   label = t("Path field item"),
 *   description = t("An entity field containing a path alias and related data."),
 *   list_class = "\Drupal\Core\Entity\Field\Field"
 * )
 */

```

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


# Question
Title: Taxonomy jump list in view in parent/child order
I have a taxonomy vocabulary of universities with their parent states. I then added this taxonomy field to the user profile so I could indicate what university the person was from. I'm trying to get this taxonomy vocabulary to display in an jump menu in a view (Drupal 7, Views 3) and honor the parent hierarchy, but the child/parent relationship is not being honored. This is how my jump list looks:

```
    California
    University of Georgia
    --Joe
    --Mary
    Georgia
    University of California
    --Mike
    --Jill

```

I'd like it to look like this:

```
    California
    --University of California
    ----Mike
    ----Jill
    Georgia
    --University of Georgia
    ----Joe
    ----Mary

```

I've read many possible solutions that suggest to add, "Taxonomy: Terms on node," but I don't even see that as an option. Any help would be greatly appreciated.

# Answer
You need to add "Content: Taxonomy terms on node" as a relationship.
> 0 votes

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


# Question
Title: Can Drupal built-in search or Apache Solr find comments on the site made with Disqus?
I'm evaluating comment systems and although I see disqus used in many cases I'm not sure if it is the best choice for me as I am uncertain that my site's *own* search system could show comments in search results.

Can Drupal built-in search or Apache Solr find comments on the site made with Disqus ?

Research I have shown so far is that Disqus has Search Engine Optimisation (SEO) -- for *external* search engines e.g. Google:-

But what about your own search system on your site, or using Solr for example. I'd prefer not to use Custom Google Search to search my site as I want control over how my results are shown.

So I'm looking for 2 answers for searching Disqus comments: 1) for the basic built-in Drupal search and 2) for SOLR.

Thank you.

# Answer
> 0 votes
Looks like it may be possible on the server side via the Disqus API PHP wrapper - I widened my answer outside of Drupal to get more input: https://webmasters.stackexchange.com/a/52159/3738

Though I still have concerns about not fully controlling the comment data and if the API changes. I'd have to see real benefits for our situation for Disqus to be able to outweigh these potential issues. Another issue is that of usability (UX/User Experience): having already logged in to the Drupal site, the user has to log in yet again to use disqus, unless the well supported Facebook login to the Drupal site can be "carried" into the Disqus login automatically. Though some user testing has revealed some would prefer the Disqus approach to be simpler.

---
Tags: 7, comments
---


# Question
Title: How to search on date ranges using apachesolr module?
I have a drupal site which have some events.

I am using apachesolr module for searching the site. Currently two fields are used for searching "keywords" and "location". Now I want to add the date field and when I click the search button it also query the search based on the date selected in the date field.

Suppose If I selected a 10/01/2011(m/d/Y) in the date field It should display the events with date 10/01/2011 or greater.

Any Idea?

# Answer
> 1 votes
Take a look at the Lucene search syntax, for dates use a filter query like `created:[2011-10-01T23:59:59Z TO 2011-10-31T14:11:00Z]`

# Answer
> 1 votes
Just came across this thread while searching for this as well and can offer an updated response for anyone using Drupal 7. If you're using Search API to search your Solr Index, Search API Date facets probably has the functionality you are looking for:

Or you can set this up as a range (possibly assuming years?) using the the Search API Search Ranges module:

---
Tags: 6, search
---


# Question
Title: Token authentication- "The form has become outdated" and rules issues
I'm using the Token Authentication and Privatemsg modules together. When a user receives an e-mail notification that they he/she has received a private message, I have placed a link (using a token provided by the Tokenauth module in a query string) that allows the user to log in and see the message.

At the bottom of the page is the message reply form. I would like the user to be able to reply via this form as well (without logging in, via token authentication). However, when I tested this, I received the following error:

> The form has become outdated. Copy any unsaved work in the form below and then reload this page.

A Google search revealed this helpful comment on drupal.org:

> So it seems you would have to either
>
> unset($form\['#token'\]) or $form\['#token'\] = NULL

Privatemsg has two message creation forms, the new message form and the reply to message form.

To fix the new message form, I added `unset($form['#token']);` to `hook_form_privatemsg_new_alter()` (new messages) and `hook_form_privatemsg_form_reply_alter()` (replies). I tested this and new private messages as well as replies can now be sent.

I then disabled caching for the privatemsg module so that the messages would always be refreshed.

However, I have a rule that is set to **Show a message on the site** ("Your message was sent to User X!") whenever a private message or reply is sent; this rule is not triggered when a private message is sent if the user is authenticated via Tokenauth even though the private message is saved to the database properly and displayed upon page refresh.

How can I make sure rules are still triggered when authenticated via Tokenauth?

# Answer
> 2 votes
From my point of view, it would seem Rules are not being triggered at all. You could, however, try invoking a rule manually by placing a rules\_invoke\_event() call within inside a custom form submit function.

Note that the `#submit` property on Drupal forms allow multiple submit handlers to be called for a single form.

In the `hook_form_privatemsg_new_alter()` and `hook_form_privatemsg_form_reply_alter()` form alters you have implemented you should be able to find and modify the `#submit` property. Just do something like:

```
// Implementation of hook_form_FORMID_alter().
patricks_form_privatemsg_new_alter($form, &$form_state) {
  ...
  $form['#submit'][] = 'patricks_privatemsg_submit';
  return $form;
}

```

Then in your submit handler you can use the rules\_invoke\_event():

```
function patricks_privatemsg_submit($form, &$form_state) {
   drupal_set_message(t('The form has been submitted.'));
   // Pass parameters for the variables provided by this event, as defined in hook_rules_event_info()...
   rules_invoke_event('privmsg_foo_rule', $foos, $barf, $bam);
}

```

If for some reason you get a rules\_invoke\_event() function not found error, just add a module\_load\_include() to your submit handler before invoking the rule.

---
Tags: forms, rules, users, privatemsg
---


# Question
Title: Please tell me what drupal table the block php visibilities settings is stored at
Within a block I have configured under the "Visibility settings" and "Show block on specific pages" I have put in PHP code that determines where this block is displayed within a page or not via a returned true or false. I have it working correctly but then I added additional restrictions within the PHP but I must have put in a syntax error that caused the site to go down saying "Temporarily Unavailable".

I need to be able to change the PHP code back to the working version but I don't know what drupal table the block PHP code is stored. Please tell me what drupal table the block php visibilities settings is stored at.

# Answer
> 2 votes
The php code should be stored in the *pages* field of the *block* table, and it should not be serialized.

The *visibility* field can have one of three values:

* BLOCK\_VISIBILITY\_NOTLISTED (0),
* BLOCK\_VISIBILITY\_LISTED (1), or
* BLOCK\_VISIBILITY\_PHP (2).

In the case of the first two, the *pages* field will contain a text list of the notlisted or listed pages for the block. in the case of the third, the field will contain the php code.

---
Tags: blocks
---


# Question
Title: Possible to make admin's flags worth more points?
I'd like the admin's flagging of a node to carry more clout than with regular users. Is it possible to either;

* Insert the count into the mysql database as a number larger than 1 whenever admin flags a node.
* Allow flag counts to be additive, ie: Admin can flag a node many times with each count being added to the total.

Perhaps it can be done using rules and php? If so what would be the procedure in rules?

# Answer
Flags work like an on/off switch. Depending if the Flag is **global** or not, that on/off switch can apply to every user (each user can have a separate room w/ the lights on or off), or globally - every user is in one room, with only one light bulb, and one light switch.

Basically what you're asking is: *is it possible to turn on the lights on twice?*

No. In our light bulb analogy, that Flag switch doesn't come with a dimmer option ;)

What Rules allow you to do is aggregate the count of the Flag "votes" by multiple users (when not using global flags), and execute an action based on the sum of user "flags". But that is not what you're looking for.
> 2 votes

---
Tags: users, flags
---


# Question
Title: How can I implement a RESTful API in Drupal?
Can any one please let me know what modules are available to implement a REST API?

So far I've only found the Redmine REST API module, which is used for Redmine.

# Answer
> 2 votes
For a REST API implementation on Drupal, use the Services module.

> A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

---
Tags: 8
---


title: Taxonomy term pages with multiple views

text:
# Question
Title: Taxonomy term pages with multiple views
I currently use only one view with path `taxonomy/term/%` and without any vocabulary verification.

However, I would like to create two views: news and products (to implement different themes) linked to two vocabularies (1 per 1): news\_categories and product\_categories.

news\_categories looks like:

> * category 1
> * category 2

product\_categories

> * category 1
>
> + subcategory 1
> * category 2
> * category 3
>
> + subcategory 1

I don't want to allow displaying terms which are not from this vocabularies. In addition I use pathauto to generating path, which sometimes are a few level dept.

I found a module called Taxonomy Views Integrator, but I'm not sure it's in 100% stable, so my question is that you are any other ways to handle many taxonomy term pages by views?

# Answer
> 5 votes
Required modules: Views, Pathauto, Simple hierarchical select, Taxonomy Views Integrator.

Create content type "food".

Create vocabulary "food" add some example terms:

```
+ fruits
  - apples
  - orranges

+ vegetables
  - carrots
  - potatoes

```

**Pathauto settings**

go to: `admin/config/search/path/patterns` and set the taxonomy term paths:

pattern for all food paths -\> `[term:vocabulary]/[term:parents:join-path]/[term:name]`

Thanks to this pattern our food paths will look like: `food/fruits/apples` and may contain more than one parent, for example: `food/parent1/parent2/parent3/child`

Go to: `admin/structure/taxonomy/food` and check if all paths are setted up correctly. If not, edit them and check `Generate automatic URL alias`.

**Views**

Create view showing taxonomy terms from `food` vocabulary and add these three displays:

```
Page: Title: "`All food content`"

```

Path: `/food`

Relatonship: `Taxonomy term: Content using Food terms`.

```
Page: Title: `Food category`

```

Path: `/food/%`

Relatonship: `Taxonomy term: Content using Food terms.`

Contextual filter: `(field_food_terms) Content: Has taxonomy term ID (with depth)`

contextual filter settings: `depth = 1` (use: this page override)

Override title: `Food category - %1` This means, if we go to `food/fruits`, all items one level below `fruits` will be shown (all fruits)

```
Page: Title: `Food subcategory`

```

Path: `/food/%`

Relatonship: `Taxonomy term: Content using Food terms.`

Contextual filter: `(field_food_terms) Content: Has taxonomy term ID (with depth)`

contextual filter settings: `depth = 0` (use: this page override)

Override title: `Food subcategory - %1`

There is no terms below, if we go to `food/fruits/apples`, all items with term name `apples` will be shown (only apples)

**Use Views to override term paths**

At the end you need to go back to: `admin/structure/taxonomy/food` edit each term and choose `Use view override.`

---

For each term you need to specify which view will be used to override, it's the main disadvantage of this solution.

## **Results**

---

---

---

## An example of article and blocks with relationship to the taxonomy.

# Answer
> 1 votes
Ok, maybe I don't fully understand the question.

**Goal**
Let's just assume the goal is to display, on taxonomy/term/%, a different view depending on which vocabulary that term is in. (whether there are pathauto aliases for this path, does not matter at all.)

**Views page + contextual filters?**
If you simply override the path with Views, this will be one views display for all terms, no matter which vocabulary - because they all share the taxonomy/term/% path.

**Alternative I: Taxonomy display module**
The Taxonomy display module allows to customize the "associated content" display on taxonomy term pages. It allows to use a different view per vocabulary.

On "manage display" for the term, enable "Custom display settings" for the "Taxonomy term page" view mode, then for this view mode, configure the "Term page display".

**Alternative II: Display Suite + Taxonomy display + dynamic field**
What I often do instead is use Display Suite, and use the "Dynamic fields" feature. I think you need to enable ds\_extras, ds\_ui (both shipped with Display Suite) and work your way through the settings. Ideally, you should also enable views\_content ("Views content pane").

This allows to not just have a dedicated views display per vocabulary and view mode, but it also allows to freely place one ore more such views in the ds layout, along with other fields.

The Taxonomy display module will only be used to hide the core list of associated content. Possibly this could be achieved with a custom module, up to you.

Quick guide:

* Download taxonomy\_display, ds (7.x-2.\*) and views. Enable ds, ds\_extras, ds\_ui, views\_content, taxonomy\_display.
* Create a view with a "Content pane" display and an argument taking the taxonomy term tid. This has more to it than I currently remember, so good luck figuring it out :)
* Go to admin/structure/ds/fields
* Add a dynamic field, name it whatever you want, e.g. "Tagged content". As the entity type, name "Taxonomy term"
* Go to admin/structure/taxonomy/categories/display (where "categories") is your vocabulary machine name)
* Enable "Use custom display settings for the following view modes: Taxonomy term page". Save.
* Go to admin/structure/taxonomy/categories/display/full
* In "Term page display" vertical tab at the bottom, set Term display = Core, Associated content display = Hidden. Breadcrumb and feed is up to you.
* In "Layout for categories in full", enable "One column" (under "Display suite"). Save.
* Move the "Tagged content" up in the "Content" region.
* On the dynamic field, click the cog-wheel icon, then "Select content", then in the dialog under "View panes" you can select the views display you just created. Configure the argument (Term id from url). Save.
* Repeat for other vocabularies.
* Make sure you disable the usual page view overriding taxonomy/term/%.

**Alternative III: Taxonomy display + Display suite + Views content DS**
The Views content DS is a bit more convenient than Display suite dynamic fields. Up to you.

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


# Question
Title: Is there a way for a rules execute PHP action to return a value?
I would like to be able to stuff the result of the PHP code into a rules variable. Is this possible?

# Answer
I think that's not possible. More info here: http://drupal.org/node/1415628
> 1 votes

# Answer
For achieve this you can save your result in some where(**(variable, session,static variable etc**) and in anotherside use your variable, if you return value is array or object just need serialize it and in anotherway unserialize it.

maybe this code take some idea to you in rules in php execution

```
 global $user;
 $myreturn=array (....);
variable_set('return-'.$user->uid,serialize($myreturn));

```

and in another part

```
 global $user;
 $yourvariable=unserialize(variable_get('return-'.$user->uid));

```

**This is just trickly way and maybe another solution be better for achieve this question**
> 1 votes

# Answer
For text, you can use the Add a Variable action and then set the value to use php evaluation.
> 1 votes

---
Tags: rules
---


title: how to convert Taxonomy terms to nodes

text:
# Question
Title: how to convert Taxonomy terms to nodes
**Short Question :**

* is there a way convert all of one vocabulary taxonomy terms to one content type nodes ? And switch all term refrences in the database to entity references to the converted term/nodes?

**Details :**

* A long time ago, I have made a website for music and i used the core terms for local singers and performers now i want to use entity reference for a better content control user interface.

the website has one **content type** "Audio File" The content type fields are :

+ **Audio file** : file upload
    + **Performer** : term reference of vocab "Performers"

The taxonomy term fields are -Vocab : "**Performers**:

+ **Performer Name** : title field.
    + **Performer Portrait** : Image upload field

the site is running and there is already more than 150 singers and over 1000 audio files. So doing this manually is almost impossible. I think i should use migrate module but i don't know how to use it and it seems very complicated !

Thanks :)

# Answer
Export taxonomy using https://drupal.org/project/taxonomy\_csv

Then use excelent https://drupal.org/project/feeds module and create node importer and map fields accoridingly.
> 5 votes

# Answer
I think there is not a "ready-to-use" waay to do this.

You could create a custom module. Supposing that you have already created and configured:

* the new content type "performers" with all fields (with a field called "old id" there will have the "old" tid from the term
* the "audio" content type with entity reference to Performers

you could create a module that:

* get all terms from the vocabulary
* for every term you create a node "performer", with values from terms and using the tid for the field "old id"

After this you could:

* get all nodes of type "audio"
* for every node you get the "tid" value of the performer and with views or entity\_query\_field search for the "performer" node that has "old id" = "tid"
* assign the nid of the performer to the entity reference in "audio"
* save the "audio" node

These could be the "logical" process of the module.
> 3 votes

---
Tags: taxonomy-terms, entities, migrations
---


# Question
Title: Display Original Image on Node View when using Image Crop Module
I have an image field on a content type using Image with Cropping.

The cropped image is used on a block view and a page view, but on the actual single item node view I need to have the original full image.

Any advice would be great.

# Answer
I found this, not so elegant but it works.

In the theme file (page--TYPE.tpl.php) use the following code to get the file object:

```
$file = _imagefield_crop_file_to_crop($node->FIELD["und"][0]["fid"]);

```

This will load the original file used for the cropping.
> 1 votes

# Answer
If the Image field does not support a "un-cropped original" style on the field's View page, then it looks like a second image field (without crop) would be in order. You would then use the un-cropped field on the single node view, and the cropped one in the view and block.
> 1 votes

---
Tags: 7, media
---


# Question
Title: How do I alter the output of a field using a views handler
Currently I'm uning Views PHP to reformat some fields in a view. in the documentation of views it says

> While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is highly advisable to use regular handlers and plugins when available (or even to create one yourself).

In my particular use case, I'm trying to re-format the output of a field that is being loaded by relationship. How would I create a views handler, or a views plugin that does this?

# Answer
You add your custom views handler using `hook_views_data()` like so:

```
function mymodule_views_data() {
  $data = array(
    ['my_table_name'] => array(
      'my_field_alias' => array(
        'real field' => 'my_field_id',
        'group' => t('Testing'),
        'title' => t('Testing'),
        'help' => t('Testing a thing.'),
        'field' => array(
          'handler' => 'my_custom_views_handler_test',
          'click sortable' => TRUE,
        ),
        'sort' => array(
          'handler' => 'views_handler_sort',
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_string',
        ),
        'argument' => array(
          'handler' => 'views_handler_argument_string',
        ),
      ),
    ),
  );

return $data;
}

```

And then you declare your custom views handler:

```
class my_custom_views_handler_test extends views_handler_field {
  /**
   * Render some stuff.
   *
   * Data should be made XSS safe prior to calling this function.
   */
  function render($values) {
    $value = $this->get_value($values);
    return $this->sanitize_value($value);
  }
}

```

Almost all changes you'll be wanting to make should be made in an override of the render function.
> 2 votes

---
Tags: entities, views
---


title: Can I add more blocks in a View page?

text:
# Question
Title: Can I add more blocks in a View page?
I have a page that I created by View, I tried to create a template by creating `node--view_page_machine_name.tpl.php`, but it didn't work, the page did not change to this new template style.

How can I add more blocks/regions into a view page? Thanks.

# Answer
In your view, under advanced there is a link called "Theme Information". If you open that up, there will be a list of all the different parts of the view that can be themed and a list of all the theme suggestions for each listed in order of broad to narrow.

You can create a theme file and naming it appropriately from the list of files in the theme information section. Once you've created the file, click on the "Rescan template files" button and the file you've created should be bold in the list.

Save the view and clear the cache.
> 5 votes

# Answer
But you don't mean the big Add button in your view which gives you the possibility to add blocks, attachements and else to your view, do you?

Be careful when you add blocks that way, you may want to override the display type, which can be chosen top left the moment you edit/add/delete a field, a filter criteria or else. Otherwise the changes will be applied to all your display types in that view.

Anyhow, I prefer to create an empty page first (via Content \> Add Content \> Page) and then I plant views blocks as much as I need on that page. So when I create a view I choose Block instead of Page.

And then when I'm done with creating my view I go to Structures \> Blocks to choose the region and the site (the site I created first) where that block (views block) then should be displayed.

That way it's much easier I think to edit views 'cause now I have these Contextual Links on my page and when I hover over them they provide a quick link to edit the block or edit the view immediately.
> 1 votes

# Answer
Consider using panels :) https://drupal.org/project/panels. And please change title to page instead of pager, which is a very different thing!
> 0 votes

---
Tags: views, nodes, theming
---


# Question
Title: Integration of Microsoft Exchange server with Drupal
I am using Drupal 7.

I would like to integrate Microsoft Exchange server with my Drupal site, so that I can login with the credentials of Exchange server and can also integrate with other features of Exchange server like Events, Calenders etc.

I checked one module called LDAP(Light Weight Directory Access Protocol), and it is working with other servers, But i don't know whether I can use this integration with Microsoft Exchange server.

# Answer
> 1 votes
All recent version of Exchange (2000+) require and Active directory for the authentication and authorization. Active Directory is integrated via LDAP.

---
Tags: authentication-authorization
---


# Question
Title: How to display custom block without default wrapped html around
I have custom module with new block. When this block is displayed, the output is wrapped with html tags from block.tpl.php template:

```
<section id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

```

I would like to display only content without the wrapped html around. I can accomplish this by overriding the block.tpl.php file in the theme, however. This requires me to go into every possible theme and override the template file every time installing the module. How to avoid that? How to display only content of the custom block from custom module without overriding template file? Is there some attribute that i can set in the block render array like #theme\_wrapper?:

```
$block['content'] = array(
               '#markup' => '<div>Hello World!</div>',
              // '#theme_wrappers' => array('attempt_to_override'),
)

```

I was thinking the 'theme\_wrappers' attribute can be used, but i wasn't able. Thank you for any help

# Answer
> 1 votes
I don't actually think this is possible using a block; however, take a look at hook\_block\_view() and hook\_block\_view\_alter().

Those MAY do what you want. They allow you to alter the contents of a block before it is displayed; however, it is likely that you'll still end up with the contents of the block 'inside' the template's block boiler plate.

Keep in mind that it's up to the theme to decide how blocks are styled so the theme markup boilerplate is there by design.

If you need to inject html into specific areas of the site / page you might need to do something differently.

In that case hook\_page\_build() or hook\_page\_alter() might be a better choice.

---
Tags: 7, theming
---


# Question
Title: Redirect from one URL to another based on user role
I have two pages on my site (created using views) that I would like to hide from anonymous users by redirecting them to a custom access denied page. i.e. If an anonymous user tries to go to the page "wolfdogs/deceased" they are redirected to "access-denied". I found this bit of php that looks promising:

```
if (in_array('anonymous user', array_values($user->roles))) {
  $dest = $_SERVER['REQUEST_URI'];
  $dest = substr($dest,1); //this removes preceding slash from string
  $path[]='vote'; //example paths to hide from anonymous users...
  $path[]='volunteer';
  $path[]='papers-list';
  $path[]='event-register';
  $path[]='replays-list';
  $path[]='how-to-upgrade';
  $path[]='membership-renewal';

  if (in_array($dest, $path)) {
    return drupal_goto('members-only'); //this line re-directs to custom access denied page.
  }
}

```

Ideally I would like put this into a block, and then put the block on the "hidden" pages. However, it was written for Drupal 6; I don't if it works with Drupal 7, and I am unsure how to implement it into a block.

# Answer
> 2 votes
You could also try the Path Access module to restrict access to certain paths based on the users role.

# Answer
> 5 votes
You should be able to restrict the access to the view right from the view edit page. When you are editing the view, change the "Access" setting under the Page Options to allow access based on the Role Authenticated User, which will display an Access Denied page for any anonymous users.

---
Tags: 7, uri, redirection
---


# Question
Title: Where in the database does fieldset and field instance info live?
Background: I'm writing a module that will hopefully make reverse-engineering specs for site audits easier. (If you're interested, you can see the Topograph module-in-progress on my Github account.)

Basically it's a bunch of byzantine views that use custom handlers to pull things like serialized data out of the DB to display stuff like nodetype settings to the admin user.

I'm having a lot of trouble finding certain things, though. Fieldset info is a major one, as well as settings like whether the field is required. I'm not finding it in the blob of data pulled from the `{field_config_instance}` table (though I might be overlooking it). Can someone point me to where this info can be retrieved per nodetype/field instance?

# Answer
> 2 votes
Whether a field is required or not can vary by content type (ie, the bundle). I am pretty sure you need to use `field_info_instances($entity_type, $bundle_name)`. You can then use `field_info_field($field_name)` on the results. Something like:

```
$fields_info = field_info_instances('node', $bundle);

foreach ($fields_info as $field_name => $instance) {
  $field_info = field_info_field($field_name);
}

```

`dpm()` both the `$instance` and `$field_info`. Everything you need should be in those two variables. This is a snippet from a dynamic exporter I have.

---
Tags: entities
---


# Question
Title: Can't find my website page listed under admin/structure/pages
Driving me crazy! I have a website page: http://www.randymtrader.com/contact that I cannot find anywhere in drupal admin/structure/pages. There is nothing with the path /contact. Where else could it be listed? I need to edit the page. Any ideas?

Thank you!

# Answer
> 4 votes
The `/contact` page is provided by the Contact module, which you must have enabled. It displays the `contact_site_form` form, which is declared in `/modules/contact/contact.pages.inc`.

Configuration options for this form can be found at the `site.com/admin/structure/contact` URL.

If you're looking to change form structure, you may need to create a custom module and implement hook\_form\_alter(). If you're after changing layout, you may be able to get away with adding/moving blocks (in which case have a look at Context for more options than the core blocks page), but more likely should use something like Panels to create a new page and insert a new contact block on it. You may want to have a look at the Webform module, which can be used to create & configure forms through the UI.

---
Tags: chaos-tool-suite
---


# Question
Title: Including JS after the JS specified in theme info file
The goal is to include js files for custom block from custom module after the JS specified in the themes.info file. From the moduleName.module

```
function moduleName_block_view($delta = ''){
  $block = array();
  switch($delta){
    case 'contact_form':{
                $block['subject'] = '';
                $block['content'] = array(
                    '#markup' => build_contact($delta),
                    '#attached' => array(
                        'js' => array(
                            'http://somepath/0.0.2/contact-0.0.2.min.js' => array(
                                'type' => 'file',
                                'weight' => 1000,
                            ),
                            drupal_get_path('module', 'moduleName').'/js/contact-config.js' => array(
                                'type' => 'file',
                                'weight' => 5,
                            ),
                        ),
                    ),
                );
...
return $block;
}

```

The weights work for the two JS files within the custom block as specified here. Problem is that, i am unable to make these js files be imported after the js files specified in theme.info file. How to make these file import after the theme js? Thank you for help

# Answer
You can specify the `#scope` attribute to control where the JS gets added. For example, you could place it in the footer, which (more likely than not) would come after your theme's JS:

```
'#attached' => array(
  'js' => array(
    'http://somepath/0.0.2/contact-0.0.2.min.js' => array(
    'type' => 'file',
      'weight' => 1000,
      'scope' => 'footer',
    ),
    drupal_get_path('module', 'moduleName').'/js/contact-config.js' => array(
      'type' => 'file',
      'weight' => 5,
      'scope' => 'footer',
    ),
  ),
),

```

Alternatively, you could implement hook\_js\_alter() to change the 'final' ordering of the JS files added through `#attached`, `drupal_add_js()`, .info files, etc.
> 3 votes

---
Tags: 7, theming
---


title: Add field from rendered entity in view

text:
# Question
Title: Add field from rendered entity in view
I would like to display the body summary of a single, specific article in the header of a view using the "entity: rendered entity" option and selecting "content." I can display the full content of the article and the teaser, but I don't see a way to access the article's fields individually. I don't want to display the title / author information. (My (probably wrong) guess is the "tokens" option, but upon selecting it, I see no place to utilize the tokens.) Insight appreciated. Thanks!

# Answer
If you can display the Full & Teaser view modes, then you can display any custom view modes, too.

Install the Display Suite module and create a new 'view mode' - let's call it "body" - and on the same screen, make sure it's applied to nodes. Then go to Structure -\> Content Types -\> Article (or whatever your content type is called) -\> Manage Display, and you will see three tabs: Default, Teaser and Body (the view mode you just created). Scroll to the bottom of the page and choose a layout (single column should do the trick), and then drag the body field into the appropriate region. Don't forget to save the form after rearranging fields.

At this point you can go into your view, and select the new 'Body' view mode where the options for 'Full' and 'Teaser' were showing up earlier.
> 2 votes

---
Tags: views, entities
---


# Question
Title: Taxonomy terms from multiple vocabs on a single line
I migrated from Drupal 6 to Drupal 7 and used the same theme, now the "post tags" (taxonomy terms from multiple vocabularies) aren't displayed on the same line as shown below.

How to get these into a single line.

# Answer
This change in my `style.css` did the trick :

```
.node .taxonomy,
.node .field-type-taxonomy-term-reference {
  font-size: 0.8em;
  line-height: 100%;
  display: inline;
  /* padding-left: 1.5em; */
}

```
> 1 votes

---
Tags: theming, taxonomy-terms, entities
---


# Question
Title: How do I get the category links as I had them in Drupal 6, before migrating the site to Drupal 7?
I am migrating my Drupal 6 site to Drupal 7. I have vocabulary/category links like http://www.megaleecher.net/category/12.

How do I replicate this with Drupal 7? I exported the below view to Drupal 7, but it does not work.

```
$view = new view;
$view->name = 'vocabulary';
$view->description = '';
$view->tag = '';
$view->base_table = 'node';
$view->human_name = '';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'time';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Sort criterion: Node: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Argument: Taxonomy: Vocabulary ID */
$handler->display->display_options['arguments']['vid']['id'] = 'vid';
$handler->display->display_options['arguments']['vid']['table'] = 'vocabulary';
$handler->display->display_options['arguments']['vid']['field'] = 'vid';
$handler->display->display_options['arguments']['vid']['style_plugin'] = 'default_summary';
$handler->display->display_options['arguments']['vid']['default_argument_type'] = 'fixed';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['defaults']['query'] = FALSE;
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['path'] = 'category/%';

```

# Answer
> 0 votes
D2D module did not established the nid-term relationship when importing, so while we had the nodes and terms imported successfully there was no pointer relating the two which resulted in no results for category/vocabs.

Used Drush site-upgrade and things imported correctly.

# Answer
> 0 votes
check this migrate and migrate\_extras module, it is very handy framework to migrate content, you can easily migrate

* node
* taxonomy/categories
* users

Edited:

Let me clarify with your scenario, while migrating from source(D6) to destination(D7),

you have to define source field and destination fields as shown in below code sample.

first you have to migrate Taxonomy terms from D6 to D7. later on you have to migrate node entity, while preparing node migrate class, you have to migrate term reference field as it is. so that in prepareRow function we can replace with old term\_id with new term\_id which is already migrated.

For example see sample code.

```
abstract class JiveBlogMigration extends Migration {

public function __construct() {
// Always call the parent constructor first for basic setup
parent::__construct();

// With migrate_ui enabled, migration pages will indicate people involved in
// the particular migration, with their role and contact info. We default the
// list in the shared class; it can be overridden for specific migrations.

  }

}

/**
 *
 * Jive Blog Post Information Migration class.
 *
 */
class JiveBlogPostMigration extends JiveBlogMigration {

  public function __construct() {
  // The basic setup is similar to BeerTermMigraiton
  parent::__construct();
  $this->description = t('Jive Blog Post Data Migration.');
  $this->map = new MigrateSQLMap($this->machineName,
                array('jive_blog_post_id' => array(
                        'type' => 'int',
                        'not null' => TRUE,
                        'description' => 'Jive Blog Post ID.'
                    )
                ),
                MigrateDestinationNode::getKeySchema()
   );

// Added ContainerType field for mapping
$query = db_select('migrate_jive_blog_post', 'mjbp')
        ->fields('mjbp', array('jive_blog_post_id', 'jive_user_id', 'jive_group_id', 'jive_container_type', 'subject', 'body', 'permalink', 'minorEdit', 'creationDate', 'modificationDate', 'status', 'displayName', 'blogstatus', 'feedEnabled', 'feedFullContent', 'pingOverride', 'pingServices', 'trackbacksEnabled', 'trackbacksModeration', 'trackbacksNotification')); //SELECT the fields from node
//generate the count for the number of records to be imported
$count_query = db_select('migrate_jive_blog_post', 'b');
$count_query->addExpression('COUNT(jive_blog_post_id)', 'cnt');
$source_fields = array(
    'jive_blog_post_id' => t('The id of a particular document in the jive system'),
    'term_data' => t("The taxonomy terms associated with the node"),
    'jive_container_id' => t("The social group or space id associated to the node decided in prepareRow()."),
);
$this->source = new MigrateSourceSQL($query, $source_fields, $count_query);

// Set up our destination - nodes of type blog
$this->destination = new MigrateDestinationNode('blog');

// Mapped fields
$this->addFieldMapping('title', 'subject')
        ->description(t('Mapping beer name in source to node title'));

// References to related objects (such as the author of the content) are
// most likely going to be identifiers from the source data, not Drupal
// identifiers (such as uids). You can use the mapping from the relevant
// migration to translate from the old ID to the Drupal identifier.
// Note that we also provide a default value of 1 - if the lookup fails to
// find a corresponding uid for the aid, the owner will be the administrative
// account.
$this->addFieldMapping('uid', 'jive_user_id')
        ->sourceMigration('JiveUserAccount')
        ->defaultValue(1);
// Mapping for Tags
$this->addFieldMapping('Tags', 'term_data');

// Additional mapping fields
$this->addFieldMapping('field_displayname', 'displayname');
$this->addFieldMapping('field_pingoverride', 'pingoverride');
$this->addFieldMapping('field_pingservices', 'pingservices');
$this->addFieldMapping('field_feedenabled', 'feedenabled');
$this->addFieldMapping('field_feedfullcontent', 'feedfullcontent');
$this->addFieldMapping('field_status', 'blogstatus');
$this->addFieldMapping('field_tbmoderation', 'trackbacksmoderation');
$this->addFieldMapping('field_tbnotification', 'trackbacksnotification');
$this->addFieldMapping('field_minoredit', 'minoredit');
$this->addFieldMapping('field_trackbacksenabled', 'trackbacksenabled');

//This is for path
$this->addFieldMapping('path', 'permalink');
$this->addFieldMapping('pathauto_perform_alias')
        ->defaultValue(0);

// Group mapping for space, personal, group associated Blog posts
$this->addFieldMapping('og_groups', 'jive_container_id');

$this->addFieldMapping('body', 'body');
$this->addFieldMapping('created', 'creationdate');
$this->addFieldMapping('changed', 'modificationdate');
$this->addFieldMapping('status', 'status');

// Unmapped destination fields
$this->addUnmigratedDestinations(array('revision_uid', 'teaser', 'revision', 'language', 'promote', 'sticky',
    'field_group_sticky', 'field_content_images', 'field_featured_content',));

//specify the unmapped source fields.
$this->addUnmigratedSources(array('jive_group_id', 'jive_container_type'));
}

public function prepareRow($current_row) {

 $source_id = $current_row->jive_blog_post_id;

 //populate all the tags associated with a particular node using the getDrupalTags() method
 //that returns an array of all the tags associated with a particular node.
 $term_data = JiveMigrationUtilities::getDrupalTags($source_id, 38); //38 is the object type for the blogpost in jive.
 if ($term_data) {
  $current_row->term_data = $term_data;
 }
 if ($current_row->jive_group_id != 'NULL') {
  $current_row->jive_container_id = JiveMigrationUtilities::getDrupalContainerNid($current_row->jive_container_type, $current_row->jive_group_id);
  }
 return TRUE;
}

}

```

Usual flow of migration module, it will create a mapping table for each migration class like migrate\_map\_jiveblogmigration, it contains sourceid1 and destid1 columns. for example D6 nid is as sourceid1 and D7 nid is as destid1.

in prepareRow function you can write a logic to replace old term\_id with new term\_id for each row of node migration.

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


# Question
Title: Drush and database credentials from external sources
For some specific automation reasons, I use the following snippet in settings.php rather than defining db credentials directly in it.

```
$databases = array(
  'default' => array(
    'default' => array(
      'database' => $_SERVER['DB_NAME'],
      'username' => ini_get('mysql.default_user'),
      'password' => ini_get('mysql.default_password'),
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

And when I try to use drush, it won't pick up database credentials. How can I give the right database credentials to Drush? Can I define something in drushrc files per project?

The following is what I get from `drush status`.

> Drupal version : 7.22
> Site URI : `http://default`
> Database driver : mysql
> Database hostname : localhost
> Database username :
> Database name:
> Default theme : garland
> Administration theme : garland
> PHP configuration : /etc/php5/cli/php.ini
> Drush version : 5.4
> Drush configuration :
> Drupal root : /home/oep/www/dev/docroot Site path : sites/default
> File directory path : sites/default/files

# Answer
> 1 votes
As you can see, drush is run from command line interface, so it uses `cli/php.ini` and not regular one. If you feel like keeping password and username in ini file, you need to make sure there are synchronized between WWW and CLI `php.ini` files.

---
Tags: drush, configuration
---


# Question
Title: How to enable both passwords at registration AND email confirmation together?
I know how to enable setting the password at registration, and I know also how to set email confirmation after registration. But I don't know how to enable both features to work together.

When I enable the former function, the ladder would stop works.

Is it possible to enable both functions using UI?

I have tried Login Toboggan module but it doesn't have this function, either.

# Answer
> 2 votes
All you need to use is the user registration password module

> Let users register with a password on the registration form when verification mail is required.
>
> By default, users can create accounts directly on the registration form, set their password and be immediately logged in, or they can create their account, wait for a verification e-mail, and then create their password. With this module, users are able to create their account along with their password and simply activate their account when receiving the verification email.

# Answer
> 1 votes
You can use Email Registration module to

> Allows users to register with an e-mail address as their username

and User registration password to

> Let users register with a password on the registration form when verification mail is required.

---
Tags: users, emails
---


# Question
Title: What is the proper function for multi dimensional localized menu?
What is the proper function to get multi dimensional localized menu in Drupal 7?
after searching, I found `i18n_menu_localize_tree()`, but I didn't get it as tree menu. Should I use `i18n_menu_translated_tree()`, or did I miss something?

# Answer
menu\_tree($menu\_name) Seems to do that. It runs the items through \_menu\_item\_localize.

It works if your menu is translatable. In my setup menu items were not assigned to language, but translated with 18n\_menu from site default language.

This atleast gets translated menu. Localized menu might imply also to version where certain items are only shown with specific language active(in that case this answer migth not work).
> 2 votes

# Answer
If you use the i18n\_menu module for menu translation/localization, you can indeed use the `i18n_menu_localize_tree()` to retrieve the localized tree of an original given menu tree.

```
$tree = menu_tree_all_data('main-menu'); // Depending the requirements, you can use menu_tree or menu_tree_all_data

if(module_exists('i18n_menu')) {
    $tree= i18n_menu_localize_tree($tree);
}

```
> 1 votes

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


# Question
Title: ESIs with Varnish 2.1.5 for Anonymous Users
We're trying to configure our sites running D7 to use ESIs with Varnish 2.1.5, and having a hard time figuring this out.

We have a file `/test.php` that is being included in the template via esi so it appears on *all* pages of our site. The call to the file is through (in the template)

```
<esi:include src="/test.php" />

```

Relevant vcl conf is:

```
sub vcl_fetch {
...
  // enable esi
  esi;
  // if url is test.php, set ttl to 15 s
  if (req.url == "/test.php") {
    unset beresp.http.set-cookie;
    set beresp.ttl = 15s;
  }
}

```

The text from `test.php` appears when users are logged in, but does not appear when they are logged out -- which is what we're after. This is without the ESI module as that is for authenticated users.

# Answer
> 1 votes
Try turning off Anonymous caching and see what results you get (caching should be handled by Varnish).

1. Go to admin/config/development/performance
2. Uncheck *Cache pages for anonymous users*

# Answer
> 0 votes
I have a working instance with Drupal7, Varnish and ESI in working state\[Th ESI tags are getting replaced for both Anonymous and logged in users\].

I can confirm that ESI tags work well with Drupal Page Cache. I don't see a reason you need to disable the Drupal Page cache for ESI tags to work.

And regarding the behavior that you were experiencing, I think the anonymous page cache was built you added your ESI tag and hence it was not displaying. I think clearing Drupal Cache and Varnish Cache could have just fixed your issue.

---
Tags: 7, proxies
---


# Question
Title: programatically how to get fieldcollection item by passing fieldcollection id?
Retrieve field\_collection item as field-set format by passing id. I have only field\_collection id. I want to retrieve field-collection form by passing field id.

# Answer
Try to do like this...

```
$nid = 49;
$node = node_load($nid);
// Renders total node with your field collection items.
$wrapper = entity_metadata_wrapper('node', $node);

// Let's use field_test_collection is your collection item and field_test_collection_title, field_test_collection_desc are your couple of fields under it.
// Iterate through each item from field_test_collection.
foreach($wrapper->field_test_collection as $i){
  // Title is here.
  $title = $i->field_test_collection_title->value();
  // Description is here.
  $desc = $i->field_test_collection_desc->value();
  print $title . '<br>';
  print $desc . '<br>';
}

```

and

check out this link Entity API. It may help you.
> 2 votes

# Answer
You can use `field_collection_item_load()`, e.g.

```
$item = field_collection_item_load($item_id);

```
> 2 votes

# Answer
It could also be achieved with the following code.

```
$wrapper = entity_metadata_wrapper('field_collection_item', FIELD_COLLECTION_ID/FIELD_COLLECTION_OBJECT);

```
> 0 votes

---
Tags: entities
---


# Question
Title: Expose filter in block to show results on view page
I want to make custom search block on home page, in header region. I'm using Exposed filter block in Views module, but results on the page are shown just below the block, in header. I want results of the search to be shown on the other page, like regular search do. Is there a way to achieve this. I'm using Drupal 7.

# Answer
> 9 votes
Create a page view using filter you want.
Step 1) Enable the block in your View

Step 2) Put the exposed filter block where you want it to be
Step 3 ) Test the result

# Answer
> 2 votes
One more thing for people using "Content pane" display in views. You need to set "Use Panel path: Yes" in order to fix this issue.

---
Tags: views
---


# Question
Title: Programmatically hide comment and view tabs
Can you please help me to hide the tabs from the Find/Add/Edit content page?

Is there a way to programmatically hide them?

# Answer
A more generic solution could be Tab Tamer.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
> 6 votes

# Answer
To hide the menu tabs you want to hide, you just need to create a module containing the following code.

```
function mymodule_menu_alter(&$items) {
  $paths = array('admin/content/comment', 'node/%node/view');

  foreach ($paths as $path) {
    $items[$path]['type'] = MENU_CALLBACK;
  }
}

```

I would rather follow Potney Switters's suggestion, and install the Tab Tamer module, since:

1. It implements a user interface to change which tabs should be hidden; this is better than hard coding paths in the code
2. It doesn't force you to find which module implements which tab, and get the path from the code of that module
3. It doesn't require too much resources
4. It is code that you don't maintain, so you don't need to port it to Drupal 8 because somebody else will do it

The last point could also mean you need to wait to upgrade to Drupal 8 until the Tab Tamer module is ported to Drupal 8, but since you are probably using other third-party modules, that should not be a problem.
Of all the points I listed, I think the first two are the reason why it is worth using the Tab Tammer module. The only reason not to use that module would be using a less resource-consuming module, which would also mean using a module that uses less code, including the one used for the settings page; that would mean having hard-coded settings, with the consequences reported in the second point.
> 5 votes

---
Tags: 7, hooks
---


title: How to set the field label as an <h2>?

text:
# Question
Title: How to set the field label as an <h2>?
I'd like to be able to set the field label as an `<h2>`. How can I do?

I'm editing the features definition for a field collection directly so if it's possible to set it in there that would be super-handy!

# Answer
> 3 votes
One can provide a field.tpl.php file within the theme.

You can copy the existing field.tpl.php file from /modules/field/theme (which btw is just auxilliary and not used by Drupal) into the theme's directory and replace the line:

`<div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>`

into

`<div class="field-label"<?php print $title_attributes; ?>><h2><?php print $label ?>: </h2></div>`

or something.

---
Tags: 7, entities
---


# Question
Title: Conditional Fields Changed Answer Problem
I have three fields on an entityform the third is hidden unless the second one is answered with yes.

The problem I have is that if a user makes three visible by answering "yes" and then answers three but then decided to change question 2 to "no" field 3 is hidden but the answer is still recorded.

# Answer
Adding another dependency with **field 3** \- **emptied** when **question 2** is **no** should most likely fix your problem
> 0 votes

---
Tags: entities
---


# Question
Title: How do I re-name my zone--content.tpl.php file for a separate front page layout?
I am using Omega 3.x along with Delta and contexts for creating a drupal theme for my site. I have experience with using D6 themes like Zen but I am still learning my way around Omega.

I want to know **how I can create and name a separate template for my zone called content for the front page**. I wouldn't mind a hard coded or a Delta+context solution or for that matter any other method to achieve my goal as long as Omega is used.

# Answer
> 6 votes
This was too much for a comment so I put it in an answer. newdwardss's answer contains the right methodology, but it doesn't address the Omega theme.

You can use the same logic as in that answer, but customise it for the zone template:

```
function MYTHEME_preprocess_zone(&$vars) {
  if ($vars['zone'] == 'content' && drupal_is_front_page()) {
    $vars['theme_hook_suggestions'][] = 'zone__content__front';
  }
}

```

That will allow you to use a template file called `zone--content--front.tpl.php` which will only be used for that zone, and only when on the front page.

# Answer
> 1 votes
Your front page only template should be called:

page--front.tpl.php

and/or you could get more custom via:

```
<?php
function YOUR_THEME_NAME_preprocess_page(&$vars) {
if ($vars['node']->type == 'content'){
    $vars['theme_hook_suggestions'][] = 'page__content';
}
}
?>

```

But in your case you may need to switch on a different part of the $vars\['node'\] object that references your "zone".

See Drupal 7 Template Suggestions for a full reference (quite handy).

For clarity, by "zone" do you mean region? If so, you can implement the above page--front.tpl and then call your custom region tpl output on that page--front.tpl only.

# Answer
> -1 votes
For use with the region content template (region--content--front.tpl.php) use this instead:

```
function YOUR_THEME_NAME_preprocess_region(&$vars) {
  if ($vars['elements']['#region'] == 'content' && drupal_is_front_page()) {
    $vars['theme_hook_suggestions'][] = 'region__content__front';
  }
}

```

---
Tags: theming
---


title: Set <front> page in theme settings?

text:
# Question
Title: Set <front> page in theme settings?
I've created a settings page for my theme, and I'd like to be able to set the frontpage from there, but I don't know how I can change the frontpage in code?

This is the setting:

```
$node_type = "page";
$result = db_query(
    'SELECT n.nid, n.title FROM {node} n WHERE n.type = :type',
    array(':type' => $node_type)
);
$options = array();
foreach ($result as $record) {
    $options[$record->nid] = $record->title;
}

$form['static_nodes']['front_page_id'] = array(
    '#type'        => 'select',
    '#title'       => t('Frontpage'),
    '#options'     => $options,
    '#description' => t('Set the page used as the frontpage.'),
    '#default_value' => theme_get_setting('front_page_id'),
);

```

# Answer
> 4 votes
**Solution:**

```
function billetsalget_form_system_theme_settings_alter(&$form, &$form_state)
{
    /**
     * The group fieldset
     */
    $form['static_nodes'] = array(
        '#type'          => 'fieldset',
        '#title'         => t('Static Pages'),
        '#weight'        => -2,
    );

    /**
     * Get pages from db as options
     */
    $node_type = "page";
    $result = db_query(
        'SELECT n.nid, n.title FROM {node} n WHERE n.type = :type',
        array(':type' => $node_type)
    );
    $options = array();
    foreach ($result as $record) {
        $options[$record->nid] = $record->title;
    }

    /**
     * Select dropdown for Frontpage
     */
    $form['static_nodes']['front_page_id'] = array(
        '#type'        => 'select',
        '#title'       => t('Frontpage'),
        '#options'     => $options,
        '#description' => t('Set the page used as the frontpage.'),
        '#default_value' => theme_get_setting('front_page_id'),
    );

    /**
     * Run function when form is submittet
     */
    $form['#submit'][] = 'billetsalget_form_system_theme_settings_submit';
}

function billetsalget_form_system_theme_settings_submit(&$form, &$form_state)
{
    /**
     * Set frontpage to 'node/' + node_id selected in the form
     */
    variable_set('site_frontpage', 'node/' . $form_state['values']['front_page_id']);
}

```

---
Tags: forms
---


# Question
Title: hook_node_grants() implemented by a custom module is not invoked
I am using the following code in a Drupal 7 module.

```
define('BNA_ACCESS_REALM', 'billetsalget_nodeaccess');

function billetsalget_nodeaccess_node_access_records($node) {
  $producttypes = array('internal_product', 'external_product', 'call_product', 'event_product');
  $grants = array();

  if (in_array($node->type, $producttypes)) {
    $grants[] = array(
      'realm' => BNA_ACCESS_REALM,
      'gid' => $node->nid,
      'grant_view' => TRUE,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    );
  }

  return !empty($grants) ? $grants : array();
}

function billetsalget_nodeaccess_node_grants($account, $op) {
  dpm($account);
  die(var_dump($account));
}

```

`hook_node_access_records()` is working and running as it should, adding data to the database.
As far as I can see `hook_node_grants()` is never invoked. I have tried with all sorts of stuff in there, but it just looks like it doesn't even run.

---

It didn't have anything to do with my code. I'm new to Drupal so I didn't know `hook_node_grants()` don't get invoked when I'm signed in as an administrator. Newbie mistake from my side :)

# Answer
It didn't have anything to do with my code. I'm new to Drupal so I didn't know **hook\_node\_grants() don't get invoked when I'm signed in as an administrator**. Newbie mistake from my side :)
> 2 votes

---
Tags: hooks, users
---


# Question
Title: User's field autocomplete/autosuggest widget
I have a user field where multiple users can be added. Currently, I am using the auto-complete widget.

Is there a module that allows you to customize what can be additionally shown on autocomplete? I would imagine that you could add an 'autocomplete' view similar to full-page or teaser. Something like Facebook's search. Providing more info like picture or residence of the user.

# Answer
In your field setting, you can choose a view for node or user references:

To create this kind of view-reference, you have to previously create a view with a reference page like this :

Note that every field you'll choose for the view, will appear in the autocomplete input

Hope this can help
> 3 votes

---
Tags: views, entities
---


# Question
Title: Replacement Pattern to get current node url
I'm looking for a **valid** replacement pattern, to get the url of the current node for a `custom text` in a `list` of filtered nodes.

Example markup for custom text field:

```
<a data-custom-attribute="john-doe" rel="123456789" href="[node:url]">[title]</a>

```

Unfortunately, Drupal doesn't show me any *useful* pattern examples:

# Answer
> 12 votes
I think what you want to do is add "Content: Path" as a field. This is the path to the node.

1. Make sure the "Exclude from display" box is checked.
2. After you have added the field, make sure it is above your custom text field (click the arrow next to "Add" and select "Rearrange").
3. Once, you've done that, \[path\] will become a replacement token.

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


title: Ajax callback is not invoked

text:
# Question
Title: Ajax callback is not invoked
I am using Drupal 7, and I used `hook_form_alter()` to add the following markup.

```
  $form['linkb'] = array(
    '#type' => 'markup',
    '#markup'=>"<a href=''>Click here </a>",
    '#title' => t('something'),
    '#name' => 'linkb',
    '#ajax' => array(
      'method' => 'html', // this is important without this if else condition for ajax will not work.
      'effect' => 'fade',
      'callback' => 'clicktell_verification',
      'wrapper' => 'replace_textfield_div',
    ),
  );

```

I want to run AJAX when I click on *Click here*, but this is not working. I have also created a callback function, but it doesn't still work.

Why isn't the AJAX callback being called?

# Answer
> 2 votes
#ajax is never used by elements of markup type. You need to use it with one of the following elements:

* button
* checkbox
* checkboxes
* image button
* password
* radio
* radios
* select
* submit
* tableselect
* textarea
* text\_format
* textfield

---
Tags: 7, ajax
---


# Question
Title: How to save autocomplete and date type fields while adding node programmatically?
I am creating a node programmatically and I have a field which is autocomplete and has number of values set to unlimited.

In the code for adding the node programmatically ,the code is as given below

```
    $node->field_user[]['value'] = $user->name;
       $node->field_time[]['value'] = date('m-d-Y H:i', REQUEST_TIME);
  $trans_node->field_download_flag[0]['value'] = 'YES';

```

So after programmatically creating a view when I check into the 'find content' place I see a node being generated but when I click on the link(where the content title is )( not on the edit link) , I cannot see the field\_user in the view list

**field\_time**
**type**: date
**widget** : popup calendar
**no of values** : unlimited.
**field\_date**
**type**: Entity Reference
**widget** : Autocomplete
**no of values** : unlimited.

**field\_flag**
**type**: boolean
**widget** : checkbox/radiobutton
**no of values** : unlimited.

I think the code for field\_user should be as

```
$node->field_user[]['target_id'] =  $user->name;

```

but still i am getting error that is WSOD

# Answer
I think

```
$node->field_user['und'][]['target_id']

```

and

```
$node->field_time['und'][]['value']

```

is the good way
> 3 votes

---
Tags: entities, nodes
---


title: Skype auto link

text:
# Question
Title: Skype auto link
I know how to add a link field in Drupal for Skype (skype:username?chat), but I dind't find any answer about automatically convert it into a Skype link. Let's say users fill their profiles and in a link field write "foreigner"; this link should be automatically converted into `<a href="skype:foreigner?chat">foreigner</a>` when shown.

How can I achieve this task?

I'm using Drupal 7.

# Answer
> 3 votes
The module I would use is the Skype Status module. Despite the name, it shows a link to allow users to chat or call another user on Skype.

> Retrieves Skype status information via Skype's public presence service for users to display in their profile and also provides a block for site-wide usage (available only in D7!).

What you need to do is:

* Install and enable the Skype Status module
* Add a user profile where users can enter their Skype ID
* Go to admin/config/people/skype\_status
    + Select the field used for the Skype ID
    + Change the action performed when the button is clicked
    + Select the button style

Once the users enter their Skype ID, their user profile will show a button to chat/call them, which shows also their status on Skype.

For the status to be visible, users need to select "Shows my status on the web" for their Skype account from the Skype application.

---
Tags: navigation
---


# Question
Title: Ordering/ Sorting product displays on the product category page
I have created product displays which are now showing on the relevant category pages (product-category/%). The product category page is created in views which is great but I want to have full control over the order of which the products are displayed (top to bottom).

At the moment in 'Sort Criteria' of views I only have options to sort by Title, ID, Date posted and Category which is not useful. I want to sort by something like SKU or some other field of the product.

Any ideas?

# Answer
> 1 votes
> How about re-making your view so it shows Commerce Products, and add the relationship to the product display the other way round to get node data? That way you should definitely have SKU available as a sort option from the base table (commerce\_product) \- Clive

Thanks Clive - this worked.

# Answer
> 0 votes
You can add any field you want to the Sort Criteria. hit the "Add" button and pick Content: SKU (or whatever it's called).

# Answer
> 0 votes
In order to have full control over your products order you can install a great module Draggable Views. Then add a integer field to your product content type.

Create yourself a new "admin view" using a draggable table (Drupal 7 is just a table) and add all the fields you need including the integer sort field.

In Drupal 6 you will have to set the sorting field in the table settings, where in Drupal 7 you add another field "Draggableviews:content"

Inside your Product view as well as in your admin set the sort field as the integer sort field that you created.

Now you are able to re-order your products much like the menu system in Drupal Core.

---
Tags: views
---


# Question
Title: Using Views' Contextual filters in a Panel for one taxonomy term
I have one taxonomy term, Country, which is linked to another, People. One people is from one country.

How can I make a view in my Panel, using Contextual filters, in order to show the specific view I prepared for "Country" ? I tried to use contextual filters to do so, and it works when I use the preview with the Country ID - but not in Panels.

# Answer
> -1 votes
I managed to do what I wanted to by taking the problem reversely :

* I created my view, then added a contextual filter not by "Country ID", as I did, but by "People ID"
* Then I configured the argument input in Views by taking the source from the argument of the panel (which matched my "People ID") and it was taken in account by my Views and actually works.

Drupal is quite complicated to understand sometimes ! :) Thanks for advice Patrick Kenny ;)

Bye

# Answer
> 0 votes
If you want to display a different view for a country, I think what you probably want to do is use the Taxonomy Term override page rather than using contextual filters.

To do this, go to the pages admin screen (/admin/structure/pages). Then, enable the **Taxonomy term template** panel to override the display of taxonomy terms using Panels.

To show a custom view, you can edit the **Taxonomy term template** panel. This will allow you to use the taxonomy term as arguments for your view, because Panels understands that you are overriding the taxonomy term display.

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