title: Multiple Values to Trigger #states

text:
# Question
Title: Multiple Values to Trigger #states
How can I have multiple values trigger the Form API's #states?

Say for example, I wanted this field to be visible not only if the value is 5 (currently works below), but wanted to make the field visible if the the values are 3, 4 or 5.

```
'#states' => array(
    'visible' => array(
       ':input[name="field_star_rating"]' => array('value' => t('5')),
    ),
),

```

As a note, I tried the following and it **does not work**. It only works if the value is '4'

```
'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array('value' => t('5')),
        ':input[name="field_star_rating"]' => array('value' => t('4')),
    ),
),

```

This also **does not work**, it too only works if the value is '4':

```
'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array('value' => t('5'), 'value' => t('4')),
    ),
),

```

# Answer
> 60 votes
Here's what you need:

```
'#states' => array(
    'visible' => array(
        ':input[name="field_star_rating"]' => array(
            array('value' => t('5')),
            array('value' => t('4'))
        ),
    ),
),

```

# Answer
> 3 votes
Only way I could figure is to use #ajax in D7.

Here are a few helpful tip's I wish I would have known before starting.

1. #ajax in the form API is awesome and worth learning
2. #states does not support OR or XOR (Without a patch? http://drupal.org/node/735528 )
3. dpm($form); and var\_dump($form\_state) on a custom submit function are priceless

Here is a modified version of one of the AJAX examples from the examples module.

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

    $form['star_rating'] = array(
        '#type' => 'select',
        '#title' => t('Star Rating'),
        '#options' => array('_none' => '- select -', 5 => '5 Star', 4 => '4 Star', 3 => '3 Star', 2 => '2 Star', 1 => '1 Star'),
        '#ajax' => array(
            'callback' => 'plugin_autotextfields_callback',
            'wrapper' => 'textfields',
            'effect' => 'fade',
        ),
    );

    $form['textfields'] = array(
        '#title' => t("Fieldset Name"),
        '#prefix' => '<div id="textfields">',
        '#suffix' => '</div>',
        '#type' => 'fieldset',
        '#description' => t('Where the field will be placed'),
    );

    if (!empty($form_state['values']['star_rating']) && $form_state['values']['star_rating'] == 5) {
        $form['textfields']['review'] = array(
            '#type' => 'textfield',
            '#title' => t('Message if 5 stars'),
        );
    } else if (!empty($form_state['values']['star_rating'])) {
        $form['textfields']['review'] = array(
            '#type' => 'textfield',
            '#title' => t('Message if not 5 stars'),
        );
    }

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Click Me'),
    );

    return $form;
}

function omfg_autotextfields_callback($form, $form_state) {
    return $form['textfields'];
}

```

I hope this helps someone that runs into the same problem :)

# Answer
> 3 votes
```
 $form['student_type'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

// High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'textfield',
    '#title' => t('What standardized tests did you take?'),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type[high_school]"]' => array('checked' => TRUE),
        ':input[name="student_type[undergraduate]"]' => array('checked' => TRUE),
        ':input[name="student_type[graduate]"]' => array('checked' => FALSE),
      ),
    ),
  );

```

P.S. See the examples module for more features "form\_example/form\_example\_states.inc"

---
Tags: 7, forms, javascript
---


title: adding group by in views sql query

text:
# Question
Title: adding group by in views sql query
I have view of teasers which one has united filed.

Is there a way to add "group by" by this field (join field table and group by the field) into sql query of view?

# Answer
In Views 3, under "advanced settings", there is a setting for enabling aggregation, which will give you group by options.

Most likely they are hidden by default as the UI is complicated enough as is.

You can also check out chapters 28-30 in the NodeOne Taming the beast learn views with nodeone which are all about aggregation.
> 2 votes

# Answer
Letharion's answer already explains the essential stuff. Nevertheless I'd like to clarify things a bit more to make it easier to find this Q&A. I lost like one or two hours for this, because they changed the name of this property.

In SQL the function is called `GROUP BY` (see here in the MySQL manual). A typical use case is after a JOIN in order to get the min/max/average value of certain rows or to count certain rows after a JOIN.

To allow to create such queries with Drupal's views module in Drupal 6 there was the module views\_groupby.

In Drupal 7 this is working out of the box. **But this option is not called group by or grouping anymore, it is called *enable aggregation*!**

Some links to discussions in the past:
> 2 votes

---
Tags: 7, views
---


# Question
Title: Contextual links don't display in a floated custom region
I created two custom regions in my Drupal 7 theme and used CSS to float them side-by-side (to create columns). That worked fine, and I'm able to place blocks in the regions, but the contextual links don't display.

I tested them without the float, and the contextual links are right where they should be, leading me to believe that it's the float positioning that's causing the problem.

This isn't too big a deal, since I can go to Structure --\> Blocks to administer them, but the contextual links are handy, and besides, it's bugging me and I want to figure it out. Any suggestions?

# Answer
> 2 votes
Try to add an "overflow:hidden;" to the wrapper of both the content and the contextual links to force it to fill the dimensions of its children. Either that or add a clear as a sibling of the elements. What's probably happening is the wrapper is being rendered to 0 height.

# Answer
> 0 votes
Right click, shift click, double finger tap, or do whatever you need to bring up INSPECT ELEMENT in your browser and look around your page until you find the contextual links and then look at what CSS is no longer working with them with float. They are most probably still there, just hidden from plain view.

---
Tags: theming, views
---


title: Menu sort by year field

text:
# Question
Title: Menu sort by year field
I'm created a content type and have got field\_year. I want, sort my contents by field\_year on my sidebar. How can I do this?

# Answer
I see you have added views tag , so, I think, you don't mind to list your content with Views.
If your field `field_year` is integer it is really easy to sort your content:

Some notes:

1. If you need block, just create Block display in Views. New block will be available on `admin/structure/block` page.
2. Add fields you want. Here I'm showing only title as a link to the original piece of content.
3. Remove all sorts and add your own by clicking on the *Add* button. It's very easy to find your field by it's name or machine name.

Result:

Yes, `active` class is added automatically. Views module has tons of settings. To learn more please take a look at “Taming the Beast: Learn Views with NodeOne” series.
> 0 votes

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


# Question
Title: i18n language switcher don't show on default lang
I'm using Drupal 7 and Clean theme. And my site have 3 languages. Using i18n module for this features. Everything is working...

Language Switcher block is active, showing on 2 languages. But, when click my site default language, don't show this block.

How can i solve this?

# Answer
> 0 votes
There is an option under language switcher block configuration.You have to select all the language checkbox to display language switcher block in all languages.

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


title: Add close button in ctools model dialog

text:
# Question
Title: Add close button in ctools model dialog
I am using ctools modal dialog/popup window to display some records. The default close button is working fine. How can I add a custom close button?

Thanks

# Answer
As for this issue commited on November '11, you should be able to close any CTools modal window with a link that has the class "ctools-close-modal"

For example, in my modal I've got this for element to cancel and close:

```
  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), '#',
       array(
         'attributes' => array(
           'class' => 'ctools-close-modal'
          ),
         'external' => TRUE
       )
     )
  );

```
> 6 votes

# Answer
Just add CSS class `ctools-close-modal` to any element inside the dialog like this:

```
$form['close_link']['#markup'] = '<span class="ctools-close-modal"> × </span>
<a href="#" class="ctools-close-modal">or click here.</span>';

```
> 3 votes

---
Tags: entities, chaos-tool-suite
---


# Question
Title: Theming own field: how do I control the outer markup?
I'm working on a custom field and formatter and right now I'm at the theming stage. My formatter should render a list of items as a run-in list of badges, much like the tags here on Drupal answers. Currently I am getting a top-to-bottom list, as the fields get the Drupal's default wrappers:

```
<div class="field-items">
  <div class="field-item even">...</div>
  <div class="field-item odd">...</div>
</div>

```

I thought it would be more appropriate if I had a control over the wrappers markup and delivered something like:

```
<div class="my-field-wrapper">
  <span>Value 1</span><span>Value 2</span><span>etc.</span>
</div>

```

I have already managed to control the `span` markup via a custom tpl, but I'm unsure how I am supposed to theme the field's outer markup to suppress the default wrappers. Of course I know I could override `div` styling by setting `display: inline-block`, but I treat this as my first theming excercise hoping to learn.

# Answer
The way to correctly theme what you are asking is shown here: theme\_field()

In particular:

> This is the default theme implementation to display the value of a field. Theme developers who are comfortable with overriding theme functions may do so in order to customize this markup. This function can be overridden with varying levels of specificity. For example, for a field named 'body' displayed on the 'article' content type, any of the following functions will override this default implementation. The first of these functions that exists is used:
>
> ```
> THEMENAME_field__body__article()
> THEMENAME_field__article()
> THEMENAME_field__body()
> THEMENAME_field()
>
> ```
>
> Theme developers who prefer to customize templates instead of overriding functions may copy the "field.tpl.php" from the "modules/field/theme" folder of the Drupal installation to somewhere within the theme's folder and customize it, just like customizing other Drupal templates such as page.tpl.php or node.tpl.php. However, it takes longer for the server to process templates than to call a function, so for websites with many fields displayed on a page, this can result in a noticeable slowdown of the website. For these websites, developers are discouraged from placing a field.tpl.php file into the theme's folder, but may customize templates for specific fields. For example, for a field named 'body' displayed on the 'article' content type, any of the following templates will override this default implementation. The first of these templates that exists is used:
>
> ```
> field--body--article.tpl.php
> field--article.tpl.php
> field--body.tpl.php
> field.tpl.php
>
> ```
>
> So, if the body field on the article content type needs customization, a field--body--article.tpl.php file can be added within the theme's folder. Because it's a template, it will result in slightly more time needed to display that field, but it will not impact other fields, and therefore, is unlikely to cause a noticeable change in website performance. A very rough guideline is that if a page is being displayed with more than 100 fields and they are all themed with a template instead of a function, it can add up to 5% to the time it takes to display that page. This is a guideline only and the exact performance impact depends on the server configuration and the details of the website.

Finding the right naming convention is somewhat a mess, so I suggest you to try the Theme developer module in order to find out all the possible names for your template file.

Here is the naming convention guide. Given your comment my best guess would then be: field--field-chemical-hazards.tpl.php
> 2 votes

# Answer
Copy the 'field.tpl.php' file located at modules \> field \> theme

Paste this file to your theme 'templates' folder

This will override the default field template but if you want to be more specific, look at the commments within the file for examples

```
field-name-[field_name].tpl.php
field-type-[field_type].tpl.php

