# Question
Title: What is the order of page load in Drupal?
How does the page load order occur for Drupal?

I understand that first the modules are run and the data is returned to the view files. But which files are responsible for the view loading inside the theme?

Would it be `page.tpl.php`?

Also I trying to determine the page load when a `404` error is thrown. Which `page.tpl.php` loads the page when a 404 error is thrown?

I know that `drupal_not_found()` function returns the data, but how would I know which view would load that page?

# Answer
> 1 votes
With regard to error pages, Drupal has its defaults, but you can create your own just like any other node. Just create a page for the error, then go to `yoursitename.com/admin/settings/error-reporting` and specify it as the page to display. You can do this for 403 and 404 errors.

The error pages are loaded just like any other. Which theme files are loaded depends highly on the theme. In Drupal 6, `page.tpl.php` is the top-level template file in the theme, and would be used for error pages just like any other page. However, it is quite possible to have other files that only theme certain portions of the page.

I would highly recommend a slow, methodical reading of Drupal's theming guide for an introduction. This will help you understand how Drupal decides which `.tpl.php` files (as well as CSS, JS, etc.) to use for a given page request.

Also, note that a lot of the details have changed significantly between Drupal 6 and Drupal 7. If you're doing new development, you'd probably be better off focusing on version 7—but of course if you have older sites to maintain, you'll need to look at the relevant documentation.

# Answer
> 1 votes
The "Living, Breathing, Drupal: The Biology of the Request" does a good job on explaining how Drupal does a page load.

---
Tags: theming
---


title: Module for content publication workflow

text:
# Question
Title: Module for content publication workflow
I am looking for a Drupal 7 module to manage a content publication workflow for different roles. When a user with a certain role creates a content node, it needs to be validated by another user within another role, before it is marked as published. In Drupal 6, I have used the Workflow module, but it is not available for Drupal 7.

# Answer
> 8 votes
There is now the Workbench module, for Drupal 7.

> Workbench provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:
>
> * a unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time
> * the ability to control who has access to edit any content based on an organization's structure not the web site structure
> * a customizable editorial workflow that integrates with the access control feature described above or works independently on its own

# Answer
> 3 votes
You can also use the Maestro module.
There is an example workflow to publish content.

# Answer
> 2 votes
You can use the rules module as described here: http://drupal.org/node/1027546

---
Tags: 7, workflows
---


# Question
Title: Changing article text and summary with template_preprocess_node()
I use Drupal 7.9 with Views module (if the latter is important). I've created a small module for my site that changes transliteration of Japanese words in articles from Latin to Cyrillics and vice versa (yes, I need such a thing). User sees a form with radio button set, chooses transliteration, his choice goes to $\_COOKIE and then I change transliteration in article summary and body based on user's choice. Or better to say I'm trying to change it but it doesn't work. The code goes like this:

```
function mymodule_preprocess_node(&$variables) {
    /* Suppose we have a summary containing only one word 'Yamamoto' that has to be changed to 'Ямамото' */
    $variables['node']->body['und'][0]['summary'] = 'Ямамото';
}

```

After this code is executed, the changed variable has the correct value of 'Ямамото'. But in the main page for some reason I see the unchanged 'Yamamoto'. What am I doing wrong? Do I change the wrong field? Do I mess up working with parameters passed by reference? Do I use the wrong hook?

# Answer
I believe that the node has already been rendered by the time `template_preprocess_node()` is called so changing any values on the node object will have no effect. You can try looking at `$variables['node']->content` to see if you can modify the text in that (I think this is the full HTML rendered node though, so lots of extra text/markup to deal with here).

You're probably better off using hook\_node\_load() instead. This gives you a chance to alter the node object directly before it gets rendered.
> 0 votes

---
Tags: 7, nodes, hooks
---


# Question
Title: Show or hide field data using java script in node
I create one cck content type and add one text field in them with name of:
My friend name: text field with add more button
Then, i submit form with entering my 15 friends names
**Like this:**
1
2
3
.
.
.
15
this node display all of 15 names,

i am trying to do after submit form display only 10 name and after 10 name display more link after click more button show remaining 5 names.
**Like this:**
1
2
3
4
5
6
7
8
9
10 **more...**
Remaining 5 names
11
12
13
14
15
how can i do this ? i am using **Drupal 6**

# Answer
Replace `.field-field-friends-name` with your field name and adjust `hide_after` as necessary. This worked for me on my site

```
Drupal.behaviors.hide_more_friends = function() {
  var field = jQuery('.field-field-friends-name');
  var hide_after = 10;
  var items = field.find('.field-item');

  if (items.length > hide_after) {
    items.slice(hide_after).addClass('excess').hide();

    var more_link = jQuery('<a href="#">more</a>').click(function() {
      jQuery(this).remove();
      field.find('.excess').show();
      return false;
    });
    field.find('.field-items').after(more_link);
  }
}

```
> 1 votes

# Answer
jQuery will do this for you, but you wiull probably have to either write your own code for list items \> 10, or adapt existing code to suit your needs.

There are various show/hide plug ins for jquery. In Drupal the facet api uses a jquery function to do just that as well given it's limit.

Here is the function from facetapi.js

```
/**
 * Applies the soft limit to facets in the block realm.
 */
Drupal.facetapi.applyLimit = function(settings) {
  if (settings.limit > 0 && !$('ul#' + settings.id).hasClass('facetapi-processed')) {
    // Only process this code once per page load.
    $('ul#' + settings.id).addClass('facetapi-processed');

    // Ensures our limit is zero-based, hides facets over the limit.
    var limit = settings.limit - 1;
    $('ul#' + settings.id).find('li:gt(' + limit + ')').hide();

    // Adds "Show more" / "Show fewer" links as appropriate.
    $('ul#' + settings.id).filter(function() {
      return $(this).find('li').length > settings.limit;
    }).each(function() {
      $('<a href="#" class="facetapi-limit-link"></a>').text(Drupal.t('Show more')).click(function() {
        if ($(this).prev().find('li:hidden').length > 0) {
          $(this).prev().find('li:gt(' + limit + ')').slideDown();
          $(this).text(Drupal.t('Show fewer'));
        }
        else {
          $(this).prev().find('li:gt(' + limit + ')').slideUp();
          $(this).text(Drupal.t('Show more'));
        }
        return false;
      }).insertAfter($(this));
    });
  }
}

```
> 1 votes

# Answer
Extended code with more or less link

```
  Drupal.behaviors.hide_more_friends = function() {
  var field = jQuery('.field-field-test');
  var hide_after = 10;
  var items = field.find('.field-item');

  if (items.length > hide_after) {
    items.slice(hide_after).addClass('excess').hide();
    console.log('hide after'+hide_after);
    console.log('item last'+items.length);
    items.slice(hide_after).addClass('excess').hide();
    items.slice(items.length-1).addClass('last');

    var more_link = jQuery('<a href="#" class="more-link">more</a>').click(function() {
      jQuery(this).hide();
      field.find('.excess').show();
      jQuery('.less-link').show();
      return false;
    });
        var less_link = jQuery('<a href="#" class="less-link excess">less</a>').click(function() {
      jQuery(this).hide();
      field.find('.excess').hide();
      jQuery('.more-link').show();
      return false;
    });
    field.find('.field-items').after(more_link);
    field.find('.field-item.last').after(less_link);
    jQuery('.less-link').hide();
  }

}

```
> 0 votes

---
Tags: 6, theming, nodes, ajax, javascript
---


# Question
Title: Calculate the sum for 3 CCK fields with Rules in Drupal 7
I have 4 stock fields (Stock 1, Stock 2, Stock 3 and TOTAL STOCK) and I want to set up a rule to calculate \["+"\] the sum of Stock 1, Stock 2 and Stock 3 fields, and automatically appear in TOTAL STOCK field.

example -\> http://ucreateawebsite.com/DRUPAL/dalexgrup/pt

What event, conditions and actions Should I use?

Thank you.

# Answer
> 3 votes
I found the answer:

***For Event I used:***

* After updating an existing commerce product

***For Conditions I used:***

* Entity has field

+ Parameter: Entity: \[commerce-product\], Field: field\_stock1
* Entity has field

+ Parameter: Entity: \[commerce-product\], Field: field\_stock2
* Entity has field

+ Parameter: Entity: \[commerce-product\], Field: field\_stock3
* Entity has field

+ Parameter: Entity: \[commerce-product\], Field: field\_totalstock

***For Actions I used:***

* Calculate a value

+ Parameter: Input value 1: \[commerce-product:field-stock1\], Input value 2: \[commerce-product:field-stock2\]; Provides variables: Calculation result for Stock1 and Stock2 (stock1\_plus\_stock2\_result)
* Calculate a value

+ Parameter: Input value 1: \[stock1-plus-stock2-result\], Input value 2: \[commerce-product:field-stock3\]; Provides variables: Calculation result for stock1-plus-stock2-result and Stock3 (stock1\_plus\_stock2\_result\_plus\_stock3)
* Set a data value

+ Parameter: Data: \[commerce-product:field-totalstock\], Value: \[stock1\_plus\_stock2\_result\_plus\_stock3\]

You can see what I wrote on http://ucreateawebsite.com/DRUPAL/dalexgrup/pt.

# Answer
> 0 votes
You can try playing with:

**Event**: on updating content

**Conditions**: entity has field (to have it available in actions) for stock1, stock2 and stock3

**Actions**: set data value

---
Tags: 7, entities, rules
---


# Question
Title: What events, conditions and actions I should use for this case?
I use "commerce" and "commerce stock" modules, I created a list with products and a few extra fields in **Product types**: \- Image \- Deposit 1 Stock \- Deposit 2 Stock \- Deposit 3 Stock

