# Question
Title: How do I prepopulate a field with calculated options, when user is editing node?
Say the user is creating a node. I want to display a drop down option list, with prepopulated options, based on a calculation (i.e. reference to user's groups, user's other nodes, etc...). Drupal 7.

I've had no luck with the rules, computed field, prepopulate field modules... maybe i'm missing something?

# Answer
> 1 votes
Use hook\_form\_alter or hook\_form\_FORM\_ID\_alter to pre-populate your dropdown list with results returned from a custom function.

---

For example, using a form of hook\_form\_alter():

```
$form['field_my_field']['und']['#options'] = _my_custom_function();

```

Then make sure your function `_my_custom_function()` return's a proper array.

```
function _my_custom_function() {
    $custom_values = array();
    $custom_values['key1'] = 'value1';
    $custom_values['key2'] = 'value2';
    $custom_values['key3'] = 'value3';
    return $custom_values;
}

```

Obviously you can include some 'logic' in the `_my_custom_function()` to return your calculated list.

---

Here are a few super-useful link's I wish I would have know about before.

# Answer
> 0 votes
write a module and provide a hook\_form\_alter to change the values of the form element. Just google hook\_form\_alter for tutorials and code snippets.

# Answer
> 0 votes
Are you using a list field?

It has support for a callback to provide the allowed values. See list\_field\_info() That is however not exposed in the UI (which makes somewhat sense as you can't implement a function there either).

So you can simply implement a function that returns the allowed values and then update the field configuration (through api calls in your module, directly in the database, or export your field as a feature and then adjust it there).

In fact, if it is a list field, you probably have to do it this way instead of a hook\_form\_alter() in order to get past the validation, but I'm not 100% sure.

---
Tags: 7, entities
---


title: Loop through nodes of same content type

text:
# Question
Title: Loop through nodes of same content type
I currently have a page template set up in its page-node-946.tpl.php. `$content` is being populated by that node numbers content. I need to loop through and display a teaser for all content nodes and certain type. I need some instruction on how to do it. Maybe I've gone wrong by trying to do this with a page-node template.

# Answer
You can use Views for looping throug nodes. Just build Views that show list of certain nodes, then call it into your template file, like this: `print views_embed_view('VIEWNAME', 'DISPLAY_ID');`
But creating for each page one node template file is not good way for this (you will got many count of this page-node-XXX.tpl.php files, for serving all of these you will take more time, even you want to change something little), node-TYPE.tpl.php will better with more common page.tpl.php.
p.s. Also customizing page via Panels without template have better UI.
> 1 votes

---
Tags: theming, nodes
---


title: Where is the entity ID stored?

text:
# Question
Title: Where is the entity ID stored?
I have an installation which I am trying to upgrade from Drupal 6 without much success. I have decided to manually port the database over.

I realized that in a fresh installation of Drupal 7, node has entity ID = 1 whereas in another installation, node has entity ID = 2.

Where is the table storing this data located?

# Answer
> 3 votes
Check for `hook_entity_info` and `entity_extract_ids`. The former specified a base table and the id key, the latter allows to extract the ID from the entity.

---
Tags: 7, entities
---


# Question
Title: How to use the dsm( ) Devel function to print the $form array of my form?
I want to use the `dsm()` function of the Devel module to print the `$form` array of a form, where the `form_id` is `search_theme_form`. How to do that?

# Answer
Start a custom module, insert this code:

```
/**
* Implements hook_form_alter().
*/
function foo_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'search_theme_form') {
    dpm($form);
  }
}

```

Also, you might want to use dpm() over dsm() since the latter is a legacy function.
> 12 votes

# Answer
```
function THEME_form_search_theme_form_alter (&$form, &$form_state){

krumo ($form); // you can use DSM as well here

}

```

Replace THEME with your theme name and put that in your template.php, if you want to do that from a module then replace THEME by your module name and put that funciton in your .module file
> 3 votes

# Answer
Use drupal\_retrieve\_form to get the structured form array:

```
$form_state = array();
dsm(drupal_retrieve_form('search_theme_form', &$form_state));

```
> 2 votes

---
Tags: debugging
---


# Question
Title: How can I override a module-defined view and export to code?
I'm using nrembrowser to provide a media library and allow users to insert media via a wysiwyg interface. The module provides its own view which I've altered. I keep my views in code (using features) but I don't know any way to override an existing module-defined view via code (ie something similar to strongarm, but instead of overriding a variable, it's overriding a view). I've solved the problem by using a nrembrowser hook to change the view to my custom one, but I'd be interested in knowing if I could've overridden the module's default view in some way.

# Answer
Using hook\_views\_default\_views\_alter(). There's a page on this on drupal.org. As far as I know there's no way to have features automatically export an overridden view and put it in a hook\_views\_default\_views\_alter(), and it looks like there's actually an issue with using features together with this hook.
> 1 votes

---
Tags: views, 6, features
---


# Question
Title: Userpoints: Require userpoint for being able to create a node?
How would one go about requiring the user to have userpoints before creating a node?

Perhaps with some kind of Rules validation?

Cheers

# Answer
> 3 votes
There is a module in the userpoints\_contrib project, which does exactly this.

You can combine it with userpoints\_nc or a rule to also deduct points when a node is created, so that creating nodes costs something.

---
Tags: forms, userpoints
---


# Question
Title: How to create a PHP file that returns a list of nodes as XML?
How do I create a PHP file that returns a list of nodes as XML when called if I have a menu structure like this:

```
<GalleryXML>
--gallery 1
---Item 1
---Item 2
---Item 3

```

And I want a url like `localhost/getgallery.php`

this url will then return my gallery as xml, something like this

```
<galleryXML>
    <gallery name="gallery1">
        <item name="item1">
            <image>localhost/site/default/image1</image>
            <imagethumb>localhost/site/default/image1</imagethumb>
            <url>http://google.com</url>
            <description>lorum ipsom</description>
        </item>
    </gallery>
</galleryXML>

```

Where `Image`, `Imagethumb`, `url` and `description` are fields on the item node

Thanks in Advance!

# Answer
> 6 votes
This is what i did:

1. I created a view.
2. Changed the style to XML data document (Need to download the Views Datasource module)
3. Added the fields I needed and Nodequeue
4. Added a filter to filter by node type so it looks like this:

then I added a new page with a path:

my end result looks like this:

```
 <node>
    <node>
        <Description>blablalbla</Description>
        <Image>
        sites/default/files/articles/siteadmin/test.png
        </Image>
        <ImageBig>sites/default/files/test.png</ImageBig>
        <Link>derp</Link>
        <gallery>Gallery1 For flash</gallery>
    </node>
    <node>
        <Description>sdfsdfdf</Description>
        <Image>
        sites/default/files/articles/siteadmin/test.png
        </Image>
        <ImageBig>sites/default/files/test.png</ImageBig>
        <Link>sdfdf</Link>
        <gallery>Gallery2 For flash</gallery>
    </node>
</node>

```

---
Tags: nodes, 6
---


# Question
Title: Call a php function on text selection in text area
I have a text area in form. When some text from text area is being selected, I have to enable a button. How can I do that?

# Answer
> 3 votes
If you want to do something when text is selected, take a look at the .select() jQuery event. Then you can enable/disable the button however you like.

Example from the jQuery page:

```
<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:blue; }
  div { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>

    Click and drag the mouse to select text in the inputs.
  </p>
  <input type="text" value="Some text" />
  <input type="text" value="to test on" />

  <div></div>
<script>
    $(":input").select( function () {
      $("div").text("Something was selected").show().fadeOut(1000);
    });
</script>

</body>
</html>

```

# Answer
> 2 votes
You can use the `onfocus` event of textarea for this kind of job.

# Answer
> 1 votes
This can only be done with Javascript, because when some text is being selected, that is only on the client side. And with jQuery show(); hide(); (CSS) it should be fairly easy.

---
Tags: 7, ajax, javascript, forms
---


# Question
Title: Multi step user registration form drupal 6
How to do Multi step user registration form in drupal 6 ?

I am having an idea of doing multistep process using custom form.

**But i am bit confusing while doing the same case with "user registration".**

For example :

Let us consider i am having 10 fields and separating it with three forms like 4+4+2.

**Now when i complete the first form and click next button where should i need to save the values of current form. I used $form\['storage'\]. But it didn't helps.**

Could anyone please clear me this or provide me an easy tutorial for **"multistep user regsistration".**

Any help will be thankful and grateful..

Thanks in advance..

# Answer
> 1 votes
This blog post may help you: Multistep registration form in Drupal 6

---
Tags: 6, forms, users
---


title: MySQL 5.5 performance in Windows 7

text:
# Question
Title: MySQL 5.5 performance in Windows 7
My collegues and I are working on a Drupal 7 project. From time to time, we need to do a clean install on our machines (to get the latest updates working).
However, when installing the Drupal database, my collegues laptop is much faster than mine, despite the fact I've got the latest and most powerfull laptop (Windows 7 Enterprise, 64-bit and 8GB of RAM).

What causes this lack of performance in installing the new Drupal website? I reinstalled MySQL 5 times, and still I don't see any improvement.

# Answer
This is funny. *I just answered a question about MySQL 5.5 being slow in the DBA StackExchange*. You will have to configure it to perform better. It is not automatically configured for high performance by default.
> 1 votes

---
Tags: database
---


title: Hook Menu and module prevalence

text:
# Question
Title: Hook Menu and module prevalence
I am implementing the following in a module:

```
function foo_module_menu() {

    $items['taxonomy/term/%'] = array(
    'page callback' => 'subproducts_populate_taxo',
   'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK);

    return $items;
};

```

This hook doesn't seem to work, i assumed it was because of the taxonomy module having prevalence on this menu item, so i gave my module a -1 weight.

Now strange thing, it work but only after clear cache once after applying the weight change. If i reflush cache the Taxonomy module take prevalence again even though i didn't rechange the weight..

Any ideas ?

# Answer
Use hook\_menu\_alter() to override existing menu entries.
> 3 votes

# Answer
Thanks your suggestion, it ll probably come in handy later, though in the mean time i got it working by making the weight of my module lighter than the taxonomy. **Seems that to override menu items lighter module get prevalence.**
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How do I filter a views page with contextual filters?
I have an all events views page where I would like to put the links 'All Events', 'Upcoming Events', 'Past Events' in the header.