```

Edit the markup in the code, taking consideration of the conditional statements

You will need to clear the caches when adding a template file
> 1 votes

---
Tags: theming
---


# Question
Title: Fatal error when calling drupal_goto from hook_boot
When I am trying to call drupal\_goto from hook\_boot I get an error:

> Fatal error: Call to undefined function drupal\_goto()

What am I doing wrong and why is that happening?

My code:

```
function custom_mobile_redirect_boot() {
  include_once 'Mobile_Detect.php';
  $detect = new Mobile_Detect();
  if ($detect->isMobile() || $detect->isTablet()) {
    drupal_goto('http://testsite.local');
  }
}

```

# Answer
In `hook_boot()` lot of APIs will not work as the required function definitions for them will not be loaded. In this case `common.inc` where `drupal_goto()` is defined is not yet included ergo you get that error. If its not possible to use hook\_init() make use of Header. Check out mobile\_tools module hook\_boot() for more info.
> 8 votes

---
Tags: 7, hooks, redirection
---


title: Workflow / Views: Specific state date

text:
# Question
Title: Workflow / Views: Specific state date
I need a column (field) in a view where you can see the date of a specific state (Workflow state).

For example: A content type news has three workflow states: new, reviewed, published. Now I need a view where you can see each news (also ones that haven't entered that state!) with a field where the date is shown when it was new, reviewed and published (sortable). The Workflow module only provides "Previous time", but that's not specific to a state.

Any ideas?

I know how to program a views handler for custom table/fields but my problem is that the node -\> workflow\_node\_history has an 1:n relation.

drupal 6, workflow 1.5, views 2.x

```
Example:

Title   | Date new     | Date Reviewed | published
---------------------------------------------------
Title1  | 01.03.2012   | 13.03.2012    | pending
Title2  | 02.05.2012   | 16.05.2012    | 20.05.2012
Title3  | 20.05.2012   | pending       | pending

```

# Answer
The Views PHP Module provides a custome field that is click sort enabled

Value code example:

```
....
$result = db_fetch_object(db_query("SELECT stamp FROM {workflow_node_history} WHERE nid = %d AND sid = %d", $row->nid, $sid));
if(isset($result->stamp)) {
   return $result->stamp;
}
return 0;

```

Output code:

```
<?php
print date('d.m.Y', $value);
?>

```

Enable click sort: sort numerically
> 1 votes

# Answer
Add to the Filter criteria: *Where current state = reviewed*

Add the current field: *Workflow: current time*

That should return you the time of the state change to reviewed, for all nodes who are currently on the state "reviewed". If you want to show the nodes that haven't entered the state "reviewed", then just show all the nodes, and their current workflow state timestamp.

Disclaimer: I answered this on D7 so I don't know if that field and filter are available in D6.
> 0 votes

---
Tags: views, 6, workflows
---


# Question
Title: Re-write the output of taxonomy_term_page() without hacking core
In Drupal 7, taxonomy.pages.inc contains the `taxonomy_term_page()`, which places a `<div class="term-listing-heading">` around the taxonomy heading output.

How can I re-write the output of taxonomy\_term\_page() in my theme, so I can remove the DIV without hacking core?

I'm quite surprised that there isn't a tpl.php file available for `taxonomy_term_page()` as this would making theming much easier.

# Answer
You can do it with preprocess page something like this:

```
function themename_preprocess_page(&$vars) {
  if  (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    unset($vars['page']['content']['system_main']['term_heading']['#prefix']);
    unset($vars['page']['content']['system_main']['term_heading']['#suffix']);
  }
}

```

in your theme's `template.php`

I believe `system_main` could be called something else, depending on your site setup.
> 11 votes

# Answer
As it is a menu callback, you can implement hook\_menu\_alter() in a module to alter the menu callback invoked for that page.

```
function mymodule_menu_alter(&$items) {
  if (!empty($items['taxonomy/term/%taxonomy_term'])) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] = 'mymodule_term_page';
  }
}

function mymodule_term_page($term) {
  // Build breadcrumb based on the hierarchy of the term.
  $current = (object) array(
    'tid' => $term->tid,
  );
  $breadcrumb = array();

  while ($parents = taxonomy_get_parents($current->tid)) {
    $current = array_shift($parents);
    $breadcrumb[] = l($current->name, 'taxonomy/term/' . $current->tid);
  }
  $breadcrumb[] = l(t('Home'), NULL);
  $breadcrumb = array_reverse($breadcrumb);
  drupal_set_breadcrumb($breadcrumb);
  drupal_add_feed('taxonomy/term/' . $term->tid . '/feed', 'RSS - ' . $term->name);

  $build = array();

  $build['term_heading'] = array(
    'term' => taxonomy_term_view($term, 'full'),
  );

  if ($nids = taxonomy_select_nodes($term->tid, TRUE, variable_get('default_nodes_main', 10))) {
    $nodes = node_load_multiple($nids);
    $build += node_view_multiple($nodes);
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
  }
  else {
    $build['no_content'] = array(
      '#prefix' => '<p>',
      '#markup' => t('There is currently no content classified with this term.'),
      '#suffix' => '</p>',
    );
  }
  return $build;
}

```
> 6 votes

# Answer
Like the previous example, except it may be cleaner and more future proof to modify the returns from taxonomy\_term\_page in a wrapper rather than copy the original function wholesale:

```
function mymodule_menu_alter(&$items) {
  if (!empty($items['taxonomy/term/%taxonomy_term'])) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] = '_custom_taxonomy_term_page';
  }
}

function _custom_taxonomy_term_page ( $term ) {

   $build = taxonomy_term_page( $term );

   // Make customizations then return
   unset( $build['term_heading']['#prefix'] );
   unset( $build['term_heading']['#suffix'] );

   return $build;
}

```
> 3 votes

---
Tags: taxonomy-terms, theming
---


# Question
Title: How do I get name and label of fields in user profiles?
I want to get the list of fields added to user profiles(listed here admin/config/people/accounts/fields). I need machine name and label of each field. How do I get them?

# Answer
> 7 votes
You can use the `field_info_instances()` function to get that data:

```
$fields = field_info_instances('user', 'user');

foreach ($fields as $field) {
  $machine_name = $field['field_name'];
  $label = $field['label'];
}

```

---
Tags: 7, entities
---


# Question
Title: Adaptively Displaying Images Inline Drupal 7
For Drupal 7.14 I've been trying to display images inline adaptively to a content type. In my content type I have a long text and summary field and an image field. I'm using the Adaptive Image Styles (ais) module. I upload the image and then insert the image using the insert module. I'm using full HTML without any text editor. But when I insert the code it does not display adaptively.

# Answer
I was finally able to get AIS working for adapting with inline images and shadow box. It can be done through Wysiwyg (see here for instructions: http://drupal.org/node/1555376) or I just insert this code in the image tag: class="adaptive media-image attr\_*typeof*\_foaf:Image img\_*fid*\_1172 img\__view\_mode\__media\_adaptive attr\_*format*\_media\_adaptive" typeof="foaf:Image". From what I can tell none of the other adaptive modules can do this. I checked it in Adaptive Image and it does not do inline images. An example of this working can be seen at: `http://173.236.7.153/~ssanalyt/drupal/consulting-areas/business`
> 1 votes

---
Tags: media, theming
---


# Question
Title: Why is the content of the <head> tag no longer loading in Google Chrome?
For some strange reason, the content of the `<head>` tag no longer loads in Google Chrome Inspector. The CSS files are still loaded.

Does anyone have a fix for this?

# Answer
> 0 votes
Problem seems to be kpr. When this function is used head content load but will not show in the chrome inspector tool.

# Answer
> 0 votes
That is for sure *not* a Drupal problem. I'd check the page source to see the head contents; if they appear there, maybe there is an unclosed tag.

---
Tags: theming
---


# Question
Title: Programmatic Content on a Node - preferably a non-code solution
Trying to generate content ONLY when certain user roles are selected (and these roles would stack up, so lets say user 1 had roles A and B, they would have content for both roles A and B - logical AND), but only on certain pages.

How would I go about creating this?

Basically I want the logic to flow as such:

```
display content[default];

if userrole == A {
display content[A];
}
if userrole == B {
display content[B];
}

```

I'd prefer not to write any code, because A) I want it easily modifiable for the client and B) Well, it isn't my site!

Plus, code issues tend to be messier than module issues in my experience.

I've heard Panels or Ctools might be able to do this, but I'm unfamiliar as to how.

# Answer
Yes, Panels can do this.

Basic steps are:

* Install/enable panels and dependent modules.
* Make a new panel page
* Add your content pieces to the page
* For the per role pieces, click the options (the gear), and add a new visibility rule. User: role should be in the list. Configure accordingly.

Once you start the process, the terms I am using will make sense.
> 0 votes

# Answer
I think you can achieve this using the Context module. Here is a quote about it (from the module's project page):

> ... allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
>
> Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.
> 1 votes

---
Tags: 6, nodes
---


# Question
Title: Logic on Node Add Page for Specific Content Type
I created a new content type in Drupal 7 and I want to make a template to customize the node add page for that content type. I want to be able to check if the user is authenticated with Facebook before they can use the node add form. If user is not authenticated then I will show them a paragraph explaining that they need to authenticate via facebook before they can use this form. I want them to always see the form link but they can only use the form if they are authenticated to facebook. I just don't know where to put it. Is it possible to make a template file specifically for that node add page so that I can include my logic?

# Answer
Hiding options such as publishing and URL aliases is accomplished through the use of user *roles* and *permissions*. Visit `/admin/people/permissions` on your site to see what I mean. Enable the help module for more (contextual) assistance.

If you want to perform additional modification beyond basic access control, then, seeing as to how you are attempting to customise a form, you would need to implement a Drupal *hook* named hook\_form\_alter(). You will need to do this in a custom module - if you haven't done this before, it's a lot easier than it sounds :)

