title: How to create multiple batch imports

text:
# Question
Title: How to create multiple batch imports
Ok I have been working with the batch API and I have one working successfully now I would like to run another batch after the first one.

batch\_set says I can do this:

```
array(
  array('my_function_1', array($arg1)),
  array('my_function_2', array($arg2_1, $arg2_2)),
)

```

I am trying this, but it isn't running the second function:

```
$batch['operations'][] = array('test_function1', array($new_node), array('test_function2'), array($new_node));
batch_set($batch);

```

Any ideas on how to run the second function?

# Answer
Using more than one function for a batch surely works, as one of the test functions for the batch API contains the following call.

```
batch_set(_batch_test_batch_3());

```

\_batch\_test\_batch\_3() contains the following code.

```
  // Ensure the batch takes at least two iterations.
  $total = 10;
  $sleep = (1000000 / $total) * 2;

  $operations = array();
  for ($i = 1; $i <= round($total / 2); $i++) {
    $operations[] = array('_batch_test_callback_1', array($i, $sleep));
  }
  $operations[] = array('_batch_test_callback_2', array(1, $total / 2, $sleep));
  for ($i = round($total / 2) + 1; $i <= $total; $i++) {
    $operations[] = array('_batch_test_callback_1', array($i, $sleep));
  }
  $operations[] = array('_batch_test_callback_2', array(6, $total / 2, $sleep));
  $batch = array(
    'operations' => $operations,
    'finished' => '_batch_test_finished_3',
    'file' => drupal_get_path('module', 'batch_test') . '/batch_test.callbacks.inc',
  );
  return $batch;

```

What is wrong in your code is how you set `$batch['operations']`.

The correct code is the following one.

```
$operations[] = array('test_function1', array($new_node));
$operations[] = array('test_function2', array($new_node));

$batch = array(
  'operations' => $operations,
);

batch_set($batch);

```
> 2 votes

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


title: How to set a POST data in value in FAPI

text:
# Question
Title: How to set a POST data in value in FAPI
I'm trying to port a working FAPI module from D6 to D7. I'm passing a POST value to the form and then assigning using :

```
 $link = check_url(substr($_POST['file_link'], 0, 300));
     $form['anu_download_file_link'] = array(
        '#type' => 'value',
        '#value' => $link,
      );

```

But when form is submitted the form is built again but this POST data file\_link is missing in the submit handler.

In D6 $form\['#cache'\]=true was working fine which avoided recreating of the form but now in D7 it does not seem to work.

How can pass POST values to the submit handler?

# Answer
> 0 votes
We need to use in D7 :

```
$form_state['cache'] = TRUE;
$form_state['no_cache'] = FALSE;

```

instead of

```
$form['$cache']=TRUE in D6

```

---
Tags: 7, forms
---


# Question
Title: How do I redirect users from Japan to a certain subsite?
I want users from Japan to be redirected to *www.example.com/test2* when they hit *www.example.com/test1*. In the menu only Test1 is visible.

What tools do I need? I tried to insert a PHP script into the header with the 'Add to Header' module, but for that I need the directory of the sites, which I do not have. I can also set Geo Rules, but then I have two sites with different URLs which are invisible and unaccessible for those excluded, but the 'Access denied' message is not preferable.

# Answer
> 1 votes
You can have country based redirection to any internal, or exernal path using the Context, Context GeoIP, and the Context Redirect modules.

# Answer
> 0 votes
try looking up in the .htaccess and do the changes, modify the rewrite rules..once you are in the .htaccess just go through the file once..you will understand as all is commented pretty nicely...

---
Tags: 7
---


# Question
Title: How can I display a node so that it appears as a regular page
When I am using Drupal through the standard user interface, and click on a node title, Drupal will show the content in the main content area and (depending upon permissions and configuration) will add some tabs between the title and the content. If comments are enabled for the node, a comment entry form will appear below the content field. The tabs and the comment form can be seen in the image below, with the text in red coming from the node fields that resides in the database.

I want to do the same programmatically from the inside of a module. I.e. I want to pull a node from the database, and then display it so that it looks the same as if I've clicked on its title in the user interface.

Here is a more detailed description of what I want to do: I am writing a *module* to display a node for the user. This module have a button ("Get info") that the user may click. When the user clicks the button, it module pulls various data from a number of external sources, does some processing of this data, and stores the results as a new node object in the database (all this already works).

However, I want to show this node object to the user that pushed the button as soon as it has been created (i.e. to avoid having the user click through a link in order to view it). The user experience I am after his that the user clicks on a "Get info"-button, and then *automatically* is shown the new node that has been created programatically as a result of this click.

The last bit (showing the user the newly created node) does not work. I am asking for help to get that part of this module right.

So far I've tried to use the following code (suggested here, but later deleted):

```
$node = node_load($nid);
$elements = node_view($node, 'full');
$full = drupal_render($elements);

```

This results in the follwing display on the page:

Note that there are no tabs ("View", "Edit", etc.) between the title and the content, and no comment form below. The blue "The title" is a hyperlink, i.e. it neccessary for a user to click through that hyperlink to get to a full node view with a comment form.

# Answer
> 1 votes
If its the path name you want different how about simply using Pathauto

If not - for setting the page title u should do a drupal\_set\_message() with $node-\>title and disable it in the node object.

I hope this is of some help.

**EDIT** Trying to be of help again

> '' *However, I want to show this node object to the user that pushed the button as soon as it has been created (i.e. to avoid having the user click through a link in order to view it)* ''

If it is one node at a time, since you are creating the node programmatically, how about redirecting the user to the node right after you create/save the new node?

# Answer
> 0 votes
Redirecting (suggested by SGosh) was the solution. The following single line of code does *exactly* what I want. After creating the node programmatically, I pull the `$nid` from the node object. Then:

```
drupal_goto('node/' . $nid);

```

will display it as a regular node.

---
Tags: 7, nodes
---


# Question
Title: WSOD while trying to install Drupal Commerce Kickstarter
I'm trying to install Drupal Commerce Kickstarter with core, but I cannot go past random WSOD, or hangs, to complete installation. WSOD happens randomly, but mostly after "Configure site" step. Very rarely I can reach "Installing additional functionality", but then it just stops at some point and won't move.

(At this point: )

I'm trying to install it on local apache2, and have 128M of memory\_limit, 1000 of max\_input\_vars, and 60 of max\_input\_time. If you need any more information, just ask and I will provide it. What can I do to complete installation?

# Answer
According to Commerce's docs http://www.drupalcommerce.org/commerce-kickstart-2/troubleshooting-kickstart-2-installation

RAM: minimum 128M, more is recommended because your server can fail with this memory if it is at all strained

Since the Commerce Kickstart 2 distribution can install an entire setup and configured working demo, the installation process requires a bit more sustained power. In our early beta tests, installations can sometimes silently fail when it uses close to your memory limit.

So, the answer is, "Scotty, we need more power!"
> 2 votes

---
Tags: 7, installation, commerce, wsod
---


# Question
Title: Authenticated users missing from users_roles table
I have created several authenticated users in my site through the `admin/people/create` interface. However, these users are not showing up in the `users_roles` table. Is this a known issue or am I doing something wrong.

When creating these users I used fake emails, so authentication emails where not received. However, I've turned off the "require email authentication option." Also, when using dpm() on a variable the contains all the users created from a `user_load_multiple` I can see that they have a `2` in the user role. So why is it not in the database?

# Answer
It is not an "issue" - but the authenticated user role is not registered in the `users_role` table. For this type of user, the status is determined by the field `status`in the `users` table.

AFAIK, *every* user registered in the `users` table is considered having the "authenticated user" role, so there is no need to explicitly register this role in the `users_role` table. Instead, users having this should have their status set to "blocked" when you want to "strip" them of any grants.
> 7 votes

---
Tags: users, database
---


title: responsive menu toggling module?

text:
# Question
Title: responsive menu toggling module?
I was curious after stumbling upon this particular construction of a responsive menu.

How was this responsive menu toggle menu created? is it via a module or just pure css / javascript?

http://picturefill7weblinc.h011.attiks.com/node/1

# Answer
It uses the Responsive Bartik theme. I can see from the CSS that it uses CSS media queries and from the project description that it uses JavaScript (Html5shiv, Respond.js and Selectivizr.js).
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Batch API passing data to finished function
I am creating a batch import and I would like to pass two different counts to my finished function. For example in my 'operations' function I check for an NID if it exists update the node if it doesn't then create it.

In my 'finished' function I want to do something like:

```
 batch_import_finished($success, $results, $operations) {
   if ($success) {
     $message ='Nodes created: '.$nodesCreated. '<br />';
     $message .='Nodes updated: '.$nodesUpdated;
   }
   else {
     $message = 'some errors';
   }

  drupal_set_message($message);
}

```

Hope this makes sense.

# Answer
> 13 votes
First, make sure you set the *finished process* in your batch process.

```
$batch = array(
      'title' => t('Merging content ...'),
      'operations' => array(
         array('batch_import_import', array($col1, $col2),  //Note we pass 2 variables here.
       ),
      'finished' => 'batch_import_finished', // set this!
      'init_message' => t('Connectng to the base site ...'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('An error occurred during processing'),
      'progressive' => FALSE
    );
...
batch_set('admin/content');

```

Then, in your worker function, you can take the last argument passed to it as $context.

For an example, from above example above, your worker function should be something like this:

```
function batch_import_import($col1, $col2, &$context) {
  //do the stuff.
  if (!isset($context['results']['created'], $context['results']['updated'])) {
    $context['results']['created'] = 0;
    $context['results']['updated'] = 0;
  }
  $context['results']['created']++; // is_new == TRUE or some logic.
  $context['results']['updated']++; // add some logic to determine created or updated.
}

```

and then in the finish function, you get `$context['results']` as the second argument.

```
batch_import_finished($success, $results, $operations) {
   if ($success) {
     $message = t('Nodes created: @count', array('@count' => $results['created'])).'<br />';
     $message .= t('Nodes updated: @count', array('@count' => $results['updated']));
   }
   else {
     $message = t('some errors');
   }

  drupal_set_message($message);
}

```

I have also corrected the $message as you can use `t()` function here. Note that you pass `$context` by reference. See batch\_api examples for more information. This is just some code copied from a module I was developing the other day.

In the finished function, `$operations` contain unprocessed items.

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


