# Question
Title: How do I connect to the database from a module?
I would like to connect to the database from a Drupal 7 module. Currently I only have the query I want to run which is:

```
$query = db_select('z_lists)
->fields('country')
->condition('value', $country, '=')
->execute()
->fetchAssoc();

```

What I can't figure out is how to establish a connection to the default database.

Any help?

# Answer
Just execute the query, Drupal takes care of everything else.

If it doesn't work, then that's for another reason.

Also, see Given that db\_select is much slower than db\_query, why would I want to use it?
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Ideas on how to create a multi-part form, where the form requires completion/approval by another user
**Desired form submission workflow:**

* **User A** fills out a form, along with an email address for **User B**
* **User A** submits the form, which then notifies **User B** by email of a request to complete and approve the form
* **User B** clicks a link in the notification email and is able to complete (and approve) **User A**'s submission

**User B** would actually be adding extra data to the form, not just "approving" it.

What are your ideas for ways to accomplish such a multi-part form? Are there any modules (besides webform) that could assist with this type of form logic? Would you base this on webform, or Drupal 7's forms API?

# Answer
All you need is D7 forms API if you are comfortable writing PHP. There are several ways you could go about it. One assumes that the e-mail address of User B is the same e-mail they used to create their Drupal account. You'll need to store the result of User A's submission in a database somehow. Depends if you are already storing data from the DB or not. If not you can use variable\_set() to store the e-mail address in one of Drupal's core tables and then variable\_get() to retrieve it.

The idea is to save whatever user A stores to the DB after filling out the form. In your form definition, at the top check to see if that value is there. If so, you know user A has completed his part, next step is to check the user accessing this form. If their e-mail address matches the e-mail supplied during user A's part then you display user B's part of the form.
> 1 votes

---
Tags: 7, forms, webforms
---


title: Show all nested menu links in Drupal 7

text:
# Question
Title: Show all nested menu links in Drupal 7
How do I display all nested links in `<ul><li>` format in Drupal 7? The default code only displays the 1st level links even though they are arranged in the Drupal admin menu as nested:

```
<?php if ($main_menu): ?>
<div id="mainmenu"> <?php print theme( 'links__system_main_menu', array('links' => $main_menu) ); ?> </div>
<?php endif; ?>

```

Only the 1st level is displayed in the ff. menu setup:

```
-Fruits
---Apples
---Oranges
---Lemons
-Cars
---Big car
---Small car
---Fucked up car
-Whatever

```

# Answer
The default `$main_menu` variable in `page.tpl.php` is set to `menu_main_menu()`, which is a contextual view of the main menu tree.

To get your desired output, you need to get the entire menu tree using `menu_tree_all_data()` and `menu_tree_output()`.

To do this in your theme, create `template.php` if you haven't already, and add a new preprocess function for the page template:

```
function THEMENAME_preprocess_page(&$variables) {
  // Get the entire main menu tree
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Add the rendered output to the $main_menu_expanded variable
  $variables['main_menu_expanded'] = menu_tree_output($main_menu_tree);
}

```

Then, in `page.tpl.php`, you can just use:

```
<?php print render($main_menu_expanded); ?>

```

to get a expanded, nested unordered list of the main menu.

For a little more flexibility, you might want to consider the Menu Block module, which will let you create blocks of expanded menus out of the box with its *Expand all children of this tree* option as well as a host of other options for segmenting menu trees.
> 23 votes

---
Tags: routes, theming, navigation
---


title: Grouping fields together

text:
# Question
Title: Grouping fields together
Is it possible to generate fields which are "grouped" together when marked as Unlimited? For example, a select field with label "What time do you wake up?" lets the user select the day of the week (Mon-Sun) then beside it an empty textfield to type in the time they get up. These 2 fields are "grouped" together. Then if they want to add another day of the week (Unlimited), the new field generates a dropdown menu and a textfield together all over again.

NOTE: No CCK please. I'm using Drupal 7 and it's already in the core.

# Answer
> 2 votes
Try the Field Collection module. It's not stable yet (beta 1) but it looks promising.

# Answer
> 0 votes
I know the Drupal way to build a module that solves everybody's problems but I needed something a little more specific. Here is my business hours module. I made it with the Field API which is actually very easy to use.

# Answer
> 0 votes
This is actuall a feature in CCK 3, which is in alpha for D6 but not yet available (as an "extras" module) for D7...

Shame, they should've had this by default.

Here is a discussion about modules that have similar functionality:

http://drupal.org/node/939836

But Field collection seems to be the smartest choice for now.

---
Tags: 7, entities
---


# Question
Title: What is best method for token replacement within node content?
I am a newbie and have scoured forums (including this one), books, and documentation but cannot find a clear answer to this:

What is the best method (custom module? PHP within node content? other?) to replace a token within the body of a node with the value of a custom user profile field?

Use case: I need to replace text within an external URL with a string specific to the current user. I'm hoping I can put a token string into the URL within the node content, and have the token replaced with the specified value from the current user's profile.

I have not created any custom modules, but am willing to dive into it if somebody recommends a specific path to take.

# Answer
> 5 votes
Token Filter

> Token Filter is a very simple module to make token values available as an input filter.

# Answer
> 2 votes
To implement a system to replace custom tokens, you have two possibilities, supposing that you are referring to text present in the node body that needs to be replaced with dynamic values:

* use a filter module that allows you to define which text needs to be replaced, and with what
* use a custom module that replaces the text found in the node body before the node is shown

In the first case, the filter module would be invoked also for comments, and the filter would not be able to make a difference between replacing text in a node body, or in a comment body. In the case the module allows you to define the PHP code executed when a specific text is found in the node/comment body, there is also a performance issue. Instead of passing PHP code to `eval()`, it would be better to define a custom module that implements a specific filter to replace a specific text you need. Also in this case, the module would not be able to know when it is invoked for a node or a comment; it also means the filter module could not get information outside the arguments given to the filter callback, which means it is not able to get information about the author of the node, since the filter callback doesn't get any node or comment object.
In the case of Custom filter, the description given for the input format is not translatable; that means that passing from English to French as language for the site (or the node being shown), the description reported would not be shown in French.

In the latter case, a module implementing hook\_nodeapi('view'), in Drupal 6, could alter the content of `$node->content` to alter the node body; similarly, a module implementing hook\_node\_view() would achieve the same result in Drupal 7 and later versions.
In both the cases, `$node->content['body']` contains the node body as array that follows the format used by the form API, or required by drupal\_render().

Enabling the PHP input format for a site that is not used as developing/testing site is not considered a good idea. Rather than enabling that input format is better to implement a custom module, which is what has been done on Drupal.org that replaced a content type using the PHP input format with a normal content type, and implemented a custom module to alter the content of specific nodes.

# Answer
> 1 votes
You might be interested in Custom filter.

> Instead of creating a new filter module for every filter you need, you can use this module for tasks like creating your own tags, replacing token values and all changes you need in the text. You can use simple replacements or use PHP code to write more powerful things (like use it to highligth code with Geshi).

---
Tags: nodes, tokens
---


# Question
Title: Views taxonomy exposed filter, show tree/hierarchy in drop down menu
I have an exposed taxonomy filter that allows the user the filter by term. The vocabulary is 2 tiers, however in the exposed filter menu the hierarchy appears flat.

Is there a method/module to show the hierarchy with indentation or prefixing child terms with "-", similar to the taxonomy term selection menu from the node edit form itself.

x-post from https://stackoverflow.com/questions/6222875/drupal-views-taxonomy-exposed-filter-show-tree-hierarchy-in-drop-down-menu

SOLUTION:

The filter Taxonomy: Term ID (with Depth) will display the option "Show Hierarchy In Dropdown" when you select the Dropdown widget.

# Answer
The filter Taxonomy: Term ID (with Depth) will display the option "Show Hierarchy In Dropdown" when you select the Dropdown widget.
> 6 votes

---
Tags: views, 6, taxonomy-terms, input-formats
---


# Question
Title: Logging out user by modifying database directly?
Is there a way to log out a user by just modifying the drupal database?

# Answer
> 3 votes
You can delete the user's session in the sessions table.

---
Tags: database, users
---


# Question
Title: dissecting the og module - where is the content type form submit handler for function og_ui_form_node_type_form_alter?
drupal version: 7

Hi, I'm trying to add settings to a content type form and I'm using organic groups as a guide. I see the form elements for OG being added in the og\_ui.module at line 316 in this function `og_ui_form_node_type_form_alter` but I don't see where these form elements are being submitted, handled, saved, processed... I would've expected it to add another submit handler to the form but it doesn't seem to be the case. Anyone have any experience with this?

# Answer
This happens automatically.

Adding a variable to that form means that it is automatically saved with `variable_set()` with a `_node_type` suffix. Similar to admin forms.

Here is another example: userpoints\_nc\_visits\_form\_node\_type\_form\_alter().

As you can see, the form element is for example named `userpoints_nc_visits_points` and the default value is fetched with `userpoints_nc_visits_points_type` (inside the get setting api function).
> 1 votes

---
Tags: nodes, organic-groups, forms
---


# Question
Title: What approach for showing custom user fields on a node?
I've added a few custom user fields which users complete when registering.

What is the simplest approach to show these fields when viewing content that user has created?

For example, when viewing a blog entry I can see the 'submitted by..' and their name. I would like to use my custom user fields to expand that summary.

I've got no problem using views, or creating/modifying the theme etc, but I'd like some guidance on the easiest approach before I start out. (It's too easy to hack away on one approach in Drupal when there's a much easier solution!)

# Answer
> 4 votes
I would do this with two steps.

1. Create a theme function that will take the user object and render what you want to render instead of submitted by username.
2. Alter the node template or use the preprocess\_node and get the user from the node $node-\>uid and use hour theme function to replace the default submitted by with your custom value.

Doing it like this should be quick, easy and simple.

# Answer
> 4 votes
Ok, I'm only using drupal 6 but I think these answers can lead you to a solution:

1. With the core profile module there is a block "Author information"
2. You can use the Author Pane module but it doesn't have a stable release for D7 yet.
3. You can use views to build an author block:

If you're using profile from core:

> Create a user view
> Set the argument to User: uid
> Choose "Provides default argument" set to "User ID from URL" and check "Also look for a node and use the node author"
> Add your user profile fields.

