# Question
Title: Finding out the machine name of a field when using Views
When using Views, I always use fields instead of content. But I noticed that Views does not show the machine name of a field and it only *assumes* that you already know it. Is there some other way to find out the machine name?

Knowing the machine name lets me access the field directly like so

```
print $fields['machine_name_here']->content;

```

# Answer
Go to the settings page of a view, and click on "Theme information"; then you look at the IDs of each field. For example, if "Theme information" shown this information, then "last\_comment\_name" would be your machine name.

> Field Node: Last comment author (ID: last\_comment\_name):
> 6 votes

# Answer
If you use the devel module (highly recommended) you could also insert a function to show you all the available fields for the view:

```
<?php dpm($fields); ?>

```
> 1 votes

---
Tags: views, entities
---


# Question
Title: How to deal with this kind of node references, when creating a new instance of a content type?
I'm new using Drupal, and I'm trying creating a database driven website in Drupal. I don't know what is the best way of doing the following:

I need to have three types of 'entities' (content types):

* **Worker**
* **City**
* **State**

Every **Worker** lives in one and only one **City**, and every **City** is in one and only one **State**.

I could create those three contet types:

* **State**
* **City**, that will have a node reference to **State**
* **Worker**, that will have a node reference to **City**

But...

When I someone creates a new Worker, I don't want Drupal to show a list with all the cities (because there could be cities with the same name in different states).

How could I add the feature of **selecting first the State, and then the City**, when creating a new Worker, or something like that that allows the user to differentiate?

**Edit:**

The module Dependent Fields would work in this case, but it forces me to add another field to the **Worker** content: A **State**. I don't want this, because it could be kind of redundant information (knowing the city of the worker, I can also know the state). Do you know what I mean?

# Answer
> 5 votes
I would create a taxonomy hierarchy that has nested State -\> Cities. You can then provide a way for them to choose a state, and filter a drop-down by the parent taxonomy.

Hierarchical Select will do this for you.

If you need to create a content type for city, just apply the same taxonomy term to link the two together.

Kim

# Answer
> 2 votes
Sounds like the Conditional Fields module might help. This allows you to make CCK fields that are dependent, so you can choose State and then get City.

Some more details about this module (from its project page):

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
>
> When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
>
> You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

# Answer
> 1 votes
What about using the Postal module? I could use some help developing it.

# Answer
> 1 votes
I found this - http://drupal.org/node/626088 \- Hierarchical Select Node Reference.

It sounds exactly like what you were originally intending. Looks a bit complicated to setup.

# Answer
> 0 votes
I think you should to use taxonomy for State & City with multilevels? After use hierarchical\_taxonomy module.

Enjoy ;)

# Answer
> 0 votes
what about making diferent entitys . you can use eck http://drupal.org/project/eck one entity for state , and another one for city. then you could use relation (http://dev.nodeone.se/en/learn-the-relation-module) o maybe entity reference (http://dev.nodeone.se/en/using-the-reference-modules). then you createa field in user acount or in the content type that you have made that refers them .

you could use display suit (http://www.youtube.com/playlist?list=PL7E361A55994F1648) , field group http://www.youtube.com/watch?v=vhA5b5KpHZw and Renderable elements (http://www.youtube.com/watch?v=rSgd91tZSEc), this crate a mutipage content types

good luck.....

---
Tags: 7, nodes
---


# Question
Title: Pathauto does not trigger on node_save when programatically creating nodes
I am programatically saving nodes. From my reading, it sounds as if Path auto is trigged to autmatically create a URL alias when node\_save() is called. However, this is not happening.

I later read that I needed to set $node-\>path\_set\_alias = TRUE. However, this is not working correctly either.

Using 7.12 and the latest versions of pathauto.

Here is my code.

```
$node = new stdClass();
        //set other defaults
        node_object_prepare($node);

        $node->type = $page_data['content_type'];
        $node->body[LANGUAGE_NONE][0]['value'] = $page_data['description'];
        $node->body[LANGUAGE_NONE][0]['summary'] = text_summary($page_data['description']);
        $node->body[LANGUAGE_NONE][0]['format']  = 'filtered_html';
        $node->title = $page_data['title'];
        $node->field_product_price[LANGUAGE_NONE][0]['value'] = $page_data['price'];
        $node->field_item_location[LANGUAGE_NONE][0]['postal_code'] = $page_data['zipcode'];
        $node->uid = "1";
        $node->status = 1;
        $node->active = 1;
        $node->pathauto_perform_alias = TRUE;

    //the name of my actual field is 'product images'
    $node->field_product_images[LANGUAGE_NONE] = $images;
    unset($images);

    $node->field_baby_clothes_category[LANGUAGE_NONE][0]['tid'] = $page_data['category'];

    if($node = node_submit($node)) { // Prepare node for saving
        node_save($node);
}

```

Thoughts on how to get this to work correctly? Thanks!

# Answer
We discussed on Drupal.org that not setting the $node-\>language property causes this issue to happen. Either setting $node-\>language = LANGUAGE\_NONE or $node-\>language = 'en' should fix this.

Also using $node-\>path\['pathauto'\] = TRUE rather than $node-\>pathauto\_perform\_alias for Drupal 7.
> 4 votes

---
Tags: 7, nodes, path-aliases, importing-exporting
---


# Question
Title: Ubercart need to pay depends on user role
I am using drupal 6.20 and Ubercart 2.0 Like what I asked in the subject. Is there any chance that I can customize a ordering process with or without payment?

For example: There are 2 roles of users ( Role A and Role B) Users of Role A need to pay all my products to complete the transaction. Users of Role B don't need to pay any of my products to complete the transaction.

Actually I want my website to be suitable for 2 kinks of clients: 1. wholesalers (Role A) --- order online but pay through company invoicing system 2. retailers (Role B) --- order online and pay instantly

Appreciate any thoughts and helps on this!

# Answer
> 1 votes
This question has been **solved** and just want to put the solution here to help someone has the same interests!

Download the uc\_purchase\_order module, http://drupal.org/project/uc\_po

And give the permission to the user role you want them to purchase through purchase order.

---
Tags: ubercart
---


# Question
Title: User creation failing due to integrity constraint violation
For reasons I can't understand, I am unable to create users in my Drupal installation (which wasn't a problem last time I tried).

If I try in the UI (at `/admin/people/create`) or if I try with `drush user-create`, in both cases the error message I get reads like:

```
WD rules: Unable to modify data "account:field-user-image:alt": Invalid data value given.
↪  Be sure it matches [warning] the required data type and format.
WD rules: Unable to evaluate action data_set.
WD user: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate
↪ entry '187810' for key[error] 'PRIMARY': INSERT INTO {users} (uid, name, pass, mail,
↪ created, access, status, data) VALUES (:db_insert_placeholder_0,
↪ :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3,
↪ :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6,
↪ :db_insert_placeholder_7);
Array
(
    [:db_insert_placeholder_0] => 187810
    [:db_insert_placeholder_1] => xxxxxxx@xxxxxxx.com
    [:db_insert_placeholder_2] => $S$XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXXX
    [:db_insert_placeholder_3] => xxxxxxx@xxxxxxx.com
    [:db_insert_placeholder_4] => 1329491489
    [:db_insert_placeholder_5] => 0
    [:db_insert_placeholder_6] => 1
    [:db_insert_placeholder_7] => a:1:{s:34:"user_relationships_ui_auto_approve";a:0:{}}
)
 in drupal_write_record() (line 6975 of /var/www/html/includes/common.inc).
WD php: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate
↪ entry '187810' for key[error] 'PRIMARY': INSERT INTO {users} (uid, name, pass, mail,
↪ created, access, status, data) VALUES (:db_insert_placeholder_0,
↪ :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3,
↪ :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6,
↪ :db_insert_placeholder_7);
Array
(
    [:db_insert_placeholder_0] => 187810
    [:db_insert_placeholder_1] => xxxxxxx@xxxxxxx.com
    [:db_insert_placeholder_2] => $S$XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXXX
    [:db_insert_placeholder_3] => xxxxxxx@xxxxxxx.com
    [:db_insert_placeholder_4] => 1329491489
    [:db_insert_placeholder_5] => 0
    [:db_insert_placeholder_6] => 1
    [:db_insert_placeholder_7] => a:1:{s:34:"user_relationships_ui_auto_approve";a:0:{}}
)
 in drupal_write_record() (line 6975 of /var/www/html/includes/common.inc).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
↪ '187810' for key 'PRIMARY': INSERT INTO {users} (uid, name,
↪ pass, mail, created, access, status, data) VALUES (:db_insert_placeholder_0,
↪ :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3,
↪ :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6,
↪ :db_insert_placeholder_7); Array
(
    [:db_insert_placeholder_0] => 187810
    [:db_insert_placeholder_1] => xxxxxxx@xxxxxxx.com
    [:db_insert_placeholder_2] => $S$XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXXX
    [:db_insert_placeholder_3] => xxxxxxx@xxxxxxx.com
    [:db_insert_placeholder_4] => 1329491489
    [:db_insert_placeholder_5] => 0
    [:db_insert_placeholder_6] => 1
    [:db_insert_placeholder_7] => a:1:{s:34:"user_relationships_ui_auto_approve";a:0:{}}
)
 in drupal_write_record() (line 6975 of /var/www/html/includes/common.inc).
Drush command terminated abnormally due to an unrecoverable error.

```

(where  indicates that I've wrapped lines for legibility).

Now I can see that this is because it is trying to enter a duplicate `users.uid` into the database, but I can't work out why that would be the case. At no point have we manually entered `users.uid` values, so the `autoincrement` should just be doing its thing.

Is there something I'm missing? Is there some way for me to reset something so that Drupal (or mySQL) just resets its autoincrement value and tries to do the insert with a valid UID?

Alternately, should I just mess with the database manually? It'd be awkward to do, as there are a surprising number of fields to have to mess with, but I could do that if it's easier?

**Update:** A friend suggested running `mysqlcheck`, but that is passing ok. Also, Clive's suggestion of resetting the autoincrement for the table doesn't seem to have resolved the problem.

# Answer
After a *really* long time getting *really* frustrated with this, I've just fixed it *with one line of SQL*. (Some days I really hate computers.)

The database table `sequences` contains one row and one column. This `sequences.value` is the `autoincrement` ID that is used for (amongst other things) new user accounts.

I don't know why it was wrong or how it got wrong. But

```
mysql> update sequences set value = 200000;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

```

and suddenly user account creation works again.

Did I mention that some days I really hate computers? ;o)
> 4 votes