I would like to link them to the same views page but show filtered results. It seems possible by looking at contextual filters but not sure which way to go.

Thanks,

Kevin

# Answer
you can add exposed filters to show past and future events. When you use the filters you'll see the URLs it generates. Those are your links and you can add them to the header of the view with a "global text area". You can now hide the exposed filter forms by setting "Exposed form in block:" to yes. That will remove them from the view.
> 1 votes

---
Tags: views
---


title: Change default messages from Poll?

text:
# Question
Title: Change default messages from Poll?
We're running the core Poll module on our site, and we'd like to change the default messages that it generates. I'm meaning stuff like `Your vote could not be recorded because you did not select any of the choices.`

I looked at the poll content type, but there weren't any settings for it there. It's apparently not listed under modules, because it's core, I suppose.

How can I change these messages from their defaults?

# Answer
> 5 votes
You can use the String Overrides module. More options are described in the handbook page Change default strings (text).

# Answer
> -1 votes
Apparently these messages are hard-coded into the poll module, so to change them, one would need to hack core.

```
poll.module:738:    form_set_error( 'choice', t('Your vote could not be recorded because you did not select any of the choices.'));

```

---
Tags: 7, polls
---


title: Manually flush ImageCache cache?

text:
# Question
Title: Manually flush ImageCache cache?
Im using ImageCache but I've since modified some of the original image files in my Drupal site. The reason being I needed to modify images uploaded to nodes but don't want to manually add them all again. Can I now manually flush ImageCache's cache?

Thanks

# Answer
Just display list of all presets, there are links for flushing presets. Presets list is available at `/admin/build/imagecache/list`

Flushing urls of respective presets would be `/admin/build/imagecache/[preset_id]/flush`
> 10 votes

---
Tags: media
---


title: Display multi values field as html list

text:
# Question
Title: Display multi values field as html list
In my content type I have two multi values fields for images and embedded videos. Those fields are displayed in view.

I wanted to display elements of these fields in carousel. I found solution on google, but this solution only works when I have more than one items in field.

I didn't manage to do it for one element in the field.

I want to display those fields (no matter if field has one or more items) in html list.

Could somebody give me any advice?

**\[EDIT\]**

I try similar solution to @Shoaib Nawaz answers, but because of memory problems I can display values only from $row object.

The part with data of embedded videos look like this:

```
   [node_data_field_video_field_video_embed] => Array
        (
            [0] => Array
                (
                    [embed] => http://www.youtube.com/watch?v=XnflHoDIwFk
                    [value] => XnflHoDIwFk
                    [provider] => youtube
                    [data] => a:6:{s:20:"emvideo_data_version";i:5;s:23:"emvideo_youtube_version";i:5;s:8:"duration";i:831;s:8:"playlist";i:0;s:9:"thumbnail";a:1:{s:3:"url";s:43:"http://img.youtube.com/vi/XnflHoDIwFk/0.jpg";}s:5:"flash";a:3:{s:3:"url";s:32:"http://youtube.com/v/XnflHoDIwFk";s:4:"size";s:4:"1011";s:4:"mime";s:29:"application/x-shockwave-flash";}}
                    [status] => 1
                    [version] => 5
                    [title] =>
                    [description] =>
                    [duration] => 831
                )

```

The part of images looks like:

```
[node_data_field_photos_field_photos_fid] => Array
        (
            [0] => Array
                (
                    [fid] => 18515
                    [list] => 1
                    [data] => a:2:{s:3:"alt";s:30:"System stołów automatycznych";s:5:"title";s:0:"";}
                )

```

Screen with jcarousel with this stuff (worked only for fields with more than one items):

Now I need to find function to turn this data to html or code it all.

# Answer
> 1 votes
Try to do it with View field template. Edit your view and check for 'Theme information'. View will suggest some suitable field template according to your field and view's name. The most common template of fields is **views-view-field.tpl.php**

Other specific can be:

```
views-view-field--<my-field>.tpl.php,
views-view-field--<my-view>.tpl.php,
views-view-field--<my-view>--<my-field>.tpl.php,
views-view-field--<my-display>.tpl.php,
views-view-field--<my-display>--<my-field>.tpl.php,
views-view-field--<my-view>--<my-display>.tpl.php,
views-view-field--<my-view>--<my-display>--<my-field>.tpl.php

```

Here `<my-field>`, `<my-view>`, `<my-display>` are placeholders to replace actual field, view and display name.

Create any one of template in your active theme directory and
Try `print_r(get_defined_vars());` in your template to know available variables/values.

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


# Question
Title: How to store user specific data after registration?
Let us say you want to collect a bit more information about users during registration. For example, instead of just username and email, I also want place of residenc. How do I collect and store this data per user? At the end of the day I want to end up with place of residence of each user by doing an easy query.

**PS**: Currently, I have added extra fields to the form `user_register_form`, but I don't know how to associate this data with my new user because I don't have the new user id.

What is the right approach? Because I think this should be a trivial Drupal exercise, but am sweating `:)`.

I am using Drupal 7.1.

```
// implements hook_form_alter()
// user-register-form id the id in html but id that works in php is user_register_form
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'user_register_form':
      $form['placeofresidence']= array(
        '#title'=>'where do you stay?',
        '#type' => 'textfield',
        '#required' => true,
      );
      $form['#submit'][]='mycustommodule_submit'; //add to callback submit list
      break;
  }
}

function mycustommodule_submit($form, &$form_state) {
  $stayswhere=$form_state['values']['placeofresidence']; // how do I associate this with new user?
}

```

# Answer
> 7 votes
users are a "fieldable entity" in Drupal 7. Just go to "configuration / people / account settings / manage fields" and add your fields. Make sure to check the "Display on user registration form" box.

For the "place of residence" I recommend the addressfield or location modules.

# Answer
> 3 votes
Another way to approach this is use the 'data' field of user. According to the documentation here, you could do something like this. Let's say you have added a new form element to the new user registration form and want to save the data in it for something later after they authenticate themselves successfully for the first time.

```
function custom_module_user_presave(&$edit, $account, $category) {
  //If the account is being created for the first time
  if (empty($account->original->login)) {
    $edit['data']['custom-field'] = $edit['custom-field'];
  }
}

```

This information will always be returned on a user\_load and can be found in the $user-\>data array. For this example, it would be in $user-\>data\['custom-field'\].

---
Tags: 7, hooks
---


# Question
Title: Migrated a drupal database from a preview site to a live site and am now getting an error
Migrated a drupal database from a preview site to a live site and am now getting an error.

(I only moved the database)

`The selected file /tmp/filethQvCf could not be uploaded, because the destination css/css_4b1c49411f8ee294df61cf73ebc413c6.css is not properly configured.`

I should note that /sites/default/files/ctools/css is chmod 777

# Answer
Figured it out. As admin:

admin \> settings \> file system

The Temporary directory was set to a different path that didn't exist in the preview site.
> 2 votes

---
Tags: 6, migrations
---


# Question
Title: how does links__system_main_menu() work?
How does the below code work at a high level?

```
print theme('links__system_main_menu', array(
  'links' => $main_menu,
  'attributes' => array(
    'id' => 'main-menu-links',
    'class' => array('links', 'clearfix'),
  ),
  'heading' => array(
    'text' => t('Main menu'),
    'level' => 'h2',
    'class' => array('element-invisible'),
  ),
));

```

# Answer
Drupal renders the array argument you passed by looking up a suitable theme hook for `links__system_main_menu`.

The meaning of the argument should be documented in the module that provides the theme hook.
> 2 votes

---
Tags: theming
---


# Question
Title: Commons: can each non-admin user create groups?
I wan to configure a Drupal Common site so that every user can create groups. Can I do so? how? Thanks.

And is there any documentation anywhere for commons? OR a support forum?

# Answer
The answer is yes. Straight out of the box, each Commons user can create groups.
> 1 votes

---
Tags: 7
---


# Question
Title: how can i change the "Create new Account" to Custom registration
Is there any ways to add more fields in "Create new Account" ?

By defaults it provides only username and emailid.

So how can i add more fields like gender, date of birth.

# Answer
Fields module should be enabled with Field UI and other. http://YOURSITE/admin/config/people/accounts/fields \- add field, mark "Display on user registration form." on field editing form.
> 2 votes

---
Tags: 7
---


# Question
Title: How do I override the default sorting when filtering a view by Taxonomy terms?
## My current settings …

In Drupal 6, I currently have a **view** that filters and sorts nodes by the following criteria:

The taxonomy term is very general, and nodes can either be assigned to "Referenzen" only, or any of its sub-nodes. This is done for the basic structuring of the site. Here, in this view though, I only want to "load all nodes with 'Referenzen' assigned", regardless of their sub-term.

## The problem …

"Wichtig" ("important") is an integer value that defines the primary sort criteria for me. I do not care whether a reference is filed under "Media" or "Consulting", or any other sub-term.

However, the nodes are finally displayed like this:

```
Node 1   Important:  100   Taxonomy: Referenzen
Node 2   Important:    0   Taxonomy: Referenzen
Node 3   Important: -100   Taxonomy: Referenzen
Node 4   Important:  100   Taxonomy: Referenzen – Media
Node 5   Important:   80   Taxonomy: Referenzen – Media

```

As you can see, the "Important" factor comes second when sorting the nodes, and the taxonomy grouping comes first.

**How can I change this behavior, so the following is achieved:**

```
Node 1   Important:  100   Taxonomy: Referenzen
Node 4   Important:  100   Taxonomy: Referenzen – Media
Node 5   Important:   80   Taxonomy: Referenzen – Media
Node 2   Important:    0   Taxonomy: Referenzen
Node 3   Important: -100   Taxonomy: Referenzen

```

## The executed query

```
SELECT node.nid AS nid, node.title AS node_title, node.language AS node_language, node_data_field_image.field_image_fid AS node_data_field_image_field_image_fid, node_data_field_image.field_image_list AS node_data_field_image_field_image_list, node_data_field_image.field_image_data AS node_data_field_image_field_image_data, node.type AS node_type, node.vid AS node_vid, node_revisions.teaser AS node_revisions_teaser, node_revisions.format AS node_revisions_format, node_data_field_important.field_important_value AS node_data_field_important_field_important_value, node_data_field_date.field_date_value AS node_data_field_date_field_date_value
FROM node node
INNER JOIN term_node term_node ON node.vid = term_node.vid
LEFT JOIN content_field_image node_data_field_image ON node.vid = node_data_field_image.vid
LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid
LEFT JOIN content_field_important node_data_field_important ON node.vid = node_data_field_important.vid
LEFT JOIN content_type_story node_data_field_date ON node.vid = node_data_field_date.vid
WHERE (term_node.tid = 2) AND (node.language in ('***CURRENT_LANGUAGE***')) AND (node.status <> 0)
ORDER BY node_data_field_important_field_important_value DESC, node_data_field_date_field_date_value DESC

```