If you use Content Profile

> Create a node view
> Set the argument to Node: Nid
> Choose "Provides default argument" set to "Node ID from URL"
> Create a relationships to retrieve the content profile
> Add your content profile fields.

---
Tags: 7, entities, users
---


title: How to view the query in Views 3?

text:
# Question
Title: How to view the query in Views 3?
I want to look at the MySQL query built by Views. In views 2 it just shows while I can't seem to find it in the View 3 UI. Is it still available?

# Answer
> 14 votes
You can choose to display the query; it's a checkbox called "Show the SQL query" on the Views settings page (admin/structure/views/settings).

---
Tags: views
---


title: menus and per page sub menus

text:
# Question
Title: menus and per page sub menus
I have my primary navigation (which is hard-coded into the theme). What I want is for a sub-menu (depending on the page) to appear in the left sidebar.

For example, if they click on the primary link for "bears" then the left sidebar menu might have "black bears" and "brown bears". How can these sub menus be accomplished? I don't want sub-menus these hard coded (i.e. easily configured by the client)

# Answer
You could try Menu block
> 2 votes

---
Tags: theming, routes, navigation
---


# Question
Title: How do I hide one block and show another in a template
My page.tpl.php is set to use a particular block in the right-hand column.

However, I have one template page (created by a module) in which I don't want to display this block.

How can I hide the block ONLY on that page and show a different block instead?

# Answer
Each block can have various visibility settings. Among others, you can configure that a block should only show up on a number of pages or everywhere *except* on a number of pages.

So go to the blocks administration page, click on the configure link for that block then make sure "All pages except those listed" is selected and insert the path for which you want to hide it. You can also use wildcards for something like "forum/\*", which would hide the block when viewing a forum page.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Does Drupal detect if the user register email could not be delivered and removes the account?
I got this error message back from the MTA:

> This message was created automatically by mail delivery software (Exim).
>
> A message that you sent could not be delivered to one or more of its recipients. This is a permanent error. The following address(es) failed:
>
> #######@*****\****.+++
> Connection timed out:
> retry timeout exceeded

This is fine so far. What puzzles me is the fact that the created account disapeared. This is reproducible. The account was created again (same email address), the delivery error occoured again and the account disapeared.

Is this on purpose?

# Answer
Drupal doesn't know about the status of the email. I'm not sure how Drupal 5 does it, but it would be possible to setup Drupal to delete accounts older than X that has never logged in.
> 1 votes

---
Tags: users, 5
---


# Question
Title: Glossary input filter saving to node_revisions
I have been using the Glossary module and it has been working great. I add `"ADSL"` into a node and if a glossary definition exists, on render it converts it to `"<acronym title="Asymmetric Digital Subscriber Line">ADSL</acronym>"`.

However, today I noticed it has started putting the glossary term markup into the node content (saving in the database table node\_revisions). When I edit the node again, it no longer contains "ADSL"; it contains the full markup generated by the Glossary input filter (`<acronym title="Asymmetric Digital Subscriber Line">ADSL</acronym>`).

As far as I am aware, the data is saved straight to the database before any input filter should touch it, as per Drupal Input Formats and Filters.

I am completely confused to how this is possible. Does anyone know what might cause an input filter to act so?

# Answer
Resolved, somehow the Glossary filter got enabled in the CKeditor's security settings "Please choose carefully all filters that protect your content (probably not all filters listed below are security filters)."

Disabled this and now the Glossary works as it should.
> 1 votes

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


title: Active main menu link

text:
# Question
Title: Active main menu link
I need to set an item in the main menu as active even though I'm using separate sub menu blocks. What is the best way to do this? Due to particular styling I cannot just put them under the Category headings (like breadcrumbs).

The problem I came across is that the main menu item isn't active, as it doesn't know that the user is in the sub category of it as there is no link back. I can't find a way to set a particular main menu link as class active.

# Answer
> 2 votes
You should look into menu position. You can set active menu trails based on path or node type and they have a simple api for extending the functionality.

# Answer
> 1 votes
You could also have a look at the Menu block module. It claims to fix the issue in Custom menus never receive an active trail. The creator of the module also have some blog posts about the module: Use Menus in Drupal 7? You Need Menu Block Module.

---
Tags: routes
---


# Question
Title: Terms for cities and state to build dependent selects
I'm adding a "City" field to a content type. I need it to be 2 dependent select lists. I mean, the user will select a state in the first select and the second select will be populated with the cities for the selected state.
In fact those are for Spanish *provincias* (states) and *localidades* (cities).

I know I can do this using the 'hierarchical\_select' module, but now I need to create the taxonomy Terms for states and cities.

Is there any way to find and import those Terms (Spanish *provincias* and *localidades*) into my site? Creating these term is a daunting task.

# Answer
> 1 votes
You can use the module Taxonomy CSV import/export which is very handy to import and create taxonomy terms or vocabulary.

---
Tags: taxonomy-terms
---


# Question
Title: How to import title, description and image from website
I would like to have a "Facebook style link commment" feature in Drupal 7. When you enter a URL it will pull the page title, first 100 characters of the main website text and an image. There is a module called "Facebook Style Micropublisher" but it's Drupal 6 only. Any other ideas on how this could get accomplished?

# Answer
> 1 votes
The manual way to do it is to create a custom module that uses drupal\_http\_request to download the remote URL, then parse through the resulting data to pull out any images, a summary, and the contents of the title tag.

This is a lot harder than it sounds because manually parsing HTML is actually pretty tricky. If you must take this approach, try using simplexml or a library that tries to simplify things for you.

A better approach might be just porting the Drupal 6 module yourself - it's probably less work and you could contribute your code back and possibly get patches from other contributors.

---
Tags: 7, importing-exporting
---


# Question
Title: How to display one of Drupal's default forms
I have a module that i want to use to display a modified version of one of Drupal 7's default forms. The form ID is `user_profile_form` and it is the form used to edit a user's account information.

So this is the structure of my module:

1. `hook_menu` with a page callback to a function --\> `user_exe_edit()` --\>
2. function `user_exe_edit()` calls `drupal_get_form(input_simple_form)` --\>
3. function `input_simple_form($form, &$form_submit)`

Now I need the function input\_simple\_form to return the Drupal form with id "'user\_profile\_form".

How do I do that?

# Answer
`user_profile_form()` is an existing function, but it's not defined in a module file; that means that the file where the function is defined needs to first be loaded, in a way or the other.