I created a view (table - http://ucreateawebsite.com/DRUPAL/dalexgrup/pt) with this fields: \- Bulk Operations \- SKU \- Imagine \- Title \- Deposit 1 Stock \- Deposit 2 Stock \- Deposit 3 Stock

I have a problem in succeeding to create another stock field (the fourth - called **TOTAL STOCK**) and making it to automatically update when the other 3 fields are being changed. I want the fourth field to calculate and show me the sum of the other 3 fields.

---

* Example 1 *
Deposit 1 Stock -\> 15
Deposit 2 Stock -\> 15
## Deposit 3 Stock -\> 15

## TOTAL STOCK -\> 45

---

* Example 2 *
Deposit 1 Stock -\> 10
Deposit 2 Stock -\> 05
## Deposit 3 Stock -\> 01

## TOTAL STOCK -\> 16

This **TOTAL STOCK field** I should create in **Product type** like: \- Deposit 1 Stock \- Deposit 2 Stock \- Deposit 3 Stock ??????

Then I should create a rule? What events, conditions and actions I should use?

Thank you.

# Answer
> 1 votes
I found the answer:

***For Event I used:***

## 1. After updating an existing commerce product

***For Conditions I used:***

## 1. Entity has field - Parameter: Entity: \[commerce-product\], Field: field\_stock1

## 2. Entity has field - Parameter: Entity: \[commerce-product\], Field: field\_stock2

## 3. Entity has field - Parameter: Entity: \[commerce-product\], Field: field\_stock3

## 4. Entity has field - Parameter: Entity: \[commerce-product\], Field: field\_totalstock

***For Actions I used:***

## 1. Calculate a value - Parameter: Input value 1: \[commerce-product:field-stock1\], Input value 2: \[commerce-product:field-stock2\]; Provides variables: Calculation result for Stock1 and Stock2 (stock1\_plus\_stock2\_result)

## 2. Calculate a value - Parameter: Input value 1: \[stock1-plus-stock2-result\], Input value 2: \[commerce-product:field-stock3\]; Provides variables: Calculation result for stock1-plus-stock2-result and Stock3 (stock1\_plus\_stock2\_result\_plus\_stock3)

## 3. Set a data value - Parameter: Data: \[commerce-product:field-totalstock\], Value: \[stock1\_plus\_stock2\_result\_plus\_stock3\]

You can see what I wrote here -\> http://ucreateawebsite.com/DRUPAL/dalexgrup/pt

---
Tags: rules, commerce, actions
---


# Question
Title: How do I redirect users to the page they were before logging in to my site?
I´ve got a Drupal site that after the user logs in it is redirected to his profile. I want to create a specific rule so people from specific characteristics can retur to the page they were before they´ve logged in.

I´m planning to do that with the rules module.

So, I´ve set the parameters and conditions, but when I try to create the rule, telling Drupal where it should redirect people, I just don´t know how to say that.

I think I should put some php code inside that page redirect rule, but don´t know how. Hopw you can help me out.

FYI, I've tried (unsuccessfully) this:

```
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header("Location: http://www.mysite.net/user");
exit();

// On successful login
$redirect = $_SESSION['redirect_to'];
// unset the session var
unset($_SESSION['redirect_to']);
header("Location: http://www.mysite.net/$redirect");
exit();

```

# Answer
> 3 votes
Have a look at the Login Destination module.

In custom code, to issue a redirect in Drupal use the `drupal_goto()` function. Drupal has a massive API, use it.

# Answer
> 1 votes
First approach: read the referer. BUT it is not a safe and pretty option https://stackoverflow.com/questions/165975/determining-referer-in-php

Also, you can create a session ( session\_start() ) for every anonymous user and later, create a new one when they log-in, extracting the current page URI or something stored in the "guest session" and using it to redirect. Cookies can somehow be forged BUT no personal info is on the session so... why not?

# Answer
> 1 votes
you could append the current URI as an argument to the login page:

```
header("Location: http://mysite.com/user?return_to=" . $_SERVER['REQUEST_URI']);
exit;

```

Then have the login script read that argument and use it for a redirect after successful login.

```
$retTo = $_GET['return_to'];

```

etc, etc.

---
Tags: redirection
---


# Question
Title: Should a module implementing a filter delete the Drupal variables it uses, when uninstalled?
I checked some modules implementing an input filter, and (if not in few occasions) I have never seen the modules removing the `module_name_$format` Drupal persistent variables when they are uninstalled.

Since a module should normally delete its Drupal persistent variables when it is uninstalled, is there a reason why an input filter module doesn't normally delete its own Drupal variables, for example because this is already done by Drupal?

# Answer
> 2 votes
A module should be responsible for cleaning up after itself when it is uninstalled. There is no reason not to do this, unless some other modules depend on those variables but I very much doubt this is a case. If they depend on a module they probably depend on the entire module, not just some variables defined by it.

I, for example, use htmLawed and out of curiosity checked the `.install` file; it does clean the variables defined in the format "module\_name\_format\_%".

As a best practice you should drop all the tables and delete the variables defined by your module, doing this by implementing `hook_uninstall` in your `.install` file.

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


# Question
Title: I need to remove manually a display from a view
While I was testing an organic groups view it caused a block display in the same view to come up with an error message every time I try to edit it. I could re-created the block view but can't delete the old block view through the UI. Is it safe to delete it manually from the views\_display table?

# Answer
> 1 votes
You can always try, you could also try to delete the display from the 'views\_display' table, in any case make sure to do a complete dump of your database so you may restore it if anything goes wrong=)

---
Tags: 7, views
---


title: How can I email all registered users?

text:
# Question
Title: How can I email all registered users?
A lot of similar questions show up in Google, but I can't find a solution for Drupal 7.

# Answer
> 3 votes
I often use Views Bulk Operations for this, and send a tokenized email. I have it create jobs rather than sending everything all at once. But every year I sent an email to 18000 members.

