# Question
Title: Issue with the pagination in a custom template
I'm working in Drupal 7.

I have an issue with the search results: I have many records, and only one page with 10 results is generated. If I do a search that have many results (e.g. 50 results) I always see a single page showing 10 results.

If I change the template of a core module, e.g. the Garland theme, the pagination works well; if I set as default the custom template, the pagination doesn't work. In a template what calls the pagination? Why doesn't the pagination work in the custom template?

The custom template is based on a contributed theme. If I remove the search--results.tpl.php file, I see the pagination, but only two pages for any search. If a search returns 50 results, I can only see two pages; if the search only has one result, I can only see two pages showing the same result duplicated more than once.

The code contained in the search--results.tpl.php file is the following one.

```
<?php if ($search_results): ?>
  <h2><?php print t('Search results');?></h2>
  <ol class="search-results <?php print $module; ?>-results">
    <?php print $search_results; ?>
  </ol>
  <?php
       /* $search_conf = variable_get('search_config','');
        $search_limit = $search_conf['results']['limit']; */

  if (stripos($pager,'page=2')) print $pager; ?>
<?php else : ?>
  <h2><?php print t('Your search yielded no results');?></h2>
  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

```

The content of the template.php file is the following one.

```
/**
 * Return a themed breadcrumb trail.
 *
 * @param $breadcrumb
 *   An array containing the breadcrumb links.
 * @return a string containing the breadcrumb output.
 */
function MYTHEME_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';

    $output .= '<div class="breadcrumb">' . implode(' › ', $breadcrumb) . '</div>';
    return $output;
  }
}

/**
 * Override or insert variables into the maintenance page template.
 */
function MYTHEME_preprocess_maintenance_page(&$vars) {
  // While markup for normal pages is split into page.tpl.php and html.tpl.php,
  // the markup for the maintenance page is all in the single
  // maintenance-page.tpl.php template. So, to have what's done in
  // MYTHEME_preprocess_html() also happen on the maintenance page, it has to be
  // called here.
  MYTHEME_preprocess_html($vars);
}

/**
 * Override or insert variables into the html template.
 */
function MYTHEME_preprocess_html(&$vars) {
  // Toggle fixed or fluid width.
  if (theme_get_setting('MYTHEME_width') == 'fluid') {
    $vars['classes_array'][] = 'fluid-width';
  }

  $vars['node_type_MYTHEME'] = '';
  if ($node = menu_get_object()) {
    $vars['node_type_MYTHEME'] = $node->type; // find your cck field here
  }

  // Add conditional CSS for IE6.
  drupal_add_css(path_to_theme() . '/fix-ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lt IE 7', '!IE' => FALSE), 'preprocess' => FALSE));

}

/**
 * Override or insert variables into the html template.
 */
function MYTHEME_process_html(&$vars) {

  // Hook into color.module
  if (module_exists('color')) {
    _color_html_alter($vars);
  }
}

/**
 * Override or insert variables into the page template.
 */
function MYTHEME_preprocess_page(&$vars) {

    /*if (isset($vars['node'])) {
    $vars['theme_hook_suggestion'] = 'page__'.$vars['node']->type; //
    }*/

    }

/**
 * Override or insert variables into the node template.
 */
function MYTHEME_preprocess_node(&$vars) {

  if(user_is_logged_in() == 0){
  unset($vars['content']['links']['comment']['#links']['comment-add']['title']);
  }

  $vars['submitted'] = $vars['date'] . ' — ' . $vars['name'];

  $type = $vars['type'];

  if ($vars['teaser']) { // custom teaser templates
    $vars['theme_hook_suggestions'][] = 'node__teaser';
  }
  if ($vars['teaser'] && $vars['type']) {
    $vars['theme_hook_suggestions'][] = 'node__' . $type . '__teaser';
  }
}

/**
 * Override or insert variables into the comment template.
 */
function MYTHEME_preprocess_comment(&$vars) {
  $commentsDate = date('M d, Y',$vars['elements']['#comment']->created);
  $vars['submitted'] =  $vars['author'] . ' — ' . $commentsDate;
  //$vars['submitted'] = $vars['author'];
  $vars['title'] = $vars['elements']['#comment']->subject;
}

/**
 * Override or insert variables into the block template.
 */
function MYTHEME_preprocess_block(&$vars) {
  $vars['title_attributes_array']['class'][] = 'title';
  $vars['classes_array'][] = 'clearfix';
}

/**
 * Override or insert variables into the page template.
 */
function MYTHEME_process_page(&$vars) {
  // Hook into color.module
  if (module_exists('color')) {
    _color_page_alter($vars);
  }
}

/**
 * Override or insert variables into the region template.
 */
function MYTHEME_preprocess_region(&$vars) {
  if ($vars['region'] == 'header') {
    $vars['classes_array'][] = 'clearfix';
  }
}

/**
 * Override or insert variables into the region template.
 */
function MYTHEME_form_search_block_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#type'] = 'image_button';
  $form['actions']['submit']['#src'] = drupal_get_path('theme', 'MYTHEME') . '/images/button-search.png';
}

/**
 * Implement themehook_preprocess_user_picture().
 */
/*function MYTHEME_preprocess_user_picture(&$variables) {
$variables['fpublic_path_image_user'] = $variables['account']->picture->uri;
}*/

/**
 * Implement MYTHEME_node_preview for rewrite related message.
 */

function MYTHEME_node_preview($variables) {
  $node = $variables['node'];

  $output = '<div class="preview">';

  $preview_trimmed_version = FALSE;

  $elements = node_view(clone $node, 'teaser');
  $trimmed = drupal_render($elements);
  $elements = node_view($node, 'full');
  $full = drupal_render($elements);

  // Do we need to preview trimmed version of post as well as full version?
  if ($trimmed != $full) {
    if(!preg_match('@videos|image@',$node->type)){
    drupal_set_message(t('The trimmed version of your post shows what your post looks like when promoted to the list of pages or when exported for syndication.<span class="no-js"> You can insert the delimiter "<!--break-->" (without the quotes) to fine-tune where your post gets split.</span>'));
    }
    if(!preg_match('@videos|image@',$node->type)){
    $output .= '<h3>' . t('Preview trimmed version') . '</h3>';
    $output .= $trimmed;
    }
    $output .= '<h3>' . t('Preview full version') . '</h3>';
    $output .= $full;
  }
  else {
    $output .= $full;
  }
  $output .= "</div>\n";

  return $output;
}

function MYTHEME_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    $attributes['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    $attributes['class'] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

    if($element['#parents'][0] == 'field_image' && $element['#title'] == 'Title'){
    return ' <label' . drupal_attributes($attributes) . '>' . $t('Image Caption !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
    }   else {
    // The leading whitespace helps visually separate fields from inline labels.
    return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
    }
}

```

# Answer
In your search-results.tpl.php file you've got this line near the bottom:

```
if (stripos($pager,'page=2')) print $pager; ?>

```

That line is definitely not part of the standard search-results.tpl.php and would definitely cause strange issues when outputting the pager.

Try changing that line to simply:

```
print $pager;

```

That should solve the problem. :)
> 4 votes

# Answer
Try this:

1. edit the the view for block with pagination (you said in a comment that you have such a block);
2. go to the "pager" section and click on "paged, x items" (x is the number of items you display)
3. change "pager ID" to a different number
4. save the view

I think that your block is overriding the main pager. By changing that ID you tell Drupal that it should use 2 different pagers on the same page.
> 0 votes

---
Tags: 7, theming, search
---


title: Ajax form - Multiple select elements

text:
# Question
Title: Ajax form - Multiple select elements
I have a form with multiple select elements with an #ajax callback on change. The ajax is working but the problem is that I can't figure out how to find which select has triggered the ajax. All ajax callbacks point to the same function.

Any ideas on how to find which select was changed?

Thanks.

# Answer
> 1 votes
You should be able to make the distinction by checking `$form_state['triggering_element']`:

```
switch ($form_state['triggering_element']['#name']) {
  case 'select1':
    // Do something
    break;
  case 'select2':
    // Do something
    break;
  // ...
}

```

---
Tags: 7, forms, ajax
---


# Question
Title: Comment approval permission to non-admin user
I have three accounts in my Drupal 6 site:

* admin (which is admin)
* moderator
* moderator2 (which is authenticated role defined)

Now I want to give permission to the moderator2 to approve comments just like I did from admin account by only going to `/admin/content/comment`. How can I do that?

# Answer
> 0 votes
I take that "moderator2" is a username name used for a user account. In that case, if you want to give to moderator2 the permission to administer comments, then you have to associate the user account with a role you only give to those users you want to be able to administer comments, then you visit the page on admin/user/permissions, and select "administer comments" for that role.

In this case, I called the role "comments moderator" but I could have chosen another name.

If "moderator2" is a role name, then on the page at admin/user/permissions you see something similar to what shown in the following screenshot.

The permission is the same as before.

**P.S.** The only permission for which you are interested is "administer comments." The other permissions don't influence that one, and users with a specific role would be able to approve comments, even without to have (for example) the permission to access comments.
The only permission associated with the page at admin/content/comment is "administer comments."

```
  $items['admin/content/comment'] = array(
    'title' => 'Comments',
    'description' => 'List and edit site comments and the comment moderation queue.',
    'page callback' => 'comment_admin',
    'access arguments' => array('administer comments'),
    'file' => 'comment.admin.inc',
  );

```

---
Tags: 6, comments
---


title: Ubercart and Drupal 6 or 7?

text:
# Question
Title: Ubercart and Drupal 6 or 7?
At present stage Drupal 7 looks very mature, BUT is see some modules are not yet moved to Drupal 7 or not production Ready. For now I had troubles finding UC\_Product\_Import and UC\_AJAX\_CART. I was pretty confident that 7 was the right choice, but I am getting afraid I will need more modules that yet did not do the move to Drupal 7. What do you think?

# Answer
What's your reason for looking at Ubercart in D7? I would recommend taking a look at Drupal Commerce. It's not the perfect fit for everyone and is very developer orientated at the moment (this will get better eventually). It is where the future for e-commerce is for Drupal so I would defiantly take a look at it.

If DC isn't an option then it's just a matter of looking which modules you require have a stable release and which are close to a stable release.