# Answer
I encountered a similar problem and traced it to Rules. A thread about rules causing this error can be found here: http://drupal.org/node/1169800
> 3 votes

# Answer
You can reset the auto increment value fairly easily:

```
ALTER TABLE users AUTO_INCREMENT = 187811

```

It is a bit strange though, when you add a user the `uid` is determined with the line of code:

```
$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());

```

As that grabs the maximum user id out of the database and uses PDO to get the next available ID I'm not sure if the auto increment field actually comes into it.

Either way it's worth running the alter query against the table, it might do the trick.
> 2 votes

---
Tags: 7, users, database
---


# Question
Title: Given $form, how to programmatically generate its corresponding $form_state?
The media\_mover module contains this function, which builds a form and pre-populates default values:

```
/* step 1 */ $form = media_mover_api_configuration_base_form($configuration);

```

It also contains this function, which submits the form:

```
/* step 2 */ function media_mover_api_add_config_form_submit($form, &$form_state)

```

I would like to programmatically generate the form (step 1), and then programmatically submit the form (step 2).
Step 1 is not a problem; I am able to generate `$form`. For step 2, I need `$form_state`.

Given `$form`, is there a way to programmatically generate its corresponding `$form_state`? I am using Drupal 6.

This is a more detailed explanation of what I am trying to accomplish. I am able to programmatically fill out and submit a particular form by laboriously setting all the field values in `$form_state['values']`, and then calling `media_mover_api_add_config_form_submit($form, &$form_state);`

However, the process would be much simpler if I could instead use this function, which converts a `$configuration` object into `$form`, and does all the heavy lifting:

```
$form = media_mover_api_configuration_base_form($configuration);

```

This function enters a default value into each form field. The only missing step, then, is to copy all these default field values from `$form` to `$form_state['values']`. I am wondering whether there is a function to do this. Or is there a way to loop through all the fields in `$form` and extract the field-name and default value?

# Answer
> 1 votes
I've made a slight improvement to this solution. The $values array didnt respect the tree format and moves \[$key\]\[$key\]\['value'\] to $value\[$key\]\['value'\] causing sub elements with a key of "title" to overwrite the node title:

```
function mymodule_get_form_state($form){
  $values = array();
  _mymodule_form_get_values($form, &$values);
  $form_state = array();
  $form_state['values'] = $values;
  return ($form_state);
}

function _mymodule_form_get_values($element, &$values) {
  foreach (element_children($element) as $key) {
    if (isset($element[$key]) && $element[$key]) {
      if (isset($element[$key]['#default_value']) && $element[$key]['#default_value']) {
        $values[$key] = $element[$key]['#default_value'];
      } else {
        // Recurse through all children elements.
        _mymodule_form_get_values($element[$key], &$values[$key]);
      }
    }
  }
}

```

# Answer
> 0 votes
I would wager that `media_mover_api_add_config_form_submit()` is a function registered as the submit function for a form. That is, it doesn't 'submit the form,' it is called when the *user* submits the form in their web browser.

Form API lets you register functions to handle validation and submission of forms. Generally, you don't call these; you let Drupal do it.

I suppose the obvious question is: Why do you need $form\_state?

Here's a link to the Form API Quickstart Guide.

UPDATE: OK given your update....

I know very little about Media Mover, though it looks useful. Poking through the code, I suggest that if you need to save a new configuration, then you just do it: `$conf = new media_mover_configuration; /* set configuration here */ $conf->save();` Or subclass the configuration if you need an encapsulated approach. You also might try asking the project's lead for guidance, and remind them to add more documentation to the code. :-)

Also, MM might support Features, if that helps you.

# Answer
> 0 votes
FAPI is your friend and embeds this functionality.

# Answer
> 0 votes
form\_state\_defaults() will retrieve the default values. But what are you exactly trying to achieve? I'm guessing that at some point you want to set some values to be submitted? Do you have post data?

As paul-m I'm also guessing that `media_mover_api_add_config_form_submit()` is a function registered as the submit function for the form you mention. Calling this function as above won't work.

You can call the process form function though, which will build it validate and submit it if applicable.

ie: `drupal_process_form($form['#form_id'], $form, $form_state);`

---
Tags: forms
---


# Question
Title: Export Webform submission data into external database
I need webform submission data to be inserted into an external sql database. How would I go about doing this? Would this be a custom module, or be processed in template.php? I am having trouble understanding how I can capture that data and have it sent over to an external database.

# Answer
Usually the first step to solving a problem like this in Drupal is finding the right hook.

A quick google search for "webform hooks", and then we pick the hook where we'd have access to the completed webform's data: http://api.lullabot.com/hook\_webform\_submission\_insert/7

The example on that page happens to be exactly what you want to do!
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: views filter: problems with the query object
I am trying to get my filter query ready, but I don't understand how any of the query object works. my actual SELECT query looks like this:

```
SELECT nid
FROM `field_data_field_verein` verein
LEFT JOIN `ds_vereine` ON ds_vereine.tid=verein.tid
WHERE ds_vereine.plz IN
  (SELECT ds_plz_distance.plz_first
  FROM `ds_plz_distance`
  WHERE ds_plz_distance.distance < 20
  AND ds_plz_distance.plz_first=ds_vereine.plz)
OR ds_vereine.plz IN
  (SELECT ds_plz_distance.plz_second
  FROM `ds_plz_distance`
  WHERE ds_plz_distance.distance < 20
  AND ds_plz_distance.plz_second=ds_vereine.plz)
OR ds_vereine.plz IN
  (SELECT ds_plz_ort.plz
  FROM `ds_plz_ort` ort
  WHERE ds_plz_ort.kreis=306)

```

I honestly do not know how to use `$this->query->add_where()` function to incorporate this query. All it gives me is a fatal sql error.

you can see my views filter handler functions here: views filter: broken filter - but what's broken about it?

thanks!

**Edit**

Following Countzero's advice I took the plunge and delved deep into the views-api/code. Two problems I struggled very strongly with were a) joining the required tables the right way and b) implementing the subqueries. I'll shortly explain what I found worked for me.

a) I followed the api-docs and told views my used tables in `hook_views_data`. Don't. Instead join it in your filter. In short:

```
$join = new views_join();
$join->construct('table','left_table','left_field','field');
$this-query->ensure_table('table',$this->relationship,$join);

```

b) It is actually not a problem at all to nest conditions and thus subqueries. It was quite difficult to find out what you have to pass as an argument in the `add_where` function, so I tell you here for your convenience (;)):

```
$subquery=db_select('table','table_alias')
  ->fields('table_alias',array('field'))
  ->condition('table_alias.condition_field',20,'<')
  ->where('table_alias.condition_field=base_table.bt_field',array());
$this->query->add_where($group,'base_table.bt_field',$subquery,'in');

```

Note: The key lies in constructing the select query without executing it and passing it as a value directly.

# Answer
Your `add_where` syntax doesn't follow the documentation given in Views code. Here is a paste :

```
/**
   * Add a simple WHERE clause to the query. The caller is responsible for
   * ensuring that all fields are fully qualified (TABLE.FIELD) and that
   * the table already exists in the query.
   *
   * @param $group
   *   The WHERE group to add these to; groups are used to create AND/OR
   *   sections. Groups cannot be nested. Use 0 as the default group.
   *   If the group does not yet exist it will be created as an AND group.
   * @param $field
   *   The name of the field to check.
   * @param $value
   *   The value to test the field against. In most cases, this is a scalar. For more
   *   complex options, it is an array. The meaning of each element in the array is
   *   dependent on the $operator.
   * @param $operator
   *   The comparison operator, such as =, <, or >=. It also accepts more complex
   *   options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is an array
   *   = otherwise. If $field is a string you have to use 'formula' here.
   *
   * @see QueryConditionInterface::condition()
   */
  function add_where($group, $field, $value = NULL, $operator = NULL) {

```

So basically you cannot inject a complete query like you tried to, but you must use the different methods provided by the objects to carefully construct the different parts.

The less clear part is the `group` argument : it refers to the groups defined in the `filters` part of Views UI, the one created when you use `Create new group`in the filters contextual menu.
> 0 votes

---
Tags: 7, views, database
---


# Question
Title: Populating fields from the User entity during a Commerce checkout
When a user checkouts out, they need to fill in some specific information which should be saved to the User entity.

Thus I need to modify the checkout form to collect the information I want, then save it to the User.

It seems like a cheeky way to simplify the process would be attaching User fields directly to the Commerce Order entity. Is this possible, or should I just load the User entity form and copy the fields I want in a hook\_form\_alter?

# Answer
> 1 votes
You could attach the fields from the user to the form, but you would need to handle saving the user in the form submit. You could in form alter do something like this

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form id') {
    $form['user_fields'] = array();
    global $user;
    field_attach_form('user', $user, $form['user_fields'], $form_state);
  }
}

```

You also need to add validate and submit handlers in the `form_alter` in the validate handler do

```
 field_attach_validate('user', $user, $form['user_fields'], $form_state);

```

And in the submit handler do

```
field_attach_submit('user', $user, $form['user_fields'], $form_state);
user_save($user);

```

---
Tags: commerce, entities
---


# Question
Title: How can i reload jQuery scripts after form submit in views using ajax?
I have a views with ajax enabled using B.E.F. to filter some content. After submitting these filters jquery scripts stop working. Please help me to find an answer how to reload any of these scripts after using submit button with ajax? I\`ve tried to do something like this and load it as a simple script using drupal\_add\_js in template.php:

```
Drupal.Behaviors.reload = function (context) {
jQuery(".form-submit").submit(function() {
  jQuery("table").stickyTableHeaders();
});
}

```

I know that this code can hardly work but still firebug says Drupal.Behaviors is undefined.

# Answer
If you wrote your JS code like this.

```
(function ($) {
  Drupal.behaviors.tableStickHeaders = {
    attach: function(context, settings) {
      $("table").stickyTableHeaders();
    }
  };
})(jQuery);

