title: Not authorised to view page admin

text:
# Question
Title: Not authorised to view page admin
So I am following the book Drupal 7 Pro Development book and just completed chapter 2. I cannot access my modules admin page. Here is my menu hook. Can you please point me in the right direction.

```
function annotate_menu(){

 //Makes category
 $items['admin/config/annotate'] = array (
 'title' => 'Node Annotation',
 'description' => 'Adjust node annotation options',
 'position' => 'right',
 'weight' => -5,
 'page callback' => 'system_admin_menu_block_page', //function from system settings.
 'access arguements' => array('administer site configuration'), //who can see this.
 'file' => 'system.admin.inc', //file where callback function is called
 'file path' => drupal_get_path('module', 'system'), //get system module path
 );

 //Makes menu under category
 $items['admin/config/annotate/settings'] = array (
 'title' => 'Annotation Settings',
 'description' => 'Change how annotations behave',
 'page callback' => 'drupal_get_form', //function called
 'page arguements' => array('annotate_admin_settings'), //formID which is function name in annotate.admin.inc
 'access arguements' => array('administer site configuration'), //who can access settings
 'type' => MENU_NORMAL_ITEM,
 'file' => 'annotate.admin.inc', //file where formID is located.
 );

 return $items;
 }

```

# Answer
> 1 votes
You've just spelt 'arguments' wrong in both of the 'access arguments' and 'page arguments' properties.

At least one of 'access callback' or 'access arguments' needs to be present in the router item or you won't be able to access the page.

Just fix that spelling, clear the cache, and it should work fine

---
Tags: routes, users
---


title: How to insert javascript in a block?

text:
# Question
Title: How to insert javascript in a block?
I would like to insert a JavaScript code in block body but I cannot save it, after 2 or 3 minutes it stop (shows a message **The connection has timed out**). I want to add `statcounter` code to a block.

EDIT 1:

I can add JavaScript in `local-host` but I can't do in server (Linux server, VPS cPanel)

# Answer
Create your own text filter which just does nothing which means it allows really "all" input without any filtering.

Please make sure that you allow only trusted people to use this filter since it would be easy to add XSS code.
> 1 votes

---
Tags: 6
---


# Question
Title: The User registration form in drupal 7 site
The User registration form in drupal 7 site has only one country under the country dropdown. How to add the entire list from country module?

gbctest.com/drupal7

# Answer
> 1 votes
change the "Country status" of the user's field for country to "both" or enable all country you want

---
Tags: users
---


# Question
Title: Page callback for module admin settings not working
Ok so it seems my callback for my admin settings is not working correctly. It keeps coming back with a HTTP Error 500 (Internal Server Error)

**Menu Hook**

```
function annotate_menu(){

 //Makes category
 $items['admin/config/annotate'] = array (
 'title' => 'Node Annotation',
 'description' => 'Adjust node annotation options',
 'position' => 'right',
 'weight' => -5,
 'page callback' => 'system_admin_menu_block_page', //function from system settings.
 'access arguments' => array('administer site configuration'), //who can see this.
 'file' => 'system.admin.inc', //file where callback function is called
 'file path' => drupal_get_path('module', 'system'), //get system module path
 );

 //Makes menu under category
 $items['admin/config/annotate/settings'] = array (
 'title' => 'Annotation Settings',
 'description' => 'Change how annotations behave',
 'page callback' => 'drupal_get_form', //function called
 'page arguments' => array('annotate_admin_settings'), //formID which is function name in annotate.admin.inc
 'access arguments' => array('administer site configuration'), //who can access settings
 'type' => MENU_NORMAL_ITEM,
 'file' => 'annotate.admin.inc', //file where formID is located.
 );

 return $items;
 }

```

Page Callback

```
function annotate_admin_settings(){
//get array of node types with "internal names" as keys and "friend names" as values
//$options would return array('page' => 'Basic Page', 'article' => 'Articles');

$types = node_type_get_types(); //module function (node.module) that gets all node types and store in array $types

//go thru the $types array
foreach($types as $node_type){
    $options[$node_type->type] = $node_type->name; //access the $node_type object and store specific properties from the node_type object in $options array
}

$form['annotate_node_types'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Users may annotate these content types'),
    '#options' => $options,
    '#default_value' => variable_get('annotate_node_types', array('page')), //when using the system_settings_form, the name of the form element must match the key of the variable_get ie $form[] = variable_get('$form[]', '')
    '#description' => t('A text field will be available on these content types to make user-specific notes.'),
);

$form['#submit'][] = 'annotate_admin_settings_submit';
return system_settings_form($form);

}

/**
process form settings submission
*/

function system_settings_form($form, $form_state){
    //loop thru each of the content type checkboxes shown on the form
    foreach($form_state['values']['annotate_node_types'] as $key => $value){
        //if the check box for a content type is unchecked look to see whether
        //this content type has the annotation field attached to it using the
        //field_info_instance function. if it does then we need to remove the
        //annotation field as the admin has unchecked the box.
        if(!value){
            $instance = field_info_instance('node', annotation, $key);
            if(!empty($instance)){
                field_delete_instance($instance);
                watchdog("Annotation", 'Deleted annotation field field from content type: %key', array('%key' => $key));
            }
        }else{
            //if the check box for a content type is checked, look to see whether
            //the field is associated with that content type. if not then add the
            //annotation field to the content type.
            $instance = field_info_instance('node', annotation, $key);
            if(empty($instance)){
                $instance = array(
                    'field_name' => 'annotation',
                    'entity_type' => 'node',
                    'bundle' => $key,
                    'label' => t('Annotation'),
                    'widget_type' => 'text_textarea_with_summary',
                    'settings' => array('display_summary' => TRUE),
                    'display' => array(
                        'default' => array(
                            'type' => 'text_default',
                        ),
                        'teaser' => array(
                            'type' => 'text_summary_or_trimmed',
                        ),
                    ),
                );
                $instance = field_create_instance($instance);
                watchdog('Annotation', 'Added annotation field to content type: %key', array('%key' => $key));
            }
        }
    } //end forloop
}

```

# Answer
Change `function system_settings_form($form, $form_state)` to `function annotate_admin_settings_submit($form, $form_state)`.
> 2 votes

# Answer
system\_settings\_form() is a function defined from Drupal, and you cannot define the same function twice. The function is defined in system.module, which a module Drupal requires to work.

It is also the wrong name for the form submission handler, as your form builder contains the following line.

```
$form['#submit'][] = 'annotate_admin_settings_submit';

```

The form submission handler is then `annotate_admin_settings_submit()`, not `system_settings_form()`.
> 0 votes

---
Tags: forms
---


# Question
Title: How to modify a field value at theme/Views level?
My content type has a Link field which stores a website URL (e.g. 'site.com'). I use this field in various views and node templates.

My site is multi-language, and I know how to check the current language using the global $language.

Now I need to modify the link field value depending on the selected language. So output 'site-en.com' if visitor is viewing the site in English, 'site-de.com' if viewing in German etc.

I can't use manual field translation (Entity Translation) because the field values are imported from XML using Feeds, and there are hundreds of values.

So I wonder if there is a hook to programatically modify a field value before it is used by templates and Views module?

Or maybe there is a better way..?

# Answer
> 0 votes
copy /modules/field/theme/field.tpl.php to your theme folder and rename it to field--field-site-link.tpl.php (if field key of your field is field\_site\_link), edit template, see comment in file for avalable variables, or just override existings

---
Tags: views, i18n-l10n, entities
---


title: CAPTCHA on custom form

text:
# Question
Title: CAPTCHA on custom form
I have a client where they have an integrated form from another website. For some reason the Drupal 7 captcha module will not work on this form when entering it into captcha settings. The form id="contact-form" and then in the captcha setting I put contact\_form. This works on any other form that is either created with webform or and drupal module but will not work when the custom form is put into the content section of the page.

Any ideas?

# Answer
You must create form with FormAPI, then the form is avalable for Captcha as you say "contact-form" -\> "contact\_form". If the form is embeded whatever other method like iframe, then the form must already contain integrated own captcha. This also applies when form is build without FormAPI - using in client's site.
> 3 votes

---
Tags: 7, captcha
---


# Question
Title: Move field from one profile type to another?
I have a field in one profile type that really belongs in another profile type. The field already contains values.

I can imagine exporting the contents of the field, attaching a new instance of the field to the "other" profile, and importing the exported values to the new instance using feeds. But is there a more straightforward way to move a field (and existing values) from one profile type to another?

# Answer
> 1 votes
There's no easy way. That means if you don't have a lot of records your better off doing it manually.

If you must: 1. Add the field to profile type B. 2. Change the nid in the field data and revision DB table for every user from the nid of profile A to the nid of profile B. 3. Remove the field from profile type A.

---
Tags: entities, users
---


# Question
Title: How can we theme menu blocks in drupal 6
I decide to theme menu blocks in my drupal 6.x.

I have copied **block.tpl.php** into my theme folder and I have renamed it to **block-menu.tpl.php**

**but it seems it doesn't work !!**

How can I modify the theme for menu blocks?

# Answer
You can user the theme developer module to check whether your template is called at all. It will show you what nameing conventions to use.

And just in case: You have to flush your caches to make sure new templates and theming methods are taken into account.
> 1 votes

# Answer
Actually, I think the problem is you re-named `block.tpl.php` `block-menu.tpl.php` instead of **copying it as it works** for me here. If it doesn't for you, or you want to theme a specific menu block, you can do something like this:

1. Copy the default `block.tpl.php` to your theme's directory if it's not already there.
2. Examine your html source and look for the ID of any block, eg `<div id="block-menu-my-menu" ....>` and then, id=
3. Create a new `block-menu-my-menu.tpl.php` in your theme's directory, eg, block-BLOCK\_ID.tpl.php.

You need to have **BOTH** otherwise Drupal 6 won't look for the specific block template override.

In either case, you have to clear the cache after creating both templates.

Now you should be able to theme this specific menu block.
For good measure, if you want to keep things clean, you can also **create a directory** structure for all of the templates, eg, create a **tpl directory** and then in there have subdirectories like `block, node, page, etc,` and put all your various templates in there.

ADDITION:

To be more precise, read: Drupal 6 Template Suggestions

> What's a template suggestion? It's an alternate template `(.tpl.php)` file that you have created to override the base or original template file. *Suggestions only work when they are placed in the same directory as the base templates.* In other words, if you want `comment-blog.tpl.php` to display in your browser, **comment.tpl.php** also needs to exist inside your theme's folder and the two files must be in the same directory. `comment.tpl.phpcomment.tpl.php`