Another thing to bear in mind when choosing between Drupal 6 and Drupal 7 is that Drupal 6 will have support (e.g. security releases) dropped for it eventually, so going with Drupal 7 may offer more longevity.
> 2 votes

---
Tags: ubercart
---


title: PHP Variables when writing rule

text:
# Question
Title: PHP Variables when writing rule
I am writing some php code to update an external database with the shipping and billing information after the order is complete, so I am writing a rule on checkout complete that adds the customer information to the database. I need to figure out what is contained in the variables that I want to use (eg. $commerce\_order-\>???) how would I figure this out, and is there a reference list anywhere that I can use?

# Answer
If you simply want to find out what is inside $commerce\_order then you can use

```
<?php echo var_dump($commerce_order);?>

```

I have made a module in the past that did a simerler thing to what you are trying to do. Using Ubercart I created a module that took advantage of the hook\_order function.

```
<?php
function myFunction_uc_order($ops, &$arg1, $arg2){
    global $user;
    $userId = $user->uid;
    if ($ops = 'update' && $arg1->order_status == "payment_received" && $arg2 =="completed"){
        $order = uc_order_load($orderId);
        //$order now contains all order information for the current order
    }
}
?>

```

This code will be run every time an order is "updated", this includes being created. So inside the if you can add your code to export to your 'external' database.

Hope this helps
> 2 votes

---
Tags: 7, rules, commerce
---


# Question
Title: how to render html link within dsm message?
I would like to include a link to the reports page within a dsm message. Here is what I tried:

```
  $loglink = l("logs", 'admin/reports/dblog');
  $msg= "See $loglink for watchdog messages";
  dsm ($msg);

```

However, this displays the raw html (a href=...) and does not render the link.

How do I render the html link within a dsm message? (I am using Drupal 6.x)

# Answer
> 8 votes
You can't with `dsm()` I'm afraid, it's run through Krumo which encodes any special chars into HTML entities. Check out the `dpm()` documentation (which is called internally by `dsm()`) and follow the function trail through and it'll make more sense.

You'll have to resort to good ol' `drupal_set_message()`:

```
$loglink = l("logs", 'admin/reports/dblog');
$msg= "See $loglink for watchdog messages";
drupal_set_message($msg);

```

---
Tags: navigation, debugging
---


# Question
Title: Adding jQuery UI selectmenu() to Drupal form
I'm trying to add a styling to the select form elements in my Drupal form using jQuery UI. I'm using Drupal 7 so the usual way to add jQuery UI would be something like this:

```
 drupal_add_library('system', 'ui.accordion');
 drupal_add_js('jQuery(document).ready(function(){jQuery("#accordion").accordion();});', 'inline');

```

However, when I try to add an effect that isn't bundled with Drupal 7 core, like this one, that approach doesn't work. Has anyone come across this problem before, and if so, is there a "standard" Drupal way of solving this?

# Answer
> 4 votes
I think the 'Drupal' way would be to implement `hook_library()` to add the new element to the system:

```
function MYMODULE_library() {
  $libraries['ui.selectmenu'] = array(
    'title' => 'jQuery UI: Selectmenu',
    'website' => 'http://filamentgroup.com/lab/jquery_ui_selectmenu_an_aria_accessible_plugin_for_styling_a_html_select/',
    'version' => '1.8.7',
    'js' => array(
      drupal_get_path('module', 'MYMODULE') . '/jquery.ui.selectmenu.min.js' => array(),
    ),
    'dependencies' => array(
      array('system', 'ui.widget')
    ),
  );

  return $libraries;
}

```

And then add it to your pages using `drupal_add_library()`:

```
drupal_add_library('MYMODULE', 'ui.selectmenu');

```

Doing it this way ensures that all the necessary core UI files are included in the page automatically, and allows you to add the widget with a single line of code any time you want to.

# Answer
> 0 votes
You would have to download the .js file and put it on your server. Then reference it this way:

```
drupal_add_js(drupal_get_path('theme', 'YOUR_THEME_NAME'). '/js/jquery.ui.selectmenu.js');

```

Don't use drupal\_add\_library

---
Tags: javascript
---


# Question
Title: How to determine what image style an image field of a node has?
In D7, is there a way to get an image style assigned to an image field? if I have created an image style, say, my\_image\_style by overriding a default image style (thumbnail, medium or large at /admin/config/media/image-styles) and then assigned it to a field\_image of a node at /admin/structure/types/manage/article/display, how can I programmatically determine what style does field\_image have?

# Answer
You can use the `field_info_instance()` function to get that information:

```
$entity_type = 'node';
$field_name = 'field_image';
$bundle = 'article'; // Or whatever content type you need.
$view_mode = 'default'; // Or whatever view mode you want to get settings for, e.g. teaser.

$info = field_info_instance($entity_type, $field_name, $bundle);

$settings = $info['display'][$view_mode]['settings'];

$image_style = $settings['image_style'];

```
> 4 votes

---
Tags: 7, entities, media
---


# Question
Title: Create shipping charge based in produc weight' with Drupal commerce module?
I just followed this Randy Fay video which shows how to generate a charge based in the products weight. I works fine. It multiplies the weight of products by a **Cost Per Pound** (CPP)

I need this **CPP** to be different based in the total weight of ALL products in the order.

**Example:**

Order up to 1 pound ........ **CPP** = 0,006

Order with weight higher than 1 pounds ........ **CPP** = 0,004

# Answer
Easy, create two rules, one where the condition is that the total weight is more than 1 pound and one where the condition is less than or equal 1 pound.

You can setup the rest of the rules to be the same, with only the price (CPP) being different.
> 1 votes

---
Tags: commerce
---


title: Using Drupal Commerce as a Quote Form

text:
# Question
Title: Using Drupal Commerce as a Quote Form
I have a client who needs to allow customers to put products in a cart so that they can be custom quoted, instead of purchased online. Is Drupal Commerce aptly suited for this? If so, what are some strategies to hide pricing throughout the process?

# Answer
Actually, Drupal Commerce fits this need perfectly as you can pretty much disable the entire notion of payments etc. no problem and the rest of the system won't mind at all.

The default "add to cart form" you use for adding stuff to your cart doesn't even display price.

Also, making a view out of the current user's shopping cart order (shopping cart contents are for Drupal Commerce "orders", just incomplete ones) to make a custom display of what the user has compiled and to make a rule for checkout that just sends the "order" to you(r) client.

I'd be happy to answer any more detailed questions you might run into, but in general, the answer is "yes" as the architecture of Drupal Commerce is very flexible and as it's fully entity-based, it integrates seamlessly with all other aspects of your Drupal site.
> 3 votes

---
Tags: commerce
---


title: Suggestions for a content type recipe?

text:
# Question
Title: Suggestions for a content type recipe?
Currently I am building two content types, and I would like to consolidate them into one. Here is the scenario. I have two content types - Restaurants and Shops. These two have exactly identical fields except for 'Category' which is a taxonomy list. For restaurants, the taxonomy list contains restaurant food categories (asian, italian, etc) and 'shop type' for shops (fashion, electronics, etc). The only reason I have two content types is so that I can enforce the category field which is required.

However, in my mind it seems like it would be better to just have one content type. What I would like to do is create a 'Business' content type where you then select what type of business. In this case, Shop or Restaurant, for example. When the appropriate Business type is selected, the corresponding taxonomy to describe that particular selection will become apparent, and be able to be enforced. So, if I choose 'restaurants' then the restaurant types list will become visible where as selecting shops will display the shop type list.

Any thoughts on the best way to handle this architecture?

# Answer
I personally prefer to set up more content types than less. So in this case, if it was up to me I'd have the Restaurants and Shops as two separate content types. The reason for this is scalability - in the future if you need to add more specific data to either Shops or Restaurants it's much easier to do if they are separate content types from now.

As separate content types it's a little harder to share template files, but this can still be achieved by including files via PHP.

Also you won't need to add any additional code to enforce a particular vocabulary selection depending on another field - the taxonomy module is set up so that you can choose which vocabulary is applicable to a certain content type, so even this core functionality lends itself to creating more content types.
> 0 votes

# Answer
You can use a Taxonomy vocabulary with 2 level heirachy. Something like this:

* + Restaurants
        - Restaurant type 01
        - Restaurant type 02
        - ...
    + Shops
        - Shop type 01
        - Shop type 02
        - ...
> 1 votes

# Answer
Conditional Fields will let you show/hide a term reference field, depending on the value chosen in the Business Type field.

Reference field option limit may also be a solution. Using 3 vocabularies:

* Business Type vocab:

+ Restaurant
    + Shop
* Restaurant food categories vocab (terms reference Business Type \> Restaurant)
* Shop categories vocab (terms reference Business Type \> Shop)

With this setup, a Context for the Business Type taxonomy would provide flexibility for theming, breadcrumbs, active trails, etc. Views would be able to differentiate between the two with a taxonomy filter.
> 0 votes

# Answer
I know it is not going to be an answer to your question, but I second mbelos's opinion. The gain seems delusive to me as well.

Think the Views way. Having one content type, how would you imagine setting up a view like "show me shops in town X that offer mens jackets", "show me restaurants that serve chinese or italian"... If you think you can address such scenarios having one type, go ahead - you are probably safe. I'm afraid however that over time you are going to be buried in if's and regret that merge.
> 0 votes

---
Tags: 7, nodes
---


title: Google Analytics Module not working

text:
# Question
Title: Google Analytics Module not working
Configuring Google Analytics Module, I mistakenly kept the example code during the first 2 configurations of the module: `UA-673320-6`.

Then I finally out the correct code:`UA-30183564-3`.

From looking at my website's page source, it appears all 3 configurations are in the header as javascript snippets?

I am not sure how to get Google Analytics setup so that it is linked to my website?