# Question
Title: Drupal bootstrap running from command line
I am using Drupal 7 functions externally, and I followed this tutorial for using Drupal functions externally; it works perfectly.

In test.php file I have loaded/included Drupal bootstrap.

When I run the script from command line (`php test.php`), it gives me the following error:

> PDOException: SQLSTATE\[42000\] \[1049\] Unknown database 'default\_drupal' in lock\_may\_be\_available() (line 167 of /data/var/www/html/mcsu\_sites\_test01/includes/lock.inc).

How can I fix this error?

# Answer
You could also try Drush. Once you've installed it, you can `cd` into your drupal root then run `drush scr test.php`. In that file, all Drupal functions will be available.
> 2 votes

# Answer
You need this section from `scripts/drupal.sh`:

```
// define default settings
$cmd = 'index.php';
$_SERVER['HTTP_HOST']       = 'default';
$_SERVER['PHP_SELF']        = '/index.php';
$_SERVER['REMOTE_ADDR']     = '127.0.0.1';
$_SERVER['SERVER_SOFTWARE'] = NULL;
$_SERVER['REQUEST_METHOD']  = 'GET';
$_SERVER['QUERY_STRING']    = '';
$_SERVER['PHP_SELF']        = $_SERVER['REQUEST_URI'] = '/';
$_SERVER['HTTP_USER_AGENT'] = 'console';

```
> 1 votes

# Answer
According to `PDOException error` , probably your problem is in db conection . drupal **can not connect database** .
which version of drupal you are using ?

check $databases or $db\_url variables(according your drupal version) and it's properties set correctly

if your are usning Drupal 7

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'yourdatabase',
      'username' => 'usernameofdb',
      'password' => 'passwordofdbuser',
      'host' => 'dbhost', //localhost if you are localy worked
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
 );

```

or in drupal 6 in `settings.php` in default directory check

```
$db_url = 'mysql://username:password@localhost/databasename';

```
> 0 votes

---
Tags: bootstrapping, drush
---


# Question
Title: In Views, how can I display an edit link if a node relationship exists, otherwise display an add link?
I have a view of assignments, and want students to be able to post their work from that node. If they already have a work node, I want to display an edit link. Otherwise, I want to display an add link. In a previous version of this view, I used a Views PHP field that queried the DB for a work node matching the assignment, but I am rewriting the view because of a bug and I wanted to revisit this because it seemed a but ugly. Can anyone think of a better way?

# Answer
**I am assuming the following things for this answer**

1. There is a content type called assignments.
2. There is a content type called workbook which has a reference to the assignments content type
3. The view is of the assignment content type.

**Now to achieve what you are looking for follow the below steps**

1. Add a relationship of the type "Entity Reference: Referenced Entity"
2. Now add the field Content: Edit link. Choose the relationship we created in step one
3. Set the "NO RESULTS BEHAVIOR" and add the link to add a workbook page like `<a href="node/add/workbook">Add workbook</a>`
4. Add a CONTEXTUAL FILTER of the type "Content: Author uid" and provide default value and select "User ID from Logged in user" from the list.

That should do it.
> 1 votes

# Answer
I have had a similar situation and I did the following which is probably not the best thing to do - I will use your terms:

* When an `assignment` node is created a `work` node for each `student` is created with the field `field_submitted` set to `false`
* On the view, the field `field_submitted` is included but excluded from display
* I have a php field with this code which displays edit or submit, both are actually sending to the same node but they will give the student some insight about what he should do next:

```
if(!empty($data->field_field_submitted[0]['raw']['value']))
   echo l(t('edit')/*, ... */);
else
   echo l(t('submit')/*, ... */);

```
> 1 votes

---
Tags: views
---


title: How to make tokens display correctly?

text:
# Question
Title: How to make tokens display correctly?
I created a blog site and I used the Display Suite module to create a layout for the article content type. In one of the regions I created a custom code field that had "*Posted by \[user:name\] on \[node:created:long\]*".

After creating it I noticed that only the date was showing up and not the user token. I tested this out with several of the user tokens and none of them seemed to work. The only thing I can think of is that users tokens aren't supposed to work in Display Suite, but I couldn't find any proof one way or another.

The second issue is involving the number of views to a particular node. When I go to drupal.org, there is a list of tokens. The one I am trying to use is `[node:source:total-count]`, but nothing appears. I read that it might be a more in depth process than a simple token.

# Answer
> 1 votes
The token used to get the user who wrote the content is not \[user:name\]. This is the username of a user account that you are trying to view, so this might not be available on the node page as we are not referring a user.

To display the author name you should use \[node:author:name\].

If you install the token module you could go to the Help \> Token (admin/help/token) page and see the available tokens.

For more details and a list of the available tokens, see this page.

EDITED As per suggestion in comment.

---
Tags: 7, tokens, display-suite
---


# Question
Title: Tips for Information Structure & Superfish Menu
I am thinking of using the superfish menu module. The site will have three levels of navigation. Any tips for creating the nodes/pages so that the Menu structure works out properly? Or as long as I create all the level one pages and then use them as the parent menu for any child pages, will the menu be generated ok?

# Answer
You can always rebuild the menu, so I would just start adding content and organizing the links. The main advantage of a CMS like Drupal is that you are not "locked in" to a specific configuration and you can always change it around freely at any time.

One thing to be careful about is that the deeper your navigation structure, the harder it is for users (particularly older users and those not skilled in using mouse, etc. as well as those on mobile devices) to use the menus, but this is something you can only find out once you actually build the menus and do usability tests.

As you note, you will need to first create the parent pages before you can add links underneath them to the child pages.
> 1 votes

---
Tags: navigation
---


# Question
Title: How i can show the value of submitted form
I have implemented normal form in drupal 7 , and i want to show the value it is retrieve by this functions (submit)

```
function parkingcalulator_form_submit($form, &$form_state) {

    $parkingType = $form_state['values'] ['parking_type'];
    $totalCost = 0;

    $from = strtotime($form_state['values']['from_date']);
    $to = strtotime($form_state['values']['from_time']);

    $difference = $to - $from;
    $timeInHours = floatval($difference) / floatval(60*60);

    //// if the start time is greater than the end time set the error here
    if ($timeInHours <= 0 )
    {
        form_set_error('$timeInHours',t('Time inserted error'));
    }

    if ($parkingType == 0) {
        // Normal
        if ( $timeInHours < 200 )
        {
            $totalCost = calculateShortTermParkingCost($timeInHours);
        } else {
            $totalCost = calculateLongTermParkingCost($timeInHours);
        }
    } else if ($parkingType == 1) {
        /// Valet
        $totalCost = calculateValetParkingCost($timeInHours);
    }

     return $totalCost;

}

```

it does not show the value of (return $totalCost) ,how i can get the value on it

# Answer
> 2 votes
First of all the validation should not be done in the form submit function. It should be done in a validate function.

For example in your case there would be an additional function which would look like

```
 function parkingcalulator_form_validate($form, &$form_state)
 {
    $from = strtotime($form_state['values']['from_date']);
    $to = strtotime($form_state['values']['from_time']);

    $difference = $to - $from;
    $timeInHours = floatval($difference) / floatval(60*60);
    if ($timeInHours <= 0 )
        {
            form_set_error('from_time',t('Time inserted error'));
        }
    }

```

If you want to display the result with in the form, after submitting then you would add a value to the form\_state with in your form\_submit function such as

```
$form_state['total_cost'] = $totalCost;

```

And then tell the form to rebuild by adding this code again in the form\_submit function

```
$form_state['rebuild'] = TRUE;

```

Now with in the function you create the form the variable $form\_state\['total\_cost'\] would be available. you place that in a form element of the type markup. something like this

```
if(isset($form_state['total_cost']))
{
$form['total_cost'] = array(

  '#markup' => t('Total Cost is : ') . $form_state['total_cost'],

);
}

```

The if condition is used so that it is not executed in the first stage when the form is not submitted as the value is not yet there in the variable. The above code should go in the form function in your case `parkingcalulator_form($form, &$form_state)`

For more details examples you should refer the Examples Module which has a submodule called Form Examples.

# Answer
> 1 votes
A form submission handler doesn't return any value. To output a message for the user, you simply use drupal\_set\_message().

I assume the message for the user would simply be `t('The total cost is @total_cost', array('@total_cost' => $totalCost))`. if the output would be something more complicated, for example an image to show to the user, then the approach needs to be different, similar to the following code.

```
function mymodule_image_form($form, &$form_state) {
  if (!empty($form_state['image'])) {
    $form['image'] = array(
      '#theme' => 'image',
      '#path' => $form_state['image'],
    );
  }

  // Add the rest of the form.

  return $form;
}

function mymodule_image_form_submit($form, &$form_state) {
  $values = $form_state['values'];

  // Create the image, or select the image basing on the input given from the user.
  // Set $form_state['image'] to the path of the image.

  $form_state['rebuild'] = TRUE;
}

```

---
Tags: 7, forms
---


# Question
Title: different sidebars for different taxonomy vocabularies
I have few blocks I would like to show in sidebar of term page but not for all taxonomy term, only for a certain vocabulary. I can write taxonomy/term/\* but it will appear the block on all term pages. Is there a way to limit it by certain vocabulary?

# Answer
If you have pathauto installed then go to the `admin/config/search/path/patterns` (You find this when in the URL Aliases in the Admin, There would we tab named as Patters)

There you can define a pattern for each vocabulary. Set different url patterns for each of the vocabulary and then you should be able to use than in the block configuration.

Please note that you would have to do bulk update on taxonomy before the urls can take effect on existing terms.

OR

You could use the context module with has much more control over what to display. You can create a context of the type Taxonomy Term and select the vocabularies you want the block to be shown when that condition is true display the required blocks.
> 0 votes

---
Tags: 7, taxonomy-terms, blocks, theming
---


title: Colorbox has broken my site. Help!

text:
# Question
Title: Colorbox has broken my site. Help!
I had downloaded the libraries module. I then watched another tutorial which told me to CREATE a libraries directory in the sites/all folder. WHich I did, I then downloaded the colorbox plug in and pasted it in the empty libraries directory. I am now getting the following error:

Fatal error: Call to undefined function libraries\_get\_path() in /Applications/XAMPP/xamppfiles/htdocs/drupal/sites/all/modules/devel/devel.module on line 407

I deleted both libraries directories to start from scratch but the error is still there. How do I fix this?

# Answer
libraries\_get\_path is defined in `libraries.module`

Make sure the Libraries API module ( e.g 7.x-2.0 ) is installed and enabled.
> 0 votes

---
Tags: javascript
---


title: Allow photos in advancd forum replies?

text:
# Question
Title: Allow photos in advancd forum replies?
I'm currently using the insert module to allow forum users to easily upload a image and insert it into the forum topic body. I'm looking for a way to allow users replying to a topic to do the same thing. So, for example, user A could create a thread titled "Post your photos on mountains here" and users could reply to the thread and post their photos.

I'm sure this is possible through the text editor with IMCE or similar, but I find that route to confusing for simple forum users. That's why i like the insert mod, select your file and hit upload/insert. simple. So, any alternatives or something I'm overlooking?

# Answer
> 1 votes
There is an option to add fields to comments.

From Structure -\> Content Type select manage fields for the content type that needs image attached

There is a tab called "Comment Fields".

Select that, add and image field to it and that should do it. You would see an upload button in the comment.

---
Tags: files
---


# Question
Title: Programmatically subscribing user to a organic group
I need to expose OG memberships within API functions calls and wonder how to programmatically subscribe a user to a group (pending state) and then i need to approve him programmatically and change from pending to member. Im using OG 7.2.

```
function ask_membership($uid, $gid){
  ????
}