There should be plenty of information and guides on SE, d.o as well as Google on how to use this hook to modify forms. But the one reference that you definitely need to be aware of is the Form API reference.

Since you want links to the node-add form to be visible, rather than controlling access to the page based on the FB-authentication status, you can check the status during the form\_alter and either add a message and *disable* the form, or as is usually done, set an error message or notice (using `drupal_set_message()`) and redirect them to a page where they can log in via FB; the message/notice will be displayed at the destination.
> 0 votes

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


# Question
Title: overloading the destination url of privatemsg
I have a privatemsg message form, and I need to alter the success URL that loads when a message is sent. What is the easiest way to go about doing this? The code i'm using is more or less based on the example code used here:

```
 module_load_include('pages.inc','privatemsg');dru
 print drupal_render(drupal_get_form('privatemsg_new'));

```

# Answer
Using the Devel module implement hook\_form\_alter and find your forms `$form_id`. Then supply a #redirect FAPI attribute like, `$form['#redirect'] = 'my-custom-thankyou-page';` and be sure to make your custom page as a drupal Page, module callback, View etc.
> 0 votes

---
Tags: privatemsg
---


# Question
Title: How to expose non Drupal tables in Views?
I wonder what is the best way to allow the Views module to access external tables not in Drupal?

I tried the Data module, but it doesn't allow for a datetime datatype.

# Answer
> 3 votes
The data module is a good start.

You can skip the data module and create your own views type with hook\_views\_data()
Angie has an example here.

Date times can be tricky, if you post another question with your specific problem with date times there may be a solution.

You don't specify if the DB is the same. You would need to define a second database in your settings.php if you need to connect to a different DB.

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


title: 404 to sites/default/files/css/,

text:
# Question
Title: 404 to sites/default/files/css/,
I have a site that has a 404 being reported as "sites/default/files/css/," - yes, a css file with the name comma ","

I have no idea what is causing this 404. The watchdog shows the referring URL can be almost any page on the site but going there and viewing the page source does not turn anything up. It is intermittant and not created on every page request.

Has anyone seen this before? Anyone know what causes it?

I am using Drupal 7.14

Kind regards,

John

# Answer
Assuming everything is using proper Drupal methods for attaching stylesheets (.info, `drupal_add_css`, `$foo["#attached"]["css"]`, etc), I think it is impossible for core to create a bad link to a file. Still, it would be worth it to search the code for "drupal\_add\_css" and "#attached" to see if there are any problems.

I think there are two possibilities here.

One could be a JS library dynamically attaching a stylesheet to the page. Unless you are doing this yourself, I don't think this is a likely culprit. Most of the libraries that do this (eg, jQUery UI) are rather well tested and I doubt would do this. Stranger things have happened, though.

The other possibility is a bad `url()` reference in your CSS for a font or background image. Search though all of your CSS for "url" and see if you have any problems. Validating the CSS couldn't hurt, either.
> 4 votes

---
Tags: theming
---


title: Get term from tid in views

text:
# Question
Title: Get term from tid in views
I have a view which overrides the default taxonomy page. The view has a contextual filter which look for the tid in the URL.

My goal is to get the taxonomy term to display as the title of the page.

I tried setting the view's title to "Department: \[field\_dept\]" (the field which references the taxonomy term and is loaded in the view). This work great, \[field\_dept\] is replaced with the taxonomy term as expected.

There is an exception though. When the view has no results, there is no \[field\_dept\] to look up and my page title looks like this "Department: \[field\_dept\]" :-/

Now I'm trying to figure out how to get the taxonomy term from the tid, which is in the URL and available in my view.

Is there a function available in views that will return the term from a tid? Something like get\_term\_from\_tid(%1), so I can use it in the title of the view or via title override in the contextual filter?

Drupal 7.14

Views 7.x-3.3

# Answer
Do you use "Content: Has taxonomy term ID" field as contextual filter?

If yes then edit this filter, in "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" section check "Override title" and in appeared textfeild input "Department: %1"

"%1" will be replaced by the name of current term. If no term is specified "%1" will be replaced by "all".

If you want change word "all" then in section "WHEN THE FILTER VALUE IS NOT IN THE URL" click on "Exceptions", check "Override title" and specify your value.
> 1 votes

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


# Question
Title: How can i change the form default value but not via hook_form_alter
I have a question about add a node which have a specific field!

I create two buttons on different page called A,B.

When User touched the A button,i redirect the user to the node\_form page.

The specific field default value will be set as ValueA.

When the user touched the B buttons,the value of the specific field will become ValueB.

So i cant user hook\_node\_form\_alter.

I want to write the code at the myform\_submit() because of touching the button.

How can i do that?

Are there any method which can change the form value not via the form\_alter()?

Please Help Me fix this problem! Thank you!

# Answer
Let assume you want to create a page. Then create button A which redirect user to /node/add/page?button=a and button B redirect to /node/add/page?button=b

Then in your module create hook\_form\_alter for node form

```
function MODULE_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'page') {
    if ($_GET['button'] == 'a') {
      $form['FIELD_NAME']['und'][0]['#default_value'] = 'aaa';
    }
    elseif ($_GET['button'] == 'b') {
      $form['FIELD_NAME']['und'][0]['#default_value'] = 'bbb';
    }
    else {
      $form['FIELD_NAME']['und'][0]['#default_value'] = 'ccc';
    }
  }
}

```
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: how to access drupal site using domain containing host ip address as prefix
My drupal site works in local domain dev.example.com (which is configured as a virtual host).

For some reason, now I need to access the site using exactly the following address:

```
http://192.168.3.149/dev.example.com

```

where 192.168.3.149 is the IP address of the local host where the site resides.

When this address is entered, I am redirected to `http://192.168.3.149/install.php`. Looks like Drupal treats this as a new domain.

How to tell Drupal to treat these two domains identically, i.e. treat `http://192.168.3.149/dev.example.com` as an alias of `http://dev.example.com` ?

# Answer
> 0 votes
It sounds like your site's settings might be in a multisite folder like `/sites/dev.example.com/`. When you aren't visiting via the hostname it will fall back to the settings in `/sites/default/`—check that those values are correct.

---
Tags: 7, users
---


title: How to redirect based on views results?

text:
# Question
Title: How to redirect based on views results?
I have a view that shows a list of nodes and has a contextual filter. If the number of nodes shown is only 1 then I want to redirect to that node page instead of showing the view. Can I do that in views or do I have to code it?

# Answer
> 6 votes
I don't think Views does anything like that by default, but a quick...

```
if (count($view->result)==1) {
  drupal_goto('node/' . $view->result[0]->nid);
}

```

...at the beginning of a display output template for the view in question should do it for you.

Or better yet, per @MPD...

```
function MOTOMODULE_views_pre_render(&$view) {

  if ($view->name=='JUSTONEPLEASE' && count($view->result)==1) {
    drupal_goto('node/' . $view->result[0]->nid);
  }

  // any other pre_render()ing here

}

```

---
Tags: 7, views, redirection
---


# Question
Title: How to find the view/page/module that's generating a SQL statement
I have newrelic performance monitoring with my Pantheon hosting account. It shows "slow SQL" reports but I can't tell which page, view or module is generating a SQL statement.

For example:

> SELECT node.nid AS nid, node.title AS node\_title, users\_node.name AS users\_node\_name, users\_node.uid AS users\_node\_uid, node.created AS node\_created, '?' AS field\_data\_field\_photo\_node\_entity\_type FROM node node INNER JOIN users users\_node ON node.uid = users\_node.uid LEFT JOIN field\_data\_field\_photo\_topic field\_data\_field\_photo\_topic ON node.nid = field\_data\_field\_photo\_topic.entity\_id AND field\_data\_field\_photo\_topic.field\_photo\_topic\_tid = :views\_join\_condition\_? WHERE (( (node.status = :db\_condition\_placeholder\_?) AND (users\_node.uid = :users\_uid? ) )AND(( (node.type IN (:db\_condition\_placeholder\_?)) AND (field\_data\_field\_photo\_topic.field\_photo\_topic\_tid IS NULL ) ))) ORDER BY node\_created DESC LIMIT ? OFFSET ?

How could I get that info?

# Answer
> 3 votes
If the query is executed from the Views module (as it seems in your case), then you can look for the view that executes that query.

Go on admin/structure/views/settings, and select "Show the SQL query"; if that doesn't help there is also the " Show other queries run during render during live preview" option.

For example, this is the output I got for the tracker view.

On admin/structure/views/settings/advanced, there is also the "Add Views signature to all SQL queries" which has the following description:

> All Views-generated queries will include the name of the views and display 'view-name:display-name' as a string at the end of the SELECT clause. This makes identifying Views queries in database server logs simpler, but should only be used when troubleshooting.

In the previous example, the query becomes the following one. (Notice the `'tracker:default' AS view_name` part.)

```
SELECT node.type AS node_type, node.title AS node_title, node.nid AS nid, node.language AS node_language, users_node.name AS users_node_name, users_node.uid AS users_node_uid, node_comment_statistics.comment_count AS node_comment_statistics_comment_count, node_comment_statistics.last_comment_timestamp AS node_comment_statistics_last_comment_timestamp, history.timestamp AS history_timestamp, node.created AS node_created, node.changed AS node_changed, 'tracker:default' AS view_name
FROM
{node} node
LEFT JOIN {users} users_node ON node.uid = users_node.uid
INNER JOIN {node_comment_statistics} node_comment_statistics ON node.nid = node_comment_statistics.nid
LEFT JOIN {history} history ON node.nid = history.nid AND history.uid = '1'
WHERE (( (node.status = '1') ))
ORDER BY node_comment_statistics_last_comment_timestamp DESC
LIMIT 25 OFFSET 0

```

# Answer
> 4 votes
I suspect your logs are are the output from the MySQL Slow Query Log. What ends up here varies based on server configuration, but they general culprits are

1. Queries that take a long time
2. Queries that don't use indexes

My suggestion is to try to match up the timestamps (start time) to the Apache access\_log to get a page. Then, use the Devel module and enable "Display query log" from admin/config/development/devel. This will record queries and log them along with execution times.

