# Question
Title: How to change the Drupal Commerce Stock formatter?
Drupal Commerce Stock displays the correct number of stock. For example:

Product Name, Price: $ 1.00, Stock: 20.

I would like to change the stock levels to 1, 2, 3, 4 and 4+. So if the stock level is 5 or more, the displayed stock will be 4+. What's the best way to do this?

# Answer
If you want to display the stock of a product with 4+ when it's \>5, assuming that you've got stock a field attached to the product and exposed to the node display (default behavior) you can use hook\_entity\_view\_alter or hook\_node\_view\_alter to alter the #markup of $build\['product:field\_stock'\]
> 0 votes

---
Tags: commerce
---


# Question
Title: Why are the regions being highlighted when I mouse over on them?
On each region hover over the region is highlighted with a background colour of light blue and the border changes to red. I cant work out whats causing this (i'm a newbie). Im using a base theme of ninesixty and only have a few additional modules installed. Its not a browser addon as I see the same thing in firefox and chrome.

Please help!

# Answer
> 1 votes
This is a debugging feature that this theme uses. Disable this line (or similar) in ninesixty.info by adding a semicolon before it.

```
stylesheets[all][] = styles/framework/debug.css

```

Then clear caches for example on this page: admin/config/development/performance

---
Tags: theming
---


title: How to add custom images to header

text:
# Question
Title: How to add custom images to header
I would like to add some custom images into the header block of my website and the problem is that I don't know if I should modify some php file or if it is possible via admin panel. Which method is better and if it is better to modify a file, which file is it and where is it located.

Thank you in advance.

# Answer
The simplest way: Add a block at admin/structure/block/add. Add the html for your images directly into Block body. Make sure the text format is Full HTML. Assign your block to Header region.

Before this, you need to upload the images on your server. You can either upload them directly to your theme folder or create an image content type with image field and use that to upload your images.
> 2 votes

---
Tags: theming
---


# Question
Title: How do I create content importing data from an Excel file?
I am using Drupal 6 and created a custom content type. I have an excel sheet that has more than 2 lacs entry. It is not easy to enter manually.

Is there is any way to this, either programmatically or from the UI?

# Answer
> 2 votes
You need the Feeds module.

1. Export your excel sheet as CSV with column headings quoting every cell.
2. Download and install the Feeds module (and optionally Feeds Tamper).
3. Create a new Feeds importer to consume the CSV. http://example.com/admin/structure/feeds/create Set *Fetcher* (change) to **file upload**, *Parser* (change) to **CSV parser** and Processor to Node processor.
4. Map (exactly) your column headings in Node processor mapping.

I've used this with great success in Drupal 7 and once in Drupal 6. PS: Upgrade to D7.

---
Tags: 6
---


title: managed links in Wysiwyg?

text:
# Question
Title: managed links in Wysiwyg?
I am looking for a systematic way to deal with links in Drupal, like there is for images. For images, you add image field to content type, then install "Insert" module and you can use Wysiwyg to easily insert the image anywhere inside the node content and still have it "manageable" because it is a field.

I am looking for something similar for links (external and internal), but can't think of any existing method. What I have found is to either use "Links" module and have all links displayed at the bottom of the node (via a field) or use Wysiwyg "Link" button and insert links anywhere, but they are unmanaged.

I am looking for a solution where:

1. All links would be more easily managed - because they would be kept as fields (most probably "Link" field)
2. It would be possible to have those links displayed not as a link list at the bottom of the node, but rather in various places inside node content (like images with "Insert" module).

# Answer
> 1 votes
I would recommend that you base your solution on the ckeditor\_link module. To use this module, you will of course need to be using ckeditor for your wysiwyg editing. If this is not a problem, then users will be able to use a new "Internal Link" URL type when creating links. Typing in the node title of the target will make a link to node/1234, and this link will be transformed into a link to the node's path alias at render time. Now, your internal links will automatically change if you edit the path alias of the node; there is nothing else you need to do to manage them.

For external links, I would make a new node type for external links, and make a landing page for each one. Use a link field on the landing page to hold the external link, and put boilderplate text in your template for that content type. Once you've set this up, you can again use the ckeditor\_link module to target your landing page. If you don't like the idea of a landing page and you're a little handy with coding, you could make your own version of ckeditor\_link for external links, and modify its input filter to render the URL of the target link instead of the URL of the landing page.

# Answer
> 1 votes
camcam, The best module I found so far is LinkIt, it can be either integrated into TinyMCE or can be used on standalone fields. It does allow for internal vs. external links flexibility on standalone fields, so should solve your issue. Hope this helps.

---
Tags: 7, entities, navigation, wysiwyg
---


# Question
Title: restrict some url access, based on user roles
I am theming an administrative page.
There are 2 roles (admin, role2) that have access to all the administrative pages. Now, I want to restrict the access to some URLs to the *role2* role: Users with that role should be redirected to other pages. How is this done using the template?

I know I can use permissions to restrict the access, but I want to restrict the access basing on the URL being visited.

# Answer
> 4 votes
You can implement hook\_menu\_alter in your custom module and can provide function for 'access callback' property of the menu item.

```
<?php

/**
 * Implements hook_menu_item_alter()
 *
 */
function custom_feature_menu_alter(&$items) {

  $items['admin/structure/types']['access callback'] = 'custom_feature_access_callback';

}

/**
 * Custom access callback
 */

function custom_feature_access_callback($arg) {

  global $user;

  $roles = array_keys($user->roles);

  //Adding condition for the user roles. You can change 3 to your user role. I have tested this with administrator user role
  if (in_array(3, $roles)) {

    return FALSE;
  }
  else {
    return TRUE;
  }

}

```

---
Tags: uri, redirection, users
---


# Question
Title: How to make a user not being able to publish his content?
how is this possible to make a user/role not being able to publish content he has created ,but to be able to create new (unpublished) content? thanks

# Answer
One way of doing the same is using the hook\_node\_presave() and set the node to unpublish for certain users/roles as below:

```
/**
 * Implements hook_node_presave().
 */
function MyModule_node_presave($node) {
  global $user;
  $user_id = $user->uid;

  // Check if the author of node is user whose content you want to unpublish,
  // similarly for checking the user role: "in_array("USER_ROLE_TO_CHECK",$user->roles)"
  // To add the add check for content type, add "$node->type === 'CONTENT_TYPE'"
  if (($user_id === 'USER_ID_WHOSE_CONTENT_IS_TO_BE_UNPUBLISHED') && (!isset($node->original))) {
    // Unpublish nodes when node is created:
    $node->status = 0;
  }
}

```

This will always unpublish the content created by the user belonging to that user\_ids/roles.

---

Alternatively you can use the Override node options module: The Override Node Options module allows permissions to be set to each field within the Authoring information and Publishing options field sets on the node form.
> 0 votes

# Answer
How about `[implementing hook_node_presave($node)][1]` in your custom module,so as example code consider the following

```
function mymodulename_node_presave($node) {
  global $user;
  // check if user has role and checking node->original is not set ensures it works only when insertion of node happens not when it is edited
  if (in_array("your_user_role",$user->roles) && (!isset($node->original))) {
    // keep the node unpublished
    $node->status = 0;
  }
}

```
> 1 votes

# Answer
You can achieve this functionality using below step.

* Go to Administration -\> Structure -\> types.
* Edit your content type.
* Uncheck 'Published' check-box under 'Publishing options' fieldset in the form.

Now, when any user except administrator of the site, create new content, by default content be unpublished. Only administrator or user which has permission to override publishing options, can published or modify publishing options.

If you would like use to access their unpublished content, you need to provide access 'View own unpublished content' to user role.
> 1 votes

# Answer
I think I found this,with these two modules https://drupal.org/project/publishcontent and https://drupal.org/project/override\_node\_options
> 0 votes

---
Tags: nodes
---


title: installing twitter and oauth on drupal

text:
# Question
Title: installing twitter and oauth on drupal
I have just been trying to get twitter going on my drupal 7.21 website. i followed the tutorial at http://drupal.org/node/1346824 Everything was fine until the last step of authorising a twitter account, when i got a blank page back from the twitter app and a message saying "unauthorised oauth request". I've tried re-installing, messing with callback URL's etc but cannot get anything to work. Has anyone else solved this problem? Thanks Andy

# Answer
> 1 votes
After the new Twitter API upgrade, I would recommend using the Twitter Pull sandbox project. It works beautifully.

# Answer
> 0 votes
make sure to put correct "OAuth Consumer key" and "OAuth Consumer secret" from admin/config/services/twitter/settings

---
Tags: authentication-authorization, social-network
---


# Question
Title: Is there a way to download Drupal without any included Documentation?
Drupal comes with heavy Documentation. Many files sometimes have more documentation than code in that file.

Is there a way to download Drupal files without the included Documentation?

Also, if I do find such a version of Drupal, will there be any performance improvement in my Drupal site?

# Answer
There is no way to download Drupal and it's module without documentation that is provided in comments. If you are really concerned about performance, use opcode cache, for example APC \- it will store precompiled opcode in memory, so the comments will not need to be loaded at each request.

PHP engine is pretty well optimized at skipping non-code parts of PHP files, so the memory requirement is the only thing that may really hit you. Exception are primarily-HTML files - getting in and out of `<?php ?>` blocks costs a minuscule amount of CPU power, so constructs like `<?php /* some docs */ ?>` adds a tiny bit of load on CPU - but again, you shouldn't be able to fill the difference, and if you are, opcode caching is the way to go.
> 2 votes

# Answer
Short answer: no.

Long answer: you don't need it. It does not provide almost any significant performance improvements and if you would make such package/distribution yourself, you would need to filter out the comments/documentation in core and all additional modules yourself. This would make it extremely hard to debug, learn from source, extend and most of all maintain after updates for documented Drupal are published.

There are many ways to improve performance of a Drupal site. Start reading about APC, caching strategies and best site building techniques to learn about that.
> 3 votes

---
Tags: 7
---


# Question
Title: Cannot insert very long text in long text field
When I insert a very long text in a long text field, Drupal shows this error:

> Data too long

This field is allocated for articles in a content type, so I am sure the data will not be longer than some extent, but when the number of characters is almost more than 30000, it shows the error. Is there any default limitation on it?

The exception I get is the following one:

> PDOException: SQLSTATE\[HY000\]: General error: 1406 Data too long for column `'source'` at row 1: `INSERT INTO {locales_source} (location, version, source, context, textgroup) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4);`

# Answer
> 4 votes
Maximum theoretical data length in this database column is 4'294'967'299 characters (less than 232)

It is also limited by:

> The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers.

"Data too long" is a MySQL error message, not Drupal one, so you need to re-configure your MySQL if you want to allow longer texts in body (or any other field)., as described in MySQL documentation.

---
Tags: 7, entities, database
---


title: Submitting fieldsets

text:
# Question
Title: Submitting fieldsets
I have fieldsets in my form like this

```
$form['fieldset_1']['name']

```

and then

```
$form['fieldset_2']['name']

```

but when I submit the form and access the values item in $form\_state there is only one name value - not as expected `['fieldset_1']['name']` and `['fieldset_2']['name']`

can someone help how the form could be submitted and to have access to bot name values ?

# Answer
You can use the `#tree` property on both fieldsets, e.g.

```
$form['fieldset_1'] = array(
  '#type' => 'fieldset',
  '#title' => t('Title 1'),
  '#tree' => TRUE,
);

$form['fieldset_1']['name'] = array(
  '#type' => 'textfield',
  ...
);

$form['fieldset_2'] = array(
  '#type' => 'fieldset',
  '#title' => t('Title 2'),
  '#tree' => TRUE,
);

$form['fieldset_2']['name'] = array(
  '#type' => 'textfield',
  ...
);

```
> 5 votes

---
Tags: forms
---


title: Drupal module for download limit

text:
# Question
Title: Drupal module for download limit
Is there any Drupal 7 module there, that can restrict any user, based on role/privilege, number of downloads per day. For example, 'x' type of user can download 10 files/day.

# Answer
I don't think such module exist. But you can write your own module. Download Count may help you while writing your custom module.
> 1 votes

---
Tags: 7, files
---


title: Recursively pre-populate Webforms

text:
# Question
Title: Recursively pre-populate Webforms
I am trying to pre-populate a webform based on the values from a third party service.

I am using form\_alter to start the processing and then using a recursive function to traverse the tree. I am passing the sub-form(part of a form of type fieldset) by reference, so that changes do carry forward.

Here is the code :

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
    $submitted = $form['submitted'];
    prepopulate_form($submitted, $value_array);
}