function approve_membership($uid, $gid){
  ????
}

```

Any help appreciated

# Answer
> 4 votes
Ok got it working, its still the og\_group() function.

```
function group_membership($type, $gid, $uid){
  $group_type = 'node'; //All our/my groups are of type node
  $entity_type = 'user'; //All our/my members are type users
  $values = array(
    'entity_type' => 'user',
    'entity' => $uid,
    'field_name' => FALSE,
    'state' => 1,
  );
  $return = FALSE;

    switch ($type){
        case 'subscribe':
          $values['state'] = 2;
          og_group($group_type, $gid, $values);
        $return = 'SUBSCRIBED TO TEAM';
          break;
      case  'approve':
          $values['state'] = 1;
          og_group($group_type, $gid, $values);
        $return = 'APPROVED TO TEAM';
        break;
      case 'delete':
        og_ungroup($group_type, $gid, $entity_type, $uid);
        $return = 'REMOVED FROM TEAM';
        break;
      default:
        $return = 'FALSE TYPE';
        break;
    }

  print json_encode($return);
}

```

Not that pretty but it works for now.

---
Tags: organic-groups
---


# Question
Title: List of certain user flagged nodes in a view
I'm using Drupal 6.28 latest views and flag modules (for drupal 6 ofc). I have a node content type "group" which can be flagged. So I'm user with id2 I'll go on node/10 and flag it, then I'll go on node/11 also flag it. Now I want to display all flagged nodes by me on my user page /users/myname.

What I did so far:

1 Created a node view 2 Set up a relationship **Flags: User's flagged content**, checked **Include only users who have flagged content.** then chosen my created flag. (for content type "group") 3 added argument **Flags: user uid** 4 added field "title"

I have 2 flagged nodes but it shows nothing.. What I am doing wrong?

# Answer
1) Create a Node View

2) Add a relationship Flags: Node flag (select the required flags and tick "Include only tagged Nodes"

3) Add another Relationship Flags : User (use the above relationship on this)

4) Add Argument User ID (*named Contextual Filters in Drupal 7*) and use the relationship "Flags : User"

5) Add the required fields.
> 5 votes

---
Tags: views, flags
---


# Question
Title: Static field works, dynamically modified element gets lost
I'm new to Drupal forms - trying to figure out a maddening problem.

I have a content type of 'doc-upload' with various fields including 'publisher\_code'.

When I define the 'publisher\_code' field type to 'text', and go through my upload process, yada yada yada, the value appears in my $node structure later as expected.

When I change 'publisher\_code' to "field type: List (text), widget: Select list", and I try to dynamically populate that element with:

```
function mymodule_form_doc_upload_node_form_alter(&$form, &$form_state) {

  $publishers = array( 'pub1' => 'Publisher 1', 'pub2' => 'Publisher 2' );

  $form['field_publisher_code'] = array(
    '#title' => t('Select a publisher'),
    '#type' => 'select',
    '#options' => $publishers,
    '#multiple' => FALSE,
    '#empty_value' => '',
    '#empty_option' => '- None -',
    '#required' => TRUE
  );
}

```

The form displays properly, but when the form is submitted, the 'field\_publisher\_code' doesn't come out the other side - presumably it's getting filtered/invalidated somewhere, but I can't seem to find where?

# Answer
> 0 votes
instead of over writing the form element just edit variables you want to change something like below

```
  $publishers = array( 'pub1' => 'Publisher 1', 'pub2' => 'Publisher 2' );

  $form['field_publisher_code']['#type'] = 'select';
  $form['field_publisher_code']['#options'] = $publishers;
  $form['field_publisher_code']['#multiple'] = FALSE;