````
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-673320-6']);
_gaq.push(['_setDomainName', '.XXXXX.com']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//--><!]]>
</script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-673320-6']);
    _gaq.push(['_setDomainName', '.XXXXX.com']);
    _gaq.push(['_trackPageview']);

    (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async    = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') +     '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//--><!]]>
</script>
<script type="text/javascript" src="http://XXXXX.com/sites/all/modules/umi_docs_migrate/js/sphinx.js?m17g0h"></script>
<script type="text/javascript" src="http://XXXXX.com/sites/XXXXX.com/files    /js/js_IDBX5SzkJ9gGNq7x-qOE_2DZsexqguTJQGMKvi4w-Uw.js"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var _gaq = _gaq || [];_gaq.push(["_setAccount",    "UA-30183564-3"]);_gaq.push(["_setDomainName", ".XXXXX.com"]);var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30183564-3']);
_gaq.push(['_trackPageview']);_gaq.push(["_trackPageview"]);(function() {var ga =     document.createElement("script");ga.type = "text/javascript";ga.async = true;ga.src =    ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-  analytics.com/ga.js";var s = document.getElementsByTagName("script")        [0];s.parentNode.insertBefore(ga, s);})();
//--><!]]>
</script>

````

# Answer
I would like to offer an alternative. I have always had issues with putting my analytics into the analytics module. I have experienced what you have experienced, plus I question why this code has to go into a module? The fewer modules you have the faster your site performs.

I always get the code from Google and then hard code it into the theme files. In drupal 7, this would go into your html.tpl.php just before the tag, just as google instructs. That is called for every single page, so no pages will ever go without it. Plus, it makes your code lighter and one less module to worry about. It has always been the best solution for me.

note: if you are using d6 it would have to go into each page.tpl.php template or its derivative if you have more than that one. Hope that helps.
> 2 votes

# Answer
Have you tried clearing your cache? If that doesn't work, uninstall the module and reinstall it, making sure that when you configure it you set the correct Google Analytics ID on the first go...

I've never experienced this, but you might have stumbled across a bug. Make sure you're using the most up to date version of the module.
> 1 votes

---
Tags: javascript, google-analytics
---


# Question
Title: Allowed range for date input - down to the day level rather than the year level?
I am trying to set up a content review process for a client's site.

The desired process is this:

* When users are adding content, they specify a "review date"
    + This date must be between today and today +365 days
    + A week before that date, send an email to users of a role letting them know

When I am setting up the date field, I've set "Starting year" and "Ending year" (in Field Settings -\> More settings and values -\> Date entry), however this doesn't behave as expected. It will let you set a date within calendar years, but not within a year of today. So I can make it work for any date in 2012, but not a specific day.

I'm fine with the rules + email bit, just the date field is holding me up.

I'm thinking it will be some custom JS, but am open to any approaches :-)

# Answer
Ok, so this is our "solution". Not tidy, but we didn't want to edit the date module directly.

My module:

```
<?php
function modulename_form_alter(&$form, &$form_state, $form_id){
  if(substr($form_id,-9) !== "node_form" ){
    return;
  }
$jsPath = drupal_get_path('module', 'modulename');
  $jsOptions = array(
    'group' => JS_THEME,
    'weight' => 20
  );
  // Load this JS late, so that it happens after the main date module
  drupal_add_js("$jsPath/js/modulename_datepicker.js", $jsOptions);
}

```

My colleagues code for the modulename\_datepicker.js file:

```
jQuery(document).ready(function(){
    for (var id in Drupal.settings.datePopup) {
        if (Drupal.settings.datePopup[id].func == "datepicker") {
            var defVal = jQuery('#'+id).val();

            jQuery('#'+id).datepicker();
            jQuery('#'+id).datepicker( "option" , {
                changeMonth: Drupal.settings.datePopup[id].settings.changeMonth,
                changeYear: Drupal.settings.datePopup[id].settings.changeYear,
                firstDay: Drupal.settings.datePopup[id].settings.firstDay,
                defaultDate: Drupal.settings.datePopup[id].settings.defaultDate,
                dateFormat: Drupal.settings.datePopup[id].settings.dateFormat,
                minDate: 0,
                maxDate: "+1Y"
            });

            if (defVal == '') {
                jQuery('#'+id).datepicker( "setDate" , "+1Y");
            } else {
                jQuery('#'+id).datepicker( "setDate" , defVal);
            }
        }
    }

});

```

Better solutions welcomed :)
> 0 votes

---
Tags: 7, nodes, entities, javascript, datetime
---


# Question
Title: Code working normally in a fresh HTML file but not in a Drupal block
Just wondering if someone would be kind enough to help me with a problem i am having.

This is the code that i am currently using for my E-junkie View Cart button on my Drupal site:

```
<a href="https://www.e-junkie.com/ecom/gb.php?c=cart&cl=206570&ejc=2" target="ej_ejc"       class="ec_ejc_thkbx" onClick="javascript:return EJEJC_lc(this);"><center><img src="http://www.e-junkie.com/ej/ej_view_cart.gif" border="0" alt="View Cart"/></center></a>
<script language="javascript" type="text/javascript">
<!--
function EJEJC_lc(th) { return false; }
function EJEJC_config() {
EJEJC_POSTCALL=true;
}
function EJEJC_shown() {
jQuery("#imgHeader").attr("src", "http://www.eastwestcards.com/banner2.png");
}
// -->
</script>
<script src='http://www.e-junkie.com/ecom/box.js' type='text/javascript'></script>

```

When i use this code on a normal HTML page the pop up is very nice and clean. However, when i try to use this code in a block on drupal the pop-up still works but there is no banner and the tables for the shopping cart all messy and etc.

Another thing that I am wondering about is my twitter feed doesn't work.

I have tried enabling the PHP module and set the input filter to PHP code and the twitter feed now shows but i am unsure if this is an efficient way to fix the problem. When i did this for the code above the banner of my cart started showing but the tables and etc. were still messed up.

I've been reading some FAQs and some people are suggesting that I should make exceptions in my theme's CSS files so that it does not affect the pop-up cart on my site but I do not know how to do this.

Apologies for the chunks of text, thank you in advance for any help.

# Answer
> 2 votes
Inputing PHP or Javascript through the UI is almost always a bad idea, and can happen to be impossible in some cases, for security reasons.

I recommend another approach, for example creating a block in a custom module with the various block hooks.

This way, you won't bypass Drupal security and you'll have a much more versatile and robust solution.

---
Tags: blocks, theming
---


# Question
Title: How to alter query of block inside a panel
I have a View that contains many blocks. I want to customize the query for a specific block.
I have tried `views_query_alter()` hook and `$view->query->add_where`, but in this case the query will be modified for all blocks.

Any idea of how to customize the query using `add_where` for a specific block?

# Answer
> 2 votes
You can check `$view->current_display` in your `hook_views_query_alter` to alter the query differently for each different block.

---
Tags: views, panels
---


# Question
Title: Specifying the length of an integer in hook_schema
Why does Drupal not allow you to specify the integer length with type `int` in `hook_schema`?

# Answer
> 2 votes
Please see the Data Types documentation, I believe you can use `tiny, small, medium, big, normal`

---
Tags: installation, database
---


# Question
Title: Loading cck fields from nodes of a content type
I have created 4 nodes by a content type called insert\_item using CCK; now I am trying to load all CCK fields into a template of a new node where I would use the CCK field value of the insert\_item content type.

What I have written is the following code:

```
$nodes = array();
$result = db_query("SELECT nid FROM {node} WHERE type = 'insert_item'");
while ($row = db_fetch_object($result)) {
  $nodes[] = node_load($row->nid);
  print $nodes;
}

```

What I got is the following:

> ArrayArrayArrayArray

I really don't know what to do.

# Answer
> 1 votes
Try changing `print $nodes` to `print_r($nodes)` and also move it to the outside of your `while` loop.

Your code should look like this:

```
$nodes = array();
$result = db_query("SELECT nid FROM {node} WHERE type = 'insert_item'");
while ($row = db_fetch_object($result)) {
  $nodes[] = node_load($row->nid);
}
print_r($nodes);
//If you use Devel, uncomment this next line and comment out print_r above
//dpm($nodes);

```

This will give you an easy to read value.

Another option is to use the Devel module, and instead of using `print_r` you can use `dpm()` which uses Krumo to pretty print the contents of your array. There are some basic instructions for that `dpm()` here and here.

*Information on `print_r` here.*

> If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.

---
Tags: entities
---


# Question
Title: Create a custom form from Custom Content Type & Save it
I've created a custom *content-type* using GUI interface.

I need to customize the *form* which takes input while creating a content of the `content-type`. I can do this by `hook_theme` implementation *but* I'm trying to create a brand new form, and save the content's fields in database, so that it appears as a full-functional content of my `content-type`.

1. How do I create a form *(I know how to create forms in my custom module)* that contains the `fields` *(all, or selectively some)* of my custom *content-type*?
2. Most Importantly, when the form is submitted, how do I **save** the `fields` so that it appears as a brand new content-type?

*I think I've made it clear, please answer, or ask me to clarify the question more if necessary...*

# Answer
node\_form will give you a form for your content-type, just pass a node.object having your content-type (*$node-\>type*) and maybe something more .., plus the content-type needs to be registred already i guess

saving is handled automagically ...
> 1 votes

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


# Question
Title: Which variables do I need to export with Strongarm?
I have a theme based on adaptivetheme, which uses the color selector tool to allow one to edit the theme's color scheme through the UI.

When exporting a feature using the theme, the following variables are available:

* `color_themename_files`
* `color_themename_logo`
* `color_themename_palette` (gives the list of colors)
* `color_themename_stylesheets`

If exporting `color_themename_files`, an array of files like the following is exported:

```
array(
  0 => 'public://color/omtheme-58e01b40/bullet-round.png',
  1 => 'public://color/omtheme-58e01b40/bullet-sm-arrow-right.png',
  2 => 'public://color/omtheme-58e01b40/bullet-sm-arrow-down.png',
  3 => 'public://color/omtheme-58e01b40/button.gif',
  4 => 'public://color/omtheme-58e01b40/button-o.gif',
);

```

Similarly, `color_themename_logo` gives:

```
array('value' => 'public://color/themename-5cbf1601/logo.png');

```

I know I want to export `color_themename_palette` since that's the list of colors. Is there any reason to export the other three variables?

# Answer
> 1 votes
Searching the color module for `variable_get` reveals that `color_themename_stylesheets` is used in function \_color\_html\_alter(), which is called by themes that can use the color module. Moreover, the value of that variable is not recreated automatically, when \_color\_html\_alter() is called. This also holds for the other three variables.

So you have to export these variables if you want to have the theme properly colored out of the box. Of course you also have to make sure that the referenced files are in the correct place.

# Answer
> 1 votes
Yes if the paths match up exactly on the other setup. No if the paths don't.

Ideally you want to avoid putting platform specific options into features/code as they might not be the same across multiple environments.

---
Tags: 7, theming, features
---


# Question
Title: Customize Flag Ajax Message on Rules Trigger
Greetings fellow Drupalers,

We're using Rules to listen for a flag trigger. And we wanted to present a custom mesage set in rules to the user after he triggered this as well. Since we're using the AJAX toggle, no message would be presented, however since there's no page load.

What's the best course of action for the desired funcionality? Or even which direction would you follow?

Best regards.

# Answer
Rules don't support siuch feature. Change "Link type" to Normal link or Confirmation form, so you will got drupal messages from Rules.
> 1 votes

---
Tags: 7, ajax, rules, flags
---


# Question
Title: Views: how can I cleanly add a row of arbitrary text within a collection of fields?
I have a view that displays fields. I want to add a text-based explanation as one of the rows in the view. The display looks like this:

* Field A (Picture)
* Text 1: A row that contains explanatory text that appears regardless of whether there is any data below or not
* Field B (Data- may or may not be present)
* Field C (Data- may or may not be present)
* Field D (Data- may or may not be present)
* Field E (Data- may or may not be present)

What I'm currently doing to implement Text 1 is adding a field that will definitely always be available (user ID, etc.) and rewriting it to show the text I want to display. This does what I want but it feels like an ugly hack. Is there a better way to do this?

# Answer
> 1 votes
In Fields, select Global from the Group Dropdown and then you can select Custom Text and set it up pretty much anyway you'd like; at least in Drupal 6 and Views 3 anyway.

# Answer
> 0 votes
You should use a template file to theme the view. Here is a brief explanation.

---
Tags: views
---


# Question
Title: Can I find the term depth via $node without resorting to a taxonomy_get_tree or an SQL query?
I'm trying to find all terms in a vocabulary associated with the current node, that do not have any children.

The most obvious way might be to use taxonomy\_get\_tree() and match with the returned array to find the childless. Another way is to use a function like this one, and it involves a MySQL query. While my current taxonomy is small and the performance concerns are minimal, I would like to avoid this if this info is already available somewhere.

So, how can I find the depth of a taxonomy term, in a more performance friendly way?

# Answer
The data for taxonomy is in the database. If you want to get that data there is no way to do so without running a database query.

Any function that retrieves this data (including `taxonomy_get_tree()` and the function you link to above) has to run database queries to get at the data.

`taxonomy_get_tree()` is a bit heavy so I'd advise using the `term_depth` function you link to. If you want to increase performance slightly you can improve that function to offer a static page load cache. This will only make a difference if you call the function more than once in a single page load though:

```
function term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_result(db_query("SELECT parent FROM {term_hierarchy} WHERE tid = %d", $tid));
    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + term_depth($parent);
    }
  }

  return $depths[$tid];
}

```

Short of building your own cache mechanism that doesn't rely on the database (which would be a massive amount of overkill for this situation) I don't see any way of making this more performant.
> 5 votes

# Answer
Drupal 7 version of Clive's answer:

```
/**
 * Find the depth of a term
 */
function term_depth($tid) {
  static $depths = array();

  if (!isset($depths[$tid])) {
    $parent = db_select('taxonomy_term_hierarchy', 'th')
      ->fields('th', array('parent'))
      ->condition('tid', $tid)
      ->execute()->fetchField();

    if ($parent == 0) {
      $depths[$tid] = 1;
    }
    else {
      $depths[$tid] = 1 + term_depth($parent);
    }
  }

  return $depths[$tid];
}

```
> 4 votes

---
Tags: 6, taxonomy-terms
---


# Question
Title: How hidden the user_filter_form to a specific role?
How can I hidden with `alter_form` to hide the `user_filter_form` in the page of list of users to a specific role?

# Answer
`hook_form_alter()` wouldn't actually be the best place for this; the form is actually called in from `user_admin()` so the best place for your code would be `hook_page_alter()`.

The first thing you should do is create a custom permission that you can assign to the role:

```
function MYMODULE_permission() {
  return array(
    'access user filter form' =>  array(
      'title' => t('Access User Filter Form')
    ),
  );
}

```

Then implement `hook_page_alter()` to hide the form:

```
function MYMODULE_page_alter(&$page) {
  // Make sure this is the right page
  if (arg(0) == 'admin' && arg(1) == 'people') {
    // Make sure filter form actually exists
    if (isset($page['content']['system_main']['user_filter_form'])) {
      // Check user access
      if (!user_access('access user filter form')) {
        // Deny access to the form if necessary
        $page['content']['system_main']['user_filter_form']['#access'] = FALSE;
      }
    }
  }
}

```
> 0 votes

---
Tags: 7, users
---


# Question
Title: form error Fatal error: Cannot use string offset as an array
It's pretty stright forward, im trying to display the results of my form, Im having trouble finding something that explains how to display the results outside of the `drupal_set_message()` code, I think I am close with my current code.However I am getting this error Fatal error: Cannot use string offset as an array

```
/**
 * Block info
 */

function zillow_block_info(){
    $blocks['zillow_block'] = array(
        'info' => t('Zillow Block'),
    );
    return $blocks;
}

function zillow_block_view($delta = ''){
    $block = array();
        switch ($delta){
    case 'zillow_block';
        $block['subject'] = t('Zillow Block');
        $block['content'] = drupal_get_form('zillow_form');
    break;
    }
    return $block;
}

/**
 * Api info
*/

function zillow_api_info($form, &$zinfo){
    set_time_limit(3600);
    $state = $zinfo['values']['state'];
    $zillow_id = 'XXXXXXXXXXX';
    $xml = file_get_contents('http://www.zillow.com/webservice/GetRateSummary.htm?zws-id='.$zillow_id.'&state='.$state.'');
    $zinfo = simplexml_load_string($xml);

    foreach($zinfo->response as $rates){
        $zinfo .= $rates->today->rate[0];
        $zinfo .= $rates->today->rate[1];
        $zinfo .= $rates->today->rate[2];
        $zinfo .= $rates->lastWeek->rate[0];
        $zinfo .= $rates->lastWeek->rate[1];
        $zinfo .= $rates->lastWeek->rate[2];
    }

    return $zinfo;
}

/**
 * Form
 */

function zillow_form($form, &$zinfo){

    $form['description'] = array(
        '#type' => 'item',
        '#title' => t('Get your mortgage rates'),
    );
    $form['rates'] = array(
        '#type' => 'fieldset',
        '#title' => t('Mortgage Rates'),
        '#collapsiable' => TRUE,
        '#collapsed' => FALSE,
    );

    $form['rates']['state'] = array(
        '#type' => ('select'),
        '#title' => t('Choose One'),
        '#options' => array(
            'AK' => t('Alaska'),
            'AZ' => t('Arizona'),
        ),
        '#required' => TRUE
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    if(isset($zinfo['values'])){
        $form['page_output'] = array(
        'markup' => 'Submitted value:'. $zinfo['values']['state']);
    }
    return $form;
}

/**
 * Submission Output
*/

function zillow_form_submit($form, &$zinfo){
  drupal_set_message(t('this is the info the form has submitted. states=@states, todaysrates=@todaysrates', array('@states' => $zinfo['values']['state'], '@todaysrates' => zillow_api_info($form, $zinfo))));
  $zinfo['processed']['states'] =  serialize($zinfo['values']['state']);
  $zinfo['processed']['todaysrates'] =  serialize(zillow_api_info($form, $zinfo));
}

```

Edit\** My code has been modified I am now only getting this error

# Answer
The problem is here:

```
if(isset($zinfo['values'])){
    $form['page_output'] = array(
    'markup' => 'Submitted value:'. $zinfo['values']['state']);
}

```

Any element of a render-array that doesn't start with a `#` symbol is itself considered a child render-array by the `drupal_render()` function.

As `drupal_render()` expects an array when your array key is `markup` (without the `#`), it tries to treat the variable as an array. Since it's a string, PHP complains that it can't use the provided variable as an array...because it isn't one :)

This should work:

```
if(isset($zinfo['values'])){
    $form['page_output'] = array(
    '#markup' => 'Submitted value:'. $zinfo['values']['state']);
}

```

Have a look at Render Arrays in Drupal 7 and the FAPI `#markup` property for more information.

**EDIT**

There's a slightly bigger problem: in `zillow_api_info()` you're accepting the `$zinfo` parameter by reference, and then overwriting it with this call: `$zinfo = simplexml_load_string($xml);`.

That code overwrites the `$zinfo` variable in memory, so when you use it again in your submission function it will cause errors. It's also what's causing the last two lines not to work, and `$zinfo['values']` to not exist when your form is rebuilt.

The easiest solution is to change `zillow_api_info()` to look like this:

```
function zillow_api_info($form, &$form_state){
  set_time_limit(3600);
  $state = $form_state['values']['state'];
  $zillow_id = 'XXXXX';
  $xml = file_get_contents('http://www.zillow.com/webservice/GetRateSummary.htm?zws-id='.$zillow_id.'&state='.$state.'');
  $zinfo2 = simplexml_load_string($xml);

  foreach($zinfo2->response as $rates){
    $zinfo2 .= $rates->today->rate[0];
    $zinfo2 .= $rates->today->rate[1];
    $zinfo2 .= $rates->today->rate[2];
    $zinfo2 .= $rates->lastWeek->rate[0];
    $zinfo2 .= $rates->lastWeek->rate[1];
    $zinfo2 .= $rates->lastWeek->rate[2];
  }

  return $zinfo2;
}

```

As an extra note, you do need `$zinfo['rebuild'] = TRUE` in your submit function too.

I'd really advise using the `$form_state` variable name throughout your code when it refers to the form state array, it'll make problems like this vanish instantly :)
> 6 votes

---
Tags: 7, forms
---


# Question
Title: Keeping $attributes but adding a rel (D7)
I have the following piece of code:

```
l('<div class="magnifier gradient"></div>' . $image, $link_path, array('html' => TRUE, 'attributes' => $attributes))

```

Which creates a nice link, as it should be. Now I want to add a rel-attribute without getting rid off $attributes (because I need that one). I have Googled and tried a lot, but nothing seems to work. So if anyone can help me with just adding a rel-attribute without deleting the other attributes, I would be grateful!

Thanks

# Answer
> 2 votes
If I understand you right you just want to add the `rel` attribute to the `$attributes` array before you call `l()`. Something like this:

```
$attributes['rel'] = 'the_rel';
print l('<div class="magnifier gradient"></div>' . $image, $link_path, array('html' => TRUE, 'attributes' => $attributes));

```

That will add the an item to the `$attributes` array with a key of `rel` and a value of `the_rel`, and won't affect any of the other attributes already in the array.

---
Tags: theming, navigation
---


# Question
Title: Category tags like drupal.org (Drupal 7)
I am wondering how to create tags like they have on the main drupal site:

I assume drupal.org is designed using Drupal :)

Can anyone tell me if this is somehow built in to drupal? The only options I see for term reference fields are list, text fields (which only allow the user to input one tag) or hierarchical reference fields. Is there some module that allows for the use of these more sophisticated tags?

# Answer
There are a number of modules such as:

* Nice Tags, here is an excerpt about it from the module's project page:

> ... improves seamlessly the UX for taxonomy tags input fields.
>
> No 3rd party JS libraries are required, as it works out of the box with jQ version shipped with Drupal.
* Active Tags, here is an excerpt about it from the module's project page:

> ... adds a new option to free tagging taxonomies. If selected the taxonomy widget is replaced by a new jQuery enabled tag entry widget.
>
> Works with core Taxonomy module and Content Taxonomy module.
>
> This module came about through work on a site where some users found separating tags with commas confusing. Some users got it, and some didn't. This resulted in a site littered with concatenated tags. Wordpress has a similar tag entry mechanism where tags are entered separately. It has been implemented here using jQuery to rewrite the standard taxonomy entry form.

You can also use your taxonomies as tags as well if that's something you are interested in.
> 2 votes

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


title: watchdog table grows too big too fast

text:
# Question
Title: watchdog table grows too big too fast
On a rather busy D6 site, I need to truncate watchdog table very frequently, since it grows at about few Gigabyes per day. On the other hand I can not disable access logs to avoid the table's inflation. Running cron yeilds a lot of errors and does not seem to clean watchdog table. So what is the best way to deal with this problem?

Thanks

# Answer
> 7 votes
Without knowing what kinds of errors you are seeing, it is hard to say what to do. If this is a live site, then I suggest that you edit your `settings.php` to turn off PHP error reporting. IIRC, this will do it for you

```
error_reporting(0);
ini_set('display_errors', FALSE);
ini_set('display_startup_errors', FALSE);

```

or you could also edit your `php.ini` and do the same thing, or use the equivalent `.htaccess` directives. You may get by with just turning off `E_NOTICE`.

If you are seeing favicon.ico errors in the in the log, then I suggest putting in a rewrite to point to the favicon in your theme, or at least on in one of the standard themes.

Another possible watchdog clogger are the internal connection messages. You can try adding

```
# make sure internal dummy connections don't make it into drupal
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]

```

to `.htaccess` if you are seeing them.

All of this said, if you are seeing several gigs of errors or warnings in your watchdog, then you have a **serious** problem with your site. Clone the site to a development version, and figure out what is really going on: fix the actual problem (ie, stop the errors) instead of curing a symptom (ie, hiding the error messages).

---
Tags: database, log-messages
---


# Question
Title: How do I redirect a taxonomy menu item to another path?
I have a taxonomy menu, and I want to redirect the page request from taxonomy/term/% to a custom path using a page callback function. How can I use a function to cause the redirect?

# Answer
> 4 votes
If I understand you want to implement `hook_menu_alter()` and override the `page callback` for that path:

```
function MYMODULE_menu_alter(&$items) {
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'MYMODULE_taxonomy_page_callback';
}

function MYMODULE_taxonomy_page_callback($term) {
  // Either redirect the page
  drupal_goto('somewhere');

  // Or build up some output to replace the original taxonomy term page.
  // This way you won't actually have to do a redirect at all
}

```

If I can offer a bit of advice, keep this callback function in your module file so it's always included. Otherwise you'll need to change the `file` property of the menu item too and that can get quite messy as Drupal is expecting the file to exist in the path that the defining module is in (in this case the taxonomy module).

# Answer
> 1 votes
I know you specifically asked about using a page callback function, but the more general question (emphasized in the question title) is simply to redirect a taxonomy term to a custom path/page. For that, the **Page Manager module** (part of CTools) is a great tool. It may help many people who want to accomplish the generic case, but don't know how or simply don't want to use a page callback function. There's also a great set of videos about Page Manager on Drupalize.me. At the time of this writing, those videos are free, not sure if that will change at some point.

---
Tags: taxonomy-terms, routes
---


# Question
Title: form_set_error: How to set for an array Drupal 6
```
Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [nid] => 164
                    [module] => uc_product
                    [remove] => Remove
                    [title] => Strokes1
                    [data] => a:4:{s:10:"attributes";a:0:{}s:9:"shippable";s:1:"0";s:12:"restrict_qty";s:1:"0";s:6:"module";s:10:"uc_product";}
                    [qty] => 2
                    [description] =>
                    [cart_item_id] => 200
                )

            [1] => Array
                (
                    [nid] => 165
                    [module] => uc_product
                    [remove] => Remove
                    [title] => Strokes2
                    [data] => a:4:{s:10:"attributes";a:0:{}s:9:"shippable";s:1:"0";s:12:"restrict_qty";s:1:"0";s:6:"module";s:10:"uc_product";}
                    [qty] => 1
                    [description] =>
                    [cart_item_id] => 203
                )

            [2] => Array
                (
                    [nid] => 166
                    [module] => uc_product
                    [remove] => Remove
                    [title] => Strokes3
                    [data] => a:4:{s:10:"attributes";a:0:{}s:9:"shippable";s:1:"0";s:12:"restrict_qty";s:1:"0";s:6:"module";s:10:"uc_product";}
                    [qty] => 1
                    [description] =>
                    [cart_item_id] => 204
                )

        )

    [update] => Update cart
    [checkout] => Checkout
    [form_build_id] => form-5c5819d5418df14f08153f1ce15d6acc
    [form_token] => 2341b9068b8ffb7454d267b22e572d7d
    [form_id] => uc_cart_view_form
)

```

I'm using form\_set\_error to display the error messages if there is no product.

My Issue is:

For example, I am having 3 products in the checkout page.

When I clicks submit I need to validate that all the products are available.

Here, let us consider if the second product is not available I am showing the error message "Product Stroke 2 is not available".

**But all the check boxes in the cart is highlighted**

Because I had set form\_set\_error to items element.

**How can I set form\_set\_error for *every individual element*.**

What I have given to display error message:

form\_set\_error('items', 'Not available');

Kindly guide me how to resolve the issue. I am using ubercart module with drupal 6.

# Answer
> 3 votes
There is a comment on the API page for `form_set_error` which explains how to set a form error on a subelement of a form item.

From the comment:

```
form_set_error('field_name][i][value', t('Your message'));

```

---
Tags: ubercart
---


# Question
Title: Create a new revisions only at the time of specific state transition
I am using Revisioning and Workflow module along with Drupal 6 to create new states of the node and revisions.Currently if I select 'New revision in draft, pending moderation (requires "Create new revision")' under workflow settings it will create a new revision only when a node is published.But I want it other way.I want to create a new revision only at aspecific state change of my choice.

For e.g. The node is in 'Finally Submitted' state and it is transitioned to 'Moderation' state. At this transition I want to a new revision to be created otherwise not.

How is that achievable?

# Answer
I would look into using Rules, You can have something like the below:

```
Event: Workflow state has changed
If: Workflow state is x (choose your state)
DO: Create a new pending revision of the node

```
> 0 votes

---
Tags: workflows, nodes
---


# Question
Title: Why are all of the non-value columns indexed, but the value column isn't?
I'm working on improving performance for a Drupal 7 website and noticed that all of the non-value columns (entity\_type, bundle, delete, etc) are indexed, but the actual value field isn't...does this make sense to anyone?

I know Drupal uses the other fields to join against other tables, but any views/custom queries that are searching for nodes with specific field values are going to suffer are they not?

Is there some reason why the value column isn't indexed by default? Will it cause problems if an index is added?

---

The specific field I'm looking to index is a date field if that provides any more insight into the situation

# Answer
> 5 votes
I'm not an expert in this but I think it's probably due to the fact MySQL enforces a maximum key length for indexes. For InnoDB this is 3500 bytes (further limited to 3072 bytes by MySQL itself), and for MYISAM it's 1000 bytes.

Whether or not the value columns are indexed is actually done on a per field-type basis. For example, the long text field type (for fields like the node body) has no index on the `fieldname_value` column, but it *does* have an index on the `fieldname_format` column.

The `fieldname_format` column is a `varchar` limited to 255 characters, and so would not produce an index key that is too long. Conversely the `fieldname_value` column is a `longtext` type, which has the potential to create a key that would be too long. (You *can* specify a prefix length to get around this but I don't think Drupal supports it).

As another example, if you then look at a table for an `image` (or `file`) field type you'll notice there is an index on the `fieldname_fid` column. Because this field is an integer type it naturally lends itself to be indexed, without having to worry about the maximum index key length.

I think it basically comes down to the type of data the field is storing. `entity_type`/`bundle`/etc. are all integer columns and so can be easily indexed by whatever storage engine you're using, while `text` types (or `varchar` types with a large enough length) will create an index key that's too large for the storage engine to handle.

Hope that helps a bit

# Answer
> 0 votes
Just to complete Clive's answer above, nothing can prevent you from adding indexes wherever you want, and it sure could improve performance, but be aware that it can be counter-productive.

Indexes can be used automatically by MySQL, even in cases you wouldn't expect, so you have to be careful and use some `EXPLAIN` queries to ensure your indexes get used at the moment you want and at no other time.

Long story short : it is a case by case problem, which explians why the devs didn't try to guess what performance gains one would be looking after.

---
Tags: 7, database
---


# Question
Title: How to get node.tpl.php to display different content for different nodes?
I currently display some database content through PHP code written directly in the body of several nodes.

I would like to shift this code into node.tpl.php (as I have seen from the Zen examples that code to modify a node should be in node.tpl.php). However, I have multiple nodes, each displaying different kinds of database content.

How should I structure the code in node.tpl.php so that if it is Page A, then I display database content A and if it is Page B, then display database content B?

As an example.

Currently I have the following in one of my node body:

```
<?php
  $db = mysql_connect('localhost', 'root', '');
  mysql_select_db('sage', $db);
  $query = "show tables";
  $db_query = mysql_query($query, $db);
  echo "<TABLE border = '1'>";
  echo "<TR>";
  echo "<TH>TABLE NAME</TH>";
  echo "</TR>";
  while($row = mysql_fetch_array($db_query)) {
      $tableName = $row[0];
      echo "<TR>";
      echo "<TD><a href=/node/5/$tableName>$tableName</a></TD>";
      echo "</TR>";
  }
  echo "</TABLE>";
?>

```

Do I copy and paste this code directly into node.tpl.php?

# Answer
> 1 votes
This code DOESN'T belong in the template files. You should implement a module for your business logic, database connection and the like.

Template files should be reserved for theming, or very basic alternatives.

Your case is 'by the book' where it is important to separate logic from presentation, otherwise, as you already understood, you'll end up with duplicate code everywhere, poor performance and an unmaintainable site.

# Answer
> 2 votes
I don't See any node id in your code. If all you want is to have PHP generated output for an URL, define the path with hook\_ menu() and just return the generated HTML from the call back method.

---
Tags: 7, nodes
---


# Question
Title: Altering database tables belonging to core modules
Using D6's date\_api.module module, I noticed that the .install uses db\_add\_field() to add a "timezone\_name" column to the {users} table, and hook\_schema\_alter() to declare that change.

I was surprised to see a module alter a core module's table, and would have instead expected date\_api to create a {date\_user\_timezone\_names} table with "uid" and "timezone\_name" fields (and subsequently a hook\_user($op='load') to add a timezone\_name property to the user object).

The advantages of simply adding a column to another module's table are obvious to me. I'm interested in hearing what the disadvantages are. Are there any gotchas that one should be aware of?

# Answer
> 3 votes
Yes, I'm not sure altering core tables is a good idea.

I don't see any problem with it, as long as you just add fields.

But I remember having seen some code here and there that cycles through all the fields in a table, so even this might cause problems.

It's a bit personal and question of belief, but as far as I can, I try to make my code as something that can work with core's code and structure. I've seen too many devs going in implementation hell with decisions like that.

Also, having to alter what's already been designed by big teams and/or big guys like core devs is very often due to a bad analysis of the use case.

My general advice for anybody who's lower than core dev level (including me, of course) would be : don't do it.

---
Tags: 6, hooks, database
---


# Question
Title: Sending HTML email replies using Webform in Drupal 7
How can I get Webform to send an HTML-formatted email?

# Answer
> 2 votes
You should download Mimemail to do this.

Then, in the webform options, you can create your template with the field you want using `%value[machine_field_name]` to get just the value or `%email[machine_field_name]` to get the label and value.

---
Tags: webforms
---


# Question
Title: change action link on views exposed form
I have created a views exposed form. How can I change the action link, or the "Submit" button.

I use Drupal 7.

# Answer
> 1 votes
You can alter the value of the submit button inside the view:
Advanced -\> Exposed From -\> Exposed form style -\> Settings -\> Submit button text.
From http://drupal.org/node/109604:
The documentation for Views 2 and Views 3 for Drupal 6 and Drupal 7 is contained within Views module!
Install the Advanced Help module to access it.

# Answer
> 0 votes
It's a normal form, so you can change what you want with hook\_form\_alter. Beware though : if you change the structure (vs presentation) of the form, you'll probably run into problems.

---
Tags: 7, views
---


title: Set number of users

text:
# Question
Title: Set number of users
I'm creating a site which give a set number of logins to each company who wants to use it. For example, we give 20 logins to Company A. What I want is when a user tries to create an account from the given company , if all the allowed slots are taken up they can't create an account. At present I have a content type for Client, which has the client details and then a field for the number of 'licences' available. Then when a user creates a new account they choose which client they are with. The site is built in Drupal 7

Is there a module out that which can already do this?

Thanks

Kieran

# Answer
> 0 votes
If you create the main company as a user (ie Company A has an "*admin*" user account) then you could use User Relationships and User Relationship Limits. I suppose you could possibly use Rules to create a new users whenever a company is created and tie the user to that content with either the Relation or Entity Reference module.

**User Relationships**

> Admins create relationship types (friend, coworker, etc). Relationship types can be setup to be one-way or mutual. If a relationship type is one-way (subscriber) only the requester is shown as relating to the requestee. Relationship types can also be set as needing or not needing approval.

**User Relationship Limits**

> User Relationship Limits extends User Relationships and provides the ability for site administrators to limit the number of possible relationships.

---
Tags: 7, users
---


# Question
Title: why does drupal_get_path() not work in my code?
somehow drupal\_get\_path is not working I'm my module in my function `vacancies_manage_test_pager()`

drupal\_get\_path() returns notting ( empty string or NULL or something ) when I `DSM(drupal_get_path('module','vacancies_manage'));` I get an empty message

module code:

```
/**
 * Implements hook_permission
 */
function vacancies_manage_permission() {
    return array(
        'manage own vacancies' => array(
            'titel' => t('Manage own vacancies'),
            'description' => t('Allows users use the own vacancies page'),
        ),
    );
}

/**
 * Implements hook_menu
 */
function vacancies_manage_menu(){
  $items = array();

    // Test items
    $items['vacancies_manage'] = array(
      'title' => 'Vacatures beheren',
      'description' => 'Eigen vacatures beheren.',
      'type' => MENU_NORMAL_ITEM,
      'page callback' => 'vacancies_manage_test_pager',
      'access arguments' => array('manage own vacancies'),
    );

    // needed for jQuery / ajax callback
    $items['vacancies_manage/callback'] = array(
      'title' => 'vacatures beheer Callback',
      'type' => MENU_CALLBACK,
      'page callback' => '_vacancies_manage_test_pager_callback',
      'access arguments' => array('manage own vacancies'),
    );

    return $items;
}

function vacancies_manage_test_pager() {
    drupal_add_js(drupal_get_path('module', 'vacanies_manage') . '/jquery.url.js' );
    drupal_add_js(drupal_get_path('module', 'vacanies_manage') . '/vacanies_manage.js' );
    drupal_add_js('initializeTable();', 'inline');

    return ('<div id="table-container"></div>');
}

function _vacancies_manage_test_pager_callback() {

    global $user;

    header("Content-type: text/html");
    header("Expires: Wed, 29 Jan 1975 04:15:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");

    // build header for HTML table

    $header = array (
        array('data' => t('Titel')),
        array('data' => t('Aangemaakt op')),
        array('data' => t('Gepubliceerd')),
        //array('data' => t('Dupliceer')),
    );

    // query db for user nodes
    $query = db_select('node','n');
    $query->fields('n', array('nid','title','created','status'));

    if($user->uid !== "1" ) {
        $query->condition('n.uid', $user->uid);
    }

    $results = $query->execute();
    dsm($results);

    // display nodes
    $rows = array();

    foreach($results as $vacancy) {
        $rows[] = array(
            'data' => array(
                $vacancy->title,
                $vacancy->created,
                ($vacancy->status == 1?t('Ja'):t('Nee')),
                //dupliceer
            ),
        );
    }

    //Theme the html table
    $html = theme('table',
        array(
            'header' => $header,
            'rows' => $rows,
            'sticky' => TRUE, // Optional to indicate whether the table headers should be sticky
            'empty' => 'U heeft geen vacatures.', // Optional when no results
        )
    );

    $html .= theme('pager',
        array(
            'tags' => array(),
        )
    );

    die($html);
}

```

# Answer
You've spelled vacanies\_manage wrong.... (same with your js file, too \[and titel in your permissions\])
> 5 votes

---
Tags: uri
---


# Question
Title: Where to add my merchant gateway using ubercart?
I am trying to figure out how to add the gateway of my merchant so I can accept credit card payment.

I have given a URL by my merchant and I can redirect to this URL easily using my own PHP code, but I can't find a way to integrate it using Ubercart.

Example gateway is https://test.mymerchantgateway.com/ECN/eng/payment/payForm.jsp.

So that when my customer checkout it will be redirected to the url above and when the payment is successful it will return to my website using the "successUrl" like:

```
<input type="hidden" name="successUrl" value="http://mydomain.com/success.php">

```

I am using Drupal 6, if that makes any difference.

# Answer
> 1 votes
There are lots of modules that actually does this. You will need to do some custom coding and integrating with Ubercart. It's been a while since I did this and it also depends on your Ubercart/Drupal version. But you can checkout the quickpay module for drupal 6 integration example.

The typical way of doing these kinds of things, is to create a form and auto post it with javascript to the payment gateway url with all the params needed. It's up to you to send the correct params along and up to the gateway to redirect back. But answering those questions won't be drupal or ubercart related.

---
Tags: ubercart
---


title: Inline Content-type

text:
# Question
Title: Inline Content-type
Is it possible with Drupal to create/edit other nodes of different content-types, when editing a node of one content type?

Example:

* Content-type Survey; has fields title, body and an x amount of questions.
* Content-type Question; has title and body

Rather than creating the question nodes separately and linking them with an Entity Reference when editing Survey (lots of back and forths, and can get quite cumbersome when a lot of surveys/questions). I would like to add the questions underneath the Survey form when creating/editing a Survey node.

I've used this before with other frameworks such as Django (called Inline), example: https://docs.djangoproject.com/en/dev/intro/tutorial02/#adding-related-objects and would be amazing and a great feature for UI/UX if Drupal could do this as well.

# Answer
> 0 votes
I have have found that field collection does the job I need. Not perfect, but very decent.

# Answer
> 0 votes
I'm working on this in a sandbox right now: http://drupal.org/sandbox/rszrama/1181848 Supports only products right now. I plan to implement the final UI (the add form below the table, better styling) this week, then promote it to the "Inline Entity Form" namespace.

---
Tags: 7, nodes
---


# Question
Title: How can I use node_load() with a module created page that requires an argument?
I would like to load the contents of a page like how node\_load() works, although what I am trying to load isn't a node but a page created using a module. The entry in hook\_menu uses an argument which needs to be passed in the URL. This is for a popup (jquery overlay) that I want to reuse where the code is already done for the standalone version.

Any idea how this can be done?

# Answer
The code executed from Drupal, in index.php, contains the following code.

```
$return = menu_execute_active_handler();

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

```

menu\_execute\_active\_handler() accepts an argument: the path being shown. If that argument is not passed to the function, then menu\_get\_item(), the function called by `menu_execute_active_handler()` uses the content of `$_GET['q']`.
In your case, you would pass to the path you are interested to. Your function should use code similar to the following one:

```
function mymodule_get_page($path = NULL) {
  $return = menu_execute_active_handler($path);

  // Menu status constants are integers; page content is a string.
  if (is_int($return)) {
    return $return;
  }

  if (isset($return)) {
    return theme('page', $return);
  }

  return −1;
}

```

The calling function would need to check the returned value: If it is a string, then it the what returned from `theme('page')`; if it −1, then the menu callback didn't return any value (but could have printed the page content; if it is an integer different than −1, then it's a Drupal error code, i.e. the one reporting the site is off-line, the user is trying to access a page without to have any permission, or the user is trying to access a non existing page.

The only "problem" with this code is that sometimes a menu callback doesn't return any content, but it prints the content directly; this is normally done for content that doesn't need to appear together the rest of the page output Drupal normally adds (e.g. the content for the blocks associated to a page), such as when a module returns XML content that should not mixed up with the HTML output generated from Drupal.
In this case, the function should intercept the output directly printed, with ob\_start() and ob\_get\_flush().

```
function mymodule_get_page($path = NULL) {
  ob_start();
  $return = menu_execute_active_handler($path);
  $output = ob_get_flush();

  // Menu status constants are integers; page content is a string.
  if (is_int($return)) {
    return $return;
  }

  if (isset($return)) {
    return theme('page', $return);
  }

  return $output;
}

```
> 1 votes

# Answer
This is probably a bad way of doing this and certain things will not work (such as inline javascript). I haven't been able to find 'the proper way' of doing this so what I did was create a page with PHP input and passed the view function for the page I wanted to `echo()`. I could then use `node_load()` and `node_view()` to grab the content for display. I wouldn't recommend this method but it's the only one I've found to solve the problem so far. More suggestions welcomed!
> 1 votes

---
Tags: 6
---


# Question
Title: Field Collection, with Entity Reference, can get value
I've got a field collection, which contains

1. A copy field
2. A user field, via entity reference

Now when I try to access the copy field by storing the collection in `$collection`, via

```
$collection->field_my_collection_copy->value();

```

I get what im looking for, but trying similar on the entity referenced field

```
$collection->field_my_collection_user->value();

```

It breaks. By looking into the variables for `$collection->field_my_collection_user` I should have 'uid' available on it, but `$collection->field_my_collection_user->uid` gives me nothing and `$collection->field_my_collection_user->uid->value();` gives me `Unable to get the data property uid as the parent data structure is not set`

# Answer
> 0 votes
Hah, I should've given the anonymous user the privilege to view the data.

---
Tags: entities
---


# Question
Title: Create a custom front page for anonymous users
I'm trying to create a custom front page for anonymous users, something like page--front-anonymous.tpl.php.

I could use the page--front.tpl.php template file, and check the role there, but I believe it is possible to create a separate template file for the front page when it is visited from anonymous users.

Any advise?

# Answer
in your THEME\_preprocess\_page(&$vars) hook you can put something along the lines of...

```
if ($vars['is_front'] && !$vars['logged_in']) {
   $vars['template_files'][]='page-front-anonymous'; // drupal 6
   $vars['theme_hook_suggestions'][]='page_front_anonymous'; // drupal 7
}

```

which should work using the is\_front and logged\_in variables set by the various modules before you get to it. if you are using a module, and don't want to rely on weight/execution order, you could do it with:

```
global $user;
if (drupal_is_front_page() && !$user->uid ) {
.....

```
> 3 votes

# Answer
I'm not sure how complicated your page is, but if all of you content is in blocks, you can adjust block visibility using the block access module on a per-role basis. I did that on a project - I ended up with one template file, but different pages based on whether or not someone was logged in.
> 1 votes

---
Tags: theming
---


# Question
Title: In the People list, change from time span display to date display
This is Drupal 7: when I am logged in as administrator and I click "People" to check the registered users, the default Drupal display is the "Member for", which displays a time span. For example: "2 min 10 sec" or "23 hours 24 min" or even "6 days 22 hours". How can I change that display to a "Member since" display that would show the date and time the user actually registered? Thanks!

# Answer
> 2 votes
I'm not aware of an existing module that will do this but the following function in a custom module will do the trick:

```
function MYMODULE_form_user_admin_account_alter(&$form, &$form_state) {
  // Get the user IDs listed in the form
  $uids = array_keys($form['accounts']['#options']);

  // Since loading the user objects will incur overhead it would be best to get the
  // created data directly from the users table. It's a shame because this query has
  // already been run in user_admin_account(), but it's not saved anywhere that we can
  // easily pick it up.
  $sql = 'SELECT uid, created FROM {users} WHERE uid IN (:uids)';
  $created_data = db_query($sql, array(':uids' => $uids))->fetchAllKeyed();

  // Loop through the results and change the column data for the "Member for" column.
  foreach ($created_data as $uid => $created) {
    $form['accounts']['#options'][$uid]['member_for'] = date('d/m/Y H:i', $created);
  }

  // Finally change the header to say "Member Since"
  $form['accounts']['#header']['member_for']['data'] = t('Member Since');
}

```

The only thing you might want to change is the date format...see PHP's `date()` function for all the available tokens

---
Tags: users, entities
---


# Question
Title: What is the accepted way to display certain content on different pages
I have a couple different pages. Each page has a main content area and a sidebar. Each sidebar contains a paragraph unique to that page. It is necessary that the paragraph in the sidebar and the main content are different content types.

I handled this by using references module. I created a content type "category page" and a content type "page spotlight". The page spotlight has a "node reference" field that references a category page. I then created a view that enforces that relationship. This allows me to map the spotlight to the pages.

I am wondering is using taxononmy a better approach? I come from a very structured programming background where there are "right" ways of doing things, and I am just looking for the "drupal way" of approaching this problem.

# Answer
That is definitely one way to do it. I don't think there is a "Drupal way" to accomplish this per se, but you can also accomplish this through taxonomy and panels. It really just depends on if having an extra Content Type bothers you or not.

I think the way you currently have it is the most efficient way. To me you should only use taxonomy if it fits the mold of Drupal's definition of taxonomy.

> > Taxonomy, a powerful core module, gives your sites use of the organizational keywords known in other systems as categories, tags, or metadata. In Drupal, these terms are gathered within "vocabularies." The Taxonomy module allows you to create, manage and apply those vocabularies.
> 1 votes

---
Tags: 7, views, nodes
---


title: Help Needed Regarding View Module

text:
# Question
Title: Help Needed Regarding View Module
Hi I am a newbie and want to Get Functionality from view module in the form of grid in which i want to show some fields and a main title after clicking on title user will be directed to full post. Can anyone help me how to get this functionality. In other word i want to change the order of displaying data to end user created by the view module.

# Answer
If you have already created a view which shows nodes you want to display, in the view settings select Format \> Grid, and Show \> Fields in the Format area; select the fields you want to display in the Fields area.

If you want other than default sorting options use modules such as the following ones:

* the Weight module (It allows you to assign weight to nodes and then sort them by that weight.)
* the Menu Node Views module (If you have added your nodes to some menus, then this module allows to sort nodes in the view by that order.)

### Note

The Menu Node Views module starts producing duplicate results, if the content of the node is translated to other languages (translated using the Entity translation module).
> 2 votes

---
Tags: views
---


# Question
Title: Allowing a user to choose which image style they want for a single uploaded image
I have a views list showing a set of property's displaying address, image, description and price in a horizontal manner, each line is a new listing for a property.

the user simply uploads an image and clicks save. however I have recently been asked to allow for the user to again upload a single image, only this time select an image style that contains an an overlay or watermark image on top of the uploaded image.

I have managed to create the image styles with a watermark effect for each overlay image they requested such as "Available now", "Under Offer" ect. But I have absolutely no idea how I provide a choice for the user to select one of these image styles.

so to clarify the user would like to upload an image and then select a pre made image style under that uploaded image to apply a watermark over the top. I am having trouble providing a choice for the user to select. everything else has been achieved.

I hope this makes sense I have tried to be as detailed as i can and hope there is a solution to this. Thank you for everyone's time.

# Answer
> 2 votes
You can add an additional field to your content type that stores the values of the image style presets on your site. This will allow them to select which image style they want once they've uploaded an image.

You'll need to write a small custom module to pull the existing image style presets from the database and programatically populate the allowed values of the in your new select field.

You can create a custom node or views template and use the value of the image style field to display the uploaded image with the selected image style.

---
Tags: nodes, media
---


# Question
Title: Drupal commerce - what page/function should i call after an off site payment
I'm creating a module to integrate '*xpay - carta sì*' payments inside Drupal commerce. I don't have any documentation on xpay apart for the module developed for ubercart. Anyway i managed to code the part where the payment method is added and i succesfully dealt with going from my site to the bank page sending the correct data. I'm stuck with where to go after the payment is completed. When i send the data to the bank i set some url to call according to the outcome of the transaction

```
'RESULT_URL' => $site_url.'/cart/xpay/complete',
'NOTIFICATION_URL' => $site_url.'/cart/xpay/server',
'ERROR_URL' => $site_url.'/cart/xpay/error',
'ANNULMENT_URL' => $site_url.'/cart/xpay/error',

```

I've defined those menu\_callbacks, but i'm not sure that Drupal Commerce works like this, maybe i should do something totally different like returning to `$site_url.'/checkout/%order_id/payment'`

Has anybody of you tackled something similar?

# Answer
> 3 votes
i used those two

```
// Return to the previous page when payment is canceled
'cancel_return' => url('checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),

// Return to the payment redirect page for processing successful payments
'return' => url('checkout/' . $order->order_id . '/payment/return/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),

```

but also have an IPN. (your NOTIFICATION\_URL)

don't forget to create a commerce transaction with the feedback from the carrier !

maybe have a look at another module, like postfinance (by me), or paypal (by Ryan - the commerce god ;))

---
Tags: 7, commerce
---


# Question
Title: Where does Drupal 7 store custom user account fields?
I imported 8500+ external users from an external user table using Feeds module successfully. Now, I am trying to add some more attributes to these users (ie. age, gender, ...). I proceeded to create several new fields for my users under admin/configuration/account settings/manage fields (ie. Age, Gender, ...). However, these fields are now all empty and it would not be possible for me to manually edit these fields for all users.

Could someone please tell me where D7 stores these new fields in the database (which table)? I would like to use a SQL script to automatically update the users with these fields.

PS. Is using a SQL script to update these information the correct approach?

# Answer
> 5 votes
Assuming you're using the SQL storage backend they're stored in the `field_data_field_FIELDNAME` and `field_revision_field_FIELDNAME` tables. The field system in Drupal 7 is generic across all entities so field data for nodes/users/all entity types is stored in the same tables.

Rather than input directly into those tables, though, I'd suggest using the Drupal API to load, alter and then save each user instead. The code might look something like this:

```
// Grab all the uids in the users table
$uids = db_query('SELECT uid FROM {users}')->fetchCol();

// Load the users
$users = user_load_multiple($uids);

// Loop through and edit each user
foreach ($users as $user) {
  // Load the extra data from whatever source you're using
  $extra_data = my_function_to_get_extra_data_by_user_id($user->uid);

  // Update the fields
  $user->field_FIELDNAME1[$user->language][0]['value'] = $extr_data['FIELDNAME1'];
  $user->field_FIELDNAME2[$user->language][0]['value'] = $extr_data['FIELDNAME2'];
  // etc...

  // Save the user object
  user_save($user);
}

```

You'll probably want to change this code to process the users in batches as it's likely to take a long time to run.

# Answer
> 0 votes
The Migrate module is very helpful with these kind of tasks. User fields have to be created first.

> The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

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


# Question
Title: contextual and downward filterable tagcloud
I am not sure how I would properly and clearly explain this question. What I am looking for in general is a tagcloud that is sensitive to context. So it will only list the tags that are relevant to the content that you are looking.

Let's say you have a repository of links all of which can be tagged freely. On the highest level (the entry archive page) you will have a tagcloud that shows all the tags that exists. Once you will click on one of those tags, it will list all the links that are tagged with that specific keyword. However, the tagcloud will now not show ALL tags, but just an aggregation of all tags within the context of the tag on which you have already filtered. Quite an abstract explanation. Let me try to give an example. Let's say you have 5 links, which are tagged comma separated:

```
Link1: tag1, tag3
Link2: tag1
Link3: tag2, tag5
Link4: tag3, tag5
Link5: tag4, tag5

```

So, on the highest level, you will have a tagcloud that shows all tags: tag1, tag2 ... tag5. Let's say you click on tag3. On the archive page of tag3, you will only see tags that are relevant to that tag, in this case: tag1, tag3, tag5 (see Link1 and Link4, both are tagged with tag3, but have tag4 and 5 additionally)

I hope I could make it a bit clear. Any clues on how to accomplish this with Drupal?

# Answer
> 0 votes
What I think you are saying you want to do is this:

1. Grab all content that is tagged with a certain term, then
2. List in a block all taxonomy terms from that content

And if so, it's pretty straightforward to loop through a list of node and aggregate and each taxonomy term that is attached to each node, and then stylize a block of those terms, eg,

```
$nids= // execution results of a view or other sql that filters on a term;

$found=array();
foreach ($nids as $nid) {
   $node=node_load($nid);
   foreach ($node->taxonomy as $t) {
      found[$t->tid]=$t->name;
   }
}

```

which will (if my off the top of the cuff php code is accurate ;-) produce an array $found that is a list of terms that can be styled however you wanted in a variable or block, most simply like:

```
 foreach ($found as $tid => $name) {
    $content.=l($name,'taxonomy/term/' . $tid) . ' ';
 }
 return $content;

```

You can probably do all of this in a View itself with some funky templating, too, if you didn't want to create a module and/or theme preprocess function.

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


title: Can I make search field with Views?

text:
# Question
Title: Can I make search field with Views?
I would simply like to create a search bar (a text field) that when filled out will return a list of a certain content type on a new page.

Right now with Views I have created a search bar (text field) as an exposed filter but it also shows all the content with it. What I want is to have the search bar but have the results content show in a new window when the search bar is submitted.

Can this be accomplished with Views?

# Answer
> 1 votes
At advanced, the column at the right, in the view config you can set the filters to apear as a block. You could place this at any random page and when submitting you will be send to the viewpage desiplaying the results from the filter.

# Answer
> 0 votes
You can use contextual filters and tell the view to display nothing if the filter from the URL was empty.

---
Tags: views, search
---


# Question
Title: Drupal 301 redirects for matching paths without .htaccess
I am using a Drupal site on top of nginx, and would like to be able to redirect a set of pages from an old style url, to a new one, using 301s. The content has already been migrated over to the new urls, but there may be links elsewhere with the old style. How can I achieve 301 redirects for matching paths, to redirect using part of the information from the old url to inject into the new one (namely \[timestamp\]).

From:

```
example.org/article/[timestamp]

```

To:

```
example.org/article/doi/static-[timestamp]

```

I know how I would do this with .htaccess, but is there a way to do this in Drupal itself, or a module to achieve this?

Having looked at the docs, I think that

```
drupal_goto($path = '', array $options = array(), $http_response_code = 301)

```

May be the best way to go, with a corresponding (pseudocode):

```
if path == oldpath,
    drupal_goto(etc.)

```

# Answer
In this case, I looked at @Arosboro's suggestion about using Global Redirect. This was a bit more than I actually required, as all I needed was a simple redirect for a particular page. What I did instead was implement a quick module which handled the redirect based on a regex match for the old URL.

```
function redirect_init() {
    if (isset($_GET['destination'])) {
        $destination = $_GET['destination'];
        unset($_GET['destination']);
    }

    $request_path = redirect_request_path();

    // If the request_path() matches an article, redirect to the new URL
    // for articles.
    if ($request_path) {
        drupal_goto($request_path, array(), 301);
    }
}

function redirect_request_path() {
    $path = ltrim(request_path(), '/');

    if (preg_match('/^article\/\d+$/', $path)) {
    $path_list = explode('/', $path);
    $timestamp = $path_list[1];
        return 'article/doi/10.7244/cmj-' . $timestamp;
    } else {
        return;
    }
}

```
> 1 votes

# Answer
Probably the Global Redirect module suits your needs.

You may have to implement the timestamp feature as a new token with a custom module.
> 1 votes

---
Tags: uri, redirection, path-aliases
---


# Question
Title: How can I create a Feature and have it saved under 'features manage' tab?
I see that I can create a Feature, but the only option is to download it. Is there a way I can just have Drupal import it to the manage tab of Features?

# Answer
> 2 votes
You can use the "Direct save" feature of the Features Tools module if you want to do this from the UI instead of the command line with Drush.

# Answer
> 1 votes
Once you copy the downloaded Feature to your /sites/all/modules folder it will show up under Manage Features in the UI. If you're using Drush, then when you run `features-export` it will export the code to your /sites/all/modules folder, bypassing the download step. However, I've found that creating the Feature in the UI is easier than creating it from scratch with Drush. So I'd recommend just sticking with the UI and copying the downloaded code. Once it's been created, the `features-update` Drush command is the easiest way to update the Feature with any changes you've made to it's components.

---
Tags: features
---


# Question
Title: How do you embed an external URL (to a software application) in Drupal with 508 compliance?
We need to embed a software application (by URL) into a Drupal 7 site. The resulting page needs to be Section 508 compliant. I have been told that iFrames are not Section 508 compliant. That is what we used in the past. Is there an alternative that is accessible?

# Answer
I am not claiming to be a 508 or a WCAG expert, but I am working through some of these issues with a client right now (though, not for a Drupal site, but it is why I have all of these links handy).

In the current version of the Section 508 standard, section 1194.22 describes the standards for "Web-based intranet and internet information and applications.". iframes are not explicitly mentioned, though frames are

> (i) Frames shall be titled with text that facilitates frame identification and navigation.

This is explained in the accompanying guide with some examples. You can extrapolate this to an `<iframe>` and use the title attribute.

The current draft doesn't really mention details like this, but everything web related essentially says that you need to meet WCAG 2.0 Level A and AA (it is more complicated that that if you dive into the draft).

If you pour through all of this, the sufficient technique is to add a title onto the iframe. There is also an advisory technique to provide alternate content.

Based on the comments in @Clive's answer, I would say the @mlangfeld's situation is more of a grey area, as the iframe contains something *functional* and not just *non-text content*.

This shows where automated testing isn't sufficient to meet all guidelines (and many of the Level A and AA ones need to be manually verified anyway); it is possible to pass these automated tests and still have a horribly inaccessible website.

Getting this back on track for Drupal, in an ideal world, I would make a custom module that would interface with the remote application via webservice, and use this instead of the iframe. The module would have forms defined to replicate the application, and the submit handlers would call out to the webservice, and then build results. If you can't do a true webservice, then I would investigate a custom module that serves as a proxy between Drupal forms and POSTing to the application's forms.

This way you can ensure that your forms are accessible, and that you eliminate the complications of the iframe. If this can't be done, then I would get an actual current screen reader and test what happens, and work through options with the client (either internal or external).
> 1 votes

# Answer
I can't find a single reference on Google that says iFrames aren't section 508 compliant...however they *will* fail compliance if you do not:

> Provide alternative content for IFRAME elements

iFrames can contain nested alternative content, like so:

```
<iframe src="frame.html">
  <p>Description of the loaded content</p>
</iframe>

```

The rationale listed for this is:

> Some browsers do not support the IFRAME element, or do not have the ability to load multiple documents together. It is therefore necessary to provide alternative content for this element even if the IFRAME only loads HTML.

This information came from here, but all of the other links I found on Google said exactly the same thing in one way or another.
> 1 votes

---
Tags: nodes
---