function prepopulate_form(&$form, $value_array) {
  foreach ($form as $key => $settings) {
    if (is_array($settings) && isset($settings['#type'])) {
      if ($settings['#type'] == 'fieldset') {
        prepopulate_form($form[$key], $value_array);
      }
      $value = 'Some logic to get the value from value arrya';
        dpm($value); // I am getting the expected output here.
        $form[$key]['#default_value'] = $value; // The changes I make here are not being carried to the actual $form array I suppose
    }
  }
}

```

But the form is not getting pre-populated. I am not sure what I am missing here.

Any insights would help. Thanks !

# Answer
> 4 votes
The main problem is you are not passing the form array by reference so your values are never coming back into the form. Try this (note the ampersand on $form\['submitted'\]):

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  $submitted = &$form['submitted'];
  prepopulate_form($submitted, $value_array);
}

```

Otherwise you are only modifying the $submitted variable and not the actual form.

Alternatively, you could also just pass $form\['submitted'\] into the prepopulate\_form() function instead of using the $submitted variable and that would also work.

Plus, you are using $value\_array, which does not exist, so you will need to pass actual values in.

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


title: Failed to disabled specific page

text:
# Question
Title: Failed to disabled specific page
I'm creating an e-commerce using drupal.

In this site I have several catalogs to distinguish between some products. Let's say I have url `site_home/catalog/1` , `site_home/catalog/2`, `site_home/catalog/3`, and site\_home/catalog/4\`.

I need to disable view for /catalog/1 , /catalog/2 and /catalog/3, but everyone can view /catalog/4 and newly created catalog in the future which will have id \> 4.

I've tried using Pages Module to disable those pages.

I've created new rule with this module which is called /catalog/%catalog with arguments for %catalog is string. And then for Access Rule I added a criteria String: URL path. Current path type is not one of "catalog/1, catalog/2, catalog/3" but when i enabled this rule I got:

```
/catalog/1 - /catalog/3 --> access denied
/catalog/4 --> page not found

```

Any ideas why this is happening, and which settings did I missed?

# Answer
If you are using taxonomy terms for your catalog you could try using taxonomy term permissions https://drupal.org/project/term\_permissions. If you are using a view for each catalog you can just restrict access to each view as you like.
> 0 votes

---
Tags: users, 7
---


# Question
Title: how to bulk edit all users (change city field for example)
I need to run bulk operations on all the users. Like changing the value of a field for all users.

I am using Profile 2 module for extended profile fields.

# Answer
You can use views and views bulk operations for this.

You can create a user view and add a relationship that joins it to the profile2 profile.

Then add the views bulk operations field and configure it to include the "Modify entity values" operation. You could also change the label to "Change profile values" or something if you prefer.

Then on your bulk operations view, select the checkboxed for all the users you want to update a value for, select the "Modify entity values" operation, click the execute button, then complete then next form.

When you do this, you must be setting the fields to the same values for all the users you selected.

If you need to give some users a different value you have to go through the process multiple times.

If you have lots of different data and it wouldn't be feasible to go through this process so many times then you would be better off using something to import your data from csv, like the feeds module or the migrate module.
> 5 votes

---
Tags: users, views
---


title: Why user_save overrides user picture?

text:
# Question
Title: Why user_save overrides user picture?
I have a user profile form. If a user selects a picture, it's uploaded and shows on user profile but If user just updates other details and leaves the picture the same the user\_save overrides the user picture and then there is no user picture. My code is like this.

```
if(!empty($_FILES['files']['name']['profile_image']) && isset($_FILES['files']['name']['profile_image']) && ($_FILES['files']['size']['profile_image'] != 0)) {

        $filepath = 'public://pictures/';
        $file = file_save_upload('profile_image', $validators, $filepath);
        $file->status = 1;
        file_save($file);
        if(isset($file) && !empty($file) && !is_null($file)) {
            $loaded_user->picture = $file;
        }

    }
user_save

```

# Answer
> 3 votes
I assume you are not setting you default\_value for the file field and that you are using a managed\_file field.

The default value should be the fid of the file that has been uploaded before.

Something like this:

```
$form['profile_image'] = array(
  '#title' => t('Profile picture'),
  '#type' => 'managed_file',
  '#description' => t('Upload a photo for your profile.'),
  '#default_value' => $previously_uploaded_file->fid,
);

```

In your case I'm not exactly sure where the $previously\_uploaded\_file-\>fid will come from, but I assume it will be in your form or form state or else you will have to get it from the database or something.

If you are using a regular file field instead of a managed\_file file field I don't believe you can set a default value.

In that case you have to make sure that when you do the user save that you are not overwriting the file with an empty value.

---
Tags: users
---


# Question
Title: How to avoid clearing of the form state?
I want to add form field based on data provided in submit handler. I am using `$form_state` for the job. I have done similar in the past but now it's just not work

Form code:

```
function module_form($form_state) {
 if (isset($form_state['module']['data'])) {
   //add field
 }
}

function module_form_submit($form, &$form_state) {
  $form_state['no_redirect'] = TRUE;
  $form_state['rebuild'] = TRUE;
  unset($form_state['redirect']);
  $form_state['module']['data'] = module_get_data($some_value);
}

```

Inside module\_form `$form_state` is always empty...

# Answer
> 2 votes
This:

```
function module_form($form_state) {

```

needs to be changed to this:

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

```

The function sig for forms changed in Drupal 7 to the second example above.

---
Tags: 7, forms
---


# Question
Title: change save button text of a node to submit
I am using drupal 7.10 I have a content type in which i want to change the save button text to submit.I tried various posts in this forum to no avail.i need help on this.Thanks in advance.

# Answer
This is the complete `$form['actions']['submit']` array the Node module uses for the form.

```
  $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#access' => variable_get('node_preview_' . $type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
      '#value' => t('SaveTest'),
      '#weight' => 5,
      '#submit' => array('node_form_submit'),
   );