MORE ADDITIONS:

I am not sure what kind of development environment you have, but hopefully it is similar to MAMP, which I use for quick stuff on my MacBook:

> 1. cd /applications/mamp/htdocs/modules/system
> 2. cp block.tpl.php /applications/mamp/htdocs/sites/all/themes/YOURTHEME
> 3. cd /applications/mamp/htdocs/sites/all/themes/YOURTHEME
> 4. cp block.tpl.php block-menu.tpl.php

Now, if YOURTHEME already has a `block.tpl.php`, you can omit step 2, but just make sure that when all is said and done somewhere in or under the YOURTHERE directory, there is a directory that contains both `block.tpl.php` and `block-menu.tpl.php`. It could be in the base level directory, it could be in a subdirectory, regardless, just make sure both files are there. Also, make sure that YOURTHEME doesn't have a `block.tpl.php` elsewhere. If it does, make sure that `block-menu.tpl.php` is in that directory, eg, that you don't have two sets of `block.tpl.php` and `block-menu.tpl.php` files in different directories in YOURTHEME's directory structure for that would be confusing the theme registry build process and it would pick up only one of them.

Clear all caches to make sure the theme registry is rebuilt to see these new templates. If you have the Admin Menu module installed you can do this easily from the leftmost dropdown menu.

Now you can edit `block-menu.tpl.php` to theme all blocks created by the menu module.
> 0 votes

---
Tags: theming, blocks
---


# Question
Title: How to add exist taxonomy term field to custom form
It's possible to add exists taxonomy reference field to new custom form?

For example: i have a term field named "field\_tags" and would like to add to new form -\>

```
  $form['node_taxonomy_term'] = // load here exists taxonomy autocomplete field "field_tags"
  $form['#submit'][] = 'save_node_terms';
  return $form;

```

# Answer
Not exactly i think, but you can implement next:

```
$form['node_taxonomy_term'] = array(
  '#type' => 'textfield',
  '#autocomplete_path' => 'ntt/autocomplete',
);

```

add menu callback for autocomplete path

```
function HOOK_menu() {
  $items = array();

  $items['ntt/autocomplete'] = array(
    'page callback' => 'node_taxonomy_term_autocomplete',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

```

and add callback function

```
function node_taxonomy_term_autocomplete($str = 0) {
  $matches = array();
  //vocabulary id
  $vid = 2;

  $result = db_select('taxonomy_term_data', 't')
    -> fields('t', array('tid', 'name'))
    -> condition('vid', $vid, '=')
    -> condition('name', $str.'%%', 'LIKE')
    -> range(0, 10)
    -> execute();

  foreach ($result as $term) {
    $matches[$term -> tid] = check_plain($term -> name);
  }

  drupal_json_output($matches);
}

```

enjoy
> 3 votes

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


# Question
Title: Restrict administrator users from seeing blocks
I am using Drupal 6. I placed a JavaScript snippet in a block required by a third-party chat service I have on site. Now, this block is by default displayed on my administrative pages, which is annoying. Is it possible to restrict the admin role from seeing this block?

I tried this kind of snippet but it doesn't work.

```
global $user;
if (($user->role) == 'anonymous') {
  return TRUE;
}
else {
  return FALSE;
}

```

?\>

# Answer
If you don't want the block displayed on admin PAGES, eg, `www.yourhost.com/admin/HERE`, you can go into the block admin pages and restrict the block to be displayed on all pages EXCEPT `admin/*`.

However, if you don't want your "root" or "superuser" to see the blocks on any page, you can do what @BetaRide has suggested above in the PHP area of the admin page.

In the same vein, if you don't want anyone with an admin role to see the block, you can do something like this:

```
global $user;
if ($user->uid==1 || in_array('admin users', array_values($user->roles))) {
  return FALSE;
} else {
  return TRUE;
}

```

Of course, here you have to make sure you have a role called `admin users` so that might be different on your system.

If you don't want to add a role, you could use permissions and do it like this:

```
if (user_access('access administration pages')) {
  return FALSE;
} else {
  return TRUE;
}

```

which would display the block only to those users who could NOT access the admin pages.
> 1 votes

# Answer
This should do the job:

```
 global $user
 return $user->uid!=1;

```

This disables the block for the admin user.
> 0 votes

---
Tags: blocks
---


title: Bulk create Nodes from SQL

text:
# Question
Title: Bulk create Nodes from SQL
I have an ASP.NET website using MySQL. 1 table('books') holds more than 1000 books, each record has unique ID, name, writer etc. I want to import those books into Drupal. I'm planning to create Custom Fields(name, writer etc) for a New Content Type.

Is it possible to create Nodes like this from SQL file?

# Answer
> 3 votes
Possible, yes. Recommended, no. I do a lot of importing from outside sources, and would *never* entertain using direct SQL `INSERT` statements.

I would export your existing database in another format, and pursue one of standard approaches.

The easiest is probably Feeds. In your case, I would export as CSV, and then use the CVS imported built into feeds. Based on your description, it sounds like you have a one-to-one mapping, and the CSV importer is good for this.

The Migrate module can also handle moving data from one source into Drupal.

A more robust solution would be to create a custom importer, build up a `$node`, and then use `node_save`. There are a lot of nuances with this, and this is not a good approach unless you are familiar with the Drupal API already.

---
Tags: 7, database
---


# Question
Title: why i can't update user's picture by user_save()
i wrote the program belowed

```
$fields=array('name'=>'test user','picture'=>$fid);

```

`$account=user_save($account, $fields);`

i really changed the user name but i can't change the picture field in the users table

what could the problem be?

by the way, i also use db\_update. The situation is the same

the code is blowed

```
db_update('users')
->condition('uid',$account->uid)
->fields(array('picture'=>$file->fid))
->execute();

```

still not work I hope somebody can help me,Thanks!

# Answer
hybrydauth module does somethink like this

```
$file = new stdClass();
  $file->uid      = $account->uid;
  $file->status   = 0; // mark the file as temporary
  $file->filename = basename($tmp_photo_realpath);
  $file->uri      = $tmp_photo;
  $file->filemime = $info['mime_type'];
  $file->filesize = $info['file_size'];

  // The file should be an image
  $errors = array();
  $errors += file_validate_is_image($file);
  $errors += file_validate_image_resolution($file, variable_get('user_picture_dimensions', '85x85'));
  $errors += file_validate_size($file, variable_get('user_picture_file_size', '30') * 1024);

  // Make sure file extension is a valid image
  if (!in_array(strtolower($info['extension']), array('jpg', 'png', 'gif'))) {
    $errors[] = ' invalid image file extension.';
  }

  if (count($errors)) {
    drupal_set_message(t('Profile Image Import:') . ' ' . $errors[0], 'warning');
    // Clean up (set fid to avoid error messages)
    $file->fid = 0; file_delete($file);
  }
  else {
    // We'll need a valid file id on the file object; file_save() will give us one
    $file = file_save($file);
    // Update user account (fid is not empty, status is temporary -- image
    // will be moved to proper directory and assigned to the user)
    $fields['picture'] = $file;
    $account = user_save($account, $fields);

```
> 0 votes

# Answer
Try this code

```
 $file = file_load($fid);
 $file->status = 0;
 $edit = array ('picture' => $file);
 $u = user_save($account,$edit);

```
> 2 votes

# Answer
This is done in fboauth module

```
  // Update the user record.
  $picture_file->uid = $account->uid;
  $picture_file = file_save($picture_file);
  file_usage_add($picture_file, 'user', 'user', $account->uid);
  db_update('users')
    ->fields(array(
    'picture' => $picture_file->fid,
    ))
    ->condition('uid', $account->uid)
    ->execute();

```

you can use this code you just have to load file `$picture_file` first using file\_load
> 0 votes

---
Tags: users, media
---


# Question
Title: Trying to make gallery with views in Drupal 7
I have made 2 content types one is called Series and the other is Pictures. I have made a field on Pictures that will reference to Series. Using views I made a tab menu page that will appear on only the Series content type. What I'm having trouble is having to show all the Pictures that is referenced to that series. How would I do this?

# Answer
This question could use a bit of clarification.

> Using views I made a tab menu page that will appear on only the Series content type

What does the view currently display if not all the pictures associated to the series? Just every single pictures that exists in the database? Or doesn't display anything? If it displays every single picture existing, then you need to add a "Contextual filter" to the view, choose the field that you use to reference the series. And choose "Provide a default value" and choose "Content ID from URL" option.

For display I would use HTML List type of views, and use image presets (core) to display the thumbnails and use lightbox2 (contrib) module to display the large image.
> 1 votes

# Answer
Have you tried the Views Slideshow module? It is a module written specifically for creating slideshows in Views and is well-supported (well documented; video tutorials are available) on both Drupal 6 and 7.
> 0 votes

# Answer
You have to create a page view of nodes with content type:picture set page url to something `node/%/pictures` and add contextual filter of reference field. It will show all the pictures of particular series.
> 0 votes

# Answer
Or use an existing module, Media Gallery for example.

If you really want to create your own, using Contextual filters like Baysaa explained should work.
> 0 votes

---
Tags: media
---


# Question
Title: If Statment in Custom node template based in feild content existance
I have a content type called specials

In that content type I have a field called discount code which has a machine name of field\_discount\_code

I have a custom node template called node--specials.tpl.php that I am using to fomate the display of this content type

If the discount code if filled in by the user I want drupal to show some text if it is left empty I want it show some other generic text

here is the code I am trying but not having any luck with

```
<?php if (!empty($content['field_discount_code'])): ?>

<p>Call <strong>1-800-661-2555</strong> to contact our Guest Service specialists to reserve this package or book online by using discount code "<strong><?php print render($content['field_discount_code']);?></strong>".</p>

<?php else: ?>

<p>Call <strong>1-800-661-2555</strong> to contact our Guest Service specialists to reserve this package.</p>

<?php endif; ?>

```

If I leave the discount code empty drupal is still showing the first text chunk but with nothing in the render($content\['field\_discount\_code'\]); area.

so like this

Call 1-800-661-2555 to contact our Guest Service specialists to reserve this package or book online by using discount code "".

I have also tried

```
<?php if ($content['field_discount_code'] == "NONE"): ?>

text to display here

<?php else: ?>

text to display here

<?php endif; ?>

```

but no joy I am relatively new to drupal dev so perhaps I am doing this the wrong way any insight would be greatly appreciated!

# Answer
That's weird, the first code works in my end. Are you sure the `node--specials.tpl.php` is being called in the first place? I am suspecting that maybe you're still using node.tpl.php though I'm not sure.