It looks like that bad query is tied to a view. For these, enable "Add Views signature to all SQL queries" on the Advanced settings page. When you do this you can identify which view is slow.

To resolve the "slowness", copy the query and hand edit to add in the parameters. Then open a MySQL tool, and use the `EXPLAIN` statement. Look at what it tells you and go from there.

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


# Question
Title: how to render a field "view mode" inside a field collection item template file?
to render a field "view mode" (or "format") inside a node.tpl.php i use, for example:

```
<?php
     print render(field_view_field('node', $node, 'field_myfieldname', array(
        'label'=>'hidden',
        'type' => 'text_summary_or_trimmed',
        'settings'=>array('trim_length' => 30),
    )));
?>

```

now i'd like to do quite the same thing, but inside a field-collection-item.tpl.php (for a field that is part of a field collection).

in my field-collection-item.tpl.php, i can render each field just like in a node;tpl.php:

```
<?php print render($content['field_myfieldname']); ?>

```

but if i try the first code above inside field-collection-item.tpl.php (to trim a field-collection field), it just doesn't work...

thanks you for helping !

# Answer
I haven't tested this but I suspect your issue arises from the fact that the $node object is not available to that template file. You have a couple of options; write your own theme function, load the node object some other way (this might still not work though because of the way field collection works) or just trim the rendered value.

Something like this should work for you if you are just looking to trim the result to 30 characters:

```
<?php print trim(substr(render($content['field_myfieldname']), 0, 30)); ?>

```
> 1 votes

---
Tags: theming, entities
---


# Question
Title: How to customize the node info being shared on Facebook and other sites?
This article describes how to use hook\_process\_html() to customize the node info when you embed your page into Facebook or other sites.

Is this still the best way to go or are there other ways?

# Answer
I would use the Meta Tags module. It makes the Facebook Open Graph information easy to update and configurable per node, if necessary.
> 4 votes

---
Tags: 7, social-network
---


# Question
Title: How to display the trimmed value and the full value of a field in a same node
I have a content type with a text field that i want to render trimmed and full in the same node.

I've set my field to "trimmed" and rendered it in my node.tpl.php using
`<?php print render($content['field_image_desc']); ?>`

Now i need to render the same field but not trimmed (to display it in an overlay div).

Thanks for helping...

# Answer
> 3 votes
i answer myself:

inside node.tpl.php, this is rendering a trimmed version of my field

```
<?php
     print render(field_view_field('node', $node, 'field_myfieldname', array(
        'label'=>'hidden',
        'type' => 'text_summary_or_trimmed',
        'settings'=>array('trim_length' => 30),
    )));
?>

```

and then i render my 'default' format field like always

```
<?php print render($content['field_image_desc']); ?>

```

# Answer
> 0 votes
This is simple, your obviously going to want some sort of event to open the overlay so create a link field. Display the full content in the overlay with a different view mode.

---
Tags: nodes, entities
---


# Question
Title: Add a CSS class to field in content type
I'm fairly new to Drupal and I want to add a custom CSS class to a custom field in content type.

I've created a content type called 'custom page' and I have a field called 'custom\_page\_main\_title' the only thing I would like to do is to add a custom CSS class or iD to this

How can I do this please? Thanks!

# Answer
I wrote a blog post about this a little while ago. It mostly serves as a reference for understanding the method for targeting the markup for specific fields in specific content types utilizing theme functions in template.php which is stored in your theme's directory.

Definitely check it out. If you can understand it, then in the future changing any of the HTML for particular fields, including the classes generated, becomes trivial.

To bring the pertinent content from my blog post into this thread, we have the following function in `template.php`:

```
function theme_field($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
  }

  // Render the items.
  $output .= '<div class="field-items"' . $variables['content_attributes'] . '>';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

  return $output;
}

```

What you would do would be to replace the word `theme` in the function name to the name of your theme, and since you're targeting a specific field in a specific content type, you would append to the word `field` in the function name with `__custom_page_main_title__custom_page`. So the function would look something like:

```
function themename_field__custom_page_main_title__custom_page($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
  }

  // Render the items.
  $output .= '<div class="field-items"' . $variables['content_attributes'] . '>';
  foreach ($variables['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
    $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

  return $output;
}

```

Now you need to decide where in the structure of the field the class needs to be added, so perhaps add that on as an addition to your original question.
> 1 votes

# Answer
The best way is to create your own theme, then check the html generated and update the theme css, a good point to start is using Fusion theme.

Another option is using a module called CSS Injector.
> 0 votes

# Answer
You could install Display Suite It gives you an option to append class to each field in your custom content type.
> 0 votes

# Answer
There's a very simple module called Field Formatter CSS Class that does exactly this. When activated it allows you to add a CSS class to your field via the **Manage display** tab of your content type.
> 0 votes

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


# Question
Title: How do I redirect a user role on login (Drupal 6)?
So I want to create a new user role (already done) and redirect them to a certain page (and use a certain menu) when they log in.

I'm not seeing any specific place to do this under roles or permissions - does it need a third party module? I can give a list of the modules my client is using if that helps.

Note, this is in Drupal 6.

# Answer
I'm not 100% sure since I don't have a D6 to test, but you should be able to do this with rules.

If there's a missing link in rules it's straight forward to code your own condition or action:
> 1 votes

# Answer
You can use Rules Module

You can create the redirect after the login.
> 0 votes

# Answer
You can write a small piece of code to redirect on login.

```
function hook_user($type, &$edit, &$user, $category = NULL) {
    global $user;
    switch ($type) {
        case 'login':
    if (in_array('administrator', array_values($user->roles))) {
          drupal_goto(ADMIN_DASHBOARD);
        }
        break;
    }
}

```

Or you can do the same using Rules module. Now to show a Role Based menu you can use Menu Access Module to set permissions
> 0 votes

# Answer
I achieved this using the Front Page module. It does exactly what you need.
> 0 votes

---
Tags: routes, users
---


# Question
Title: How to access parent site products in child site using drupal services ?
I want to create shopping cart in child sites but using PARENT site database. I don't want to install UberCart for each child site as i have several child sites.

For example : when i add a product (LAPTOP) it must be available on all child sites with complete detail (Title,Model,Price,sku,etc.....)

Can someone guide me to right path. Using drupal 6.

# Answer
What you can do is set up different codes connecting to same database.

So all sites might have different CSS but same database so same products and other Drupal configuration.

Essentially it is one Drupal site. Does this solve your problem?
> 0 votes

---
Tags: commerce, ubercart, services
---


# Question
Title: Ubercart Marketplace vs Ubdercart Affiliate?
We want to implement a multi-seller, affiliate-like shop but I'm stuck at which module to proceed with. What exactly is the difference between the two? Documentation is quite general and one can not tell which one is better.

# Answer
Ubercart Marketplace is where you want your "sellers to post their products" - more like eBay.

Whereas Ubercart Affiliate module is where "you sell your products" but affiliates help marketing those by spreading your site's links. This is much like the affiliate programs that are run by most hosting providers.

This is the primary difference. And they both plug to Ubercart. So they can leverage all UC features.

However it is possible that you use both in conjunction. Never tried that out. Would be interesting.
> 2 votes

---
Tags: ubercart
---


# Question
Title: In what order are implementations of the of same hook done from different modules invoked?
Suppose there two modules, *first\_module* and *second\_module* which implement `hook_user_login()` hook.

When a user logs in, which function is called first?
How does Drupal decide the invocation order for hooks?

# Answer
Hooks are called in order of

1. Weight, which is defined per module in the database as `{system.weight}`. Lower weights come earlier in the calling process.
2. Alphabetical, by module name.

By default, modules get assigned a weight of 0, so nearly all hooks in the system run in alphabetical order. Some modules will adjust this in their install hooks so they run earlier or later in the `module_invoke_all` function.

See also: Adjusting module weight: what are the risks and things to look out for?
> 32 votes

# Answer
By default a modules weight defines its place in line to execute a hook\_\* function.

You may alter the default ordering of the implementing modules with hook\_module\_implements\_alter. A small example can be found in further reading of this blog tutorial.

From that blog post an example implementation is:

```
function mymodule_module_implements_alter(&$module_list, $context){
 if($context === "node_insert"){
 $temp = $module_list['mymodule'];
 // Removing the mymodule key/value
 unset($module_list['mymodule']);
 // Adding the mymodule key value as the last member in the list
 $module_list['mymodule'] = $temp;
 }
}

```
> 12 votes

---
Tags: 7, hooks
---


title: Easily Determine if Field Is Required

text:
# Question
Title: Easily Determine if Field Is Required
I have a large set of Content Types,each with a fair amount of fields. IS there a way to programatically report on whether those fields are required or not? It is tedious to click on each field to check it.

# Answer
You can make use of Field Info API functions to get this information.

Since the 'required' setting is on the instance level, not the field level, you'll need to use either `field_info_instances()`, which will get the instance information for all fields attached to a given entity type and bundle:

```
$entity_type = 'node';
$bundle = 'article';

$info = field_info_instances($entity_type, $bundle);
foreach ($info as $field_instance) {
  $required = (bool)$field_instance['required'];
}

```

or alternatively, if you only want the info for a single field, the `field_info_instance` function:

```
$entity_type = 'node';
$bundle = 'article';
$field_name = 'field_my_field';

$info = field_info_instance($entity_type, $field_name, $bundle);
$required = (bool)$info['required'];

```
> 2 votes

# Answer
In Drupal 7 you can use field\_info\_fields() function to get list of all defined fields and its settings (i.e required this field or not).

In Drupal 6 the similar functionality provided by content\_fields() function.
> 0 votes

---
Tags: entities
---


# Question
Title: Help me to implement this plan - limit users to edit content
I have a plan that need your help to be implemented.

**I am using Drupal 6.x**

Let me describe it at first.

We have a content type called it **Article**

This content type has Title, Description, Link, Status & belongs\_to fields.

Title : Title of article record. Description : brief description of record Link : the source link \[HTML\] Status : the status of record. Available options are FREE , Finished, In progress \[it is drop down menu\] Belongs to : it is the name of user that is working on this record.