```

You need to hook into the node form.

```
/**
 * Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['#node']) && $form_id == YOUR_NODE_TYPE . '_node_form') {
    $form['actions']['submit']['#value'] = t('YOUR_NEW_VALUE'),
  }
}

```
> 7 votes

# Answer
This should be pretty easy using a hook\_form\_alter, replace CONTENTTYPE with the machine readable name of your content type and MYMODULE, remember to always use underscores ("\_") too.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'CONTENTTYPE_node_form') {
         $form['buttons']['submit']['#value'] = "submit";
   }
}

```
> 6 votes

# Answer
Due the mistake I did, I'm going to change my answer from:

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'CONTENT_TYPE_node_form') {
     $form['actions']['submit'] = array(
              '#value' => t('your_value'),
     );
  }
}

```

or via jQuery...

```
$('#form_id').val('your value');

```

to:

```
function YOUR_MODULE_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['#node']) && $form_id == CONTENT_TYPE . '_node_form') {
    $form['actions']['submit']['#value'] = t('your_value'),
  }
}

```

or via jQuery

```
$('#form_id #input_id').val('your value');

```
> 2 votes

# Answer
Try out Node buttons edit module.

> This is a simple little module that allows one to change the text on the 'Save', 'Preview' and 'Delete' buttons on a node form.
> 2 votes

---
Tags: nodes
---


# Question
Title: Date Validation according to different type
I met a problem when create a new content.

I created a content type, it has a field named Type, this field have two values. When select "normal", another field Date will be hidden. When select "renewal", another field Date will display.

Now I want to compare start date and end date before save this content. On one way, I used field validation, but it always give warning for both "normal" and "renewal".

On the other, I add new rules to compare the date, but it gives warning always after saved the content.

Anyone could help me to solve this problem? very appreciate for this.

# Answer
> 0 votes
use `strtotime()` on both the date fields and then compare that value in the validate function of the form.

---
Tags: forms, rules
---


# Question
Title: Converting a left join query with empty right side to Views
On a multilingual site, I'm trying to create a view on nodes where the content should be either in the current language, or in English if no translation exists in the current language. After trying to solve this with the Views web interface for a while, I figure that what is provided for filtering is simply not sufficient.

So I'm thinking of adding module code, to extend Views to support this particular use case.

Starting from then end result, this is what the constructed query should look like:

```
select node.* from {node} node  -- provided by Views
-- join:
left join {node} tnode on node.tnid = tnode.tnid and tnode.tnid > 0 and tnode.language = ***CURRENT_LANGUAGE***
-- condition:
where (node.language = ***CURRENT_LANGUAGE*** or node.language='en' and tnode.nid is null)

```

I'm assuming that `***CURRENT_LANGUAGE***` is a macro that will be replaced by the actual value of the current language; 'en' might be an argument, chosen in the admin interface, but that is not really important.

But now I'm stuck on how to actually code this up for Views.

Any help, including alternative approaches, welcome.

# Answer
> 0 votes
You can use this function

```
function MY_MODULE_views_query_alter(&$view, &$query) {
    if($view->name == 'view_name'){
       }
}

```

https://api.drupal.org/api/views/views.api.php/function/hook\_views\_query\_alter/7

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


# Question
Title: How do I add a Product to the Cart programmatically in Ubercart?
I'm creating a section of my site where users must purchase individual nodes of a certain content type. In an effort to enhance usability, I allow the user to create the node without paying, but then save it as "Unpublished" so it's not yet visible on the site. Then, once the user pays, we'll publish their node. So whenever a user creates a node of a particular type, it should add a Product (which represents the right to post that particular node) to the user's Cart.

I know I can implement `hook_nodeapi()` to hook into the node creation event, but how do I add the product to their cart?

# Answer
> 9 votes
Is the node that users create is a valid product type node? In any case you can try this - http://api.lullabot.com/uc\_cart\_add\_item

```
uc_cart_add_item($nid, $qty = 1, $data = NULL, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE)

```

Here $nid = nid of the product, $cid = cart id (also user id) - look at http://api.lullabot.com/uc\_cart\_get\_id

Hope this helps.

# Answer
> 2 votes
You can use the following code, where $nid is your product node id:

**Drupal 7**

```
  $nid = 4844;
  $form_state = array(
    'values' => array(
      'nid' => $nid,
      'qty' => 1,
    ),
  );
  $node = node_load($nid);
  drupal_form_submit("uc_product_add_to_cart_form", $form_state, $node);

```

**Drupal 6**

```
  $nid = 4844;
  $form_state = array(
    'values' => array(
      'nid' => $nid,
      'qty' => 1,
    ),
  );
  $node = node_load($nid);
  drupal_execute("uc_product_add_to_cart_form", $form_state, $node);

```

# Answer
> 0 votes
For anyone else who comes to this... bsenftner's comment is incorrect. Nodecheckout lets customers create a node before paying.

"So whenever a user creates a node of a particular type, it should add a Product (which represents the right to post that particular node) to the user's Cart."

... is exactly what Nodecheckout does.

I have a working classified advert system whereby the user creates their advert. On saving, Nodecheckout adds a (product) node called "Classified Advert - 6 Months" to their cart. Paying for this product publishes their node.

Even anonymous users can create an advert and then have their account created as part of the checkout process.

---
Tags: ubercart
---


title: Rules content unpublish in 30 days

text:
# Question
Title: Rules content unpublish in 30 days
I've followed this thread https://groups.drupal.org/node/240678#comment-782543, but that's based on a date field and it has a different scenario.

My idea is: When a new content is created, after 30 days will be automatically unpublished.

How can I achieve this without using additional date fields?

# Answer
> 2 votes
Instead use Auto Expire module, Using this module you can set the node to unpublish after 30 days.

For your case set zero in purge field, otherwise it will automatically delete from database.

> This module allows site administrators to set expiration times for content types.
>
> End users creating content that has auto expiry set cannot control the expiry time. They could be allowed to renew the content for one or more cycles.

---
Tags: rules
---


title: style views_slideshow pager

text:
# Question
Title: style views_slideshow pager
Is there a way to change views\_slide show "image 1 of 3" to be 3 circles, where the active one is black and the rest are grey? I tried doing that in CSS but does not look like its the right approach for doing this.

# Answer
@Scorchio Thanks for that. I was successfully able to convert the layout from '1 of xx' to '1 2 3 4 5 6 x' by overriding views-slideshow-slide-counter.tpl.php and modifying the views\_slideshow.js. My changes are below.

### views-slideshow-slide-counter.tpl.php

```
<div id="views_slideshow_slide_counter_<?php print $variables['vss_id']; ?>" class="<?php print $classes; ?>">
<?php
    $slide_count = count($view->result);
    for($i=1;$i<=$slide_count;++$i)
        print '<span class="num'.$i.'">'.$i.'</span> ';
 ?>
 </div>

```

### views\_slideshow.js

```
Drupal.viewsSlideshowSlideCounter.transitionBegin = function (options) {
  $('#views_slideshow_slide_counter_' + options.slideshowID + ' span').removeClass('active');
  $('#views_slideshow_slide_counter_' + options.slideshowID + ' .num' + (options.slideNum + 1)).addClass('active');
};

```
> 5 votes

# Answer
*\[I don't know which version you're using - I'm checking a version of Views Slideshow which is tagged 7.x-3.x right now in the project repo. It shold be similar for earlier versions.\]*

I'm sorry for not being able to give a complete recipe, but here are my tips anyway.

* The **theme/views-slideshow-slide-counter.tpl.php** file contains the text part for the text you've mentioned. Pay attention to the `<span class="num">`, because...
* ...the **js/views\_slideshow.js** file contains the necessary jQuery bits for modifying that number (see around line 381):

```
/**
 * Implement the transitionBegin for the slide counter.
 */
Drupal.viewsSlideshowSlideCounter.transitionBegin = function (options) {
  $('#views_slideshow_slide_counter_' + options.slideshowID + ' .num').text(options.slideNum + 1);
};

```

If you could hook into that jQuery or override it in some way, that would solve your problem. (I don't really know how to do that - my Drupal-related Javascript skills could get some polishing, but hopefully that's enough for a good start.)
> 2 votes

# Answer
The pager widget in the View settings gives you all the CSS classes you need to do this.
> 0 votes

---
Tags: views, javascript
---


# Question
Title: View is returning two default results when no value in filter is being selected. Why?
I have created a view to display node's title and added exposed filter for filtering content. When the view page is loaded it is returning two nodes , I do not know on what basis it is returning those two nodes.I want no result should be displayed until I select some value in filter.Please suggest ??

# Answer
There is a views setting "Exposed form style", where you can select "Input required" if you don't want results to be displayed by default.

See the attached screenshots:

Then
> 2 votes

# Answer
When you add a filter under Filter criteria, and select "Expose this filter to visitors, to allow them to change it", also check the "**Required**" checkbox. This will make the view not show any results until this filter has been submitted.

**Update**: this works generally (e.g. with the operator 'Contains' on a field), but not when the exposed filter is Content: Type. You can work around the error by checking "Limit list to selected items" and checking the content types that may be selected. However, now the view will initially be filtered on the first content type of the select list, instead of empty. See this Views issue.

**Alternative solution**

You can use the approach outlined here:

* Choose Filter type to expose: Grouped filters
* Deselect 'Optional'
* Create a default option, e.g. a label 'Choose a content type', operator 'Is not one of' and select all available content types. This will return your empty view.
* Create a label for each content type you want to expose and use 'Is one of' operator, with the corresponding content type checked.
> 0 votes

---
Tags: views
---


# Question
Title: hook_menu, display a form at the top and table at the bottom
I'm a bit lost trying to create a page with hook\_menu that displays a form and a table below it. Preferably the table should only be displayed after the form has been submitted, but that's not the main issue.

I don't have any issue with displaying the table or the form, but I can't get it to be displayed at the same time on the same page.

I have a `my_module_table()` function that ends with

```
...
return theme('table', array( 'header' => $header,  'rows'=> $rows  ) );

```

I then have a function for the form `my_module_form($form, &$form_state)`

I then have this function to put both of these functions in an array

```
function my_module_page() {
  $output = array();
  $output['form'] = drupal_get_form('my_module_form');
  $output['table'] = 'my_module_table';
  return $output;
}

```

Than last I try to create the page and get both the form and the table to render on the page using **hook\_menu**

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

  $items['mymodule'] = array(
    'title' => 'My module',
    'access callback' => TRUE,
    'page callback' => 'mymodule_page',
  );
  return $items;
}

```

I don't have any issues with the form or table functions, they work fine if I don't try to render both at ones.

Can anybody tel me what I'm doing wrong?

# Answer
You can change this:

```
$output['table'] = 'my_module_table';

```

To this:

```
  $output['table'] = my_module_table();

```

Also note that this:

```
...
return theme('table', array( 'header' => $header,  'rows'=> $rows  ) );

```

Can be this:

```
...
return array (
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('Nothing found. Nada. Zip. Zilch.'),
);

```

This will add this fragment to the render array you are creating in my\_module\_page(), meaning it can be overridden further down the line if necessary.
> 1 votes

# Answer
Here's an implementation of my earlier suggestion to append the table as a form markup and rendering the form with table in the menu callback

```
/**
 * Form builder function
 */
function mymodule_form() {
  $form = array();
  $form['sometext'] = array(
    '#type' => 'textfield',
    '#title' => t('Some random textfield'),
    '#default_value' => 'Hello world',
  );
  $form['tablemarkup'] = array(
    '#markup' => my_module_table(),
  );
  return system_settings_form($form);
}

/**
 * Callback function for returning form with themed table
 */
function mymodule_page() {
  $output = array();
  $form_data = drupal_get_form('my_module_form');
  $output = drupal_render($form_data);
  return $output;
}

/**
 * Function to return themed table.
 */
function my_module_table() {
  $header = array(
    'data' => 'Table title',
  );
  $rows[] = array(
    'Table data value',
  );
  return theme('table', array('header' => $header, 'rows'=> $rows));
}

```
> 2 votes

# Answer
You should convert your output to a renderable array for starters, but you could try something like

```
$output = render(drupal_get_form('my_module_form'));
$output .= my_module_table();

```

i think it will work, edited.
> 0 votes

---
Tags: 7, routes
---