```

It should automatically be reapplied when needed. This is the recommended way if writing JavaScript for Drupal.
> 2 votes

---
Tags: 7, views, ajax, javascript
---


# Question
Title: Can I create a text field which is both a autocomplete taxonomy, and a freetagging field
I want to let my users store a list of their interests. I don't know what they are going to say (or how many interests) so I am going to let them create their own, preferably as one big comma separated list.

But I'd also like to have those interests as taxonomy terms so that I can find users later on based upon their interests...

Can you suggest a way of doing that?

It would be best if the field was autocomplete too to reduce the number of variants so for example I might type into my interests field

Books, Movies, Hitch

and if the system has other people interested in "Hitchhikers Guide to the Galaxy" then it offers that to me, along with "Hitchhiking", "Hitch (film)" and so on...

(In case you are familiar with it what I am describing is very similar to the LiveJournal interests field)

I am using Drupal 7, Profiles2, and MySQL. I might consider writing a custom module for this if that is the only way, but only if there is demand for it elsewhere.

Hey- thinking about it I'd quite like the way that this site does its tagging of posts..... :-)

# Answer
That is how the autocomplete taxonomy widget works by default?

It provides autocompletion, but users can also add their own new tags.

Simply add a taxonomy field to your profile, select the Autocomplete Widget and you're good to go.
> 3 votes

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


title: Get user Account form

text:
# Question
Title: Get user Account form
I am trying the user account form(the one that comes in *user/%/edit*) of the logged in user, I have tried:

```
drupal_get_form('user_profile_form');

```

&

```
drupal_get_form('user_profile_form',1);

```

Though the form is loaded, on calling `render()` the div is empty.

# Answer
> 8 votes
The second example won't work because `user_profile_form()` takes a user object as it's argument, not an id. I suspect your form is not being outputted because you're not actually calling `print` on it...`render()` just prepares the string it doesn't actually output it.

Try this code:

```
$account = user_load(1);
print render(drupal_get_form('user_profile_form', $account));

```

**EDIT**

You'll also need to include the user.pages.inc file where the function itself lives:

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

```

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


title: No title on article page

text:
# Question
Title: No title on article page
I have created a view which displays the 10 latest news items (articles). They show up fine in teaser format. When clicking on the full article there is no title displayed and I can't work out why. This is my node--article.tpl.php:

```
<div class="article">
  <div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
    <div class="postheader">
        <?php print $user_picture; ?>

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

        <?php print render($title_suffix); ?>

        <?php if ($unpublished): ?>
            <div class="unpublished">
                <?php print t('Unpublished'); ?>
            </div>
        <?php endif; ?>

        <?php if ($display_submitted): ?>
        <div class="postinfo">
            <?php print $user_picture; ?> <!-- print the user picture, do not move if you want the picture displaying on the top -->
            <?php
                print t('!username • !date • !time',
                array('!username' => $name, '!date' => date( "d/m/y",$node->created), '!time' => date( "G:i",$node->created)));
            ?>
        </div>
        <?php endif; ?>
    </div>
    <div class="content"<?php print $content_attributes; ?>>
        <?php
            // We hide the comments and links now so that we can render them later.
            hide($content['comments']);
            hide($content['links']);
            print render($content);
        ?>
        <div class="links">
            <?php print render($content['links']); ?>
        </div>
    </div>
    <?php print render($content['comments']); ?>
</div>

```

Also I should note that I'm very new to drupal and I don't know PHP very well. If anyone could tell my why that would be really helpful. Thanks.

# Answer
Your template is expecting that the node title will be displayed as the page title, which in controlled in the `page.tpl.php`. Either the title is printed, but not where you expect or you don't print the page titles at all.
> 2 votes

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


# Question
Title: How to list members in a group using views Drupal 7?
I am using Profiles 2 and Organic groups.

I was successful in listing users via views \> Users.

I am using "profiles 2" module to collect and store details of users rather than the core drupal user management.

I have created few groups using "organic groups" module.

My question is how to list all the "PROFILES" (created via profile2 module) of members belonging to a group using views ?

# Answer
> 2 votes
I had forgotten to add Groups Audience as a field in the Profile type created by Profile 2 which in my case was "Main Profile".

# Answer
> 0 votes
I haven't used neither OG nor Profile2, but since no-one else has given you a more specific answer, I will provide a general one.

When you create a View, your first choice is, "What do list", it's possible that "Profile2" provides a "profile" specific choice here, but most likely, you should go with the regular "user" list.

Then, the filtering on a specific group, is done with a contextual filter, probably on group id.

I would recommend you learn to understand the basic structure for Views first, and you will be able to understand the answer to a whole class of questions similar to this one. Some video tutorials can be found here.

---
Tags: views, organic-groups, users
---


# Question
Title: Filter menu_tree_all_data() tree by language?
My site uses multiple languages and I'm using menu\_tree\_all\_data() to get the menu tree programmatically. Currently all nodes and their translated nodes use the same menu tree.

If I use a menu block the menu that is displayed is filted by language version of the site the user is on. Which is good.

When calling the menu\_tree\_all\_data() in code to build a menu programmatically it returns the entire tree and there does not seem to be an option to filter the menu by a language.

Does anyone know how to get the menu tree in code filted for a specific language?

# Answer
> 6 votes
I suppose you have i18n\_menu.module installed. In this case, use `i18n_menu_localize_tree($MENU_TREE)` to get the tree for the current language.

To get secondary menu, for instance (on template.php):

```
$tree = menu_tree_all_data('menu-secondary');
$variables['secondary_menu_expanded'] = menu_tree_output(i18n_menu_localize_tree($tree));

```

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


# Question
Title: Using jQuery to copy some content from div to input value - value displays nicely but there`s no value in html
I've got a webform in a block (using webform pay and webform block) which printing in a overridden template via module\_invoke.

There is a simple price field (input). In the content type i\`ve got a price field also. I am using this kind of script to copy value from node's price div to another input field in a block:

```
$(document).ready(function(){
  var txt = $('.field-field-price .field-item').html();
  var txt = jQuery.trim(txt);
  $('#edit-submitted-price').val(txt);
});

```

The needed value displays just fine but in html value="" and i just can\`t submit the form with needed value in price field. The screen-shot is attached. Thanks in advance for your time and understanding!

# Answer
> 1 votes
The `value` attribute for text inputs determine the initial value, it does not change when the user inputs something in the field or when it's changed by JavaScript.

If you are experience some error, it's most likely something else that's the problem.

---
Tags: 6, javascript, webforms
---


# Question
Title: How to fix special characters in node titles?
When I imported content from my legacy system using the migrate module some special characters didn't get imported correctly.

For example the `"` character got changed to `"` and is showing as such in the node title. Is there an easy option fix that when displaying or do I have to replace it at the database level?

# Answer
> 7 votes
Drupal does `check_plain` on titles which removes all html and does some conversion of chars (`& -> &`). Depending on how the migration went, that could be part of the problem (escaping escaped content). But it's hard to say what the problem is without knowing what you actually got in the database.

Drupal uses the philosophy to store everything raw in the database, and escape it on output. If the legacy system did it differently, you could have the data stored differently than what Drupal expects, and would then need to fix it at the database layer.

---
Tags: 7
---


# Question
Title: How to add custom node field into page title?
I have a custom node field I want to add into the page title. How can I do this?

Content type is a property listing and I want to have area size and location printed next to the title.

e.g. Large Mansion 900 sq ft (Chicago)

Location is also a taxonomy term in a dropdown list.

Do I need a preprocess\_page function to extract the field and then use page.tpl.php?

# Answer
> 4 votes
A `hook_preprocess_page` function in your template.php file would certainly be one way to do it:

```
function MYTHEME_preprocess_page(&$vars) {
  $node = menu_get_object();
  if (isset($node->nid) && $node->type == 'article') {
    $data = $node->field_custom_field[$node->language][0]['value'];

    $vars['title'] = $vars['title'] . ' ' . $data;
  }
}

```

In page.tpl.php your `$title` variable should contain your new string based on the field.

You'll probably want to do a couple of extra checks in there as well, for example making sure the node is of the right type, etc.

**EDIT**

To address your comments I guess you'd want to do something like this:

```
$area_size = $node->field_area_size[$node->language][0]['value'];
$location = $node->field_location[$node->language][0]['value'];

$vars['title'] = "$vars[title] $area_size sq ft ($location)";

```

# Answer
> 1 votes
There's a module for that: Page Title.

> This module gives you granular control over the page title. You can specify patterns for how the title should be structured and, on content creation pages, specify the page title separately to the content's title.

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


# Question
Title: Grant permission for publishing options without full 'administer content' permission
As the question says. I'm working on a news site, and authors should be able to create a full piece and be able to chose whether to publish or not. How can you do this?

# Answer
> 4 votes
You can use the Save Draft module. It adds a 'Save as Draft' Button to the node\_form for content types, allowing the user to click the 'Save as Draft' button to save the node as a draft. It has it own separate permissions aside from the 'administer content' core permission.

# Answer
> 3 votes
The Publish Content module could be useful.

---
Tags: 7, users, nodes
---


# Question
Title: Need help with import problem on Aquia DEV desktop for Windows
I am trying to import a DEV version of a site using the import function on Aquia Dev Desktop

I can successfully import the codebase and the sql dump file, but every time I go to the site, I get this error

\**Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

Fatal error: Unknown: Failed opening required '/var/www/xhprof/header.php' (include\_path='.;C:\php5\pear') in Unknown on line 0\**

We have tried this on three different laptops, all using the same Windows 7 configuration. We get the same result every time. This leads me to believe that there is something wrong with the files that I was given to import

Does anybody have any insight into what might be happening?

Thanks!

# Answer
We fixed this with a hammer.I hope we can find a more precise fix in the future.

These are the instructions I gave to our team

1. Go to root directory of your original localhost Drupal installation (aka codebase)
2. Copy all the stand alone files –leaving the folders uncopied
3. Go to the root directory of your Drupal installation that you are trying to import (aka codebase)
4. Delete all the stand alone files in the codebase (leaving folders)
5. Paste in all the stand alone files from the localhost codebase

This should get things working again.
> 1 votes

# Answer
Try commenting out the line in settings.php that requires an include from the /var/www directory.

Make sure you open the correct settings.php - path will be sites/yourlocalsiteurl/settings.php.

For me the line to remove is line 260:

```
require('/var/www/site-php/myacquiacloudaccountname/myacquiacloudaccountname-settings.inc');

```
> 1 votes

---
Tags: 7
---


# Question
Title: How can I get documentation on a variable listed in the Features UI provided by Strongarm?
When looking through the list of variables provided by Strongarm, there are several that sound like they might be useful to include but what they actually refer to is impossible to guess from the name alone (e.g., mail\_system). How can I quickly look up unknown variables to see what it is that they do?

# Answer
> 3 votes
Unfortunately, this is a shortcoming of the Variables system in Drupal: there is no centralized place documenting what they do. This is one reason why it is recommended that modules implementing their own advanced configuration (more than a few key-value pairs) do so using their own tables in `hook_schema()`, where everything can be documented. That having been said, you can grep around for where they're set/read from your Drupal root:

```
grep -rn 'variable_[gs]et(' . | grep 'foo_variable'