## The exported view

… can be downloaded here:

> http://cl.ly/1c2c0X3f1Q2L3Y3x3l3w

## MySQL Query Browser

… however tells me that those that have the "Wichtig" field not set have the value `NULL` and therefore are sorted last. All newly created nodes get "Wichtig" set as `0`, however all old ones still have `NULL`.

So what can I do to make those with *NULL* have the value `0` instead ~~and how can I prevent this for new articles in the future?~~

# Answer
> 2 votes
Maybe the MySQL IFNULL() function could be the solution. It allows you to check the selected field value and give it a custom one when null. In your SQL statement, instead of

```
node_data_field_important.field_important_value AS node_data_field_important_field_important_value

```

you should have:

```
IFNULL(node_data_field_important.field_important_value,0)  AS node_data_field_important_field_important_value

```

Try the modified SQL statement in your MySQL Query Browser and see if it works.

I'm an old database administrator, but a Drupal beginner, so I don't really know how to put this function in a View using the web interface. Do you?

I'm searching a way to add custom SQL to views (because as a beginner I'm interested too) and found something about **hook\_views\_query\_alter()**. It belongs to Views 2 API. You should use that hook to change the corresponding array value using your exported view code as reference for array indexes. I have no time to try it, but probably this is the right way.

IMHO another way should be taking the exported view code, modify it manually adding the IFNULL() MySQL function on the field name and then reimport it into a new view. I'm not sure that Drupal will write a correct SQL query or that it won't discard some SQL it doesn't expect... This should be the same as using the hook above, but in a rude and not to so elegant manner...

Hope it helps.

# Answer
> 1 votes
if you want to alter views query to overwrite the default shorting

function modulename\_views\_query\_alter(&$view, &$query){
if ( $view-\>name == 'test\_merchandise' ) {
//here you will get the whole $query object and alter only the place you want change
$query-\>orderby\[0\] = "substring(node\_data\_field\_date\_field\_date\_value,1,4) DESC";
print\_r($query);
}
}

# Answer
> 0 votes
If I understand well your question, why not validate the "Wichtig" ("important") field before be stored to store `0`? If is possible, I think that you have several alternatives to validate fields:

Rules module has form support to validate fields: http://drupal.org/node/298487 (see *Form support*)

also, with `hook_form_alter` (or `hook_form_FORM_ID_alter`) you can validate fileds with custom modules: http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook\_form\_alter/6 http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook\_form\_FORM\_ID\_alter/6

this guide show you how to validate fields in custom forms http://drupal.org/node/751826

also Form API Validation allows to you validate fields: http://drupal.org/project/fapi\_validation

if I am not wrong and is useful my answer, I have some experience validating with rules and `hook_form_alter`, so if is necessary, I can add more information inside this answer.

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


title: field_widget_form call as a custom form

text:
# Question
Title: field_widget_form call as a custom form
I want to call my custom field\_widget\_form with the use of drupal\_get\_form() Is it possible to do that? simple requirement .. I want to build a form where user enter the field value and that value should be store with the node but only one field value instead of all 30 fields.

Now i have created the field with custom code so how can i call this function field\_widget\_form() in that or any other help full alternative.

# Answer
> 3 votes
When you define a widget form, you can change it from another module with hook\_field\_widget\_form\_alter(), which requires Drupal 7.8 or higher.

```
function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

```

---
Tags: 7, entities
---


# Question
Title: 'serialized' field in schema still needs manual unserialization?
I've modified my schema so that I can store an array of items in one field:

```
"required_product" => array(
  "type" => "text",
  "length" => 'medium',
  "not null" => TRUE,
  "default" => "",
  "serialize" => true,
),

```

This works great when using drupal\_write\_record, as the array data is correctly serialized before putting it into insert/update query and executing.

However, I still have to manually serialize when I extract the data - example:

```
$form_state["values"] = db_fetch_array(db_query("SELECT * FROM {amh_shop_discounts} WHERE discount_id=%d", $discount_id));
$form_state['values']['required_product'] = unserialize($form_state['values']['required_product']);

```

This is less useful - shouldn't it do both?

Currently running Drupal 6.22

# Answer
> 5 votes
This is just a guess, so correct me if I'm wrong...

I think that automatic unserialization is not possible because the schema is not loaded by db\_query. While drupal\_write\_record() loads the schema definition before writing to the database, db\_query simply executes the query string you put into it, without knowing which schema definition the query relates to.

---
Tags: 6, database
---


# Question
Title: Creating event lists using nodequeue, static pages and dynamic dates
I'm new to Drupal, with some familiarity in other CMSes. I'm currently attempting to create a series of event lists, and have met up with a few issues. The number of modules available for the system are confusing my Googling, as terminology isn't uniform across the web and I'm picking up information for everything but what I want. From reading in StackOverflow, I gather it's a common problem with Drupal. I'm looking for recommended resources or perhaps more direct help - advice on whether to learn the system fully despite this being such a simple/small job would be useful as well.

**In summary:**

Need an online system to create itineraries, lists of events containing location information and dates that are specific to unique clients/users. Employees access the backend, assemble an itinerary and provide a link to customers with an appropriately formatted, final page/document. Drupal is a CMS that is potentially going to be used for a future website, and "location information" would be a duplication of web content - this system would make for a neat way of populating the website with content whilst the main frontend is being developed.

**What I need**

* locations are created as static nodes (pages)
* access the backend with an interface that allows for the selection of these location nodes and compiles them into an ordered list
* each node, despite being static, is associated with a date field (start and end) specific to each ordered list
* lists are unique and independent, using the same static content to fill description fields but able to be linked with specific date information

**Where I'm currently at**

* locations are created as static nodes (pages)
* the itinerary is a nodequeue, where an employee creates a new one, adds location nodes and can control the order without technical know-how
* display using Views, using unique URL per list
* trying to find a way to relate the unique nodequeue with a pair of dates for each location
* been playing around with custom content types/custom fields, but don't know how to define the relationship between the static/dynamic content
* using Date API for javascript calendar pop-up in these custom fields

Any help would be much appreciated! I've tried to word the concept clearly here, and am looking for a friendly pointer in the right direction. Even so much as the appropriate keywords so I can find tutorials would help - been a few long hours of head scratching.

Thanks in advance for any help!

# Answer
> 0 votes
Yup, adding my solution for the collective knowledge!

* Created each location as an individual page (appropriately classified by taxonomy/etc. for site navigation)
* Assigned the desired custom fields, most ended being display hidden
* Created new content type, "itinerary-location-reference", using module "Reference" (for D7)
* Within this content type, assigned custom fields for dates/visitor name/etc.
* One of the custom fields needs to be a node reference
* Referenced the location

This creates two nodes that are linked...one is the static location content, the other a node containing date/personal information. I then added this overall reference node to my nodequeues. Done.

I can see a few issues down the road regarding number of entries into the database, but apparently Drupal's good for a few million, so fingers crossed!

---
Tags: datetime
---


# Question
Title: How can I allow users to duplicate a select field while creating a page from a custom content type?
I have one select field (filled with taxonomy terms) in a custom content type. I can't figure out how to allow users to duplicate that select field (select "apples" and then add the select field again -- 2 instances of it now -- and select "oranges") when creating a page with the custom content type.

EDIT: is there perhaps a module that would do this? I've looked at similar kinds of modules like Webform, but none of them seem to be quite what I'm looking for.

# Answer
If you use CCk, you can just edit your field setting in it's global settings and select illimited value number : And you get a button "Add another" : here I just used a text field for the example but it can be a select or anything else
> 0 votes

---
Tags: nodes, entities
---


title: Save an article or story on Drupal 7

text:
# Question
Title: Save an article or story on Drupal 7
How can I save an article or story on Drupal 7?

Is there any modules to install, or do I need to do it programmatically?

**Note :** This is not offline bookmarks kind of stuff, nor is it related to browsers.

# Answer
What I understood from your question and comments, you are looking String Overrides module.
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to show descriptions when a user hovers over a form element
How is the descriptions tooltip done in rubik theme by development seed? I have looked through the entire theme and couldn't identify which is handling this. Is it js or css? https://github.com/developmentseed/rubik

# Answer
The entire tooltip code is found within the Rubik theme in the files core.css and core-rtl.css. The majority is within core.css. The specific piece that *shows* the tooltip is:

```
.page-content .form-item:hover > .description { display:block; }

```

But each tooltip has text contained in `<div class='description'></div>`, so you can search through core.css/core-rtl.css and find statements regarding `.description`
> 4 votes

---
Tags: theming, javascript
---


title: Output view field as link

text:
# Question
Title: Output view field as link
I need to output a field in a view as a field, how can I make part of the path the value of a CCK field?

For example if for a given item, my CCK value = '19' how can I make my path automatically be website.com/directory/19?

# Answer
I think that you can use, in respective field settings of your view, the option `Rewrite the output of this field`. please see this example (in image) with a field `title`. you must replace `[title]` with the respective field tag, according the indication in `Replacement patterns > Fields`.
> 5 votes

---
Tags: views, 6, entities, navigation
---


# Question
Title: Can't moderate content from "View Draft" page using Workbench Moderation
I am using Panels Everywhere, and Workbench Access & Moderation. I have gotten everything to work, but I haven't been able to figure out how to get the block above the content created, that allows the moderator to go from Draft \> Needs Review (or another transition).

9:24 in at http://nodeone.se/node/1024

I can moderate the content from root/node/#/moderation, but can't on the webpage.

Seeing if someone has run into this before and can help me out.

# Answer
Figured this out. Was so easy it was hard...

Had to configure the "Workbench information" block and set it to "Content" region. It then would show up above the content. I also had to add the tags in the "Page elements" panel settings.

Hopefully this will help someone else out.
> 0 votes

---
Tags: 7, panels
---


# Question
Title: Using jQuery to communicate to Drupal 7 via AJAX
I've been learning how to use AJAX with Drupal 7. I already know how to use the '#ajax' attribute with a form and also how to use the 'use-ajax' class with a link.