Instead of defining a page callback that then calls `drupal_get_form()` to get a form defined in a form builder implemented in the same module, I would rather define the menu callback using the following code (the code I am writing is for Drupal 7, but can easily adopted for Drupal 6, if there is the need.

```
$items['path'] = array(
  'page callback' => 'drupal_get_form',
  'page arguments' => array('input_simple_form'),
  'file path' => drupal_get_path('module', 'user'),
  'file' => 'user.pages.inc',
);

```

The code for the form builder could be something similar to the following one:

```
function input_simple_form($form, &$form_state) {
  $form = array_merge($form, drupal_get_form('user_profile_form', $account));
  // ...
}

```
* user\_profile\_form() uses a third argument, the category of the profile to show. Its default value is "account"; if you are getting an error about a missing third argument, then you can explicitly pass that parameter too, for example using its default value, as in `drupal_get_form('user_profile_form', $account, 'account')`.
* "user.pages.inc" is the file containing the `user_profile_form()` form builder, in Drupal 7, and Drupal 6. The reason that you get the error you see is that such files are loaded only when Drupal is instructed to load them; that is done by using the "file" and "file path" array indexes. ("file path" is only required when the file is not between the files of the module implementing `hook_menu()`.)
* I used `input_simple_form()` as form builder, in the case you need to use its own validation and submission handlers.
* There is a `$account` variable that has not been defined in the example code I wrote. That is one of the required arguments that `user_profile_form()` needs, as the function needs to know for which user account the form is being build. That is the other reason to use your own form builder, which should load the user object for the account used for the user profile form, or pass the value of the global `$user` to `drupal_get_form('user_profile_form')`.
> 8 votes

# Answer
I'm not sure if I'm misunderstanding the problem, but is

```
return drupal_get_form('user_profile_form');

```

What you are looking for?

In the case of that particular form, it is defined in an inc file which is probably automatically included by the menu system. You'll need to run

```
module_load_include('inc', 'user', 'user.pages.inc')

```

before you call drupal\_get\_form to ensure that the form building function is available to Drupal before you call it.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Content profile + rules. Problem with action, when user is created a profile then logged in
guys. Got a problem with content\_profile and rules modules. By default rules has a

> Redirect to profile creation page, if users have no profile.

It works fine. When a user is registering on the site then logging in, it redirects the registered user to a node/add/profile (Content profile creation page). But when a user that already has a profile node logs in, he's redirecting to mysite.com/node, not on a user page.

What's wrong?

# Answer
Where do you want them to go?

> Redirect to profile creation page, *if users have no profile*.

If a user already has a profile node, they won't be directed to create one (as stated in the rule itself) so when the user logs in, he/she should be taken to your default front page (or whatever page he/she was trying to access if access was denied to anonymous users.

---

**EDIT**

If you want users to be directed to the user page if they already have a profile, simply create another rule to do so. Below is an example of a rule to do this for you:

1. Create a new rule, give it any title you like, for the **Event** select `User has logged in` and click "Save changes"
2. Now click "Add a condition", choose `User has content profile` and click the "Next" button
3. On the settings page for the condition, you may choose what content type to use for your content profile condition. Choose one (or leave it if using default `Profile`) and click "Save"
4. Now click "Add an action", choose `Page redirect` (under the **System** heading) and click the "Next" button
5. On the settings page for the redirect, in the first textbox for **To:** enter `user`, click the "Force redirect" checkbox and click "Save" (as seen below):

Make sure the rule is enabled and your users should be directed to the correct pages.
> 1 votes

---
Tags: rules, users
---


# Question
Title: Where can I see the options accepted by the field API for the widget type?
Where can I see the options accepted by the field API for the widget type?

```
$instance = array(
  'field_name' => $field_name,
  'label' => 'Demofield Demo',
  'description' => 'This is a demonstration text field.'
  'widget' => array(
      'type' => 'text_textfield',
  )
);

```

# Answer
> 1 votes
The default options for each widget are listed in the hook\_field\_widget\_info() implementation.

You can find all such implementations in core by searching for "\_field\_widget\_info": You can find a list of all core implementations of that hook by searching for "\_field\_widget\_info": http://api.drupal.org/api/search/7/\_field\_widget\_info

# Answer
> 2 votes
There isn't a preset list of widget types; the widget types are the ones defined from modules that implement fields. Using the following code, you can get the list of all the widget types implemented by the enabled modules:

```
$array = module_invoke_all('field_info');

foreach ($array as $id => $info) {
  print $info['default_widget'];
}

```

The code essentially invokes all the implementations of hook\_field\_info(), and print what is defined as default widget.
If you have installed Devel, instead of `print` you can use `dsm()`.

If you want to know the settings available for the field implementation, then you need to look for the implementation of hook\_field\_settings\_form(), such as list\_field\_settings\_form(), or text\_field\_settings\_form().

```
function text_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];

  $form = array();

  if ($field['type'] == 'text') {
    $form['max_length'] = array(
      '#type' => 'textfield',
      '#title' => t('Maximum length'),
      '#default_value' => $settings['max_length'],
      '#required' => TRUE,
      '#description' => t('The maximum length of the field in characters.'),
      '#element_validate' => array('_element_validate_integer_positive'),
      // @todo: If $has_data, add a validate handler that only allows
      // max_length to increase.
      '#disabled' => $has_data,
    );
  }

  return $form;
}

```

---
Tags: 7, entities
---


title: How to add term description to view?

text:
# Question
Title: How to add term description to view?
I have a list of nodes (ubercart products) filtered by taxonomy term. How can I attach a term description to the view?

# Answer
> 1 votes
You can extract the tid used in the view in a preprocess hook, and use it to get the description and render it where you want.

Another solution would be to create an area handler that displays the description. This could then be used to render the term description in the header or footer section of the view.

To create an area handler you need to subclass `views_handler_area` and add your area handler to the term using `hook_views_data_alter`

```
hook_views_data_alter(&$data) {
  $data['taxonomy_term_data']['your_area_handler'] = array(
    'title' => t('Title'),
    'help' => t('Help text.'),
    'area' => array(
      'handler' => 'your_views_area_handler_class',
    ),
  );
}

```

The area handler doesn't need much more than a render function which acts as it's theming function, so it's not that tricky.

---
Tags: views
---


# Question
Title: Is it possible to add custom stylesheets while using a core theme?
I'm trying to add a custom stylesheet although I'm using the Garland theme but so far I wasn't able to do it.

I've tried the following:

```
function mymodule_init(){
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_js ( $path . '/extra/script.js' ); // script is loaded and works
    drupal_add_css( $path . '/extra/style.css' ); // css isn't.
}

```

I also have a form that I will display when accessing `/myform`, so I tried to add the CSS there:

```
function mymodule_formname($form_state){
    drupal_add_css( drupal_get_path('module', 'mymodule') . '/extra/style.css' );
    // $form definition here
    return $form;
}

```

No success. Finally also tried to include the CSS using the `#attached` form parameter but still no results. I flush the cache for each of the attempts just to be sure...

Am I missing something? Shouldn't this be possible?

# Answer
You can use context and context add assets to get the job done. If you are not familiar with context it's a way to set reaction blocks, theme HTML, theme pages, menus, etc based on conditions on menu items, paths, node types, taxonomy terms, etc. You can include a custom css file on your form with context add assets.
> 2 votes

# Answer
Adding Module Stylesheets using drupal\_add\_css()

Using hook\_init() to include CSS and JS files

Kind of what you're trying to do... but yeah, you should be able to do it pretty easily inside your module. If it won't be added in hook\_form\_alter(), try it outside of there site-wide, or using hook\_init() like you tried originally (just make sure you clear all caches on the performance page).

Are you using Drupal 6 or Drupal 7?
> 1 votes

---
Tags: 7, hooks, theming
---


# Question
Title: Is this the correct way of iterating through users and check if they have a determined permission?
I'm developing a module where I need to retrieve all users of a website and check if they have a specific permission.

```
<?php
$reviewers = array();

$result = db_query('SELECT uid, name FROM {users} ORDER BY uid');

while ($record = db_fetch_object($result)) {

    if ($record->uid != 0) {
        if (user_access('review article', user_load($record->uid), TRUE)) {

            $reviewers[$record->uid] = (string) $record->name . '@domain.com';

        }
    }
}

```

I'm using this code and it works but it can become quite slow. I've tested in a site with 5.000 bogus users and it takes about 30 secs to complete.

# Answer
> 2 votes
That code works, but as you found out, it needs to load each user completely and is therefore very slow.

Unfortunately, the database schema of permissions/roles in D6 is really crappy. It stores all permissions of a role in a single role, separated with a comma.

But still, it should be possible to query that information directly. What you want to query is which roles have a specific permission and then which users that have at least one of these roles.

Something like this:

```
db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {permission} p ON p.rid = ur.rid WHERE p.perm LIKE '%s'", '%, $permission_name_here,%');

```

There are a few special cases where this doesn't work/needs additional checks:

* uid 1 does have all permissions
* all users automatically have the authenticated user role (rid 2) but that is not stored in the users\_roles table. So if a permission could possibly be assigned to that role, then you need to explicitly check that and if yes, return all users.
* It is possible to dynamically assign roles to users based on some conditions. In this case, the query won't work for that...

---
Tags: 7, users
---


# Question
Title: How do I backup my site w/o the command line?
Nearly all the documentation on backing up my Drupal site seems to require using the command line. My hosting service does not provide command line access. How do I backup my site without using the command line?

# Answer
I'd go with the Backup and Migrate module. You can either start backups manually or have it run automatically on cron run. Then you can just download your `/sites/` folder and you should have a full backup of everything (assuming your files, modules and themes are all in `/sites/` like they should be.)
> 27 votes

# Answer
The "Backup and Migrate" module should do the trick:

http://drupal.org/project/backup\_migrate

If you don't want to go that route, you should be able to do a SQL dump of your database (assuming you have a mySQL Admin type interface with your hosting account) and FTP the contents of your Drupal "sites" folder.

That should be enough to restore it elsewhere I'd think.
> 11 votes

# Answer
Another recommendation for Backup and Migrate, and you can also add the Backup and Migrate Files Module if you want to grab your files automatically.
> 9 votes

# Answer
I use this handy script which backups not only the database but the whole site altogether. By adding the DB password to the script, you will be ablt put it in your cron table to makes backups automatically and even add other commands to send the backup to an external server etc.
> 1 votes

---
Tags: backups
---


# Question
Title: Drupal 6: only displaying select vocabularies?
I use two vocabularies, one for tags and one which determines where a view will be displayed. Can anyone tell me how I could output the terms of my former category while hiding the ones in my latter category?

Thanks!

# Answer
> 3 votes
Assuming that the row style of your view is "Fields", add a "Taxonomy: All terms" field to your view. On that field's settings form, you will see a "Limit terms by vocabulary" checkbox. Select it and choose the vocabulary you want to show.

# Answer
> 1 votes
What you want is to display the terms of a vocabulary. The views module is great for this. You can create a view showing terms and select only to show the ones in the vocabulary of your choice.

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


# Question
Title: How can I point to a site in a not common directory path?
Normally when adding a new Drupal site I just put the sites root folder in /var/www/ and then edit the hosts file for that address and then edit the httpd.conf file to point to that site.

The situation here is the Drupal site I am working on came from a git repo where other people work on it as well. The site came like this - /sitename/web/sites/default so when I put that in my /var/www directory it isn't the same as a usual setup which is - /sitename/sites/default, multipleSite1, multipleSite2, ...

So the /web directory is throwing things off I think. It messes with the simple way I point to a site with http.d conf and the way Drupal looks inside that directory for the settings.php file.

Simple example of httpd.conf that normally works fine

```
<VirtualHost *:80>
     DocumentRoot /var/www/testsite
     ServerName testsite
</VirtualHost>

```

Any ideas? I'm sure it's a real simple solution.

-apache2 on ubuntu10.04

# Answer
> 2 votes
If I have an unusual directory structure I tend to use symlinks to get the folders into the correct place on the system.

If your site is running a standard drupal install you could install that to /var/www as normal

and create a link to your directory

```
ls -s /path/to/my/default/dir /var/www/default

```

---
Tags: .htaccess
---


# Question
Title: Update query with a dynamic expression in Drupal 7?
```
db_update('warrior_members')
          ->fields(array('points' => 'points' +1))//This is not working
          ->condition('uid', $liv_user)
          ->execute();

```

## How to increase the cell at 1?

Sorry for my bad English

# Answer
> 12 votes
You want to use an expression: http://api.drupal.org/api/drupal/includes--database--query.inc/function/UpdateQuery%3A%3Aexpression/7

Example:

```
db_update('warrior_members')
  ->expression('points', 'points + 1')
  ->condition('uid', $liv_user)
  ->execute();

```

Or to make the 1 dynamic:

```
db_update('warrior_members')
  ->expression('points', 'points + :amount', array(':amount' => 1))
  ->condition('uid', $liv_user)
  ->execute();

```

---
Tags: database
---


# Question
Title: How do I call an implementation of hook_form_alter()?
I have a function in my module that implements hook\_form\_alter(): `function getuserform_form_alter(&$form, $form_state, $form_id)`.

How do I call it? How do I pass it the required parameters?

# Answer
> 2 votes
`hook_form_alter` comes in two variants:

* `hook_form_alter`
* `hook_form_FORM_ID_alter`

Both are called when a form is retrieved using `drupal_get_form` or one of the other form builder functions, but the latter is only invoked for the form with the specific form\_id. Unless you are doing the same alterations to multiple forms, it's a good idea to use the `hook_form_FORM_ID_alter` variation, as it will create less overhead.

All hooks are called by Drupal when certain events happen. For `form_alter`, that is when the form is being built. So all you need to do, using the example in your question, is to do a check on the `$form_id` and do the alterations you want.

Notice `$form_state` should be passed by reference using the `&$form_state` notation. Sometimes you need to not only change `$form` but also `$form_state` to be able to modify the form like you want.

# Answer
> 1 votes
Like other hook implementations, they are automatically called by Drupal core code.

You don't invoke an implementation of `hook_form_alter()` (or `hook_form_FORM_ID_alter()`), in the same way you don't directly call an implementation of `hook_user()` (or `hook_user_OP()`, in Drupal 7). You call a Drupal function that invokes that type of hooks: for `hook_user()`, you call `user_load()`; for `hook_nodeapi()`, you call `node_load()`; for `hook_form_alter()`, you call `drupal_get_form()`, `drupal_build_form()`, or `ajax_get_form()`.

---
Tags: forms
---


# Question
Title: How can I have multiple versions of the same form, in different pages?
There is a default Drupal 7 form called "user\_profile\_form". I would like to show certain elements of this form on one page of my website, and then a different set of elements from this same form on another page.

Is there a way to either:

a) have multiple versions of the same form (keeping the same ID) or
b) clone the form and then modify it (there will be two different form IDs)