```

I presume your $form already has the variable when you get the form.

---
Tags: 7, forms
---


# Question
Title: Making sure edits work as intended before publishing
I just wanted to pre-empt a situation that is highly likely to occur at some point in the future. I am going to be hosting a small online business using shared hosting. Obviously, once the website (which uses Drupal) is finalized and I take it out of maintenance mode, I want to keep it usable 99.99%. However at some point of time, I'll probably wish to make some edit, add content or even make some reforms that will need some thorough testing. I know that there is a preview button but for some alterations this may not be enough, but I'd still like to avoid putting the site in maintenance. (Although for fixing bugs and critical updates I obviously would).

I'd appreciate your suggestions on how I could do this please. I assume it must be a common issue among online businesses?

# Answer
The more or less standard solution is to maintain a so-called staging site (i.e. a mirror of your production site, but in a protected environment), and make all changes to the staging site *before* committing them to the production site.

The use of a staging site is not only limited to edits, but is also very useful when making more substantial changes, such as updating a module or adding a new module. The staging site let you run detailed tests to make sure that changes does not "break" anything before committing to the main site.

You can use drush to simplify syncing content and configuration between the staging and production site.

**Edit:** By "protected environment", I mean some computer that is not available to outsiders on the Internet. It is typically only available for use by yourself (and your team if you're not working alone, but manage a team of developers). The standard way of protecting it is to use a firewall and only allow connections from the IP-addresses belonging to you (and your team members)
> 1 votes

---
Tags: 7, nodes
---


title: How do I redirect anonymous users?

text:
# Question
Title: How do I redirect anonymous users?
I let anonymous users publish content on my site, but the content must be reviewed before to be published. The following is my ways to do that:

* Using CCK, I created a content type and unchecked the publish option.
* I gave the permission to create/edit/delete the content type to anonymous users.

This allows anonymous users to publish the content, but when they save the node they get an "Access denied" error.

What's the difference between what I do and using Workflow module? Is there a way to redirect the page, and make the anonymous users see the node they created?

# Answer
As the node is not published, when anonymous users create a node, they cannot see it. That is the reason they get the "Access denied" page.

You can redirect anonymous users to another page, and I would suggest to install, and use Rules, which allows (among other things) to redirect users when some conditions are met. The module can be useful to accomplish many other tasks, and avoids you to write custom modules.
> 2 votes

# Answer
There is also the view unpublished module which will allow anon users to view the unpublished node they just completed.
> 3 votes

# Answer
For example, in your site navigation, in place of **node/add/page**, instead link to **node/add/page?destination=*node/123*** (where *node/123* is a page is where you'd like to send users after adding new content).
> 0 votes

# Answer
You may also be interested in the Anonynous Publishing module.

Disclosure: I am the maintainer.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to create a an image gallery with a short description below each image
I have created an image gallery using views and a custom content type, Photo. It has 2 rows of three images each. I have uploaded the 6 images via the Photo content type, added a body describing the images and then used the views module to create the gallery. However in the gallery only the images and their titles are visible.

What I want is that the title should be displayed below and also the description for images should appear.

Here's a wireframe of what I am trying to build: https://i.stack.imgur.com/gGoFL.jpg

# Answer
Creating an Image Gallery Of images in nodes.

1. Add a content type to be used for the image gallery.
2. Add the image field
3. Add one node per image with the description in the body field.
4. Create a view of the type content
5. Add the fields Title, Image, Body (In this order so that they are displayed in that order itself
6. set the format to grid.

Now when you visit the page you should see the gallery as you wanted.
> 1 votes

---
Tags: views, media
---


# Question
Title: Moving Drupal to a new host but same domain
I am planning to switch web hosting provider for one based in the UK, as the data centers and offices for my current web hosts are in the US which makes it a lengthy process if I need to contact them etc. I am going to transfer my domain name (so I think that all of my URLs will be the same) and I have downloaded my `public_html` directory and MySQL database to my computer. If I just upload everything to my new host will everything work?

I have checked and I know that my new hosts have similar spec'd servers with PHP 5, but it just seems a little too simple. The biggest thing I am concerned about is the different timezones and the MySQL database really. If it makes any difference, I will be using shared hosting.

# Answer
> 1 votes
Drupal sets the timezone setting in PHP, so you should have the same timezone on the new server as you had on the old server. There could be issues when adding new times, but you'll quickly see that and fix it.

Running the same version of Apache, PHP, and MySQL should make things "just work", with caveats being things like htaccess overrides (sometimes you can't use certain overrides in your htaccess file in shared environments), PHP sub-versions of 5 (i.e. 5.2 to 5.4 introduces some new stuff, deprecates some functions, etc., but your code should still run fine), etc.

You should be able to reach your new shared account via some machine-code URL, like http://my-account-number.my-new-host.com to see that everything works before you point the domain. Be sure to clear the cache by visiting admin/config/development/performance after you do the import, OR when you export the database, do not include the **contents** of the cache\_\* tables. Backup and Migrate module makes this part easy, as that's the default when you export a database.

# Answer
> 3 votes
Few things to check.

Which version of PHP? I've seen Drupal sites break going from 5.3 to 5.4

You might want to check what the TTL of your domain is. If it's long you'll have people visiting the new site and the old one at the same time. You can set it to 5 minutes (300) which should make sure everbody moves across to the new site at roughly the same time.

Stress testing. Can the new hosting actually handle the expected load? Things like uploading images will take a lot of memory.

---
Tags: 7
---


# Question
Title: How to set one region over the other (and not beside it) in Omega theme?
I´m using Omega theme in a Drupal 7 installation, and don´t know how to put the sidebar second right below the sidebar first.

Under Zone and region configuration I have the content section, with the content zone inside it. Content zone has 12 columns. Inside it I have 2 regions: content (6 cols). sidebar second (3 cols).

If I add there another region, (sidebar first in my case) Omega puts it along the other two, and I can only set the weight of each one to determine wich one will appear first. **But what if I want one region under the other?**

I´m using delta module to create different layouts according to some variables, but every time I try to set one region over the other it fails. Is there any way to do that?

Thanks!

UPDATE: How may I use context to do that in case it is possible?

# Answer
> 1 votes
After some digging and reading what **Mohammed** says (thanks!), commenting my question above, I´ve found that there´s in fact a solution: You should allow context to manage that specific twist you want to do for that special viewport.

The problem is that context won´t allow that, there´s no viewport context. But there´s a new module out there called Context Breakpoint that would do the trick.

It´s important to remember what the readme file says though:

> Adaping to resolution should mostly be done with CSS and media queries, but sometimes you just can not do everything you need to do in CSS. This module detects screen and browser size with Javascript and sets a cookie accordingly. This means that Javascript and cookies must be enabled. Also, after changing the browser size, a reload will obviously be required for the changes to show up.

# Answer
> 1 votes
The side bars are used to create columns and not for placing it one on top of the other.

If you want a single column then you would go for one of the three. If you want two columns go with any two of them and if you want three columns go for all three.

As for placing contents one on top of the other the blocks should be used for that. Let us say you have two blocks one to show the latest articles and another to place the login box and you want the articles to be on top of the login box then you would go with one of the side bars and content and place both the blocks in the same sidebar and arrange it as you would want it.

# Answer
> -1 votes
The problem isn't really with Omega, it's more in the way that divs work.

You can't float divs sequentially that way without putting one inside the other.

What you want to do requires putting one region *inside* another, not on top of.

You could make custom template files and a custom grid that puts one zone alongside the other, but you'd lose the ability to extend each zone to 100% width, limiting your design options.

One javascript solution is good old Masonry http://masonry.desandro.com/ which essentially gives you the equivalent of a "float: top-left;" css rule.

---
Tags: 7, theming
---


# Question
Title: Can you display data dynamically from a textfield in the URL and Name of Views?
I have a content type of Product which includes a text field for the user to enter a Brand. This text field is open to the users to enter correctly, as there are hundreds of brands and I don't want them to have to learn how to enter taxonomy terms.

I am wondering if there is a way to dynamically create a View that will also dynamically generate the page name and page URL depending on the brand, and then display a table view of all of the Products with that Brand.

So for example if I have /category/brand/product-name as the parameters for the URL, for a specific product it would be /tshirt/busted/open-road, and with Busted being the Brand entered by they user, the view would automatically create the /busted url, and populate it only with Busted brand products in a table view.

Is this possible? I was thinking perhaps I needed to use tokens to grab the \[node:field\_brand\], but I am unsure exactly how I would do this, or if it was even possible. Also, if there is a better way of handling this data instead of a textfield, I would like to know!

# Answer
> 0 votes
I think you can still use taxonomy for this. The taxonomy can be open ended not need to make it closed to the terms you define.

When you add a taxonomy reference field choose the widget as autocomplete this will enable the user to add their own taxonomy term which may not be there in the list already.

If you are very particular about using the field then you can use that a contextual filter in a view so that it would appear in the url as mentioned.

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


# Question
Title: how to perform versioning content between users?
I need to create a content type "Project Software". Users can upload source code to their projects as a portfolio editing option. In one project can participate more users. So I need a solution for versioning the project so that it can be shared for online editing code.

# Answer
> 0 votes
You should take a look at the project module. This is used on the drupal site as well.

---
Tags: 7, files, nodes, version-control
---


# Question
Title: How do I display the "recently created node" block using Views?
I am trying to show the recently added content data in a block, using the Views module, but I can't see any record even if I recently added some nodes.

# Answer
> 1 votes
You need to check the views output settings. Notice there is a preview option. You wrongly select either fields either the filter doesn't match. You need to filter by Content Date Field and order it desc.

# Answer
> 1 votes
Ok I guess you are having problem with the content type selection. Use the right content type in the Filter criteria ( Content: Type= xxxxx) where xxxxx is your content type you are working with or created for the node. While Field display is set to fields.

# Answer
> 0 votes
1. check *Filters*
2. If you have set *display* to *fields*, Don't forget to add some fields in the *Fields* section

# Answer
> 0 votes
The issue must be within the views settings. Please check whether your content which you want to see is published or not and the permissions for different users to see the content. If that is not the case, check what Content Type you are selecting in the view..it should appear in left hand side once you are in the view settings...you should be able to follow from there onwards...also, check what field you have added, if you haven't then add them of type content:node

---
Tags: 6, views
---


# Question
Title: How to retrieve data from set with drush_set_option() from within install profile
I've been messing around with trying to pass varabiles to an install profile based on a signup form, as descripbed in this post. I'm able to get the data out of the form and into drush using `hook_pre_provision_install()`, but I'm not sure how to grab that data from within the install profile that was set with drush\_set\_option().

# Answer
It appears the answer is simple: You can use drush\_get\_option().

> Get the value for an option.
>
> If the first argument is an array, then it checks whether one of the options exists and return the value of the first one found. Useful for allowing both `-h`, and `--host-name`.
> 0 votes

---
Tags: distributions, drush
---


title: Where to see the result of hook_menu()

text:
# Question
Title: Where to see the result of hook_menu()
What is the purpose of `hook_menu()`, if I can create menus from the administration pages?

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

  $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'page callback' => 'blog_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  $items['blog/feed'] = array(
    'title' => 'RSS feed',
    'page callback' => 'blog_feed',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

so now where do I see the result of this function in the admin panel or in the site where the module is rendering?

# Answer
hook\_menu() is the method used by modules to add their own menu items. Most of the menu items you see on Drupal are added by modules with that hook.
The user interface allows you to add extra menu items that are not added by modules.

If you are asking the difference between creating a module that adds menu items with `hook_menu()`, and adding menu items with the user interface, `hook_menu()` allows to do things that are not possible with the user interface. For example, the menu that is visible when you hover the gear icon visible for a block is created with menu items added with `hook_menu()`. (It requires the Contextual links module, which is a Drupal core module.)

The tabs that you see, for example, on a node page, are created with `hook_menu()`, or `hook_menu_alter()`. You could not create them with the user interface.

What you can create with the user interface are links that go:

* In a menu block
* In the Menu links
* In the Secondary links
> 1 votes

# Answer
it depend on the type. if it is MENU\_CALLBACK, then it would not be displayed anywhere; it would be just an internal link.

On the other hand, if it is MENU\_NORMAL\_ITEM, it would be displayed in the navigation menu, in the appropriate place depending on the path; for example, if the path is admin/config/regional/language/configure, it would end up as tab for the Languages page.

See also the documentation page for hook\_menu().
> 0 votes

# Answer
Basically, the `hook_menu()` is a way to legitimize a URL within your site. For example you, might need to set up a URL for your AJAX where you'd process data, such as `/my-application/get-ajax-data`. You do that with `hook_menu` \- the key for `$items` array is the path you want to define.

The name of the hook may certainly be misleading, as the result might not necessarily be a menu item. But this is how you tell Drupal "Hey, this URL is authorized, no fear to go there." Of course - as it shows in the code you provided - there's the whole access control over it.
> 0 votes

---
Tags: routes
---


# Question
Title: How to provide a translation for a string used within t()?
On my site I use a module which creates text using t('text from module'). How can I tell drupal that I have a translation for that, and of course, that my translated text is being displayed?

# Answer
As alternative, on admin/config/regional/translate/translate you can translate any string used by modules installed on that site, and on admin/config/regional/translate/import you can import the translation files.

>

>

Those are the paths for Drupal 7; for Drupal 6 they are, respectively, admin/build/translate, and admin/build/translate/import.

The first page is useful to translate the string provided by a custom module, but also to alter an imported translation, while the second page is useful to manually import the translations exported from a site, such as http://localize.drupal.org.

To automatically get translation strings from Drupal.org Translations there is the Localization update; to contribute back the translation to Drupal.org Translations there is the Localization client module. Both the modules have been written by Gábor Hojtsy, who is the administrator for Drupal.org Translations.
If you are interested in using both the modules, there is also the Localized Drupal Distribution distribution, which comes with those modules.
> 3 votes

# Answer
First, make sure you install the **Localization update** module. It is the key to handling anything that has to do with translation. Enable automatic translation updates.

If the module is an "official" module with a stable release. the **Localization update** module will pull down translations from localize.drupal.org \- provided they exist. If they don't exist, *you* should provide them (read about how you can contribute on localize.drupal.org) - and the **Localization update** module will install them for you within 24 hours (if you've enabled automatic updates).

If the module does not have a stable release, there will not be anything on localize.drupal.org. In that case, you must add local translations using the built-in translation interface.
> 3 votes

---
Tags: i18n-l10n
---


# Question
Title: places where register_globals can be set
Story for background problem: I have a hostgator account. Uploaded the content of a drupal install folder to the actual root of the server. To fix this, I deleted all the files that I recognised from the drupal installation folder. The hostgator person on the chat reassured me that by default the .htaccess file is empty so going to back to an empty would bring me back to the original state. Everything seemed fine

Until I wanted to update 1 drupal 7 installation from 7.17 to 7.18. when starting to run mysite.com/update.php it said

```
  PHP register globals  Enabled ('1')
register_globals is enabled. Drupal requires this configuration directive to be disabled. Your site may not be secure when register_globals is enabled. The PHP manual has instructions for how to change configuration settings.

```

Checked the cpanel's php quickconfig settings. This said `register_globals` was set to `off`. So that means this setting is overwritten somewhere on a deeper level (it's a shared server so the root of my server is at a deeper level than the php installation which I obviously can't touch). There IS a php.ini file in my root folder of my server but that one also says

```
register_globals = Off