# Question
Title: Views: How to show titles of nodes but hide link based on role
In views (D7) i made a list of nodetitles that link to content. Some nodes are not accessible for anonymous users, others are. I want the view to list accessible nodetitles with a link but non-accessible titles without a link. How can i do that? I use content access for setting permissions on individual nodes.

What if i add two fields for Title, one with a link to content and one without. Both fields excluded from display. I can add a binary (or whatever works) field in my content type telling views if visitors should have access to an individual node. Nodes that allow access should (manually) be set open with content-access. That isn't the best way because it requires two edits for every node that should be accessible, but i don't mind.

Than i can make a Views-PHP field that tests on the binary field and either displays the first title-field or the second.

Anyone can help me with some rough coding example for this?

# Answer
I found it. I added a boolean field with Yes as the value for access, No for no access. This requires some careful management, as the value of this field has to equal the given access control. But in Views everything is very easy, using the extra boolean field. I added both Titles (Title1 being the one without a link, Title2 with link) and the boolean field. Both titles excluded from display, the boolean included. In its settings rewrite i input \[Title2\], and in the empty behaviour \[Title1\]. That's all.
> 1 votes

# Answer
You could use Views PHP module

First you would add the title field and additionally a path to the current node as well.

Then you can add a views php field and with in this field you can check the permissions for the current user or the role of the current user or any other logic you want to put. Then depending on the role either you can simply print the title or title with the link.

Another option would be to override the field template and do the same logic there. that is check the current role and if the role is not allowed to see the link then only print the title id they have the permission then print with the link.

You might want to set access restriction to none. (Should be careful with this one as all the permissions with in the view would be disabled. So all the quries would be run without checking the permissions.)

There are some gotchas. The module is in dev stage so should use the module with care. and using php should be done carefully. Unsecured code can damage the site's security.
> 0 votes

---
Tags: views, users
---


title: Form is not submitted with arg() in URL

text:
# Question
Title: Form is not submitted with arg() in URL
I have a list of items. By clicking on an item I open a form at /items\_form/123 where 123 is the itemid. When filling the form I use the arg() function to get the 123 and read some data from the database. No problem.

My problem is, when submitting the form, the default submit handler is not called. When I open the form without the arg e.g. /items\_form and submit this form, the submit handler is called. Where is my missing link? Here is my hook\_menu:

```
$items['items_form'] = array(
'title' => 'Item Form',
'page callback' => 'drupal_get_form',
'page arguments' => array('get_item_form'),
'access arguments' => array('access items_form content'),
'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
);

```

Any ideas?

# Answer
> 1 votes
First, if you want to get an argument from the URL, you should declare it in hook\_menu, as such:

```
$items['items_form/%'] = array(
  'title' => 'Item Form',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('get_item_form', 1),
  'access arguments' => array('access items_form content'),
  'type' => MENU_NORMAL_ITEM, //Will appear in Navigation menu.
);

```

Drupal's menu system will then pass in the itemid to drupal\_get\_form(), which will then pass it along to your form declaration function. You will need to add an argument to your function definition to access it, suggest something like this:

```
function get_item_form($form, $form_state, $itemid = NULL){
  $form = array();
    ...
}

```

Please look at the documentation for hook\_menu for more information about how to handle URL arguments. I would caution against using arg() in your code.

The reason this is important is what happens when you submit your form with a URL argument. By default, if you do not override with the #action parameter in your form, it submits a POST request to the present URL. By not declaring that your URL has an argument in it, Drupal actually doesn't know how to handle a request to \*items\_form/123\*. The only reason you see anything but a 404 when you go to \*items\_form/123\* is that Drupal attempts to find the nearest path. I suspect that since it doesn't know explicitly what to do when a request is made to \*items\_form/123\* it breaks the form submission handling.

I should also mention that you'll need to declare both \*items\_form\* and \*items\_form/%\* menu paths if you wish them both to work. They're distinct paths in the eyes of Drupal's menu system.

---
Tags: 7, forms
---


title: EntityFieldQuery HAVING clause

text:
# Question
Title: EntityFieldQuery HAVING clause
Is there any way I can use having clause with EntityFieldQuery? I want to get the nodes which have same field value similar to HAVING clause in SQL. Or do I need to do other ways? Please suggest if there is any good way to do this.

# Answer
You can use the `havingCondition` available in the query builder.

```
$query = db_select('node, 'n');

// add fields or other conditions

$query->havingCondition('nid', array(1, 2, 3), 'IN');

```
> 1 votes

# Answer
You could subclass `EntityFieldQuery` and add a `having()` method, or (probably quicker) you can add a tag to the query, and use `hook_query_TAG_alter()` to alter it when it's a standard `SelectQuery`:

```
function MYMODULE_query_my_tag_alter(QueryAlterableInterface $query) {
  $query->having('some_field > :val', array(':val' => $some_val));
}

```

To use that with your query:

```
$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->fieldCondition(...)
  ->addTag('my_tag');

```
> 2 votes

---
Tags: 7, database
---


# Question
Title: Drupal 6 - emfield is blank when logged out
I have created a content type and have added the Embedded Media Field. As i was logged in as administrator everything was showing ok but when I logged out and checked the page it was empty.

The text is showing ok but the enfield fields does not show the tumbnails of the youtube videos.

When i see the node while I am logged in as administrator everything looks correct but when I log out the corresponding emfields will not show up.

Has it to do with permissions? Because I have rebuilt them.

I check the php error.log and i see no errors.

Has anyone had any similar problem?

# Answer
> 1 votes
I'd check that permissions are actually set to view this field. If you go to `admin/user/permissions` you can see these as well as all permissions set on your site.

---
Tags: 6, entities, nodes
---


# Question
Title: Adding a Select List (Text) field to an entity bundle programmatically
I've been searching for hours, but can't seem to find a solution to this. Now, I'm able to create a plain old text field as such as this:

In moduleA.install:

```
if (!field_info_field('field_myfield')) {
  $field = array(
    'field_name' => 'field_myfield',
    'type' => 'text',
  );
  field_create_field($field);
}

```

Then, in moduleB.install, I add that field to a specific taxonomy bundle:

```
$instance = array(
  'field_name' => 'field_myfield',
  'entity_type' => 'taxonomy_term',
  'label' => 'MyField',
  'bundle' => 'new_terms',
  'widget' => array(
      'type' => 'text',
  ),
);
field_create_instance($instance);

```

What I would like is the field it creates to be a select list, instead of just a text field. I've been looking around, trying to figure it out (using "list-select" in place of type), but any time I've deviated from what's above, I get an error on field\_create\_instance when installing moduleB. I realize it's probably (hopefully) something as simple as knowing the proper widget name, but I either can't seem to find it, or am searching for the wrong thing.

# Answer
> 0 votes
The field type would be `list_text` (as defined in `list_field_info()`, and the widget type is `options_select`, as defined in `options_field_widget_info()`.

Kind of tricky to track down, but this little snippet should help in future:

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

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

```

It'll get you a complete field and instance definition of an existing field, ready to use in code.

---
Tags: entities
---


title: How to sort Apache Solr search results?

text:
# Question
Title: How to sort Apache Solr search results?
I want to make possible for the user to SORT Apache Solr results based on some taxonomy terms.How can I do that? I also want to make possible for a user to change the number of the results on the page. How can I achieve both of them? Thanks in advance

# Answer
I good way to utilize Solr for search with Drupal, is to use the Search API, is has a Solr integration module, which will allow you to setup a View with exposed filters and full text search. With the flexibility of Views, you should be able to setup the view to allow the users to sort as they wish.
> 5 votes

# Answer
I guess this comes too late for you but maybe will help someone else:

(1) Sorting can be handled with Facets: Facet API ( facetapi )

(2) # of results per page sounds like a Drupal configuration thing, maybe handled in the configuration of the Block in which you show the search results
> 0 votes

---
Tags: search
---


# Question
Title: Template page--node--<id>.tpl.php not working
I've created a page node for an about page. I've checked the node id of the node which is 11. I've created a file named page--node--11.tpl.php in my theme directory containing some test html but it's not overriding the standard page.tpl.php file. I've also tried using the following file names: page-node-11.tpl.php page-node--11.tpl.php

I've cleared the cache but still no luck.

What am I missing?

# Answer
> 7 votes
According to Drupal 7 Template (Theme Hook) Suggestions it should be `page--node--11.tpl.php` (note the double dashes):

> page--\[front|internal/path\].tpl.php base template: page.tpl.php The suggestions are numerous. The one that takes precedence is for the front page. The rest are based on the internal path of the current page. Do not confuse the internal path to path aliases which are not accounted for. Keep in mind that the commonly-used Pathauto module uses path aliases.
>
> The front page can be set at "Administration \> Configuration \> System \> Site information." In Drupal 6, at "Administrator \> Site configuration \> Site information." Anything set there will trigger the suggestion of "page--front.tpl.php" for it.
>
> The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:
>
> * page--node--edit.tpl.php
> * page--node--1.tpl.php
> * page--node.tpl.php
> * page.tpl.php
>
> Also see page.tpl.php in the Drupal API documentation for more information.

---
Tags: 7, theming
---


# Question
Title: Output block in particular region from custom module drupal 7
I have a custom module that spits out a form using the drupal form API. What I'd like to do is output a block (a custom menu) in a particular region of the page (using block regions would be the best way I'm guessing.) As of now, the block renders in the top left everytime. How can I output the menu block in a particular region of the page?

```
function client_menu(){

 $items=array();

 $items['campaign']=array(

   'title'=>'Campaign Manager',
   'description'=>'Area for clients to manage their campaigns',
   'page callback'=>'drupal_get_form',
   'page arguments'=>array('client_campaign'),
   'access arguments'=>array('access client administration'),
   'type'=>MENU_NORMAL_ITEM
 );

 return $items;

}

function client_campaign(){

$block = module_invoke('menu', 'block_view', 'menu-client-admin');
print render($block);

//a bunch of form API stuff...

}

```

# Answer
> 1 votes
Why aren't you creating a standard block which returns your form? Currently you have a page callback (http://yoursite.com/campaign), and you are injecting this into a block ...

Here is some sample code that could help you further:

```
function client_block_info()
{
    $blocks = array();

    $blocks['client_campaign'] = array(
        'info' => t('Area for clients to manage their campaigns'),
        'title' => t('Campaign Manager'),
        'region' => 'content', // Your desired region, can be edited in administration screen
        'status' => 1,
    );

    return $blocks;
}

function client_block_view($delta = '')
{
    $block = array();

    switch ($delta) {
        case 'client_campaign' :
            $block['content'] = client_block_content();
            break;
    }

    return $block;
}

function client_block_content()
{
    return drupal_get_form('client_campaign');
}

function client_campaign($form, &$form_state)
{
    // Build your form

    return $form
}

```

---
Tags: blocks
---


# Question
Title: Free Shipping for selected products in Drupal Commerce
I'm trying to set up a rule to allow free shipping for selected products. I'd like to use a boolean field with a checkbox for free shipping. If the box is ticked the product should be excluded from any postage calculations during the checkout.

I'm using the commerce and commerce shipping module.

Any help would be greatly appreciated!

# Answer
I definitely think you should give Commerce Discount a try for this, it provides a Free Shipping offer type when commerce shipping is present and thanks to Inline Conditions, you can filter for the products you might want.
> 1 votes

# Answer
Instead you can try Commerce Free Shipping module, it will change the price of the service to 0 and can display a message to the user saying the free shipping are applyed or the amount left to obtain free shipping.

> You can use this module to have a free shipping rate by:
>
> * Shipping service
> * Total amount of the line items in the cart (don't take in account the shipping line items)
> -1 votes

---
Tags: commerce, rules
---


title: Horrific errors and WSOD

text:
# Question
Title: Horrific errors and WSOD
I was installing the panels module when all of a sudden my site went to white screen of death with a whole bunch of error messages. (Check this out here: http://graphbyte.co/fuck.png ).

Right before I tried to install panels I had abandoned the process of creating a custom page. I realized I hadn't enabled the panels module, which I needed for this custom page, so I jumped into the modules page and attempted to install it.

I tried deactivating the panel module directly from the database but that had no impact on the situation.

What can I do??? Please helllllp!!

Thanks,

G

# Answer
OK I found out that that error in particular is due to not having a large enough allowed packet size in your mysql configuration. Here is a bit more info on that:

http://is.gd/pV7c2M

If you're running LAMP, here is how you can create a configuration file and increase your max packet size limit:

http://is.gd/mI3B82
> 0 votes

# Answer
For reference, here's a link to the Drupal.org documentation to check WSOD problems: https://drupal.org/node/158043
> 0 votes

---
Tags: wsod
---


# Question
Title: save the value of a custom form in the database
Why isn't the code saving values in the database?

```
module_load_include('inc', 'firstform', 'firstform_node_form_alter');

function firstform_menu() {
$items = array();

$items['submit_driven_ajax'] = array(
    'title' => 'send your email',
    'page callback' => 'drupal_get_form',
    'access callback' => TRUE,
    'weight' => 3,
);
return $items;

```

}

```
function firstform_intro() {
$markup = t('The AJAX example module provides many examples of AJAX including forms, links, and AJAX commands.');
return $markup;}

function firstform_form($form, &$form_state) {
$form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '<div id="box">',
    '#suffix' => '</div>',
);
$form['email'] = array(
    '#type' => 'textfield',
    '#required' => TRUE
    , '#description' => "Please enter your email name.",
    '#ajax' => array(
        'callback' => 'firstform_text_driven_callback',
        'wrapper' => 'box',
        'name' => 'email1',
    ),
);
$form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
        'callback' => 'firstform_submit_driven_callback',
        'wrapper' => 'box',
        'name' => 'submit1',
    ),
    '#value' => t('Submit'),
);