Try to print some text in your tpl file to check if it is being used by your content type.
> 0 votes

---
Tags: 7, theming, nodes
---


title: Building a form and printing in a block

text:
# Question
Title: Building a form and printing in a block
I would like to build a form, and print it in a block via `hook_block()`.

How can I do this?

# Answer
> 0 votes
That is what done from user\_block(), which contains the following code.

```
  case 0:
    // For usability's sake, avoid showing two login forms on one page.
    if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {

      $block['subject'] = t('User login');
      $block['content'] = drupal_get_form('user_login_block');
    }
    return $block;

```

---
Tags: forms
---


# Question
Title: how to add custom css as default for the whole site
How can I add my css file as default for the whole Drupal site?

Where to put my CSS file so that it applies to whole Drupal 7 site that I am creating.

# Answer
If you want it on every theme, then you'll want it in a module.

Using this method you won't have to put the CSS in with every theme - just add and enable the module.

Just create a module that uses the following code:

```
function MYMODULE_preprocess_page($vars) {
  $options = array(
    'group' => CSS_THEME,
    'every_page' => TRUE
  );
  drupal_add_css(drupal_get_path('module', 'MYMODULE') . '/MYGLOBALCSS.css', $options);
  $vars['styles'] = drupal_get_css();
}

```

`drupal_add_css()`

`drupal_get_css()`

You'll need to clear your theme registry to have the changes picked up.
> 2 votes

# Answer
You need to add a stylesheet to your theme folder in a folder named 'css' for example, then in your YOURTHEME.info file you need to make a reference to it like...

```
stylesheets[all][] = css/default.css

```
> 1 votes

---
Tags: theming
---


title: paging an array result in D7

text:
# Question
Title: paging an array result in D7
I have a Query like this:

```
$query = db_select('nid_tid', 'nt')
->fields('nt')
->condition('terms', $name,'=');
$result=$query->execute();

$row=$result->fetchAssoc();
$nid =$row['nid'];
$ex=explode(',', $nid);
foreach ($ex as $tag_nid)
{
  $out .= $tag_nid;
}

```

return $out

I want paging this result .for example per 10 result in one page

thank you

# Answer
> 0 votes
You need to extend the query to a `PagerDefault`, and then use `theme_pager()` to output the pager links at the end of your content. The rest will be taken care of for you:

```
$limit = 10;
$query = db_select('nid_tid', 'nt')
  ->fields('nt')
  ->condition('terms', $name,'=');

$query = $query->extend('PagerDefault')->limit($limit);

$result = $query->execute();

$row = $result->fetchAssoc();
$nid = $row['nid'];
$ex = explode(',', $nid);
foreach ($ex as $tag_nid) {
  $out .= $tag_nid;
}

$out .= theme('pager');

```

---
Tags: 7, paging
---


title: Get users by term id

text:
# Question
Title: Get users by term id
In user profiles, I have added a term reference field. In my module, I want to get users that have a term id. Is there a function like `taxonomy_select_nodes` but for users to select users having a taxonomy term?

# Answer
There isn't, but since users are entities, and taxonomy term references are fields, you can use an `EntityFieldQuery` to get this data. You could even wrap it in a function to make your life very easy:

```
function taxonomy_select_users($term_id) {
  $query = new EntityFieldQuery;
  $query->entityCondition('entity_type', 'user')
    ->fieldCondition('field_taxonomy_term_field', 'tid', $term_id);

  $results = $query->execute();

  if (isset($results['user'])) {
    return user_load_multiple(array_keys($results['user']));
  }

  return FALSE;
}

```
> 2 votes

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


# Question
Title: Variable_get question default value in form
So I am reading Drupal Development Pro 7 and have stumbled upon something I am a little bit unsure about to do with the variable\_get function & form element. I understand it retrieves a stored value from the database and the second parameter is a default value if it cannot find anything in the database matching that form element.

My question is what does the second parameter do in this example below.

```
foreach($types as $node_type){
    $options[$node_type->type] = $node_type->name; //access the $node_type object and store specific properties from the node_type object in $options array
}

//Checkboxes on Form
$form['annotate_node_types'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Users may annotate these content types'),
    '#options' => $options,
    '#default_value' => variable_get('annotate_node_types', array('page')), //when using the system_settings_form, the name of the form element must match the key of the variable_get ie $form[] = variable_get('$form[]', '') Always form_element name
    '#description' => t('A text field will be available on these content types to make user-specific notes.'),
);

```

# Answer
The `#default_value` for a 'checkboxes' element must be an array rather than a single value (so you can have multiple default values selected).

All that code does is provide the default value wrapped in an array, so that it conforms to what the 'checkboxes' element type is expecting.
> 2 votes

---
Tags: forms, configuration
---


title: How to have Menu like apycom

text:
# Question
Title: How to have Menu like apycom
How can I create menus like Apycom Menus ?

Do I need to create custom module and then use it which will be available to whole site or I can just use css and js from the apycom menus?

# Answer
> 0 votes
If you have the source code, you can integrate it with your Drupal's templates. Otherwise, I don't see how you could do it.

---
Tags: routes, theming, javascript
---


# Question
Title: welcome page before main page (home page)
How do I redirect the users who want to visit my site to a PHP page that has a link to index.php?

When someone go to example.com they should see a PHP page (e.g. a welcome page) where they would find a link to access the front page.

# Answer
> 0 votes
**Modules**

You could accomplish this with the Rules module and add granular control over who sees the splash page and when.

**Additional Details**

Create a new rule. (admin/config/workflow/rules/reaction/add)

React on Event: Drupal is initializing

Condition: Execute Custom PHP Code

```
$homepage = FALSE;
if (drupal_is_front_page()) {
  $homepage = TRUE;
}
return $homepage;

```

Action: Page Redirect

**Drupal Rules Exported Rule**

This can be copy and pasted into the Rules Import menu. (admin/config/workflow/rules/reaction/import)

```
{ "rules_show_splash_page" : {
    "LABEL" : "Show Splash Page",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "splashpage" ],
    "REQUIRES" : [ "php", "rules" ],
    "ON" : [ "init" ],
    "IF" : [
      { "php_eval" : { "code" : "$homepage = FALSE;\r\nif (drupal_is_front_page()) {\r\n  $homepage = TRUE;\r\n}\r\nreturn $homepage;" } }
    ],
    "DO" : [ { "redirect" : { "url" : "splash-page-url" } } ]
  }
}

```

Tested and working on my dev site.

# Answer
> 2 votes
If you're happy to go down the module route, the following should get you started.

You're going to want to set a cookie to see if the user has been to the site before. If the cookie is set, then you know the user has been to your site ebfore and it shouldn't redirect to the splash page.

```
function MYMODULE_init() {
  if (!isset($_COOKIE['mysite_firstvisit'])) {
    drupal_goto('path/to/splash/page');
    setcookie('mysite_firstvisit', '1');
  }
}

```

# Answer
> 1 votes
This project is in alpha, but the Splashify project may be what you're looking for.

# Answer
> 0 votes
I think you're talking about a Splash Screen (or "splash page").

I only know of one module that has such functionality for Drupal 7 (there was the Splash module for Drupal 6 but it hasn't been ported), and that's ThemeKey. One of the features that you can apparently "easily achieve" is:

> a front-page / "splash" screen

# Answer
> 0 votes
I added a page--front.tpl.php in my theme. Drupal picks that up as a splash screen.

---
Tags: 7
---


title: Is Drupal 6 compatible with php5.3?

text:
# Question
Title: Is Drupal 6 compatible with php5.3?
We have just upgrade our server and now Our drupal 6 sites are not working properly because now the php version has been changed from 5.2 to 5.3.

is there any guide or suggestion about this? how to run a drupal6 with PHP5.3?

Thanks in advance.

Downgrading the php version from 5.3 to 5.2 solves the php problem and apparently the javascript problem as well.

# Answer
System requirements says:

> Although PHP 5.3 is supported by Drupal 6.14 core and higher (see the release notes for 6.14), some contributed modules may not be compatible with PHP 5.3, and some PHP 5.3 configurations still show warnings with Drupal 6.14; work is ongoing to resolve the latter in #360605: PHP 5.3 Compatibility.

The issue linked in the requirements page is actually marked as fixed; this means that Drupal core is completely compatible with PHP 5.3 since Drupal 6.14.
> 2 votes

---
Tags: 6
---


# Question
Title: How to create a homepage exposed views search box drupal 7
I'm sure this is really easy to do, but I've spent the best part of 2 hours trying to get Views to accomodate and I'm stuck.

Simply, I would like to create a single search function using Views in Drupal 7 which can go on a homepage to search for both "subject" and "town/ZIP" (ie "English Teachers" available in "Detroit". then the user hits the GO button. This will search the node fields and return a list which (ala a general google search engine style). I'm ambitious in moving forward with D7, but it's painfully slow at the moment).

OK, I'm new to D7 but not IT, but the lack of helpful books or tutorials is making self-learning takes 'years' and not 'months' (I'm upskilling during this downturn and I need to get back into employment like now not next year!).

Can anyone point me to a decent 'How to' tutorial for the above, or suggest the real easy way option in Views? I'd rather use Views and not have any .tpl

# Answer
> 1 votes
1. Add filters for this fields to your view.
2. Mark this filters as exposed.
3. Go to blocks and make sure your exposed filter is visible.

# Answer
> 0 votes
You could use Views filters populate to use one exposed string filter to search on multiple fields.

---
Tags: views
---


# Question
Title: use different layouts for different pages
I developed the layout of the first page in page.tpl.php. Here I've created some regions, to put the blocks. The problem is that these blocks reflect my "content type", and it has a link that when i do to click, don't happens the linking.

**I would like to link to a page with a different layout but I do not know where to set the second layout and how to redirect the link to this page. thank you!**

EDIT

the layout of the content type is level node (node.tpl.php), while the layout of the first page I set it at page (page.tpl.php). Going on the first page, I find a link within the block that should bring to the page of the node, but does nothing ...

As you can see, the title is my link to the node:

EDIT

in the layout of my first page I removed the "content", this may be the error?

# Answer
copy page.tpl.php to page--node--1.tpl.php for node with id 1, then edit it as you want. node.tpl.php theming the piece between sidebars/header/footer place only.
> 1 votes

# Answer
Custom content types are should be themed at the node level. Add a node template file to the theme/templates directory according to your content type. For example, I have a "Trip" content type. This gets themed with a node--trip.tpl.php file.

You don't need to do anything special to redirect.
> 2 votes