Update: Sadly, token replacement (a key feature to do this successfully, unless you're sending the same message to everybody) seems to be broken right now in both 6.x-1.x and 7.x-3.x of VBO. See http://drupal.org/node/1348552)

The basic strategy:

* Create a view of users
* In D6, you make it a VBO view by changing the style; in D7 you do it by adding a "bulk operations" field.
* When configuring the style or the field, tell it you want to send an email (or tokenized email in D6; make sure you have token\_actions enabled).
* Send the email. Use tokens in your email like
    + D6: \[mail\] and \[user\] - there are prompts to show you how
    + D7: \[user:mail\] and \[user:name\]. It's hard to figure out the right tokens for D7, but if you install and enable the Token module and then visit the admin-\>configure-\>system-\>actions and create an email action, you'll be prompted with the available options.

Things you'll want to do for testing:

* Make sure you test locally so you don't make big mistakes
* Use the Reroute Email module or another technique to make sure that email does not escape.
* Create dummy users with Devel Generate module (part of Devel module)

# Answer
> 5 votes
You could use the Mass Contact module.

> The Mass Contact module allows anyone with permission to send a single message to multiple users of a site, using its roles functionality.

---
Tags: 7, emails
---


# Question
Title: How to charge a user to post a job listing in D7?
I have a job board and want to charge recruiters for each time they post a job listing. I will be using paypal and would not mind using the Commerce module in Drupal 7. I'm comfortable building Rules, even very complex ones. What is the best way to let job recruiters and businesses manage purchasing credits to be granted permission to create a job posting content type?

# Answer
Commerce Credits gives the developer many different granular options to configure paying per content basis
> 1 votes

# Answer
You can use a combination of Commerce userpoints and Commerce Node Checkout. This will allow them to purchase credits to be applied to publishing nodes.
> 2 votes

---
Tags: users, commerce, payment-gateways
---


title: Load all node titles with db_query()

text:
# Question
Title: Load all node titles with db_query()
```
$title = db_result(db_query("SELECT title FROM {node} WHERE nid = %d", 1));

```

with this code i can get title from node with id == 1. But how can i load all node titles with specific content type?

```
$title = db_result(db_query('SELECT title FROM {node} WHERE type = %s', $content_type));

```

Please correct my code to get all node titles from specific content type and how to limit them by 20 items for example?

# Answer
> 7 votes
```
$result = db_query_range("SELECT title FROM {node} WHERE type = '%s'", $content_type, 0, 20);
$titles = array();
while ($row = db_fetch_object($result)) {
  $titles[] = $row->title;
}

```

http://api.drupal.org/api/drupal/includes--database.inc/group/database/6

---
Tags: database
---


# Question
Title: Struggling to start a project from scratch
I am having 6 months of experience in drupal 6. I can able to handle bugs and any new functionality in the existing project.

**But i can't able to move single step ahead in the new project.** I know PHP very well and if i need to start a project from scratch in PHP i can do without any hesitation.

But i can't able to do with drupal :(

> 1. What is the problem with me ?
> 2. What should i need to do to start a project from scratch ?
> 3. What are the things i need to improve ?

Any guidance will help me a lot..

Thanks in advance..

# Answer
The "Drupal learning curve" article will help you put things in perspective. You can't learn Drupal in a day, but if you learn a little bit every day you'll be a pro soon. The buildamodule.com courses are a great learning tool.

If you start with Drupal I also recommend starting on Drupal 7.
> 2 votes

# Answer
It sounds, what Your problem is not in Drupal.

Check the Done Manifesto, probably it will help.

And let's move to Drupal 7 :)
> 3 votes

# Answer
I think first you need project requirements.

Then install Drupal which is very easy to do and start reviewing the modules which could provide functionality you are looking for.

Try to come up with very specific project related problems instead of asking philosophical questions.

There is nothig wrong with you, just do it!
> 0 votes

---
Tags: 6
---


# Question
Title: create thumbnails of Vimeo videos programmatically
I am wondering if there is a way to create thumbnails of Vimeo videos programmatically. e.g. is there a function like image\_style\_url() to create an image derivative given a style and image path? thanks.

# Answer
> 3 votes
You you can use the Vimeo Simple API to get the video thumbnails.

There is a fantastic write up here on stackexchange so I won't reinvent the wheel, but for a quick re-cap you can use the following code (thank you @Fluffy from link above.)

```
<?php

//Video ID - Easy to find in URL (example ID below)
$video_id = (int) 6271487;

//Format you would like returned. (Can be php, xml or json)
$format = (string) 'php';

//Build request URL
$request_URL = "http://vimeo.com/api/v2/video/$video_id.$format";

//Get data and unserialize
$response = unserialize(file_get_contents($request_URL"));

//Echo's url to image.
echo $response[0]['thumbnail_medium'];

?>

```

Optionally, check out the Vimeo Advanced API method: vimeo.videos.getThumbnailUrls

---
Tags: files
---


# Question
Title: I want to make node views "Edit link" field as a menu
Is it possible to make "Edit link" field as a menu. On my site one user can create only node and I have a page view which displays the node the user logged on has created. This views has a "Edit link" field so that the user can jump to node edit page from this view page.

However I want to have a menu or tab that can directly link to the node edit page of the node the logged in user has created. It should a menu or a tab that says "edit my node" and the user can directly jump to the node edit page without visiting the page views.

# Answer
Menu items in Drupal are cached, so you cannot make them dynamic. I recommend that you do like the user module in Drupal core does for the /user path.

First, create a custom module. In your custom module, implement hook\_menu like this:

```
$items['my-page'] = array(
  'title' => 'My page',
  'page callback' => 'edit_my_page',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

```

This will link the url example.com/my-page to the view\_my\_page() function. The view\_my\_page function could look like this (similar to user\_page()):

```
function edit_my_page() {
  global $user;
  $my_nid = 0;

  // Write your own code here to retrieve the Node ID for the
  // current user and store the Node ID in $my_nid.

  if ($my_nid) {
    menu_set_active_item('node/' . $my_nid . '/edit');
    return menu_execute_active_handler();
  }
  else {
    return drupal_get_form('user_login');
  }
}

```

Now, when a user navigates to example.com/my-page, Drupal will serve the correct node edit page.
> 0 votes

# Answer
I'm a bit confused, because your question sounds like a basic Drupal feature that has been around for years: tabs with "local tasks" as they are called. Here is a screenshot from a Drupal 7 site, without any extra modules:

If I understand correctly, the 'Edit' tab is what you are looking for... Or isn't that what you need?
> 0 votes

---
Tags: views, 6, routes
---


# Question
Title: hook_form_alter doesn't load load my form_id
I'm trying to hide a CCK field in my node-edit form. I followed this tutorial:

http://dominiquedecooman.com/blog/drupal-how-disable-form-element-cck-form-using-form-alter

but i'm stucked at the implementing hook\_form\_alter function, it seems that this hook doesn't recognize my form, i've tried this:

```
function video_tutorial_form_alter(&$form, &$form_state, $form_id) {
  print_r($form_id);
}

```

but it only prints "search\_block\_form search\_theme\_form";

# Answer
> 3 votes
You have 3 options if you wish to hide a form item:

1. Use .css and make your life simple using display:none;
2. create a custom module (see below)
3. Why even have the cck field if you are going to hide it? What's the point of that?

Please note that the above tutorial DISABLES the field and does not HIDE it. Disabled fields can not be edited, but they are still displayed!

To point 2: Is this function in your themes template.php? If yes, I presume your theme is called 'video\_tutorial', if not, you should rename your function so it is THEMENAME\_form\_alter.

However, since you're using the edit node form it will actually be using the admin theme, not your front end theme - unless you have changed permissions for certain usergroups not to be able to access the admin theme or you are using the front end theme as your admin theme (unlikely) -, so you're better off creating your own module to override the form rather than using the themes template.php file:

**How to create your custom module:**

1. Create a folder, call it whatever you like - but it should make sense - eg:

```
custom_admin_overrides

```
2. In it, create two blank text files:

```
custom_admin_overrides.info
custom_admin_overrides.module

```
3. Open custom\_admin\_overrides.info and add the basics so drupal can see your module:

```
name = Custom Admin Overrides
description = Custom Module that provides Admin Area Overrides
package = Custom
core = 7.x

```

Save the .info file and add the following to your custom\_admin\_overrides.module file:

```
<?php
function custom_admin_overrides_form_alter(&$form, $form_state, $form_id) {
 if($form_id == 'YOUR_FORM_ID') {
  $form['FIELD_NAME']['#disabled'] = TRUE;
 }
 // YOU CAN UNCOMMENT THE BELOW FOR EXTRA HELPFUL DETAILS
 // GET FORM ID UNCOMMENT BELOW
 drupal_set_message("YOUR_FORM_ID is : " . $form_id);
 // GET ALL FORM ELEMENTS UNCOMMENT BELOW
 // drupal_set_message(dprint_r($form, TRUE));
}

```

Note that we aren't closing the

Save and upload the folder to your site/all/modules/custom/ folder.

Now enable the module and from that point onwards you should see the form id's displayed on all admin pages in the drupal message box at the top.

Now go to your specific node create/edit page and make a note of the form id and the field name you wish to disable. Now reopen your custom\_admin\_overrides.module file and replace the values for

```
YOUR_FORM_ID

```

and

```
FIELD_NAME

```

Save and now your field should be uneditable. Uncomment the following line to stop displaying the form id's:

```
drupal_set_message("YOUR_FORM_ID is : " . $form_id);

```

---
Tags: entities
---


# Question
Title: Select fields with group names in Drupal 7?
When you make a select list on a webform module you get the option to group values by a group name or category: "Option groups for lists and menus may be specified with . \<\> can be used to insert items at the root of the menu after specifying a group." Reference : http://drupal.org/node/325766 -\> "Entering options through the interface"

Is this something I can do with the defualt node select fields aka (list module) ie. http://drupal.org/documentation/modules/list ? I have never heard of it but it would be nice. I have to make a list of working group positions on my site and I have 3 groups each with it's own group name, Hospital, Dental and Physicians and I am trying to figure out the best way to list these groups and their positions in a nice select value widget, I was thinking of using taxonomy but it's not really the same thing as what I want.

# Answer
You can do that if you use php to generate the allowed values, as you have already read in Select fields with group names?. However, that feature did not go into Drupal core when most of the CCK module for Drupal 6 was included in Drupal 7. The D7 version of CCK tries to provide this feature. As the module page says, it contains:

> some miscellaneous helpers to do things that core will not do, like maintain the PHP code snippets some fields may have been using to define allowed values (partially working)
> 2 votes

---
Tags: entities
---


# Question
Title: How to display a colorbox only one time when a page loads
I have created a colorbox effect to show the login form when the home page loads using the following jQuery code:

```
jQuery(document).ready(function() {
  jQuery.fn.colorbox(
    {href:"user/login/colorbox",open:true}
  );
});

```

Now I want to do the same to display a registration form, but this registration form should only be displayed one time.

Please can any one help me find a solution..

# Answer
> 0 votes
I would suggest writing a cookie after showing the login form and checking if the cookie exists before that. For cookies there's a nifty jquery plugin as well - no big programming involved on your side. HTH

---
Tags: users, javascript
---


# Question
Title: Merge two drupal views with different base types ('user' and 'node')
**Is it possible to merge two views, one based on users and one on nodes?**

The purpose of this is to create a directory of contacts, however some of the listings will be site users and some will not be - they will be created by admins.

It has crossed my mind to just use a content type that users can create; the downside of this is that if they update their details they'd have to update their node too...

# Answer
> 1 votes
Why not simply use a content type *only*?

You can for example add an optional user reference field to a content type, which points to the user to whom the contact belongs. Then you can embed the content type into the user profile, if you want that. For example by using the Panels project.

For normal users, you could write a few lines of custom code to automatically populate the user reference to the current user and hide the field from them. You could also add a check that they can only create a single contact, if you want that.

# Answer
> 0 votes
Checkout this article on "reusing fields":

> There are two main reasons for reusing fields. First, reusing fields can save you time over defining new fields. Second, reusing fields also allows you to display, filter, group, and sort content together by field across content types. For example, the contributed Views module allows you to create lists and tables of content. So if you use the same field on multiple content types, you can create a View containing all of those content types together displaying that field, sorted by that field, and/or filtered by that field.

I'm not sure if it will work with the users content type. If not you could use profile2 which uses regular content types for user profiles.

---
Tags: views
---


# Question
Title: Why are URL encoded values in $_GET variables broken?
I'm working with a payment gateway that returns payment feedback in the URL. One of the variables has a special character in it:

```
PM=Sofort+%DCberweisung

```

The `%DC` is `Ü`. However, it's coming through instead as �—and in case that doesn't display properly here, it's a black triangle with a question mark inside it. I confirmed this by replacing my menu callback with a simple print and die:

```
print($_GET['PM']); die();

```

The output is just (again: I'm not sure how that broken character might appear here on StackExchange):

```
Sofort �berweisung (DE)

```

I have confirmed that if I replace the `%DC` in the URL with `Ü`, it prints fine, so it's not a problem with that character: something is going wrong, somewhere, when the server tries to decode the URL-encoded value.

Does Drupal do any kind of processing on `$_GET` variables during bootstrapping? Could this be an Apache configuration issue?

**Update:** This is definitely something in Drupal. I moved my print-then-die to the very beginning of `index.php` and it prints the correct value. This tells me that it's not an Apache problem. Then, on a clean D6 install with no contrib modules, I added a small module that just adds a single menu callback to do that same print-then-die, and I got the invalid character there.

# Answer
Sounds like your incoming data is ISO-8859-1, not the other way round. Drupal is *always* in UTF-8 (and utf8\_encode converts *from* ISO-8859-1 to UTF8).

This is what I get when urlencoding Ü.:

```
$ drush ev 'var_dump(urlencode('ü'));'
string(6) "%C3%BC"

```

And when urldecoding *and* utf8 encoding %DC:

```
$ drush ev "var_dump(utf8_encode(urldecode('%DC')));"
string(2) "Ü"

```

Makes all perfect sense to me.
> 2 votes

---
Tags: 6
---


# Question
Title: How do I remove frontpage content block?
I am trying to remove the main page content page. I made a views slider (block) which I then displayed on the frontpage. However, I am finding it difficult to remove the mainpage content block. I am using drupal 7 and the zen subtheme.

# Answer
> 2 votes
You cannot remove the `content` part of a page as it is not a block. The content is suppose to be your main content that always shows and blocks are things that can be conditionally shown around your content.

You can create a page display for your view, then change the front page of your Drupal site to point to your views page display (D7: admin/config/system/site-information, D6: admin/settings/site-information).

# Answer
> 0 votes
You don't have to remove the default front page: Just make a new page that you want as front page, and click 'make front page' option.

You might need the Panels module for that.

---
Tags: 7, blocks
---


title: Conditional that looks at URL

text:
# Question
Title: Conditional that looks at URL
Im attempting to wrap my secondary links in an if statment that looks at the URL and only displayes them if URL is work/\*.

The secondary links are only related to work but show on every page so i am trying to emove on any path that is not work/\*. The secondary links are within my page.tpl

Ive been tryin with this but no joy.

```
 <?php  if ($the_url = explode('/', urldecode(request_url('work')))):?>
         <div id="secondary-links-wrap"><?php if (!empty($secondary_links)){ print theme('links', $secondary_links, array('id' => 'secondary', 'class' => 'links sub-menu')); } ?></div>
<?php endif; ?>

```

Any help would be much appretiated.

Thank you

# Answer
Try this:

```
$request_array = explode('/', request_uri());
if (in_array('work', array_values($request_array))) {
  //execute your custom code
}

```
> 2 votes

---
Tags: routes
---


# Question
Title: Why doesn't a form immediately call its submission handler?
I have a form which is called from a page function. The page initially makes some external calls to get #default\_value data which gets passed to `drupal_get_form()`. When the form is submitted, the page function gets called before the submission handler. Why is that? I don't get it and I don't want that to happen because it then connects to an external data API for no reason.

Does anyone know of a good place to find the calls order for a default submission handler? I'm unable to debug this.

There is an AJAX update when the form inputs refresh, but I don't see how that matters.

# Answer
> 2 votes
To understand this, we should step back a bit in look at how forms are used regardless of what CMS (if any) is in use.

All `<form>` tags have an `action` attribute which define what page the browser should send the data to. If `action` is left blank (or missing) the browser will assume it should send the data to the same URL it is currently on. In this scenario the URL will be loaded to get the form *and* then again to send the data.

This is how the Form API works (by default). When you define a URL (using `hook_menu` I presume) that presents a form to the user, the browser will use the same URL to load and send the form.

The menu router in Drupal has to be run first so it can determine what page to display. Only after that does Drupal see that it has a form and then run the submit callback. **In other words, you cannot change the order of these functions.**

You can provide an #action attribute in your Form API implementation which (combined with a new `hook_menu` entry) should let you separate your form load/submit functions.

---
Tags: forms
---


title: How to add a timer in views?

text:
# Question
Title: How to add a timer in views?
I have created a view which displays a list of product in table grid formate with four rows. I have fields related to the product like image,price,descriptions and so on. Now I want to create a field which should display the discount time left for each product. I tried to use jQuery countdown timer module to implement this but it didn't work. Can any one suggest which module I can use to create a timer field in Druapl7.

# Answer
I think you were on the right track.

Check out this issue comment: http://drupal.org/node/685956#comment-4412688

It links to a GitHub repo, from which you can find a fork at https://github.com/blackice2999/jquery\_countdown/tree/7.x-1.x that appears to contain a Drupal 7 port.

Try that.
> 0 votes

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


# Question
Title: Creating and storing data in the database
I have created a forum in administer-\>modules in Drupal 6, and I have set the permissions also, but it is not showing in my site.
I do not know how the forum contents will be stored in database, and how to establish a connection to the database.

# Answer
You don't have to worry about the database. But do some reading on how the forum works. If you're not getting any error messages you probably didn't set it up correctly.

Visit this page to see a list of all your forums: `www.example.com/admin/content/forum/list`

And some reading:
> 2 votes

# Answer
It sounds like you have skipped some necessary steps for configuring Drupal 6 forums.

Forums are based on a taxonomy structure, which you'll first need to create in: /admin/content/forum You create "containers" (where "forums" can be created) and forums (where topics can be created and replies made to them). This is a fairly good overview of all the steps needed to set up a basic forum system in Drupal 6: E-how article for building forum website in Drupal 6

You may also wish to consider using the Advanced forum module, which adds some extra functionality to the fairly basic "core" forum features.
> 1 votes

# Answer
Try clearing the cache in Drupal. You don't need to manually connect to the database.
> 0 votes

---
Tags: database
---


# Question
Title: D7+ i18n: What is the normal way: a single node with 2 translations or a different node for each translation
I am having a difficult to understand this issue:

My D7 + Internationalization create a different node for each translation. Is this the normal way? Than how does Drupal know they belong to a same article. I remember in D6 was one node and one editing page for all the translations of the articles.

I think the normal way is to keep a single node and different paths with different prefix: /fi or /en.

What do you think?

# Answer
> 1 votes
I believe this is the normal way. In /admin/content it lists the content and you can sort by language.

It knows which belong to which because it writes that info into the node table in the database by defining the 'tnid': The translation set id for this node, which equals the node id of the source post in each set.

---
Tags: i18n-l10n
---


# Question
Title: How to add custom language specified text?
I'm using multilingual feature in D7.

Let's say...I have a word 'standard' that I like to use in other languages.

Where do I put the word and how do I load it in my templates?

# Answer
You can set the translations for each specified language in the strings settings part of the internationalization module: /admin/config/regional/i18n\_translation

To show it in a template file you simply use the t() function to wrap your text - which translates text for you and automatically adds new text defined in the t() function to the strings page.

See http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

If you are hardcoding links with your text you can use l(), so if you have say a text link and want the text to be translated you would use l() and in it define your text using t() - something like this: http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

See http://api.drupal.org/api/drupal/includes--common.inc/function/l/7 for its usage.
> 1 votes

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


# Question
Title: How to switch between conflictual hooks?
In a custom module I'm implementing the `hook_menu_alter` hook to alter the page callback for the `$menu['taxonomy/term/%taxonomy_term']` menu.

I've noticed that my hook is not implemented because another contrib module ( Taxonomy Display module ) already implements the same hook (all works fine if I disable TD).

What I need is not to prevail on TD hook with mine, but to use my hook under a certain condition, and TD hook for all other cases.

The condition is the presence of parameter "v" in the querystring, like the following example:

if url == `taxonomy/term/tid?v=value` then use `mymodule_menu_alter`

if url == `taxonomy/term/tid` then use `taxonomy_display_menu_alter`

How I can do that?

Thank you very much!

MXT

# Answer
> 1 votes
I've reached a working solution:

```
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // move mymodule at the end of the list, so it will be implemented at last:
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

function mymodule_menu_alter(&$menu) {
  if (isset($menu['taxonomy/term/%taxonomy_term'])) {
    // alter menu to serve my own custom term page
    $menu['taxonomy/term/%taxonomy_term']['page callback'] = 'mymodule_term_page';
  }
}

function mymodule_term_page($term) {

    $params = drupal_get_query_parameters();
    $vocab = taxonomy_vocabulary_load($term->vid);

    // If this voc hasn't to be processed, return the default taxonomy term page:
    if(!variable_get('mymodule_' . $vocab->machine_name . '_enabled')) {
      module_load_include('inc', 'taxonomy', 'taxonomy.pages');
      return taxonomy_term_page($term);
    }

    // If param 'v' is present in querystring
    if(isset($params['v'])) {
      // return another custom callback term page:
      return mymodule_show_term_tree($term);
    }
    else {
      // Else call Taxonomy Display module calback page:
      module_load_include('module', 'taxonomy_display');
      return taxonomy_display_taxonomy_term_page($term);
    }
}

```

I'll hope this will be usefull to others.

# Answer
> 2 votes
If you implement a hook, it will always be executed.

The condition of a query string makes things more complicated in your situation, because all menu items are defined by their path (`taxonomy/term/tid` in your case). This means that - as far as Drupal is concerned - `taxonomy/term/tid?v=value` and `taxonomy/term/tid` have the same menu item, so both requests will be handled by the same code.

Is it really necessary that the URL takes the form of `?v=value`? If you could make it `taxonomy/term/tid/value`, you can create your own custom menu item for `taxonomy/term/%/%`, and simply leave the `taxonomy/term/tid` path as is.

# Answer
> 1 votes
I'm not sure but perhaps you should make the weight of your module higher than Taxonomy Displays, so your modules hook get called first. Check out this http://drupal.org/node/110238

---
Tags: 7, hooks
---


# Question
Title: is it possible to load data of one block in the tpl of another
I'm a novice drupal coder and trying to accomplish the following

My scenario is such that i have the template files **block-mymod-1.tpl and block-mymod-2.tpl** respectively.

What i'm intending to do is get the data of block 2 to be displayed in that of 1.

currently $block-\>subject and $block-\>content in block-mymod-1.tpl give the subject and content of block1.

Is there a drupal way of overload the *$block* so that it could hold the subject and content of second block also?

Apparently my google skills were not good enough or i couldn't find a direct answer.

Any positive response would be greatly appreciated..

Thanks n Cheers!!!

# Answer
I'm not 100% sure if this will work, but it's worth a try!

You may be able to use module\_invoke to place block 2's content into the template of block one using the following code in your `block-mymod-1.tpl`:

```
$block = module_invoke('block', 'block', 'view', '2');
print $block['content']

```

This post might help to explain more, but for your needs you are only interested in the first and last arguments. The first tells Drupal which module you're invoking, and the last is the block ID of the node you're looking to load the data for.
> 1 votes

---
Tags: 6, blocks, theming
---


# Question
Title: Adding user roles without access to permissions
I want an administrator to add roles to a user without having access to admin/user/permissions where he can alter user permissions.
Currently, on the user permissions form there is only one checkbox that allowes neither one of them or both.
What is the correct way to achieve this?

# Answer
> 0 votes
Check out the Role Delegation module.

---
Tags: 7, users
---


# Question
Title: Setting the permission for editing block content with a specific role
I have installed the modules below, but still can not set the permission for editing a block **body** with an specific role. Does someone know how to solve this issue?

Thanks

Block Access

Block Content Per Role

# Answer
Both of those modules look more like they are meant to simply display different blocks/content depending on user role. You may be better off utilising Nodes In Block. Create a content type, or use one of your existing content types and create a node that has the required block content. Lastly, allow certain roles permissions to edit that particular node. That will in turn update the block content!
> 0 votes

---
Tags: 6, users, blocks
---


# Question
Title: Is it possible to use a function which uses $node without the expense of node_load
In cases where $node is not available but I know the nid, is it possible to mimic $node rather than using node load. I would like to try and cut the expense of performing a full node load..

For example to find a nodes taxonomy by vocab:

```
  $nid = 1;
  $vid = 1;
  $node = stdClass();
  $node->nid = $nid;
  $terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);

```

I have tried the above but it doesnt seem to work. I want to use the taxonomy\_node\_get\_terms\_by\_vocabulary function but dont want the expense of having to use node\_load to get the $node object

# Answer
In this case, I would just look at the source for taxonomy\_node\_get\_terms\_by\_vocabulary:

```
function taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid') {
  $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight', 't', 'tid'), $vid, $node->vid);
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
  }
  return $terms;
}

```

The only thing needed is `$node->vid`. Note that `vid` in this particular referes to node revision and not vocabulary ID. If you knew the `vid`, then you could just create your own function:

```
function mytaxonomy_node_get_terms_by_vocabulary($nodevid, $vid, $key = 'tid') {
  $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight', 't', 'tid'), $vid, nodevid);
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
  }
  return $terms;
}

```

The problem is that in most cases you don't know the `$node->vid` without doing a node\_load. Just querying using the nid may or may not be right if you use revisions or start using revisions in the futures. The proper way to do it would be to `JOIN` the node table into the query so you can use `$node->nid` as an argument instead of `$node->vid`.
> 3 votes

# Answer
You could just write a query yourself if you don't want to load a whole node object.

It should look something like this:

```
SELECT td.name
FROM {term_data} td
INNER JOIN {term_node} tn ON tn.tid = td.tid
WHERE td.vid = 1
AND tn.nid = 1

```

Then you can just loop through your results and do whatever you need with them.

I don't have easy access to a Drupal database at the moment, so the query might be slightly out..but it should be enough to get you started :)
> 0 votes

# Answer
I asked a similar question a couple days ago. Check the answers here and here.
> 0 votes

---
Tags: 6, performance
---


# Question
Title: Dynamic view listing nodes in proximity dependent on taxonomy term in url - which is not attached to the node itself
I think what I want is quite complex, but maybe someone can help me with some basics of it.

In d7 I have a content type and each node uses address field and via geocoder creates the geo data for that node. I use taxonomy terms here to categorize the node (eg: shop, restaurant, hotel, etc ..) and some nodes may have multiple categories added as they may be multiple types at the same time(one may be a restaurant as well as hotel).

I have created a taxonomy tree as such:

country -\> city, eg:

```
england -> london
        -> manchester
        -> newcastle

```

Each city also has geo data attached to it. The country and city will be used in the url to filter the results based on a set proximity.

So, for example I could have this url

```
www.example.com/england/london/restaurant

```

which is equal to (for examples sake)

```
www.example.com/country/$2/$3

```

The country page is a static page that may list taxonomy terms (cities) for that country.

The next page up - selecting the city from the country page - does not yet display a view, but gives options for which category the node is in (this taxonomy term is attached to the node (Shop, Restaurant, etc ..))

Now I want to create a view that uses term $2 to set the location from which to start the proximity search from (the geo data is already added to the taxonomy field for cities and mustn't first get geocoded from the city name)

Then term $3 is the category which is attached to the node.

It then displays all the nodes from that category at a previously set distance (radius) away from the cities geo data. I presume I can either create an admin field where the distance can be set or simply hard code it in the module.

So, I am quite new to creating my own custom module and apart from field api I have not had much experience with other drupal api's - especially the views api.

Here is what I need to do - as far as I am aware:

Create a custom module - I don't think I can get around that - that:

1) gets the $2 and the attached geodata

2) creates a view for all nodes with taxonomy term $3 attached to it and filters them using proximity to only show nodes in a XX km radius from the geo point supplied by $2. This obviously includes converting lat/long to distances from the set point...

3) I want to be able to display a proximity slider so the radius value can be changed and the view refreshes.