Can you point me in the right direction?

# Answer
You can use `hook_menu()` with `drupal_get_form()` to use any form on any path (see Using a node editing form on a page that not a node edit page).

You can then use `hook_form_alter()`, and get that to work differently depending on the path.

You can use `$_GET['q']` for the full path or `arg()` to get parts of the path. and use `if()` logic to determine how to alter the form.
> 5 votes

---
Tags: forms
---


# Question
Title: Is adding indexes to a Drupal database safe?
I have been searching and reading about this, but I have not seen anything definitive about the topic of adding indexes to Drupal tables (both core and contrib).

My main concern is what happens with any custom indexes when you update core or contrib code and there are schema changes. What happens in this case?

EDIT:

I think some context may help. I am primarily concerned with adding indexes to tables to tune site performance (queries showing up in the slow query log, pages with slow views, etc). This may involve adding an index to a table in someone else's module. For example

1. I install module `foo`
2. Module foo creates table `foo`
3. I add an index to table `foo`
4. Module `foo` has an update that changes the schema

What happens?

# Answer
Yes, it could result in problems.

If a module wants to do something with the column on which you have added an index, it will remove it's own indexes and then do whatever operation it intends to do.

What exactly will happen will depend on your database type and the actually executed operation. For example, a rename of the column will work fine with MySQL, but will fail on PostgreSQL. But if it tries to delete that column (maybe after migrating data to a different table/colun), it will fail.

The chances that this will happen are relatively low, at least for minor updates (does depend on the actual module however. I usually don't add *any* changes which could break something to minor releases), but it is possible.

My suggestion would be that you try to work together with the module maintainers. If the problematic query/ies are from the module itself, then the maintainers will probably happily add the indexes, if you provide a patch. Provide DESCRIBE output of the problematic query/ies before and after adding the index. Also provide a patch that updates the schema (include an update function to set it for existing installations).

Someone who is actively working on performance related things and does the above really well is catch, here is an example: http://drupal.org/node/983950
> 9 votes

# Answer
As reported in `DatabaseSchema_pgsql::changeField()`, and in `db_change_field()`:

> IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field.

That means that you have to drop all affected keys and indexes with db\_drop\_{primary\_key,unique\_key,index}() before calling db\_change\_field(). To recreate the keys and indices, pass the key definitions as the optional $new\_keys argument directly to db\_change\_field().

For example, suppose you have this field definition and you want to change *foo.bar* to serial, leaving it as the primary key.

```
$schema['foo'] = array(
  'fields' => array(
    'bar' => array('type' => 'int', 'not null' => TRUE)
  ),
  'primary key' => array('bar')
);

```

The correct calls sequence is the following one.

```
db_drop_primary_key($ret, 'foo');
db_change_field($ret, 'foo', 'bar', 'bar',
  array('type' => 'serial', 'not null' => TRUE),
  array('primary key' => array('bar'))
);

```

Similar code is used for Drupal 7.

Keep in mind that, for my experience, you cannot remove a primary key that uses a serial field. On Drupal 6, I got an error all times I tried doing that; I didn't try that on Drupal 7.
Apart that, I don't know any other issue you could have with database indexes.

About adding an index to a database table that is created from another module, I would not suggest doing that, because:

* A module doesn't drop an index for a field that is being changed, if the module itself didn't create that index. It would not be possible for the module to do that because it doesn't know the name of the index.
* Modifying a database table created by another module is never a good idea, even in the case the module is a core module. If there is another module that changes the same table, how could the modules handle any conflict they have with each other, or with the changes the core module would apply to its own database?

If the database table is being created from another module (a core module or a third-party module), I would suggest to open a feature request for the module, providing a use case for using a new index; if there are any performance issue, adding an index could be the desired thing to do.

If you are going to add an index to a table created from another module to your own site, then be prepared to any changes you need to do to your custom module every time the module is updated, and before you install it in your own site.
It is you who can decide if the extra work is worth the performance you get. Personally, I don't think it is worth, though.
> 3 votes

---
Tags: database
---


# Question
Title: An Atomic Question about Views Modules and Templates
I am a Views newbie. I added a template file to my sub-theme folder with a more specific name (from Theme Information), the file name becomes **highlighted**, but the file is not used (I'm sure of this cuz I wrote some new lines to the template (`<li>Like, Doah!</li>`, etc.).

Some extra details:

* I am using fusion core with a fusion sub-theme (begot from fusion\_starter). The fusion sub-theme is activated. I've not changed much.
* The custom view is fully created, has a menu entry, and displays an end user content page with the correct data.
* I currently have only two "views-view-\*" template files between the directories containing the two fusion themes.
    + fusion\_core/views-view--page.tpl.php (edits to this page ARE visible on the end user "content" page).
    + fusion\_my\_subtheme/views-view--my-view--default.tpl.php (the trouble file)
        1. Click Theme: Information to find "views-view--my-view--default.tpl.php" is listed as the most specific file name available under Display output.
        2. Theme Information highlights this template file name bold. And, when I renamed this file, the Theme Information display returned an error message that the file is missing--therefore I conclude the Drupal/Views app is finding this file.

Why, if this file name is highlighted, is this more specific template file located in my sub-theme directory not being used by Drupal? Is it possible there is an order to cache clearing, or template refresh? I feel as though I'm trying to catch my tail... :/

If the file name is highlighted, changes are made to that custom file named, then Views Module and Drupal should render the page with changes made to this template--that's "How it works", yes?

Xtian

# Answer
> 2 votes
This is rather strange. The fact that the correct file name is highlighted in the Views theming information section suggests it's set up correctly. However, I'll add some more things to check and see where we end up.

You should also have the `views-view--page.tpl.php` file in your sub-theme's folder. Strictly speaking, anytime you are overriding a template file with a more specific template file, the default template file should reside in the same directory. So just copy `views-view--page.tpl.php` to your `fusion_my_subtheme/` folder. Then clear your theme registry\[1\] and try again.

I would also suggest using the Devel Themer module to help figure this out. It will tell you for sure which template file is being used for the View's display.

1. I usually choose to clear ALL caches instead of just the theme registry. Occasionally I've seen strange problems disappear when I do this.

---
Tags: views, theming
---


# Question
Title: How do I convert a database from MyISAM to InnoDB?
I am going to convert all the tables of 500MB database from MyISAM to InnoDB to see whether it will improve the overall performance of a busy Drupal 6 site. I am wondering what is the best (i.e. safest/easiest/fastest) way to do the conversion.

# Answer
As a MySQL DBA, I trust MySQL to do the conversion by having MySQL write the script for me.

Form the Linux command run this query

```
mysql -h... -u... -p... -A --skip-column-names -e"SELECT CONCAT('ALTER TABLE ',db,'.',tb,' ENGINE=InnoDB;') FROM (SELECT A.db,A.tb,A.tbsize FROM (SELECT table_schema db,table_name tb,(data_length+index_length) tbsize FROM information_schema.tables WHERE engine='MyISAM' AND table_schema NOT IN ('information_schema','mysql')) A LEFT JOIN (SELECT table_schema db,table_name tb FROM information_schema.statistics WHERE index_type='FULLTEXT') B USING (db,tb) WHERE B.db IS NULL) AA ORDER BY tbsize" > /root/ConvertMyISAM2InnoDB.sql

```

The script will convert the smallest tables first. This script was also bypass any MyISAM tables that have FULLTEXT indexes.

Ater looking over the script, you can simply run it in MySQL as follows:

```
mysql -h... -u... -p... -A < /root/ConvertMyISAM2InnoDB.sql

```

or if you want to see the timing of each conversion, login to mysql and run this:

```
mysql> source /root/ConvertMyISAM2InnoDB.sql

```

This should not get messed up because a full table lock happens when the conversion is being executed.

Once all tables are converted you need to tune the MySQL settings for InnoDB usage and scale down the key\_buffer.

Please read this for setting the InnoDB Buffer Pool : https://dba.stackexchange.com/questions/1/what-are-the-main-differences-between-innodb-and-myisam/2194#2194

Please read this also : https://drupal.stackexchange.com/questions/1715/what-would-the-optimal-mysql-configuration-for-a-drupal-7-site-be/2367#2367

Give it a Try !!!
> 7 votes

# Answer
I've written a drush command for this a while ago.

```
<?php
/**
 * Implements hook_drush_command().
 */
function convert_drush_command() {
  $items = array();

  // the key in the $items array is the name of the command.
  $items['convert-engine'] = array(
    // a short description of your command
    'description' => "Convert MYSQL Table Type",
  );
  return $items;
}

function drush_convert_engine() {
  $args = func_get_args();
  $engine = $args[0];

  $result = db_query("SHOW TABLES");
  while ($row = db_fetch_array($result)) {
    $table = array_shift($row);
    drush_log(dt('Converting @table to @engine', array('@table' => $table, '@engine' => $engine)), 'success');
    db_query("ALTER TABLE $table ENGINE = $engine");
  }
}

```

Worked for me a year ago or so, not sure if the drush API changed since then.

You can place that in a convert.drush.inc for example in the .drush folder or execute it somehow on your site, for example with the devel execute php block. As a drush script, you can call it like this:

```
drush convert-engine InnoDB

```

**Warning**: If someone does something with the database while these commands run, your database will be messed up completely. Unrecoverably. So, put your site into maintenance mode and make a backup before trying this! And of course, try on a development/testing site first :)
> 4 votes

---
Tags: database
---


title: Get the "href" attribute of an image

text:
# Question
Title: Get the "href" attribute of an image
I created a new content type in Drupal 7, and added an image field named "field\_photo." Can anyone tell me how I can extract the "href" attribute of that photo? Is there a short code I can use?

# Answer
> 2 votes
When you access the field on your node you will get the file id. This can be passed to file\_load which will return the file object. One of the properties is `filepath` which holds the path to the actual file. I'm guessing that's what you are after - images doesn't use href `<a>` tags do.

---
Tags: media
---


# Question
Title: Allow users to select among various default images while creating their profile if none is uploaded
I'm using ImageCache, ImageField and Content Profile to create my user profiles and I'd like to offer different default images if the user doesn't upload one.

Currently, ImageField offers a default image if none is uploaded but how can you show your user a lists of profile images in order to let them select one or upload their own ?

I'm looking to get something like this:

Of course if the user upload one it will be used on their profile.

Any module you can recommend me or custom code to achieve this ? Does the Gravatar module allow this ?

Thanks a lot.

# Answer
Use this module - Avatar Selection.

Does exactly what you're looking for.
> 3 votes

# Answer
The Gravatar module currently allows the site administrator to choose the default image to use if the user doesn't have a Gravatar (including all the choices you've presented above), but this applies on a site-wide basis --- users cannot choose their own Gravatar variant, though they can still upload their own image if desired.