I have a nice jQuery slider on my page that emits a jQuery event (called 'slide') every time the slider moves to a new picture. The event also contains which slide number we will be viewing. I can bind to the event using jQuery like this:

```
$('.slider').bind('slide', function(e, data) { alert(data.slide); });

```

That will pop up an alert showing the current slide. Instead I want to make an AJAX call using Drupal 7's AJAX and pass this current slide number to Drupal.

I've been searching for an answer and I think it might have something to do with the Drupal.ajax DOM object but I'm not sure.

# Answer
> 19 votes
I am assuming you'd like to display some data when you're moving the slider around.

The way I do it is without using the '#ajax' attribute.

Implement the AJAX call, send the slider value as POST variable to '/foo/ajax':

```
    jQuery('#slider').slider({
            // Define your slider (min, max etc)
            ...
            // Add event handler
            change: function(event, ui) {
                jQuery.ajax({
                    type: 'POST',
                    url: '/foo/ajax',
                    dataType: 'json',
                    success: ajaxCompleted,
                    // Might want to use 'ui' instead of jQuery('#slider').
                    data: 'slider_value=' + jQuery('#slider').slider('values', 0);
                });
            }
    });

```

Make a menu item that's called when the slider moves around:

```
function foo_menu() {
  ...
  $items['foo/ajax'] = array(
    'title' => t('foo AJAX'),
    'type' => MENU_CALLBACK,
    'page callback' => 'foo_ajax',
    'access arguments' => array('access content'),
  );
  ...
  return $items;
}

```

Implement the foo\_ajax page callback:

```
function foo_ajax () {
  // Retrieve the slider value
  $slider_value = (int)$_POST['slider_value'];

  // Get some id's from the foo table
  $result = db_query('SELECT id FROM {foo} WHERE value = :value', array(':value' => $slider_value));
  $data = array();
  foreach ($result as $row) {
    // Do something with data
    // Parse to json

    $data[] = $row->id;
  }

  // Return json
  drupal_json_output($data)
}

```

Implement ajaxCompleted (within your javascript):

```
function ajaxCompleted () {
    // Parse Json
    // Add some stuff to your DOM.
}

```

# Answer
> 1 votes
If I'm understanding correctly you need to setup a Drupal path with a page callback to whatever PHP function is going to handle the slider data. Then just make an AJAX call on slide event. Something like this:

```
$('.slider').bind('slide', function(e, data) {
 var href = path/to/your/drupal/handler;

 $.ajax({
  type: "POST",
  url: href,
  data: {slide: data.slide},
 });

});

```

This way you can 'POST' the slider data to PHP and have the callback function take in the data as an argument and do whatever needs to be done from there. Read up on the jquery $.AJAX function for more options of what you can do with return data, etc etc

edit: Wow someone posted a much more thorough example of the same concept at the same time. Definitely check out his solution for more details!

---
Tags: javascript, ajax
---


# Question
Title: Getting 'bool(false)' output before normal page HTML
I've seen this happen once or twice before, but can't remember where or why.

Basically, in one of my page's HTML output, the first line of HTML is returned as 'bool(false)' - On that particular page, I have a function in hook\_init() that logs in a user using user\_login\_finalize(). Here's the HTML from the

```
page:bool(false)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">
<html lang="en" dir="ltr" version="HTML+RDFa 1.1"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
...

```

On the page as displayed, I get a blank line above my theme's header with this bool(false) appearing.

On refreshes, that goes away (basically, it only happens when I log in a user programmatically using user\_login\_finalize()).

# Answer
> 0 votes
It seems that the problem went away if I commented out the `user_module_invoke()` call inside `user_login_finalize()`.

Obviously, I didn't want to maintain a patch for that, nor did I want to take out that behavior, as I may want to use `hook_user_login()` sometime. So, I basically copied `user_login_finalize()` into my own private function, removed the `user_module_invoke()` call, and am now using the private function for my particular need. Seems to be working fine!

---
Tags: users, theming, sessions
---


# Question
Title: How do i post/donate a module in drupal.org?
I have a module that i have developed, and I want to post it on drupal.org to be available for other developers to download. How do I do that?

# Answer
> 4 votes
http://drupal.org/contribute/development

# Answer
> 3 votes
Essentially, you need to apply for a Git account in order to be able to commit the code in the Drupal.org repository, and create the project for your module. Before doing that, you need to approve the conditions for using Git repositories, and you need to set up your Drupal account to be able to commit code.
Alternatively, you can create a sandbox repository that, differently from the full projects, don't require you apply for a Git account, but don't allow you to create releases for your module.

If you don't want to maintain the module, the second option is maybe the preferable. If somebody is interested in the module, he would probably ask to become co-maintainer, and transform the sandox project in a full project.

---
Tags: 7, community-official-site
---


title: Clean up rdf mappings and vocabularies

text:
# Question
Title: Clean up rdf mappings and vocabularies
In the past I have imported automatically some vocabularies using rdfx/evoc and put some rdf mappings using rdfx ui. The module also made automatic rdf mappings with taxonomy terms and various fields that does not let me delete.

Now I need to clean up the mappings and reach astate of rdf mappings as it would be a fresh install.

RDF UI and other modules do not provide the possibility of deleting mappings.

What tables/fields I have to delete/alter from the database, so to clean up, without damaging the rest of the site? How I can bring rdf\_mapping, mapping BLOB to defaults?

# Answer
> 1 votes
You are more likely to get an answer in the RDF Extensions issue queue on drupa.org. see this comment as an answer to your question: http://drupal.org/node/1296820#comment-5068706

---
Tags: rdf
---


# Question
Title: How do I use Panels to replace a default node page?
In my Drupal 7.8 installation, I have defined a custom content type "Reviews" which has several fields. Instead of displaying the normal Reviews page for every review, I want to display a panel layout with the fields stuck in different panel regions. I have absolutely no clue how to begin doing this, and I couldn't find any simple instructions.

I have Views, Panels, and CTools modules already installed.

Thanks!

# Answer
> 1 votes
I found using Views, panels and Ctools a complex and steep learning curve. Two resources have been very helpful. 1. The video series from Nodeone.se has two video series that can help, "Taming the Beast' (views) and 'Learning Pagemaker'which includes panels. 2. The new book "Drupal's Building Blocks" by Earl and Lynette Miles (Merlinofchaos at drupal.org).

---
Tags: views, nodes, entities, panels
---


# Question
Title: Can't login using OpenId (core) and Google profile
I'm using the OpenId module (included in core v7) but can't link an OpenId to an existing account. Every time I try to add it an error occurs:

> Sorry, that is not a valid OpenID. Ensure you have spelled your ID correctly.

I'm trying to connect using a Google profile. The URL I'm trying is "https://profiles.google.com/x" (x =\> my id).

Has anybody succeeded in doing this?

# Answer
> 0 votes
The following works for me in Drupal 7:

```
https://www.google.com/accounts/o8/id

```

For more information, see Whats My Google OpenID URL?.

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


title: User logout when browser closes

text:
# Question
Title: User logout when browser closes
Is there a way to automatically log out users when they close a browser?
I've tried to set (settings.php)
`ini_set('session.gc_maxlifetime', 0);
ini_set('session.cookie_lifetime', 0);`
but this doesn't work. Seems to me like it has anything to do with the 'sid' stored in the 'sessions' table?

# Answer
There is the session\_expire module, and this module's page has some information about garbage collector confs and stuff.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Ternary Flags? Or possibly cancelling flags
In my Drupal site, users can be in 1 of 3 states. They will always be in one of these three states. This would be easy to do if the flag module could have three states. However, it only has 2. Is there a flag add on that allows for three states? Could I potentially have 3 flags that, when selected, cancel the others out? Or will I have to write my own module?

# Answer
This is not available in the Flag module (as you already know) and won't be available in the future (Issue: Flag States). I have not seen an add-on module that will allow you to do this either.

An easy way would be to use Flag with Rules. You would have to create multiple flags to use, and when a user flags one of the states, have set rules to unflag the other 2 states.

Another option would be to write a custom module. Maybe even utilize the Voting API
> 3 votes

# Answer
checkout the rate module, they have an "emotions" option where you can specify your different states.
> 0 votes

---
Tags: 7, flags
---


# Question
Title: In a message about a new comment, how to tell if the comment needs approval or not?
I am currently using Triggers + Actions to send the node author an email when a new comment is added.

Some of the commentators on my site do not require approval (registered users and repeat commentators).

I would like to indicate in the mail whether the comment requires approval - or send a different message all together in this case. I didn't find any way to configure this.

Answers to a related question suggested the Rules module, but I didn't find a way to make a condition based on whether the comment needs approval.

Edit: I think that the relevant conditions is about comment:status. This field doesn't appear as a data selector in Rules, for some reason.

# Answer
> 0 votes
There is a great tutorial on Rules with a similar use case.

---
Tags: 7, comments, emails
---


# Question
Title: Calculate the greater of two values in Rules?
I'm trying to set up a rule which sets a CCK field to the greater of two other CCK fields, but calculate a value only has +-\*. How do I figure out the greater of two values?

# Answer
> 0 votes
I guess that you can try this to the 'numeric comparison' rule:

here is the lines used with cck fields `field_test1` and `field_test2`:

```
 <?php $field1 = $form_state['values']['field_test1'][0]['value']; echo $field1; ?>
 <?php $field1 = $form_state['values']['field_test2'][0]['value']; echo $field2; ?>

```

---
Tags: rules
---


# Question
Title: How a anonymous user can view profile of authenticated user
How to see a profile of registered user by a anonymous user.

exampel : someuser2

when an administrator clicks any username or someuser2 it displays in this format in url on browser

http://mydomain/users/someuser1

When an anonymous user paste this link on browser, the profile doesn't appear.

Is there any permissions to be ruled out ?, to display user profile.

# Answer
In Drupal 7

* /admin/people/permissions
* Users - Section --\> View user profiles!

Drupal 7 user Permission

In Drupal 6

* /admin/user/permissions
* user module --\> access user profiles
> 1 votes

---
Tags: 7, users, uri
---


# Question
Title: Create a new user programmatically and mimic the registration flow?
I notice we already have an example for programmatically creating a new user in Create a user programmatically and give they a role. However, this example uses `user_save()`, which does not mimic the registration process, (e.g. no email is sent to the user).