```

I looked up this problem and a lot of people seem to solve this by settings the register\_globals to off in the places I mentioned. I also put a php.ini file in my drupal installation folder at the same level as my index.php file. This solved the register\_global problem, but then I started getting errors about the PDO not being compatible with my current php version (5.2.13 while PDO would be needing 5.2.4 and up). And I don't think asking my provider to update php would be the way to go....

# Answer
I have hostgator account too. In hostgator and certain other host providers the `php.ini` that overrides the default values should live in `/home/USER/` (i.e. check if `/home/USER/php.ini` exists, where `USER` is the username of your hosting account). Make sure that **this** file has `register_globals = Off`.

If `/home/USER/php.ini` is not there then either copy the default (if you have shell access check `php.ini` location with the command `php -i | grep php.ini` and then copy this file to `/home/USER/php.ini`) or ask tech support to help.

More details can be found here on HostGator support site.

Finally, if you are using `drush` on your host account you might encounter "Register globals detection" issue in which case I would suggest the solution in comment #6, i.e.

```
cd drush/
ln /home/USER/php.ini php.ini

```

the resason for this is that `drush` script (`drush/drush`) checks for `drush/php.ini` and if it does not find it there it detects the default `php.ini` **not** the `/home/USER/php.ini` one.
> 3 votes

# Answer
I had this same problem with a CPanel web host recently.

I solved the register\_globals and PDO errors with a php.ini file in the drupal root:

`/php.ini:`

```
register_globals = off
upload_max_filesize = 32M
post_max_size = 32M
memory_limit = 256M
extension=pdo.so
extension=pdo_mysql.so