return $form;}

function firstform_submit_driven_callback($form, $form_state) {
$element = $form['box'];
$element['#markup'] = "your email ({$form_state['values']['email']}): " . date('c');
return $element;}

function firstform_text_driven_callback($form, $form_state) {
$element = $form['box'];
$element['#markup'] = "your email ({$form_state['values']['email']}): " .date('c');
return $element;}

 function firstform_block_info() {
$blocks = array();
$blocks['firstform'] = array(
    'info' => t('Form mail'),
    'weight' => 0,
);
return $blocks;}

function firstform_block_view($delta = '') {
module_load_include('inc', 'node', 'node.pages');
switch ($delta) {
    case 'firstform':
        $block['subject'] = t('');
        $form = drupal_render(node_add('firstform'));
        $block['content'] = $form;

        break;
}
return $block;}

  function firstform_node_insert($node){
  db_insert('firstform_node_form_alter')
->fields(array(
  'nid' => $node->nid,
  'email' => $node->firstform['email'],
  'date' => $node->firstform['date'],
))
->execute();}

function firstform_node_update($node) {

 if (db_select('firstform_node_form_alter', 'a')->fields('a')->condition('nid', $node->nid, '=')->execute()->fetchAssoc()) {
db_update('firstform_node_form_alter')
  ->fields(array(
    'email' => $node->firstform['email'],
    'date' => $node->firstform['date'],
  ))
  ->condition('nid', $node->nid)
  ->execute();
  }  else {
firstform_node_insert($node);}}

    function firstform_node_delete($node) {  db_delete('firstform_node_form_alter')
->condition('nid', $node->nid)
->execute();}

```

When I add firstform.install, the firstform\_node\_form\_alter table is not created.

```
function firstform_schema() {
 $schema['firstform_node_form_alter'] = array(
'description' => 'Stores email settings for nodes.',
'fields' => array(
  'nid' => array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0,
    'description' => 'The {node}.nid to store settings.',
  ),'email' => array(
    'type' => 'varchar',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Node Form Example 1 textfield',
  ),
  'date' => array(
    'type' => 'int',
    'length' => 256,
    'not null' => FALSE,
    'default' => '',
    'description' => 'Node Form date textfield',
  ),
),
'primary key' => array('nid'),
'foreign keys' => array(
  'dnv_node' => array(
    'table' => 'node',
    'columns' => array('nid' => 'nid'),
  ),
),
 );
return $schema;
}

```

# Answer
hook\_schema is called at install and unistall, so make sure your actually installing the module and not just turning it on.

If you've already had your module running on your site, switched it off at /admin/modules and then switched it back on, drupal doesn't recognize this as an uninstall/install event. Rather, you need to fully remove it from the DB by going to admin/modules/uninstall after switching the module off.
> 1 votes

---
Tags: hooks, forms
---


title: Change default / base language for t()

text:
# Question
Title: Change default / base language for t()
Currently when I use t() it shows me originaltext in english and i can translate into french and german. But I want to change the default language to french so when I write t('Salut') I will translate it into english, german, etc. later. But how/where can I do this?

# Answer
Go to the language configuration page here

admin/config/regional/language

And set the default language to French.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Print the query results inside the submit function
I have a query wherein it fetches data from the database, a simple `SELECT` query which is processed when a certain submit button is clicked. What I want to achieve is to get the results of that query so that I can populate it on my form. So far my code looks like this,

```
function my_module_my_form_submit_go($form, &$form_state){
    $values_array = array(
        'week'            => $form_state['values']['week'],
        'employee_name'   => $form_state['values']['emp_name'],
    );

    $result = db_query("SELECT * FROM {time} WHERE week='".$values_array['week']."' AND employee_name='".$values_array['employee_name']."' ");
}

```

and my form looks like this,

```
// this is where I want to populate the data which came from the database
$form['week'] = array(
    '#type'     => 'textfield',
    '#title'    => 'Week',
    '#value'    => $result['week'],
);

$form['emp_name'] = array(
    '#type'     => 'textfield',
    '#title'    => 'Name',
    '#value'    => $result['employee_name'],
);

$form['go_btn'] = array(
    '#type'           => 'submit',
    '#title'          => t('Go'),
    '#value'          => 'Go',
    '#id'             => 'go_btn',
    '#submit'         => array('my_module_my_form_submit_go'),
);

```

I am pretty sure that the query has results because I ran it on the database. What I want is to echo/print the results in the form because later on they will be also used in another form submission. How would I do such thing after the submit button is clicked. I have only managed to display a text using `drupal_set_message` but any data which came from the database, I can't display any. Please help. Thanks.

# Answer
> 0 votes
The issue is due to the form submission and rendering process within Drupal. Long story short, Drupal submits the form then re-renders the form page, which goes through a 'submission' process. So, all the drupal\_set\_message calls are getting cleared during this process.

What you want to use is an AJAX callback on the submit button, populating a section of the form with the data retrieved. And lucky for you the process is much simpler in Drupal 7.

To use the data again in a later form, look at multistep forms.

---
Tags: database, forms
---


# Question
Title: How to track user view of nodes presented in a view?
Situation: I have a simple video player set up using views with a pager. Views loads a set of related nodes, each with an embedded video. By using a pager, the user can advance to the next or previous video in the list.

Problem: I'd like to track whether a logged in user has viewed a video or not, then use this information to help a user see what they have left to watch in another view (a view that simply lists the nodes with embedded videos). So, I need to be able to list viewed/not viewed nodes with views at the user level.

I realize there is complexity around tracking whether a user has really watched a video or not, so ideally the logic that decides whether a user has watched a video or not (custom code, a rule, etc) can be extended/updated later. For now, simply tracking that the user viewed the node is fine.

Related question: since the user is viewing nodes thru the views-based player, and not by clicking node links, where is the best place to execute custom code to mark a node as viewed? I think it could be done with hook\_views\_pre\_render, but I'm not sure that's the right place.

Any thoughts on a simple lightweight approach for Drupal 7? I thought of trying the Flag module (with a user-level flag), using either Rules or custom code to flag a video as "watched", but I haven't tried it yet. There is also a module called path rules that can trigger a rule based on paths: https://drupal.org/project/pathrules

Are there other modules I should consider that already do some of this?

# Answer
I've worked out a solution based on the message module (https://drupal.org/project/message) and I think this will solve the problem well. Here's the basic approach:

1. Install message and create a new message type to capture a specific event (i.e. lesson viewed in my case).
2. Add an entity reference field to the message type created in #1 (messages are fieldable entities) in order to store a reference to the node that was viewed.
3. Write a function to create the message type created in #1. There is example code in a example module that comes along with the message module.
4. Hook the view that needs to trigger message creation and call the function created in #3.
5. Create a view that lists messages. Messages have good views support.
6. Add additional message types and logic to capture other kinds of activities (a user completing a video lesson, which in this case will mean working with the wistia api, since the videos are hosted on the wistia platform).

One question: I'm not sure where best to hook views to create a message when a user views a node through the view described in the original question . I'm currently using hook\_views\_post\_render, which seems to work well, since the view provides access to the node id needed to create the message.

Overall, I think message will be a good solution for this problem and will provide a nice foundation for tracking other activities as needed. There's a good video overview of the message module here: https://vimeo.com/63919900
> 0 votes

---
Tags: views, users
---


# Question
Title: How to put a date token at the start of Backup and Migrate file name pattems?
Because Backup and Migrate sorts files by age, when you untar or copy some files to a destination, they will be more or less the same date and it may be hard to tell which ones are the latest etc. This makes it necessary to create a file pattern with the backup date at the start and make sorting by file name easier.

PS. Getting the date of the files restored from the archive correctly can be accomplished by some of the tar options.

# Answer
On the Advanced Backup options page below the `Backup filename` there is a link `Replacement patterns` which expands to display another link `Current date` which displays some of the tokens available. None of the existing ones suits my preference which is a numeric date.

Using the PHP date options a good date prefix would be \[current-date:custom:Ymd-Gi\] or \[current-date:custom:Y-m-d-Gi\] the latter resulting in a string like '2013-11-17-1924' for 17th November 7:24 pm.

As an example I have a `Backup filename` token \[current-date:custom:Ymd-Gi\]\_\[site:name\]-PMU, the PMU meaning Pre Module Update, something to use just before upgrading modules so you can revert the configuration if something goes wrong
> 1 votes

---
Tags: datetime, backups
---


# Question
Title: Notice: Undefined index: und in include()
I'm having an issue with an undefined index I really could use some help with.

This is the error I get:

Notice: Undefined index: und in include() (line 15)

This is what my line 15 looks like:

```
<div class="House_Header_coupon_link">
  <a href="
      <?php print $node->field_house_coupon_link['und'][0]['url']; ?>
    " style="color:#
      <?php print $node->field_house_coupon_link_hex_code['und'][0]['safe_value']; ?>
    ">
      <?php print $node->field_house_coupon_link['und'][0]['title']; ?>
  </a>