# Answer
I am experimenting now with creating different responsive layouts for different parts of a commerce site I'm developing. I'm using the Omega theme with Omega Tools module to generate subthemes. I created one subtheme for global site css and templates and am creating a subtheme of my "global subtheme" for each different section of the site that uses its own layout. Then I'm using the Delta and Context modules to set the actual theme in use for each section of the site. It might seem heavy handed to change themes per section of the site, but the advantage is that each theme can use the Omega settings interface to arrange its layout. I haven't looked at performance or maintainability but it looks like this is going to accomplish layout-per-site-section and build a responsive site to boot.
> 1 votes

---
Tags: theming, 7
---


# Question
Title: Is it possible to use stringoverride on ONLY one page?
I want to modify ubercarts "Add to cart" text button but only on ONE page that I've customized. I haven't been able to figure out how to call the button via php so I don't know if that's possible. I figured I could use string override but that would change the text across all pages and for that I can just change the option in ubercart.

# Answer
> 1 votes
I'm betting you're looking for hook\_form\_alter() ... I'm pretty sure its just a form buttom on the page and you can change its `#value`property as-needed with that hook. Its up to you to figure out how to target just that form, on just that page ... I don't think you need stringoverride for this.

You would want to test this out of course :)

---
Tags: 7, ubercart, string-overrides
---


# Question
Title: Filedepot - Where is the file management interface?
I have installed the module and additional libraries as required in the README but I don't see where the file management interface is. Can someone give me the link or point me to the right direction?

# Answer
Looking at the `hook_menu()` implementations for Drupal 6 and 7 these two paths stick out:

The rest of the paths defined are variations on the above, or AJAX callbacks, so I think one of those is the path you're looking for.
> 1 votes

---
Tags: 7
---


# Question
Title: How form layout of user login page can be changed Drupal 7 without altering its tpl file ?
I want to change the layout of user login form in Drupal 7. I don't want to change or create its tpl file for that purpose. Is there any module which will works for me ?

# Answer
> 2 votes
Have a look at hook\_form\_alter. You have to change the `#weight` property of the form elements.

If you don't know what I'm talking about have a look at the FAPI reference and quick start guide.

# Answer
> 0 votes
Have you check profile 2 that you can easy change from the admin user interface. Also download the follow module which works with profile 2. Also you can hook\_form\_alter as adviced above. I have written a tutorial about this process and I hope it helps http://whatisdrupal.info/drupal-module

---
Tags: users
---


title: $form_state['values'] AJAX

text:
# Question
Title: $form_state['values'] AJAX
I have the following form:
**Displayed at Page load**

```
$form['platform'] = array(
  '#type' => 'select',
  '#title' => t('Select a Platform'),
  '#options' => array(
    0 => t('- Select -')) + $options,
  '#default_value' =>  0,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => 'ajax_select_callback',
    'wrapper' => 'replace_model_div',
    'effect' => 'slide',
   ),
);

```

I'm trying to pull out the `$form_state['values']` to determine if another select field should be shown. However I'm not sure how this will ever get called without a submit function.
**To be Displayed after option is selected**

```
 if (isset($form_state['values']['platform'])) {
 $platform_value = $form_state['values']['platform'];
 $sqlmodel = "SELECT tid, name FROM {taxonomy_term_data} WHERE vid = $platform_value";
 $result = db_query($sqlmodel);
 $options = array();
   foreach ($result as $row) {
     $model_options[$row->vid] = t($row->name);
    }

$form['model_wrapper'] = array(
  '#type' => 'select',
  '#title' => t('Select a Model'),
  '#options' => $model_options,
  '#options' => t('$platform_value'),
  '#prefix' => '<div id="replace_model_div">',
  '#suffix' => '</div>',
);
}
return $form;
}
function ajax_select_callback($form, $form_state) {
  return $form['model_wrapper'];
}

```

If I am understanding AJAX properly even though on a select change my AJAX call will happen to render the `model_wrapper`. There is nothing in the AJAX call that will re-evaluate the `if (isset` function, and as such the `model_wrapper` section will never display.

Full story and objective: AJAX dependent select

# Answer
The reason it's not working is because the `<div>` with an ID of `replace_model_div` doesn't exist when the form is first built. So when the AJAX replace happens, there's no target container to append it to.

All you need to do is re-structure you form slightly (and remove the second `#options` array added to the second select):

```
$form['model_wrapper_container'] = array(
  '#type' => 'container',
  '#prefix' => '<div id="replace_model_div">',
  '#suffix' => '</div>',
);

if (isset($form_state['values']['platform'])) {
  $platform_value = $form_state['values']['platform'];
  $sqlmodel = "SELECT tid, name FROM {taxonomy_term_data} WHERE vid = $platform_value";
  $result = db_query($sqlmodel);
  $model_options = array();
  foreach ($result as $row) {
    $model_options[$row->vid] = t($row->name);
  }

  $form['model_wrapper_container']['model_wrapper'] = array(
    '#type' => 'select',
    '#title' => t('Select a Model'),
    '#options' => $model_options,
  );
}

```

And a small change to the callback:

```
function ajax_select_callback($form, $form_state) {
  return $form['model_wrapper_container'];
}

```
> 3 votes

---
Tags: forms, ajax
---


# Question
Title: Subscribing the new user to a mailing list as a part of registration
What is the simplest way to configure Drupal in such a way, that every registering user is asked for his email and permission to send him info about site updates?

That way I want to postpone serious site building, but have a solid user base just from the now.

# Answer
The email address is already a standard user property. Using fields you can ask for permission about the mailing list.