If you do end up developing support for per-user Gravatar variant switching, consider supporting this feature request, which anticipates similar functionality: http://drupal.org/node/1172546 .
> 1 votes

---
Tags: 6, users, media
---


# Question
Title: How can I add a "weight" functionality to nodes?
I would like to be able to specify a "weight" for the article nodes published in the homepage. What is the best way to do this?

# Answer
You could for example use Nodequeue to create fixed list of nodes and then show that as the front page (as a view I guess).

Or, you could define your own weight field (for example a simple integer field, or a select with options from -50 to 50) and then create a view of nodes which you sort based on that field.
> 5 votes

# Answer
Both Draggeble Views and Nodequeue are great for creating easy-to-use admin pages with drag-and-drop sorting. The main difference between Draggable Views and Nodequeue is that Nodequeue allows manual sorting *and selection*, whereas Draggable Views allows manual sorting of an automatically populated list (a view). Both modules are explained and compared in these two blog posts.
> 5 votes

---
Tags: 7, nodes
---


# Question
Title: How do I override the default page.tpl.php?
I have one page in my `D7` website with significant deviation from the rest of my pages. In this page I will only display a limited number of regions and in a different layout.

What is the best way to override the default `page.tpl.php`? Can I create something like "`mycustom-page.tpl.php`" that gets called ONLY on a specific url within my site?

# Answer
> 13 votes
Depending for what exact content you want to make a special template there are diffrent solutions for that. Look at Drupal 7 Template Suggestions. Example for a single node: `page--node--1.tpl.php`.

In case the core template suggestions do not offer the flexibility you need, you can add more suggestions based on your own criteria. This is done in a preprocess function in your theme's template.php. For more information, see Working with template suggestions.

---
Tags: 7, theming
---


# Question
Title: Site building process: what is the relationship between CCK, Views, Panels, Blocks and Taxonomy?
A beginner question. I need to understand the relationship between the top Drupal structure modules: CCK, Views, Panels, Blocks and Taxonomy, i.e., when building a website, what is the general steps that the site builder should consider regarding using those modules? What comes first? What's next?.

Let's consider a site that categorizes IDEs (integrated development environments) and provides detailed informations about each IDE. How would be the mentioned modules implemented with this use case? What would be this websites building process?

Thanks.

# Answer
Taxonomy and CCK are both used to customize content types. This first thing you usually want to do when building a site, is to figure out how the content types should be defined. With Drupal 7 you have entities instead which provides a more flexible way of defining data structure, but the idea is the same.

Once you have defined your content types, views, panels (or context) comes into play. Views is really good at making listings of different types, like the latest articles, nodes post by user X etc.

Panels can be used to piece things together, but as it's a very complex tool, it can also be a bit overkill to use. It was originally created out of a frustration with the Drupal block system, with all it's limitations. It if you want to use panels to manage blocks, you might consider using context instead as it provides the same functionality but is more lightweight. What panels is good at making lots of pages with very different layout. It has one advantage over context, and that is a more tight integration with views, allowing to use views not defined at blocks as blocks (panel panes).

**So to sum up.**

1. Define content types.
2. Create list/displays with views.
3. Piece it together with panel/context.
> 4 votes

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


# Question
Title: Remember users Taxonomy choice, such as which city to filter the site by?
I want to convert an existing site to support the selection and association of Cities. Each node can be associated with a City, and the Cities will be selectable as tabs at the top of each page.

Lets say the City Taxonomy is:

* All Cities (mainly used for old content the client doesn't want to convert)
* London
* New York
* Paris

If a user browses to any City's front page then that will stamp that city in their cookie/user profile, such as:

* site.com/all-cities
* site.com/london
* site.com/new-york
* site.com/paris

Then when the user returns to the site front page `site.com/` without a city specified, they'll be redirected to their remembered front page.

The site does not support user accounts however, so only anonymous users will visit, so it only needs to use cookies rather than store data in the DB per user.

**Importantly,** on top of this, the site is using 1 hour page caching due to relatively low traffic and poor page load speeds, so the redirect will need to run before the cache.

What is there a standard Drupal way to achieve the above, or will it need to be entirely custom in order to run outside any form of caching?

Thanks for any advice!

# Answer
> 4 votes
I would create a custom module and.

1. Save the choice in the users session (sessions is mapped to a cookie)
2. Use `hook_boot` to do the redirect, a simple `drupal_goto` should be enough.

Using sessions is more simple, but depending on your settings the data will persist for a shorter period of time than cookies. But that might be a good thing.

---
Tags: 6, taxonomy-terms, cookies
---


# Question
Title: Managed file: the file used in the field may not be referenced
I am having some issues with the managed\_file type. Whenever I try to edit and save a form that has a managed\_file element in it an error occurs: *The file used in the Picture field may not be referenced.*

This is the code I'm using:

```
function foo_form ($form, &$form_state, $foo) {
  ...
  $form['file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Picture'),
    '#default_value' => (isset($foo->file->fid) ? $banner->foo->fid : ''),
    '#upload_location' => variable_get('foo_upload_location'),
  );

  if (isset($foo->file)) {
    $form['current_file'] = array(
      '#type' => 'hidden',
      '#value' => $foo->file->fid,
    );
  }
  ...
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
  return $form;
 }

function foo_form_submit ($form, &$form_state) {
  $foo = (object)$form_state['values'];

  $current_file_set = isset($form_state['values']['current_file']);

  if ($form_state['values']['file'] != 0 && !$current_file_set) {
    // Load the file uploaded in the form.
    $file = file_load($form_state['values']['file']);

    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);

    $foo->file = $file->fid;
  } else if ($form_state['values']['file'] != 0 && $current_file_set) {

    // If we are uploading a different picture, delete the old one and save the
    // new one. If not, don't do anything.
    if ($form_state['values']['current_file'] != $form_state['values']['file']) {
      file_delete(file_load($form_state['values']['current_file']));
      // Load the file uploaded in the form.
      $file = file_load($form_state['values']['file']);

      $file->status = FILE_STATUS_PERMANENT;

      file_save($file);

      $foo->file = $file->fid;
    }
  } else {
    file_delete(file_load($form_state['values']['current_file']));
    $foo->file = null;
  }

  ...
}

```

I traced the error back to the file\_managed\_file\_validate function in *modules/file/file.module* but don't know anything about the file references.

# Answer
The solution is to add a call to file\_usage\_add after the file is saved. This call adds a reference to the file in the database. The file\_managed\_file\_validate function will spot the reference and won't trigger the error.

```
file_usage_add($file, 'foo', 'foo', $foo->id);

```

This isn't documented in the Form API under the managed\_file example.

This issue is being discussed on the Drupal documentation issues: link
> 40 votes

---
Tags: 7, forms, files
---


title: Custom teaser text in Drupal 7

text:
# Question
Title: Custom teaser text in Drupal 7
I have a custom field named "field\_blurb." Is it possible to make this the text shown in a teaser instead of the default which is from the body field?

# Answer
Certainly, just go to the content types display settings, and pick the teaser build mode. Drag the body to hidden, and set the blurb to be displayed. Done.
> 4 votes

---
Tags: 7, nodes
---


# Question
Title: Prevent "→" from being written in URL alias
When the post title contains "→," it will be written in the URL alias. When using Boost, an URL containing "→" will not be well cached; visitors will see the uncached node.

How do I prevent the "→" character from being written in URL aliases?

# Answer
> 6 votes
The transliteration module does a good job on making ASCII urls and some other useful stuff. Works with path\_auto.

# Answer
> 5 votes
Try adding the char(s) you don't want in the aliases in the "Strings to remove" textarea you find at /admin/config/search/path/settings (Drupal 7), or /admin/build/path/pathauto (Drupal 6).

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


# Question
Title: Setting up permissions for non-registered users
How do I set permissions for non-register users?

**Step 1**: I registered Drupal 7 in my system.

**Step 2**: I wrote a module for `user_register()`.

**Step 3**: When I call the menu callback an access denied error is shown.

How should i set permission to non-register users to register?

# Answer
> 5 votes
In your menu item definitions, you can specify TRUE as the access callback to make the item always accessible.

```
<?php
  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
      'access callback' => TRUE,
    );
    return $items;
  }

?>

```

See http://api.drupal.org/api/function/\_menu\_check\_access/7

Hope this helps, Mark

---
Tags: users
---


# Question
Title: How to pass a parameter/argument to webform using clean urls?
I've found a post which explains how to pass a parameter/argument/referer to webform.

It works fine, but I get an ugly URL. Is there any way to do this using a clean URL? I mean without using GET parameters.

# Answer
> 4 votes
You could solve this using mod\_rewrite in your `.htaccess` file. Try something like

```
RewriteCond %{REQUEST_URI} ^/path/to/your/webform/(value)$
RewriteRule ^.*$ /path/to/your/webform?param=%1 [L]

```

This way you can do many things but you can't configure that with the drupal UI. Here's an example with more paramters:

```
RewriteCond %{REQUEST_URI} ^/path/to/your/webform/(value1)/(value2)/(.*)$
RewriteRule ^.*$ /path/to/your/webform?param1=%1&param2=%2&param3=%3 [L]

```

Check out the manual.

EDIT: your comment example should look something like that:

```
RewriteCond %{REQUEST_URI} ^/myform/(\d+)$
RewriteRule ^.*$ /myform?i=%1 [L]

```

The exact regex at the end depends on your parameters. If you expect only numbers like `1` or `0125` `\d+` should be fine. Check out this cheatsheet for more/other char-classes and regex stuff.

# Answer
> 2 votes
Drupal strictly recognize the `q` i.e. `$_GET['q']` as the page path otherwise redirects to Page Not Found page. Passing the arguments as part of `q`, Drupal menu system must be aware of such arguments place holders. And there arguments can be accessed by `arg([arg-index])`

Passing extra unregistered parameter to any page is only possible by additional GET variables beside `q` and can be accessed by PHP's regular way. i.e. $\_GET global array

---
Tags: webforms
---


title: A whole view disappears

text:
# Question
Title: A whole view disappears
I have deployed user generated views to a production site using Views (6.x-2.12) bulk export feature; that is, views are saved in the code as mymodule.module and mymodule.views\_default.inc, the latter of which contains 12 views in more than 11,000 lines.

Sometimes, one or more views suddenly disappear from the site. Flushing all caches usually fixes it, but it is hard to duplicate the issue and it bothers me that it may happen again in the worst time.

Possible causes that I think of are:

* Does the .inc file have too many lines (\> 11K)?
* I have saved the .inc file with Windows new lines, while the server is Linux.

Could one of these be the cause? Anyone experienced a similar issue?

# Answer
> 4 votes
Solution for the "to many lines" problem:

```
function YOURMODULE_views_default_views() {
    $files = file_scan_directory((drupal_get_path('module','YOURMODULE').'/views','.view'));
    foreach($files as $absolute => $file) {
        require $absolute;
        if(isset($view)) {
            $views[$view->name] = $view;
        }
    }
    return $views;
}

```

This way every view-code can be stored in it's own file inside a `views` subfolder inside `YOURMODULE` as `some_name.view`.

---
Tags: views
---


# Question
Title: How do I better play nice with weights, when overriding a form?
I'm attempting to use the Constant Contact module.
One of the features of this module is that it inserts a check-box into the user registration form. The problem is that it seems to set weights in a way that it interferers with my own implementation of `hook_form_alter()`, on the registration form. The field order is a mess now: the field for the confirmation of the email address is now the first one.

The Constant Contact module is specifying a weight for the checkbox:

```
'#weight' => 11,

```

My implementation of `hook_form_alter()`, just left my new form element weights blank. I could just massage my functions form weights such that it didn't have the fields out of order, but then I risk to do it again the next time I need to add something to the form or use another module that does likewise.

Is there a 'best practice' way to handle form weights assuming multiple override sources?

# Answer
You can adjust your module weight so that it runs after the offending module. This will allow you to control the weight of all elements in the form, even if another module adds and sets them. But this can get very tricky in the longer term if you rely on weights of modules too much.

you could also use an `#after_build` function to alter the weights if you have an exact order in mind.
> 1 votes

# Answer
The only thing I usually do and can recommend is to leave "gaps" between your weigts. So instead of 1, 2, 3, 4, 5 or so, I use for example 5, 10, 15, 20, 25.

The idea is that it makes it easier for other modules to move a field to a different place, or move new fields in-between.
> 5 votes

# Answer
If multiple override sources are adjusting the weight of your field then definitely there is an order in which they are performing. Your `hook_form_alter` might be performing before the other. Adjust your module's weight to perform in the last. Util module can help in this regard to adjust module weights.
> 3 votes

---
Tags: forms, hooks, users
---


title: Better site and database performance

text:
# Question
Title: Better site and database performance
I'm working on a Drupal community site and I want to ask about these things:

1. How do I make a Drupal site more secure?
2. How do I make my site work as fast as possible when there is a lot of visitors and users on the site, and there is a lot of interaction with the database at the same time? How do I maintain the database consistent in this situation?
3. How do I configure Drupal to work during high server load? How do I configure my server's hardware to work during high load moments?

# Answer
> 6 votes
1 - Use captchas and spam filtering; Mollom is a good place to start. There is also info on hardening Drupal in the drupal handbook, ie. http://drupal.org/writing-secure-code.

2 - For starters, turn on the performance module that comes with Drupal.

3 - This is a big question. I have heard good things about Context HTTP Headers, a module contributed by the White House Drupal team. You can find a comparison table on Caching: Moduls that make Drupal scale.

# Answer
> 6 votes
You've asked a massive question here, which could never be fully answered in the space I have on this text box. The answer is that performance tuning is always specific to your workload and has to be customised as such. Security is also a massive topic in itself. I think the best way to answer this is to point you to some resources, because a lot of people ask these questions.

1. Sign up to the Drupal security mailing list. You can see the list here and you can sign up to be informed by e-mail whenever a vulnerability is discovered. You can do this by logging in at drupal.org, clicking Edit on your profile, then going to My Newsletters and checking Security announcements. Also, if you're doing any development Writing Secure Code is a must-read. You should also keep an eye on whats going on with your server's security - most Linux distributions will have an e-mail list to keep you informed about the latest security situation. I'm not even going to mention securing your server to begin with, as that's a massive discussion, not relevant to Drupal.
2. & 3. Obviously, turn on all of the caching options Drupal gives you in the performance section of the admin pages. The Drupal page Server tuning considerations is really excellent and will give you a lot of practical information. Also, APC is installed by a lot of Drupal developers almost immediately and can significantly improve PHP execution time. Finally, to optimise the database a good place to start is by looking at the queries your site is executing and using the MySQL `describe` command to see what's going on and adding index's in slow spots. More information on this here.

# Answer
> 2 votes
For a highly trafficked Drupal site, you should tune MySQL for the content that is in stored now. Whatever the version of Drupal, the MySQL layer can have its configuration computed.

You should want to convert all Drupal tables to the InnoDB Storage Engine. It eliminates table locking from all SQL statements affecting your data.

If you already have InnoDB data, and innodb\_file\_per\_table is not enabled, you need to cleanup InnoDB by segmenting each table into its own physical tablespace. It is imperative to do decent MySQL tuning, even if you have a limited hardware. There are many scenarios for doing such InnoDB optimizations.

IMHO, you cannot plan good settings for my.cnf without knowing the amount of data to configure for. You would have to periodically load a current dataset from production into a staging environment, perform optimizations and come away with the numbers to configure in the my.cnf of the production server.

# Answer
> 2 votes
1. Taking all the standard precautions for web server security as read, Drupal should be very secure out of the box. The basic gist is never ever trust user input - if you stick to active contrib modules and drupal core functionality, you shouldn't need to worry about this really, but if you are coding something custom make sure any user input goes through check plain and db\_query.
2. Massive question. Drupal has some good things out of the box, such as CSS and JS aggregation, page caching, etc. Move watchdog to use syslog instead of writing to the database. Use caching wherever appropriate. Look at Boost, Varnish, memcached, block cache. Optimise your pages using yslow recommendations . If you are getting really serious, you may want to look at moving your database server onto a different machine. This list can get really long really fast, but Khalid Bahayeldin at 2bits is an authority - in particular read this presentation for an idea of quick wins.
3. See number 2!

# Answer
> 1 votes
2 & 3 You can have a look at Drupalize.me video: Drupal Performance & Scalability or others Lullabots articles like Configuring Varnish for High-Availability with Multiple Web Servers

---
Tags: 6, database, performance
---


title: CCK field in node template

text:
# Question
Title: CCK field in node template
If I have a custom CCK field, for example "temperature", is there any way I can directly call it from the node template? Like would there be a $temperature variable?

Thanks!

# Answer
You can access it directly from the node variable like: $node-\>field\_temperature\[0\]\['view'\].

If you want to see what values are actually on the node, I'd suggest `var_dump($node);` in the template to check out what fields/values you can access.
> 4 votes

---
Tags: entities, nodes, theming
---


title: Drupal Panels/Views conflict

text:
# Question
Title: Drupal Panels/Views conflict
I'm using Drupal 7 along with the Panels and Views modules. I've got a view with a page display, but I want to place it in a panel/page. I need the view's display to be that of a page because it has exposed filters, and I can't rely solely on AJAX for the filters because of 508 standards compliance concerns.

However, because the paths of the panel and the view are the same, the view takes precedence, and the panel never shows up. How do I get the view working inside the panel?

# Answer
Create your view as a content pane instead of a page. Then on your panel insert the content pane. You can also look at something like http://drupal.org/project/panels\_everywhere as a more general solution.
> 2 votes

---
Tags: views
---


# Question
Title: How do I tear out the existing menu in a theme and replace it with super-fish (v7.x)
I know this is similar to the Bartik/menu question but I do not believe it is the same, here is the requirement. I am using "the morning after" theme in Drupal 7. This theme looks the way the client wants it but we need a drop-down ability on the "main menu", the menu that runs horizontally across the top of the page. This theme does not have a "navigation", "main menu" or similar region to pop super-fish into. I have tried all the instructions in the Bartik/Super-fish post and I can get super-fish to show up in an region but I have not been able to get it to REPLACE the existing embedded-in-the-theme menu. Any help is greatly appreciated.

This site would not let me post an answer, so as an edit, here is the answer I found. This did not get me 100% where I wanted but found this on another post. It is for a different theme but it seemed to be essentially the same. hope it helps

Im using Drupal 7 with the Busy Theme and I can't figure out how to set Superfish to replace the existing main menu with itself. I can add Superfish to other regions of the theme and it works great, but there is no way to replace the main menu with Superfish that I can find. This may be a problem in that the main menu area of Busy doesn't seem to have a region set to it, so perhaps that could be the problem...

Thoughts? I want to use a drop-down menu for the main user menu, but nothing I do will allow Superfish to replace that main menu.

Description Login or register to post comments Comments

1 Posted by Mehrpadin on April 1, 2011 at 7:54pm Hey there,

Well, normally you should ask the theme developer, but as I see there are a number of similar requests in the issue tracker of the theme, I think I should help you myself:

Create a new region by putting the code below somewhere in busy.info regions\[navigation\] = Navigation You may need to rebuild your theme registry. /templates/page.tpl.php , line #52 to #58: $main\_menu, 'attributes' =\> array('id' =\> 'main-menu', 'class' =\> array('links', 'clearfix')))); ?\> Replace with this: Voila!

# Answer
Superfish will not override your theme's main menu. The only way is to make its block and place it on some region.

You can replace the theme's menu variable/function with a region variable in your page.tpl.php following a guide here.
> 1 votes

---
Tags: 7, routes, navigation
---


title: views of node with weight

text:
# Question
Title: views of node with weight
> **Possible Duplicate:**
> How can I add a “weight” functionalitiy to nodes?

I have views of node for example 10 last of news,I want when create a views of node , I can set this weight, means that create own list. for example , I chose first node , second node ...

please help me

# Answer
You should extend your contenttype with a weight field for this and use it as sort parameter. If your drupalversion is 6 you could use the CCK module for that.
> 0 votes

---
Tags: views
---


# Question
Title: Variable to check if the page is of some other Content Type
The variables `$page` and `$teaser` are very helpful but is there a way to check if I'm in a different kind of Content Type? For example, if I made a content type named **Products**, what can I type in my template file `page.tpl.php` which will display HTML only if the page being viewed is of type **Products**?

# Answer
> 12 votes
Place this in your theme's template.php, replacing 'THEMENAME' with the name of your theme:

```
function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['some_html'] = '';
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['some_html'] = '<p>Hello world!</p>';
  }
}

```

And use this in your page.tpl.php:

```
<?php print $some_html; ?>

```

Alternatively, if you want to keep the HTML string in your template file, I would do this in template.php:

```
function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['print_extra_header'] = false;
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['print_extra_header'] = true;
  }
}

```

And use this in page.tpl.php:

```
<?php if ($print_extra_header) : ?> <h1>THIS GETS PRINTED</h1> <?php endif; ?>

```

Make sure to clear the cache after creating the THEMENAME\_preprocess\_page function, otherwise Drupal will not know it's there and it will not run.

---
Tags: 7, nodes
---


# Question
Title: batch importing node data -- via database?
I'm looking to migrate an existing site to Drupal. I have a a content type on the new Drupal site that will eventually hold some 1500 nodes. Of course, I don't want to enter each one in the form on the admin side; I'd like to input them programmatically, from a script.

What I'm wondering is if I can do plain old SQL INSERTS into the node and related tables, and have my nodes ready to use. Assuming I do the inserts correctly, will the nodes just be there when I fire up Drupal? Or will I need to touch some other parts of the site?

Or is there another way, like a module for batch importing?

This is for Drupal 7.

# Answer
> 4 votes
There are two routes you can take.

One uses the Migrate module usually in conjunction with Table Wizard. This gives you a web front end for doing an import with field mapping, and other nicities. EDIT: just saw that TW doesn't have a D7 version.

The other is a custom import script. The script does the Drupal bootstrap process, queries the remote database, creates a `$node` and then does a node\_save. This is a little more complex, but not that hard.

I have been doing the later on new projects, and is easy to adapt to XML, CSV, or other data sources.

# Answer
> 1 votes
There is Node Export which would probably do and of course Feeds. I'd recommend using a module rather than plain SQL because of all the small things Drupal does when creating a node. It's just easier really.

---
Tags: 7, nodes, batch-operations
---


title: Create an advanced and complete search

text:
# Question
Title: Create an advanced and complete search
I want create an advanced and complete search, like the one on http://www.lib.muohio.edu.

I want to enable search in my CCK fields.
I don't know what module this site use; please help me to know that module(s) used in this site.

Help me to style my site like this site.

# Answer
It looks like they use the multifacet module. As for "help me to style like this site,“ that's a very broad request.
> 1 votes

---
Tags: entities, search, views
---


# Question
Title: Menus - hard coded primary nav with per-page sub nav
My primary navigation is hard coded (it has to be; graphical purposes).

Firstly, how can I tell which one is "active" (current page)?

Secondly, based upon which one is active, how can I show child links of that link in the sidebar? I've thought of a possibility, but it would require creating tons of blocks for the menus and then only enabling them on their parent page. This seems like a lot of work for something that a module should take care of.

I've found http://drupal.org/project/menu\_block which looks promising, but I'm not clear how to use it in my situation.

I prefer to have total control of how the menus will look (a custom .tpl file)

# Answer
> 0 votes
This code will show the current child links:

```
    $mn = menu_tree_page_data($menu-name);
    foreach ($mn as $menu) {
      if (!empty($menu['link']['in_active_trail']) AND is_array($menu['below']) AND !is_null($menu['below'])) {
        echo menu_tree_output($menu['below']);
      }
    }

```

# Answer
> 1 votes
I am not sure which part you need hardcoded, but if it is everything but the `a` tag, then then `l()` helper function comes to the rescue:

```
<li class="menu-item" id="foo">
  <span>
    <img src="menu_foo.png" alt="icon showing foo"/>
    <?php print l("Foo", "original/path/to/foo") ?>
  </span>
</li>

```

Now, if you access "/original/path/to/foo" or (on of its) alias(es), the `l()` helper will automatically add a class "active" to the `a` tag, generated by `l()`.

If, for some reason you need the `l()` outside of the `a`, or if you want to customize the `a` itself (e.g. by adding markup to it), you can use the code seen in the `l()` to determine *activeness* of the current item. Place this as helper in template.php of your theme:

```
function _my_theme_is_active($path) {
  $active = FALSE;
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
      (empty($options['language']) || $options['language']->language == $language->language)) {
    $active = TRUE;
  }
  return $active;
}

```

Obviously `my_theme` is the name of your theme.

Then in the `tpl.php` files, or anywhere in the scope of your theme, you can use the function:

```
<li>
  <a href="<?php print url("original/path/to/foo") ?>" <?php print (_my_theme_is_active("original/path/to/foo") ? 'class="active"' : ' ') ?> id="foo-1">
    Foo
  </a>
</li>

```

Beware that you use url() to catch aliasing for the oringial path, but that you /do/ pass in the original (system) path into the \_my\_theme\_is\_active helper.

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


# Question
Title: Using Views "Rewrite the output of this field" tokens
I have a field which allows a user to upload 3 photos called `field_prodshots`. To any Views experts out there, is it possible to **display just the first value** of that field instead of all 3 while using "Rewrite the output of this field" tokens? After all, I only need the one image to use as a thumbnail.

Typing in `[field_prodshots]` in the textarea for rewriting the output results in the display of all 3 images. I only need the first one.

# Answer
> 5 votes
There's a simple way to show only the first image in a field that allows multiple image uploads.

In the Configuration screen for the field, there's a dropdown called "Multiple Field Settings." Expand that, and you should see options for how many items you want to display, and which item in the list to start with. Change "Display \__ value(s)" from all to 1. You shouldn't need to change the separator in your case, as you're only displaying one image.

See below for screenshot. This setting should work fine alongside "Rewrite the output of this field" tokens (I haven't had it not work).

http://img585.imageshack.us/img585/8644/multipleimagesshowonlyo.png

In a field with several images uploaded, I'm correctly seeing only the first as you can see here:

http://img713.imageshack.us/img713/5479/resultzc.png

# Answer
> 2 votes
Create a template file in your currently active theme's folder

```
e.g. views-view-field--field-my-field-value.tpl.php

```

`print_r(array_keys(get_defined_vars()))` to get full list of scope variables. The most usable will be $fields and $view

# Answer
> 2 votes
If there are no other fields in the view, you can filter it by that field's delta 0.

Haven't tested it, but in Filter Criteria selecting Fields: ... (field\_prodshots) - delta and setting that to 0 should give only the first value.

---
Tags: views, media, tokens
---


# Question
Title: how to display the uploaded zip file content in drupal?
i created a cck file field and i uploaded zip file in that content type. Now i want to display the content of zip files after uploading the zip files. i don't know how to implement it?. can you tell me how to implement it?

thanks in advance.

# Answer
> 5 votes
It will not be very hard to accomplish. Don't let anyone tell you otherwise :D

What you need to do (if you have some experience with PHP and creating a very simple Drupal module) is download the PCLzip module which basically integrates the pclzip library into Drupal. There is no submodule for listing zip contents at the moment but it is very simple to make one if you keep in mind that there is a specific method in the library, the ListContent method.

You can see examples of how the methods of the library are used at the related projects that do use the pclzip module like PCLzip Folder or PCLzip Content Files. If you study their code, you will be able to achieve your goal very easily (and hopefully contribute your code back to the community).

Don't listen to advice that say: "extract the contents of the zip file first" since:

1. There is no need to extract files out of the zip file, you just need to see them
2. It's never a good idea to add extra complexity and write custom code that will be useful to nobody but you (and after a while so much custom code will be useless to you too)

Keep it simple: use the work of other people and expand it.

Edit: Let me give you an example so that you can understand how easy it is. If you check the pclzip module you will find a function that looks like this:

```
function pclzip_build_archive($filename) {
  // get the temp file
  global $pclzip_temp_file;
  $pclzip_temp_file = tempnam(file_directory_temp(), $filename);
  // build the archive
  require_once('pclzip/pclzip.lib.php');
  return new PclZip($pclzip_temp_file);
}

```

The line:

```
return new PclZip($pclzip_temp_file);

```

is the one that uses the PclZip method to create a new archive. All you need to do is create a new function, similar to that one, in your custom module, that will use the listContent method to list the contents of the zip file. It's that simple.

Notice, that there is one extra step after retrieving the contents of the zip file, and this is: "displaying them". Since the method of the pclzip library gives you back an array, it should be simple enough to display it (you can choose how you want to do it).

I have tested the following:

1. Installed the pclzip module
2. Made sure that the library is in the appropriate directory (according to pclzip instructions)
3. Added the following code in the pclzip.module file:

```
function pclzip_nodeapi(&$node, $op) {

  $cckZip = $node->field_zipfile;
  $zipPath = $cckZip[0]['filepath'];
  $zipView = $cckZip[0]['view'];

  if (isset($zipPath)) {
    require_once('pclzip/pclzip.lib.php');
    $zip = new PclZip("$zipPath");

    if (($list = $zip->listContent()) == 0) {
      die("Error : ".$zip->errorInfo(true));
    }

    $zipView .= "<div>";

    for ($i=0; $i<sizeof($list); $i++) {
      $zipView .= $list[$i]['filename'] . "<br />";
    }

    $zipView .= "</div>";

    switch ($op) {
      case "view":
        $node->content['body']['#value'] .= $zipView;
    }
  }
}

```

Notice that:

* field\_zipfile is the name of the cck field that I used to upload the zip file
* I have edited the pclzip module directly (which is not a very good idea). You should probably do the changes in your own module, but I just wanted to test the solution very quickly
* You should decide where the filenames will be printed. I have just added them at the end of the node's content without any specific formatting. you can add classes and specific tags to the filenames in order to theme them if you want.

---
Tags: entities, files
---


# Question
Title: How to use Devel module to see what creates an URL?
I want to know what creates an URL of a site for example a view,panel etc. Which command should I write on the Devel module on "Execute php" ? Thanks

# Answer
Not really sure what you are meaning by 'create url', but any url in Drupal is registered through hook\_menu(). Don't let the name confuse you - this is a seperate concept to lists of urls (like the navigation menu). The menu system keeps a cache of url to callback function mappings, which you can inspect to see which function each url points to.

To view the menu cache, you can run this code:

```
dpm(menu_router_build());

```

You can then look through the array to see the details for each url.
> 2 votes

---
Tags: uri, debugging
---


# Question
Title: In a Views page with 3 arguments, 3rd argument default PHP being ignored if 2nd argument is not present
Using Views 2, I have a View with 3 different vocabularies as arguments.

The first 2 are intended to be acquired from the URL, however the 3rd will only ever receive it's value from the Default Value PHP Code.

However if argument 2, which is optional, is not supplied, then Argument 3 is not evaluated.

**SOLUTION:**

Just to clarify where I landed:

The default option `Action to take if argument is not present` is always set to something (there is no `do nothing`).

It was already set to `Display all values` which was not working.

However `Provide default argument` \> `Fixed Entry` \> `"all"` while the argument wildcard is also `"all"` is allowing the 3rd argument to be evaluated.

# Answer
> 3 votes
Always keep the optional args in the end otherwise define `Action to take if argument is not present` or at least set `Provide default argument` in argument configuration form.

---
Tags: 6, views
---


# Question
Title: Controlling the height of a jQuery accordion in content page
I have managed to add a jQuery accordion content page to my Drupal7 site by following the instructions/code given here: http://www.chrisherberte.com/blog/drupal-7-and-jquery-ui-accordion.

However, the height on the drop down fields is not being calculated correctly. Some are too long with lots of white space, others are too short meaning a scroll bar is added to view all the text. It appears to be taking all the heights of each field and using that to calculate an average height which it then applies.

I have tried the default Bartik theme, as well as my custom theme, functionality is the same on both so not a css issue, but a problem with the jquery itself.

On top of this, using HTML list elements stops it working all together, and messes up the formatting completely.

I do not have any idea where or how to edit the Jquery to fix this problem and certainly don't really want to be hacking core.

# Answer
First you should try to set autoHeight to false, this will fix the height problem.
You should aslo consider to use behaviors in Drupal.

```
<?php
drupal_add_library('system', 'ui.accordion');
drupal_add_js("
  (function ($) {
    Drupal.behaviors.accordionRoles = {
      attach: function (context, settings) {
        $('#accordion').accordion({
          autoHeight: false
         });
      }
    };
  }(jQuery));
", 'inline');
?>

```

Then I could find the problem regarding HTML lists, I grabbed your HTML, put it locally and used the demo source for jQuery UI accordion (the section 3 have some HTML list inside) and it seems to work fine.
> 3 votes

---
Tags: 7, javascript, navigation
---


# Question
Title: Can Profile2 present fields on registration?
I'm looking at using Profile2 on a D7 site, so that we can have private fields, and different fields per role.

Is it possible to have Profile2 present its fields on the user registration page? New users are going to default to a particular role, so the fields would be that of the default role.

I've looked at the introductory and documentation pages, but they are very sparse. All I could find for configuring Profile2 on a site where it's installed was simply specifying the per-role fields.

# Answer
I think there is a checkbox in the profile settings if it should be displayed in the user registration form. At Structure \> Profile types \> edit.
> 3 votes

---
Tags: 7, users
---


# Question
Title: Show the value of a node-form field inside an AJAX field added via hook_form_alter()
I have created a simple content type "reservation" with an integer field called "field\_km" with a default value of 50.
On the node creation form, I want to have a markup field showing the value of the "field\_km" field. So, I have created a simple module with the following code:

```
/**
 * @file
 * Drupal Module : myresa
 * Adds custom code specific to this Drupal 7 site.
 */

function myresa_form_reservation_node_form_alter(&$form, &$form_state, $form_id) {
  $form[‘box’] = array(
    ‘#type’ => ‘markup’,
    ‘#prefix’ => ‘’,
    ‘#suffix’ => ‘’,
    ‘#markup’ => ‘Price not computed',
  );

  $form[‘mybtn’] = array(
    ‘#type’ => ‘button’,
    ‘#id’ => ‘mybtn’,
    ‘#ajax’ => array(
      ‘callback’ => ‘myresa_callback’,
      ‘wrapper’ => ‘box’,
      ‘name’ => ‘mybtn1’,
    ),
    ‘#value’ => t(‘Compute the price’),
  );
}

function myresa_callback($form, $form_state) {
  $element = $form[‘box’] ;
  $element[‘#markup’] = «The price for » . $form_element[‘field_km’][‘#default_value’] . » km is 35 euros» ;
  return $element ;
}

```

The form shows the 'box' markup, the button, and when clicked the button activates the callback and shows the wanted text, but not the value of 'field\_km'. It is probably a simple syntax mistake, but it beats me.

# Answer
> 2 votes
```
function myresa_callback($form, $form_state) {
  $element = $form[‘box’] ;
  $element[‘#markup’] = «The price for » . $form_element

```

No wonder this doesn't work, where does `$form_element` come from? Also fields tend to be structured like `$form[field name][$node->language][columname]` (the latter being value in your case IMO)

# Answer
> 0 votes
I am not satisfied with your code, I am making changes according to my experience.

```
function myresa_form_reservation_node_form_alter(&$form, &$form_state, $form_id) {
 $form[‘box’] = array(
  ‘#prefix’ => ‘<div id="box-val">’,
  ‘#suffix’ => ‘</div>’,
  ‘#value’ => ‘Price not computed',
);

$form[‘mybtn’] = array(
  ‘#type’ => ‘button’,
  ‘#id’ => ‘mybtn’,
  ‘#ajax’ => array(
    ‘callback’ => ‘myresa_callback’,
    ‘wrapper’ => ‘box-val’,
    ‘name’ => ‘mybtn1’,
    ),
  ‘#value’ => t(‘Compute the price’),
  );
}

function myresa_callback($form, $form_state) {
  $element = $form[‘box’] ;
  $element[‘#value’] = "The price for" . $form_state['values']['field_km'] . " km is 35 euros" ;
  return $element ;
}

```

# Answer
> 0 votes
As I was going to say, I have found the answer thanks to you both.

The correct adressing of the field value in my case is :

```
$form_state['values']['field_km']['und']['0']['value']

```

Meaning that calling `$form['field_km']['und']['0']['value']` as suggested by CHX renders "Array" and `$form_state['values']['field_km']` as suggested by SHOAIB renders also "Array" !!! The Array result put me on the track, as I have printed the whole form render using a preprint function. I noticed that it was the first value after the declaration of the field, and that then it cascaded down to its value through the language 'und', then instance '0', and finally 'value'.

Hope it helps somebody out there in outer space ;-)) Thanks a lot to you both anyway -