At first Some article records are added by admin. Note: Only admin of site can add new article record. When the new record is added it has **FREE** status and doesn't belong to users.

Then a user can select one article record and edit it. Note : user can edit only the article records that has FREE status . Also the user is able to edit the record that it is belong to him/her

He/she is able to edit only Status. and set it to another case \[in progress , finished or free\]

After editing the specific article record, the other users are not able to edit this record. but the last users who have edited this record is able to edit status field.

after editing a record, the belongs\_to field is set to the name of user who has edited it.

For example user1 open a Free status article record and edit it's status to in progress , or finished.

Note: if a user edit his own record' status field from "in progress" to FREE , the belongs\_to field is set to empty.

Note: The users are not allowed to edit the records that their status is Finished. \[only admin can do it\]

There is a page \[created by view\] that users can see the records. which article records are free, which articles are in progress ? which are finished. and also the users who are working on articles....

Now what is your suggestion to implement this plan?

# Answer
> 2 votes
I would look into the Node Access User Reference module as well as a lot of the other content/node access modules out there, eg, this list off drupal.org. After getting a good grasp there, it would be up to you to code up the integration of permissions unique to your site, but basically you would need to alter the node forms for this content type, check in there if a user reference is NOT yet set, and if so, set it to user editing the content and then be on your way.

---
Tags: users
---


title: An alternative for pathauto and token

text:
# Question
Title: An alternative for pathauto and token
I'm considering alternatives to pathauto module for automatic URL alias generation.

The reasons I want to stop using it are the following:

* Most of the aliases are \[node-type\]/\[node-title\] so I do not need all other functionality.
* Token goes wild and takes too much resources on pages where it needs to display the available tokens. I have 16 content types and quite a lot of fields and certain pages take considerably more time to load due to the large list of tokens.
* I do not need token module for anything else
* I would have 2 big modules less - pathauto and tokens, which would have impact on performance

I checked some similar discussions on drupal.org, but none of them offered really an alternative.

I'm now looking into optimizing the fields as each content type has its own set of fields (meaning they are not shared); this was done because of the performance but ironically I ended up with performance issues on the other end.

Setup: D7 with all latest modules.

Did you have similar problems? How did you solve them? Any words of wisdom?

Thanks!

---

**\[UPDATE\]**

For anyone looking for something similar, here is an article which explains how to handle that through a custom module.

# Answer
> 1 votes
The main performance problem with tokens is the token UI/token browser. You can disable that by overriding `theme_token_tree()` and returning an empty string. What I once did on a site is replace it it with a link that was able load the browser using ajax, but even that didn't help anymore on a site with ~300 fields and lots of references.

Pathautho/Token don't depend on entity.module?

---
Tags: 7, performance, tokens, path-aliases
---


title: javascript smooth scroll

text:
# Question
Title: javascript smooth scroll
I would like to implement smooth scrolling on my page made in drupal 6. I have a list of topics on top of the page. I would like the page to smooth scroll down direction to the topic. Can any point me how to do it in drupal 6? thank you

# Answer
> 0 votes
Finally I picked one of many js scripts available on internet. Then put it into js file inside theme directory + added this to theme.php

function MYTHEME\_preprocess\_page(&$variables) { drupal\_add\_js('...'); $variables\['scripts'\] = drupal\_get\_js(); flush caches and it is working.

# Answer
> 0 votes
Try customising the Scroll to Top module. Which provides a similar functionality.

# Answer
> 0 votes
If the Scroll to Top module mentioned by @vgardner isn't to your liking, you might also look at integrating Ariel Flesler's jQuery.scrollTo plugin which may offer a lot more functionality out of the box.

---
Tags: javascript
---


# Question
Title: how to put a submit button with a pre-defined submit function by calling drupal_render?
I've been search results for hours but cannot find an answer to my problem.

I want to show a list using theme("table",...); inside my table, there's a column of buttons, which each functions as deleting the record for this row. Therefore, I did something like this:

```
foreach($person_list as $pyid => $record){
  $render_ele = array('remove'.$pyid => array(
      '#type' => "submit",
      "#value"=> "remove",
      '#submit' => array('shms_cca_form_remove_person_from_group'),
      "#limit_validation_errors"  => array(),
      "#attributes" => array("pyid" => $pyid,'action' => "remove"),
    ));
  $rows[] = array(
    $record['full_name'], // full name
    $record['matric_no'],  // matric no
    $record['room_number'], // room number
    $record['position_name'],
    is_numeric($record['cca_points'])?$record['cca_points']:"Not Assigned Yet",
    drupal_render_children($render_ele),
  );
};

```

However, when I clicked on the button, the submit function I've defined is not called (it called the default submit function instead).

When I try to add another default button into my form like this:

```
$form += array(
  'nani' => array(
    '#type' => "submit",
      "#value"=> "remove",
      '#submit' => array('shms_cca_form_remove_person_from_group'),
      "#limit_validation_errors"  => array(),
  ),

```

Both this button and my old-not-functioning submit button works.

I therefore conclude that it's a JavaScript problem... possibly some JavaScript is not included when I call the drupal\_render by myself.

Could anyone help on how to solve this problem? Thanks a lot.

Update: I called drupal\_render, because I want to pass the rendered result to rows\[\] so that I can put these elements inside a table, like this:

```
$render_ele = array('remove'.$pyid => array(
      '#type' => "submit",
      "#value"=> "remove",
      '#submit' => array('shms_cca_form_remove_person_from_group'),
      "#limit_validation_errors"  => array(),
      "#attributes" => array("pyid" => $pyid,'action' => "remove"),
    ));

$rows[] = array(
  $record['full_name'], // full name
  $record['matric_no'],  // matric no
  $record['room_number'], // room number
  drupal_render($option),
);
return array(
"person_list" => array(
  '#type' => 'fieldset',
  "#title"=> t("Group Members"),
  '#collapsible'  => TRUE,
  "#collapsed"  => FALSE,
  "#children"   => theme("table",array('header'=>$header,"rows"=>$rows)).$add_member_str,
  '#weight'     => 10,
),

```

);

# Answer
> 0 votes
Are you returning those $render\_elem from your form function, when drupal\_get\_form calls that form id callback? Because i see you call drupal\_render\_children, but drupal need to know about it in form of form api array. drupal\_get\_form expecting you return from your form\_id function form api array of form elements, so it can do some operation like checking, if current request is POST and contains form\_id of your form and some name of submit button.

EDIT: Try add all submit buttons to your form array, but set their property `#printed => true`, so they won't be rendered, but drupal will be notified about those buttons and can run your submit functions.

---
Tags: 7, javascript, forms
---


# Question
Title: Having problems with OpenLayers in Drupal 7
I had some issues with a site I'm building so I decided to start over with a fresh Drupal install... but when I install/enable OpenLayers I get this ugliness http://pastebin.com/XJYy76n1

I have absolutely no idea what can this be and it's been driving me a little crazy for the past couple of days.

Any ideas?

Edit: for some additional incomprehensible info, I just enabled the test suite and ran it against the openlayers module and got the following: http://pastebin.com/MHdtHxNm

# Answer
The errors you are seeing, are mostly harmless. PHP on your server is configured to be very strict, which is a good thing, and the Openlayers have previously not been very strict about the coding standards.

I haven't looked specifically at the errors you are seeing, but when I've seen similar issues, I've almost always found the problem fixed in the dev version.

As no-one is actively maintaining the module, there is not likely going to be a new release any time soon. You're best option is probably to try dev, and report the issue if that doesn't help.

The ugly workaround is to turn down strictness on the error reporting on your php install.

You can also give the less feature rich but newer Leaflet module a try.
> 0 votes

---
Tags: javascript, location
---


# Question
Title: How can I make a View that shows the number of nodes attached to per taxonomy term?
I want to list taxonomy terms to see how many nodes are attached to each term.

I made a taxonomy View but can't find a field for the number of the nodes attached to per taxonomy term.

There is no this kind of field by defualt and maybe Views PHP or Views Custom Field are the way to go ??

# Answer
> 0 votes
This may help get you started. What you want to do can be accomplished by creating a views entity with a taxonomy argument that returns 'display summary when argument not found.' In that setting as well is an option to display the number of nodes, (339) for example, that have that term attached to them.

http://drupal.org/node/301485#comment-1065230

Check out that link and post back with questions.

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


# Question
Title: Is possible to have mutiple email for a user?
Is possible by default in Drupal 7 to have more than one email associate for a user ?

# Answer
In the Users table, 'mail' - the field for email addresses, is unique, as it's tied to other criteria to control account management, login, logout, etc.

So depending on what you are trying to accomplish, I dont think you could have more than one email control one account without some custom database changes.

However if you simply want to link an account to multiple email addresses, perhaps this is as simple as an 'email address' field for the profile. Adding unlimited to that field for the form would invoke the 'add another' and the user could simply have as many as they needed.

If you wanted that person to be able to login with any of those email addresses, then a quick module could link the fields together so that the email addressed used had a primary account referenced by it, and, then would proceed with login.

Or, I could be way off - what are you ultimately trying to accomplish?
> 1 votes

---
Tags: 7, users, emails
---


title: Changing TABS into CONTEXTUAL LINKS

text:
# Question
Title: Changing TABS into CONTEXTUAL LINKS
I'm making a module that changes the output from the tabs (View, Edit, ...) into contextual links. The name of my module is "testmodule" and the name of the theme I'm using is "Bartik".

When I place this into my test module, it works, but only when I use the Bartik theme:

```
function bartik_menu_local_tasks($variables) {...}

```

This doesn't work

```
function testmodule_menu_local_tasks($variables) {...}

```

Any idea's?

I was also wondering if I could easily change the html made by template.php, for achieving the change of tabs to contextual links I have to change this line in template.php:

```
<div id="content" class="column">

```

change into :

```
<div id="content" class="column contextual-links-region">

```

I want to do this within my module...

# Answer
I found a sollution to overwrite the "theme\_menu\_local\_tasks" function.

```
function MODULENAME_theme_registry_alter(&$theme_registry) {
    if (!empty($theme_registry['form_element'])) {
        // Menu local tasks
        $theme_registry['menu_local_tasks']['function'] = 'MODULENAME_menu_local_tasks';
    }
}

```
> 0 votes

