# Question
Title: How do I add default values to a database table using hook_install()?
I am creating a custom module with its own schema of a few tables. These tables need to have some values pre-populated into them for the module to work (default locations, select options, etc).

What's the best practices way to insert default values into these tables during hook\_install?

Since drupal\_write\_record is not available, I can use db\_query, but I just want to make sure that I'm not breaking any cardinal rules by doing so.

# Answer
The better way is to do it inside hook\_enable(); at the time the hook is invoked, the module is already installed, and the schema of its database is available to Drupal, and to `drupal_write_record()`. As the hook is invoked all times a module is enabled, and not just when the module is installed, the hook implementation should check if it didn't added those database rows already (e.g., it should use a Drupal variable containing a boolean value).

As example of module that uses `hook_enable()` for a similar purpose, you can check forum\_enable(), or php\_enable() (which adds the "PHP code" input format).

```
function php_enable() {
  $format_exists = (bool) db_query_range('SELECT 1 FROM {filter_format} WHERE name = :name', 0, 1, array(':name' => 'PHP code'))->fetchField();
  // Add a PHP code text format, if it does not exist. Do this only for the
  // first install (or if the format has been manually deleted) as there is no
  // reliable method to identify the format in an uninstall hook or in
  // subsequent clean installs.
  if (!$format_exists) {
    $php_format = array(
      'format' => 'php_code',
      'name' => 'PHP code',
      // 'Plain text' format is installed with a weight of 10 by default. Use a
      // higher weight here to ensure that this format will not be the default
      // format for anyone.
      'weight' => 11,
      'filters' => array(
        // Enable the PHP evaluator filter.
        'php_code' => array(
          'weight' => 0,
          'status' => 1,
        ),
      ),
    );
    $php_format = (object) $php_format;
    filter_format_save($php_format);

    drupal_set_message(t('A <a href="@php-code">PHP code</a> text format has been created.', array('@php-code' => url('admin/config/content/formats/' . $php_format->format))));
  }
}

```

As shown from those hook implementations, the code could necessarily need to be executed all times the hook is executed; it could also be the code needs to just executed once, as in the case the default values added to the database cannot be altered from the user, who doesn't have a user interface to alter/delete those values.
> 7 votes

# Answer
I'd go with `db_query` / `db_insert` (D6 / D7) in hook\_install().

It's not considered bad practice (and nobody is ever forcing you to use `drupal_write_record()`).

It is not uncommon for people to disable and re-enable modules, and in that case your code in `hook_enable()` would fire each time. which is not nice.
> 4 votes

---
Tags: database, installation
---


title: How to enable Gmap module in Drupal 7

text:
# Question
Title: How to enable Gmap module in Drupal 7
I just enabled the Gmap module in Drupal 7. You can see it in the picture below.

In Drupal 6, after the gmap is enabled, you can do the setting for any content type in **/admin/content/node-type/story** under **location information**.

But I don't see how to do it in Drupal 7.

I can't neither found it as a field type to add to content.

# Answer
> 1 votes
Gmap for drupal 7 is missing a js file. See http://drupal.org/node/1061444. The discussion may lead you to solution.

---
Tags: google-maps
---


# Question
Title: Load Multiple Arguments to a View with PHP Code
I have a view that I am setting up that will be the view used to select users from a user reference field. I want to build the view so that it only allows the user to reference users that are referenced by a node that this node is referring to.

To Illustrate:

**Node Type A** =\> References different users with separate user reference fields (not multi-value fields)

**Node Type B** =\> References **Node Type A**, AND *will only* reference users that are currently referenced in **Node Type A**

So I am trying to provide an array of default arguments using PHP in Views. Here's what I have so far:

```
$node = node_load(arg(1));

if($node) {
$users = array(
'am' => $node->field_am_reference[0]['uid'],
'realtor' => $node->field_realtor_reference[0]['uid'],
);
  foreach($users as $user) {
  return  $user;
   }

}
else {
return FALSE;
}

```

The **Node Type B** form is embedded into **Node Type A's** node view in the .tpl file, so I am loading Node Type A's nid from the url...this is working, but I am only getting the first user reference ('am') field to show up in the checkbox list that is used for the user reference options for Node Type B's embedded form.

# Answer
Okay...Here's the right way to do it. I was running into a problem with empty key values. I had to create the array out of the user reference fields I wanted, scrape any of the empty array keys

```
$node = node_load(arg(1));

if($node ) {
$user_args = array(
$node->uid,
$node->field_am_reference[0]['uid'],
$node->field_realtor_reference[0]['uid'],
$node->field_title_rep_reference[0]['uid']

);
//Remove empty array values and thier respective keys
  $clean_args = array_filter($user_args, 'strlen');

//Take all of the array values and put them into a single key
  $safe_args = implode(',' , $clean_args);

return $safe_args;
}

else  {

return FALSE;

}

```
> 0 votes

---
Tags: 6, views
---


# Question
Title: How to maintain and update a Drupal installation and its modules?
I'm looking for a comprehensive tutorial on best practices for updating and maintaining a Drupal installation and it's modules where there are multiple instances of the site, that is having a development instance and a live instance, and methodologies for updating the live site with changes made on the development site, and avoiding database conflicts.

TL;DR

1. Best practices for updating Drupal and it's modules to newer, more secure versions.
2. Best practices for mirroring changes made in a development instance of a site to the live instance of the site.

Note: I am using Mercurial to track changes.

# Answer
> 3 votes
I'm not sure about a guide but you will want to look into Features for change management between instances and Drush for updating Drupal and it's modules.

Anything you can't do for the database in features should be placed in an install file and applied as updates to maintain the db between instances.

---
Tags: 7, updating, deployment, maintenance-mode
---


# Question
Title: How do I add a custom image in a block (unique for every page)?
I have a block at the top of my site used for an image slider on the home page (using Nivo Slider), and I need to allow the users to add a custom image to fill that block space for any pages created (aside from home page). This image will be different per page. How can I do this?

I'm running Drupal 6

# Answer
> 2 votes
Figured it out. See this link for the answer.

---
Tags: blocks, media
---