Could I use user\_register\_submit()?

# Answer
I'm not clear on what your overall goals are here. However, you might check out the Form Clerk module. You can use it to create users, as well as many other things.

> Form Clerk is an administrative utility that provides a semi-automated way to input data into a Drupal form. Multiple instances of form data can be entered with one command. For example, multiple users with varying permissions can be created, or multiple articles with arbitrary content can be added.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How to make my site's categories appear in Google results?
I would like my site's categories to appear in the Google results. For example the bbc.co.uk has the categories "News","Learning English", etc.

Is there any module for this? Has this to do with RDF, microformats, or rich snippnets?

# Answer
Drupal is fantastic for building SEO sites but still I think you can not do this. Google does this. The official source is: http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=47334
> 3 votes

# Answer
Sites with Sitelinks - the name for the indented category listings you see on Google search results - seem to share some characteristics, from what I've found when trying to achieve the same:

* Strong presence (both in terms of search traffic and search term, particularly for brands)
* Diverse and natural backlinks to the site and pages
* Thoughtful information architecture/ site architecture

I would say that the first point is the most important, as Google seems to imply 'authority' with the search results it returns in the Sitelinks format. The subsequent two points *may* be entirely incidental characteristics - but they definitely don't do any harm!

There's nothing particular to Drupal about Sitelinks, though. Whether it's Wordpress, Magento, Drupal or a custom-built site, Sitelinks are platform-agnostic.
> 1 votes

---
Tags: search
---


title: Taxonomy term individual occupant

text:
# Question
Title: Taxonomy term individual occupant
can anyone tell me if there is a way to set the terms under a taxonomy to have only one node?

I am building a system which is based on taxonomies but each term should contain only one one. If any user tries to save a node under an occupied term, I need it to be disallowed.

Can anyone help with some insight?

# Answer
> 1 votes
you could use a hook\_form\_alter when a node is saved and check if the selected term has already been used. Then just show an error message.

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


# Question
Title: taxonomy terms that get URL aliases and then end up being ugly google sitelinks
Including tags of course. I used some tags like that I thought would be running in the background to use them as view filters, but then end up being google sitelinks such as 'subject-teaser-list'. How ugly and unprofessional that looks!

I rather have no sitelinks at all instead of these ugly looking sitelinks. You have this result when search google for 'breinwijzer'

cheers,

# Answer
you can manage which links are used for sitelinks in Google's webmaster tools.

To change the description that is used you can use nodewords (or metatag for D7).

Here is some more info about the recent change in Google's sitelinks feature.
> 1 votes

---
Tags: 6, navigation, taxonomy-terms
---


# Question
Title: Is it stable to run Drupal 7.8 on php 5.3.8?
I would like to make use of php 5.3.x built-in fastcgi functionality and therefore I would like to migrate from php 5.2.x to php 5.3.8.

Is it stable to run Drupal 7.8 on php 5.3.8 ?

# Answer
Yes. In fact, it is recommended to do so.
> 4 votes

---
Tags: 7, migrations
---


title: How should I modify a contrib module?

text:
# Question
Title: How should I modify a contrib module?
I have to modify a contrib module with a custom function. In my case I can't use hooks to extend it.

Is there a best practice, for example renaming the module and placing in `sites/default/modules`?

# Answer
If your addition is general and not specific to your site, you could create an issue and post a patch there.

And even if you have a site specific extension, maybe it can be solved in a way that just requires an additional hook to the contrib module itself which could be useful for other use cases as well. Then you could again create an issue for that.
> 7 votes

# Answer
What I've found useful is to add a contrib and a custom folder, or maybe a contrib-custom folder inside modules folder, there you can move the modules that you've created or contrib modified.

Additionally you need to keep track of the patch that you applied somewhere, maybe a patches folder with the .patch and a readme of the changes.
> 4 votes

# Answer
Depending on your situation, you can try creating a patch for it so that the module can still be updated and you can re-apply the patch file after updates to the module to keep your customizations.
> 1 votes

---
Tags: 7
---


title: domain access module in drupal

text:
# Question
Title: domain access module in drupal
I try to set up drupal multisite by using domain access module.we two sites sscsoftweb.com and kumba.sscsoftweb.com.Both are drupal sites which host in shared environment.i install domain access module in sscsoftweb.com. kumba.sscsoftweb.com is subdomain as per installation instruction i remove text followed after /public\_html

Then i create a new domain record and create two page called page1 and page2.page1 published in sscsoftweb.com similarly page2 publish in kumba.sscsoftweb.com.i set the homepage for kumba.sscsoftweb.com is node/2.

the problem is when i hit kumba.sscsoftweb.com it automatically redirect to sscsoftweb.com homepage not to node/2. is there any thing i miss.kindly suggest me how to fix this issue.

thanks..

# Answer
> 1 votes
I played with the domain access module and I remember I had to set the cookie domain in settings.php to ".example.com", in your case ".sscsoftweb.com". But I'm not sure this will fix your problem.

---
Tags: 7, domain-access
---


# Question
Title: How to override a block generated by a module?
The PCP module has a pcp-block.tpl.php file in it's module directory that generates a block output. To change that output I read that I could just copy this file into the "templates" folder of my current theme and it would take precedence over the one in the module directory. But it's not working. I did clear the theme registry cache. How do I get it to work?

# Answer
> 3 votes
Have you copied block.tpl.php to your template directory as well? In Drupal 6 you need to have the base form before a more specific template will be used. For example before region-sidebar.tpl.php takes, you need region.tpl.php; before node-story.tpl.php, you need node.tpl.php. In D6 the block.tpl.php is in modules/system/.

I don't use D7, and it could've changed as David G. says.

# Answer
> 1 votes
I guess it should work if you placed the same tpl file in your corresponding folder. Also please make sure that you saved the theme configuration settings.

# Answer
> 0 votes
In D6 in order to override theme templates the base template needs to be in your folder for your local overrides to be seen. I was under the impression this was not needed in D7.

---
Tags: 7, theming
---


title: How do I add JavaScript to a site?

text:
# Question
Title: How do I add JavaScript to a site?
How can I add JavaScript and CSS to my site?

# Answer
The Managing JavaScript in Drupal 7 guide provides the information to add JavaScript to Drupal. The techniques presented there apply to both themes and (custom) modules:

Note that Drupal already include jQuery, jQuery UI and a bunch of other libraries so you don't, and shouldn't, add them yourself. Instead you should use `drupal_add_library()` or the `#attached['library']` property.

The Working with CSS guide provides the information to add CSS to Drupal. Again, the techniques presented there apply to both themes and (custom) modules. With an exception: addition of style sheets from an `.info` files only works for a theme and not a module.

* Add `stylesheets[all][] = somestylesheet.css` to a theme's `.info` file.
* Use drupal\_add\_css() from module or theme's code.
* Use `#attached[css]` property in a From API or renderable array.
> 23 votes

# Answer
You can place your js file in your theme folder and add this js file to drupal by using `drupal_add_js()` in template.php preprocess functions.
> 2 votes

---
Tags: javascript, theming
---


# Question
Title: What would be the most efficient way to select node for a content type?
Right now i am using this query :

```
$query_info = db_query("SELECT nid FROM {node} WHERE type=:type  AND language = :language AND status=1",
                array (':language'=> $language->language, ":type" => 'info_pages' , ))->fetchCol();
$info_pages = node_load_multiple($query_info);

```

As this site is going to have lots and lots of content I am wondering if this is the right way ? If not what would be a better approach ?

# Answer
> 13 votes
```
<?php
$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title', 'status'))
  ->condition('type', 'info_page')
  ->addTag('node_access')
  ->execute();
while ($result = $query->fetch()) {
  print_r($result);
}

```

Query against node table must be a dynamic query with "node\_access" tagging to prevent node access system by-passing.

# Answer
> 0 votes
If you wish to retrieve nodes of particular content type and want to display somewhere, obviously you can use the powerful module "VIEWS" by using which you can do all the magic.

---
Tags: 7, nodes
---


# Question
Title: How can I hide a field with Views if another field has a certain value?
In my Drupal 7.8 website (with the Views and Panels modules installed), I'm trying to display a view pane in a panel. However, I only want to show certain fields in that pane if another field has a certain value.

Example: I display fields Foods, Healthy, and Unhealthy from a node using a custom view pane. But I only want to display fields Healthy and Unhealthy if field Foods (which is a multi-select field) contains the value "Cheetos"

Does anybody know how I can do this with a plugin or with views default functionality?

# Answer
> 5 votes
Solution1: You can add filter in view by selecting and restricting the value of "Foods" field since if foods has the selected option then only it will display the results.

Solution2: Just add one more field with php custom field(use views customfield module) and exclude display of all other 3 fields. In this php field you can get all the previous field values in $data variable so you can print the result as you wish by validating using php.

Hope this can help you out!

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


# Question
Title: How do I remove the tabs from the edit field collection form in Drupal 7?
When editing a field collection on a node there are two tabs typically, view and edit. I wanted to remove them. Obviously I can hide them with CSS, but this feels like the wrong way to do it. Is there a better way?

# Answer
If you want to do this with code, you can use hook\_menu\_alter(). Set the "type" to MENU\_CALLBACK. This will still keep the path registered, but it will not show a tab. More inforamtion
> 3 votes

# Answer
tab tamer has just been ported to D7 a week ago and might be able to remove those tabs as well.
> 4 votes

---
Tags: 7, theming
---


# Question
Title: Which core function might do a "SELECT * FROM" query on a custom module table?
I have a Drupal 6 website which is hosted on a shared hosting service and which is used to communicate with a desktop software application. Over the years I extended the user profile with over 70 different profile fields. With over 45.000 users this resulted in a profile\_values table containing over 1.200.000 rows and I was getting complaints about slow queries and I've read it might lead to performance issues. Switching host or upgrading Drupal 6 to Drupal 7 is **not** an option!

Since the profile data is only used when the software communicates with the website, which is done once per application start I did not really have a need for such a large profile table so I created a custom module which stores the profile data per user in a single row as a serialized array. This also has the benefit that I don't need to update my website every time a new profile value is added in the software.

But my MySQL slow query log is filling up again. The query that's logged is `SELECT * FROM {my_table}`. As I know this table is quite large I was careful not do call such a query myself and therefore I cannot find this query in my module or any of the modules that use my module. I always select a single column and pass a specific parameter to check.