---
Tags: 7, theming, routes
---


# Question
Title: Drupal 7 - Teaser trim ends after first <p> tag. How can I make it continue?
I want to my teaser to trim to 400 characters, but the trim stops after the first `<p>` tag is closed. Is there a way to override this behavior and make the teaser trim to the first 400 characters?

I have edited the teasers 'manage display' option and set it 400, then edited and saved any old content, but the teaser is still being cut off after the first `<p>` tag ends.

I have considered adding a body summary but it does not allow any formatting in the box, which I require. Any help would be greatly appreciated.

# Answer
I've been looking at this issue today and from what i understand the function used is text\_summary which works in paragraph chunks - so if you have a short 1st paragraph and then a long second one, then it sets a break point after the first paragraph and stops there, so the 2nd paragraph isn't shown.

i'm currently using the smart trim module which allows trimming by words, and gets the desired result of a consistent block of text for a teaser view of nodes.
> 8 votes

# Answer
This solution works if you are using Views to display your content (if you aren't, it's up to you which is preferable in your case between using Views and getting its many other advantages, or installing Smart Trim and keeping things simple. Views is complicated but learning it is time well invested).

1. Choose "Summary or trimmed" as the field's "Formatter"
2. Set the "Trim length" value much too high - big enough that it will always cover the whole of all the elements you'll want trimmed (e.g. 1500)
3. Under "**Rewrite settings**", select "Trim this field to a maximum length". Tick "Field can contain HTML", keep "Trim only on a word boundary" ticked, and enter the *real* character count in "Maximum length" (e.g. 200). It's a good idea to keep "Add an ellipsis" ticked to, so incomplete sentances don't look like a mistake.

So in our example, Drupal will choose the summary if there is one, or the body text if there isn't. It'll count 1500 characters, and trims cutting out any incomplete HTML elements. Unless your article contains an excessively long insane paragraph from hell, this will be at least 200 characters. Then Views' filter kicks in, trims it to 200 characters by the nearest word. This gives the real desired length, without losing the option of showing a trimmed version of the summary if there is one.

With "summary or trimmed" or "trimmed", the trimming is based on whole HTML elements so that long paragraphs can be cut out entirely. I've found that sometimes, if there's one long introductory paragraph, the trimmed field would show up completely empty - this solves that.
> 9 votes

# Answer
Under your content type -\> manage display -\> teaser -\> under "Body" field, there is a "Format" drop down list. By default it is set as "Summary or Trimmed". Set this to "Trimmed" and then select the length to be trimmed.

If that doesn't solve the problem, maybe you can try the Teaser by type module.
> 0 votes

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


title: hide node from user roles?

text:
# Question
Title: hide node from user roles?
I want to hide a node from our site for users with a specific role. I.e I have a section of my site that should only be accessed by logged in users, and I want to hide the node and the link to it in the main menu for anonymous users.

This seems like a very easy task but I'm having a hard time finding an easy way of doing this. I'm using Drupal 7.

-I've tried to do it with Rules but have not succeeded, (main problem has to do with not getting any relevant selections to choose from in the data selection.)

-I'v tried to create a new context in Context and everything looks good, but it has not the desired effect.

Is there a module for this? Something like the equivalent of node access since it is not developed anymore.

# Answer
> 0 votes
I solved my case by using the Taxonomy Access Control Lite module.

> This node\_access module governs access to nodes based on the taxonomy terms applied to the nodes. A simple scheme based on taxonomy, roles and users controls which content is visible.
>
> As the name implies, this module shares some functionality with an earlier module called Taxonomy Access Control (TAC). If you are shopping around for an access control module to use, consider that one as well. See this module's README.txt for an explanation of "why yet another access control module".

# Answer
> 0 votes
Surely you can easily do it by using roles.

Create a role for the users you want to be able to access the node type. in /admin/people/permissions set the permissions for the roles - disallow access to the node type for roles apart from your specific role that should be able to access it.

For the menu simply create a copy of your menu with the link you wish to hide for other roles and show it only for your specific role and hide the other menu instead. Since you usually assign menus as blocks this can be easily done.

---
Tags: rules, users
---


# Question
Title: Restrict content access by user language
I'm building a large multilingual Drupal intranet, but have some trouble configuring the language settings.

There are about 6 different languages and a lot of sensitive content for each language. There are about 20 different roles (for each country), where each role can have access to 1 or more languages. E.g. All regular users in Germany should only be able to access German content, however a German manager should be able to switch between the German and English content.

Right now I'm struggling just to get a regular German user to only see German content, and a regular English user to only see English content. How would that be done?

If I select "Language negotiation: none" all users see the English content and no language-dependent stuff works. If I select "Language negotiation: by prefix only" all users are able to switch between all different languages by simply typing the prefix in the url.

Is it possible to accomplish what I'm looking for without writing my own access module?

# Answer
I managed to solve this over the weekend, thought I'd share my solution if someone has the same problem.

**TL;DR**.

In my setup I use the contrib module Content Access. Basic configuration; In the System user preferences I deny `access content` to anonymous users, and in the Access Control settings for each content-type (`admin/content/node-type/[type]/access`) I disable View access for authenticated user. This way Content Access module will control exactly which role or which user can view/update/delete any content, even down on an individual node level.

I then wrote my own module that implemented the ACL api. It was a bit tricky to learn the node access system, and even more so with the complete lack of ACL module documentation/tutorials, but when I figured it out the module works really well.

The module utilizes Translation Access (i18n\_access module) for deciding the user language access permissions. Translation Access provides access control for Edit/Delete, but not for Viewing content. If that would have been the case, this module would not have been necessary...

So first I added a custom submit handler to the default permissions rebuild form

```
/**
 * Rebuild all permission when using the standard form
 */
function mymodule_form_node_configure_rebuild_confirm_alter(&$form, &$form_state) {
    array_unshift($form['#submit'], 'mymodule_rebuild_permissions_submit_handler');
}

/**
 * Route submit function through custom handler to get rid of unwanted $form arguments
 */
function mymodule_rebuild_permissions_submit_handler() {
    mymodule_rebuild_permissions();
    drupal_set_message(t('Language permissions have been rebuilt.'));
}

```

Now this is where the fun begins, I created a "rebuild permissions" function that iterates all nodes restricted by language (in my case, all nodes). If a uid is provided, permissions will be rebuilt for that user only.

```
/**
 * Rebuilds permissions for all nodes and users, or only for a specified user
 */
function mymodule_rebuild_permissions($uid = null) {
    //Select the nodes to apply language restriction on
    $nodes = db_query("SELECT nid, language FROM {node}");
    while($node = db_fetch_object($nodes)) {
        $acl_id = mymodule_get_node_acl($node);
        if(!$uid) {
            mymodule_update_user_access_all($acl_id, $node);
        } else {
            mymodule_update_user_access($acl_id, $node, $uid);
        }
    }
}

```

As seen above we need a function to retrieve/create the ACL id of the node

```
/**
 * Gets the node ACL id
 */
function mymodule_get_node_acl($node) {
    $module = 'mymodule';
    $acl_name = $module.'_'.$node->nid;
    //Get the ACL for this node
    $acl_id = acl_get_id_by_name($module, $acl_name);
    //If it doesn't exist, create new ACL
    if(!$acl_id){
        $acl_id = acl_create_new_acl($module, $acl_name);
        // View = 1, Update = 0, Delete = 0, Priority = 0
        acl_node_add_acl($node->nid, $acl_id, 1, 0, 0, 0);
    }
    return $acl_id;
}

```

As well as for updating user permissions

```
/**
 * Update language permissions for all users
 */
function mymodule_update_user_access_all($acl_id, $node) {
    $users = db_query("SELECT uid FROM {users} WHERE uid > 1");
    while($user = db_fetch_object($users)) {
        mymodule_update_user_access($acl_id, $node, $user->uid);
    }
}

/**
 * Updates language permissions for a specific user
 */
function mymodule_update_user_access($acl_id, $node, $uid) {
    //Remove from list
    acl_remove_user($acl_id, $uid);
    //Add again if user has permissions
    if(mymodule_node_access($node, $uid)) {
        acl_add_user($acl_id, $uid);
    }
}

```

Check if the user has role and language access

```
function mymodule_node_access($node, $uid) {
    //Get the user roles
    $user_roles = user_load($uid)->roles;
    //Get the content access roles
    $node_roles = content_access_get_per_node_settings($node);

    //Check if user has permission to view node
    $node_access = false;
    if(isset($node_roles['view'])) {
        foreach($node_roles['view'] as $role) {
            if(isset($user_roles[$role])) {
                $node_access = true;
            }
        }
    }
    //Check i18n selected languages
    $perm = db_result(db_query("SELECT perm FROM {i18n_access} WHERE uid = %d", $uid));
    $user_languages = $perm ? explode(', ', $perm) : array();
    $lang_access = in_array($node->language, $user_languages) || $node->language == '';
    //Return true if we have both node and language access
    return $node_access && $lang_access;
}

```

Obviously we have to update access control when inserting/updating nodes and users

```
/**
 * Implementation of hook_nodeapi()
 */
function mymodule_nodeapi(&$node, $op) {

    if($op == 'insert' || $op == 'update') {
        $acl_id = mymodule_get_node_acl($node);
        mymodule_update_user_access_all($acl_id, $node);
        if($op == 'insert') {
            node_access_rebuild();
        }
    }
}

/**
 * Implementation of hook_user()
 */
function mymodule_user($op, &$edit, &$account) {
    if($op == 'after_update') {
        mymodule_rebuild_permissions($account->uid);
    }
}

```

Finally these functions had to be included to make the ACL api work

```
/**
 * Implementation of ACL hook hook_enabled()
 */
function mymodule_enabled() {
    return !mymodule_disabling();
}

/**
 * Implementation of hook_disable().
 */
function mymodule_disable() {
    mymodule_disabling(TRUE);
}

/**
 * Remembers if we have disabled access.
 */
function mymodule_disabling($set = NULL) {
    static $disabling = FALSE;

    if (isset($set)) {
        $disabling = $set;
    }
    return $disabling;
}

```