```

After that, all was peachy.
> 2 votes

---
Tags: 7, updating
---


title: Can Crumbs be used with Panels?

text:
# Question
Title: Can Crumbs be used with Panels?
I'm building a site with Panels (and Panels Everywhere, with a custom theme based on Precision) and trying to customize the breadcrumbs for particular nodes based on their content type.

The Crumbs module looks like it does what I need, and I've been able to make it work perfectly on a test site in Garland, but as soon as I switch to using Panels, the Crumbs breadcrumbs aren't being used.

Specifically, it looks like the "Breadcrumb" Page Element Content provided by ctools doesn't use the Crumbs breadcrumb trail. Somehow crumbs\_preprocess\_page is being completely suppressed.

Can these two modules be made to work together? I don't see any open issues for Crumbs, or any comments on the troubleshooting page at http://drupal.org/node/1008658, so I have to think that *someone* has made this work.

(Drupal 7.18, Panels 1.2, CTools 3.3, and Crumbs 1.8)

# Answer
Crumbs provides a "Breadcrumb (Crumbs)" block that you should be able to use.
> 4 votes

# Answer
I am not sure about Crumbs, but there is Panels Breadcrumbs. It lets you set breadcrumbs for each panel page within panels configuration, and your breadcrumbs can be exported with Features.
> 1 votes

# Answer
What about using the Custom Breadcrumbs module instead? I've used it successfully with Panels without incident.

From the project page:

> "Many new features have been added including support for Views, **Panels**, Taxonomy vocabularies and terms, paths, and a simple API that allows contributed modules to enable custom breadcrumbs for module pages and theme templates. These are implemented using optional, independent submodules that depend on the main Custom Breadcrumbs module."

Further, Custom Breadcrumbs has more than 30,000 installations, while Crumbs only has about 4,000, so you may find that issues are better documented as well.

For further reference: Comparison of breadcrumb-related modules
> 0 votes

---
Tags: panels, chaos-tool-suite, breadcrumbs
---


# Question
Title: How to add more fields after submission?
I was wondering how to add more fields to a form after submitting that form. So the form should have these fields for example:

* Name (textfield)
* City (select list)
* Find (button)

and then when user performs the submission, the result page should look like this:

* Name (textfield)
* City (select list)
* Gender (radio buttons) \<-- so they can refine the search by gender
* Find (button)

How do I achieve that?

# Answer
> 2 votes
You need to add a submit handler to the button that updates some specific variable in $form\_state so you can determine the "step" of the form. Plus, a `$form_state['rebuild'] = TRUE;` to rebuild the form.

Assuming you are using Drupal 7, a hook\_menu or hook\_block\_view (or any other function) is calling drupal\_get\_form function with "my\_form" as argument.

```
function my_form(&$form, &$form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );
  $form['city'] = array(
    '#type' => 'select',
    '#title' => t('City'),
    '#options' => array(
      1 => t('Kandy'), 2 => t('Anuradhapura'),
    ),
  );
  if (isset($form_state['next_step']) && $form_state['next_step']) {
    $form['gender'] = array(
      '#type' => 'select',
      '#title' => t('Gender'),
      '#options' => array(
        'm' => t('Male'), 'f' => t('Female'),
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Find'),
  );
  return $form;
}

function my_form_submit($form, &$form_state) {
  $form_state['next_step'] = TRUE; // You can also change this to FALSE in validate function to prevent the gender from appearing.
  $form_state['rebuild'] = TRUE; // Don't forget this!

  // Do other stuff here.
}

```

Note how I conditionally added the gender form element, and how the submit handler sets that value.

When the form is loaded for the first time (with empty `$form_state`), the condition to add the gender element will be `FALSE`, so no element added. Then, the form submit handler adds the values so in the next form rebuild, element gets included. Tricky part is the `$form_state['rebuild'] = TRUE;` part.

Good luck!

# Answer
> 1 votes
You would want to do some kind of multi-step form. This is generally not a trivial task, but it can be done. There are a quite a few tutorials around on how to do it, but you should look at the official Docs for it first here.

Another good resource for multi-step is the "Form Wizard" component of the CTools suite, which can be found here.

Hope this is helpful. One of my upcoming projects concerns this, so I am trying to learn all I can about it as well.

# Answer
> 0 votes
This seems to be proper place to use AHAH framework. Here and here you have doc about it.

---
Tags: forms
---


# Question
Title: Is there a way to add variants to a mini panel?
I am trying to organize my content as follows, but I am not certain if it is proper to use variants (if there are variants for mini panels) this way. Suppose I have a page A. I would like to easily re-use A as a block in other pages, say as a block with a portion of the content of A and a *read more* link and placed in a sidebar of the front page. Note that I want to do this for a few hand-selected pages, and I hope these blocks can be moved around easily like panes. So I was thinking if I can do the content of A in a mini-panel A', and use A' in both A and the front page. But that way I must have two ways to render the mini-panel A'. So how do I add variants to A'?

# Answer
> 2 votes
Minipanels don't support variants, however, you can achieve a similar result by adding visibility rules to show/hide minipanel panes on certain pages, according to specified conditions.

Though more simple options are possible, an example using PHP for a visibility check is here

---
Tags: panels
---


# Question
Title: How to load a node edit form using Ctools module in Drupal 7
I am trying to load a node edit form into a modal frame using Ctools. The following is the function I am using. So far the `$op = 'view'` part is working fine, but I cannot get the node edit form to load when `$op = 'edit'`. I have searched for the better part of the day, but I cant find anything about how to load node forms in a modal frame using Ctools in Drupal 7.

```
function namecards_modalframe_node($op, $nid, $js = FALSE) {
  $output = '';
  switch ($op) {
    case 'view':
      if ($js) {
        ctools_include('ajax');
        ctools_include('modal');
        $output .= theme('namecards_download_cvs_link', $nid);
        // Create table showing contact's information
        $table_structure = namecards_get_table_data($nid);
        $output .= theme('table', array('header' => $table_structure['header'], 'rows' => $table_structure['rows'], 'attributes' => $table_structure['attributes']));
        $output .= theme('namecards_download_cvs_link', $nid);
        // Add close button to bottom of page.
        return ctools_modal_render(t('Details'), $output);;
      }
      else {
        $output .= theme('namecards_download_cvs_link', $nid);
        // Create table showing contact's information
        $table_structure = namecards_get_table_data($nid);
        $output .= theme('table', array('header' => $table_structure['header'], 'rows' => $table_structure['rows'], 'attributes' => $table_structure['attributes']));
        $output .= theme('namecards_download_cvs_link', $nid);
        // Add close button to bottom of page.
        $form = drupal_get_form('namecards_modalframe_close_button_form');
        $output .= drupal_render($form);
        return $output;
      }
      break;

    case 'edit':
      // Include 'node.pages.inc' in order to be able to use node functions
      module_load_include('inc', 'node', 'node.pages');
      //      form_load_include($form_state, 'inc', 'node', 'node.pages');
      $node = node_load($nid);

      if ($js) {
        ctools_include('ajax');
        ctools_include('modal');
        $form_state = array(
            'ajax' => $js,
            'title' => t('Edit'),
            'build_info' => array(
                'args' => array(
                    'node' => $node,
                ),
            ),
        );
        return ctools_modal_form_wrapper('namecards_some_form', $form_state);
      }
      else {
        $node_edit_form = node_page_edit($node);
        return drupal_render($node_edit_form);
      }
      break;
  }
}

```

Each time I click on the link, the modal frame opens but it is blank (accept for the loading animation). At the same time a js alert box appears containing the following:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /namecards/modalframe/node/edit/4585/ajax
StatusText: OK
ResponseText:
drupal7
@import url("http://drupal7/modules/system/system.base.css?lylwzg");
@import url("http://drupal7/modules/system/system.menus.css?lylwzg");
@import url("http://drupal7/modules/system/system.messages.css?lylwzg");
@import url("http://drupal7/modules/system/system.theme.css?lylwzg");
@import url("http://drupal7/misc/vertical-tabs.css?lylwzg");
@import url("http://drupal7/modules/contextual/contextual.css?lylwzg");
@import url("http://drupal7/modules/comment/comment.css?lylwzg");
@import url("http://drupal7/modules/field/theme/field.css?lylwzg");
@import url("http://drupal7/sites/all/modules/namecards/namecards.css?lylwzg");
@import url("http://drupal7/modules/node/node.css?lylwzg");
@import url("http://drupal7/modules/search/search.css?lylwzg");
@import url("http://drupal7/modules/user/user.css?lylwzg");
@import url("http://drupal7/sites/all/modules/views/css/views.css?lylwzg");
@import url("http://drupal7/sites/all/modules/ctools/css/ctools.css?lylwzg");
@import url("http://drupal7/modules/shortcut/shortcut.css?lylwzg");
@import url("http://drupal7/modules/toolbar/toolbar.css?lylwzg");
@import url("http://drupal7/themes/garland/style.css?lylwzg");
@import url("http://drupal7/themes/garland/print.css?lylwzg");
Skip to main content
Home
Hello drupal7
Log out
Administrative toolbarDashboard (View and customize your dashboard.)
Content (Administer content and comments.)
Structure (Administer blocks, content types, menus, etc.)
Appearance (Select and configure your themes.)
People (Manage user accounts, roles, and permissions.)
Modules (Extend site functionality.)
Configuration (Administer settings.)
Reports (View reports, updates, and errors.)
Advanced help
Help (Reference for usage, configuration, and modules.)
Hide shortcuts
Add content
Find content
Performance
Edit shortcuts
drupal7
Main menuBooks
Home
Namecards
Secondary menuMy account
Log out
Configure block
Search form
Search
Navigation
List links
Edit menu
Configure block
Add content
Development
List links
Edit menu
Configure block
Devel settings
Empty cache
Entity info
Execute PHP Code
Field info
Function reference
Hook_elements()
Menu item
PHPinfo()
Rebuild menus
Reinstall modules
Run cron
Session viewer
Theme registry
Variable editor
You are hereHome
Configure block
Powered by Drupal

```

Would appreciate any suggestions on how to get this working.

# Answer
I used the following code in a resent project, hope this helps:

Add this code to custom\_module.module:

```
/**
 * Implementation of hook_menu().
 */
function custom_module_menu() {
  $items = array();

  // @see node_menu in node.module:
  // @todo Remove this loop when we have a 'description callback' property.
  // Reset internal static cache of _node_types_build(), forces to rebuild the
  // node type information.
  node_type_cache_reset();
  foreach (node_type_get_types() as $type) {
    $type_url_str = str_replace('_', '-', $type->type);
    $items['modal/node/add/' . $type_url_str . '/%ctools_js/%'] = array(
      'title' => $type->name,
      'title callback' => 'check_plain',
      'page callback' => 'custom_module_node_page_add',
      'page arguments' => array($type->type, 4, 5),
      'access callback' => 'node_access',
      'access arguments' => array('create', $type->type),
      'description' => $type->description,
      'file' => 'custom_module.pages.inc',
    );
  }
  $items['modal/node/%node/edit/%ctools_js/%'] = array(
    'title' => 'Edit',
    'page callback' => 'custom_module_node_page_edit',
    'page arguments' => array(2, 4, 5),
    'access callback' => 'node_access',
    'access arguments' => array('update', 2),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'custom_module.pages.inc',
  );

  return $items;
}

```

add the following to custom\_module.pages.inc:

```
 /**
  * Page Callback - Modal: Add Node
  */
function custom_module_node_page_add($type, $js, $force_page_reload = FALSE) {
  // Fall back if $js is not set.
  if (!$js) {
    return drupal_goto('node/add/' . str_replace('_', '-', $type));
  }

  // Get node form defaults.
  global $user;
  $types = node_type_get_types();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE
  );

  $title = t('Create @name', array('@name' => $types[$type]->name));

  custom_module_node_form($node, $title, $force_page_reload);
}

/**
 * Page Callback - Modal: Edit Node
 */
function custom_module_node_page_edit($node, $js, $force_page_reload = FALSE) {
  // Fall back if $js is not set.
  if (!$js) {
    return drupal_goto('node/' . $node->nid . '/edit/');
  }

  $type_name = node_type_get_name($node);
  $title = t('<em>Edit @type</em> @title', array('@type' => $type_name, '@title' => $node->title));

  custom_module_node_form($node, $title, $force_page_reload);
}

/**
 * Build the Modal Form.
 *
 * @param object $node
 *   The node Object in edit case. In Add case it's only a pseudo node object.
 * @param string $title
 *   The Modal Popup Title.
 * @param boolean $force_page_reload
 *   Indicates if page should be reloaded after form submission.
 */
function custom_module_node_form($node, $title, $force_page_reload = FALSE) {
  $commands = array();

  ctools_include('node.pages', 'node', '');
  ctools_include('modal');
  ctools_include('ajax');

  $form_state = array(
    'title' => $title,
    'ajax'  => TRUE,
    'build_info' => array(
      'args'  => array($node),
    ),
  );

  $commands = ctools_modal_form_wrapper($node->type . '_node_form', $form_state);

  if (!empty($form_state['executed']) && empty($form_state['rebuild'])) {

      // overwrite commands.
      $commands = array();

      ctools_add_js('ajax-responder');
      $commands[] = ctools_modal_command_dismiss();
      // if (t('Delete') == $form_state['values']['op']) {
      //   $commands[] = ctools_ajax_command_redirect('modal/node/' . $node->nid . '/delete/ajax/reload');
      // }
      // else
      if ($force_page_reload) {
        $commands[] = ctools_ajax_command_reload();
      }
  }

  // add CSS class to Modal-Frame
  $commands[] = ajax_command_invoke('#modalContent', 'addClass', array('custom-module-node', 'custom-module-node-form'));

  print ajax_render($commands);
  exit;
}

```
> 6 votes

# Answer
Here's how to make a module from Lars Schroeter code (below).

Put both files (`custom_module.module & custom_module.pages.inc`) in a folder named `custom_module`. Of course, both files must begin with `<?php`. Then create the required `custom_module.info` file. Something like this will do.

```
name = "Node edit modal"
description = "How to load a node edit form using Ctools module in Drupal 7."
package = "Modal Gallery"
core = 7.x
files[] = custom_module.module

dependencies[] = "ctools"

```

Put the `.info` file in the custom\_module folder. Put the folder in `sites/all/modules`. Go to your modules pages and enable it. Then, create a link on a test page. For example

```
<a href="node/add/nojs/">Create content (node/add)</a>

```

Thanks Lars, the code really helped me get going!
> 2 votes

---
Tags: chaos-tool-suite, javascript
---


# Question
Title: How to load all field values from multiple entities?
I have an EFQ that finds the users whose field values match a given array of values:

```
  $users_query = new EntityFieldQuery();

  $users_query->entityCondition('entity_type', 'user')
    ->fieldCondition('field_my_field', 'value', $array_of_values);

  $users_query_result = $users_query->execute();

```

This will create a list of uid's but I need to know which uid goes with which value in the array.

# Answer
> 1 votes
EFQ will return an entity stub, if you want the fully loaded entities, you can try something like:

```
// Build query
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user');
$query->fieldCondition('field_my_field', 'value', $values);
// Execute for result
$result = $query->execute();
// If has data
if (!empty($result['user'])) {
  // Load users
  $accounts = entity_load('user', array_keys($result['user']));
  // If using devel
  // dpm($accounts);
}else{
  // No results
}

```

# Answer
> 1 votes
The only way I suggest is loading the user objects with entity\_load(), or user\_load\_multiple() using the array returned from `$users_query->execute()`. That is the only method that always work.
On Drupal, entity fields can be stored on a different database engine, or on a Mongodb database; directly querying the database could not work, similarly to directly querying the database instead of using cache\_get(), or cache\_set().

---
Tags: entities, database
---


title: How to override exposed filters view

text:
# Question
Title: How to override exposed filters view
I have one form of exposed filters of view. I need to override few elements of that, like change options for select box dropdown and like that.

For that I have created view, and used `hook_form_alter`, but the changes are not reflecting.

My work:

```
function custom_module_form_alter($form, &$form_state, $form_id) {
    if ($form_id == 'views_exposed_form' && $form['#id'] ==
         'views-exposed-form-advanced-search-page') {

         print_r($form['submit']);  //debug
         $form['submit']['#value'] = t('Search');
         print_r($form['submit']); //debug
    }
}

```

As shown above, to test, I am just trying to alter the label of submit button, and for debugging, I have added two `print_f`, statement, output of which are as follows:

First print\_f():

```
Array ( [#name] =>
        [#type] => submit
        [#value] => Apply
        [#id] => edit-submit-advanced-search
      )

```

Second print\_f():

```
Array ( [#name] =>
        [#type] => submit
        [#value] => Search
        [#id] => edit-submit-advanced-search
     )

```

As shown, the label is changing, but it is not reflecting to the form.

Considering module weight, I have also tried giving more weight to my module tham views weight. But nothing changed.

Please suggest, if I am missing something.

-- Thanks for your time.

# Answer
> 3 votes
You have to pass the variable as reference.

So the function would should be

```
function custom_module_form_alter(&$form, &$form_state, $form_id) {

```

---
Tags: 7, forms, views
---


# Question
Title: not found in Multi language site with only session detection
I have a multilingual site with 3 enabled languages. Default language is English I've only setup my language options to use the "Session" detection method. I dont to use URL language options. when i create node in English node and set pathauto for url with token \[node:author\]/\[node:content-type\]/\[node:nid\]

is work in default language only when i switch language to another this token is not work. for example when i create node in another language this path not work.

http://example.com/reza/news/324 this does not work (this node is created in arabic site) http://example.com/ar/reza/news/324 this works but i don't want to user this url i want use this example http://example.com/reza/news/324?lan=ar

# Answer
> 4 votes
The problem was resolved: When we create a new content type, the "Multilingual support" in "Publishing options" should be set to "Enabled, with translation."

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


# Question
Title: How to troubleshooting a D7 website that doesn't load (Gateway Timeout)
A website of mine, using D7, suddenly doesn't load. I always receive a Gateway Timeout error.

The strange is that with a ftp client I can browse the website as usual

What are the steps I should follow to troubleshooting this situation?

# Answer
I solved the problem disabling the Database logging module.

I had the same problem also in another website (D7 + Database logging module, solved disabling the Database logging module)

Hope this helps.
> 1 votes

---
Tags: 7, performance
---


# Question
Title: Which hook do I need to use to pull external content in pages?
I want some of my pages to pull content from another application. Someone suggest I should write a module to do that. As I'm a complete beginner in Drupal I was wondering which hook do I need to implement (a snippet would be greatly appreciated) :

* hook\_page\_alter
* hook\_page\_delivery\_callback\_alter
* something else ?

# Answer
hook\_page\_alter() is used to alter the page returned from another module, and hook\_page\_delivery\_callback\_alter() is used to change the page delivery callback for a page output from another module. All the hooks with a name ending with \_alter are hooks that alter the output of another module, what another module returns, or the data stored by another module.

The hook you should use is hook\_menu() to define a page callback, and drupal\_http\_request() to get the external content.
The minimal code you should use is similar to the following one.

```
  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_external_content_view',
      'access arguments' => array('access content'),
    );

    return $items;
  }

function mymodule_external_content_view() {
  $response = drupal_http_request($url);
  if (!isset($response->error)) {
    $data = $response->data;

    return array(
      '#markup' => filter_xss($response->data, $allowed_tags)
    );
  }
}

```

Replace abc/def with the path of the page you want to output, `$url` with the URL of the external application, and `$allowed_tags` with an array of strings for the tags that you want to allow as output. By default, filter\_xss() uses `array('a', 'em', 'strong', 'cite', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')`.
> 3 votes

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


title: How to add 4 side by side containers

text:
# Question
Title: How to add 4 side by side containers
I would like to add 4 columns/containers just above the footer of the homepage. Similar to the triptych blocks that the Bartik theme offers, except I would like to have 4 of them. I am using a Zen sub theme.

How would I go about adding 4 block and having them display one next to another?

# Answer
You just need to define them in your .info file...

```
regions[four_first]   = Footer panel (first)
regions[four_second]  = Footer panel (second)
regions[four_third]   = Footer panel (third)
regions[four_fourth]  = Footer panel (fourth)

```

Then add them to your page.tpl...

```
<?php if ($page['four_first'] || $page['four_second'] || $page['four_third'] || $page['four_fourth']): ?>
    <div id="footer-panels-wrapper">
       <?php print render($page['four_first']); ?>
       <?php print render($page['four_second']); ?>
       <?php print render($page['four_third']); ?>
       <?php print render($page['four_fourth']); ?>
    </div>
<?php endif; ?>

```

When you have done this they will appear in /structure/blocks

The rest is down to CSS...
> 2 votes

---
Tags: theming
---


# Question
Title: Exclude taxonomy terms from search_excerpt in snippet
In search-result.tpl.php or in preprocess\_search\_result function, I want to keep $snippet. It is a great view to display search results.

But Apache Solr results, or Search module results, are displayed with terms that matches the query. These terms are designed to be hidden to anonymous. They can't be displayed in the snippet.

> ex: Marguerite **Duras** … histoire " avec **DURAS**. Celle de deux personnes qui se reconnaissent avant de se connaître. Une … "Qui est Marguerite **Duras** ?" Il avait découvert l'écrivain, il allait rencontrer la …

The term *Marguerite Duras* is an admin tag. By the way, it is nice that the score relevancy depends on it.

How is created the snippet, or search\_excerpt ? I tried the Taxonomy Hide module, but it doesn't affect search results.

# Answer
The search result is a node view and hence the `hook_node_view_alter` works for it.

So you would could create a custom module and write the following function

```
function custom_node_view_alter(&$build, $type)
{
    if (($build['#view_mode'] == 'search_result') && ($type = 'node'))
    {
        unset($build['field_tags']);
    }
}

```

change the `field_tags` to the name of your taxonomy field in the content type.

`$build['#view_mode']` this variable defines the view we are on. In this case we are on the search\_result view. And the `$type` defines the module in this case it is the node.

Use the following for Drupal 6

```
function custom_nodeapi(&$node, $op, $a3, $a4) {

  switch ($op) {
     case 'search result':
          $node = node_load($node->nid);
        $node->build_mode = NODE_BUILD_SEARCH_RESULT;
        $node = node_build_content($node, FALSE, FALSE);
        $node->body = drupal_render($node->content);
      break;
  }
}

```
> 0 votes

---
Tags: nodes, search
---


# Question
Title: Adding a delete button for webform attachment fields
I have created a structure of field like below within code and not used *webform UI*. The reason of doing this pro-grammatically is because I have hundreds of forms and I wanted to do it once for all.

Here is my code:

```
            for ($i = 0; $i <= 4; $i++) {
                $form['submitted']['file' . $i] = array(
                    '#title' => t('File'),
                    '#type' => 'managed_file',
                    '#description' => t('Please upload a document or image.'),
                    '#default_value' => variable_get('file' . $i, ''),
                    '#weight' => 100,
                );

                $form['submitted']['remove_name'.$i] = array(
                   '#type' => 'submit',
                   '#value' => t('Remove'.$i),
                   //I NEED A WAY TO PASS $i AS ARGUMENT TO THE CALLBACK
                   '#submit' => array('form_remove_attachment'),
                   // Since we are removing a name, don't validate until later.
                   '#limit_validation_errors' => array(),
                );
            }

```

And here is the callback:

```
 function form_remove_attachment($i, &$form_state) {
  //dsm($form_state['complete_form']);
  $clicked = explode(' ', $form_state['clicked_button']['#value']);
  //dsm($clicked, 'clicked');
  if ($clicked[1] == $i) {
     unset($form_state['complete_form']['submitted']['file' . $i]);
  }
  // Setting $form_state['rebuild'] = TRUE causes the form to be rebuilt again.
  $form_state['rebuild'] = TRUE;
}

```

Now what I need is a *delete button* for each attachment field to allow users to change their mind on regard the attached files. I can add it of course by *JS* but this way the attachments are not eliminated from `$form_state`.

Does anyone have some suggestions?

# Answer
> 1 votes
There is an example in the examples module.

There is a module with in that called form\_example. If you check the 9th example you would get what you are looking. It has an example of adding and removing fields dynamically and the code is well documented.

change value `'#value' => t('Remove'),` to `'#value' => t('Remove' . $i),`

and in function you could get that as given below

```
function form_remove_attachment($i) {
    $clicked = explode(' ', $form_state['clicked_button']['#value']);
   //$clicked[1] would have the value of $i

    $form_state['rebuild'] = TRUE;
}

```

---
Tags: 7, theming, webforms
---


# Question
Title: Differences between Location and Location CCK?
Location has three modules: Location, Node Locations and Locations CCK

What are the primary differences between them? Are there any advantages to using Node Locations over the Locations CCK?

Thanks!

# Answer
Location: provides the Location API; handles address storage and geocoding. Essentially the base of the location module to which the other modules rely upon.

Location CCK: provide a Location behavior as a CCK field. This module uses the field API properly rather than its legacy node location module which implemented its own fields and storage.

If you are evaluating which one to use, I would recommend the cck one. The others are being deprecated soon.

Via the project page:

> Location 7.x-4.x is planned to be a stripped out version of location 7.x-3.x, which has no node location, user location, location taxonomy (at least in its curren form), location add another sub-modules. It will only have location field, which will essentially be the current location cck module.
> 4 votes

# Answer
> The Location module allows real-world geographic locations to be associated with Drupal nodes, including people, places, and other content.
>
> **Location**: provides the Location API; handles address storage and geocoding. Allows users to attach locations to nodes.
>
> **User Locations**: allows admins to associate locations with users.
>
> **Location** CCK: provide a Location behavior as a CCK field.
> -1 votes

---
Tags: 7, location
---


# Question
Title: Ubercart: maintaining cart content after user login
I have a Ubercart site where the user can add items to cart even if it is not logged in: the problem is that when he logs in the cart is emptied and he has to refill it.

Is there a way to save the cart for the anonymous user and, when he logs in, to retrieve the cart content?

# Answer
> 1 votes
The feature looking for is default ubercart behavior. You may have missed with some of your custom code may be with `hook_user` Check that to see what happens and try disable any custom modules.

---
Tags: 6, ubercart
---


# Question
Title: One role per user or multiple-roles per user
**Scenarios**: User A allows to do 1, user B allows to do 1 and 2. Assume 1 and 2 are disjoint.

*Which is better?*

**Option 1**: Create role RA can do 1, role RB can do 2, then assign user A to RA, B to both RA and RB.

**Option 2**: Create role RA can do 1, role RB can do 1 and 2, then assign user A to RA only, B to RB only.

# Answer
> -1 votes
I would do option 1, It will give more control and maybe in the future you have a user that can only do 2.

---
Tags: users
---


title: Detecting language and rewriting url

text:
# Question
Title: Detecting language and rewriting url
Drupal can automagically detect the language to use when displaying content :

* Based on URL
* Based on User preference
* Based on Browser language.

However, when I request a url like : http://mysite.com/toot/lala, Drupal detects the english language (browser settings), but it doesn't rewrite the url to : http://mysite.com/en/toot/lala

I'm afraid that this behavior will induce Duplicate Contents errors. Does someone know how to correctly set this redirection ?

# Answer
> 2 votes
The Global Redirect module will help you with that issue.

It has a redirection system specific for language prefixes, preventing content duplication.

---
Tags: i18n-l10n, uri
---


# Question
Title: Is it possible to preserve image quality when uploading images?
Is it possible to preserve image quality when uploading images through Drupal7?

For example, I take this image: http://f.cl.ly/items/0L3j21030C3O2A3x2w0b/thumb.jpg

I upload it using an Imagefield, which has no min/max resolution set, and it looks like this: http://f.cl.ly/items/2B2q2a1H402T1Z1j3w2j/baboon-onesie-costume-thumb.jpeg

So already we're seeing a loss in quality. Then it's displayed using a view, which scales the image (which it should do IF) it's larger than 190x280 (which it isn't), and now it looks like: http://f.cl.ly/items/2n023q1Q331J3E2d3a3I/baboon-onesie-costume-thumb-1.jpeg