As far as I can see there are only two functions that might have an influence on this. I implement `hook_user()` for `insert` and `update` operations and I call `drupal_write_record()` when saving the user data. But running through the code I fail to see where such a query might be called.

From where might this query originate from?

# Answer
If `grep/ack-grep` can't find `SELECT *`, just add the following code.

```
$debug_query = 'SELECT * FROM {mytable}';
if (substr($query, 0, strlen($debug_query)) == $debug_query) {
  error_log(print_r(debug_backtrace(), TRUE), 4);
}

```
> 4 votes

---
Tags: 6, database
---


# Question
Title: Can I add a page without clearing cache?
I have written a module by which user can add custom pages. Do I need to clear the cache every time user adds a page? Is there a way to adding pages without clearing cache? If yes what is it? and if no what's the function I should call?

Is `hook_menu` the only function I should put my code in it?

Does the Views module clear cache after submitting a new page?

# Answer
It's not clearing the cache you should do, it's `menu_rebuild();` if you change router items.
> 3 votes

---
Tags: routes, hooks, 7, uri
---


# Question
Title: Pass an argument to a Rules Action using VBO
If I create a Rules Action to set the value of a CCK field, and point to that action from VBO, is there a way to add user inputs to the VBO form on the views page to pass parameters to the Rules Action?

I would prefer a way to do this through GUI if possible.

# Answer
> 8 votes
Explaining how to create Rule that accept arguments (user can enter any value) and adding VBO field in Views: The Power of Rules with Views Bulk Operations (and Commerce)

From Joren comment:

```
 function modulename_form_views_form_test_view_page_alter(&$form, $form_state, $form_id) {
    $form['#submit'][] = 'modulename_vbo_submit';
    $form['select']['arg'] = array( '#type' => 'textfield', '#title' => t('Whatever') );
 }
 function modulename_vbo_submit(&$form, $form_state) {
   $nids = $form_state['selection'];
   foreach ($nids as $nid) {
     $node = node_load($nid);
     rules_invoke_component('rules_test', $node, $form_state['values']['arg']);
     drupal_goto('test-view');
   }
 }

```

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


# Question
Title: Create dynamic page with dynamic addresses
My module creates pages. These pages have dynamic addresses, such as:

How do I assign a page callback to these pages? I get the "page not found error" on these pages.

I am using Drupal 7.

# Answer
> 1 votes
I don't understand what you mean by "my module creates pages". It sounds as if you meant to say "URLs" instead of "pages".

Anyway, if you want to link a callback to a URL, you need to implement hook\_menu() in a custom module. See the menu\_example module and its hook\_menu implementation menu\_example\_menu for an example.

# Answer
> 0 votes
You should implement hook\_menu\_alter to tell Drupal about your dynamically generated paths

---
Tags: uri, routes
---


title: Using node reference question

text:
# Question
Title: Using node reference question
In Drupal-6 I have a content type called: **Colors** with the following fields: **title**, **body** and **code**. Then I have another content type called: **Material** with the following fields: **title**, **body** and **color**. This **color** field is a **node reference** related to the Colors content type.

So far so good.

Now when I create a **Material** node I can select a color from a select list. And here is my issue: this select list shows the **title** of the colors nodes. Is there any way to show the **code** for the node instead of the **title**. Or better, show the **title** and the **code**.

# Answer
You can use a view to show the nodes that can be referenced, have a look at the settings of the widget, it's been a while since I used D6, but if you select title and code inside your view it should be visible when you edit a Material node.
> 1 votes

---
Tags: nodes
---


# Question
Title: Views and joining content types on specific field in Drupal 7
How can I 'LEFT OUTER JOIN' *or* 'LEFT JOIN' using Views in Drupal 7.

Here is what I'm trying to do, using an example from Wikipedia:

I have 2 content types: Employee's and Department's (tables below)

The "DepartmentID" noted in the Employee Table below in my case would be the NodeID of the department from the "Department" custom content type.

How can I use Drupal 7's Views module to Display a list of employees with the department name pulled from another content type as noted in the graphic below?

(The SQL statement below is really what I'm hoping to be able to do with the Views module, the table is the output I'm hoping to achieve.)

# Answer
In views 3 you have the **relationships** which manage JOINS between tables.
First you add your relation with the table and then in the next screen you can select *Require this relationship*.

If you check this checkbox, a `LEFT JOIN` will be made between the tables, if you uncheck it, it will generate a `LEFT OUTER JOIN`.
> 6 votes

---
Tags: 7, views
---


# Question
Title: Is it possible to hide certain content type options?
I have a module which creates a new content type attached to a Feed. For this content type having options such as "Comment settings" or "Revision information" makes no sense. Is there a way to hide those?

# Answer
> 1 votes
I assume your logged in as admin (user 1), so you'll always see them, but for other users it depends on the permissions they have and you can also use http://drupal.org/project/override\_node\_options to toggle this for each role

---
Tags: 7, nodes
---


title: How does the service module work?

text:
# Question
Title: How does the service module work?
i am using drupal 6 and services 6.3x module but i am unable to use this module completely. I have enabled rest server module also. I added a new service and added resources to it. I added node resource to it and i am able to fetch all the nodes in json format

what i am not able to understand is :-

1. The exact uri or may be the procedure to call getTree method in taxonomy\_vocabulary resource
2. How to acccess all the methods (CRUD) functions under every resource enabled
3. The url -\> mydomain.com/service/rest/node.json works for me but how can i access the getTree method ??

I am stuck on this like forever i have even posted jobs on the drupal site but i guess there are very rare people who have knowledge about this.

**Edit :-**

Live link is http://delvelogic.com/merchant/drupal-6.22/services/rest/taxonomy\_vocabulary

The following is the java code i am using :-

```
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = null;
    HttpPost postMethod = new HttpPost("http://delvelogic.com/merchant/drupal-6.22/rest/taxonomy_vocabulary/getTree.json");
    postMethod.addHeader("Content-type", "application/x-www-form-urlencoded");
    postMethod.addHeader("Accept","application/json");
  //  postMethod.addHeader("Authorization", "basic " + Base64.encodeBytes(("admin"+":"+"admin123").getBytes()));
 //   httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT));

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     nameValuePairs.add(new BasicNameValuePair("vid", ""+1));
     nameValuePairs.add(new BasicNameValuePair("parent", ""+1));
     nameValuePairs.add(new BasicNameValuePair("maxdepth",""+1));
    // nameValuePairs.add(new BasicNameValuePair())
    try{
     postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     response = httpClient.execute(postMethod);

     InputStream input = response.getEntity().getContent();
      BufferedReader rd = new BufferedReader(new InputStreamReader(input),input.toString().length());
     String line;
     StringBuilder sb =  new StringBuilder();
     while ((line = rd.readLine()) != null) {
            sb.append(line);
     }
     rd.close();
     uploadresponse = sb.toString();

     Log.d("Response", ""+uploadresponse);
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

```

Also if there is any firefox add on so that i can actually see the method working ??

**Edit Again :-**

I have found this add on restclient to work on firefox

i choose the method as post in the url i typed http://delvelogic.com/merchant/drupal-6.22/services/rest/taxonomy\_vocabulary/getTree

added header :-

Content-type : application/x-www-form-urlencoded

Accept : application/json

request body :-

&vid=1&parent=1&maxdepth=1

it gives me 404 not found with no vocabulary with id 1 found Thanks in advance

# Answer
According to the documentation the URLs shouldn't necessarily have .json at the end, but I guess this is a setting you've changed if it's working for the node functions. I know you're not going to like this answer (I'm fairly certain you've tried it before) but the URL is: `mydomain.com/service/rest/taxonomy_vocabulary/getTree`. I've even been through the service and rest\_server modules' respective code and that is definitely what it should be.

For further proof look at the (valid, passed) test module for services taxonomy\_vocabulary:

ServicesResourceTaxonomyTests::testVocabularyGetTree.

You'll see that the URLs accessed by this successfully passed test are: `$path . '/taxonomy_vocabulary/getTree'`, where `$path` is the path to the endpoint (i.e. `mymodule.com/service/rest/`).

It really would help if you could provide a live link though so we can test to see if the problem is in your Java code or with Drupal (although the latter seems very unlikely).

EDIT

p.s. do comment on this answer as I have a lot of experience with the services module and I'm sure I can point you in the right direction with a bit more info. It pains me to see someone struggling with something that I've had nothing but joy with in the past!

ANOTHER EDIT

This is the response I get from `http://delvelogic.com/merchant/drupal-6.22/services/rest/taxonomy_vocabulary`:

```
<?xml version="1.0" encoding="utf-8"?>
  <result>
    <nodes/>
    <module>taxonomy</module>
    <name></name>
    <help></help>
    <relations>0</relations>
    <hierarchy>0</hierarchy>
    <multiple>0</multiple>
    <required>0</required>
    <tags>0</tags>
    <weight>0</weight>
    <vid>4</vid>
  </result>

```

Notice the `<vid>4</vid>` bit...I'm pretty sure the `vid` you should be looking for is `4`, not `1`!
> 1 votes

---
Tags: 8
---


# Question
Title: I need to update jQuery version for drupal manually?
For updating the drupal core jquery file i used the jquery\_update contributed module. This module help me a lot to use some of the new function/method of jquery.

But In my view i'm using ajax for pagination and exposed filter form submission. My view containing very bulky data so most of the time most of the browser giving me a script error saying - script is unresponsive, file is ...jquery.min.js