...and that's it!

Don't forget to rebuild permissions before anything (`/admin/content/node-settings`)
> 3 votes

# Answer
First I'll try Rules, maybe you can find integration with i18n.

If not writing custom module is the only option. Check hook\_boot, you can use it to check user language and display content with language that you want.
> 0 votes

# Answer
If you select "Language negotiation: by prefix only" you might be able to use `hook_init()` to do something along the lines of:

```
if "arg(#) equals user's language" {
  return // all is good
} else {
  if "user's role allows access to that language" {
    return // all is good
  } else {
    drupal_not_found();
  }
}

```

You will obviously need to flesh out the "arg(#)..." and "user's role allows" logic to your site specifics.
> 0 votes

---
Tags: nodes, i18n-l10n, users
---


# Question
Title: Where is the 'Access Rules' in Drupal 7?
I want to restrict site registration by email domain.

It used to be under `Administration``User Mgmt`.

I can't see any similar, or has this functionality been removed from the standard module set?

# Answer
> 3 votes
For anyone that might be asking the same question - email and username rules were moved to a separate module: User Restrictions.

http://drupal.org/node/1020672

# Answer
> 1 votes
This functionality was removed in Drupal 7, but I guess you are on a lucky day, there is a module that implements this same function.

I have never tried it; you mileage may vary.

---
Tags: 7, rules, users
---


# Question
Title: How to implement a "switch" in a rule set?
I would like to make a rule set that functions as a switch with breaks in PHP. Example:

* Rule 1- User has role A, redirect to 1
* Rule 2- User has role B, redirect to 2
* Rule 3- User has role C, redirect to 3
* Rule 4- no conditions, redirect to 4

In other words:

* If a user has role A, redirect to 1.
* If a user has roles B and C, redirect to 2.
* If a user does not have roles A, B, or C, redirect to 4.

Is there an easy way to do this in Rules?

# Answer
> 2 votes
Declare a variable called "done".

* First rule in the set checks for role A, sets done and redirects.
* Second rule in the set checks if done is true, and role is B, sets done and redirects.
* Third rule in the set checks if done is true, and role is C, sets done and redirects.
* Fourth rule checks if done is true, redirects.

---
Tags: rules
---


# Question
Title: Imagecache preset is missing in field configuration
I have all the modules that could have to do with imagecache enabled. It's the user: picture field that I want to use an imagecache preset on. Normally if you want to configure that field in views, there should be a drop-down list at the very bottom of the configuration form right under the 'link to user's its profile'-checkbox.

I remember I had it there but now it's gone and I can't find out why.

# Answer
Do you have the ImageCache Profiles) module installed and enabled? Here is a quote about it (from the module's project page):

> ... allows you to set user profile pictures that are consistent throughout your site and allows avatars on the user profile pages, nodes and comments to be a different size.
> 0 votes

---
Tags: views, 6
---


# Question
Title: How to find out the combinations of Views arguments that have the most Views result
I have a node view with 2 arguments in URL `my-view/%1/%2`.

Both arguments %1 and %2 are Taxonomy Term ID.

I would like to make a page that lists the number of the View result per argument combination and order them by the number of the result.

For example, Something looking like this:

```
  %1 |  %2  | Resulst
  10 |  20  | 13
  10 |  21  | 7
  13 |  21  | 5

```

Is there anyway to make this kind of page?

My goal is to find out what the top 20 combinations of the 2 arguments that have the most nodes attached to.

# Answer
> 0 votes
You could certainly do something like this in the crude but effective dull ax category:

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

  $items['xyzzy'] = array(
    'title' => 'Two Tax Terms',
    'page callback' => 'YOURMODULE_xyzzy',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  // any other custom menu items here

  return $items;

}

function YOURMODULE_xyzzy() {

  $first=array();
  $second=array();

  $matrix=array();

  // get all of the term ids on your system...

  $query=db_query('SELECT tid FROM {term_data}');

  while ($result=db_fetch_object($query)) {
    $first[]=$result->tid;
    $second[]=$result->tid;
  }

  // cycle through all of the possible permutations of a node tagged with both of them
  // (skip nodes tagged with both in opposite order, eg tagged with 1 & 2 == 2 & 1)

  $start=microtime(TRUE);
  foreach ($first as $f) {
    foreach ($second as $s) {

      $foo=0;
      $query=db_query('SELECT node.nid AS nid FROM node node INNER JOIN term_node term_node ON node.vid = term_node.vid LEFT JOIN term_node term_node2 ON node.vid = term_node2.vid AND term_node2.tid != %d WHERE (term_node.tid = %d ) AND (term_node2.tid = %d )', $f, $f, $s);
      while ($result=db_fetch_object($query)) {
        $foo++;
      }
      if ($foo && empty($matrix[$s . ' & ' . $f])) {
        $matrix[$f . ' & ' . $s]=$foo;
      }

    }
  }
  $stop=microtime(TRUE);
  $total=$stop - $start;

  arsort($matrix);

  $top20=array_slice($matrix, 0, 20);

  return '<pre>' . print_r($top20, true) . '</pre><pre>TOOK ' . $total . ' SECONDS</pre>';
}

```

but be prepared for a long wait if you have lots of terms. Also, I just copied and pasted the second db\_query sql out of Views when I ran out of memory calling one over and over inside those two foreach()'s so it's not using {table}s and all the other good stuff it could.

I am also sure there is a `COUNT(*)` sql construct that is much more efficient than my `$foo` but `$query->num_rows` isn't universally available as I found out when I tested this on a production site instead of just locally on my mac :)

# Answer
> 0 votes
Inside Drupal, this would take some real custom magic. But, let's say for example, you wanted to show

pets/birds,

pets/cats

both birds and cats would be arguments off the main Views page of pets. BUT - if you had a Google Analytics account, which does not understand Drupal arguments, you could easily decipher which page received what number of visitors.

Because Google will never discriminate vs what is a page and what is an argument, you can easily see what would be most popular as a result.

---
Tags: 6, database, views
---


title: Image or icon on particular node output

text:
# Question
Title: Image or icon on particular node output
Is there any way to replace image/icon for a particular node output ?

A simple Example:

I am getting input from user sucn as "is your car running in petrol or diesel ?" if he selects the diesel then in node output instead of displaying diesel it should display the Diesel icon which i provide.

Is there any module for that because i have several input like this..Thanks

# Answer
If your field is a reference field like node reference or term reference, then you can add an image field in the referenced entity for associating the image. Then in your node tpl file, you can load the referenced entity and print the image. If you do not want to write a custom tpl, then this can be done using the Display Suite module. But unless you need Display Suite for other purposes, the tpl way is better.
> 0 votes

# Answer
If it's a basic select field, an if/then in your node TPL file can display the icons based on the field value. Something like:

```
<?php
if (!isset($node->field_petrol_diesel['und'][0]['value'])) {
  if ($node->field_petrol_diesel['und'][0]['value']=='petrol') :
    print '<img src="/path/to/petrol-icon.png" />';
  elseif ($node->field_petrol_diesel['und'][0]['value']=='diesel') :
    print '<img src="/path/to/diesel-icon.png" />';
  endif;
} ?>

```

The first IF checks to see if the field has a value. It then checks to see what the value is, and displays an icon accordingly. You would need to change the field name (field\_petrol\_diesel) and the icon paths to match your site.
> 0 votes

---
Tags: nodes, media
---


# Question
Title: Divide a webfrom textfield component into a specific input format
I have a need to divide a webform component into a specific formatting that is to match a coupon format. The user input needs to look something like this.

Then within the webfrom exported data the coupon needs to be displayed as one field.

Can anyone please suggest how this can be done or what the best practice is to achieve this within Drupal 7?

Thank you - your help is much appreciated.

# Answer
> 1 votes
1. You can use jQuery masked input plugin to mask the field input.
2. If you really want to have 3 separate fields, you can do that with JS again. Have one field (let's call it "main" field) where you will save the value and generate the other 3 on the fly. Hide main field and on change update the value by adding the values of those three fields.

# Answer
> 0 votes
I think the Creditfield module can solve your issue. Here is a quote about it (from the module's project page):

> ... a small proof of concept module that provides 3 FormAPI elements to be used in the Drupal Form API for custom forms:
>
> * Credit Card Number
> * Credit Card Expiration Date
> * Credit Card CVV
>
> These fields provide basic validation and form errors on their own (including Luhn check against card number). You could easily add more within your own form validation callbacks as well.

---
Tags: webforms
---


title: tab tamer - problems with hiding tabs

text:
# Question
Title: tab tamer - problems with hiding tabs
I have found quite nice drupal module, the "tab tamer". It allows admin to edit labels of tabs and sub tabs, but also disable or enable them. I have install the module, and set that user/register and user/password to "Disabled". Unfortunately I can see all the time both labels. Did I make something wrong? I use the latest drupal7. Great thank for any tips or advices :)

nykon

# Answer
> 1 votes
Drupal uses the *not-logged-in* CSS class which is used for the `<body>` tag. The following CSS style will hide the registration and login form tabs. It is the easiest way to achieve the task.

```
.not-logged-in .tab-class{
  display: none
}

```

# Answer
> 0 votes
I think you can make this with CSS, instead of going with Tab tammer module. If the module has no other specific work to do than hiding the tabs, i would insist you to opt CSS. This can reduce the rework of configuration and save memory space by evading from a module.

---
Tags: 7, users
---


# Question
Title: Authentication error when deploying site's content
I have two sites *site01* and *site02* each having some content (book pages) in them. I want to copy the content of *site01* to *site02* without overwriting its existing content.
I am using Deploy module to do this, by following this procedure.
Everything is OK until I click "Deploy" on *site01*. When I do I get the following error:
I see that someone else got a similar error, but I was not able to understand the solution applied by the person. Does anybody have any clue about this?

**UPDATE**
I tried same scenario using two different machines in LAN, and it worked fine! I was able to do the deployment smoothly.
But, on same server it is failing. I don't know what may be the reason.

# Answer
I don't know what is causing the problem when the sites are on local server i.e. `http://localhost`, but it works as expected if the sites are on different servers (could be in LAN).
> 0 votes

# Answer
My guess would be that on this step:

> For Endpoint URL, enter 'http://your-destination-site.example.com/services/rest'. Click 'Finish'. Note that it appears that any path other than '/services/rest' on either origin or destination generates a Request response error: -1002 missing schema.

Your entering the incorrect url. Make sure you are using clean url's. If not, make sure to include the "?q=" part for the path.
> 0 votes

---
Tags: 7, deployment
---


title: drupal form submission

text:
# Question
Title: drupal form submission
I have a very weird problem, my custom forms submition doesn't work unless devel module is active. any ideas how to solve this problem?

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

$array = unserialize(variable_get('forexCompare_company1',""));

$array[] = t($_POST['forexCompare_company1']);
variable_set('forexCompare_company1',serialize($array));
//drupal_set_message(print_r($form_state)." k".$_POST['forexCompare_company1']);
}