I know this sounds like a massive job, but I thought that maybe I could do some of it directly in views and then maybe use some alter\_hooks to add queries (for example to grab the geo data for $2)...

Can anyone help me with this, or give me some tips on how this can be done?

I just need some sort of strating point as I am totally new to this. I would also supply any code written back to the community and document my processes for others to follow.

Many thanks in advance.

# Answer
This is a broad question and becomes difficult to answer clearly. There are too many things to do and too many details to resolve. It looks a bit like you are trying to eat an elephant with too many missing teeth. I agree that you will need to create a custom module and by the description you gave, you will need knowledge of php for server side (pre display) and Javascript for client side action (after display). The first thing to do is get do some exploring in the structure of Drupal and how it operates. From my own experience I know that a couple months of exploration has made a tremendous difference in my ability to solve a problem like this. Do you have any programming experience? If not start with php basics. Then move on to Drupal.

There is an excellent video tutorial series at buildamodule.com. It charges for some of its content, but it covers a lot of ground. Building a module will require php/mysql expertise (book:Beginning PHP and SQL by W. Jason Gilmore), an understanding of Drupal operations (book: The Definitive Guide to Drupal 7 publisher:Apress) and a solid knowledge of the key modules (book: Drupal Building Blocks by Earl & Lynette Miles).