---
Tags: forms, ajax
---


# Question
Title: Run Drupal in localhost then migrate to online once it's finalized
> **Possible Duplicate:**
> How to migrate from test environment to production environment?

I'm sure a lot of template designers work in localhost before going online. My question is **what's the best way to take your installation online once you're done playing around with it?** Do you redo everything or do you just copy your localhost db then import it online?

I'm using XAMPP in case it matters. :-)

# Answer
Since this is mostly likely a one time move (because the online version with likely be your master now) I wouldn't worry too much about perfecting the process. Just...

1. Dump the mySQL DB and place within the root.
2. Zip/Tar the codebase, including the files directory.
3. Move it to the server (via SCP or FTP), unzip/untar the whole thing.
4. Import the DB via: `mysql -hHOST -uUSER -pPASS DBNAME < db.mysql`
5. Bam!

For continual workflow I usually use:

* Backup & Migrate to create database backups.
* Git to move the code around (.gitignore your files directory)
> 4 votes

# Answer
For a first installation, just exporting/importing a database dump usually works fine. See Copying Drupal to a webhosting service for more details.

After that, it gets tricker, have a look at other questions like How to migrate from test environment to production environment?.
> 1 votes

---
Tags: 7
---


# Question
Title: Force redirect if a valid taxonomy term is not at the start of the URL?
As a follow on from this question I am trying to prepend all URLs on the site with a taxonomy term.

The term itself is handled by a custom module for the most part, however elements of the site such as the calendar modules page view don't allow for me to intervene and theme the link accordingly. If a user goes to the following URL:

* site.com/calendar

Then they should be redirected to:

* site.com/city/calendar

The city itself would be acquired from a cookie set when they hit the front page of the site, or defaults to 'all-cities'.

My vision for such a system was to check in hook\_boot against a predefined array for offending patterns (such as **calendar**) and if they are found, then it forces a redirect to the same page but prepends the city.

My gut feeling is that this is a bad approach and possibly un-Drupal. Please let me know if there is a standardized method I should be following for such things.

O’ Salvation, Deliver Me From Evil!

# Answer
I wouldn't recommend using such system because I also have the gut feeling that this would create some major confusion for modules relying on the drupal path system.

I think you should better deal with subdomains like `city.site.com`.
> 1 votes

---
Tags: 6, taxonomy-terms, redirection, uri
---