function forexCompare_form($form,&$form_state){
return array(
            'forexCompare_company1' => array(
                '#type' => 'select',
                '#title' => 'Company #1',
                '#options' => getCompanies()
            ),
            'forexCompare_company2' => array(
                '#type' => 'select',
                '#title' => 'Company #2',
                '#options' => get_stored_comp()
            ),
            'submit' => array(
                '#type' => 'submit',
                '#value' => 'Save',
            ),
            '#submit' => array(
               'forexCompare_form_submit'
            )

);
}

```

i have notice that when i return the drupal\_get\_form() on the page callback , but when i pass it as variable in theme function doesnt work

```
function userOptions_theme(){
global $user;
$user_loaded = user_load($user->uid);
return array(
  'settings_user_transfer'=>array(
      'template' => 'setting',
      'variables' => array('money' => $user_loaded,'form' => drupal_get_form('userOptions_form'))
  )
);
}

```

# Answer
> 1 votes
There are a few things wrong with your approach, don't use $\_POST, the values are there in &$form\_state and you will break Drupal form handling using $\_POST. If you have devel running use dpm() to explore that array.

In the theme function call drupal\_get\_form with the right name: forexCompare\_form, i.e. drupal\_get\_form('forexCompare\_form'). Or was the theme function just an example.

# Answer
> 0 votes
As marcvangend said, I dont have to use `drupal_render()` inside the template, and now i know why the forms was working when devel module is active, becuase it was building the theme register on every page request.

Thank you all for your help

---
Tags: forms
---


# Question
Title: How to override the /taxonomy/term/% for specific terms?
I would like to override the standard `/taxonomy/term/%` view for certain terms in a given vocabulary in two situations: one is for a given term, another is for all childs of a given term (so if and only if the current term has XXX has parent, the view must be triggered°.

When one of the condition above is met, then this view must be triggered, the standard view must be displayed otherwise.

What is the proper way to achieve this?

**EDIT**

Example: Standard taxonomy page orders teasers by published date and it is generally what I need except for all the children of the term "Regions" (Africa, Asia, Caribbean,...) where I need to order them by Country and provide exposed filters.

I don't want to create a view for each of those terms. I would like to create a view that is triggered only when the parent term is Regions. In all other cases, the standard `/taxonomy/term/%` view must be rendered.

# Answer
> 0 votes
I don't know if this is the 'right' way to do it, but I often need to do something very similar and achieve it by overriding the page callback for the standard taxonomy term page.

This involves implementing `hook_menu_alter()` like so:

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

```

Then you would provide a page callback which sees which vocabulary the current term belongs to, and makes a decision about whether to serve the standard taxonomy page or a view:

```
function MYMODULE_taxonomy_page($term) {
  $build = array();

  // If we're on some vocabulary, serve a view
  if ($term->vid == function_to_get_vid()) {
    $build['term_page'] = array(
      '#markup' => views_embed_view('name_of_view', 'name_of_display', $arg1, $arg2)
    );
  }
  else {
    module_load_include('inc', 'taxonomy', 'taxonomy.pages');
    $build['term_page'] = taxonomy_term_page($term);
  }

  return $build;
}

```

# Answer
> 0 votes
In D6, the taxonomy term page is themed by default with a function, but it can be overridden by creating a template in your theme called `taxonomy_term_page.tpl.php` (or of course writing your own function if you want).

In D7, it provides a default `taxonomy-term.tpl.php` that can be copied to your theme and modified.

So, you would have to look to see what term is being displayed and if it's one of the ones you want customized, embed your view output for it; otherwise, let taxonomy do it's thing by default.

There is good commentary in the D7 template that should make that pretty straightforward. In D6, there is a Crazy-Awesome Taxonomy Pages Video with Bob from Mustardseed Media that I found to be quite helpful but there you basically have a `$tids` array that you can look at to decide what to do.

---
Tags: views
---


# Question
Title: Sort a view by country - according to the translated countries
I have a view displaying some nodes of a content type. Each node has a location assigned (with the location module).

I want to group and sort the results by countries. The grouping works fine, and the sorting is *almost* fine too.

It does sort by country, but it does it using the *english* countries' names.

However, my website is in french, so I want it to sort using the *french* countries' names.

Most of the countries are fine, but some are not the same. For example: `South Korea` is `Corée du Sud` in french, so it's not the same order.

Views uses the english name to sort, I want it to use the current language (here french, but it's a multilingual website, so also english when it is).

# Answer
> 4 votes
Your problem is that views uses SQL to sort, since that is a lot easier and faster and it otherwise would be required to load all the records and sort them with PHP, before selecting which to show, which is a massive resources waste if you have a lot of records and use paging.

A simple solution to this problem, is to create a work around. Since the country names is stored in english, you can create a field that you hide from the user where you store the French country name. You can then in your view use this field when sorting. You would need to write a bit of code - in a custom module you create - to hide the field in the UI and automatically set the correct value based on the country the user selected in the interface. This can all be done with `hook_form_alter`.

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


title: Translate product pages automatically

text:
# Question
Title: Translate product pages automatically
I have a website with a product catalog of more than 500 products. I'm using Drupal Commerce and have created a *product display* content type to group several SKUs under a single product page.

I'm using the i18n module because I need a multilingual website.

Once the data entry is done (for the English section), the catalog must be totally translated into all the other languages, and that means a huge amount of work. Can this step (translation of product display contents) be automated in any way?

**Please note**: I just need all the products to be visible in all the active languages, at present there are no "string" product fields to translate.

**Edit**

By "automated" I mean that I start from creating product display pages in one language, and then I need product display pages in each of the defined languages; I'm looking for an automated way to create product display nodes in other languages instead of having to manually translate each page.

I've accepted the answer below because it does provide a solution to the problem and it's not a workaround, anyway it's **not** the way I took.

**How I made it work**

1. I set product display pages as *language neutral*.
2. I translated all the product page fields' labels, and then all the select lists' values.
3. At that point, I was faced with an hybrid page, with translated labels and untranslated values. I wondered why, until I found this page, mentioned in this post. That is, I...
4. went to Administration \> Structure \> Content types.
5. Click on Product page \> Manage display.
6. Set format to Default translated, Link (localized) or Plain text (localized) depending on the field type.

# Answer
To translate products, you will have to look into Entity translation. Make sure to check the Title module as well which allows to use a field for the product title so that can be translated as well.

For the automation/mass management part, have a look at the the Translation Management Tool* project. The new alpha2 release now integrates into the default Translate tab added by Entity translation and there is also a generic overview for all translatable entity types that allows to mass-translate (by sending a job to translation agencies, machine translation services, export as XLIFF and translate in a desktop tool, ..) entities, which includes products.

Note that the project is in alpha which in this case means that it hasn't been tested on many real sites yet, especially not the new entity translation integration. It has an extensive automated test suite though and is well documented (there is even a introduction video now!).

You can also translate product displays (nodes) using the same tool chain.

\*Disclaimer: I am the maintainer of that project.
> 4 votes

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


# Question
Title: Why can't I call theme functions declared in template.php in mymodule_nodeapi hook?
I have some theme functions defined in my theme's template.php file that I am calling in my modules with no problems.

I also have some theme functions defined in my\_module.module that are also working.

I'm doing some work on themed automated emails with custom rules actions and I found that when rules calls theme functions defined in my theme's template.php file they don't return anything, but when calling the same functions copied and pasted to my\_module.module the return what I expect.

I also found that bypassing rules and doing the same process (calling the functions from both locations) in a hook\_nodeapi in the 'presave' case gives me the same behaviour. (Strangely however they work in the 'load' case.)

Is there a way I can have my theme functions neatly defined in my theme's template.php where they are already working for all my other modules, and still get at them with rules / hook\_nodeapi?

Thanks!

EDIT - more info:

Thanks guys. The reason I put them in the theme to begin with is because I'm working on a multi-domain profile with a parent theme and a subtheme for each sub domain. They were template functions for html emails that need to be branded in with images and styles from each subtheme. I've had problems with putting template theme functions in modules because the path to the templates defaults to the module directory, and I need the template to be selected dynamically based on which subtheme it was called from. Thats why I wanted to define them in the parent theme so they could be overridden per child theme.

# Answer
Functions defined inside of template.php will not reliably be available (nor are they meant to be) outside of the theme. When it comes to overriding preexisting theme functions, the overrides created within template.php will automatically be applied by Drupal core, there is no reason to actually invoke the function.

For example, if you wanted to override the functionality of theme\_menu(), and you created in your theme's template.php a function named mytheme\_menu(), that new function will not actually be invoked anywhere within the site's code. The function that is invoked will still be theme\_menu() and Drupal core will automatically override that invocation with the functionality within mytheme\_menu(). This is the intended use of the template.php file; to override existing themable output, not to create new theme functions.

Now, if you create a custom element and need to create a brand new theme function for that custom element, this function must be declared within the context of a custom module. For example, you would need to define the function theme\_myelement() inside of mymodule.module. You will also need to implement hook\_theme() by defining the function mymodule\_theme() in order to tell the Drupal theme system about your new function. There's a bit more to it, which is explained in the Drupal module developer's handbook for Drupal 6 and Drupal 7.

If this doesn't answer your question, please edit your question to provide specific details about your custom module and custom theme functions.
> 1 votes

---
Tags: theming, nodes
---