```

By checking the documentation for the functions in which they're set, you can typically glean their purpose.

# Answer
> 0 votes
If you search for the string in your codebase you should at least find the module(s) which are using the variable. If this deos not help I'd say the usual candiadates have to be asked: this forum, irc, the form at drupal.org etc.

---
Tags: features, configuration
---


title: Can I use hook_block_info() in a theme?

text:
# Question
Title: Can I use hook_block_info() in a theme?
In Drupal 7, can I use hook\_block\_info() in a theme?

I would like my theme to create a block (which would contain dynamic content). This will allow the user to move it around where he wants to, or simply hide it.

Is this the way to go?

```
/**
 * Implements hook_block_info()
 */
function mytemplate_block_info()
{
  $blocks['mytemplate-block'] = array(
    'info' => t('TemplateBlock'),
    'weight' => -100,
    'status' => 1,
    'region' => 'content',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => '<front>',
  );

  return $blocks;
}

/**
 * Implements hook_block_view()
 */
function mytemplate_block_view($delta = '')
{
  $block = array();

  switch ($delta) {
    case 'mytemplate-block':
      $block['content'] = 'some custom html';
    break;

  }

  return $block;
}

```

# Answer
> 7 votes
I'm afraid you can't, no, it has to be in a module.

The array of blocks is built up in `_block_render_blocks()` using the `module_invoke()` function which, as its name suggests, only invoke hooks for modules and not themes.

If you haven't written a custom module before don't be afraid to get stuck in its pretty easy. I'd highly recommend the Module Developer's Guide which will tell you everything you need to know.

---
Tags: blocks, theming
---


# Question
Title: Removing the dash/hyphen character from site search queries
I use Custom Search module 7.x dev.

When my visitors put a dash/hyphen into search keywords, Drupal can't find the results.

For example if they search for *Station1 Station2*, everything is OK, but if the keywords are *Station1-Station2* nothing can be found as result.
(Putting a "dash" makes sense for my visitors because they want to search for timetables from Station1 to Station2.)

String Overrides removes characters but I suppose that module doesn't solve this issue.

What solution can I adopt?

# Answer
You can probably do it with hook\_form\_alter() and str\_replace(). I'm not familiar with the Custom Search module, but seems like it's just altering Drupal's default search so you could make use of this:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'search_form':
    case 'search_block_form':
      array_unshift($form['#validate'], 'mymodule_search_validation');
      break;
  }
}

function mymodule_search_validation($form, &$form_state) {
  if (isset($form_state['values']['keys'])) {
    $form_state['values']['keys'] = str_replace('-', ' ', $form_state['values']['keys']);
  }
  elseif (isset($form_state['values']['search_block_form'])) {
    $form_state['values']['search_block_form'] = str_replace('-', ' ', $form_state['values']['search_block_form']);
  }
}

```

The above code adds a custom validation function to the search and search block forms where any existing dashes will be replaced by a space. The reason for using array\_unshift() and the form validation handler is to replace values early on for avoiding potential issues that could arise at later stages.
> 2 votes

---
Tags: search
---


# Question
Title: How can I create user profiles in drupal 7?
I would like to know how to create a user profile (registered user block) similar to the one on this site. I am using Drupal 7 and the Zen theme.

# Answer
> 6 votes
In Drupal 7, users accounts are fieldable entities like nodes. From *Administration » Configuration » People » Account settings*, you can add fields and configure their display on the user page (ie. /user/$uid).

For a more complex setting with multiple profile *types* and separation of accounts (ie. user) and profiles, you can use the Profile2 module.

You can then use Views to easily crate blocks and pages to list users and information from their profiles.

# Answer
> 2 votes
You can add fields to users like you can with content types, you can find it at admin/config/people/accounts/fields.

The fields will show up at account creation, edit and view.

# Answer
> 2 votes
you can use views to create a block with profile information and then show it on the user profile page, take a look at this example.

If you want more control over the layout you can also do a template override on the user-profile.tpl.php. Just copy it from /modules/users directory into your current theme directory and make changes there.

# Answer
> 2 votes
there is profile2 module or maybe profile lite, or you can use edit profile. or the Profile UX . I prefer Profile UX honestly.

For the view you can use Views, Display Suit ...

In Views you can create a block views and place it where you want, but if you wanna personalize it you need to use the Context module.

Also you can go "yourpage.com"/admin/config/people/accounts/fields and create some custom field for your profile and then go to "yourpage.com"/admin/config/people/accounts/display to customise how it looks.

But if you wanna override the drupal /user/ page you need ctool and the page manager that is a componet of ctool, there is a video tutorial here and there is a plugin module called Contextual Administration and the video tutorial is about how to use it (http://www.youtube.com/watch?v=R5gpUfAXrAg) his blog is (https://plus.google.com/u/0/107801555171748743621/posts)

---
Tags: 7, users
---


# Question
Title: Core forum hook_menu_local_tasks_alter() override
i'm trying to implement lightweight topic tracker for core forums (tracking new topics and comments on main forum view).

I'd like to override `forum_forum_load()` method, but core forums calls `forum_forum_load()` method inside of a `forum_menu_local_tasks_alter()` and besides my overridden `mymodule_forum_load()` and `mymodule_local_tasks_alter()` it'll still call core forums own `forum_forum_load()` method making 2x more queries (2 x Amount of forums, in this case 28x2).

I replaced forum load function call inside of `forum_menu_local_tasks_alter()` with my own function and seems like it's working just fine, but I don't want to mess with the core, so I'd know if there is other way to prevent that behaviour.

I tried some other forum extending modules and they all have exactly same problem.

# Answer
You're right in not wanting to mess with core; it makes things tricky when you're trying to update to a new version of Drupal. You have to maintain patch files which may break with new core code and it just gets messy.

Fortunately Drupal does provide a method to handle exactly what you're after.

In Drupal 7 hook implementations are alterable, so you can use `hook_module_implements_alter()` to stop `forum_menu_local_tasks_alter()` from ever running:

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_local_tasks_alter') {
    unset($implementations['forum']);
  }
}

```

You'll need to copy the code from `forum_menu_local_tasks_alter()` and put it in your own `mymodule_local_tasks_alter()` function, and just replace the call to `forum_forum_load()` with the call to your `mymodule_forum_load()` function.
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: Drupal -> User error: Failed to connect to memcache server
I had someone install memcache for one Drupal project. Apparently we moved to another hosting. Upon completing the migration, the site is having issues with memcache.

Can someone guide me on how to remove the error? Please see below. I believe this is the right section for the topic, but if you find it inappropriate for this category, please feel free to move it. Thank you.

```
User error: Failed to connect to memcache server: 127.0.0.1:11211 in dmemcache_object() (line 415 of/home/searchpa/public_html/sites/all/modules/memcache/dmemcache.inc).

```

# Answer
You need to check how mem cached was run on your hosts. You can check this like so:

```
ps -Af | grep memcached

```

Check if it has -l 127.0.0.1 in arguments. If it is the case then just restart memcached with correct IP address instead of 127.0.0.1.
> 7 votes

---
Tags: caching
---


title: Extra collapsed fieldset on node form

text:
# Question
Title: Extra collapsed fieldset on node form
I have an extra collapsed input format fieldset on my node form. It above all other elements, appears unrelated to any fields, and I can't tell where it's coming from. Not sure how to investigate where the source is.

I'm guessing that the Multistep module is the cause, but I need to at least figure out what field the form is coming from.

# Answer
> 0 votes
Your first option is to simply inspect the html of the form, it should have identifying markup in the HTML which you can then use to grep all your modules for.

Your second option is to implement hook\_form\_alter and output $form to see which form is generating it and whether there are any identifying markers there. You can use kpr() to output the results of $form using the Devel module to get nicer looking output. You can also use hook\_form\_alter to remove the fieldset if you want.

---
Tags: nodes, forms
---


title: Check if cache is active

text:
# Question
Title: Check if cache is active
I would like to set some functionality in a module only on if caching is turned off.

Is there a way to check in code if caching is on or off?

# Answer
> 2 votes
The "Cache pages for anonymous users" setting is stored in the variable table (as a 0 or 1), you can get it like this:

```
if (variable_get('cache', 0)) {
  // Cache is turned on
}

```

If you're interested in the "Cache blocks" setting it's also in the variables table and you can get it like this:

```
if (variable_get('block_cache', 0)) {
  // Block cache is turned on
}

```

Just for reference the first is defined in `system_performance_settings()` and the second in `block_form_system_performance_settings_alter()`.

---
Tags: 7, caching
---


# Question
Title: Pass variables from html preprocess function to page preprocess function?
In my custom theme's `hook_preprocess_page()` and `hook_preprocess_html()` functions, I often need to identify the same information. Rather than essentially running the same if statement checks in both the identify the same info, it would make much more sense to just do it once in both of them and then pass that info to the other preprocess function. How can I do this? I tried the following but it didn't work:

```
function myTheme_preprocess_page(&$vars){
    $vars['myValue'] = 7;
}

function myTheme_preprocess_html(&$vars){
    //$vars['myValue'] should equal 7...
}

```

I also tried it the other way around (setting the value in the preprocess html function and then retrieving it in the page preprocess function) but that didn't work either. Which brings up a related question: in what order are these preprocess functions, er, processed? It seems to me that the page preprocess function comes before the html one, is that correct?

# Answer
> 14 votes
You're going to need either a `global` or `static` variable to accomplish this...personally I'd recommend going with `static` and implementing a generic helper function using Drupal's static pattern like so:

```
function _myTheme_var($var_name, $new_val = NULL) {
  $vars = &drupal_static(__FUNCTION__, array());

  // If a new value has been passed
  if ($new_val) {
    $vars[$var_name] = $new_val;
  }

  return isset($vars[$var_name]) ? $vars[$var_name] : NULL;
}

function myTheme_preprocess_page(&$vars){
  $vars['some_var'] = _myTheme_var('my_var', 7); // Set the value and retrieve it
}

function myTheme_preprocess_html(&$vars){
  $vars['some_var'] = _myTheme_var('my_var'); // Get the value
}