The quality difference is massive - there's a huge loss of colours and severe artefact creation around the image edges.

The GD image settings are JPEG quality: 100%.

Is there anything that can be done to prevent this ridiculous loss of quality?

# Answer
There's two solutions to this. The easiest is:

* Upload images with a "jpeg" extension instead of a "jpg" extension. For whatever reason, images with a jpeg extension are not mangled by Drupal.

However, the best solution if you have control over your hosting environment is:
> 5 votes

# Answer
I had this problem, uploading an image to see it scaled via an imagestyle to a low quality image.

The problem was that within my contact type I had a max image resolution set, that I'd forgotten about.

Removed this from the site, and re uploaded, everything is good.
> 1 votes

# Answer
Under the display settings for content types image field you could set the format to none:original image And a CSS rule to display the image at the desired size

**caveat**
this probably would lead to problems as users could upload images with extreme max/min image resolutions.
> -4 votes

---
Tags: 7, media
---


# Question
Title: jQuery ajax request breaks drupal behaviours
In the Drupal commerce checkout I want to fill in the billing information automatically. I do that by attaching a javascript to that form and retrieving the information that is stored in the line item. That works great except for only one thing. The first time I click “continue on the next step” nothing happens and the page refreshes. But the second time the button does work and goes to the next pane.