</div>

```

I know the error is happening because sometime the field is not given a value and allowed to be blank. I'm using Drupal 7.23 and I've tried using the isset method mentioned elsewhere on this site but it's not working and I'm out of ideas

Thanks!

# Answer
> 3 votes
Before assigning the values to the field directly you must check if it contains any value or not otherwise you will get the notice like above, try to check the value something like below (the below code is for reference only, you can modify it as per your requirement):

```
<div class="House_Header_coupon_link"><a href="<?php
print isset($node->field_house_coupon_link[LANGUAGE_NONE]) ? $node->field_house_coupon_link[LANGUAGE_NONE][0]['url'] : ""; ?>"
style="color:#<?php print isset($node->field_house_coupon_link_hex_code[LANGUAGE_NONE]) ? $node->field_house_coupon_link_hex_code['und'][0]['safe_value'] : ""; ?>">
<?php print isset($node->field_house_coupon_link[LANGUAGE_NONE]) ? $node->field_house_coupon_link['und'][0]['title'] : ""; ?></a></div>

```

Also it is recommended to use LANGUAGE\_NONE instead of `und`: The language code used when no language is explicitly assigned. Defined by ISO639-2 for "Undetermined".

# Answer
> 0 votes
While the 'error' is being logged, a notice is not really an error, just a 'hey look at this' kind of message ... But yes they are annoying and should be corrected.

'und' may not always be the correct language code. While LANGUAGE\_NONE is what you should use, you should also check for the corresponding node language type:

```
if ( isset($node->field_house_coupon_link_hex_code[$node->language]) )
  print $node->field_house_coupon_link_hex_code[$node->language][0]['safe_value']
else
  print $node->field_house_coupon_link_hex_code[LANGUAGE_NONE][0]['safe_value']

```

# Answer
> 0 votes
Assuming that this is a node template page, you can simply use the field names as variables in renderable array form, and render them like:

```
<div class="House_Header_coupon_link">
  <a href="<?php print render($field_house_coupon_link); ?>" style="color:#<?php print render($field_house_coupon_link_hex_code); ?>">
    <?php print render($field_house_coupon_link); ?>
  </a>
</div>

```

---
Tags: 7, theming
---


# Question
Title: JavaScript supposed to always be called on front page, but doesn't always run
I have some JavaScript that is called on the front page, and is supposed to execute. When I go the page initially, it works fine. Then if I go to another page, then come back, it doesn't show. It does load, and after other JavaScript files it requires. It just doesn't execute. If I refresh, it loads again.

```
(function ($) {

    Drupal.behaviors.chartSavings = {
        attach: function (context, settings) {

            // .....

            // create the submit handler
            $('#savings-form').submit(function(event) {

                event.preventDefault();
                //alert('Form submitted xxx');

                savingsplot();

            });

            savingsplot();

        }
    }

})(jQuery);

```

What am I doing wrong? I don't have any caching enabled, and in drupal\_add\_js(), I set cache to FALSE.

# Answer
> 0 votes
I had Context Breakpoint installed and enabled (even though I didn't use it yet), and found a JS error. Since I wasn't using it, I disabled it, and the problem seems to have cleared up. Reading further, it seems there are some caching implications related to that module. I'd love to know how exactly that happened underneath.

# Answer
> 3 votes
I think perhaps the issue stems from the browser's "BFCache" which is a browser feature that caches a page for quicker loading when a user presses the Back/Forward button. See below to understand more about this feature.

Try adding the following code inside of your `attach` function.

```
// Prevent the bfcache.
$(window).bind("unload", function() {});

```

The "BFCache" as taken from page: https://stackoverflow.com/a/2218733/955858

To quote that post:

> The modern browsers (Firefox, Safari/Chrome, and Opera) all support the special "back/forward" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). This allows it to re-load the page very quickly and exactly as the user left it, which is what the user wants.
>
> The load event is not supposed to fire when the page is loaded from this bfcache. For example, if you created your UI in the "load" handler, and the "load" event was fired once on the initial load, and the second time when the page was re-loaded from the bfcache, the page would end up with duplicate UI elements.
>
> This is also why adding the "unload" handler stops the page from being stored in the bfcache (thus making it slower to navigate back to) -- the unload handler could perform clean-up tasks, which could leave the page in unworkable state.
>
> For pages that need to know when they're being navigated away/back to, Firefox 1.5+ and some next version of Safari (which contains the fix for bug 28758) supports special events called "pageshow" and "pagehide".
>
> References: http://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ and https://developer.mozilla.org/En/Using\_Firefox\_1.5\_caching.

---
Tags: 7, javascript
---


# Question
Title: How to execute javascript iframe in custom module?
I have created a custom module for Drupal 7. In this module, I would like it execute a javascript file that embeds an iframe when the module is viewed. I have tried the following code with no success:

```
function chat_with_librarian_block_view($delta = '') {

  $block = array();
  switch ($delta) {
    case 'chat_with_librarian':
      $block['subject'] = t('Ask a Librarian');
      $block['content'] = chat_with_librarian_get_html();
      break;
  }
  return $block;
}

function chat_with_librarian_get_html() {

  $html = '<div id="qpchatwidget" >' .
    '</div>' .
    '<script ...call site in question with appropriate parameters...>' .
    '<noscript>Please enable javascript to chat with librarians online</noscript></script>';
  $form = array(
    'chat_frame' => array(
      '#type' => 'markup',
      '#markup' => $html,
      '#prefix' => '<div id="parent">',
      '#suffix' => '</div>',
    )
  );
  return $form;
}

```

What do I need to do to get the embedded javascript to work properly. As a side note I can make this work by creating a block through the administration screen, so I know this can be done. I just need to know what I am missing in my code to accomplish the same thing. When I do execute this code, the title is rendered but the body isn't. Examining the body of the block, I can see it contains the javascipt as returned by the function and an additional message:

```
Reload the page to get source for: url

```

It seems like the executing code cannot get correct div dimensions to return a proper iframe (but that is just a guess on my part - have put inline css to define a size). Has anyone come across something like this or how to get this working?

Thanks.

# Answer
I found the solution to my problem. The reason why this wasn't working is because the div statement:

```
<div id="qpchatwidget" ></div>

```

is on one line. If you break it up into two lines:

```
<div id="qpchatwidget" >
</div>

```

Then everything works as it should. Amazing how something so simple can mess you up.
> 0 votes

# Answer
The `$form` var in `chat_with_librarian_get_html()`is rather useless, just return the `$html` var instead and it should work.

```
function chat_with_librarian_get_html() {
  $html = '<div id="parent"><div id="qpchatwidget" ></div>' .
    '<script ...call site in question with appropriate parameters...>' .
    '<noscript>Please enable javascript to chat with librarians online</noscript></script></div>';
  return $html;
}

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: What is wrong with this drush command in Drupal 7 Ubercart 3 to delete orders in bulk via command line?
I am trying to delete my Ubercart 3 orders in bulk via the command line with just a one liner:

```
for XX in {1..12}; do drush ev 'uc_order_delete($XX)' -v; done;

```

It beats having to do it via the bulk operations in views. I'm not sure whats wrong with my command as it says I have an Undefined variable when i put $XX in quotes.

# Answer
> 0 votes
You've to use double quotes instead of single quotes, so variables retain their special meaning.

Read more:

https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash

---
Tags: 7, ubercart, drush
---


# Question
Title: Linking to a homepage when Drupal is located in a Directory
I have a problem with creating a proper link to the homepage of my website. I would like this code to redirect to my homepage:

```
<a href="/">
<div class="logo_wut">
<img style="display:inline;" src="photos/logoWUT_czarne.PNG" width="370" height="135">
</div>

```

Unfortunetaly it doesn't work, because it brings me to the homepage of my whole server and drupal is located in a subdirectory of the server. I tried to do this using php:

```
<a href="<?php print ('<front>');?>">
<div class="logo_wut">
<img style="display:inline;" src="photos/logoWUT_czarne.PNG" width="370" height="135">
</div>

```

but it doesn't work too. When i click on the image it appears:

> Page not found The requested page "/drupal7/drupal-7.23/en/%3C?php%20print%20(%27%3Cfront%3E%27);?%3E" could not be found.