```

The `$vars` arrays for each preprocess function are completely different objects in memory so you won't be able to use that array to pass things around. I've seen this sort of pattern used a lot in Drupal core so I think it would be the best way to go.

**EDIT**

Oh and yes, `hook_preprocess_page()` is called before `hook_preprocess_html()`...as far as I'm aware Drupal works in a sort of "inside-out" manner so `hook_preprocess_html()` would probably be the last one that's run in a page build.

# Answer
> 3 votes
I accomplished this with a similar case of 'node' and 'page' by doing:

```
function mymodule_preprocess_node(&$vars) {
  _mymodule_preprocess_vars($vars,'node');
}

function mymodule_preprocess_page(&$vars) {
  _mymodule_preprocess_vars($vars,'page');
}

function _mymodule_preprocess_vars(&$vars, $where) {

  // all vars common to both node and page set here

  switch($where) {

    case 'node':

      // node only vars set here;

      break;

    case 'page':

      // page only vars set here;

      break;
  }
}

```

so I'd imagine it would work similarly with 'page' and 'html' instead.

---
Tags: 7, theming
---


# Question
Title: Prepopulating a multi-select on a webform
I have a webform with a multiselect box. I want to use the prepopulate module to allow people to set the default value in the URL. The following works, but it only supports selecting one value:

/mywebform?edit\[submitted\]\[multiselect\_name\]=Value

Other places have suggested using URLs like the following, but that doesn't work for either one URL or multiple:

/mywebform?edit\[submitted\]\[multiselect\_name\]\[\]=Value

When I pass multiple URL parameters, it just takes the last one, so Value2 is selected in the following example rather than Value and Value2:

/mywebform?edit\[submitted\]\[multiselect\_name\]=Value&edit\[submitted\]\[multiselect\_name\]=Value2

As a workaround, I could define custom GET parameters for each item in the webform using the webform module, but I was hoping to make everything consistent, and as far as I can tell, webform doesn't support GET parameters that use array notation (as per http://drupal.org/node/824606), so neither of the following works as the default in the webform module:

%get\[edit\]\[submitted\]\[multiselect\_name\]
%get\[edit\[submitted\]\[multiselect\_name\]\]

Thanks for the help!

# Answer
> 0 votes
I have just read through the code of Prepopulate module, and it seems that as for now it doesn't support the feature you're after. The prepopulate module just assigns whatever is passed as a parameter to #value of the corresponding form element. To have multiple items selected you need to assign to #value something like this: array('Value 1', 'Value 2'); but there is no way you can pass this via parameters.

THe possible workaround is to hack the module code. Add the following code on the line #78 of the file - prepopulate.module

```
  if($form['#type'] == 'select' && $form['#multiple'] == TRUE) {
    $requestslice = explode(',', $requestslice);
  }

```

just before this line:

```
  $form['#value'] = $requestslice;

```

This change will allow you to pass multiple values as a comma separated list, for example:

```
  mywebform?edit[submitted][multiselect_name]=Value1,Value2

```

I have just created a patch for for the prepopulate module that implements this thing, you can find it here:

http://drupal.org/node/1468024

---
Tags: 7, webforms
---


title: Tab on user page doesnt show up

text:
# Question
Title: Tab on user page doesnt show up
I dont know what i doing wrong but for reasons the tab on user page doesnt appear! i have like three tabs which i place my self in custom module and they ok.. But now trying to use the principle i used nothing works. below is my code! Any suggestions?

```

$items=array();

$items['user/%user/mysite-news'] = array(
'title' =>t('Мой Новости'),
'description' => t('yo news.'),
'page callback' => 'mysite_news',
'page arguments' => array(1),
'access callback' =>array('view kupon'),
'type' =>MENU_LOCAL_TASK,
);
$items['user/%user/mysite-news/my-news'] = array(
'title' =>t('Мой Новости'),
'description' => t('see your news.'),
'page callback' => 'mysite_news',
'page arguments' => array(1),
'access callback' => TRUE,
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight'=>-15,
);

//and my call back function
function mysite_news($account){
  $my_name=t('my name is $c',array('$c'=>$account->name));
return $my_name;
}
?>

```

if i visit the link user/1/mysite-news/my-news

the result is displayed, "my name is admin". But the tab doesnt show on user page.. please help.

# Answer
> 1 votes
You don't define the `'page callback'` for the `MENU_DEFAULT_LOCAL_TASK` since it is taken care of by the 'root' page, plus without any additional tabs it won't show up anyway. If you add another `MENU_LOCAL_TASK` it should show up. You can think of the default local task as the page itself, there would be no reason for a VIEW tab there without anything else like EDIT UNPUBLISH etc.

---
Tags: users, 7, routes
---


# Question
Title: #required attribute not letting me to redirect a drupal 7 form
I have a form with 2 buttons. One is a submit button and another is a simple button when clicked, the page has to be redirected to another page.(I mean the user has to be redirected even if he hasn't filled in the entire form)

So after the submit button I put the following code for the other element

```
<?php
$form['health_calorie_consume']['view'] = array(
          '#type'=>'button',
      '#value'=>'View stats',
    '#validate'=>array('mymodule_form_view'),
     );
?>

```

inside the mymodule\_form\_view() function, I put the below code,

```
<?php
function mymodule_form_view()
  $form_state['redirect'] = 'http://localhost/d7/?q=node/3';
?>

```

To my surprise, Thhe function gets called but its not redirected..! and shows errors that some of the form fields with `#reuired` attribute haven't been filled out..! I tried using `drupal_goto()`function, it redirects to the other page properly but even in the redirected page those, "required" errors show up..!!

I even tried making #required attributes FALSE, inside the `mymodule_form_view()`and yet it didn't work.

So how to solve this problem..??

# Answer
> 0 votes
You can use: #limit\_validation\_errors to skip validation:

```
$form['health_calorie_consume']['view'] = array(
  '#type'=>'submit',
  '#value'=>'View stats',
  '#limit_validation_errors' => array(),
  '#submit' => array('mymodule_form_view'),
);

```

Your `mymodule_form_view` function needs fixing also like mechler pointed out. Besides passing it `$form` and `$form_state` variables you may want to use the url() function for building the redirect url.

```
function mymodule_form_view($form, &$form_state) {
  $form_state['redirect'] = url('node/3', array('absolute' => TRUE));
}

```

# Answer
> 0 votes
Modifying $form\_state requires passing it by reference to the function.

```
function mymodule_form_view(&$form, &$form_state) {
  $form_state['redirect'] = 'http://localhost/d7/?q=node/3';
}

```

---
Tags: 7, forms
---


# Question
Title: Alternative ways to group results of a view by CCK field?
I have cck content type with a variety of fields - video, taxonomy of terms, images, etc - in drupal 7, core 7.8. Unfortunately, I'm unable to group the results of the page view by a cck field by simply filtering and changing format settings by Group Field - UNLESS, I update my Drupal Core (tested w/ 7.12 and works easily). I am, however, able to group via using content: post date.

I've read through several answers on stack-xchg, ie. Grouping a View by Custom Field \- but didn't really find an alternative way to group fields in the event I am not permitted to update core or modules.

Is there a way I can group fields by cck field via code? Thanks,

# Answer
You can do almost anything you want within a views template. If you look at the Theme Information in the View UI, you can see what you can modify, or just cd into modules/views/theme and take a peek at them. But, given that the $view variable is available to almost if not all of the templates (whether or not the comments say it is), and $view-\>result is an array of row values of the view, you can certainly foreach() through it and do whatever you want. Otherwise, you have the whole gamut of preprocess() hooks, views\_pre\_render() of which is probably most of interest here.
> 2 votes

---
Tags: views
---


title: Site synchronization with aliases

text:
# Question
Title: Site synchronization with aliases
I configured the site aliases for the development, and staging sites. I have the `<DRUPAL_HOME>/sites/default/aliases.drushrc.php` aliases file with this content:

```
$aliases['dev'] = array(
  'root' => '/home/drupaltest',
  'uri' => 'localhost',
  'path-aliases' => array('%dump' => '/home/drupaltest/dump.sql')
);

$aliases['stage'] = array(
  'root' => '/home/drupaltest',
  'uri' => 'naftalin',
);

$aliases['all-scratch'] = array(
  'site-list' => array('@dev', '@stage'),
);

```

`drush @dev status` outputs:

> hubidubi@couscous:/home/drupaltest$ drush @dev status Drupal version : 6.25
> Site URI : localhost
> Database driver : mysqli
> Database hostname : localhost
> Database username : root
> Database name : drupaltest
> Database : Connected
> Drupal bootstrap : Successful
> Drupal user : Anonymous
> Default theme : garland
> Administration theme : garland
> PHP configuration : /etc/php5/cli/php.ini
> Drush version : 4.4
> Drush configuration :
> Drush alias files : /home/drupaltest/sites/default/aliases.drushrc.php Drupal root : /home/drupaltest
> Site path : sites/default
> File directory path : sites/default/files

Then I tried to run `drush rsync @dev @stage` command to sync dev site to stage and I get:

> Could not evaluate source path @dev.

I can't figure out the problem; I think the alias file is correct.

Do you have any idea?

# Answer
The drush rsync command does not bootstrap your site, so it cannot find your alias files. Move your alias files to a global location (e.g. $HOME/.drush).

Also, since @dev and @stage are multisites with the same document root, it does not make any sense to rsync from one to the other, because they share the same files. You might want to `drush rsync @stage:%files @dev:%files`.
> 2 votes

---
Tags: drush
---


# Question
Title: Programming a custom redirect in a Drupal Site
I would like to know what is the best option to setup a Drupal redirect process that will look at the current time of day and then redirect the user to a page based on this information?

Since I have not had to do this before in Drupal, I'm looking for one or two suggestions on how to do this with the user starting the action from a menu item.

One thought I had is that I could create a page that is PHP content and determine the redirect there, but I'm unsure of how to code that in that location.

Also, I'm not sure if I've overlooked a module that could help with a conditional redirect or if all the references to form redirects might be applicable to what I'm trying to do.

# Answer
You could do something along the lines of this:

```
function MYMODULE_menu() {

  $items['MYMODULE/whattodo'] = array(
    'title' => 'Where should I go now, George',
    'page callback' => 'MYMODULE_whattodo',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function MYMODULE_whattodo() {

  $foo= // code to get the current time of day in whatever form you want that matches the switch cases below

  switch($foo) {
     case // morning:
        drupal_goto(// page for the morning);
        break;
     case // afternoon:
        drupal_goto(// page for the afternoon);
        break;
     case // evening:
        drupal_goto(// page for the evening);
        break;
  }
}

```

which means when a user went to www.mysite.com/MYMODULE/whattodo, they would be redirected to whatever page you set up via `drupal_goto()`
> 4 votes