# Question
Title: Dynamically link /sites/default/css/css_***.css file for WordPress template header
FYI, I don't know Drupal at all. What I've done is stick a WordPress install at /blog/ and pull in the /sites/default/css/css\_randomstring.css and static html from the Drupal page - and along with the WordPress loop in the index.php file of Wordpress - somewhat integrate WordPress into Drupal. (I don't want to use the Drupal WP module).

The problem is that the Drupal CSS link changes when there are small edits from time to time on the Drupal end. (The php/html of the Drupal site isn't slated to change.)

Question: are these randomstring CSS files a cache or the active CSS file? How can I dynamically pull in the sites/default/css/css\_(randomstring).css file when the string changes? Or is there a different CSS file I should be linking to?

# Answer
To answer your direct question, drupal's CSS and JS aggregation contains a random MD5 hash to guarantee uniqueness, and also to guarantee that there is no programmatic way to work this out.

In order to include CSS and JS from an aggregated site into another CMS there are a couple of options:

* Use un-aggregated CSS and JS and link to the files direct (bad)
* Compress the files yourself and host them in a known location - e.g. /css/main-compressed.css
* Or another option is what we have used in the past where you basically make a really simple page.tpl.php which includes basically no content, and is for all intensive purposes a blank wrapper for your site. You have your other CMS drag this template down after every deployment, and then used it for it's page wrapper. This way you do not need to worry about the CSS and JS changing as you always have the most up to date versions in the `<head>` section.

Hope this helps
> 2 votes

---
Tags: theming, css-js-aggregation
---


# Question
Title: Make a picture display images if a CCK checkbox is checked
I am creating a website in which, there is a view that displays content, and then several icons. theses icons tell the user weather something is available, for example, the icons on this site show you that there is no sound available to listen to, but there is a video to watch. the icons are as follows:

The "find it" and the video buttons are black, but the rest of the buttons are grayed out. (They are actually displaying two different images depending on weather or not there is something to link to.) The reason that they are grayed out is that there is nothing available for them to link to.

What I want is something very similar; I want several icons that will be either grayed out or black, depending on weather or not a checkbox in one of my CCK fields is checked.

How would I go about doing this? Can I do it with a view? Is there a script that I can use?

# Answer
> 3 votes
If you want to do it inside of your content, while not using a view, you can add some conditional php to a custom node template file...so if your content type is named "train", you can create a file named "node-train.tpl.php" and put it within your theme's folder.

In your node-train.tpl.php file, you can display the content of that node based on some cck value that is selected when you create a train node. Here's an example of the code:

```
<?php if($node->field_image_select[0]['value'] =='Image 1'):?>
//If the author selects the cck checkbox value of "Image1" display this.
<img src ="../path/to/image/image1.jpg />
<?php endif;?>

<?php if($node->field_image_select[0]['value'] =='Image 2'):?>
 //If the author selects the cck checkbox value of "Image1" display this.
<img src ="../path/to/image/image2.jpg />
<?php endif;?>

```

If you want to do this within a views display, you'll need to create a view that displays your train node only and set the display type to "node" (it defaults to display type "fields")...let's say you named the view "train\_summary", then within your theme's folder you would create a new file named "node-view-train\_summary.tpl.php" - You can use the code example from above in the file you just created and every time that type of view is displayed on your site, you'll see the output from that code.

# Answer
> 3 votes
You will have to rewrite the results of your fields. NodeOne has some videos that describes what to do and I think this one http://nodeone.se/blogg/learn-views-with-nodeone-part-17-rewriting-fields will have the info you need.

Short answer is that you will configure field \> Rewrite Results \> Rewrite the output of this field and then use the "REPLACEMENT PATTERNS" that will show **only the fields that are available** (can't use fields that come after in the list).

You can use \[field\_NAME\]\_icon.png where the \[field\_NAME\] will either be black or grey to load the correct icon. This would work if Black and Grey were the allowed values of a radio button for each field. Checkboxes should be similar, but I didn't need to use them for my issue.

---
Tags: 7, views, media
---


# Question
Title: How do I add attributes to CSS in theme.info?
I'm try to add a stylesheet switcher. This requires the following CSS files to be included on the site.

```
<link rel="stylesheet" type="text/css" href="styles1.css" title="styles1" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="styles2.css" title="styles2" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="styles3.css" title="styles3" media="screen" />

```

theme.info reference some CSS files. How can I a *rel* and *title* attributes?

```
stylesheets[all][] = common/css/small.css
stylesheets[all][] = common/css/medium.css
stylesheets[all][] = common/css/large.css

```

# Answer
> 0 votes
Since Drupal will use CSS aggregation (and doesn't have support for adding extra attributes via the info file or `drupal_add_css`), you will have to print out the style sheets yourself. This can be done with theme functions or by creating the markup in the `html.tpl.php`

---
Tags: theming
---


# Question
Title: Average value of Multiaxis FiveStar value
configuration Drupal 7.7, FiveStar 2.x-dev, References module, Unique field.

1. I have node value of Story tale
2. Every user can write an Review and rate each story tale with multiaxis fivestar like: Idea, Grammar, etc. configures as rating references.
3. Every user can create only one review per each story tale (unique field module).
4. Rating is available when User create a Review node (so not ajax).

I can attach average rate of each one from multiaxis like Average Grammar, Average Idea etc for story tale by views.

What I can't do is: how to compute average of all multiaxis values it menas create one number computed from rating of Grammar + Ideas.

I tried create a Fivestar field for overall (average value). Then I created Computed field which compute overall value of review.

```
$overall = ($entity->field_style[$entity->language][0]['rating'] + $entity->field_rate[$entity->language][0]['rating'])/2;
$entity_field[0]['value'] = $overall/10;
$entity->field_overall[$entity->language][0]['rating'] = $overall;

```

Well Problem is that In field\_overall is stored requested value, but VotingApi don't register this change created by computed field and it count 0 as stored value.

So. 1. Problem is that fivestar store this value before computed field compute overall rating 2. Or problem is, that fivestar is reading value not from `$entity->field_overall` but from other value.

# Answer
The easiest thing to do would be to set the value yourself with either hook\_entity\_insert/update or in a custom submit handler to the form.

The values are stored in the fields tables and not voting API when you use the five star with fields.
> 2 votes

---
Tags: views, rating
---


# Question
Title: Content profile bug - cannot edit user profile page
If the administrator user creates a profile node for a user, then that user cannot edit his own profile. How can I solve this problem? I have looked on the Content Profile module's issues, and found similar problems but no solutions for that.

In my case, that user created his profile node by himself, but I changed his username through phpmyadmin; now, his profile node results created by the admin user, not himself.

**Problem solved!** that profile node had php input format and that user whom i edited profile hadn't access for php input format filter.

# Answer
The Content Profile module associates a node with a user. If the administrative user adds a profile node, then it is authored by the administrator. Therefore, the user that the profile node was created for will not have access to edit the node since they are not the author. As an administrator, make sure to change the "Authored by" field to be the user whose profile the node belongs to, then the user will have the ability to edit it.
> 2 votes

---
Tags: users
---


title: How can I alter an existent CCK field?

text:
# Question
Title: How can I alter an existent CCK field?
I have a "first name" field, and I would like to programatically change its attributes. I want to modify this field, but not to create one new field again.

Is it possible?

# Answer
> 1 votes
In this resource http://drupal.org/node/726282 you will find a very useful description about CCK fields and his relation with the function to alter forms, called hook\_form\_alter(). in few words, you must also use an after\_build() function.

---
Tags: entities
---


title: User Login Block does nothing

text:
# Question
Title: User Login Block does nothing
The core user login block does not appear to work.

I have it placed in the Header region (Omega theme if that helps), with the following overrides:

```
function mytheme_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   return $hooks;
 }

```

This lets me use my own tpl file for the login block.

```
function mytheme_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

```

This lets me pass new variables..

Then in the tpl file:

```
<div id="user-login-block-container">
  <div id="user-login-block-form-fields">
    <?php print $name; ?>
    <?php print $pass; ?>
    <?php print $submit; ?>
  </div>
  <div class="links">
    <a href="/user/register">Create an Account</a> | <a href="/user/password">Forgot Password</a>
  </div>
</div>

```

Except when I login, the page refreshes, and nothing happens. User is not logged in, no error. When I use correct or incorrect credentials, nothing happens.

I used this same approach on a Drupal 6 site and it worked fine. Where am I going wrong?

I disabled Login Destination and Login Toboggan while debugging, no change.

# Answer
You should print hidden elements:

```
<div id="user-login-block-container">
  <div id="user-login-block-form-fields">
    <?php print $name; ?>
    <?php print $pass; ?>
    <?php print $submit; ?>
    <?php print $rendered; // HERE HIDDEN ELEMENTS ?>
  </div>
  <div class="links">
    <a href="/user/register">Create an Account</a> | <a href="/user/password">Forgot Password</a>
  </div>
</div>

```
> 2 votes

---
Tags: 7, forms, users
---


title: Drupal 7 and Image Style problems

text:
# Question
Title: Drupal 7 and Image Style problems
I have created several image styles in Drupal 7 (thumbnail, medium, large and xlarge). I also have created a script that imports data from a CSV-file, and copy images to the system.

The script seems to work fine and all images are attached to nodes correctly. Using Views I have created a block that shows nodes of a certain node type, and thumbnails attached to said node. Links to the images is OK in HTML.

Now the problem starts. Some images (thumbnails and large) get created, but some doesn't.

I can not find a reason why the images that doesn't get created should not be created. At first I thought maybe the image size was to big, but this isn't the case. Some images that gets created are bigger than ones that doesn't, and all images are bellow the systems 32 MB limit (from 3 to about 15 MB).

I have no idea where to start looking. All images copied during the import seems fine when opening on my system (OS X).

Can anyone point me to where I can get started at finding what the problem might be?

Thanks!

# Answer
As I commented on the question, this was a file permission problem..
> 3 votes

---
Tags: 7, media
---


# Question
Title: Drupal versus with Omni Update: Should I move from Drupal to Omni Update?
**Use Case**

* Current (aging) IT website built on Drupal 5.
* Most people hate this website because the theme is awful and adding content is painful.
* An upgrade to Drupal 6 and a theme / module updates are what are needed. (Not considering Drupal 7 until more modules are available.)
* Some of our leadership thinks we need to switch platforms anyway.

**Argument**

* What are the pros of sticking with Drupal versus switching to Omni Update?
* What are some pro Drupal buzzwords that nontechnical manager-folk will understand?
* What is your best argument for selling Drupal to a prospective client?

# Answer
I think you might have answered your own question: "it will turn into a LOT of work if they decide to switch to the proprietary platform". Work = time = money, and that is manager-speak.
> 1 votes

# Answer
> What are the pros of sticking with Drupal vs. switching to Omni Update?

There is a site called http://drupal.stackexchange.com, but there is no http://omniupdate.stackexchange.com. Just kidding of course, but still, there's some truth behind this - I bet that Drupal has better support than a proprietary platform.

Now we're waiting for Drupal 8; this means we have a lot of people with good knowledge about 6 who could perform the upgrade fine (maybe some reading is needed, but still). Show the managers the difference between "stock" Drupal 5 vs. 6 vs. 7. Try to show them some of the developments underway. Show them the big guys doing crazy stuff with Drupal; mention Acquia for example, show Gardens. Mention that Drupal is good enough for Ubuntu sites, for the Twitter dev site and so on.

If none of the above works, just mention that **it's waaaaaay cheaper to perform an upgrade** than to move to a proprietary software. Perhaps even if you have to pay for other guys to do the upgrade, because you will have to move content anyway and it's easier (= less workhours) with a Drupal upgrade.
> 0 votes

---
Tags: theming, updating
---


title: Get terms from node?

text:
# Question
Title: Get terms from node?
I need to get the terms a node has. I found out that you can use this:

```
$result = field_view_field('node', $node, 'field_tags', array('default'));

```

But this prints a rendered list. I need the names, or tids.

How do I separate them?

# Answer
with taxonomy\_node\_get\_terms() function (D6) you can get 'terms from node'. one example:

```
<?php
$terms = taxonomy_node_get_terms($node);// get term from nodes
rsort($terms); //rsort() just sort an array in reverse order
$myterm = $terms[0]->name; //get a value
echo $myterm; //show value
?>

```
> 3 votes

# Answer
Searching on api.drupal.org I see there is a `field_get_items('node', $node, 'field_tags');`that you could use.

You can also inspect the $node object and get the values directly from there. To inspect the `$node` object I recommend you install the devel module and then use the dpm or krumo function like:

```
krumo($node);

```
> 1 votes

# Answer
The structure of a taxonomy field in a node is similar to the following one:

The first array index is the identifier of the language associated with the taxonomy, or "und" (the value of the constant LANGUAGE\_NONE) if the taxonomy term doesn't have any associated language.
> 1 votes

# Answer
This is how I got it working:

```
$terms = taxonomy_node_get_terms($node);
$i = 0;

foreach ($terms as $term){

    $tid = $term->tid;

    $name = $term->name;

    // show the terms

    print $name.'<br>';

}

```
> 1 votes

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


# Question
Title: Call to undefined function node_load_multiple()
```
function my_module_getcategory() {
  $nodes = node_load_multiple(db_query('SELECT nid FROM {node}')->fetchCol());
  $data = array();

  foreach ($node as $nid) {
    print $nid;
    $data[$nid] = drupal_render(node_view($nid, 'full'));
  }

  $json = drupal_json_encode($data);
}

```

The above code give me the following error:

> Fatal error: Call to undefined function node\_load\_multiple() in C:\xampp\htdocs\new\_task\sites\all\modules\my\_module\my\_module.module on line 5

How can I fix this error? I verified the Node module is enabled.

# Answer
If you call `node_load_multiple()` from hook\_boot(), then the function is not found because at the time `hook_boot()` is invoked, only the modules implementing it are loaded. Once Drupal completes the bootstrap, all the enabled modules are loaded, and you can call every function implemented by those modules.

The same is true when you call `node_load_multiple()` from your own PHP file that doesn't bootstrap Drupal before to call any Drupal functions.

Suppose that you have a example.php file that is invoked as http://example.com/example.php; if the file doesn't contain the following code, then Drupal will not bootstrap, and every Drupal function is not available.

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

In other cases, you should not get the error you are getting. The only possibility is that the node.module file got corrupted when it was copied, but at that point I would expect something else to not work too; for example, if the content of node.module is corrupted, and `node_load_multiple()` is read as `ode_load_multiple()`, then you would get the same error when you are looking at a node page (e.g., http://example.com/node/1).

As side note, `hook_boot()` has been removed from Drupal 8; if you are using that hook in Drupal 7, you will need to change your code, since it would not work anymore with Drupal 8.
> 3 votes

---
Tags: nodes
---


# Question
Title: Extend Drupal 6 "form_token" & "form_build_id"
I'm posting in my website by using command line.

Below codes works just fine for me

```
curl -b cookies.txt -d title="$(my-own-sed-command)" -d taxonomy%5Btags%5D%5B1%5D="$(my-own-sed-command)" -d teaser_include=1 -d body="$(my-own-sed-command)" -d field_source%5B0%5D%5Burl%5D="$(my-own-sed-command)" -d changed= -d form_build_id=form-2bef00e4e4c6c53c1cedfc61e857186b -d form_token=883b4e7f69cdd1bf3311854732eff3f7 -d form_id=post_node_form -d op=Save http://www.mywebsite.com/node/add/post

```

Usually I will post several times a day using above command. But the problem is; sometime I will take a rest for 2 or 3 days. After 2 or 3 days, the "form\_token" & "form\_build\_id" has expired.

In order to prevent expiration, how to extend the "form\_token" and "form\_build\_id" to become 7 days?

Any ways are welcome; hacking the core, disable token for this node type submission, etc.

# Answer
> 4 votes
**TL;DR**: Those values will not expire if

* you use the same user to log in to the site
* the PHP session is not expired
* Drupal finds in its cache the form array associated with "form\_build\_id."

The token used for "form\_token" is the one created using with the following function call: `drupal_get_token($form['#token'])`; the only value that changes in that function call, for the same form, is `session_id()` which is invoked from `drupal_get_token()`.

```
function drupal_get_token($value = '') {
  $private_key = drupal_get_private_key();
  return md5(session_id() . $value . $private_key);
}

```

The value returned from `drupal_get_private_key()` is unique for each Drupal site; the only way to make it change is to delete the Drupal variable "drupal\_private\_key" that is never deleted (if there isn't a third-party module that delete it), but it is initialized when Drupal is installed. The value returned by `session_id()` is the same each time `drupal_get_token()` is called, if the logged in user is the same, and the PHP session has not yet expired.

As for the value of "form\_build\_id," its value is totally random, initialized from drupal\_prepare\_form() using the following code:

```
  if (isset($form['#build_id'])) {
    $form['form_build_id'] = array(
      '#type' => 'hidden',
      '#value' => $form['#build_id'],
      '#id' => $form['#build_id'],
      '#name' => 'form_build_id',
    );
  }

```

`$form['#build_id']` is initialized from the following code in drupal\_get\_form():

```
  $form_build_id = 'form-' . md5(uniqid(mt_rand(), TRUE));
  $form['#build_id'] = $form_build_id;

```

As you are passing the value of "form\_build\_id," and "form\_id" in the POST data, then the following code is executed (see drupal\_get\_form()):

```
if (isset($_POST['form_id']) && $_POST['form_id'] == $form_id && !empty($_POST['form_build_id'])) {
  $form = form_get_cache($_POST['form_build_id'], $form_state);
}

```

If the cache contains the form, then "form\_build\_id" is not generated again.

---
Tags: tokens, forms
---


title: 3 calendars views

text:
# Question
Title: 3 calendars views
I'm just starting to learn Views and there is quite a lot for me to study, so I have to ask you. I am working on D7.7.x, using Calendar and Views modules.

What I want to create is this: I have an event that will be happening in 3 different cites during the period of one month but during different dates. Each city has a list of events generated as separate nodes for different days. I need only one month and it should be shown permanently - even during the month of August I should see the month of December with particular days linking to agendas. And there are 3 such calendars with the same month but different days active - the user can switch the city and the calendar will change.

What would be the easiest way to do this? Maybe even not with Calendar module?

# Answer
To learn more about Views check out these tutorials http://nodeone.se/blogg/learn-views-screencast-series-summed-up.

If you just have a new content type (Event) (that has a date field) you can Filter Criteria by Content: Type (= Event), and Sort Criteria by Event Date Descending. You can add a Display of Type Block, Pane, etc to suit your needs then. The calendar is possible, but I would advise you to get just a basic view working before trying to integrate the Calendar Mod with it.

There are numerous different options that are available and the best thing would be to watch the tutorials. Each lesson is ~10 minutes long, but cover one thing really well.
> 2 votes

# Answer
Your requirements can be met using Views itself. Views is one of the most powerful parts of Drupal and once mastered so much can be achieved. So time spent here is very worthy indeed.
> 0 votes

---
Tags: views, datetime
---


# Question
Title: Why did the Apache directive to handle a clean URL get changed?
I noticed that the clean URLs implementation has gotten more complicated in Drupal 7. Rather than `RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]` used in Drupal 6, Drupal 7 .htaccess has simply `RewriteRule ^ index.php [L]`, with a comment that says "Clean URLs are handled in `drupal_environment_initialize()`".

I read through `drupal_environment_initialize()` and understand that it's using `REQUEST_URI` to manually set `$_GET['q']`, but why the change? I see the comment:

```
// When clean URLs are enabled, emulate ?q=foo/bar using REQUEST_URI. It is
// not possible to append the query string using mod_rewrite without the B
// flag (this was added in Apache 2.2.8), because mod_rewrite unescapes the
// path before passing it on to PHP. This is a problem when the path contains
// e.g. "&" or "%" that have special meanings in URLs and must be encoded.
$_GET['q'] = request_path();

```

I've got some idea what this is saying, but can anyone explain in fuller terms the reasons behind the change? If it wasn't done this way before, was something (minorly or seriously) broken in Drupal 6 and prior?

# Answer
> 4 votes
There was something seriously broken, but it only affected a handful of cases due to fringe nature of the issue. Essentially, what happens is roughly (`%26` == `&`):

```
Request: /lost%26found
Rewrite: /index.php?q=lost&found

```

The issue here is obvious when you see it this way: you end up with two `$_GET` variables, `q = 'lost'` and `found` which isn't set properly. Since the `q` variable is truncated, you end up with the wrong page or a 404 error.

Drupal 7 fixes this by simply redirecting to index.php and then parsing the original query string manually itself, bypassing Apache and PHP's parsing of it entirely.

# Answer
> 3 votes
Using the rewriting rule used in Drupal 6 there would be a problem when the path contains escaped *&* or *%* that are changed back to respectively *&* and *%* from the "mod\_rewrite" Apache module. The solution would be using the following rewriting rule, but it would require Apache 2.2.8 or higher, when Drupal 7 is compatible with any Apache 2.x versions.

```
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA,B]

```

Between being compatible only with Apache 2.2.8 and higher, or being compatible with all the Apache 2.x versions, they preferred to the compatible with all the Apache 2.x versions.

To understand why unescaping *&* and *%* is a problem, suppose a third-party module is able to handle a path such as `title/12&id=13`; the path would be changed to `index.php?q=title/12&id=13` instead of `index.php?q=title/12%26id=13`. The effect is that the module would get `title/12` as path, instead of `title/12&id=13`.

---
Tags: .htaccess
---


# Question
Title: Do I have to unistall the disabled modules?
I'd like to know if there is any difference between disable or uninstall modules regarding performance.

Will having 10 disabled modules affect my site performance? Will the performance be better if I uninstall them?

# Answer
Disabled modules do not get executed so they should not affect performance but they may have variables and database tables that still exist. If you are not planning on using those modules again it is highly recommended to use the uninstall process at admin/build/modules/uninstall in D6 or admin/modules/uninstall in D7.
> 6 votes

# Answer
There is a difference between disabled modules and uninstalled modules; you could disable a module when you don't temporary use it, but you uninstall a module that you don't plan anymore to use.

For example, you can disable the Views UI module that comes with the Views module because you have already created the views you need, or you don't want that other users with the privilege of editing views are able to edit them.

About the performance, that has been already replied in Do non-enabled modules affect performance?
> 1 votes

# Answer
unistall modules is necessary when modules are using database/system operations and information that need be removed. A module without an uninstaller may leave tables or fields in your database. I think that, acording each module, the effect can give more performance or none, or problems. One example, some modules add colums to tables, like nodes tables, so I guess that if you do not remove these columns, then the node table will have innecessary information that will be parsed, so this represent innecessary consumption of resources.

here http://drupal.org/node/250783 you will find a 'howto' about how unistall modules, but you will find (a little) information about advantages of unistall operation.

this is one example of a module that add a column to the node table, drupal.org/project/quickstats so I guess that if you do not unistall the module, this will represent innecessary consumption (maybe minimal?) of resources to other modules (and/or to the system) when pull node information.
> 0 votes

---
Tags: 7, performance
---


# Question
Title: Add a MAX aggregation function to a query
I'm building a query with `$query = new db_select('node', 'n')` and I'm grouping by a certain field (let's say `$query->groupBy('title')`), when I'm aggregate another field (such as `$query->addField('n', 'MAX(nid)')`) it gets sanitized into a field called `n.MAXnid` (which crashes with a warning when executed)

How can I add a `n.MAX(nid)` field to my select query?

# Answer
In Drupal 7 you should add expression for this.
Read more on Dynamic queries \> Expressions
> 3 votes

# Answer
In your case, the code should be something similar to the following one:

```
$query = db_select('node', 'n')->groupBy('title');
$query->addExpression('MAX(nid)', 'max_nid');

```

You don't use `$query = new db_select('node', 'n')`; db\_select() already returns an object. If you want to clone that object, you should not invoke `new` on it.

$query-\>addExpression() returns the alias currently used for the expression you add; it is normally the same alias passed to the method, but it can be different if the alias is already used. In this case, the alias is max\_nid if max\_nid is not already used, or max\_nid\_N if the alias is already used; N is an integer that is added to make the alias unique.
Using the alias returned from `$query->addExpression()` is important when a function is altering a query passed from other functions, such as in the case of a query passed to a hook. In this specific case it is not necessary, as the function that is calling `db_select()` is also adding the expression.
> 11 votes

---
Tags: 7, database
---


# Question
Title: What is the value returned by theme_get_registry, and why is it not NULL?
I was going through Drupal code, and in the theme.inc file I found something that I couldn't understand. On `theme()`, I see the following code:

```
if (!isset($hooks)) {
  init_theme();
  $hooks = theme_get_registry();
}

```

`theme_get_registry()` is defined as follows:

```
function theme_get_registry($registry = NULL) {

  static $theme_registry = NULL;
  if (isset($registry)) {
    $theme_registry = $registry;
  }
  return $theme_registry;
}

```

I found the function is calling without any parameter, and the default parameter is `NULL`, but when I use `print_r($registry)` in the first line of the function `theme_get_registry()`, I get the values popped out; I assume the value should be `NULL` because it is not passing any value, and default value is `NULL`, from where `$registry` got values in the first line.

# Answer
> 1 votes
The value returned from `theme_get_registry()` is initialized by \_theme\_set\_registry(), which is called by \_theme\_load\_registry(), which is called by \_init\_theme(), called by init\_theme().

```
function _theme_set_registry($registry) {
  // Pass through for setting of static variable.
  return theme_get_registry($registry);
}

```

`init_theme()` is called from theme(), right before calling `theme_get_registry()`.

```
  $args = func_get_args();
  $hook = array_shift($args);

  static $hooks = NULL;
  if (!isset($hooks)) {
    init_theme();
    $hooks = theme_get_registry();
  }

```

The value used by `theme_get_registry()` (`$theme_registry`) is a static value; this means that the value `theme_get_registry()` gets from `_theme_set_registry()` is then returned all the times `theme_get_registry()` is called. `NULL` is the default value for `$theme_registry`, until `$theme_registry = $registry` is executed, and the calling function uses a value different from the default one.

To notice that the declaration of a static variable is different from the declaration of other local variables used by a function.

If I declare a variable as `static $registry = NULL` it doesn't mean the variable is always set to `NULL`. The constant value used in the declaration is the value assigned to the variable when it is initialized; the second time the function is called, its static variables are not initialized anymore, but they retain the value they had in the previous call of the function. As reported in Variable scope:

```
function test() {
  $a = 0;
  echo $a;
  $a++;
}

```

> This function is quite useless since every time it is called it sets $a to 0 and prints 0. The `$a++` which increments the variable serves no purpose since as soon as the function exits the `$a` variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

```
function test() {
  static $a = 0;
  echo $a;
  $a++;
}

```

> Now, `$a` is initialized only in first call of function and every time the `test()` function is called it will print the value of `$a` and increment it.

---
Tags: theming
---


# Question
Title: How to play a video via drupal video ftp?
I've installed the Video module (Drupal 6.2), and everything works fine. I also enabled the uploading of the video via FTP. I edited the video content type with the FTP CCK field. The FTP field uploaded file is listed in the drop-down, and as I select it provides a file link to it. I need it to be displayed in a video player.

In other words, the video file is linked as an HTTP link, and it is not being played using the video player.

Do you have any suggestions?

# Answer
> 4 votes
You just need a player frontend for the CCK field in question to display the video. This is actually quite easy.

You'll first need a video player frontend of some sort. I would recommend the VideoJS module ,personally, but I'm sure there are others worth looking into as well.

On your video content type, go over to Display, and change the display widget of that cck field to a video player frontend of your choice after enabling the video module.

# Answer
> 0 votes
CCK fields offer a way to show his content. If you `edit your content type`, you will see a tab called `'Display fields'`. In your CCK video field you will see `dropdown menus` to control how to show the video in Teaser and Full node modes. Then make test with the different display modes to your CCK field (I guess that, to this place, your module has included an option to show your video in a player video).

Also, sometimes the modules needs to locate the video player files in specific directories. so the video player will not call the video, if the player are misconfigured or not well located.

---
Tags: 7, files
---


title: How to use HTML tags in email?

text:
# Question
Title: How to use HTML tags in email?
I have a triggered rule, when a content is Published the author receives email. I want to show my logo in the email but so far I could not find how to do that. Any help appreciated?

I wrote this in email message body, but instead of an image, I see only HTML text.

```
<img src="http://www.vragenenislam.com/misc/logomuz.png" alt="Vragen en Islam" />

```

# Answer
Check out Mime Mail; that should do the trick.

> This is a Mime Mail component module (for use by other modules).
>
> * It permits users to recieve HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
> * If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment.
> * Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format
> * If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative.
> * Allows you to theme messages with a specific mailkey.
> * Converts CSS styles into inline style attributes.
> * Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.
> 2 votes

# Answer
Mimemail module use mimemail-message.tpl.php template file to format email messages. so you can control the html and CSS form this place. If you want to send a logo, you can include the html of your logo in your version of mimemail-message.tpl.php.

here is a documentation about how to theming HTML Mail sent through Mime Mail: http://drupal.org/node/958146, follow this guide to create your own template to insert your logo, but in few words you can use a copy of mimemail-message.tpl.php file (located in modules/mimemail/theme directory) into your default theme's folder, and change your html, adding your logo in the body of the template, inside the `<div id="main">`

```
...
      <div id="main">
      <img src="http://www.vragenenislam.com/misc/logomuz.png" alt="Vragen en Islam" />
        <?php print $body ?>
      </div>
...

```

Also you can add the html that you want, according recommendations located in documentation.
> 1 votes

---
Tags: emails, theming
---


# Question
Title: l() is printing "http://node/16" when gets "/node/16" as argument
This site was copied to a new domain when it started breaking. Is there some setting somewhere I need to update, so it knows how to build working URLs again?

# Answer
Pass *node/16*, instead of */node/16*.

The API reference for l() tells you that the `$path` argument is passed to the url() function. `url()` considers "/node/16" as a full URL (although the term "full URL" is not formally defined).
> 10 votes

---
Tags: 6, uri
---


# Question
Title: Full HTML Formatter / WYSIWYG Not Working In Views 3?
I have a Drupal 7 site that I've been plugging away at for the last few weeks, and I noticed that when I'm in Views and am trying to add a Global Text Area to the footer of my view (for a "Read More" link that goes to a custom page), the WYSIWYG formatter does not show up at all. The dropdown to pick formats appears, but none of them initiate TinyMCE.

The strange thing is that the Input Formats are configured just fine for the rest of the site and proper user roles. It works across all of the content types I have set up. So, my question is, how can I get this working so that I can put a link in the footer?

For sake of explaining things better, here's a screenshot. Note that this problem is only happening in Views.

# Answer
> 2 votes
I believe it's a lazy-load editor problem. The WYSIWYG libraries aren't being loaded on the parent page, so they are not available to the modal window. If you're using the WYSIWYG module with CKEditor, something like this should alleviate your issue.

```
<?php
  // Views support.
  if (module_exists('views') && $form_id == 'views_ui_edi') {
    // Load potential editor.
    foreach (filter_formats() as $format => $object) {
      if ($profile = wysiwyg_get_profile($format)) {
        wysiwyg_load_editor($profile);
        wysiwyg_add_plugin_settings($profile);
        wysiwyg_add_editor_settings($profile, 'advanced');
      }
    }
  }
?>

```

from http://drupal.org/node/356480#comment-1190907

and the patch located in -

http://drupal.org/node/356480#comment-4256204

---
Tags: 7, views, input-formats
---


title: Add JavaScript code to the backend

text:
# Question
Title: Add JavaScript code to the backend
I want to run some JavaScript code during the document ready phase.

Where can I place this code so that it runs each time a page is loaded?
I am using Drupal 7.

# Answer
The easiest solution would be to add the code in your theme. This is done by adding

```
scripts[] = path/to/file.js

```

in your theme's `.info` file. If for any reason don't want to handle this in your theme, you could instead add the javascript from within a module, using `hook_init`

```
function module_name_init() {
  drupal_add_js(drupal_get_path('module', 'module_name') . '/path/to/file.js');
}

```

For the javascript to execute on document ready, you can either use jQuery's ready event, or use a behavior.

This could look like this:

```
(function ($) {
  $(document).ready(function() {
    // jQuery's document ready event
  });
})(jQuery);

(function ($) {
  Drupal.behaviors.name = {
    attach: function(context, settings) {
      // Drupal's behavior execute on document ready.
    }
  };
})(jQuery);

```
> 5 votes

# Answer
You have to define it inside your theme; for a more in depth explanation see Managing JavaScript in Drupal 7, and use something like this inside your JavaScript file:

```
(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };
}(jQuery));

```

You can also do it from your module.
> 3 votes

---
Tags: javascript
---


# Question
Title: Image / ImageField / ImageCache (automatic thumbnails)
I'm getting pretty frustrated here:

I'm a complete newbie with Drupal, just installed some modules like CCK, and made a new Content Type for my website to display products (no webshop purpose, just displaying them). It also has an image field, for the user to upload an image, but what I'm trying to do here is have a thumbnail somehow automatically created (to display in the overview).

It seems like such a simple thing which every CMS should be able to do easily (and I'm sure it's possible) but I just don't know how it's done.

After googling quite a while I found a lot of articles on the subject however they all seem to refer to modules such as ImageCache, ImageField, and after some research about the mentioned modules it seems to me they have somehow been merged into one module: Image in Drupal 7.7

This is driving me crazy, and I would very much like to hear a simple explanation on how to get to the desired result.

# Answer
> 1 votes
Here is a tutorial that will walk you through adding images.

http://www.youtube.com/watch?v=l0I5f9YmmI0

# Answer
> 0 votes
To Drupal 6 here is a tutorial using CCK, Imagefield, Imagecache, Lightbox2 ad Views Modules. When you have installed these modules, follow the tutorial (there are few steps).

Here is another tutorial with more detail.

---
Tags: 7, media, nodes
---


title: Why does my module only list 10 nodes?

text:
# Question
Title: Why does my module only list 10 nodes?
I've been creating my very first module and have got some help here earlier. Now the issue is this: my module only list a maximum of ten (10) nodes.

The module is like a taxonomy term list, which shows nodes with a certain term. Althoug I have hundreds of nodes, and they each have the correct term, no term page shows more then 10 nodes.

If one node is removed, another one gets listed, so the error is somewhere else - but where?

Shortned down code:

```
function my_module_cmp($a, $b) {
  $a = (array) $a;
  $b = (array) $b;

  return strcmp($a['name'], $b['name']);
}

$term = taxonomy_term_load($tid);
$name = taxonomy_term_title($term);

drupal_set_title($name);

$terms = taxonomy_get_tree(10,0,1);

usort($terms, "my_module_cmp");

$counter = 0;
$result = taxonomy_select_nodes($tid);

foreach($result as $nid) {
  $node = node_load($nid);
  $alias = drupal_get_path_alias("node/$nid");
  $form['company_wrapper'][$nid]['title'] = array (
    '#markup' => '<div class="title"><a href="' . base_path() . $alias.'">' . $node->title . '</a></div>',
  );

  $counter++;
}

```

# Answer
> 2 votes
as far as i can see, if `$limit == FALSE`, `taxonomy_select_nodes()` just extends the `PagerDefault`, this class uses a limit of 10 unless otherwise specified, try changing your code so paging is disabled:

```
$result = taxonomy_select_nodes($tid, FALSE);

```

# Answer
> 3 votes
The taxonomy\_select\_nodes() function has as default limit of unlimited, so if it's only returning 10 nodes, I would suspect that's all the nodes it was able to match against the provided taxonomy terms.

Note that this function will not return any unpublished nodes, nor return any nodes you do not have access to because of any node-access controlling modules.

Also note that `taxonomy_select_nodes()` *only* returns nodes that match $tid only - and not any of that term's children which might be what you are expecting.

---
Tags: 7, nodes
---


# Question
Title: How can I redirect the users after confirmation basing on the roles they have?
I have two type of users, and I have created two types of registration forms for each role. I want to redirect the users to different pages, once they get the email confirmation according to their roles.

For example:

* user1, with the first role, must be redirected to page1
* user2, with the second role, must be redirected to page2

I think I can achieve this feature using the Rules module, but I don't know how to do it.

Can you tell me how can I implement it?

# Answer
yes, with Rules!

1. create a new rule.
2. select event: user has logged in (or if you use LoginTobogan module you can use the event "When the user account is validated".)
3. select condition: User has role(s), and assign the role (I recommend create a new Role and assign this role to a test user)
4. selet the action: Page redirect, and add the url to the destination (I have selected `'Immediately issue the page redirect'` to see the redirection (if is not select this, I can not see working the redirection, but test if you does not need this. Please review the warning about the setting)
5. enable your rule and test.
> 4 votes

# Answer
You might be able to use something like the Login Destination module to achieve what you want. If not, there might be a solution in using the Trigger and Rules modules.
> 1 votes

---
Tags: users, rules
---


# Question
Title: Set the allowed options of a selectlist CCK field?
I have some CCK select list fields which I do not define allowed values for.

I need to set the options available using information available to me when the form is being loaded.

I tried setting the values in the node-form.tpl file but I get:

"An illegal choice has been detected. Please contact the site administrator."

for each field I set the allowed values for in this way.

What's the proper way to do this?

# Answer
check this resource http://drupal.org/node/726282 you will find a very useful description about CCK fields when form is loaded, and his relation with the function to alter forms, called `hook_form_alter()`. In few words, you must also use an `after_build()` function.
> 1 votes

---
Tags: entities
---


# Question
Title: Taxonomy in Contextual filters for Views
I am new to drupal and currently I am exploring the Views module. I have a dummy website for a toy shop to learn on. I have created taxonomy as follows where "Category," "Ages," and "Brand" are vocabularies, and the rest are taxonomy terms :

* Category: Activity Centers, Electronics, …
* Ages: 0-2, 2-4, …
* Brand: FisherPrice, V-Tech, …

I want to create a view that displays all toys, depending on what has been passed in the contextual filters; for example, if the first argument is a term from the "Brand" vocabulary, the second argument is a "V-Tech" term, then toys belonging to these should get displayed with a URL such as http://example.com/Brand/V-Tech.

I selected "Content: Has taxonomy term ID" in the contextual filter, but I don't understand the next screen. I selected the 'Specify validation criteria' checkbox. There should not be a vocabulary option in the validator drop-down? Can anyone help me from here on?

# Answer
> 7 votes
I cloned the existing default view for *taxonomy/term/%*, removed all the contextual filter already existing, and then:

* I added a new relationship, "Content: Taxonomy terms on node."
* I added a new context filter, "Taxonomy vocabulary: Machine name," for which I didn't change any setting. (The Views module already selected the relationship I defined before.)
* I added a new context filter, "Taxonomy term: Term ID."

For the "Taxonomy term: Term ID" filter I used the following settings.

I changed the path for the view to "test-term/%" and removed the feed.

The setting page for the view, once done the changes I described, appears as in the following screenshot; I highlighted the parts that are different from the setting page for the view I cloned.

What I obtained is a view that shows the nodes containing the terms from the vocabulary for which I pass the machine name as first argument.

For http://tero.local/dr71/test-term/tags ("tags" is the machine name for a vocabulary I defined in my test site), I get the following result.

For http://tero.local/dr71/test-term/tags/tags (the second "tags" string is the name of a taxonomy term that the "tags" vocabulary has), I get the following.

I didn't find any way to filter out the duplicates that appear in the first case, though. This is would happen only for those vocabulary that allows the users to select more than one term per node.

The relationship with the taxonomy terms is necessary as the view is about nodes; without the relationship, it would not be possible to use "Taxonomy vocabulary: Machine name," and "Taxonomy term: Term ID" as contextual filters. You can check it: If you remove that relationship, you will not able to add them as contextual filters.

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


# Question
Title: Need to use taxonomy term as url argument to filter a view but the term is attached to a node ref field
Not sure if the title makes much sense so I'll try to explain what I'm trying to do a little more in detail.

I am building a scoreboard section of my site for high school football scores from around the state. My "score" node has two node reference fields, "home team" and "away team" that point to a "team" node. The "team" node has some taxonomy terms, namely "county" and "conference."

I am trying to build a view that lists all of the "score" nodes for the week. The main scoreboard is working, no problem. But I'd also like to be able to have links like "http://example.com/scoreboard/county-name" and "http://example.com/scoreboard/conference-name" that would just show the scores for the schools in the respective county or conference.

The following is a screenshot of how my relationships, arguments, and fields are set up.

The following is a screenshot of how the view displays on the "/scoreboard" page.

But, if I try to go to "http://example.com/scoreboard/hamilton" I get a blank page. Am I missing something simple here? It seems like it should be possible but I'm not getting it.

# Answer
> 0 votes
Configure the *Taxonomy: Term* argument to use one of the relationships that you have set up. I do not know why you have an additional *Node: Nid* argument. According to your description, it is not necessary. Remove it unless you have some other requirement that makes this argument necessary.

Setting up the view in a way that does not match the requirements should not result in a blank page. The usual techniques for debugging PHP applications can be applied to figure out what went wrong: Printing out variable values or (if you have Xdebug or the like installed) step-by-step execution.

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


# Question
Title: Drupal views get field info from node within another field
I'm attempting to create a view which will show Photo Galleries that have a reference to a project. The project has a reference to a category. It is on the category page I want to show these galleries.

So I am on the category page, and would like to show the latest galleries posted within the projects in this category.

When creating the view for photo galleries I can display the project field, so I know what project they are in. However the category field is within the project node, so how can I find out what category the project has referenced?

I need to look at the node referenced in the project field, then take the category field from that to determine if it is associated to the current category. Is this possible within the fields module or should I look at something else?

Hopefully this question makes sense, if not please ask questions or edit the question. Thanks!

Edit: This is using Drupal 7 and I assume views 3.

# Answer
I assume that you are using the References module to provide a Node Reference field to Photo Gallery nodes which reference Projects, and then provide another Node Reference field, or Term Reference field to Project nodes which reference Categories?

In Views:

1. Expand the **Advanced** column
2. Add a **Relationship**
3. In the **Add Relationships** dialog, select the Photo Gallery: Project Node Reference field from the list
4. In the **Configure Relationship** dialog, Click **Apply**
5. Add another **Relationship**
6. This time in the **Add Relationships** dialog, select the Project: Category Node/Term Reference field from the list.
7. In the **Configure Relationship** dialog, there is a field labelled **Relationship** with a drop-down menu, which lets you choose other compatible relationships you've added previously, from which you should select the **Photo Gallery: Project** relationship (I'm not entirely certain what text to expect here). Then click **Apply**.
8. Now when you add new **Fields** to the View, you'll have the option to select a **Relationship** for each individual field, which allows you to pull data from the entity (Node/Term) that is referenced by the selected **Relationship**
> 2 votes

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


# Question
Title: How can I form a Views query that retrieves all nodes that are referenced by a node in another content type?
I have a content type of Artist. I also have a content type of Release. The Artist content type has a node reference field that points to the Release content type. This node reference field allows an Artist to have 1 or more Releases.

I created a view that displays fields from the Artist content type as a page. Let's call this view "Artist Page." Artist Page has a single argument of `Node: Title` and a path of `artist/%`. This works really well.

I would like to add another view for a block of Releases belonging to a particular Artist. I hope to display this block in the sidebar for Artist Page.

How can I form a Views query that retrieves all Releases that are referenced by an Artist?

(I am making my first non-trivial Drupal 6 site and I appreciate your patience. I am happy to RTFM but please tell me where to go!)

# Answer
Ok, So the way to do this is with arguments and relationships.

Normally using the "Provide default argument" option would work but since you're not using the actual "artist" node you can't actually get the node id from the URL.

Also just an FYI, passing the title for a views argument is a bad idea because then the query is doing a lookup based on text instead of a numeric value such as the node id which is better on performance.

But anyways the solution to your problem is add the same argument to your block view as you did to your "artist" page view. This should be the node title argument. Now add a relation to your view. The relationship you want to add is the content: \[name of node reference field\] relationship.

Now you can add what ever fields to your view that you would want to include from the "release" content type but now you will see you get a relationship option in the field option. When you want to display fields from the "release" content type just be sure to select the \[node reference\] relationship.

Also we need to do one more thing. Which is getting the proper argument to be picked up by your block view. This is a bit trickier mainly because of what I mention earlier which is that you're passing the node title as an argument. So now you can edit your Node: Title argument and you should see the "option to take if the argument is not present" select the "provide default argument" and select the php code option. In there you want to paste this piece of code.

```
return arg(1);

```

Now save your view and place that block on the page and visit the artist/% page and you should now see what ever fields you want to use. This php code is telling your block view to pick up the artist/% argument from the url.

A couple of things to lookout for:

* php code in the views is bad, I just mentioned that here as a quick fix to your problem.
* When using relationship be sure to select the relationship option only when you want to display a field from the "related" item. In other works if you want to display the title of the related node select node title and be sure the relationship is selected. If you want to display the title of the node being passed in on the argument select node title just don't select any relationship.

Hope this is helpful, is a long post but relationships can be confusing.

Hope this helps.
> 2 votes

# Answer
Add an argument for the node reference, and choose "Provide default argument", setting that to "Node ID from URL".
> 0 votes

# Answer
> The Artist content type has a node reference field that points to the Release content type.

That way, every time a new Release is created, an Artist must be edited. If you instead give the Release content type a node reference to the Artist content type, a Release can be created without editing an Artist.

In that case the view would have the node reference field for the artist as a relationship and a node nid argument that uses this relationship.

As ericduran explained in his answer, use a default argument to circumvent the limitation that block displays do not automatically receive arguments from the URL.
> 0 votes

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


title: How to migrate from MySQL to PostgreSQL

text:
# Question
Title: How to migrate from MySQL to PostgreSQL
I need to know how to migrate my Drupal 6 database from MySQL to PostgreSQL. I also like to hear first hand experience tales about actual migrations.

P.S. I found this drupal-mysql2pgsql.pl migration script which apparently does the job but I could not make use of it due to the fact that I dont' know how to make " passwordless account in both databases". There is also this guide (in Thai) which adds credentials to database connection lines in the script. But it did not help either, as I could not connect to Postgresql. I know very little about Postgresql and may have had some silly mistake. Any through explanation/tutorial on this would be much appreciated.

# Answer
Module DBTNG Migrator will do it.
> 5 votes

# Answer
If you're using Drupal 7, there's a sandbox project called Portable Databse Dump that purports to allow you to dump a Drupal site from one database backend to another.
> 3 votes

# Answer
I have an experience with both postgres and mysql sites under high load, and I don't think migration can be done for performance reasons. Both engines are good, and final success depends on ability of your DB admins to tune up DB installation for specific site. Another point: to boost performance, you choose tools to minimize need in DB queries (boost/memcache/varnish), so you end up with relatively low weight of DB processing.
> 3 votes

# Answer
Check all of the modules that you use or ever may want to use on your site. Not all contrib modules are database agnostic. I can't think of any off the top of my head, but I have run into modules that use MySQL-only functions.
> 1 votes

---
Tags: 6, migrations, database
---


# Question
Title: How do I explain the large difference between page execution time and reasonable query execution time?
I believe that one of my websites is running rather slowly. I have done nothing different than I have on other Drupal websites that I have done that are running on different servers and that are running much faster.

Would this "slowness" be somehow described by the fact that the page takes 4 times longer to load than it does to actually execute the SQL queries?

> Page execution time was 2251.03 ms. Executed 342 queries in 477.02 milliseconds.

If you see above, you can see that it takes more than 4 times longer to execute the page than it does to actually get the data it needs to show on the page.

I have another site that is nearly identical and I have much faster load times:

> Executed 241 queries in 108.32 milliseconds. Page execution time was 1065.35 ms.

What explains the difference between the two sites, and how could I go about fixing the slow site?

# Answer
> 3 votes
Here is an easy calculation:

```
page_execution_time = query_time + php_time;

```

So basically you seem to do quite a lot of stuff in php. Same basic stuff you could do

* Use some opcode cache, for example apc
* Find out what needs a lot of time using xhprof

---
Tags: database, performance
---


# Question
Title: Couple of important issues before I migrate into Drupal
Currently my website is in .NET and I would like to migrate to Drupal in order to manage the content better. My site currently supports 22 languages having different domain names for each language. The site has the same theme for all of the domains. Generally, the site (including all of its domains/languages) is divided into 3 subfolders/sections which are responsible for different content and slight changes in the theme. for example: The URL http://www.example.fr (which is responsible for the French language) is divided into 3 content sections:

```
http://www.example.fr/sec1/
http://www.example.fr/sec2/
http://www.example.fr/sec3/

```

and so is the other domains/languages. As a matter of fact, each section contains a slightly different version of the whole site. I have installed fresh D7 and also I have installed i18n (and its dependencies),pathauto, panels and context modules but I have yet succeeded to answer the following questions:

How can I create a node and assign it to one of the above sections ? Once I have managed to assign a node to a section, how can I make it have a URL prefixed by the appropriate section prefix like sec1,sec2 etc. ? How can I have my theme changed according to the section the user is in?

I have heard that Drupal has a very supportive community so I am really looking forward to someone who will be able to help me in these matters as soon as possible. So thank you all.

# Answer
> 2 votes
Taxonomies and pathauto/token will solve your first two questions. Use a taxonomy to categorise your nodes, then use a token such as `[term]` or `[termpath]` to add it to the start of the automatically generated URL paths.

The sections module will solve your last question. You can assign different themes based on paths, or for individual nodes, and some other ways too. Unfortunately, it looks like it doesn't currently have a released D7 port. There may be one in the works, or you may need to try to port it (likely not hard from my understanding of how it works). Possibly related project is taxonomy\_theme, which seems to have a `-dev` D7 release. I haven't used this module in either D6 or D7 personally though; I know sections works fabulously though in D6 despite not having an update in 2 years now.

# Answer
> 1 votes
It's better to use ThemeKey instead of taxonomy\_theme - it's the same author, and he claims that his development efforts will be focued at themekey

# Answer
> 1 votes
You can use Domain Access to create different versions of your site. Then you can simply assign content to one or more of the 'domains' so the content is domain specific. With this in combination with the Internationalization module you should be able to get wath you want.

I believe there is also the possibility to assign a theme per domain.

---
Tags: migrations
---


# Question
Title: How to create a view that lists one post per user
For a blog homepage I am trying to output a view that lists a single post for each user on the site. It needs to be sorted by date, so the latest post is shown at the top.

I'm trying the 'view inside a view' method here http://groups.drupal.org/node/11746 but thinking there must be a better solution out there.

# Answer
The solution was to use Rules and Views bulk operations (VBO) to change the 'promoted to front page' property of that users blog posts when they submit a new post. The triggered rule simply removes 'promoted to front page' from all their posts and then adds it back to the newly submitted node. Thus, each user will only have a single blog post with this property, which makes the blog homepage easy as you simply create a view sorted by date and filtered with the 'promoted to front page' property. Johan Falk has done some excellent tutorials on using rules and VBO. Well worth a watch.
> 2 votes

# Answer
The first problem is to sort your users properly.
Saying in SQL, you need something like this:

```
SELECT * FROM node GROUP BY uid ORDER BY MAX(created) desc;

```

As I can see GROUP BY in ORDER part is not going to work in Views 2/3. I may be wrong.
But if number of users on your site is not too big, you still can make this done in PHP argument code like this:

```
$nodes = db_query("SELECT nid FROM {node} GROUP BY uid ORDER BY MAX(created) desc");
$items = array();
while ($node = db_fetch_object($nodes)) {
  $items[] = $node->nid;
}
return implode('+', $items);

```

This code returns IDs for nodes, which have to be displayed. Now you have sorted nodes for each user and you can play with outputting.
> 1 votes

---
Tags: views, 6
---


# Question
Title: Why do the exposed filters in my view return to previous values after I change them?
I have a catalogue list organised as a table with 4 exposed filter criteria set up. The page can be found here. An export of the view can be found here.

When a user runs the filter it works fine, but if they change the value of one of the filters and run it again, the search returns the results of the previous search and reverts to the previous value of the filter.

I know that if I enable a 'reset' button and the user resets the search that this works, but it is rather strange that if the user only wishes to change one of the filter criteria and keep the others the same that they cannot. They have to reenter all the criteria again.

Is there a configuration option that I am missing somewhere? I am running Views 7.x-3.0-rc1

---

Update: I have just noticed that even with the reset button that things do not work as they should.

If I hit 'reset' the query string at the end of the url is removed and the filter text boxes become blank. If I then add new criteria and hit 'apply' the querystring reflects the new filters, but the filter text boxes and the results reflect the original filter values.

# Answer
In this case, the reason for the failure of the filter to update was that I had caching enabled on the view. Once I turned this off the exposed filters worked correctly.
> 2 votes

# Answer
You can select under each exposed filter, if Views should remember the selection or not. Remembering the last selected value will be stored as a session variable and persist until the user logs out etc.
> 2 votes

---
Tags: views
---


title: Using OR in views Argument filter

text:
# Question
Title: Using OR in views Argument filter
Is it possible to use OR in arguments? I have content types "Sport Match" and "Sport Team". "Sport Team" can be in "Host" field or in "Guest" field of Sport Match (node reference). How can i make view containing all "Sport Match" for one "Sport Team"? I would like to display such view on every "Sport Team" node. So i'm thinking that simple two arguments with OR would to the trick.

I would like to get NID of current "Sport team" node and pass it to arguments filter which will looks something like this:

field\_host = NID

OR

field\_guest = NID

Is there way to do this in views?

In SQL this is easy, can anyone point me how alter view so I manualy insert OR filter.

Or some other idea how to do this?

(I'm using D6 and Views 2)

# Answer
> 2 votes
I'd convert that argument into a filter, then use http://drupal.org/project/views\_or for it.

To convert an argument into a filter, you can use hook\_views\_query\_substitutions or hook\_views\_pre\_view to replace a specific value (for example `***NID***`) with what you need (e.g. `arg(1)`).

---
Tags: views
---


title: Fieldsets in Content Types

text:
# Question
Title: Fieldsets in Content Types
How do you add a fieldset to a content type in Drupal 7 to group fields? I don't see this option anymore. I just want to group related fields on a form together. Will that also trigger vertical tabs instead of let fields just float around in the open?

# Answer
> 5 votes
Now its a separate module called Field group. It comes with several display options including vertical tabs.

---
Tags: 7
---


# Question
Title: How can I access profile fields with a % variable in Drupal Actions?
I have an action setup in drupal to e-mail me when a new user registers for the site. Right now it is only telling me their user name (%username). Is there a variable that can access added fields so I can get their real name (First Last), or another way to add this info to the action message? So instead of my new user action having a message like:

"%username created an account" -\> "jschmoe created and account"

I could have:

"%first\_name %last\_name (%username) created an account" -\> "Joe Schmoe (jschmoe) created an account".

I'm using Content Profile module for the first and last name fields, though have few enough users at the moment that I could switch to Profile module fields.

# Answer
You could try using the Realname module together with Token and Token Actions.
> 3 votes

---
Tags: actions
---


# Question
Title: How to know which file to delete in a submit function?
I've got a managed file field in a form like this:

```
$form['source_file'] = array(
  '#type' => 'managed_file',
  '#title' => t('Source File'),
  '#default_value' => isset($data['source_file']) ? $data['source_file'] : 0,
  '#upload_validators' => array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ),
  '#upload_location' => 'public://imagemerge/merge/',
  '#required' => FALSE,
);

```

My submit function looks like this so far:

```
function imagemerge_merge_submit($form, &$form_state) {
  $source_file_fid = $form_state['values']['data']['source_file'];
    if ($source_file_fid != 0) {
      $source_file = file_load($source_file_fid);
      $source_file->status = FILE_STATUS_PERMANENT;
      file_save($source_file);
    } else {
      //some logic to determine previous fid?
      //and then a call to file_delete()
    }
  }

```

The docs for Forms API under managed\_file say that it is up to the module to call file\_delete. How do I know when and which file to delete?

# Answer
> 3 votes
Ok I solved this but it will be different for each type of form. The form I was adding this `managed_file` upload to is actually the image effect form. (`image_effect_form()`, I had to do some form\_altering to add my submit function.) My goal was to add a new image effect that allows placing a source file onto the destination image.

What I finally did was compare the $form\_state variables in the submit function for the following actions:

1. uploading a file when none was previously there
2. removing a file and submitting no file
3. removing a file and uploading a new file

For this particular form I came up with the following variables:

```
$new_fid = $form_state['values']['data']['myformfile'];
$old_fid = $form_state['image_effect']['data']['myformfile'];

```

Once I got what the new FID is and what the old FID was It was trivial to put together some logic that deletes the file at the appropriate place. The problem is that this isn't universal logic that works for every type of form that has a managed\_file in it. There didn't seem to be a standard way to get what the old file FID was. I found it for this specific form but for the next time I do a managed\_file I'll have to examine $form\_state again and find out if/where the old file FID is stored.

My code for the submit function is below. I also added some logic for the file\_usage table.

```
$source_file_new_fid = $form_state['values']['data']['source_file'];
$source_file_old_fid = $form_state['image_effect']['data']['source_file'];

if ($source_file_new_fid != 0) {
  $source_file = file_load($source_file_new_fid);
  $source_file->status = FILE_STATUS_PERMANENT;
  file_save($source_file);
  file_usage_add($source_file, 'imagemerge', 'image_style', $form_state['image_style']['isid']);
}

if ($source_file_old_fid != 0) {
  $del_file = file_load($source_file_old_fid);
  file_usage_delete($del_file, 'imagemerge', 'image_style', $form_state['image_style']['isid']);
  file_delete($del_file);
}

```

# Answer
> 1 votes
Looking at the description given in the "Form API Reference" page for the "#managed\_file" form field, I read the following sentence:

> The #managed\_file element is expanded into a set of FAPI elements including two '#submit' buttons one for Upload one for Remove, a '#file' element and a handful of '#hidden' and '#markup' elements to handle progress indication and displaying of already uploaded files.

Looking then at the process function for that form field (file\_managed\_file\_process()), which is the one set from file\_element\_info(), I notice that it defines a form submission handler for the "Remove" button, and that function (file\_managed\_file\_submit()) calls `file_delete()`.

```
  if ($button_key == 'remove_button') {
    // If it's a temporary file we can safely remove it immediately, otherwise
    // it's up to the implementing module to clean up files that are in use.
    if ($element['#file'] && $element['#file']->status == 0) {
      file_delete($element['#file']);
    }
    // …
  }

```

I would say there isn't the need for the module using that form field to call `file_delete()`.

# Answer
> 0 votes
It's definitely so that you will have to delete the file yourself if the file was made permanent. My guess that could be when the module get's uninstalled? Or if the node get's deleted?

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


# Question
Title: How do I redirect a Read More link to another URL in Showcase Image?
When creating a showcase image for my homepage, I would like to redirect the Read More link to another page in the site, instead of the default link back to the image. Is it possible?

Or do I just have to remove the Read More link and insert a URL link inside the slide text?

# Answer
You can use the path-redirect module to forward the URL in the "read-more" link to any other internal or external URL. If you forward internally, you need to use the "node/123" system URL and delete the alias for the node you are forwarding from, before you setup the redirect.

If you point at the read more link you'll see its node or alias in the lower left hand corner of your browser.
> 1 votes

---
Tags: uri, redirection
---


# Question
Title: Within a node, how can I reference the value of a field of a node associated to the current user through a node-reference?
I'm creating a customer extranet for my client. The users are my client's customers. Within the body of a page node, I need to display the ID of the customer (company) to which the current user belongs.

Here's how I've set it up so far:

* Drupal 7
* I have a Customer content type that has a field called customer\_id (among other things).
* I have added a node-reference field to the User fields that references one Customer node. (In other words, each user is associated with one Customer.)

So in his profile, the current user has a node-reference value pointing to a Customer node, and I need to retrieve and display (in a page node or block) the value of one field (customer\_id) in the Customer node being referenced in the current user's profile.

I've been going through several Drupal books and whatever module documentation I can find, and I've been experimenting with various views using the the Views module, but I'm still pretty stymied. Can somebody point me in the direction of a good way to implement this?

Thank you for your help!

Chris

# Answer
You should be able to do this through Views arguments, with the nid of the customer node as the argument. Then that node's fields should be available to you from there.
> 1 votes

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


# Question
Title: Client-Side Equivalent of drupal_set_message with javascript
I've got javascript that notifies the user of actions and errors, and I'd like to use the existing Drupal messaging. Is this built in to Drupal?

Alternatively, (I'm fairly new to Drupal and am not very familiar with the modules available) if this is available as a module, I haven't been able to find it. Does anyone know of a module?

UPDATE: To clarify, I'm trying to set a Drupal message from the client-side (JavaScript), on a page that has already rendered. This is a very AJAXy page with tonnes of functionality that sometimes requires messages be shown to the user.

Is there is a provision in the Drupal client-side API for setting messages?

# Answer
I don't see JS API for dispaying messages even in D7. Maybe because all you need is `DIV` with classes like `messages`,`status` `warning` or `error`. You can see how drupal works with it in file `/misc/tabledrag.js`.
When you drag rows in tables drupal shows you a warning message with this code:

```
$(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');

```
> 2 votes

---
Tags: 7, javascript
---


title: Display node's languages in views

text:
# Question
Title: Display node's languages in views
do you think, it is possible to display in views the languages the node was translated to? I mean something like this:

First article
english|german

Second article
english|german|dutch

# Answer
> 3 votes
**Yes it is possible.**

I have done something similar in Drupal 7 some time ago. Here is how to do it:

**Create your View**

Create a `Fields` style View with your required filters and sorting

**Add the relationship to the Translations**

1. Add a `relationship` to the translations: `Content translation: Translations`
2. As `Translation option` choose `All`
3. Add a filter `Content translation: Language` and choose `Current user's language`

**Add the Fields**

2. Add the field `Content: Title` with no relation and with `Link this field to the original piece of content` disabled
3. Add the field `Content translation: Language` with the `Translations` relation added before and with `Link this field to the original piece of content` enabled
4. In the `Format Settings` choose `Content: Title` as Grouping Field

**Format the list**

The horizontal list of the languages can be achieved by CSS formatting

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


title: multilingual site with views

text:
# Question
Title: multilingual site with views
I'm trying to set an english/spanish website and I've already set in my post types which are the types I want to be translatable. I also translated the posts but I'm not really sure how to set the views to display the content based on the language... I want the spanish posts to show up in domain.com/es/whatever/route ... and the english posts to show up in domain.com/whatever/route ... right now, both paths show the same content (the posts in English and the posts in Spanish)...

I'm guessing I need to somehow set contextual filters and relationships but I'm not so sure about how. Could I get a hand with that?

# Answer
for Views module add filter: Node translation: Language -\> Current user's language.
> 1 votes

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


# Question
Title: hook_validate() returns errors, but the form has lost all the user's submitted values
I'm sure there's a standard Drupal way of doing this, but I've tried a couple of the statements that I've found on blogs and stuff, and I can't get a form to restore the values submitted by the users.

For example:

* form default value: "enter a long word"
* user submits: "foo"
* validation sets: "word not long enough"
* form displayed on page with value: "enter a long word"
* expected value: "foo"

So far, in the `hook_nameform_validate` function, I've tried setting `form_state['rebuild']` and `form_state['redirect']` to `FALSE` (I've seen both listed in blogs as the right answer). Perhaps unsurprisingly to anyone who knows the correct answer, neither works individually, nor do they both work together.

**EDIT** as requested, here is some actual code to show what I'm doing (wrong). You're correct that the question was probably too general to be of value without any actual code on display. This sample is still "abstracted" - there's closer to a dozen fields, but the effect is the same.

In this case, with these functions (and the others, like theme etc...) when a user submits their email address, if the validation returns an error, the form tells them "bad user" then *clears* the email field (and all others). Ideally the form should repopulate all fields with any typing they've already done.

```
function sampleform_nameform($form, &$form_state) {
    $d = sampleform_defaults();
    $form = array(
        '#method'                   => 'post',
        '#prefix'                   => $d['form_prefix'].'<div class="sample">',
        '#suffix'                   => '</div>'.$d['form_suffix'],
        'your_email'                => array(
            '#value'            => $d['your_email'],
            '#type'             => 'textfield',
            '#field_suffix'         => '<span class="required">*</span>',
            '#required'             => TRUE,
            '#attributes'           => array('class' => array('standardInput'),
                                             'default' => $d['your_email'])
        ),
        'sampleform_submit'         => array(
            '#prefix'               => $d['clear'],
            '#type'                 => 'submit',
            '#value'                => $d['submit'],
            '#attributes'           => array('class' => array('buttonInput', 'submitInput')),
            '#executes_submit_callback' => true
        )
    );
    return $form;
}

function sampleform_nameform_validate($form, &$form_state){
    $d = sampleform_defaults();
    if (!valid_email_address($form_state['input']['your_email'])) {
        form_set_error('your_email', $d['e_email_v']);
    }
}

```

It's very possible that one of the two answers below has fixed the issue, and I've not had the chance to read them yet, so with a few more minutes, maybe we'l find the answer is already here.

:)

**EDIT 2**

kiamlaluno has shown us that while I was using `#value` in my form-builder function, the correct *nondestructive* setting in creation of a form is `#default_value`

If I look back to my original reference point, *Pro Drupal 7 Development* the form API examples in chapter 11 give the instruction to use `#value` on page 247 (where you build your first form).

They also use `MODULENAME_nameform` as the hook, while it appears to be more correct to use `MODULENAME_form` (according to the way drupal works, it's easier to find further documentation if you search for `_form` rather than `nameform`).

Anyways, hopefully this saves someone else some time. Someone should probably tell Todd Tomlinson and John K VanDyk that they've got an error in their book.

:)

# Answer
There is nothing particular that needs to be done, to avoid to overwrite the value entered by the user, when a validation handler returns an error.

For example, the following form, is build from the code shown below (system\_ip\_blocking\_form()):

```
function system_ip_blocking_form($form, $form_state, $default_ip) {
  $form['ip'] = array(
    '#title' => t('IP address'),
    '#type' => 'textfield',
    '#size' => 48,
    '#maxlength' => 40,
    '#default_value' => $default_ip,
    '#description' => t('Enter a valid IP address.'),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add'),
  );
  $form['#submit'][] = 'system_ip_blocking_form_submit';
  $form['#validate'][] = 'system_ip_blocking_form_validate';
  return $form;
}

```

Its validation handler is the following one (system\_ip\_blocking\_form\_validate()):

```
function system_ip_blocking_form_validate($form, &$form_state) {
  $ip = trim($form_state['values']['ip']);
  if (db_query("SELECT * FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField()) {
    form_set_error('ip', t('This IP address is already blocked.'));
  }
  elseif ($ip == ip_address()) {
    form_set_error('ip', t('You may not block your own IP address.'));
  }
  elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) {
    form_set_error('ip', t('Enter a valid IP address.'));
  }
}

```

When I enter a value for which the validation handler returns an error, the value I enter is not modified, as you can see from the following screenshots.

This is what happens on Drupal 6 too. The only case where a field value is cleared is when the form validation handler reports an error for a password form field; in that case the password field doesn't contain the previously entered password, which would be difficult to edit as it is shown as "•••••."

There is nothing that needs to be set; by default Drupal will not change the content of a field when a validation handler reports an error for that field. As far as I know, the value of a field could be changed by its "#after\_build" callback, that is invoked after the field is built, and that is described in form\_builder() with the following sentence:

> The "#after\_build" flag allows any piece of a form to be altered after normal input parsing has been completed.
> 2 votes

# Answer
Quick example of validating form:

```
function MODULENAME_form($form, &$form_state) {
  $form['SOMEFIELDNAME'] = array(
    '#type' => 'textfield,
    '#title' => t('SOMETITLE'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}
function MODULENAME_form_validate($form, &$form_state) {
  if (strlen($form_state['values']['SOMEFIELDNAME'])<=3) { // or use mb_strlen()
    form_set_error('SOMEFIELDNAME', t('word not long enough'));
  }
}
function MODULENAME_form_submit($form, &$form_state) {
  // Here will vaildated data.
}

?>

```
> 1 votes

---
Tags: forms
---


# Question
Title: Is there a recommended method to construct a form on a grid (2-dimensional array) with Form API?
> **Possible Duplicate:**
> Theme Drupal Form API checkboxes as a grid

I would like to create a form that is able to accept values which will be saved into a multidimensional array. Is there an advised method on how to accomplish this with Form API?

As an example:

```
  |  A  |  B  |  C  |
--+-----+-----+-----+
1 |     |     |     |
--+-----+-----+-----+
2 |     |     |     |
--+-----+-----+-----+
3 |     |     |     |
--+-----+-----+-----+

```

I would like to have a textfield for each grid square and save the end value into a single array which will be serialized and saved as a variable.

EDIT: Just to clarify, I don't particular care if the form is output as a TABLE in a HTML sense, but it would obviously be nice to have it stored as a multidimensional array from a PHP perspective.

# Answer
> 2 votes
If you need a table and put checkboxes on the left you could use http://heine.familiedeelstra.com/new-tableselect-form-element-in-core

Alternative you could theme your form. Therefore you have to write a theme\_form\_id which drupal\_render the elements and put them together with theme('table').

PS: This will perhaps land in drupal8: http://drupal.org/node/80855

---
Tags: 7, forms
---


# Question
Title: Ignore "invalid" or incorrectly formatted Emails addresses (on Signup/User Import)
I am importing a large set of users from a old CMS that has about 10k+ users that have no email or badly formatted emails.

I want to force this to import, but Drupal wants to validate the email string.

Is there anyway to temporarily disable this?

# Answer
> 1 votes
Better will assign some email (e.g. unknown\_XXX@garbage.com, where XXX is row number of csv) to email of unassigned users. There's tonn of software that work with CSV.
After importing, you can run sql update command that will assign to emails '' value for that garbage email.
p.s. Also you can setup Rules module, that check if email equal to garbage email and warn him to change his email.

---
Tags: users, emails
---


title: problem with .htaccess file

text:
# Question
Title: problem with .htaccess file
I am getting the following error after uploading files in server:

> The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.

For development purposes, I am using the following server URL: http://dev.example.mhd.co.us.

I am not able to access site when it has its .htaccess file; when I remove the .htacess file, it works fine. I am using the default file that comes with Drupal. I need to enable the clean URLs on the site.; mod\_rewrite is enabled.

Is there anything else I need to configure? Do you have any idea about why I have problems?

# Answer
> 3 votes
That usually means *something* in your .htaccess is causing Apache to fail. Could for example be a missing module or a configuration that denies access to something.

Try to look at the error log of the Apache server, if you have access to it. If not (even many shared hosting sites allow access to those files for your virtual host), you could ask your hosting provider support.

It is only possible to provide a more detailed solution once you post the actual error from the error log.

# Answer
> 2 votes
This error is due to .htaccess syntax error. Restore your .htaccess

For enabling Clean URLs you must have `mod_rewrite` enabled.

Make sure if `RewriteEngine On` in .htaccess

Setting .htaccess for Drupal that is extracted on the www-root. (e.g. example.com/) Uncomment the following line from .htaccess:

`RewriteBase /`

If Drupal is extracted in sub directory (e.g. example.com/subdir/)

`RewriteBase /subdir/`

# Answer
> 1 votes
Have you run Drupal on this host before (or even Wordpress)? I have run into hosting companies that disable a lot of the directives in the standard Drupal `.htaccess` file, and this can cause Apache to throw 500 errors.

---
Tags: .htaccess
---


# Question
Title: Drupal Commerce Entity Query Line Item Prices
I'm working on a Drupal module that needs to access the line items in a Drupal Commerce Shopping Cart. On most carts, there is a "line items" table of some sort that is linked to the cart via an unique cart id.

However, Drupal Commerce uses "Entities" which effectively obfuscate the relationship between the shopping cart id, the line items, the products and their prices. If you've played around with it at all, then you understand my pain when seeing the "revision" tables and how the data could exist in one of a dozen tables and requiring complex joins that would break if (when) the client upgrades their Commerce module.

I know there is a way to query entities, but I haven't found adequate explanations for using those queries with Drupal Commerce to allow me to pull line items and pricing from a cart. I keep running into Ubercart documentation which is close, but doesn't use entities.

Does anyone know where there is documentation on doing Entity queries (particularly with Drupal Commerce)? Better yet, do you have a query in your pocket that can pull cart contents, and line item pricing?

# Answer
> 1 votes
You can use Entity API that provide a unified way to deal with entities and their properties, please read README.TXT there. Handbook is poor.

# Answer
> 1 votes
There is one part that is confusing you a bit, when thinking about Drupal Commerce, and that is the *cart*. Users doesn't have a cart, but instead have orders. An order can have the status of being completed or being active. What you see in your cart is really your active order.

An order has reference to line items and each line item has a unit price, quantity, total price and a reference to a product. If all you want is to load the line items of a users active order (cart), you can do that pretty easily:

```
global $user;
$order = commerce_cart_order_load($user->uid);
if ($order) {
  // Using entity wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
  }
}

```

You could also get the line item ids from the order and use `commerce_line_item_load_multiple` to load the line items.

---
Tags: 7, commerce
---