You can use rules module (http://drupal.org/project/rules) to get notified of new registrations and find or implement the action for a mailing list registration.

Another option would be the simple news module: http://drupal.org/project/simplenews
> 1 votes

---
Tags: users, emails
---


# Question
Title: Extract zip to server and upload the files to the node?
I allow users to upload zip files I extract, and look into them to see if they contain a .jpg file. I use that file to create a new node. The differences between the .jpg and the .zip file uploaded are that the first came as an object, while I don't know how I can take the second as an object.

I'm using the PclZip library.

This is part of the code I use when the uploaded file is a JPEG.

```
$file = $form_state['values']['file'];

$original_filename = $file->filename;
$original = file_unmanaged_copy($file->uri, 'public://work', FILE_EXISTS_REPLACE);
file_unmanaged_delete($file->uri);
list($file, $tfile) = some_fileprep($original_filename);

```

This is the code I use when the file is a .zip file.

```
include $pclzip_lib.'pclzip.lib.php';
$zip = new PclZip($file->uri);

for ($i=0; $i<$total_files; $i++) {
    $file_name = $list[$i]['filename'];
    list($f_name,$xt) = explode('.', $file_name);
    $xt=strtolower($xt);

    $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote('png gif jpg jpeg tif tiff html')) . ')$/i';
    if (preg_match($regex, $xt) and ($list[$i]['size'] < 10000000)) {
        $error[] = "File with conflict: ".$file_name;
        if((($xt == 'png') or ($xt == 'gif') or ($xt == 'jpg') or ($xt == 'jpeg') or ($xt == 'tif') or ($xt == 'tiff')) and ($f_name == 'preview')){
            $file->filename = $f_name.".".$xt;
            $file->uri = $f_name.".".$xt;
            echo "Yes: ".$f_name.".".$xt;
            $preview = true;
        }
    }

    if(is_null($error))
    {
            $to_extract = $GLOBALS['_SERVER']['DOCUMENT_ROOT'] . '/' . drupal_get_path('module', 'some') . '/testing/';
            $ar = $zip->extract(PCLZIP_OPT_PATH, $to_extract);
            $file->filename = $ar->filename;
            $file->uri = $ar->filename;

        }
}

```

# Answer
> 0 votes
When you successfully unzip a file you have the code:

> ```
> if(is_null($error))
> {
>         $to_extract = $GLOBALS['_SERVER']['DOCUMENT_ROOT'] . '/' . drupal_get_path('module', 'some') . '/testing/';
>         $ar = $zip->extract(PCLZIP_OPT_PATH, $to_extract);
>         $file->filename = $ar->filename;
>         $file->uri = $ar->filename;
> }
>
> ```

Once you've extracted the zip you have a $file object ... just save it using the drupal API such as:

`$original = file_unmanaged_copy($file->uri, 'public://work', FILE_EXISTS_REPLACE);`

# Answer
> 6 votes
You can simply use file\_unmanaged\_save\_data(), as in the following code, where `$data` is the content of the .jpeg file contained the .zip file.

```
file_unmanaged_save_data($data, 'public://work', FILE_EXISTS_REPLACE);

```

As side note, Drupal includes the ArchiverZip class, which should probably be used instead of the `PclZip` class. You don't normally deal with the class directly, but you use code similar to the following one, used by update\_manager\_archive\_extract().

```
  $archiver = archiver_get_archiver($file);
  if (!$archiver) {
    throw new Exception(t('Cannot extract %file, not a valid archive.', array('%file' => $file)));
  }

  // Remove the directory if it exists, otherwise it might contain a mixture of
  // old files mixed with the new files (e.g. in cases where files were removed
  // from a later release).
  $files = $archiver->listContents();

  // Unfortunately, we can only use the directory name to determine the project
  // name. Some archivers list the first file as the directory (i.e., MODULE/)
  // and others list an actual file (i.e., MODULE/README.TXT).
  $project = strtok($files[0], '/\\');

  $extract_location = $directory . '/' . $project;
  if (file_exists($extract_location)) {
    file_unmanaged_delete_recursive($extract_location);
  }

  $archiver->extract($directory);

```

archiver\_get\_archiver() uses drupal\_realpath(); this means it is able to get the realpath of a file when its filename is using stream wrappers, such as public://archive.zip.

---
Tags: 7, media, files
---


# Question
Title: Obtaining the node type being added with php
Other than pulling the information from the url itself, is there a way to retrieve/obtain the node type that has been selected in the add content area. ie: www.mydomain.com/node/add/article... using PHP? I have been able to do this when updating/editing a node using menu\_get\_object() in a template file but not when adding a node.

# Answer
> 1 votes
If you are changing the form used to create a node, then you could use the following code.

```
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    // The node is being created.
    // Use $node->type to get the content type of the node.
  }
}

```

The reason is that node\_add(), the page callback for the node creation form, contains the following code.

```
  $types = node_type_get_types();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE,
  );
  drupal_set_title(t('Create @name', array('@name' => $types[$type]->name)), PASS_THROUGH);
  $output = drupal_get_form($type . '_node_form', $node);

```

This means that the form used when creating a node is the node edit form.

As alternative, if you need to change the node creating form when the content type is, for example, article, you can use the following code.

```
function mymodule_form_article_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    // The node is being created.
  }
}

```

As in this case the form is altered only when article is the content type of the node, you don't actually need to check the content type.

If you need that information in other cases, then you can only get it from the URL.

---
Tags: nodes
---


title: multilanguage site

text:
# Question
Title: multilanguage site
I have a multi language drupal site. It's in English, German and Japanese. When using a translation, the sites name is still displayed in English. How do I make the site change the site name to the selected language. Any help will be appreciated.

# Answer
In Drupal, site name and slogan are variables. And there is Variable translation module (in i18n pack) for them.
More info from Gábor Hojtsy: Drupal 7's new multilingual systems (part 5) - Site settings
> 5 votes

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


# Question
Title: Upgraded Contrib modules & Drupal to 7.14 now SSL doesn't turn green
I'm using the latest D7 & securepages. When I took over this website from the previous developer, they had the problem that when they would update "anything" (according to them) it would break the SSL. I didn't believe them, so I cloned the site to a sub domain and updated everything. It still worked. My pages in the shopping cart turned into HTTPS, so everything was good. The only problem is that now the browser address bar doesn't turn green (still HTTPS, though) even though we are paying for an extended validation cert. So now the boss is asking why it doesn't turn green.

I checked the certificate and got the following:

```
Website: www.[site].com <- this is correct
Owner: This website does not supply ownership information.
Verified by: Not specified

```

This wouldn't happen prior to the update. What is causing this and how can I fix it?

I was able to get a full SSL connection again. It was one of my images that I manually edited in one of my template files. So now that I have a full SSL connection again, I guess the question has changed slightly to: Why isn't it green? The only thing I notice when checking the cert is that it shows: *This website does not supply ownership information.*

**For anyone else encountering this issue with secure pages:** In your settings file, make sure that if you have redirections to `www.example.com` or `example.com`, and that you have your `$cookie_domain` set properly.

# Answer
I am not sure if it would cause your problem, but Secure Pages requires patches to core. The two you need are listed on the main project page. I use 961508-23-32-D7 instead of 961508-21. I am not 100% sure which version of 471970 I am using (that is just for unit tests, anyway). Both apply to 7.14, but with some fuzz.
> 2 votes

---
Tags: 7, ssl
---


title: How to use Kwicks for slider?

text:
# Question
Title: How to use Kwicks for slider?
I see it in premium themes and D6 themes (demo). I would like to use it on my site.

# Answer
> 3 votes
Yes. There obviously isn't a Drupal 7 module for this yet (http://drupal.org/project/kwicks) but you can always just include the jquery plugin in your own theme / block implementation and roll your own slideshow.

Actual implementation of this would depend on what you are trying to do but according to the Kwicks documentation, all you need is to apply the kwicks js to a simple unordered list like this

```
    <div id="example1">
        <ul class="kwicks">
            <li id="kwick1"></li>
            <li id="kwick2"></li>
            <li id="kwick3"></li>
            <li id="kwick4"></li>
        </ul>
    </div>

```

So one (module-less) way you could do this is is to create a content-type of whatever it is you want to be in this slider, than create a view of these nodes with a style output of HTML list. In your views header, add a tag to include the kwicks code in:

```
<script src="http://kwicks.googlecode.com/svn/branches/v1.5.1/Kwicks/jquery.kwicks-1.5.1.pack.js" type="text/javascript"></script>

```

and then whatever jquery config you need to make the slide show, ex:

```
<script type="text/javascript">
    $().ready(function() {
        $('.my-views-class .kwicks').kwicks();
    });
</script>

```

and output it as a block / page to place it where ever you want on your site.

---
Tags: 7, javascript
---


# Question
Title: Calendar legend on taxonomy via relationship?
I'm working on a calendar view to show employees' vacation. For that I setup 2 content types:
-Employee: Name and Department (Term reference to 'Department' vocabulary)
-Vacation: Date field with start and end dates and Employee (Node reference to Employee content type)

I got views to show the calendar with vacation time for the employees, but I want to colorcode them based on the department their in. So I setup the relationship to the Employee content type and added the Department field using that relationship.

Views recognised the term reference field and allows me to set colors for each vocabulary term. Everything looks ok, except the actual calendar view which doesn't show any color at all. There is no "stripe" keyword in the html source.

To test I added a dummy term reference field to my Vacation content type itself to test the behaviour without a relationship and everything works as expected.

So it seems the colorcoding doesn't work on term reference fields via relationships. I could add the department reference field to my Vacation content type, but that would mean have the same reference in both the Employee and Vacation content types, which isn't something I'd like to have.

Has anyone come across this problem or better yet, solved it? Thanks in advance.

I'm running:
Drupal 7.14
Calendar 7.x-3.4+0-dev
Date 7.x-2.5+15-dev
Views 7.x-3.3+175-dev
Chaos tools 7.x-1.0+32-dev

# Answer
Try the fullcalendar module if you want to color-code calendar views.

It's also handy because you can display a legend in an autogenerated block that helps users figure out what each color represents, etc. It's also a good solution because colors are easy to change/update via the admin configuration page.
> 1 votes

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


title: Sort Tablesort by Computed Field?

text:
# Question
Title: Sort Tablesort by Computed Field?
I am using an EntityFieldQuery with -\>tableSort() and then adding a few columns to each row programatically. Is there a way to have tableSort() sort by my computed fields instead of only raw db fields? (Note: I don't mean the module Computed Field - which I now realize is probably the solution.)

# Answer
Unfortunately not; an `EntityFieldQuery` is just an interface to a normal SQL query.

All values for computed fields are determined after the data has been loaded from the database (in the `_computed_field_compute_value()` function) so this won't be possible using the TableSort extender.
> 1 votes

---
Tags: entities
---


title: Command line submit node

text:
# Question
Title: Command line submit node
Previously I'm using combination of `cURL` and `sed` to submit to Drupal 6 website. It was very flexible but it will works if I submit very frequently. If I want to submit 2 posts in one week, it will fail because of unique number generated in Drupal system over time.

I need to know any ways (`drush` or any other commands) that allow me submit new post easily

# Answer
> 0 votes
Drush has a `php-script` argument which will allow you to run a PHP file with any code in it. Since Drush performs a bootstrap and includes the usual files required at Drupal runtime before running your script, you have all of the Drupal API available to you in your custom script.

If you need to submit any arbitrary form you can pre-populate a `$form_state` array and then submit the values using `drupal_execute` (see its API documentation). Getting to know what values to pre-populate in $form\_state can be tricky, but this line can help you out:

```
drupal_set_message('<pre>' . print_r($form_state, TRUE) . '</pre>';

```

Place this in the submit handler function for to the form you'd like to programatically submit and then run through the form once in your browser. Upon submitting that form, you should get a print out the `$form_state` structure that you would need to mimic. Be weary on live sites though, users will be able to see that debug message too!

If you're just needing to submitting nodes then you could even use `node_save()` directly which is a bit simpler. How to do this is detailed on another question, How to create nodes using node\_save?

---
Tags: drush
---


# Question
Title: Passing an argument to a node causes 404
On my page I have a block that reads a variable in the URL. The page that it reads it on is a node. When I pass an argument through the URL to the node, it causes a 404 error. ex:

```
www.example.com/experience //This is the node, it works
www.example.com/experience/asia //Asia is the argument, I get 404

```

I've tried configuring the URL Alias to "experience/\*", but this obviously didn't work and only accepts '\*' as the argument. What do I need to configure to make this work?

I've heard of some modules that automatically add the aliases to the configuration table, but I would prefer a more straight-forward solution.

# Answer
There are four points to consider:

It is better if such parameter is passed as query string, for example in a URL like http://example.com/node/4?continent=asia. If you really like better to use a URL like http://example.com/experience/asia, then with Drupal 7 you can implement the following hooks.

```
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  if ($path == 'node/4') {
    $path = 'experience';

    if (!empty($options['query']['continent'])) {
      $path .= "/{$options['query']['continent']}";
      unset($options['query']['continent']);
    }
  }
}

function mymodule_url_inbound_alter(&$path, $original_path, $path_language) {
  if (preg_match('|^experience(/(.*))?|', $path, $matches)) {
    $path = 'node/4';
    $_GET['continent'] = $matches[2];
  }
}

```
> 2 votes

# Answer
There are modules to accept subpath aliases.

If you're on Drupal 6 then look into the subpath\_alias module.

Drupal 7 has subpathauto which does the same thing.

What they do is expand Drupal's path matching to work with subpaths, so no extra aliases are added. I've used it in the past when embedding views within nodes and it worked a treat.

So if you have `node/4` aliased to `path/test` then it will recognise `path/test/argument` as `node/4/argument`
> 2 votes

# Answer
If you changed your url from

```
www.example.com/experience/asia

```

to

```
www.example.com/experience?type=asia

```

you should be able to access `asia` and any other "type" from your block like this:

```
$types = drupal_get_query_parameters();
foreach ($types as $key => $value){
  switch ($key) {
     case 'asia':
       // code for asia goes here...
       break;
     case 'europe':
       // code for europe goes here...
       break;
     // etc
  }
}

```

Otherwise, as the comments suggest, `www.example.com/experience/whatever` is going to fail because drupal hasn't declared a menu item for that path. However, variables can be passed in practically anywhere without drupal needing to know about them all as they don't change the base url.

If you still wanted the "cleaner" looking url, I suppose you could create a hook\_menu() item like:

```
 $item['experience/%'] = array(
   'title' => 'Experience',
   'page callback' => 'experience_type',
   'access callback' => TRUE,
   'type' => MENU_CALLBACK,
 );

```

and then function called `experience_type` that returned the contents of `node/4` or whatever `experience` is aliased to. Then, in your block you could do something like:

```
switch (arg(1)) {
   case 'asia':
     // code for asia goes here...
     break;
   case 'europe':
     // code for europe goes here...
     break;
   // etc
}

```

and if all is good in the world, `www.example.com/experience/asia` would work.
> 1 votes

# Answer
It is better to implement `hook_menu()` and make a custom callback by placing a placeholder after your URL.
> 0 votes

---
Tags: uri
---


# Question
Title: Conditional fields module, "OR"-like operator
Can conditional fields module, or another module like it, make a field hidden/shown using an "OR"-like operator? For example,

if field A = 'yes' OR field B = 'no', then show field C.

Right now the conditional field module treats everything as an "AND" operator. For example, if field A = 'yes' AND field B = 'no', then show field C. I want field C to show up on either one of those conditions, not both.

# Answer
> 0 votes
The new version of the conditional fields module is taking care of this.

# Answer
> 1 votes
Maybe, the Views If Empty module could be of use to you. Here is a quote about it (from the module's project page):

> ... enables a view to output a field if another field is empty.
>
> You need Views If Empty when you have a content type with an embedded video and an imagefield thumbnail. The nodes always have the images but occasionally have a video. You want your view to display the image field when the video field is empty, display the video field when available, and never display both.

---
Tags: 7
---


# Question
Title: Custom field permissions based on workflow or rule/action
Is there a way to trigger permissions to specific fields in a content type based on a workflow or rule/action?

For example, for a content type called 'article':

* field 1 is writable, field2 is hidden
* workflow state has changed
* field 1 is now read-only and visible
* field 2 is now visible and writable

I came across this module called Workflow Fields that sounds perfect, but it is only available for Drupal 6.

# Answer
> 0 votes
I used the Rules module and custom fields to create triggers that changed when being passed from role to role.

# Answer
> 0 votes
You can probably do this with Conditional Fields.

> Define dependencies between fields based on their states and values.
>
> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

---
Tags: 7, users, workflows
---


# Question
Title: How do I revert all of my DB tables from MyISAM back to InnoDB?
> **Possible Duplicate:**
> How do I convert a database from MyISAM to InnoDB?

Due to a bug in the Backup and Migrate module http://drupal.org/node/1128620 , all of my DB tables were reverted to MyISAM. How to return them all back to to InnoDB. (Perhaps using phpmyadmin?)

I used to use http://drupal.org/project/dbtuner/ in D6 for this. However there isn't a D7 version.

Also, are there any side effects or possible gotchas for switching this in this way?

Update:

```
<?php
    // connect your database here first
    //
    $sql = "SHOW tables";
    $rs = mysql_query($sql);

    while($row = mysql_fetch_array($rs))
    {
        $tbl = $row[0];
        $sql = "ALTER TABLE $tbl  ENGINE=INNODB";
         mysql_query($sql);
    }
?>

```

What do I need to add to the section "connect your database here first" to connect to my Drupal DB?

# Answer
The easiest way is to take a backup with Backup and Migrate, open it in an editor and search/replace "MyISAM" to "InnoDB". Then restore it.

Personally, I would restore to a new catalog, and then switch the database in settings.php. This way, you can test before making the new version live.

Otherwise, this is a dup of How do I convert a database from MyISAM to InnoDB?
> 3 votes

---
Tags: 7, database, backups
---


# Question
Title: drupal 7: new field with dynamically generated select list from PHP code
I have a new node type where a user is asked who he or she knows from the site. They are to be presented with a select list with the names of the existing users on the site.

When creating this new select list field in Drupal 7, I noticed that the PHP snippet is gone so I cannot dynamically generate the select list text and values. Is there some Drupal way (Views?) to do this without having to download the CCK (development status) module for Drupal 7? The CCK module is not ready for prime time in Drupal 7. I understand that their rationale to remove PHP snippets are for security reasons (http://drupal.stackexchange.com/questions/2509/what-are-the-downsides-of-using-custom-php-code-in-blocks-nodes-views-args). The Drupal team would not leave us hanging without this common functionality, right?!??!

# Answer
I went with the CCK module out of desperation. All seems to be working well since I have my PHP snippets back.
> 1 votes

# Answer
I think your best bet would be http://drupal.org/project/entityreference module and the entityreference\_view\_widget. PHP filter is still there in D7 but you have to enable it under modules.
> 2 votes

# Answer
Yes, just use Reference module, it has node\_reference sub module within.

With node reference module on, you create views that lists out whatever selections can be avaliable to user. Then you add a new node refernce field for your content type. Select the view you created as option.
> 1 votes

---
Tags: 7
---


title: Views and sorting by label

text:
# Question
Title: Views and sorting by label
In my content type field, I have a select list of current users on the system. I want to create a page that lists all these usernames in a table. The key is the user id (uid). The label is their username. When sorting in Views, it sorts by the key (uid number). I want it to sort by the label (username). Is there a way to do this with Views? Keep in mind that the user list is all dynamically generated so manually reordering is not an option!

# Answer
Drupal is not powerful enough for this. Had to write my own module and my own SQL query to get it ordered the way I want. Maybe in Drupal 8 this feature will be available.
> 0 votes

---
Tags: 7, views
---


title: Showing referenced node in view

text:
# Question
Title: Showing referenced node in view
I have a content type "Project" and a content type "Document". Using the "references" module, the "Document" content type relates to the "Project" content type.

I have a simple view that shows a list of all projects like so:

* Project A
* Project B
* Project C

However, I want the related documents to show up in the list (the relation occurs from the document to the project, not the other way around):

* Project A
    + Document J
    + Document K
* Project B
    + Document L
* Project C
    + Document M
    + Document N
    + Document O

I've looked at the eva module (seems to be the wrong tool for the job, but that may just be my inexperience with it.) I've tried using the built in "relationships" with views, but can't find if it's possible that way.

# Answer
> 1 votes
This can be done without installing module , simply you will use aggregation and group by Project .

Here is a great tutorial from nodeone.se of how to use agregation in drupal 7
See also this blog post , in the left image he is Grouping by the room(nodereference)

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


# Question
Title: adding input format for CCK fields in drupal
Is there any way by which I can add a input format for the CCK added Text Fields ? By default its only there for Body field in any node/add , I want this for other fields to evaluate PHP Code.

# Answer
> 2 votes
Multi line text fields switch to *filtered text*. For single line text fields the answer is no.

---
Tags: 6, entities, input-formats
---


# Question
Title: How to create incremented view filters for numeric fields in Drupal?
In my Drupal 7 I'm building a view of homes/properties with exposed filters of "Minimum Rent" and "Maximum Rent" - so that people can find homes according to their budget.

Rent (per month) is basically an integer number field and can be whichever number (£475 or £677 or whatever an end user enters when creating the node). But in my exposed filters for "Min Rent" and "Max Rent" I want it to be a dropdown list of £100, £200, £300, £400, £500 etc -in other words, automatically **incremented**. Exactly as we see on websites like www.rightmove.co.uk or www.zoopla.com or any other property listing website.

How can I achieve this?

# Answer
If you create a field an select a type of text list using a list widget, you can create the any list you wish for the field. Then when you expose the field in your view the drop down list of values will be included in the exposed filter.
> 1 votes

# Answer
I'd use hybrid exposed filters as a starting point. It is a work in progress patch but very mature. See:
> 0 votes

---
Tags: views
---


title: Problem getting rid of theme error

text:
# Question
Title: Problem getting rid of theme error
```
Fatal error: Unsupported operand types in `includes/theme.inc on line 980`

```

In my homepage im getting that error. I have no idea why I keep getting that error.

I'm on the process of upgrading my Drupal 6 to Drupal 7.

Thanks

# Answer
> 2 votes
It's hard to impossible to know where this error come from without adding some debug statements before the line 980.

Try enabling devel.module and adding following code on line 977:

```
dpm(func_get_args());
dpm($info);

```

This will reveal which theme hook is being called and its parameters (variables). It should give enough clues to help you find where the error comes from.

---
Tags: 7, upgrading
---


# Question
Title: Storing Drupal form values when using tablesort or paging
I have a custom form where I use a tableselect, and a couple of textboxes and checkboxes. The query for the tableselect is extended using TableSort and PagerDefault.

I noticed that when the user sorts a column, or goes to another page (using the pager), Drupal does a simple redirect which wipes all values in the textboxes and checkboxes.

This even occurs when looking at the inbuilt /admin/content screen.

I can't really expect the user to sort and page the table, and then enter textbox values. And sorting and paging is pretty standard functionality. Is there anyway around this?

# Answer
> 0 votes
No there's no in-built way around this. The tablesort and pager functionality works by providing links to new pages. When you link to a new page, any values you have in form elements on the previous page will not exist any more, unless they've specifically been persisted to the session and then picked up again on the new page load (this is a browser issue and nothing to do with Drupal).

The easiest thing you can do is implement AJAX for your pager/sort links which invokes the content area of the page to reload rather than navigate when they're clicked. Then your form elements will remain untouched.

---
Tags: forms
---


title: Hook for node preload

text:
# Question
Title: Hook for node preload
Is there any hook for when the `node_load` or `node_load_multiple` functions are called, but before they are actually loaded from the DB?

I need this because I want to cache my nodes before Drupal goes and queries the DB for them.

# Answer
> 5 votes
No there's no such hook I'm afraid (see the list of hooks for Drupal 7).

If you want caching that goes beyond the normal static page cache provided by `node_load()` then you might want to look at the Entity Cache module, which *"puts core entities into Drupal's cache API."*. Even if you don't end up using that module you can inspect the code to get some ideas for implementing your own caching system.

---
Tags: 7, hooks, nodes
---


# Question
Title: limit view result to only commented nodes
I created a view that gets the logged in user posts, But I need to alter that view a little bit to only show the posts that has a comment by a different user "not the OP".

Do I have to create a template and add PHP to it? or this can be done with views?

# Answer
> 1 votes
You don't need to code something here with powerful Views module.

1. First, add relationship *“Comment: Comments of the node”* to current View.
2. Then in *“Query settings”* check *“Distinct”* option. Now you have list of nodes which have comments.
3. Add contextual filter *“Comment: Author uid”*, set default value to *“User ID from logged in user”* and don't forget to check option *“Exclude”* in *MORE* fieldset.

Note that this solution works only for current logged in user.

---
Tags: 7, views, comments
---


# Question
Title: Redirect for single page with htaccess file not working when url has spaces
Im trying to add a redirect to my site from one page to annother using the .htaccess file. From the documentation at http://drupal.org/node/38960 I tried the following but it doesnt appear to do anything. Thanks

```
# RewriteBase /

#custom redirects (this is where the code ive added begins)

RewriteRule http://mysite.com/one http://mysite.com/two [R=301,L]

#end custom redirects (this is where the code ive added ends)

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

# Answer
In the end the issue was spaces in the url. Working with this:

```
# RewriteBase /

RewriteRule ^taxonomy\/term\/6\ 7\ 8\ 9$ /taxonomy/term/all [L,R=301]

```
> 0 votes

---
Tags: 6, redirection
---


# Question
Title: Notice: Trying to get property of non-object in my_module_get_nodequeue_id_by_name() (line 30 of my_module/my_module.module)
```
/**
 * Gets the nodequeue id by nodequeue name
 */
function my_module_get_nodequeue_id_by_name($name) {
  $data = db_query('SELECT qid FROM {nodequeue_queue} WHERE title = :title', array(':title' => $name))->fetchField();
  return $data->qid;
}

```

The above code produced this kind of notice:

```
Notice: Trying to get property of non-object in my_module_get_nodequeue_id_by_name() (line 30 of my_module/my_module.module).

```

# Answer
> 5 votes
`fetchField()` returns a single value, not an object. You either want to use `fetchField()` like this:

```
$qid = db_query('SELECT qid FROM {nodequeue_queue} WHERE title = :title', array(':title' => $name))->fetchField();
return $qid;

```

or use `fetchObject()` instead:

```
$data = db_query('SELECT qid FROM {nodequeue_queue} WHERE title = :title', array(':title' => $name))->fetchObject();
return $data->qid;

```

---
Tags: 7
---


# Question
Title: Getting the first URL alias for a node in a SQL query
For some backups and exports, I need to fetch the URL-aliases for each node in SQL. The `url_alias` taqble, however, has no foreign key to the node table (nid) nor the other way around, it seems.

Is there some hidden join-table somewhere? A neat trick to fetch the node and its alias in a JOIN?

# Answer
Since the value in the `src` column in the `url_alias` table is predictable for nodes you can just query it directly, without the need for any joins:

```
$nid = 1; // node id
$src = 'node/' . $nid;
$query = db_query("SELECT dst FROM {url_alias} WHERE src = '%s'", $src);

```

If you definitely want to use a join though, something like this will work:

```
SELECT n.nid, ua.dst
FROM {node} n
INNER JOIN {url_alias} ua ON ua.src = CONCAT('node/', n.nid)

```
> 7 votes

---
Tags: 6, database, path-aliases
---


# Question
Title: Drupal 7 Ubercart Rest Services Module (API)
I'm looking for the best way to retrieve Ubercart orders and customers from a remote server. I'd like to plug in a connector the same way it works with Magento. I've played a little bit with Services but didn't figure out how it works with Ubercart.

Does anybody knows where I can find the right module and documentation ?

# Answer
You could use the Bee Colony - Ubercart synchronization Web Service module.

> Bee Colony is a communication service (based on services module) for Ubercart based sites. Bee Colony allows site administrator to provide full remote control over Ubercart orders and products.
>
> Main objective is to build a client/server system to allow external software to synchronize its database with Ubercart.
>
> This project mission is to evolve Bee Colony to provide an easy and powerful way to create client-side software for companies and promote in this way Ubercart use.
> 1 votes

---
Tags: 7, ubercart, services
---


title: Facebook profile information display

text:
# Question
Title: Facebook profile information display
How can i display Facebook profile information like First name, Lastname, address. I am using Drupal for Facebook module in login with facebook a/c in my drupal web site.

# Answer
You can use the Facebook OAuth (FBOAuth) module for this. Here is a quote about it (from the module's project page):

> ... provides authentication services and an API to perform actions against Facebook. This module allows users to login to Drupal through the service commonly known as "Facebook Connect". This module is built with simplicity and flexibility in mind, it provides login services (and does it well), and an API for performing any other actions you may want to write yourself to query against Facebook's APIs.
>
> **Features**:
>
> * One-click login through Facebook.
> * Automatic import of user e-mail and profile information during initial login.
> * Integration with Profile module to map Facebook data to Profile fields. (Drupal 6)
> * Integration with Field module to map Facebook data to fields on users. (Drupal 7)
> * A flexible and direct API for modules to get authenticated and query Facebook's APIs (plus extensive documentation).
> * Extensive permission settings for Facebook data retrieval.
> * The ability to de-authenticate or unlink a Facebook account from a Drupal account.
> * Does not require any external libraries or downloads.
> 1 votes

# Answer
fboauth is best one.i have using that module for user signup.you can easily mapping your facebook information with profile field like religion,email,education history,work history,etc.and the you enable the ADVANCED PERMISSION SETTINGS in toggle tab.
> 0 votes

---
Tags: users, social-network
---


title: Alter field values via module

text:
# Question
Title: Alter field values via module
How can I update field values of all nodes via module?

I have a `hook_cron` function inside `MYMODULE.module` that updates `field_popularity_score` field of all nodes, of a particular type, so that I can use Views to sort the nodes by `field_popularity_score`.

# Answer
In Drupal 7, you should use a queue for such type of operations. In short, what happens is the following:

* An item is added to the queue
* An item in the queue is processed, and removed

In the case of cron tasks, there is a hook (hook\_cron\_queue\_info()) that tells Drupal which queues need to be handled when drupal\_cron\_run() is executed, and which function handles the items contained in the queue.

```
function mymodule_cron_queue_info() {
  $queues['mymodule_update_node_popularity'] = array(
    'worker callback' => 'mymodule_update_node_popularity',
    'time' => 20,
  );

  return $queues;
}

```

For how to populate that queue, I see two possible cases:

* The field is updated for every node that is updated
* The field is updated for every node, once
* The field is updated for every node that is created, or updated

In all the cases, the following function should be used, together the hook I previously shown.

```
function mymodule_update_node_popularity($nid) {
  $node = node_load($nid);

  // Calculate the new score for the node.

  $node->field_popularity_score[LANGUAGE_NONE][0]['value'] = $new_value;
  // Replace the previous line with the following one, if the value should be different for each language.
  // $node->field_popularity_score[field_language('node', $node, 'field_popularity_score')][0]['value'] = $new_value;

  node_save($node);
}

```

The parameter received from the worker callback (in this case, `mymodule_update_node_popularity()`) is the one that is passed to $queue-\>createItem().

In the first case, I would implement the following code.

```
function mymodule_node_update($node) {
  if ($node->type == 'content type to handle') {
    $queue = DrupalQueue::get('mymodule_update_node_popularity');
    $queue->createItem($node->nid);
  }
}

```

In the second case, I would implement the following code.

```
function mymodule_cron() {
  $args = array(
    ':type' => 'content type to check',
    ':created' => variable_get('mymodule_last_checked', 0),
  );
  $queue = DrupalQueue::get('mymodule_update_node_popularity');

  $nodes_result = db_query('SELECT nid, created FROM {node} WHERE type = :type AND created >= :created ORDER BY created ASC', $args);
  foreach ($nodes_result as $node) {
    $queue->createItem($node->nid);
    variable_set('mymodule_last_checked', $node->created);
  }
}

```

The reason I am not using `"SELECT nid FROM {node} WHERE type = :type"` as query is that such query would cause `mymodule_cron()` to always add the same nodes to the queue (except for those nodes that have been deleted). `mymodule_cron()` needs a way to filter out the nodes that have been already handled, and the query I wrote is a way to achieve that. The value passed to `$queue->createItem()` can also be an array, or an object, and that value would be passed to the worker callback.

In the third case, I would use the following code.

```
function mymodule_cron() {
  $args = array(
    ':type' => 'content type to check',
    ':changed' => variable_get('mymodule_last_checked', 0),
  );
  $queue = DrupalQueue::get('mymodule_update_node_popularity');

  $nodes_result = db_query('SELECT nid, changed FROM {node} WHERE type = :type AND changed >= :changed ORDER BY changed ASC', $args);
  foreach ($nodes_result as $node) {
    $queue->createItem($node->nid);
    variable_set('mymodule_last_checked', $node->changed);
  }
}

```

This code works because, when a node is first created, both `$node->created`, and `$node->changed` are set to the same value.

In the first case, when you need to update the field value when the node is updated, you could implement hook\_field\_presave(), instead of using a Drupal queue.
> 4 votes

# Answer
You'll probably want to add some sort of queuing mechanism so that your cron run doesn't time out, but this would be one way:

```
// Get the nids
$args = array(':type' => 'type');
$nids = db_query('SELECT nid FROM {node} WHERE type = :type', $args)->fetchCol();

// Load the nodes
$nodes = node_load_multiple($nids);

// Loop through and update each field value
foreach ($nodes as $node) {
  $node-> field_popularity_score[LANGUAGE_NONE][0]['value'] = function_to_get_value();

  // Save the node
  node_save($node);
}

```
> 2 votes

---
Tags: 7, entities, cron
---


title: hook_scheme doesn't work

text:
# Question
Title: hook_scheme doesn't work
> **Possible Duplicate:**
> hook\_schema is not creating database table

I am developing a module in Drupal 7. It is called scorm. I created scorm.install file, where I wanted to create the necessary tables, when the module is being installed. For testing I used book module: I installed it and 'book' table was created.

So I took the code from book.install, renamed all the functions prefixes from 'book\_' to 'scorm\_' and tried to install my module. I added this code to scorm\_schema function:

```
function scorm_schema() {
    print 123;exit;

```

And 123 was printed when installing. So I removed this test code, being sure, that the hook is called.

But the book table was not created! How can I debug and find out the cause of problem?

# Answer
> 0 votes
`hook_schema()` should return an array that defines a database schema.

# Answer
> 0 votes
Book table was created after I disabled and uninstalled the module. Then enabled it again, using this set of commands:

```
drush pm-disable 'scorm'
drush pm-install 'scorm'
drush en 'scorm'

```

---
Tags: 7, hooks, installation, database
---


# Question
Title: How to create multi-value, multi-bundle entity reference fields in code?
I'm looking for example *code* that demonstrates creating a new entity reference field with multiple values, referring to *multiple different bundles*.

# Answer
Sorry for the long code dump but there's really no other way to do this:

```
field_create_field(array(
  'translatable' => '0',
  'entity_types' => array(),
  'settings' => array(
    'target_type' => 'node',
    'handler' => 'base',
    'handler_submit' => 'Change handler',
    'handler_settings' => array(
      'target_bundles' => array(
        'article' => 'article',
        'page' => 'page',
        'webform' => 'webform',
      ),
      'sort' => array(
        'type' => 'none',
        'property' => 'nid',
        'field' => 'body:value',
        'direction' => 'ASC',
      ),
      'behaviors' => array(
        'views-select-list' => array(
          'status' => 0,
        ),
      ),
    ),
  ),
  'storage' => array(
    'type' => 'field_sql_storage',
    'settings' => array(),
    'module' => 'field_sql_storage',
    'active' => '1',
    'details' => array(
      'sql' => array(
        'FIELD_LOAD_CURRENT' => array(
          'field_data_field_entity_reference' => array(
            'target_id' => 'field_entity_reference_target_id',
          ),
        ),
        'FIELD_LOAD_REVISION' => array(
          'field_revision_field_entity_reference' => array(
            'target_id' => 'field_entity_reference_target_id',
          ),
        ),
      ),
    ),
  ),
  'foreign keys' => array(),
  'indexes' => array(
    'target_id' => array(
      'target_id',
    ),
  ),
  'field_name' => 'field_entity_reference',
  'type' => 'entityreference',
  'module' => 'entityreference',
  'active' => '1',
  'locked' => '0',
  'cardinality' => '-1',
  'deleted' => '0',
  'columns' => array(
    'target_id' => array(
      'description' => 'The id of the target entity.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
  ),
  'bundles' => array(
    'node' => array(
      'page',
    ),
  ),
));

```

The `target_bundles` in the `handler_settings` is where you assign the different bundles, and the `cardinality` of `-1` ensures unlimited values for the field.

In case you're interested, this is the code that allowed me to build the above definition from an existing entity reference field (which seems to have originated at this blog post):

```
$entity_type = 'node';
$field_name = 'field_entity_reference';
$bundle_name = 'article';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

```

It's a handy little script; I'm sure I've posted it somewhere here before but I can't find it at the moment.
> 3 votes

---
Tags: entities
---


# Question
Title: How to share user and user profile in a multisite environment?
> **Possible Duplicate:**
> How do I create a multisite, sharing users and nodes?
> How to share user and user profile in a multisite environment?

My question was about the whole process to get the shared user in a multisite environment. I didn't know how to start.

I found my answer here

http://drupal.org/node/547862

As the title says I would like to share user and profile table between multisites.

I have got the main domain like example.com and then I have two subdomain site2.example.com and site3.example.com with separate db.

My 'sites' directory is:

**all**

modules

themes

libraries

---

**default**

files

setting.php

---

**site2.example.com**

modules

themes

libraries

files

setting.php

---

**site3.example.com**

modules

themes

libraries

files

setting.php

I know how to create multisites with separate db, modules, themes and files, now I would like to know the whole process to create a multisite with shared user and user profile. What I need to do?

Thanks in advances.

# Answer
Edit settings.php -\> $databases

```
$databases['default']['default'] = array(
  'database' => 'my_db',
  'username' => 'user',
  'password' => 'pass',
  'host' => 'example',
  'prefix' => array(
    'default'   => '',
    'users'     => 'shared_db_',
    'sessions'  => 'shared_db_',
    'role'      => 'shared_db_',
    'authmap'   => 'shared_db_',
  ),
  'collation' => 'utf8_general_ci',
);

```

Add any other tables as required in `prefix` array. Have a look at settings.php as well it has lots of documentation on all these.
> 2 votes

---
Tags: 7, users, database, multi-sites
---


title: File permissions after module update

text:
# Question
Title: File permissions after module update
Everytime I update a module the (linux) file permissions are changed. I use 755 permissions for my directories and 644 for files inside the modules directory. Is there anyway I can tell drupal the default file permissions for every module update ?

# Answer
Turns out that default file permissions on a gnu/linux system come from `/etc/profile` where you can find a line like :

```
umask 022

```

This means all the files will be created with the default 755 file permissions.

However if this is not the case you should check whether you are running your php code along with suPHP since it sets it's own file permissions default and this effectively overrides the ones on `/etc/profile` (usually under `/etc/suphp.conf`).
> 0 votes

# Answer
This is probably not Drupal's fault. Check the default file permissions on your server!
> 1 votes

---
Tags: 7, users, updating
---


# Question
Title: What function does Drupal provide to save an array in a file?
I am writing a module that handles a large associative array which has string keys and floats values.

```
$array = array('hello' => 122.23, 'name' => 334.3, /* etc... */);

```

I was thinking of storing it in the database by serializing it, but the array size is dynamic, so I thought of storing it in a file to reduce access time.

What functions should I use to create the file, write the content, and read the array from the file?

# Answer
Apart from PHP functions for reading/saving data in files, Drupal 7 has file interface functions too; one of those is file\_unmanaged\_save\_data() which saves data in a file. The difference between those Drupal functions, and the equivalent PHP functions is that the Drupal functions can handle the case the module is trying to save the content in a file that already exists. See FILE\_EXISTS\_ERROR, FILE\_EXISTS\_RENAME, and FILE\_EXISTS\_REPLACE.

There are file interface functions that save a reference to the file created in a table. This can be useful in the cases the files needs to be automatically deleted because they are temporary, or programmatically deleted. See for example file\_copy(), and file\_move().

About using a database to save serialized data, that is what Drupal already does with the table containing the value of Drupal variables defined from modules. Its database table is defined as follow. (I show the definition used from Drupal 7, but Drupal 6 uses a similar definition.)

```
  $schema['variable'] = array(
    'description' => 'Named variable/value pairs created by Drupal core or any other module or theme. All variables are cached in memory at the start of every Drupal request so developers should not be careless about what is stored here.',
    'fields' => array(
      'name' => array(
        'description' => 'The name of the variable.',
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
      ),
      'value' => array(
        'description' => 'The value of the variable.',
        'type' => 'blob',
        'not null' => TRUE,
        'size' => 'big',
        'translatable' => TRUE,
      ),
    ),
    'primary key' => array('name'),
  );

```

During bootstrap, Drupal loads all the variables from the database, and saves their values in a global variable. This is the code used by Drupal for this purpose. (The function is variable\_initialize(); the Drupal 6 function is variable\_init(), called in the same circumstances.)

```
  // NOTE: caching the variables improves performance by 20% when serving
  // cached pages.
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
    $variables = $cached->data;
  }
  else {
    // Cache miss. Avoid a stampede.
    $name = 'variable_init';
    if (!lock_acquire($name, 1)) {
      // Another request is building the variable cache.
      // Wait, then re-run this function.
      lock_wait($name);
      return variable_initialize($conf);
    }
    else {
      // Proceed with variable rebuild.
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
      cache_set('variables', $variables, 'cache_bootstrap');
      lock_release($name);
    }
  }

  foreach ($conf as $name => $value) {
    $variables[$name] = $value;
  }

  return $variables;

```

Drupal doesn't have performance issues, even if that function is called for every rendered page. As you can see, it caches the value of the variables in a cache. If your data is requested frequently enough, you could consider using a cache table too.

As for using persistent variables to store data, keep in mind they are loaded in memory every time Drupal bootstrap; if you are going to store data that could not be used for the currently loaded page, then persistent variables are not what you should use for storing your data. Also, since `variable_set()` clears the cache used for the persistent variables, it is generally preferable to reduce the number of calls to `variable_set()` done for a single page.
> 2 votes

# Answer
This is more a PHP than Drupal question really. You could use functions like

* `fopen`
* `fread`
* `fwrite`

To handle the files.
> 0 votes

---
Tags: files
---


title: How to disable link on a node title?

text:
# Question
Title: How to disable link on a node title?
I'm using Drupal 7. I want disable link on some node-title.

Like disable ''Link this field to the original piece of content'' in Views.

How can i do this? For example, via template.php?

# Answer
The code that makes that happen is in node.tpl.php:

```
<?php if (!$page): ?>
<h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>">
    <?php print $title; ?>
  </a>
</h2>
<?php endif; ?>

```

So to override it, you just need to re-create node.tpl.php somewhere in your theme's folder, remove the `<a>` tag surrounding the title, and clear Drupal's caches. Then you won't get links on title for node teasers any more.

If this is too 'all-encompassing' and you just want to do it for a specific content type then as well as copying the original (unchanged) node.tpl.php into your theme's folder, create another one called, for example, node--article.tpl.php (for the article content type), and make the alterations in there instead.
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: Initially unchecked radio boxes in a form on load
I have programmed module having a form (using Drupals's form API) which contains **radio** checkboxes like this:

```
$form['r_8'] = array(
    '#type' => 'radios',
    '#options' => array(
        '1' => t('Yes'),
        '0' => t('No')
    ),
    '#required' => TRUE,
    '#checked' => '', // ???
    '#title' => t('a label text ... '),
    '#default_value' => !empty($form_state['values']['r_8']) ?
        $form_state['values']['r_8'] : '',
    '#suffix' => '<div style="clear: left"></div>'
);

```

When the page with that form is initially loaded, I want all these radios initially unchecked. I tried to set the **#checked** property to **FALSE**, but it doesn't work. Setting the **#default\_value** to, for example, -1, a warning raises (which I can understand, because -1 is none of the provided option values).

Is there any way to load initially the form with the radio's unchecked?

I could not find any information pointer so that's why I ask here.

Thanks in advance!

# Answer
`#checked` is not a property used from radios form fields, nor radio form fields. It was not even used from Drupal 6.

I used the following code, and none of the radio buttons were selected.

```
/**
 * Form builder.
 */
function custom_module_form($form, &$form_state) {
  $form['r_8'] = array(
    '#type' => 'radios',
    '#options' => array(
      '1' => t('Yes'),
      '0' => t('No')
    ),
    '#title' => t('Test'),
    '#default_value' => NULL,
  );

  return $form;
}

```

In this case, if the user doesn't select one of the radio buttons, the form field would not have a a value associated. Your code could handle it as if the user selected a third value (such as "undecided") or what your code considers the default value (e.g. "yes"); if the latter is the case, users should see a note about that.

It makes sense to use the following code, at least in a case: When you want the users voluntary select a value for the field, and not use the default one selected by the module. For example, it would make sense if the user is expressing an agreement, and you want to be sure the user noticed that field, and clicked on one of the radio buttons.

```
function custom_module_form($form, &$form_state) {
  $form['r_8'] = array(
    '#type' => 'radios',
    '#required' => TRUE,
    '#options' => array(
      '1' => t('Yes'),
      '0' => t('No')
    ),
    '#title' => t('Test'),
    '#default_value' => NULL,
  );

  return $form;
}

```
> 2 votes

# Answer
This works for me:
The default value has to return false.

```

  $form['r_8'] = array(
    '#type' => 'radios',
    '#options' => array(
        '1' => t('Yes'),
        '0' => t('No')
    ),
    '#required' => TRUE,
    '#title' => t('a label text ... '),
    '#default_value' => !empty($form_state['values']['r_8']) ?
        $form_state['values']['r_8'] : FALSE,
    '#suffix' => ''
  );

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: I want to override theme node.tpl.php file with node--[content-type].tpl.php in my custom module
I am making a new custom module. and i have 1 content type called city management(city-management). I want to override theme node.tpl.php file with node--city-management.tpl.php in my custom module.

Is it possible?

# Answer
This can be done by providing Drupal with a content type template suggestion through hook\_theme. It uses the same 'node--contentname' formalism you are used to in theme templates. This method is IMHO preferred if your module also creates the content type you're theming.
> 0 votes

---
Tags: 7, theming
---