---
Tags: routes, redirection
---


# Question
Title: Does drush support everything I can do with web admin interface?
I have just learned about Drush. Its great command-line tool. With two words, I can update drupal code within seconds.

I want to know whether I can do everything I do with web admin interface or not?

# Answer
No, you can't. That's not possible.

Every command needs to be explicitly provided to Drush. Many contrib modules now come with integrated drush commands, for example Devel generate, Features, Views, XML Sitemap and so on.

To see the list of commands that are available to you, call `drush help`. You can get detailed help on each command with `drush help <command>`.
> 3 votes

---
Tags: drush
---


title: bartik css clone

text:
# Question
Title: bartik css clone
I have a Drupal site that uses the Bartik theme, under the `/users` directory.

For the sake of consistency, I'm looking to convert Bartik to a basic non-Drupal CSS theme that I can use on the `/` folder. I only need the header and nav bar.

Anyone ever see anything like that?

# Answer
Keep in mind that if you modify Bartik, the modification itself must also be GPLv2 or later. If your use case permits this, then read on...

Honestly, your best bet is to use something like Firebug to see which stylesheets are being added and how selectors are being applied. You would then use the same templates, tags, classes, IDs and CSS rules as Bartik does to duplicate the results, adapting where necessary from there. Drupal themes tend to use classes and IDs extensively, so it probably won't be "CSS only" - your markup does matter. That said, while Drupal themes are obviously meant to work with Drupal, they could be easily adapted for other purposes.
> 3 votes

---
Tags: 7, theming
---


# Question
Title: Set Update Manager to install to sites/all/modules/contrib?
I am able to use Update Manager to install new modules, instead of having to manually upload them. I previously put everything in `sites/all/modules`, but now have reorganized my modules into `sites/all/modules/contrib` and `sites/all/modules/custom` (for the modules I write or modify).

However, Update Manager is still installing new modules in `sites/all/modules`. Is it possible to tell Update Manager to install new modules in `sites/all/modules/contrib` instead? I looked for a setting somewhere, but can't find one (D7).

# Answer
> 1 votes
To circumvent these (and other) issues, I typically use the Drush command line utility to install and update new modules instead of the Update Manager.

For instance:

```
drush dl views --destination='sites/all/modules/contrib' # Download views to this path
drush dl uuid --destination='sites/all/modules/contrib' --select # Select other releases
drush en views views_ui  # Enable Views and Views UI
drush up ctools          # Update CTools

```

Drush also provides a number of other useful commands, and integrates very nicely with other modules. I highly recommend looking into using it if you haven't already!

---
Tags: updating
---


# Question
Title: Trying to override the default taxonomy behavior, from a module
Tried to catch the routes used for taxonomy display, didn't work, which leads me to believe that I'm not taking the right approach.

```
  $items['taxonomy/term/%'] = array(
  'title' => 'Activities',
  'page callback' => 'activities_route',
  'page arguments' => array(1),
  'access arguments' => array('access content'),

```

I'm using aliases which is why i'm trying to catch the system path.

My ultimate goal is to assemble & display three views into one page, based on the vocabulary of term that is passed in. Some views are shared, while others are separate and only need to be returned for a specific vocabulary.

I'm a PHP dev, but still learning about the Drupal stack.

# Answer
Don't implement hook\_menu() to override menu items of other modules. Implement hook\_menu\_alter() for that.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Create different user profiles with drupal 7
There are two user profiles, landlord and tenant. Both require different user role as well as different registration data.

Now tenant can search through landord's profiles and comment / rate on them as well.

How can I achieve this in drupal 7

# Answer
> 1 votes
In D6 we can create each node type for each type of profile and use hook\_form\_alter() to make thing happen. In D7 we can still do the same.

But I guess there is no contrib module for that.

# Answer
> 3 votes
I don't know if you are still interested or not. I've got the same problem and I solved in this way:

1. In the User account you can put an option "Tenant" - "Landlord".
2. Then use the Rules module to create a rule that gives automatically the role dependent on the option chosen.

Or you can also redirect straight to the edit profile after the registration.

# Answer
> 2 votes
You can achieve this by using Profile2 module.

> Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields!

# Answer
> 1 votes
The features list for Profile2 include "*Optionally, profile forms are shown during user account registration.*". If it is not working, then it is either a missing documentation, a bug or a not-yey-implemented feature. In all cases, the issues queue for Profile2 is the place to look for help.

Check also if Profile2 is needed at all. You can directly add fields to users in Drupal 7, Profile2 is only needed when you want/need profiles and users to be separated entities, or several profiles (of different kind) for a single user.

If the *user profiles* are not bound to site users, then why not use nodes and a dedicated content type?