And as my table data is growing up this script error is coming up frequently (that's halt every thing on browser).

Actually this file came into the picture when i install the jquery\_update module. By my personal experience i know the reason (basically file conflict).

So i just want to know how to replace the drupal default jquery file with jquery's latest version file manually.

Any suggestion or guidance will really gonna help me a lot.

# Answer
> 3 votes
1- @see `/misc/jquery.js`

2- its better to add ur jquery to your theme .info file

* go to your theme folder
* insert your jquery file into the same folder of your theme (E.g theme name new\_jquery.js)
* in the same directory open yourThemName.info file
* add this line `scripts[] = new_jquery.js`

3- its not prefered to use Jquery 1.6 with Drupal 6

4- use jQuery.noConflict() to avoid conflict

# Answer
> 1 votes
First have a look at this post on Drupal.org, some of the posters claim to have got jQuery 1.5.1 working with Drupal 6.

It's pretty much definite that you won't get the latest version of jQuery into Drupal 6, I've heard of people managing to get as far as v1.4.4 (and now v.1.5.1) but the differences between 1.3.2 and 1.6.4 and just too much for Drupal to handle automatically.

The main problem seems to be that installing any version of jQuery \>1.3.2 breaks a lot of the core javascript functions (including views). Some people mitigate this to some extent by dropping a later version of the library into sites/all/modules/jquery\_update/replace (overwriting the existing jquery.min.js file) and then hacking the jquery\_update module itself to only preform a replacement on non-admin pages (i.e. those that wouldn't suffer from needing Drupal's default jQuery version). See my answer on this post for more details, and also run this Google search and have a look at the first 5 or 6 links there, they have some very good information.

To be honest though I don't think installing an updated version of jQuery will help with this problem anyway, if your scripts are becoming unresponsive then the problem is that the PHP script at the other end is taking too long to respond...I'm almost positive there's nothing jQuery will be able to do about that. Could you look at reducing the number of items on each of views pages or reducing the complexity of the view's database query instead?

---
Tags: javascript
---


# Question
Title: Querying taxonomy terms with the level hierarchy
I am currently struggling against a problem I can't fix, probably because of my scarce knowledge of the Drupal API.

I have a taxonomy tree that looks like the following one:

```
    SHOE BRANDS 143
         KIDS   151
         MEN    152
            STIVALE/BOOT    164
            SANDAL  165
            PANTOFOLA/LOAFER    198
            MOCASSIN    199
            DERBY   200
            FRANCESINA/OXFORD   201
            POLACCHINO/ANKLE BOOT   202
            SNEAKER 203
        OUTDOOR/SPORT   153
        WOMEN   154
            STIVALE/BOOT    166
            SANDAL  167
            POLACCHINO/ANKLE BOOT   189
            SNEAKER 190
            DERBY   191
            FRANCESINA/OXFORD   192
            PANTOFOLA/LOAFER    193
            SABOT   194
            MOCASSIN    195
            BALLERINA   196
            DECOLLETEE/PUMP 197

```

What I need to do is to populate a select box with the child elements of the "SHOE BRANDS" parent (which should be "KIDS" "MEN" "OUTDOOR" and "WOMEN"). After that I will populate a second select box with an Ajax call passing the **tid**, to get all the different shoe types.

The query I'm using to populate the first select is this one (and the problem rises here):

```
SELECT *
FROM node
INNER JOIN term_node AS tn
ON node.vid = tn.vid
LEFT JOIN content_type_extra_content AS xc
ON node.vid = xc.vid
WHERE tn.tid IN (SELECT th.tid FROM term_hierarchy AS th WHERE th.parent = '143')
GROUP BY tn.tid

```

Note the '143' which is the tid of the "SHOE BRANDS" term.

Don't know why, but I only get as output "KIDS" and "OUTDOOR" (which are the only terms with no child elements.

Am I missing something in my syntax?

# Answer
have you reviewed taxonomy\_get\_tree() documentation? http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy\_get\_tree/6 I guess that taxonomy\_get\_tree() documentation and code function could be a guidance.

> **taxonomy\_get\_tree** ...
>
> Return value
>
> An array of all term objects in the tree. Each term object is extended to have "depth" and "parents" attributes in addition to its normal ones.
> 1 votes

# Answer
I would suggest you remove the none-relevant LEFT join, and use only joins, rather then subselects.

```
SELECT td.name, td.tid
FROM node n
INNER JOIN term_node AS tn ON node.vid = tn.vid
INNER JOIN term_data AS td ON tn.tid = td.tid
INNER JOIN term_hierarchy AS th ON tn.tid = th.tid
WHERE th.parent = '143'
GROUP BY tn.tid

```

The `GROUP BY` might provide a problem to, so try removing that to see if you get more results. You will probably see carthesian products then, which you can reduce with a `SELECT DISTINCT()` instead of the select all.
> 0 votes

---
Tags: taxonomy-terms, database
---


# Question
Title: Unable to upload video files in drupal 7 with the video module
I am trying to make a simple video uploading site with Drupal. I am using the Video module. Let me tell you what I have done:

1) Just made a fresh installation of Drupal 7.7

2) Installed the Video module

3) Enabled the following

* Video
* Video UI

Now when I go to configuration tab I see the following error:

> Exception: You must have the cURL extension enabled to use this library. in require\_once() (line 22 of C:\wamp\www\freshdrupal\sites\all\modules\video\libraries\zencoder-php\Zencoder.php).

However I can still create a new content type and add field of video type. In that case when I add a content and upload video it gaves the same exception error as shown above.

Please help. If there is any substitute module for doing the same please tell me so. I need it urgently.

# Answer
> 2 votes
According to your error, you need to have CURL installed.

If you're running a mac: http://www.davidonzo.com/lng/en/post/986/php-mac-os-x-how-to-install-the-curl-library/

If you're running linux: type in the command line - "apt-get install curl"

If you're running WAMP on Windows: click the WAMP icon in task tray, then go to PHP \> PHP Extensions \> php\_curl. Then restart apache.

# Answer
> 0 votes
for the video module you have to configure an encoder, either FFMPEG (for video encoding on your server) or Zencoder (video encoding service).

Make sure to follow all the steps to configure Zencoder correctly including postback (I believe the postback is by ftp).

---
Tags: files, media
---


# Question
Title: SQL + Drupal: how to filter correctly using SQL within a Drupal Database?
I have been using Drupal for quite sometime, but now I have come to a crossroad: using MySQL to extract data from my site's database via phpMyAdmin.