# Answer
> 3 votes
You should use `url()` function to generate a page URL. For the `frontpage` it is:

```
<a href="<?php print url('<front>'); ?>">YOUR LINK</a>

```

If the generated links using the url() function are not correct, you can change the `$base_url` variable in the `settings.php`

```
$base_url = 'http://www.yourwebsite.com/drupal7/drupal-7.23';

```

# Answer
> 2 votes
There is global variable `$base_path` which define base URL path of the Drupal Installation.

This will at least default to '/'.

```
<?php global $base_path; ?>

<a href="<?php print $base_path; ?>">Home</a>

```

Or you can use `base_path()` function which will return the global variable `$base_path`.

```
<?php $path = base_path(); ?>

<a href="<?php print $path; ?>">Home</a>

```

Or, You can also define `$base_url` in your settings.php file of Drupal installation as below.

`$base_url = 'http://www.example.com';`

There should not be trailing slash (/) in your base url.

```
<?php global $base_url; ?>

<a href="<?php print $base_url; ?>">Home</a>

```

Kindly see that if you modify your `$base_url` in your `settigns.php` file, then you need to modify your `$base_url` when you transfer your file from development server to live server.

# Answer
> 1 votes
Drupal stores the homepage URL in the $base\_url global.

```
<a href="<?php global $base_url; print $base_url; ?>">YOUR LINK</a>

```

Details: https://api.drupal.org/api/drupal/developer!globals.php/global/base\_url/7

---
Tags: theming
---


# Question
Title: How do i generate token for each user who submit my custom form?
I have a created a custom module with simple form with only three fields (URL, title, and email), where user must enter all the fields for submission.

>

I am able to send the mail to the user from my custom module, but I need to create and attach a validation link (possibly with unique token for email).

How do I generate a token and store it in the database to use it for validation?

# Answer
> 0 votes
1.Declare custom tokens using hook\_token\_info()

2.Create custom tokens using hook\_tokens()

3.You can use your custom tokens using token\_replace() that is call the token\_replace at the place where u need to send the email.

4.Create a seperate file inside your module with .tokens.inc extension and include the hook\_tokens\_info() and hook\_tokens() inside it.

---
Tags: 7, forms, emails
---


# Question
Title: Changing the content of one node reflecting in other node created using node clone
I used node clone to create similar contents. After creating the content using node clone, I have disabled and uninstalled node clone module.

Now, whenever I try to modify something in the cloned content or original node, both are getting reflected with the recent changes. Why is this happening? How do I resolve this?

Note: *I have uninstalled the module and cleared performance cache many times now*. Weird thing is, these changes are applying only to field collection fields.

# Answer
The problem with using node clone on node which uses field collection is, it preserves entity reference.

> The group of fields is simply an entity. When you use node clone to clone a node the reference to the entity is preserved.
>
> *Quoting from this article.*
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: What's the best practice for field API prefixes? (To prefix or not to prefix, that is the question)
I'm implementing a giant list of fields, instances, bundles, et cetera in a custom **site specific** module.

In progress, I see that the core **Tags** vocabulary has a `field_` machine name prefix, and none of my custom vocabularies have this prefix. I've known that creating fields through the Drupal GUI also prefixes fields with `field_`.

In my previous experience working with prefixed fields, this has always seemed too verbose.

Is prefixing Field API fields with `_field` a best practice for a reason I haven't come across yet?

# Answer
> 3 votes
I prefix my custom fields always with the name of my module, which, I think, is a good practice, so that I know which module provides this field. And also I think this is the same reason Drupal Field UI adds the `field_` prefix since the fields are created by the Field module in this case.

# Answer
> 0 votes
In our team we make the following naming.

field\_NAME\_OF\_PROJECT\_NAME\_OF\_MODULE\_FIELD\_NAME

Example: Project: Rockstar Module: Counter Field Name: id

Final:field\_rs\_counter\_id Keep in mind those are saved in the database as field\_data\_field\_rs\_counter\_id, and I experienced character limit.

Regards

---
Tags: entities
---


# Question
Title: How to display only the first value in Views, by overriding TPL.PHP?
I am trying to override the output of one field in Views, and I need it to print only the first value of the field.

Like:

Unfortunately my knowledge of PHP and Drupal-API are very low, so I hope to get some help here.

# Answer
You can do this on the View edit page using the UI without editing the template.

* Go to `admin/structure/views`
* Edit the view in question
* Under Fields, select the field in question
* Expand the section **'Multiple field settings'**
* Set as: 'Display **1** value(s) starting from **0** (first item is 0)
* Save your view and that's it.
> 1 votes

# Answer
Instead of going with template level, you can use pager option. User pager and select " Display a specified number of items" to 1.

If you want a specific condition to be passed to display only one item, then please do mention what your views shows, and the template variables.
> 0 votes

# Answer
You should check hook\_views\_pre\_render(&$view)

which will provide you the option to change any value of any views. to change the specific view

```
function hook_views_pre_render(&$view) {

if ($view->name == 'view_name') {
// then check for $view->result[0] and you will get the first row where you can edit your stuff
}

}

```
> 0 votes

---
Tags: views
---


# Question
Title: Delete old files from server when content is updated
When a node is updated by replacing a new file upload, old files exist on the server maintaining versions.

I want to delete old files from the server when content is updated.

# Answer
> 0 votes
This is already discussed topic. I found some source.

Drupal Forum and Original Source

After that I would create a cron job (Implementing hook\_cron). And insert this snippet.

I hope it works out for you.

Alternatively, if you dont want this action to happen once per day, you can insert it in hook\_submit, or hook\_update. But I would go for the first method.

Do it once per day/week/whatever time period you like.

---
Tags: 7, nodes, files
---


title: Cache field / entity / node

text:
# Question
Title: Cache field / entity / node
I have a custom field/widget that has a format view function that is highly resource intensive. I currently am caching the result using `cache_set()/cache_get()` inside the `hook_field_formatter_view` function for my field.

Is there a better way I could be doing this? I tried to use `drupal_render()`'s `#cache` property and it cached the output but still ran my `hook_field_formatter_view` function.

Basically, I know how to do full page cache (for anonymous users) but how do you cache a field/node/entity (for everyone)?

# Answer
> I currently am caching the result using cache\_set()/cache\_get() inside the hook\_field\_formatter\_view function for my field

Honestly this is not a bad way to go about doing it. When you have custom logic which is resource intensive, taking responsibility for your own caching decisions is usually the right idea. Honestly, I really wish more developers would familiarize themselves with cache\_get/set().

Entitycache appears to be an effort to do this generally, and over time I am sure that some best practices will emerge as more people work in this space. However as of today, for anyone looking at a similar problem-set: "Figure out how to cache it yourself" is a *good answer*.
> 3 votes

# Answer
I think you should consider using Render Cache module. This when used in conjunction with Entity Cache it should complement each other well as mentioned on the project page.
> 0 votes

---
Tags: entities, caching
---


# Question
Title: One content type with several fields or several content types?
currently I'm working on a master data management system in Drupal. We've got products for different sales channels (like ebay, magento, amazon etc.) On field where I'm struggling is: Category (CatEbay, CatMagento, CatAmazon, etc.) for one and the same product.

Two options: Add more fields to a sales channel (content type) or add different sales channels. If I've got different sales channels, I need to implement a relation as well as the translation might be tricky.

If I simply add several category fields, it doesn't look very nice, but makes everything quite easy.

There is something like: https://drupal.org/project/bundle\_inherit but does it work with translation or export node + it's alpha2 and we are in a production environment ... maybe it just adds complexity without a lot of benefit.

Would there be a disadvantage to point out by going the 'adding fields' way?

Thanks, Chris

# Answer
> 2 votes
According to me,

1. You should only build one content type : "Product". Create the required fields according to your need.
2. Then, Create taxonomy terms like "Clothing, Electronics, etc." and then use entity\_reference module to refer the node(i.e Product in this case).
3. That's it, Done.
4. Just create some products and go to taxonomy and add products.
5. For displaying products on page, You should plan to theme taxonomy pages.

# Answer
> 0 votes
I think adding fields is the right way to go. I suggest you to create a taxonomy vocabulary for the categories and add a term reference field to your content type.

---
Tags: nodes
---


# Question
Title: Unable to display Drush cache-clear theme registry
I was using drush to do some of the most frequently used Drupal tasks, mainly to cache clear. It was working great, but recently I'm getting only the following option:

```
Enter a number to choose which cache to clear.
 [0]  :  Cancel
 [1]  :  drush
 [2]  :  registry

```

It was supposed to be:

```
 [0]   :  Cancel
 [1]   :  all
 [2]   :  drush
 [3]   :  theme-registry
 [4]   :  menu
 [5]   :  css-js
 [6]   :  block
 [7]   :  module-list
 [8]   :  theme-list
 [9]   :  nodeaccess
 [10]  :  registry
 [11]  :  token
 [12]  :  views

```

There is no way to clear css/js or theme registry. Whats the problem? Is it with Drush or Machine settings. Any advise highly appretiated.

# Answer
> 3 votes
The Drush code looks like this: `$types = drush_cache_clear_types(drush_has_boostrapped(DRUSH_BOOTSTRAP_DRUPAL_FULL));`

If the parameter to drush\_cache\_clear\_types is TRUE, then the missing cache types shown above are included in your selection list. Your Drupal site is not bootstrapping all the way up to the 'FULL' level, which means there's probably something wrong with the Drupal site. Try running `drush status --debug`, and see if you can determine from the log messages why the bootstrap is stopping.

**Update:** See MPD's comment below. I thought the exact same thing as I was driving in to work this morning: this situation can also arise if you have told Drush where your Drupal root is, but have not specified your sites folder. The Drupal root is specified via --root, or by using cd to switch to a directory anywhere in your Drupal installation. The specific site is selected via --uri, or by using cd to switch to the same directory that contains settings.php. If you cd to the folder that contains settings.php and run `drush cc all`, that might fix your problem.

# Answer
> 1 votes
I had this. I was using aegir. You would be in the wrong directory if you only see:

```
Enter a number to choose which cache to clear.
 [0]  :  Cancel
 [1]  :  drush
 [2]  :  registry

```

By going into `/var/aegir/platforms/xxx/sites/domainname/` and then running drush cache-clear you will get