You'll know your ready when you find yourself looking forward to writing a custom module.
> 1 votes

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


# Question
Title: What else must I do to set up a new custom module?
I am defining my first custom module and cannot get Drupal to see it.

What I have done:

1. Created a subdirectory with module name at sites/all/modules/custom/mymodulename. The name is just letters, nno spaces underscores or dashes.
2. Added two files mymodulename.info & mymodulename.module.
3. mymodulename.info contains: name = mymodulename and includes a description, package = Other, and core = 7.x.
4. ran update.php
5. flushed caches
6. reloaded admin/modules page
7. module is not listed???

I suspect that I somehow let Drupal know this is my first attempt and it is just messing with me! How can I appease it?

# Answer
> 1 votes
Check for spelling mistakes, because you seem to have everything you need for it to be listed.

---
Tags: 7
---


# Question
Title: Can I make the second button in a form the default button?
I have a form in a custom Drupal 6 module built with the Form API, it has 1 or more image\_button elements in a list followed by the Save and Cancel buttons.

Everything is working fine when clicking the image and standard buttons, they call the submit functions they should, but if I hit the \[ENTER\] key within any of the text fields in the form the first button in the form is submitted, which unfortunately in this case is an image\_button in the list rather than the Save button.

This is a standard problem with web forms, you generally have to hack in a hidden (by style and/or size) button early in the form definition to ensure the default submit path is called (in this case that's what the Save button will call) rather than the submit path for the buttons that are before the button you want to be the default.

Is there some Drupal 6 magic that enables setting a default button regardless of where it is in the form definition that I've failed to find in the docs, or should I create a phantom submit button that is styled to not be visible?

Thanks in advance for any answers.

# Answer
The answer seams to be no, there is no built in Drupal method of getting around the problem of the first button in a form being the default when pressing \[ENTER\].

Here is what I had to do.

I created an extra submit button at the top of my form:

```
// A submit button that needs to be hidden, it'll be the default rather than one from the list.
$form['hidden-submit'] = array(
  '#type' => 'submit',
  '#value' => 'Save',
  '#attributes' => array('class' => 'hidden-default-submit'),
);

```

In the CSS included for the page I added the following belts and braces CSS to hide the extra submit button in as many web browsers as I could test:

```
.hidden-default-submit {
  position: absolute;
  left: -2000;
  top: -2000;
  width: 0;
  height: 0;
  border: 0;
  margin: 0;
  padding: 0;
}

```
> 0 votes

---
Tags: 6, forms
---


# Question
Title: flowplayer - stream from file:///fodler/video.flv possible?
I have converted my made in drupal into HTML with blue crab (spider) I have to give to my clients a USB stick with the site made in drupal and all pages have to work

there is only one problem \- the videos won't work offline Does flowplayer only work with a HTTP server??

# Answer
Flash video has problems playing from some local URLs in Windows, but it mainly has to do with network shares. The workaround is to map the share to a drive letter.

You may also be having problems with local file access versus network resource access. Google "flash player security restrictions" for an overview. With the Flowplayer SWF, you are likely out of luck for working around this w/o getting users to change security settings.

The best option is to use a local web server. With this you may even be able to get Drupal running off of your memory stick. There are several options, but I have had good luck with Server2Go. I have never used it with Drupal, though.
> 1 votes

---
Tags: media
---


# Question
Title: Can an identical profile and theme name cause conflict during installation?
I recently purchased a theme to install it on an Aegir hosting environment, which is a multi-site installation system. Does identical profile and theme names cause conflict or errors in Drupal?

# Answer
> 2 votes
Yes. Modules, themes, and profiles must have unique names.

---
Tags: theming, distributions
---


# Question
Title: Comment styling dependent on author's user roles
I want to style comments differently depending of the author's user roles. How can i add a specific class attribute in the comment template if the author of the comment has a certain role?

# Answer
I got it myself. Here is how to do it:

In your theme `template.php`:

```
function MYTHEME_preprocess_comment(&$vars) {
    // user roles
    // 1 = anonymous user
    // 2 = authenticated user
    // 3 = administrator
    // ...
    $vars['role_classes'] = '';
    $sql = "SELECT users_roles.rid FROM {users_roles} WHERE users_roles.uid = " . ((int) $vars['comment']->uid);
    $result = db_query($sql);
    foreach($result as $record) {
        $roleId = $record->rid;
        if($roleId == 3) $vars['role_classes'] .= ' comment-by-admin';
    }
}

```

Then change in your `comment.tpl.php`

```
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

```

to

```
<div class="<?php print $classes; ?><?php print $role_classes; ?> clearfix"<?php print $attributes; ?>>

```
> 2 votes

# Answer
It would probably be best to add an extra class to the body tag, so you can target .comment etc. inside the body.role-xxx - you can then use it on any element on the page

The site I'm on right now has

```
<body class="html not-front logged-in no-sidebars page-node page-node- page-node-521317 node-type-article" >

```

You need to add another to that by

```
global $user;
$custom = '';
foreach($user->roles as $key => $value ) {
  $custom .= ' role-' . $key; //or value, if you prefer
}
// add the string to the body attributes in the link below

```

http://api.drupal.org/api/drupal/includes--theme.inc/function/template\_preprocess\_html/7

Sorry, that is a bit garbled as I've got to run out the door right this second - but hopefully you can decipher and get your answer ;o)

Edit:

Tested working solution for you (I was slightly off with my guess yesterday)

```
function THEMENAME_preprocess_html(&$variables) {
  global $user;
  foreach($user->roles as $key => $value) {
  $variables['classes_array'][] = 'role-' . $key;
}

```

Then you can do something like

```
body.role-3 .comment {
  border: 2px solid green
}

```
> 0 votes

---
Tags: 7, theming, comments, users
---


title: Long form links in an "overview page"

text:
# Question
Title: Long form links in an "overview page"
I have a drupal project with a hierarchical page structure. On each category page (top level), I'd like to have a blurb about the category, and then a series of links to subpages, where each link has a title, an image, and a sentence or two, laid out in a box.

I've looked into modules such as "Menu Node Views" and "Node Hierarchy" but I'm not certain that those are the best way to go about doing this. (Right now, as a temporary solution, I've just defined a bunch of blocks each containing an individual link/image/blurb and attached them to the overview pages using contexts).

Can someone suggest a good way to do this? Ideally it could be attached to the menu system in some way so that changes to the menu would be reflected in the appropriate overview page.

(See http://www.freethechildren.com/aboutus/index.php for an idea of the kind of navigation structure I want to display in the page content, although there will be actual content above the link blocks).

# Answer
> 0 votes
I would simply use content types (cck if you're in d6), views in blocks, taxonomy and some theming. I'm sure there are other ways to do it, but this would maybe be one.

Create a taxonomy 'category' and add all the 'categories' to it.

Create the content types category\_page and category\_sub\_page (or something along those lines).

Create the fields you need for each content type: For the category\_page add a taxonomy tag field (to add the category from your 'category' taxonomy vocab) and if you wish to have images as headers different on each cat page add an image field etc ..

For the sub\_page you need 2 or 3 image fields (depending on how many different images you wish to show (1 on the teaser, 1 or 2 on the main page?) and another taxonomy field.

Create your category overview page - tag it. Create your subpages pages for that cat - tag them too.

Create a .tpl file for your node type: In d7, copy the node.tpl.php file in your theme/template/ directory twice and name them node--category\_page.tpl.php and node--category\_sub\_page.tpl.php (that's if you used naming conventions like above).

Create a node view that displays node type = category\_sub\_page and filter them by category, so only display category = 'SOMETHING' - or go even further and use arguments to get tax term of page and show only subpages with the same term (this way you could only use 1 view for multiple category pages). Create a block view from that showing teasers, add it to the content reagion using the blocks page. It should be displayed below the actual page content - if you don't have a region there you will need to add a block region. You'll have to add it to your theme in the page.tpl.php and the theme.info file. Read up about it.

Now edit your theme files for sub\_pages .. node--category\_sub\_page.tpl.php - start it with

```
<?php if (!$page): ?>

```

anything in between here will be shown as the teaser - that's you're menu block with text image - then

```
<?php endif; ?>
<?php if ($page): ?>

```

now anything in between is your sub\_page full view.

To help you add items use to display the different items called.

```
 <?php dsm($node); ?>

```

then add them with php, defining your layout and style classes. Now theme it using css to get your desired look

Now you've create a node that displays sub-nodes in a block below the content.

---
Tags: routes, blocks, navigation
---


# Question
Title: How to create page and restrict it to authenticated users?
I'm using the empty\_page module to create "myhome" page and show blocks with a user's own content. That page throws an error for authenticated users.

How can I create an empty page in code and throw a 403 error when a visitors tries to access it?

# Answer
You could override using the hook\_theme, even though this module doesn't actually give you any real themeable output.

Copy the function empty\_page\_menu() from line 26 onwards in file empty\_page.module to your themes template.php. Rename it to YOUR\_THEME\_NAME\_menu() The last bit says:

```
// Create the dynamic callbacks.
 foreach (empty_page_get_callbacks() as $cid => $callback) {
  $items[$callback->path] = array(
   'title' => t($callback->page_title),
   'page callback' => 'empty_page_empty',
   'access callback' => TRUE,
   'type' => MENU_SUGGESTED_ITEM,
  );
 }

 return $items;
}

```

Change this line

```
'page callback' => 'empty_page_empty',

```

to maybe

```
'page callback' => 'empty_page_empty_secure',

```

Now copy the empty\_page\_empty() function in empty\_page.module

```
/**
 * An Empty Page callback's empty content.
 *
 * @return string $output
 */
 function empty_page_empty() {
  return '';
 }

```

Rename it to empty\_page\_empty\_secure() and add a simple check: something like

```
 function empty_page_empty_secure() {
   if(user_is_logged_in()) {
     return '';
   } else {
     // go to your 403 page
   }
 }

```

Note that I havn't tried this, but it should work.
> 1 votes

# Answer
You should try the Frontpage module - it allows you to set different home pages for authenticated and unauthenticated users.
> 1 votes

---
Tags: 7, users
---


# Question
Title: cck delta values: delta with leading space = "historical change," no leading space = "multiple selection?"
One of our sites began exhibiting a periodic bug where users would try to save their profiles and get an error about an illegal value in one of the fields (a cck field for "industry," fwiw, that we disabled by removing edit permissions for it a month ago). The field has a number of possible values as checkboxes, so users were able to pick more than one when the field was available to them for editing, prior to us disabling it.

We noted that admin users could save the profiles, and that they would then begin to be savable by users with normal privileges.

We zeroed in on the content\_field\_industry table, and began running through cases with assorted users before we finally figured out that field records with multiple deltas sometimes suffered from the issue, but other times didn't. After more digging around, we finally observed that:

* if the record had more than one delta and values in the field\_industry\_value column had a leading space, the record would fail to save for normal users
* if an admin user saved the user profile, any delta records with a leading space in the field\_industry\_value column would be destroyed and the profile would become editable by a normal user
* if the record had more than one delta and the values in the field\_industry\_value column had no leading spaces, normal users could edit their profiles with no error

We don't want to lose the data, but we don't want it to be edited by normal users anymore, either, and we don't mind the thought of losing meaningless deltas (the ones that serve a historic purpose rather than a "this is a multiple selection" purpose).

Is there a safe way to clean up this issue, perhaps by simply deleting leading-space deltas?

# Answer
Use a custom module and unset the field items using hook\_form\_alter(), or do it in your themes template.php.

```
/**
* Implements hook_form_alter().
*/
function YOUR_THEME_form_alter(&$form, &$form_state) {
  if ( $form_id= 'YOUR_FORM_ID' ) {
    unset($form['YOUR_FORM_FIELD']);
    // ... ADD MORE
  }
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Images in content type: reusing and limit
In a content type template, I allow images. The only widget that appears for that field, is a File Upload widget. What if I want to reuse the image that has already been uploaded?

Also, how do I raise the limit of uploaded images from 10 to more?

Thanks Artur

# Answer
> 1 votes
Use the FileField Sources module to allow you to select new or existing files through additional means, including:

1. Re-use files by an auto-complete textfield
2. Attach server-side files uploaded via FTP
3. Transfer files from a remote server (cURL required)

**4. Select existing files through the IMCE file browser**

Also, to raise the limit of uploaded images from 10 to more, edit your image field settings and set the "Number of values" to "unlimited"

---
Tags: media
---


# Question
Title: How do I receive and record Paypal transaction variables from POST?
I have a service I want my customers to subscribe to, and I want to be able to update a field within my DB based on their subscription. Was it cancelled? Did it successfully begin/recur? I'd like to get this information, so I can perform the update within my database accordingly.

I would like to capture the transaction variables that Paypal POSTS to a specified successful payment URL, but I have no idea how. I obviously need to create a page that does this, but I'd like to know what I need to do.

# Answer
> 2 votes
Look at the uc\_paypal module included with Ubercart for a fantastic example of this. Look at uc\_paypal\_menu() (in uc\_paypal.module) and uc\_paypal\_ipn() (in uc\_paypal.pages.inc).

---
Tags: ubercart, payment-gateways
---


# Question
Title: Can you have multiple groupings on a view?
Is there a way to toggle between several different grouping on one view?

I have a view that is a list of nodes and I need to be able to group them by node title or by created date. Is there a way to do this without having to create two different views?

# Answer
1. Create multiple view pages in a single View definition and assign each with the same basic paths, but a different last segment eg. Node/%/Group1 & Node/%/Group2.
2. For each view select a menu item in the second column and set the type to menu tab. Provide the name to display on each tab.
3. Set one of the pages' menu to default menu tab so it will show up first. set its parent to already exists.

When you enter the path in the URL, you should get the default page displayed with the menu tabs above the view block.
> 2 votes

# Answer
Look at (Format: Unformatted list | Settings ) Settings. You will find Grouping field jump menu with all of your fields. You can choose one and will do the trick.
> 0 votes

---
Tags: views
---


title: How do I alter myuserpoints table?

text:
# Question
Title: How do I alter myuserpoints table?
I am using the Userpoints module. Using that, when I click the "My Score" link I am viewing a table with list of points.

There are 6 headers and 6 rows displaying. In that table, I need only 3 headers and 3 rows to display.

As of now, the module shows the following headers:

* Points
* Approved
* Date
* Operation
* Category
* Description

What I need to display is the following headers:

* Points
* Date
* Description

How can I achieve this?

# Answer
Here is the way:

> hook\_menu\_alter()

```
/**
 *Implemantation of hook_menu_alter()
 */
function your_module_menu_alter(&$items) {
  $items['myuserpoints']['page callback'] = 'userpoints_list_my_userpoints_custom';
}

```

By using menu alter write your custom function and change the table structure as per your need. And it's done :)
> 1 votes

---
Tags: userpoints
---


# Question
Title: How to lock a piece of content form being edited by specific roles?
I'm using Drupal 7. Right now, all users can create certain content. the way I have it set it is that all content has to be approved by users of the "editor" and "administrator" roles. Once the content is edited and approved I want to lock out the author so that he can not edit it anymore.

# Answer
I've not used it, but the Content Lock module might fit your needs!

**EDIT AFTER COMMENT**

What you could do then is utilise Taxonomy Access Control using the following method:

1) Add a Taxonomy vocabulary called "Locked" (or something like that)

2) Add two terms to that vocabulary - Locked and Unlocked

3) Set the permissions for authenticated users to be able to add/edit the content, but do not allow them to set the taxonomy terms.

4) Set the permissions using TAC so that if a node has the term of *Unlocked*, it is still editable, but as soon as that term gets changed to *Locked*, then authenticated users cannot edit that node.

5) Once the content has been submitted and approved, the user with the Editor or Admin role sets the term on the node to *Locked*. This will prevent the user from being able to access the edit page for the node.

It sounds much more complicated than it really is. You'll see what I mean when you get to the settings page for TAC.
> 5 votes

# Answer
I've done similarly for my article directory (http://www.articlesdirectoryindia.com) . I use http://drupal.org/project/rules to redirect to error page if author tries to re-edit an (submitted and) approved article. I suppose approval is indicated using CCK field in your case.

Otherwise you can simply write form\_alter and attach a validation function to give error in this case( trying to re-edit or save an approved article), which is better way to do it.
> 3 votes

---
Tags: 7, users
---


# Question
Title: Drop-down menu that shows the average of multiple rating criteria on Fivestar
I am working on customizing the Fivestar module, to allow the rating of multiple criteria.

The Fivestar rating should show a drop-down menu, in which the user could rate the object on 4 different criteria. The resulting rating should be the average value of those four criteria.

Can anyone point me in the right direction on where to start on this?

edit: i am running drupal 6

# Answer
This problem has been solved: I wrote the code to paste in the template, and added a module to sort by votes.

See Dropdown menu that shows average of multiple rating criteria.
> 0 votes

---
Tags: 6, rating
---


# Question
Title: How to access the filepath of an image from a view on a content type
I have a problem Accessing the file path of an uploaded image. I'm trying to create a custom Carousel and build it up in a Drupal Block. I'm pulling the array created from the view of the content type like so:

```
$slides = views_get_view_result('slide');

foreach ($slides as $slide) {
    echo $slide->_field_data['nid']['entity']->field_slide_image['und'][0]['uri'];
}

```

My problem is that URI prints out "public://someimage.jpg" instead of "someimage.jpg" or "sites/all/images/someimage.jpg." I know I could do a string replace on this, but Drupal must have a way of getting the right file path to the image. Any suggestions?

# Answer
> 1 votes
You can use `file_create_url($uri)` which will generate an absolute URL (including `$base_url` which contains your server domain name).

`print file_create_url('public://someimage.jpg');` will generate something like `http://localhost/sites/default/files/someimage.jpg` if your website is installed in localhost and your files are located in the default directory.

---
Tags: media, files
---


# Question
Title: Which Drupal clients allow editing of non-Blog nodes?
I'm looking around at some different techniques for posting content to our heavily-customised Drupal instances. We use a custom node type and I would like to be able to post content to that node type from a desktop client.

All of the clients I've found so far are general blogging clients - are there any available that support custom node types? Are there any restrictions around what they can / can't do?

# Answer
> 1 votes
Depending on how much work you want to do, you could write a custom interface in HTML5/JS, then wrap it in Titanium (link below) or Air http://www.appcelerator.com/products/titanium-desktop-application-development/

Then use the Services module http://drupal.org/project/services as the API - you might want to extend the functionality yourself

Also, not sure if this is for a particular client requirement. But if it was just node creation without opening a browser you could consider this http://drupal.org/node/1045918

...Or you can pull out the necessary code from the blog api and extend :o)

Either way I've got no simple answer I'm afraid

---
Tags: nodes
---


# Question
Title: selecting a referenced node from 1000's of nodes
I've a cck field "address" of node type Address within Building node type. My site may have tons of such addresses. So let me assume that already 10000 nodes of type Address exist and then one visitor tries to create a node of Building.

In the node reference field of address how'd one be able to select the correct address from 10000 addresses from "auto complete text field" address field?

As far as I know auto complete address would show only the node titles and many addresses can have same titles so how one would be able to select a particular address in the address auto complete text field ?

# Answer
> 1 votes
If you truely need to have a design that needs that many nodes to be referenced, you need to either have data integrity (Make sure that the nodes have proper titles so they can be found with the AC widget), or instead you need to build your own and more advanced widget.

The AC widget is not build for referencing 10.000's of nodes, if that is your need, you should create your own widget, that allows the users to input more data and thus easier find the address node they need. With CCK you can build your own widget.

Building a widget is in itself no small task, and building one that can handle these needs will not be any easier. There are a bunch of blogs with guides on how to do this, and you can look at the CCK module to see how it does it to get a better understanding.

**Update:**

I don't know what this Area 1-4 is all about, but my hunch is, that this could be built more clever to avoid this mess, I could be mistaking, but it seems like a flawed design, if a user needs to pick a reference from a list of 10.000's.
One way to deal with this, would be to let the user actually enter the address, and behind the scenes search for it. If it exists create the reference, if not create the node with the info and then create the reference.

---
Tags: 6, entities
---


# Question
Title: Template file is not overriding drupal 7 defaults
Why node--type.tpl.php is not working? I've cleared drupal cache 100 times no results. Is there something else i must to do?

# Answer
Overriding node templates are done by placing node--'nodetype'.tpl.php templates inside your custom theme folder. If the template isn't accepted after cache clear, check if the Machine name on admin/structure/types is the same as 'nodetype'.
> 4 votes

# Answer
Make sure you put node--underscores\_between\_words.tpl.php and saved it in your active theme directory.
> 0 votes

# Answer
To override the node templates using node--type.tpl.php in your theme you need to also make sure that your theme overrides the system node.tpl.php template; this can just be a copy of the system node.tpl.php file in your theme if you don't wish to change it. Without it, any other node templates in your theme will be ignored.
> 0 votes

---
Tags: theming
---


title: How to prevent user registration

text:
# Question
Title: How to prevent user registration
I'm getting a couple of user registrations on my personal website (presumably from bots or people trying to hack my site). How do I disable new user registration entirely?

# Answer
Change the setting 'Who can register accounts?' to 'Administrators only' at http://yoursite.com/admin/config/people/accounts
> 32 votes

# Answer
Go to admin/config/people/accounts and check the box that says Administrators only under **Who can register accounts?**
> 3 votes

---
Tags: 7, users
---


# Question
Title: How can I extract a specific field from a set of nodes?
I am using Drupal 7.

I have a custom content type with multiple fields. For example, one field contains a thumbnail image. Another is a text field.

There are 36 nodes that use this custom content type. In database terms, I have 36 records.

How do I have Drupal extract a specific field from each of the 36 'records' and display them on a single page?

For example, in PHP I could write an SQL query such as "`select fieldname from table`" and display using `while() { print $row['fieldname']; }.`

How do I achieve this using Drupal 7?

# Answer
> 2 votes
Use views, add fields - only the image - display for that content type only if published. done.

If you want to fine tune it, do some theming.

---
Tags: entities
---


title: Changing title of node when saving

text:
# Question
Title: Changing title of node when saving
Whenever an user saves a node I want to prefix it with table autoincrement-id so that the id is unique.

So if the title of node is "xyz" then it should be saved as unique id "299999-xyz". Ideally this id should be the node-id which is unique but it may not be possible to know the actual id until the node is saved in the table.

**What is the best way to accomplish it?**

I'm thinking of changing the title in the form validate function. This id can be numeric time() value.

**PS:*\*I'll have tons of such nodes so when linking them from other nodes (node-reference) this id will uniquely identify such nodes in "autocomplete textbox" in node forms.

# Answer
> 4 votes
I suspect you can do this via a hook\_nodeapi when `$op == "presave"`.

```
function mymodule_nodeapi (&$node, $op, $a3 = NULL, $a4 = NULL)
{
    if ($op == "presave") {
      $unique = mymodule_get_unique_number();
      $title = preg_replace("/^\d+\-/", "", $node->title);
      $node->title = $unique . "-" . $title;
    }
}

```

The trick is to tweak the PCRE pattern to extract the unique number from the $title. Putting in better delimiyters would help. You could always save off the original title in a CCK field that only uid==1 can edit, and build the node title from that.

EDIT: Just re-read the question. This will change the title every time you save. Not sure if you want that or not. You can edit the logic to only do this once, based on the preg results.

# Answer
> 7 votes
Use the module "Automatic Nodetitles". This allows you to use tokens on the title field. Once enabled you can set any pattern for the title. Set your pattern on /admin/content/node-type/YOURCONTENTTYPE to "\[nid\] - \[title\]" for example. Already existing nodes can be updated automatically.

# Answer
> 0 votes
This should also be possible using php by invoking hook\_insert. This hook is called after the node is saved and the nid is available, so you can then make changes and resave the node.

---
Tags: 6, forms, nodes
---


# Question
Title: Display vocabularies/terms inside content-type view
I'm working with D7 and Views 3. I created a view for my term pages (type=content, to show all my tagged content, which is a products' catalog). So far so good.

But now I would like to display in the same term page the vocabulary to which the selected term corresponds, along with all its siblings-terms, and a list of all the other vocabularies (without their terms), so the user can click on them and change the product category they're viewing.

I have my catalog like this:

Vocabulary A \- Product A1 \- Product A2 \- Product A3

Vocabulary B \- Product B1 \- Product B2 \- Product B3

Vocabulary C \- Product C1 \- Product C2 \- Product C3

And I'm trying to have this in my view (supposing I'm viewing product C2): Vocabulary A Vocabulary B Vocabulary C \- Product C1 \- Product C2 (selected) \- Product C3 Plus the other fields that belong to my product content type.

The idea is that the user can easily move between categories, and have the current category they're viewing with all its terms displayed.

Can I accomplish this with a single view? I tried adding taxonomy:name, term:name, etc as fields to my current view but I just managed to display the current term name and that's it. Can I create a taxonomy view inside my content view? or maybe this can be accomplished with arguments and relationships?

This is my first Drupal site so I'd appreciate any suggestion to know if I'm on the right track.

Thank you!

# Answer
> 0 votes
Create a new view block within your View definition and define it using contextual filters to display the appropriate content. Then go to admin/structure/blocks and move the block to the regions you wish it to appear in. One of the options for configuring the block will be to assign what pages it shows up on. By entering taxonomy/terms/% or whatever other path alias you are using you can limit where these additional blocks will appear.

---
Tags: 7, views
---


title: aligning nodes in views grid style

text:
# Question
Title: aligning nodes in views grid style
i need help aligning nodes in the views grid style. Each of my rows has 2 nodes but the problem am facing is that they are not aligned. in each row one node is slightly higher than the other. How can i create fixed grid dimensions so that each row is inline?

# Answer
I use the ccs\_injector module to add css snippets to fix alignment issues like the one you described.

For example, the css I used to assign even widths on a 4 column grid and to vertically align the content:

```
td.col-1, td.col-2, td.col-3, td.col-4 {
width: 25%;
vertical-align: top;
text-align: center;
}

```
> 2 votes

# Answer
I have not worked with grids specifically, but in general layout is managed using css and theming. If you have not gotten into theming in Drupal yet you will need to get familiar with it. Check google, there are many good tutorials. You will also need a tool such as firebug, an add-on for the Firefox browser.
> 1 votes

---
Tags: views
---


title: Remove menu item from display

text:
# Question
Title: Remove menu item from display
How can I programatically remove/hide a menu item when the menu is displayed?

# Answer
> 2 votes
If I understand well your question, you can use `theme_menu_item_link()` function to your template.php of your theme.

This is an example that I have tested (in this example Garland is the theme used, so you must replace the name of the function with the respective name):

Here is the example menu:

This is the function to remove the items:

```
function garland_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ($link['title'] != 'item 1') {
    $link['localized_options'] += array('html' => TRUE);
    return l('<span>' . $link['title'] . '</span>', $link['href'], $link['localized_options']);
  }
  else {
    unset($link);
  }
}

```

Please note that I have added `if($link['title'] != 'item 1'){..` to detect the menu item, and remove it (with `unset($link)`).

This is the code for changing the text:

```
function garland_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ($link['title'] == 'item 1') {
    $link['title'] = 'new text';
  }

  $link['localized_options'] += array('html' => TRUE);
  return l('<span>' . $link['title'] . '</span>', $link['href'], $link['localized_options']);
}

```

Remember to clear the cache to see the changes.

I found these other resources related with theme\_menu\_item\_link(): http://drupal.org/node/245156, http://drupal.org/node/249864, http://drupal.org/node/417482.

# Answer
> 1 votes
Here you have my implementation. I added the return line into the last `else`, and check for a specific role.

```
function batuka_menu_item_link($link) {
  global $user;
  if (in_array("club member", $user->roles)) {
    if (empty($link['localized_options'])) {
      $link['localized_options'] = array();
    }
    if ($link['title'] != 'Instructor Profile') {
      $link['localized_options'] += array('html'=>true);
      return l('<span>'.$link['title'].'</span>', $link['href'], $link['localized_options']);
    }
    else {
      unset($link);
      return;
    }
  }
}

```

---
Tags: 6, routes
---


# Question
Title: Validating form data that it is a weekday
I'm trying to validate a custom form field from an Ubercart module (in the checkout process). The field would specify a delivery date. The delivery date must be a business day.

How does one determine if it is a business day or not?

Are there given functions within Drupal that provide which day of the week when a response is given? Or would native php functions be the route to go with?

# Answer
> 2 votes
```
date('w'[, $timestamp]);

```

gives you the days of the week as an integer from 0 (Sun) to 6 (Sat).

So you could check to see whether the chosen delivery date is 1 - 5. I am not aware of any existing Drupal function to do this, but it's a fairly simple function to write oneself.

---
Tags: 6, forms
---


# Question
Title: Does db_affected_rows() works well with PostgreSQL?
This is a clean installation and I was starting to develop a module.
So I have the following code (and nothing more apart from the hook\_menu()):

```
$result = db_query("SELECT * FROM {variable}");
return db_affected_rows();

```

I used the `variable` table as an example since it was likely to be populated (and it is, of course!). Well, to my surprise db\_affected\_rows() always returns `0`.
Is there any reason why it doesn't work? Are there any reported bugs that I may have missed?

Setup:

* Drupal 6.22
* PostgreSQL 8.4
* PHP 5.3.8

# Answer
> 4 votes
To summarize for Drupal 6:

* `db_affected_rows()` gives you number of rows returned by a select if the database is MySQL but not if it's PostgreSQL.
* In Drupal 6 if you are using PostgreSQL you can run `pg_num_rows()` on the query to get the number of rows.

It is indeed database specific.

<sub>\[Reference: this comment in the Drupal documentation\]</sub>

---
Tags: 6, database
---


# Question
Title: How do I execute functions on a custom module?
I am writing my first custom module and would like to test its functionality, but am not certain how to call functions to run them from within Drupal. The module is installed.

# Answer
> 4 votes
You can call specific functions for testing using drush (drush ev "command();") or using the devel.module block/page (at /devel/php or so).

However, apart from some quick tests, in 99% of the cases, Drupal is going to take care of calling the functions of your module, through hooks and callbacks.

E.g., to have your module display something in your site, you need to implement `hook_menu()`, define a page callback then simply visit the defined path.

---
Tags: 7
---


# Question
Title: How do I use render() for my custom content?
I am creating a custom module to read content from text files and generate various custom content types I have defined on a project. Some will have specialized lists and tables and all will have specific class assignments. I can easily generate the appropriate markup added to the text and send it to the node-\>body, but have been researching render().

I understand that render takes an array that encodes the content and styling, but cannot find a framework for the array to know how to structure it for my content.

How does render work?

# Answer
There is no magic framework involved (just magic array structures). You just need to build up your array (Or in your case, extend $node-\>content in hook\_node\_view() if you want to alter how a node is displayed).

Basically, a render array is a nested array with properties (always start with a #) and child-elements, which are assumed to be another render-array. drupal\_render() will then dig itself through and convert it to HTML.

There are basically three things you can do, define a #type (types are defined in hook\_element\_info(), see system\_element\_info) including the necessary properties, define a #theme function and the necessary properties or just simply #markup, which is simply going to print whatever is in it (Note that #markup actually #type =\> markup, which is added automatically)

A basic example:

```
<?php
$render_array = array(
  '#type' => 'cointainer',
  '#attributes' => array('class' => array('your-class')),
  'child_element' => array(
    '#markup' => t('Some text'),
  ),
  'a_table' => array(
    '#theme' => 'table',
    '#rows' => $rows,
    '#header' => $header,
  ),
);
$node->content['your_module'] = $render_array;
?>

```

Assuming that the node template uses render($content), this will result in `<div class="your-class">Some text<table>...</table></div>`

You can also directly return such an array in a page callback function, see userpoints\_list\_transactions() for an example.

I have a feeling that you are however asking the wrong question: Note that is only for *rendering*, you can not store anything in this structure. To store that, you should first create the necessary fields on your content types and put your data in it, if you don't want it to be just text within the body. Also have a look at Display Suite, which gives you a lot of control on how to display your fields.
> 4 votes

---
Tags: 7, theming
---


# Question
Title: Replacing a 'Teaser'-themed node in a View its it's 'Full Content'-theme using ajax in Drupal 7
So, basicly, I have a Drupal 7 view that's displaying Teasers of Nodes.

WHen a user clicks this teaser, I want the node to load it's "Full Content"-content instead, and I would like this to be done using Ajax.

I've looked around a lot but I can only find solutions for Drupal 6, and many good solutions at that, but I'd love some help with figuring this out in D7!

Thank you!

# Answer
> 1 votes
You can try using the jQuery load method.

```
$('#teaser').load('node/exampleid #node-container');

```

Replace your teaser data with full-text.

The second method is to load hidden full-text with teaser in view; then, via jQuery on click method, just replace teaser by hidden-text.

---
Tags: ajax, views
---


# Question
Title: Views don't seem to be working properly on localhost with Chrome
This seems to be something connected to being on localhost rather than a server as once the site is uploaded it works fine - it's almost as if Chrome is too fast for my drupal site. Parts of the views don't register properly (fields will be missing) but some of them do.

The site works fine locally on FireFox, IE and Safari - it's just Chrome. Any ideas?

# Answer
> 1 votes
I think your chrome cache is loading the 'old' page

clear your chrome cache:

* when in chrome press shift+ctrl+del
* then check ´Empty the cache´
* click clear browsing data.

should be fixed now ;)

# Answer
> 0 votes
Clear your cached data and everything should be fine then. If not, clear the site cache and the reload the page. Also try updating the chrome. Chrome is fast but not fast enough for drupal.

---
Tags: views
---


title: Menu drop down in Drupal 7

text:
# Question
Title: Menu drop down in Drupal 7
I just started to learn and to develop a Drupal 7 site; therefore, I don't know Drupal very well.
How can I create the menu used in these two sites, http://www.honda.com.my/ and http://www.toyota.com.my/index.html?

# Answer
> 3 votes
There is three sides to the question.

One is to make dropdown multi-columns menu, also called *mega menu*. The Superfish module should provides that. But I'm sure there are others.

The second is to have pictures associated with the menu entries. One solution is to use pictures associated to the pages linked from the menu. If all the pages are nodes, this can be done by using a file (or media) field. Another solution is to use picture associated to taxonomy terms. And to use these terms as categories for the pages (through classic term-node association or any other solution). To get the picture for a menu entry, simply get the image for the term associated with its page.

Instead of looking for the pictures of menu entries when building the menu, which could be query intensive, I would rather use a custom menu callback to deliver the picture of a menu entry. The menu callback takes a single argument, the menu path, and ends by issuing a redirect (ie. drupal\_goto()) to the picture to use. Off course, use an image style to resize the pictures to fit in the menu.

The third question is to automatically generate a menu from the products list (nodes). I'm not sure this is actually wanted. The menu in Drupal are dynamic and can be edited at any time by users with the right permissions. On creation a node can be placed in a menu. If automatic menu are needed, custom code may be needed. The Auto Menu provides this feature even if it has not been ported to Drupal 7. The Taxonomy Menu produces menu from taxonomy hierarchies, so if product are terms this can work too. If coding is an issue, the Rules menu can provide the necessary tools to implement any custom menu entry creation logic. The solution really depends on the actual site structure.

Off course, you can also bypass the menu system and produces your menu using Views or custom code, but it means you will end up with a full-custom solution which won't be able to re-use any existing module, or even code snippets, targeted at *normal* Drupal menu.

# Answer
> 2 votes
An easy solution can be to use nice\_menus and override their theme\_nice\_menus\_build function.

Depending on your needs, you could call a block view from there, using views\_embed\_view, or any other kind of PHP logic you might need.

# Answer
> 1 votes
For Drop down menus there are modules like nice menus , super fish and mega menu. Mega menu is still in the development satge. You can go with any one depending on your requirement.

---
Tags: 7, routes, javascript
---


title: How to expose only one form in views?

text:
# Question
Title: How to expose only one form in views?
I have created a view with two exposed forms based on filter criteria and the sort criteria. I would like to display the sort criteria in the actual view and the filter criteria as a block.But when i save the view i get these two forms either as a block or as a view content. Can any one help me to display the filter criteria as a block and the sort criteria as a actual view?

# Answer
> 2 votes
I would suggest that you clone the view and amend it to display only the filter criteria that you require. You can then display the cloned view in a block and the original in a page, or wherever you require it to be.

---
Tags: forms
---