# Answer
> 0 votes
there is profile2 module (http://drupal.org/project/profile2) or maybe profile lite (http://drupal.org/project/profile\_lite) , or you can use edit profile (http://drupal.org/project/edit\_profile). or the Profile UX (http://drupal.org/project/pux.)

but you need the module field permision http://drupal.org/project/field\_permissions, just select the permision of the field for each role and its all.add the fields at the same profile ,but make diferente permisions for each role ,

---
Tags: 7, users
---


# Question
Title: Search based on user profiles in Drupal 7
I want to develop user matching feature on website. A user will search by giving some search criteria (like we give search criteria in dating / real estate website to filter out search results), and system after, filtering out, will return the users matching that search criteria.

How can it be accomplish in Drupal 7 ? Is there any module or combination to modules to achieve that goal ? Thanks in advance.

# Answer
Searching with Drupal core is not very performative because you are doing search queries in a mysql database.

Apache Solr is much more performative and includes a much greater feature set for searching Drupal content: http://drupal.org/project/apachesolr

If you want to limit search results just to users you can use the solr module above plus Facet API http://drupal.org/project/facetapi and only expose the facets for the content authors. You can also create a view using Solr Views that will return the author in the search results.
> 1 votes

# Answer
You can create a view of youe users and expose the desired search criterias. This gives you all you need to search for users. This works even with User defined user fields.
> 1 votes

# Answer
maybe the search api http://drupal.org/project/search\_api, and here is the tutorial http://vimeo.com/15556855 about how to setup the api .

i think yo need also http://www.slideshare.net/darrenmothersele/active-tags-and-taxonomy-views-drupal-drop-in-november-2010 here you can find the way to mix taxonomy , views and active tags.
> 1 votes

---
Tags: users, search
---


# Question
Title: views_get_view() returns an outdated view version
I created a view setting *Items per page* to 10. `views_get_view()` shown ten nodes.

I have since changed the view and set *Items per page* to unlimited, and cleared the cache. `views_get_view()` still shows ten nodes.

The preview of that view shows more than ten nodes, so the view works as expected, but it uses only the *Default* display.

I also tried calling `views_get_view()` passing `TRUE` as second argument, which is supposed to ignore the cache. It did not change the number of nodes shown by `views_get_view()`.

How can I correctly show that view?

# Answer
`views_get_view('some_view')` doesn't actually execute the View, it just retrieves the specification for the View.

How are you executing the view?

From the comment on your question, I see that you're doing:

```
$view = views_get_view('some_view');
$view->execute();
print_r($view);

```

On this thread, merlinofchaos (the primary author of Views) recommends the following sequence:

```
$view = views_get_view('some_view');
$view->init_display();
$view->pre_execute();
$view->execute();
print_r($view);

```

which is roughly equivalent to this:

```
$view = views_get_view('some_view');
$view->preview();
print_r($view);

```

...except that the later also renders the view as HTML, which, if you're not going to use that rendered HTML, is wasteful.
> 2 votes

---
Tags: views, 6
---


title: CCK counterpart for user's profiles?

text:
# Question
Title: CCK counterpart for user's profiles?
Im looking for a module that allow to add fields to users profiles, with the same functionality and flexibility of CCK for nodes; I've actually activated the profile module, but the fields type doesnt fit my needs.

For example, i need to have a node reference field on my users (for nodes that they belongs to - follow), but in general, profile's fields doesnt allow multiple values at all..

I've tryed content profile module, i guess will be my last choice, i dont like to have the user profile and the profile node as two separate entities.. and look a bit overlìkill for me.

Any idea?

# Answer
> 2 votes
For Drupal 6, these are the only two options I know of, either use content\_profile and use aditional nodes or stick with what profile.module can do.

In Drupal 7 however, users are fieldable, which means that you can attach any field that you can attach to nodes too. Additionally, there is the http://drupal.org/project/profile2 project, which provides something similar to content\_profile. However, profiles are in that case not nodes but a custom entity.

# Answer
> 2 votes
You can try Advanced Profile kit module..

# Answer
> 0 votes
you can go "yourpage.com"/admin/config/people/accounts/fields and create some custom field for your profile and then go to "yourpage.com"/admin/config/people/accounts/display to custumise how it looks in drupal 7 ,also use http://drupal.org/project/pux to setup how it will look like.

in drupal 7 you can use the number of values that you want (http://drupal.org/node/1312562 just to illustrate ) for each field when you edit the field in manage fields tab. also if you wanna put together some fields use field collection http://drupal.org/project/field\_collection. here you can find the video tutorial how it works. http://droplabs.net/video/field-collection-in-drupal-7.

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


# Question
Title: How can I do "Buy one get two free" with Ubercart?
For example the firs item is $3 and the second one & the third one are $0. Can I do this? Maybe Ubercart Discounts (Alternative) can do the result but I don't want to show the discount price and just want to show the second and the third item $0 on the cart page.

# Answer
> 0 votes
I found the solution using Ubercart Custom Price module and the code below.

```
// Load the current shopping cart.
      $items = uc_cart_get_contents($cid = NULL, $action = NULL);

    // Count the number of items
      $number_of_items = count($items);

    $firstPrice = 10;
    $secondPrice = 0;
    $thirdPrice = 0;

    switch ($number_of_items) {
      case 0:
        $item->price = $firstPrice;
        break;

      case 1:
        $item->price = $secondPrice;
        break;

     case 2:
        $item->price = $thirdPrice;
        break;
    }

```

---
Tags: 6, ubercart
---


title: create tabs inside nody body

text:
# Question
Title: create tabs inside nody body
I want to create tabs inside the node body and so I found the yui\_tabview module but it only works in Drupal 6. Anyone know a module that works for Druapl 7?

# Answer
Drupal has jQuery UI tabs built right in so you'd be better off leveraging that if possible. This is a standard theme function I chuck into most projects to help with this sort of thing:

```
function theme_tabs($vars) {
  if (empty($vars['items'])) {
    return '';
  }

  $js_added = &drupal_static(__FUNCTION__, FALSE);
  static $delta = 0;

  if (!$js_added) {
    drupal_add_library('system', 'ui.tabs');
    drupal_add_js("jQuery(document).ready(function(){ jQuery('.tabs-container').tabs(); });", 'inline');
    $js_added = TRUE;
  }

  $tabs = $content = '';
  foreach ($vars['items'] as $key => $item) {
    if (isset($item['#access']) && !$item['#access']) {
      continue;
    }

    $tabs .= '<li><a href="#' . $key . '-tab-' . $delta . '">' . $item['title'] . '</a></li>';
    $content .= '<div id="' . $key . '-tab-' . $delta . '">' . render($item['content']) . '</div>';
  }

  $delta++;

  return '<div class="tabs-container">' ."<ul>$tabs</ul>$content</div>";
}

```

You would call it like this:

```
$tabs = array(
  'tab1' => array(
    'title' => 'Title for tab 1',
    'content' => 'Content for tab 1' // Note this can be a string or standard Drupal render array
  ),
  'tab2' => array(
    'title' => 'Title for tab 2',
    'content' => 'Content for tab 2'
  ),
  // etc.
);

$args = array('items' => $tabs);
print theme_tabs($args);

```

Of course if you're doing this 'properly' you would register the theme function in a module like so:

```
function MYMODULE_theme() {
  return array(
    'tabs' => array(
      'variables' => array('items' => array())
    )
  );
}

```

and call it like this instead:

```
print theme('tabs', array('items' => $tabs));

```

Hope that points you in the right direction.
> 3 votes

# Answer
There's also the Quicktabs module

Are you aware of drupalmodules.com?
> 1 votes

---
Tags: routes, blocks
---


# Question
Title: Additional form validation only after passing default validation
In Drupal 6.25.

I am building a custom user registration form that needs to run some actions on an external service after properly passing default form validation but before creating a new user record in Drupal. So far I am doing the following:

```
function mbrusers_form_alter(&$form, &$form_state, $form_id){
   if($form_id == "user_register"){
       if($default_form_validation_passed){
           $form['#validate'][] = 'mbrusers_infusionConnect_validate';
       }
   }
}

function mbrusers_infusionConnect_validate($form, &$form_state){
    // Run actions on external service
    if($error){
        form_set_error("", "SET ERROR");
    }
}

```

I feel like I'm overlooking something, but I haven't been able to figure out what to do. Maybe using validate is the wrong idea? Any help that sets me in the right direction is appreciated.

# Answer
> 1 votes
You should be able to rearrange the order of multiple validation functions in the `$form['#validate']` array. After ensuring that your function runs in the correct order, wrap your code acting on your service in an if statement checking for existing form errors using form\_get\_errors(), like so:

```
// Validation has already failed if prior functions return errors, so this is safe.
if (empty(form_get_errors())) {
  // Run calls on external service here...
  if($error){
    form_set_error("", "SET ERROR");
  }
}

```

Since you need to validate the response from your service, doing it in the validation phase makes the most sense.

# Answer
> 1 votes
I'm pretty sure you have to re-arrange the order of the validators, and inject yours basically in the middle instead of just adding it at the end.

From user.module, `$form['#validate'] = user_login_default_validators();` or:

```
/**
 * Set up a series for validators which check for blocked/denied users,
 * then authenticate against local database, then return an error if
 * authentication fails. Distributed authentication modules are welcome
 * to use hook_form_alter() to change this series in order to
 * authenticate against their user database instead of the local users
 * table.
 *
 * We use three validators instead of one since external authentication
 * modules usually only need to alter the second validator.
 *
 * @see user_login_name_validate()
 * @see user_login_authenticate_validate()
 * @see user_login_final_validate()
 * @return array
 *   A simple list of validate functions.
 */
function user_login_default_validators() {
  return array('user_login_name_validate', 'user_login_authenticate_validate', 'user_login_final_validate');
}

```

and

```
/**
 * A validate handler on the login form. Check supplied username/password
 * against local users table. If successful, sets the global $user object.
 */
function user_login_authenticate_validate($form, &$form_state) {
  user_authenticate($form_state['values']);
}

```

so I'd do something like:

```
$form['#validate'] = array('user_login_name_validate', 'mbrusers_infusionConnect_validate', 'user_login_authenticate_validate', 'user_login_final_validate');

```

instead of `if <Default form validation passed>` so that your validation function is called before the normal/usual second validator.

# Answer
> 1 votes
Another way to achieve your functionality I reckon is to use hook\_user and trap $op = 'insert' to do something before the user account is added to the Drupal database.

---
Tags: 6, forms
---


title: Translation of modules

text:
# Question
Title: Translation of modules
I am using Drupal 7.9 and Webform 3.15. I need to translate **-select-** option on top of list box. Also I have to translate in Captcha module (7.x-1.0-beta2), the text **What code is in the image?** and **Enter the characters shown in the image**. How can do this?

How can I translate modules to required language?

# Answer
You have to switch on the Locale module, which is part of Drupal core. There you can search for the strings you want to translate.

If you want to translate an entire module from scratch, I suggest that you read about translation on drupal.org and make yourself familiar with the toolchain. It's fairly straightforward.
> 3 votes

---
Tags: webforms, i18n-l10n, captcha
---


# Question
Title: dreamhost VPS returns a lot of blank pages
After upgraded from shared hosting to VPS (for more memory), my site returns a lot of blank pages, for example:

* plain `/update.php` is OK, but returns blank page after clicking `Continue` and `Update`
* plain `/admin/reports/status` is ok, but `/admin/reports/updates/check?destination=admin%2Freports%2Fstatus` returns blank space

php `memory_limit` is now 512M.

Any dreamhost user shares some experience?

# Answer
I would check PHP error reporting on the server : usually, WSOD are caused by hidden PHP errors. A value of `E_ALL & ~E_NOTICE` is usually fine, at least for development.
> 1 votes

---
Tags: 6, wsod
---


# Question
Title: Views 3: template suggestion file for header/footer parts?
In Views 3, is there any type of template suggestion for header and footer parts of a view?

I know I can paste Full HTML into Global Header and Footer fields, but - as I have the main part themed in a tpl file - I'd also find it more comfortable to have the header/footer parts laid out in an external text file.

# Answer
There's no template that I know about, but nothing can stop you from overriding the header and footer values in a view's general template like `views-view.tpl.php`, or even include a separate file instead of outputing the variable directly.
> 2 votes

---
Tags: views, theming
---


title: Views: Show either field a or field b

text:
# Question
Title: Views: Show either field a or field b
I'm trying to find a way to get a view to display either field\_a or field\_b. For example I have to different image fields that are being rendered differently on the full node display, both of which are optional. Now I'd like to be able to show one of those pictures in my list view, either picture 1, or, if that's not present, picture 2, but never both.

Is there any smarter way to achieve this than to put the logic into a views fields template?

# Answer
> 1 votes
> put the logic into a views fields template

If it's a "one-off", most of the time, that's the way I would have gone about it. Display the "primary" field, exclude the seconday. Template the primary to display the second as necessary.

At a recent project, I "was just going to do this once", but then the client started changing their mind, and now I have a really big mess of views templates. If I knew that I would have a lot of logic like this, I would use a Views Context display instead, pull that into Panels, and have the Page manager handle the display logic instead. More complicated, but also neater IMO, and easier to maintain, as the logic becomes independent of the presentation.

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


# Question
Title: Why am I getting a "page not found" error for this implementation of hook_menu()?
Here's the implementation of `hook_menu()` in my theme, "myTheme":

```
function myTheme_menu() {
    $items = array();
    $items['ajax'] = array(
        'title' => 'AJAX',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    $items['blog'] = array(
        'title' => 'sonia blog',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}

```

example.com/ajax is working fine, but example.com/blog is returning me a "page not found" error. I have cleared my cache.

Do you have any idea about what is going wrong?

**EDIT**
One of the commenters suggested that I need a `page_callback` property. However, the documentation on `hook_menu` does not say that it's required. Regardless, I tried adding this callback but still no luck. Here's the code with it:

```
function myTheme_menu() {
    $items = array();
    $items['blog'] = array(
        'title' => 'sonia blog',
        'access arguments' => array('access content'),
        'page callback' => 'myTheme_callback_blog',
        'type' => MENU_CALLBACK
    );
    return $items;
}

function myTheme_callback_blog(){
    return '';
}

```

# Answer
I believe you cannot define a `hook_menu()` implementation in a theme; it should be defined in a module.

When you make changes to a `hook_menu()` implementation, you need to ensure that you rebuild the menu router, as well. To that end you can manually look at your database's "menu\_router" table to see if the callback is being registered.
> 4 votes

# Answer
You are trying to implement these in a theme, which will not work; you need to add these in a module.

See How to use hook\_user\_login and hook\_user\_logout to output content to the page.
> 0 votes

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


title: Use AJAX without writing a module - D7

text:
# Question
Title: Use AJAX without writing a module - D7
I want to use ajax to load some html from a php file. I don't want to write a module. So, here's the thing I did:

In `sites/all/themes/mytheme/js/myjs.js`:

```
$('#color_main_id a').click(function() {
  $.ajax({
    url: "get_node_details.php",
    type: 'GET',
    cache: false,
    // data: nid <--- Question#1
    data:  "color=" + this.rel,
    success: function(data, status, jqXhr) {
      $('.product-summary').html(data);
    }
  });
});

```

In `sites/all/themes/mytheme/js/get_node_details.php` I wrote some code to get a node detail with `entity_load` and `field_view_field`.

Here's the questions:

1. How can I pass the current node id from my js function in js file to php function in php file? (See the comment above)
2. In `get_node_details.php` I've got `Call to undefined function entity_load()`. How can I solved this?

Thanks

# Answer
> 5 votes
I'm sorry to say but, **you are doing it wrong**.

In some very few cases it could be worth not to write a module for an ajax request. The reason would be that you want to do something simple, not related to Drupal that needs to be very fast. I did this once for a site where I needed to look up if a domain name was registered or not.

In this case you are not isolated from Drupal. You need to know the context of your script (The node id) and you need to use the Drupal API's `entity_load`, so instead of creating a custom PHP file and writing code in there, why not create a module which is a PHP file, only it's named `foo.module`, use the drupal API's to in make the ajax callback `hook_menu`, and add the javascript with context `drupal_add_js` and you will save yourself a lot of work, by doing things the Drupal way. Drupal is made it make it easy to develop stuff by creating modules, instead of adding custom PHP files, which makes things a lot more difficult to manage.

If you really wanted to do this without creating a module, you would need to bootstrap Drupal in your custom PHP file (making it pointless to use a custom php file), and add the node id in the `preprocess_node` hook in your theme.

---
Tags: 7, ajax
---


title: Admin Block Page Custom Theme

text:
# Question
Title: Admin Block Page Custom Theme
I am trying to use the garland theme on the blocks page rather than using my custom theme.

I have found this question: Force block page to use admin theme?

Which has given me a code snippet to use. I have placed this in the modules/block/block.admin.inc file on line 36.

The theme is still my custom theme and i must be doing something wrong. If possible i would rather not use a module.

The code i am using:

```
function mytheme_init() {
  // Hardcode the administration theme onto the blocks page
  if ($_GET['q'] == 'admin/build/block') {
    global $custom_theme;
    $theme = 'garland';
  }
}

```

Thanks!

# Answer
FYI it's a REALLY bad idea to hack core. Firstly, God knows what could break, and secondly..whatever changes you make will likely be over-written if/when you update core.

To answer your question, you're calling the $custom\_theme as you should, but then assigning a Garland to `$theme`, which isn't used.

Try the following:

```
function mytheme_init() {
  // Hardcode the administration theme onto the blocks page
  if ($_GET['q'] == 'admin/build/block') {
    global $custom_theme;
    $custom_theme = 'garland';
  }
}

```

In your custom theme's `template.php` instead of in `block.admin.inc`. Make sure you change `mytheme` to whatever your custom theme's name is (e.g. `my_custom_theme_init` or `custom_init`).

You might also want to look at the Administration Theme module or the Themekey module for admin theme options/theme switching.

Themekey sounds like a pretty good bet for ease of use:

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules.

**EDIT**

I forgot, the Admin module also comes with an admin theme option, and a pretty decent admin menu for end users (clients etc.).
> 1 votes

---
Tags: 6, theming
---


title: Remove language code from URL

text:
# Question
Title: Remove language code from URL
For example, with example.com/en/apple/12/article/11/23, in `hook_init()` `arg(0)` returns "apple," as I expect; in `hook_boot()` it returns `en` which is language prefix of English.

# Answer
> 3 votes
That is because `hook_boot()` is invoked too early in the bootstrap process, which means:

1. Not all the modules are loaded, including the Locale module that is the one that alter the path, and the reason why `arg(0)` returns "apple" in your example, when called in `hook_init()`.
2. The language has not been set; it is initialized during the `DRUPAL_BOOTSTRAP_LANGUAGE` phase, while `hook_boot()` is invoked during the `DRUPAL_BOOTSTRAP_PAGE_CACHE` phase.
3. The call to drupal\_path\_initialize(), which alters `$_GET['q']` with `$_GET['q'] = drupal_get_normal_path($_GET['q']);` is done during the `DRUPAL_BOOTSTRAP_FULL` phase, which is the last bootstrap phase.

Differently, `hook_init()` is invoked as last step done in the `DRUPAL_BOOTSTRAP_FULL` phase, which means all modules are loaded, the language has been set, and `drupal_path_initialize()` has been already called.

As side note, `hook_boot()` has been removed from Drupal 8; if you are using it, you will need to change your code. Using `hook_init()` is a possible alternative, since it is still used in Drupal 8.

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


# Question
Title: How to send 2 mails simultaneously with drupal_mail()
I want to send my order to my email, and also to my client's email.

I am sending an order placed on my website using this code:

```
function MYMODULE_form_submit($form, &$form_state) {
  order_mail_send($form_state['values']);
}

```

This is the `order_mail_send()` code:

```
function order_mail_send($form_values) {
  $module = 'shop';
  $key = 'key';
  $to = $form_values['email'];

  $language = language_default();
  $params = array();
  $from = NULL;
  $send = FALSE;
  $message = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  $message2 = drupal_mail($module, $key, $from, $language, $params, $from, $send);

  $subject = 'Order Status';

  $message['subject'] = $subject;
  $message['body'] = array();

  $message['body'][] = "<h3>Your order: ".$form_values['first']." ".$form_values['last']."</h3>";

  // …

  // Retrieve the responsible implementation for this message.
  $system = drupal_mail_system($module, $key);

  // Format the message body.
  $message = $system->format($message);
  $message2 = $system->format($message2);

  // Send e-mail.
  $message['result'] = $system->mail($message);
  $message['result2'] = $system->mail($message2);

  if ($message['result'] && $message['result2'] == TRUE) {
    drupal_set_message(t('Your order has been sent. Thank you!'));
  }
  else {
    drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
  }
}

```
1. Now it sends the first email (`$message = $system->format($message);` but not the second one. How can I make it work?
2. How can I empy the cart values after sending the emails? The cart empties when I close the browser, but I want to delete it after sending as well.

# Answer
You can use CC to send a copy to admin/yourself
`$message['headers']['CC'] = "foo@gmail.com"`
> 4 votes

# Answer
Your code is not correct, as a module that calls drupal\_mail() doesn't then call drupal\_mail\_system(), but it implements hook\_mail(). An example of this hook implementation is contact\_mail(), which handles the emails sent from the Contact module in contact\_personal\_form\_submit(), and contact\_site\_form\_submit().

```
  // contact_site_form_submit()
  $values = $form_state['values'];
  $values['sender'] = $user;
  $values['sender']->name = $values['name'];
  $values['sender']->mail = $values['mail'];
  $values['category'] = contact_load($values['cid']);

  // Save the anonymous user information to a cookie for reuse.
  if (!$user->uid) {
    user_cookie_save(array_intersect_key($values, array_flip(array('name', 'mail'))));
  }

  // Get the to and from e-mail addresses.
  $to = $values['category']['recipients'];
  $from = $values['sender']->mail;

  // Send the e-mail to the recipients using the site default language.
  drupal_mail('contact', 'page_mail', $to, language_default(), $values, $from);

  // If the user requests it, send a copy using the current language.
  if ($values['copy']) {
    drupal_mail('contact', 'page_copy', $from, $language, $values, $from);
  }

  // Send an auto-reply if necessary using the current language.
  if ($values['category']['reply']) {
    drupal_mail('contact', 'page_autoreply', $from, $language, $values, $to);
  }

```

As also said from kantu, you can CC send the email to any other user that is not the receiver.
> 3 votes

---
Tags: emails
---


# Question
Title: how to insert a search form in custom content
I'm trying to insert a search form in the middle of some custom HTML on a Panel Page. There's already the Search Block on the page somewhere else. The Search Widget is available, but it gets inserted *after* the custom HTML, which is not what I want. I thought I could do something like
http://api.drupal.org/api/drupal/modules!search!search-block-form.tpl.php/7

```
<div class="container-inline">
<?php if (empty($variables['form']['#block']->subject)): ?>
<h2 class="element-invisible"><?php print t('Search form'); ?></h2>
<?php endif; ?>
<?php print $search_form; ?>
</div>

```

or

```
<?php
drupal_get_form('search_form');
?>

```

but the PHP doesn't seem to execute (naturally, I have PHP selected as the input.).

**Edit:** This produced a search form in the correct place, but the CSS conflicts with the existing Search Block.

```
<?php print render(drupal_get_form('search_block_form')); ?>

```

# Answer
I was close but needed to declare the variable. I still don't really understand what's happening here, but it works.

```
<?php global $search_form; print render(drupal_get_form('search_form')); ?>

```
> 3 votes

---
Tags: 7, search
---


# Question
Title: How to relate nodes by field, not title?
I'm using Feeds to import content from XML. The content is films and their showtimes, like this:

```
<film id=av1>
  <title>Avatar</title>
  <showtimes total="2">
    <showtime show_id="1" id="av1" date="1/1/2012" price="10" />
    <showtime show_id="2" id="av1" date="2/1/2012" price="15" />
  <showtimes>
<film>

```

Right now, I've created two content types (Film and Showtime) and using Node Reference (References module) to relate Showtime to Film. Then I have various views that use the relationship to show listings, date listings etc.

This works ok, but Node Reference can only link on node title, so if someone updates the film title in the source feed we get problems. It would be better to link using the ID field, which never changes.

The problem is that I'm using Feeds to import to two content types, so running two Feeds importers, and they have to use title from the source to sync. So say the Film title is changed in Drupal, then more Showtimes get added to the XML. On import, the new Showtime nodes are created but can't find their Film node. Using the ID field from the source would keep things joined up. Maybe using Field Collection instead of referenced content types is better?

Possible solutions:

* Use a taxonomy vocabulary and create a new term 'id' for each film. Then tag showtimes with the same term. I'm not sure this is a good use of taxonomy, creating single-connections in this way?
* See if Relation module provides linking by field. Probably won't work with Feeds yet.
* Create a single content type for films, and use Field Collection to store the showtimes. Then everything is connected in a single node. Not sure how feasible this is.

Any guidance or suggestions welcomed!

# Answer
> 2 votes
You are mistaken. Node reference uses the node id - the primary key for nodes to create the reference. The form element where you need to enter the node you want to reference, uses autocomplete to make it easier to find the node you want to reference, but the value stored is the node id. So there is actually no problem in using node reference and changing the title.

Code from the node reference module to illustrate this, can be found where the schema is defined for the field type it uses to create these reference:

```
/**
 * Implements hook_field_schema().
 */
function node_reference_field_schema($field) {
  $columns = array(
    'nid' => array(
      'type'     => 'int',
      'unsigned' => TRUE,
      'not null' => FALSE,
    ),
  );
  return array(
    'columns' => $columns,
    'indexes' => array('nid' => array('nid')),
    'foreign keys' => array(
      'nid' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
    ),
  );
}

```

---
Tags: 7, feeds, nodes, entities
---


title: Search for node to reference

text:
# Question
Title: Search for node to reference
I have a content type that has a reference field to another content type, call it "associated".

When editing the content, I'd like the user to be able to search for the "associated" entity to link to, for example using a view with a exposed filter.

Is there any combination of modules that will allow me to do this?

So i'm basically after a select widget that bring up a popup or something similar.

Thanks,

# Answer
The closest thing I know of, is the relation and relation select module combo. Relation select hasn't seen any development for quite a while, but you might be able to get where you want. It allows you to setup a view with exposed filters can be be used to selecting the node you want to reference.

This is Drupal 7 only.
> 1 votes

---
Tags: nodes
---