```
[0]   :  Cancel
 [1]   :  all
 [2]   :  drush
 [3]   :  theme-registry
 [4]   :  menu
 [5]   :  css-js
 [6]   :  block
 [7]   :  module-list
 [8]   :  theme-list
 [9]   :  nodeaccess
 [10]  :  registry
 [11]  :  token
 [12]  :  views

```

# Answer
> 0 votes
Bindaddress requires you to login remotely, so in settings.php you should change the host to the bind address.

Also you cant use root with empty password, instead Login to mysql

```
mysql -u root

```

create user and grand all permission and use that user in your settings.php

```
GRANT ALL ON *.* TO myname@'192.168.1.90' IDENTIFIED BY 'myname';

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'project_db',
      'username' => 'myname',
      'password' => 'myname',
            'host' => '192.168.1.10',// if that is your ip
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

---
Tags: 7, drush
---


title: SQL Query to display taxonomy terms

text:
# Question
Title: SQL Query to display taxonomy terms
I am working on a Drupal 6 site and have very limited knowledge of writing sql queries.

I have a content type manage\_current\_university (which is a content profile) and in that use a taxonomy cck field field\_host\_university. I am generating a table of users who have signed for a content.

If I write this query in phpMyAdmin, I get the correct tid for that user

`SELECT field_host_university_value FROM node n INNER JOIN content_type_manage_current_university mcu ON n.nid = mcu.nid WHERE n.uid =120;`

Replicating the same query inside a module:

`$currentuniversity_query = db_query("SELECT field_host_university_value FROM node n INNER JOIN content_type_manage_current_university mcu ON n.nid = mcu.nid
 WHERE n.uid =".$uid."");
while($currentuniversity_result = db_fetch_object($currentuniversity_query)){
 $currentuniversity = $currentuniversity_result->value;
print $currentuniversity; }`

Where $uid fetches $user-\>uid of signed up users.

But the table column is blank for this one. Using similar query to fetch other profile values of the signed up user works.

Please help!

# Answer
Ok. My query was correct. The issue was in the php variable call. I changed `$currentuniversity = $currentuniversity_result->value;` to `$currentuniversity = $currentuniversity_result->field_host_university_value;` and now its working fine. Thanks for your help.
> 0 votes

# Answer
Try using db\_select something like below to build the query for your above condition:

```
$currentuniversity_query = db_select('field_host_university_value', 'fhuv');

//query of left join with 'content_type_manage_current_university' table.
$currentuniversity_query->leftJoin('content_type_manage_current_university', 'ctmcu',
  '(fhuv.nid = ctmcu.nid)');

//query of conditions and fetching the result
$currentuniversity_query = $currentuniversity_query->condition('fhuv.uid', $uid, '=')
  ->fields('fhuv');
  ->execute();

```

You may have to modify a query little bit, I just provided what you can try. Also have a look at: https://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_select/7

---

For **Drupal 6** try the following:

```
$currentuniversity_query = db_result(db_query("SELECT mcu.field_host_university_value FROM node n INNER JOIN content_type_manage_current_university mcu ON n.nid = mcu.nid
WHERE n.uid =%d", $uid));

```
> 0 votes

---
Tags: 7, database
---


title: Two formats in one view

text:
# Question
Title: Two formats in one view
Let me see if I can explain what I need.

1) I need some tabbed buttons listed first:

# View All | Category 1 | Category 2 | Category 3

2) For each button, clicking the tab should opens an area to display:

Other tabbed buttons (to the left).

## Current | Future | Past

Each of the buttons/views has a grid and a table display each (to the right).

### Grid | List

Those are all views (example: Category 1 - Current - Grid format view, Category 1 - Current - Table format view).

I can probably use quicktabs module to display my top level tabs, but how to achieve #2?

# Answer
I did something similar using the module Views Field View.

Module Page Description:

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.
> 0 votes

---
Tags: views
---


# Question
Title: How to add two registration form on single page?
How can i add two registration form on single page

I had created two registration page using the Profile 2 module and given a custom path,eg:

`http://localhost/dupal/member/register`
`http://localhost/dupal/non_member/register`

How can I display that two form on single page
eg:`http://localhost/dupal/user/register`

# Answer
Give a try to Profile2 Registration Path module:

**Problem with Profile2 module**: By default, the Profile2 module permits you to add fields from chosen profile types to the default user registration form. Unfortunately, there is only one user registration form. Thus, every user will be presented with these fields during registration. If you have two profile types targeted at two different audiences, you cannot have two separate registration forms.

**Solution**:

> **Profile2 Registration Path** enables you to set a unique registration path for each Profile2 profile type. Users who register via that unique path will be presented with fields from the chosen profile type(s).

---

Alternatively another method to include multiple forms (e.g: FORM1 and FORM2) on same page is somewhat like below(however I am not sure where it will work with the profile2 forms):

```
$output = array();
$output['FORM1_DISPLAY'] = drupal_get_form('FORM_1_FORM_ID');
$output['FORM2_DISPLAY'] = drupal_get_form('FORM_2_FORM_ID');
return $output;

```
> 1 votes

# Answer
You can implement `hook_menu_alter` in your custom module and adds custom `page callback` for `user/register` menu item.

In your custom 'page callback' function, you can use `drupal_get_form` function to render the both form.

You can check the code snippets and may be it will help you.

```
<?php

/**
 * Implements hook_menu_item_alter()
 *
 */
function custom_feature_menu_alter(&$items) {

  //Configuring user login and register menu item
  $items['user/login']['type'] = MENU_CALLBACK;
  $items['user/login']['page callback'] = 'custom_feature_user_register';
  $items['user/login']['title'] = 'Login / Register';

  $items['user/register']['page callback'] = 'custom_feature_user_register';

  $items['user/register']['type'] = MENU_CALLBACK;
  $items['user/register']['title'] = 'Login / Register';

}

/**
 * Callback to display user login and register form
 */
function custom_feature_user_register() {

  //Addding user login form
  $output = '<div class="profile-left">';
  $output .= '<h3>Member Login</h3>';

  $output .= drupal_render(drupal_get_form('form_id_1'));
  $output .= '</div>';

  $output .= '<div class="profile-left">';
  $output .= '<h3>Register</h3>';

  $output .= drupal_render(drupal_get_form('form_id_1'));
  $output .= '</div>';

  return $output;
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: drupal_goto not working in hook user login
I have $u variable which stores the path in hook user login to redirect users to the page.

```
drupal_goto($u);

```

I am not being redirected to the page- path $u. drupal\_goto not working. I have tried everything increased te weight of the module,even tried with $\_GET\['destination'\].

# Answer
> 1 votes
Instead of using drupal\_goto(), try passing the path in **$edit\['redirect'\]** in hook\_user\_login as below:

```
<?php
/**
 * Implements hook_user_login().
 */
function hook_user_login(&$edit, $account) {
  // To check if the form is not the user reset form.
  if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
    $GLOBALS['destination'] = 'PATH_YOU_WANT_TO_REDIRECT';
  }
}
?>

```

---
Tags: users
---


# Question
Title: Programmatically created nodes don't appear unless opened and saved
I've written a simple script that iterates over a CSV file and creates nodes in Drupal. All of the nodes are present in the admin interface but do not appear on the site unless I manually click 'Edit' then immediately save. This is a real problem because I do not have time to open each and every node. Funny thing is, this doesnt happen for every node.

A simplified version of my code

```
 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $title = $data[1];
    $address1 = $data[2];
    $address2 = $data[3];

    // Add a node
    $node = new stdClass();
    $node->type = 'store_location';
    node_object_prepare($node);
    $node->status = 1; # published or not...
    $node->promote = 0;
    $node->uid = 1; // ID of author
    $node->created = date('U', strtotime('now'));

    $node->language = LANGUAGE_NONE;
    $node->path['pathauto'] = TRUE;
    $node->title = $title;
    $node->gsl_addressfield['und'][0]['thoroughfare'] = ucwords($address1);
    $node->gsl_addressfield['und'][0]['premise'] = ucwords($address2);

    node_save($node);
}

```

# Answer
Use hook\_node\_presave($node) to check whether you are getting proper values.

Also, try drupal\_form\_submit() instead of node\_save() for edit
> 1 votes

---
Tags: nodes
---


# Question
Title: Removing input formatting options and description from comment form
How do I remove the input formatting options and descriptions from the comment form?

I'm not interested in a CSS and/or jquery based solution, nor am I interested in using the Better Formats module, as I am using Drupal 7 and it specifically states it is not ready for production sites (besides the fact installing a module to do this seems like overkill). I want the html sent over the wire to not have the "input format" related text at all.

Drupal drives me nuts sometimes, because some stuff that should be simple is ridiculously complex.

I've searched but no one seems to know how to do this. Here's some things I've found:

# Answer
> 16 votes
Ok found this drupal issue discussing the matter: Node and Comment Input Format fieldset is not working (I found it by searching for "edit-comment-body-und-0-format" which html id of the fieldset that contains all the input format mumbo jumbo).

At the end of this issue is a link to the following site which gives a solution: How To Remove Format Options / Guideliness From Comments Textarea in Drupal 7.

Here's the code I'm using on my site, in template.php of my theme (I'm using a zen subtheme):

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

  $form['comment_body']['#after_build'][] = 'mytheme_customize_comment_form';

}

function mytheme_customize_comment_form(&$form) {
  $form[LANGUAGE_NONE][0]['format']['#access'] = FALSE;
  return $form;
}

```

I just tried it and it does seem to be working. Woohoo!

# Answer
> 3 votes
Check this module https://drupal.org/project/simplify .

From the module's project page:

> Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.

Very helpful to hide unnecessary tips and text format option under RTE

---
Tags: 7, theming, forms, comments, input-formats
---


# Question
Title: How to render a multiple value field of type generic file
If I use the textformatter module (included textformatter\_contrib) I can display a repeatable field with links as a list.

By selecting 'list' as format for the full view of the field of the content type. I can't select 'list' for the file field. The default format for my file field is 'generic file'

# Answer
That module provides formatters for the following field types:

* entityreference
* node\_reference
* user\_reference
* link
* field\_collection

(gathered from here).

There's no support for file fields so you'll need to either implement the functionality yourself, or file a feature request to the Textformatter issue queue.
> 1 votes

---
Tags: entities
---