Everything was going great with the basics (I was going through w3school's tutorials), I learned a lot about SELECT, operators, booleans, etc., but then I came to a stop while trying to filter my results concerning dates, with UNIX TIMESTAMP.

I need to be able to filter results between two dates and, no matter what I do or try, my results are wrong.

I have been trying to wrap my head around this concept (which I believe I already have) but I haven't been able to filter correctly using timestamps.

I went back to square 1 to review syntax, so I want to think that's not my problem, but I definitely need help.

Has anyone found something in the web that might cover this issue? Everytime I look for UNIX TIMESTAMP articles, they are quite superficial (I guess this is not a very hard issue after all).

Thanks in advance.

# Answer
> 3 votes
I'll make an attempt but I haven't quite identified the problem yet. Does your result set deviate from the expected? Is there an error? Answers to those could make it easier to assist.

A Unix timestamp is simply the number of seconds since Jan 1st, 1970.

The query

```
SELECT type FROM node
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y') = 2011
    AND FROM_UNIXTIME(created, '%m') = 07;

```

works for me; it returns all nodes of type 'page' created in month 7 of year 2011. These queries also work:

```
SELECT * FROM node -- all pages from July
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y-%m') = '2011-07';

SELECT * FROM node -- all pages from May, June, July
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y-%m') BETWEEN '2011-05' AND '2011-07';

SELECT * FROM node -- all pages from weeks 33, 34, 35, 36, starting on Mondays
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%u') BETWEEN 33 AND 36;

SELECT * FROM node -- all pages created between 8 morning and 4 afternoon
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%H') BETWEEN 8 AND 16;

```

However, you can also use PHP to generate a Unix timestamp from a date, then simply compare that with the stored values (following is untested):

```
$t1 = mktime(0, 0, 0, 5, 1, 2011);
$t2 = mktime(23, 59, 59, 7, 31, 2011);
//$t2 = mktime(0, 0, -1, 8, 1, 2011); // 1 second before midnight Jul 31/Aug 1st.
SELECT * FROM node -- all pages from May, June, and July
    WHERE TYPE = 'page'
    AND created BETWEEN $t1 AND $t2;

```

I would suggest you take an exact query you're trying to use and execute it directly against the database in order to determine if the problem is with the query or something else. If it is the query, play around in there until you get the desired result or ask for help.

NB: Drupal expects tables to be enclosed in braces, in case it needs to handle table prefixes. This means the first query (in Drupal) should look like this:

```
SELECT type FROM {node}
    WHERE TYPE = 'page'
    AND FROM_UNIXTIME(created, '%Y') = 2011
    AND FROM_UNIXTIME(created, '%m') = 07;

```

If you don't use table prefixes it's not necessary (that is, it should still work) but it's good practice to always include them regardless.

# Answer
> 0 votes
I use this page to convert the dates and then use it in my query. Hope this works for you.

# Answer
> 0 votes
I came up with something like this:

```
SELECT SUBSTR(field_actu_fecha_value, 1, 10), COUNT(*)
FROM content_type_actualidad
WHERE  `field_actu_fecha_value` >= '2011-05-21'
AND  `field_actu_fecha_value` <= '2011-06-01'
GROUP BY SUBSTR(field_actu_fecha_value, 1, 10)

```

I learned a lot about "DATE TIME" and how Drupal fortunately uses ISO time (so you don't have to deal with UNIXTIME, although it does not hurt to know about this too), so you can break the "DATE TIME" to search and refine your search as specifically as you need to.

For example, here I am filtering all "content\_type\_actualidad" nodes from the very last week of May 2011, and counting those results too.

---
Tags: database
---


# Question
Title: Error when submit a Webform with Ajax using Jquery
I am having a webform in my drupal. I am using the jquery Ajax submit method to submit it.

This is the code I am using.

```
$("#webform-client-form-59--3").ajaxForm(function() {

$(".talk-region").html("<h3>Thankyou,</h3> Our representative will be contacting you soon.<br/><a href=\'#\'>Close</a>")

});

$("#webform-client-form-59--3").validate();

```

But when I check in firebug.. Its posting, but the response am getting is

```
302 Moved Temporarily
        5.2s

```

# Answer
If you want to submit a webform, or any form for that matter, with jquery try calling the .click() event for the submit button or call the .submit() function for the form object. If it's properly 'ajaxified' by drupal (using the use-ajax class) the click on the submit button should def submit the form.

jquery .click()

jquery .submit()
> 0 votes

---
Tags: 7, ajax, javascript, webforms
---


# Question
Title: Creating new content type (programmatically) with CCK fields as default
> **Possible Duplicate:**
> Module development - integrating custom content types

Is there any way to programmatically create a new content type with few CCK default fields? I don't want to add those fields after I created the content type, but I want them to be delivered with my module instead Luca

# Answer
> 3 votes
there are several suggestions about create CCK programatically (also can be seeking for CCK import content):

I extract interesting comments from StackExchange:

>

I hope this information be useful

---
Tags: entities, nodes
---


# Question
Title: Blocking a certain user from apearing in user search results
I'm looking for a way to exclude certain users (by ID or name) from appearing in the user search results in Drupal 7.

Any thoughts?

# Answer
If you're using drupal search out of the box to search users, that should still call implementations of hook\_search\_page

Build a small custom module that implements hook\_search\_page, parse thru `$results` and remove anything you don't want appearing in search results.

```
function custom_module_search_page($results) {
  foreach($results as $result_index => $result) {
    //do something, maybe detect for a user id
    //and run unset($results[$result_index]); if the criteria is met
  }
}

```
> 2 votes

---
Tags: 7, users, search
---


title: execute a php code after a user login

text:
# Question
Title: execute a php code after a user login
I see that triggers page is changed from the version 6, It's pretty wierd.. I can't find When user logs in execute a php code thing...

What I have to do is exactly that.. control some user roles depending on his location (intranet or internet) I already have the php code developed but...can't find how to put it ....

```
$usr = user_load($uid);

$array_roles=array();
//supose i'm logging in from internet
    $details = array(
        'uid' => $uid,
        'roles' => array(
            21 => 'Internet'
            )
        );

foreach($usr->roles as $key=>$value)
{

 if ($key!=20 and $key!=21) // exclude internet or intranet roles
 {

  $details['roles'][$key]=$value;
 }
}

user_save($usr, $details);

```

# Answer
> 2 votes
The best way to execute your custom code after a user logs in is by implementing hook\_user\_login in a small custom module you build yourself. Turn that php you wrote into a function then call it.

i.e.

```
function module_name_user_login(&$edit, $account) {
  module_name_user_function($account->uid);
}

function module_name_user_function($uid) {
$usr = user_load($uid);

$array_roles=array();
//supose i'm logging in from internet
$details = array(
    'uid' => $uid,
    'roles' => array(
        21 => 'Internet'
        )
    );
foreach($usr->roles as $key=>$value) {
  if ($key!=20 and $key!=21) {
  $details['roles'][$key]=$value;
  }
}
user_save($usr, $details);
}

```

More about custom modules, and modules all around can be found at The Module Developer's Guide

I would not recommend putting custom php in a trigger and action. **Keeping custom code in the database is always dangerous** for people coming down the line that have to maintain your site in the future.

# Answer
> 1 votes
What you want is the Rules module -- you can do this exact thing. Simply create a new rule, select "user login" as the condition, and add a new action "execute custom PHP".

---
Tags: 7, migrations, users, rules, actions
---


# Question
Title: "Node Recommendation" Module alternatives
I what hoping to use the Node Recommendation module for drupal 6, but after testing it for a while I have come to realize that this particular module has to many issues.

http://drupal.org/project/noderecommendation

The idea of the module is excellent! give node recommendations based on related taxonomy terms and content types.

Are there any alternatives that are under active development and are stable enough that do something similar?

Thank you.

# Answer
> 3 votes
There are two excellent modules, both compatible with Drupal versions 6 *and* 7:

1. If you want to display similar nodes calculated by the actual node content, try Similar entries
2. If you want to display similar nodes calculated by some sort of taxonomy setup, try Similar By Terms

There's also Relevant Content, a module which allows you to configure the recommended nodes based on many different things, with different block configurations and stuff for dealing with CCK. I haven't used it, but I've heard it's quite good.

# Answer
> 2 votes
May be relatedcontent. . But I prefer Views for this as more flexible tools.

---
Tags: 7, nodes
---


title: Setting menu trail of subpage of a node

text:
# Question
Title: Setting menu trail of subpage of a node
I'm trying to have a subpage for a special content type. Everything is working fine, also the breadcrumb is working now.

Only the active menu trail isn't showing up and I really don't know how to hack into the right process. Are there any special functions helping me with this problem?

I tried `menu_set_active_trail()`, but having problems with nodes placed in a menu by the user where I cannot get the previous menu trail for the node itself.

I hope you can help.
Thanks in advanced!

# Answer
The function you need is menu\_tree\_set\_path. It will be released with Drupal 7.9.

If you can't wait, the workaround is to use this code in hook\_init:

```
<?php
$item = menu_get_item();
$item['href'] = '<the href of an existing menu link>';
menu_set_item(NULL, $item);
?>

```
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How can the <any>-value be passed as a param in a filtered url for a View?
I have created a View with two exposed filters: name and status. The name is a text field, the status is a key|name list: 10|one,20|two,30|three

Using the View as a page, the user can filter the view by entering a text into the name field. The user can filter the status from a dropdown. The dropdown shows 'one' by default because that is the most used filtering.

Everything ok so far.

Now I would like to construct a url as well for this filtering. No problem for the name: view\_name?name=richard works perfectly.

For a specific status this also works well: view\_name?status=10 (only the key is accepted as a value).

For some views I would like to show all records for one name, whatever the status is. The status defaults to 'one' (which must stay like that) therefore it is not enough to only pass a name. I have to pass something for the status as well. I tried things like:
view\_name?status=
view\_name?status=10&status=20 (only last value is used)
view\_name?status=0
view\_name?status=-1
view\_name?status=\*
view\_name?status=Any

How can I pass the Any-value through the url ?

# Answer
I suddenly realized that the passed value probably has to match one of the values in the select-options. I just had to look at the source of user page. The value for the Any-option is All. So this works:

```
view_name?status=All

```
> 1 votes

---
Tags: views, uri
---


# Question
Title: How do I make a horizontal user login block for the top user region?
I'm not sure why but Drupal doesn't provide for a horizontal user login with the register or forgot password links. How do I do this?

# Answer
> 7 votes
There are many many ways to do this, there is even a screencast and a module to do this. I would personally do this from the theme layer using css, or if I was using Fusion as a base theme, I would do this from the block configuration (thanks Skinr!)

I'm adding some links that will help you out.

http://drupal.org/project/userloginbar

http://ericlondon.com/changing-user-login-block-horizontal-layout

http://www.youtube.com/watch?v=XMyOX6v-k3Y

http://www.victheme.com/blog/drupal-7-creating-horizontal-login-bar-without-module

---
Tags: theming, users
---


title: Drupal with frames

text:
# Question
Title: Drupal with frames
I'm using Drupal 7 to create a musician's website. That musician would like to be able to play a sample of their music across multiple pages of the site without interruption. The only way I know to do this is to use frames. However, in the many sites I've used Drupal for, I've never used frames on a single Drupal site.

Has anybody else had experience with how to accomplish this?

EDIT: To clarify, the client wants an integrated music player within the site itself. Creating or finding a music player is easy. It's setting up to work with Drupal and not reload across pages that I don't know how to accomplish.

# Answer
You can just open new window via js and play it there. You can now navigate through site and music will play until you don't close certain window. So you should create page/node with player, create page template for it (you should remove showing block, menus, etc in this) and point for js:window.open to that page.
> 2 votes

---
Tags: 7
---


# Question
Title: Using tokens or variables in Views "No Result Text" field
How can I include a variable or token as a replacement in views "No Results Text"?

I would like to have information from the currently logged in users account populate this section when it would have otherwise been empty.

I would also like to access the second argument passed in the URL as replacement text.

`example/values/passed/to/views`

How can I use `arg(2)` as replacement text in views?

Here is how I'm hoping to use the UID:

# Answer
As I understand, in that field you should be able to use only fields and arguments tokens provide by Views only.

Unfortunately you can't use regular tokens on that field. Maybe you should ask this directely on that issue your request to add support of tokens (that make sense actually).
> 0 votes

---
Tags: 7, views
---


# Question
Title: Earliest hook to generate content during user registration
During the user registration process in Drupal 7, at which point can I access the newly created UID to create 'default content' for that user? I would like to do this as early on as possible. Preferably before the user has been approved by an admin or before they have verified their email address.

# Answer
> 3 votes
You can use hook\_user\_insert(), it should be early enough for you.

Technically speaking, hook\_user\_presave() is the first hook called from user\_save() (even before the user is written to the database), but according to the documentation it is "primarily intended for modules that want to store properties in the serialized {users}.data column". More importantly, it is also invoked when a user account is updated, so that wouldn't fit your use case.

# Answer
> 0 votes
Implement hook\_user\_insert().

---
Tags: hooks, users
---


# Question
Title: Language information in Session for anonymous users
I selected the language preference to be detected with user sessions, the problem is that for anonymous user this preference does not seem to be stored. As this site is not user driven (Meaning that site users don t need to create account in order to browse the site), it s very problematic.

Is there anyway to have this language preference stocked in anonymous sessions ?

# Answer
> 1 votes
For Drupal 7 it's normal, there's no session created automatically for anonymous users, we created a new module that stores and detects the language inside a cookie, see locale\_cookie, the benefit of a cookie is that your session table stays small.

# Answer
> 0 votes
Answering my own question, i added the following code in the top of my html.tpl.php

```
 if (isset ($_GET['language'])){

    $_SESSION['language']=$_GET['language'];
 }

```

I am not sure if it's normal that this doesn't happen automatically.

---
Tags: i18n-l10n, sessions
---


title: Drupal update domain whitelist

text:
# Question
Title: Drupal update domain whitelist
I'm working on a Drupal project that will live on a locked-down webserver. The internet access on that box is constrained by a domain whitelist so I need to be able to provide a complete list of the domains that are needed for Drupal to update itself and its modules.

We're using Acquia-Drupal so we'll certainly the following to be able to update Drupal itself:

```
git.acquia.com

```

I ran a drush update while listening with `netstat -t -u -c` to try and get a feel for which domains are needed. This raised the following:

```
*.drupal.org  (obviously)
ec2-174-129-202-133

```

The latter seems to be an AWS domain.

I realise it may depend on the modules to some extent, but is there a definitive (and unchanging) list of domains that are required to update Drupal's modules?

I'm particularly concerned that if I start getting into AWS domains, they will change down the line, breaking our update path!

# Answer
> 0 votes
The whitelist that we used (which seems to work fine) is as follows:

```
master.drupal.org
master2.drupal.org
ftp.drupal.org
ftp-osl.osuosl.org
git.acquia.com  <-- we are using this repo for Drupal core, you may not need it

```

They may not all be needed, `ftp-osl.osuosl.org` in particular may be required by another part of our stack, but this represents a working list of required domains.

---
Tags: updating
---