It has the same strange behaviour when I load the page once, go to another page and go back. Then it works from the first time.

My javascript is rather basic and does work, but for some reason it breaks my form.

```
(function($) {
Drupal.behaviors.mymodule = {
    attach : function(context, settings) {

         var txtFullname = jQuery('input[id^=my_dynamic_id]');

        // do ajax request
        jQuery.ajax({
            type : "POST",
            url : 'http://example.com/retrieve_information',
            data : {
                'order' : settings.order_id
            },
            dataType : "json",
            success : function(data) {
                txtFullname.val(data.fullname);
            }
        });

    }
};
}(jQuery));

```

One thing I really have a hard time grasping (but then again I'm a Drupal beginner) is how a DOM operation can break the whole thing, especially when the only thing I'm doing is filling a simple textfield.

Is there a way in jQuery to trigger drupal to rebuild a form, because I have the gut feeling that this is the reason why it works the second time.

EDIT: It doesn't seem to have anything to do with jQuery as I have rewritten that part to use the Drupal ajax framework.

From the moment the billing information is filled in - i'm setting the values of the field in hook\_form - the submit button doesn't seem to work for the first time.

# Answer
I presume you need to add that code with in document ready. Some thing like give

// Code that uses jQuery's $ can follow here.

```
(function($) {
Drupal.behaviors.mymodule = {
    attach : function(context, settings) {
      jQuery(document).ready(function($) {
         var txtFullname = jQuery('input[id^=my_dynamic_id]');

         // do ajax request
         jQuery.ajax({
            type : "POST",
            url : 'http://example.com/retrieve_information',
            data : {
                'order' : settings.order_id
            },
            dataType : "json",
            success : function(data) {
                txtFullname.val(data.fullname);
            }
        });
      });
    }
};
}(jQuery));

```
> -1 votes

# Answer
I guess you should try to add in your JS a `Drupal.attachBehaviors();` on your form or your ajaxified field
> -1 votes

---
Tags: ajax, commerce, javascript
---


# Question
Title: There are no products in your shopping cart
I'm using Ubercart in a Drupal 6 setup.I have created products and able to order the products as an authenticated user mode ,but when i go with anonymous buying it doesn't showing any products in cart page and it results "There are no products in your shopping cart." when click add to cart button.

For me its working good in live site , when i took live dump to my testing site , am facing above bug (There are no products in your shopping cart.) please help if anyone knows the solution for this .Thanks in advance.

# Answer
> 0 votes
That issue might be a MySQL problem. I'm assuming here that you dump the live DB and load it in your test machine.

Please check the uid value for the anonymous user in "users" table. The anonymous user is the one with empty fields. The uid value should be 0.

With certain MySQL configurations when loading sql dumps, autoincremental fields cannot accept the 0 value, and gives an incremented value.

---
Tags: ubercart
---


# Question
Title: How one can get a field auto loaded with node title by passing nid
How one can get a field auto loaded with node title by passing nid. I mean instead of getting the selectllist of all available title i want it to be auto loaded with corresponding node title.

NOTE: I have passed nid to that content type. Now have to fetch the corresponding node title into a field.

Thanks in advance , Manju

# Answer
> 1 votes
Prepopulate might solve your problem.

> The Prepopulate module allows fields in most forms to be pre-populated from the $\_REQUEST variable.
>
> For example, the following URL,
>
> `http://www.example.com/node/add/blog?edit[title]=this is the title`
>
> will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well. Prepopulate is excellent for creating bookmarklets. For examples on usage for all of these cases, please read the USAGE.txt file that comes with the module or you can read the online handbook page.

# Answer
> 1 votes
The Node Reference URL Widget worked well for my issue. I got the field autopopulated using the value from URL.

Manju

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


title: How to see which varient is in use?

text:
# Question
Title: How to see which varient is in use?
Is there any way to know which Panel varient is being used, when I'm viewing the node or term? I know there is the panel page listing and that shows the varients, but it is difficult to know which nodes are using this varient.

I'm asking because I have a site, node template panel has over 20 different varients, some are in use some are not. Attempting to document them is painful.

Thanks!

# Answer
There is probably a better way, but when I've had to do this I just change the page title for each variant. Of course, you probably don't want to do this on a live site, but if you have a test site it's not so bad.

Alternately, you could also add a CSS class, etc.
> 1 votes

---
Tags: panels
---


# Question
Title: How do I display date and time for multiple time zones?
I am webmaster at http://www.archerpoint.com. We would like to display our events in both Eastern and Pacific time. I only know how to control the system time zone or let the user set their own time zone, but I do not know how to display a single time entry as two separate time zones without hacking code or creating and displaying two separate entries, one for each time zone. Is there a simple solution for this?

# Answer
> 1 votes
Try to save date-time values in UTC format and while displaying them you can use format\_date function

where you will need to pass timezone value to its parameter.

---
Tags: datetime
---


title: How to implement jQuery?

text:
# Question
Title: How to implement jQuery?
I want to add a slideshow in my Drupal website. But i dont know how to add jQuery file in Drupal.

# Answer
Drupal already ships with jQuery, you don't need to add it yourself.

* Drupal 6 comes with v1.2 (can be upgraded to 1.3.2 with jQuery Update)
* Drupal 7 comes with v1.4 (can be upgraded to 1.5.2 with jQuery Update, higher with the dev version).
> 3 votes

# Answer
You probably dont want to randomly add a plugin and manipulate the markup on page but rather use the CMS and various modules to achieve your goal. The thing with Drupal is someone has usually done it. In this case the 'views\_slideshow' module is probably the best out there.

http://drupal.org/project/views\_slideshow

There alot invloved in configuring this initially but when you have done your see the benefits. If you dont use the CMS to your advantage, your going to find it difficult to manage or for most of us, your client would be able to manage it.

Alternatively, you could add a JS file on the theme layer either in your .info file

```
  scripts[] = js/scripts.js

```

Or through a template function

```
function THEME_preprocess_html(&$vars) {

  drupal_add_js(path_to_theme() . '/js/SOMEFILE.js');

}

```
> 2 votes

# Answer
in some cases that you want a specific slideshow that drupal doesnt already have, you need to theme it yourself, you can add your .js file in your drupal .info like this:

```
scripts[] = "scripts/script.js"

```

in other cases other answers are good to go
> 1 votes

# Answer
Here is some more information

**Adding JavaScript** There are two ways for Themes to easily add JavaScript to a page.

**In .info File**

```
scripts[] = foo.js

```

**In template.php**

```
<?php
function example_preprocess_html(&$variables) {
  $options = array(
    'group' => JS_THEME,
  );
  drupal_add_js(drupal_get_path('theme', 'example'). '/foo.js', $options);
}
?>

```

**To add a library**

```
<?php
drupal_add_library('system', 'ui.autocomplete');
?>

```

**JavaScript behaviors**

JavaScript behaviors

Drupal uses a "behaviors" system to provide a single mechanism for attaching JavaScript functionality to elements on a page. The benefit of having a single place for the behaviors is that they can be applied consistently when the page is first loaded and then when new content is added during AHAH/AJAX requests. In Drupal 7 behaviors have two functions, one called when content is added to the page and the other called when it is removed.

Behaviors are registered by setting them as properties of `Drupal.behaviors`. Drupal will call each and pass in a DOM element as the first parameter (in Drupal 7 a settings object will be passed as the second parameter). For the sake of efficiency the behavior function should do two things:

* Limit the scope of searches to the context element and its children. This is done by passing context parameter along to jQuery:
`jQuery('.foo', context);`
* Avoid processing the same element multiple times.
In Drupal 6 assign a marker class to the element and use that class to restrict selectors:
`jQuery('.foo:not(.foo-processed)', context).addClass('foo-processed').css('color', 'red');`

In Drupal 7 use the jQuery Once plugin that's bundled with core:
`jQuery('.foo', context).once('foo').css('color', 'red');`
> 1 votes

---
Tags: javascript
---


# Question
Title: How can I exclude folders when updating drupal using drush?
How can I use `drush pm_update` and exclude some folders? For example, I don't want to update Sites and Profiles folders.

# Answer
> 4 votes
If you want to update Drupal core without updating contrib, use `drush pm-update drupal`. Always upgrade a copy of your site and test it before modifying your production site.

If you want to avoid updating just a specific contrib project, use `drush pm-update --lock=skipthis`. The lock is persistent until removed with --unlock.

---
Tags: drush, updating
---


# Question
Title: Upload one image but save/export to multiple formats
Have been searching for this quite some time but I can't seem to find an answer. There must be someone who has encountered this before.

What I want to do is have an editor upload 1 image and then save/export it to multiple formats. Automatically save a thumbnail, smaller teaser version and a version that has a color filter. I don't want to create 3 upload fields and have the editor choose a filter.

Any help is appreciated.

# Answer
> 0 votes
If you are on Drupapl 7 then in Admin You would see Image Style. Once you are there you can define different presets such as thumbnail, large, medium etc. There are three predefined presets available. But you can add your own with the dimensions of your choice. Once you set that you can use that where ever you display in the image.

In views or fields display management with in the content type.

For advanced filters you should look into the imagecache actions

---
Tags: files, media
---


# Question
Title: Sample Images not showing (Omega Kickstart theme)
Sorry for this beginners question: I made a fresh installation of Drupal 7 and then installed "Omega Kickstart" theme by copying the zip-isntallation-link under http://drupal.org/project/omega\_kickstart

However, the file is only about 300 Kbit and indeed there is no sample images showing - in fact only one logo changed on my startpage and a slightly different formated text.

**Is it possible to install the theme with all the sample-images and modules?**

# Answer
> 0 votes
The Omega Kickstart is just a theme; it doesn't contain any module. You are probably interested in the Commerce Kickstart distribution, which contains the Drupal Commerce module, and any of its dependencies.

> Commerce Kickstart is the quickest way to get up and running with Drupal Commerce. It includes the latest versions of Drupal core, Drupal Commerce, and the other modules it depends on. It also gives you a set of options to create a fully-featured demo store out of the box complete with an attractive theme, catalog and search configuration, and a custom back office interface.

---
Tags: theming
---