# Question
Title: Drupal 7 hook_block_info and hook_block_view permission wise display
I have a module that has permission hook for normal access and for administrative access. I want to display two different blocks to different set of users. Say, the "admin" will only get to view one block and a "site owner" will see the other display.

So, till now what I have done is, declared 2 hook\_block\_info() as,

```
    $blocks = array();
//Block for the Normal Site Owners
$blocks['payouts'] = array(
    'info' => t('Listing of Payouts'),
    'cache' => DRUPAL_NO_CACHE,

);
//Block for the Administrators
$blocks['commission_payments'] = array(
    .....
            .....
);

```

When I declare the hook\_block\_view() I use user\_access() to restrict the user's to see it. But is there any way I can restrict the user's to view the block infos in the region settings ? Is there any array parameter for hook\_block\_info that can achieve this? I suppose the 'page' parameter will only handle the page where to display the block.

# Answer
> 1 votes
An easy solution is just to check the user role in `hook_block_view()`:

```
function hook_block_view($delta = '') {
  global $user;
  $block = array();

  switch ($delta) {
    case 'payouts':
      if (in_array('Admin', array_values($user->roles))) {
        $block['content'] = t('Hello Admin');
      }
      break;

    case 'commission_payments':
      if (in_array('Site Owner', array_values($user->roles))) {
        $block['content'] = t('Hello Site Owner');
      }
      break;
  }

  return $block;
}

```

# Answer
> 0 votes
Use the same trick that you do in block\_view in your block\_info. The array returned from block\_info forms the list for the Block page. However, if a block has been enabled, it will no longer be visible, either in the Block page, or on your other pages (unless the user has permission).

hook\_block\_list\_alter may also be an option for what you want, but is only D7 and up.

---
Tags: 7, hooks
---


title: Profile2 add fields as content type

text:
# Question
Title: Profile2 add fields as content type
Is it possible to assign a content type to a field using profile2 module ? The website is developed in Drupal 7.

For example i have a content type product and another one images. I would like to have a profile which has as fields all the fields from product content type and also to be able to add more than 1 image content type to the same profile.

# Answer
Please check out Entity Reference Module. It might help.
> 1 votes

---
Tags: nodes, users
---


# Question
Title: Field widget do not save values in database!
I have a strange problem. I'm designing a new field type using field-API with a widget of course. My widget display is ok but when I save a node the field do not save the value entered in the widget..

This is the hook\_field\_schema()

```
function MODULE_field_schema($field) {
  $columns = array(
    'streamtype' => array('type' => 'varchar', 'length' => 25, 'not null' => FALSE),
    'streamtag' => array('type' => 'varchar', 'length' => 25, 'not null' => FALSE)
  );
  return array(
    'columns' => $columns,
  );
}

```

And this in the hook\_field\_widget\_form()

```
function MODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

      switch ($instance['widget']['type']) {

        case 'MODULE_default_widget':
          $item = $items[$delta];

          $element += array(
            '#type' => 'fieldset',
            '#delta' => $delta,
            '#element_validate' => 'MODULE_field_basic_widget_validate'
          );

          $element['streamtype'] = array(
            '#type' => 'radios',
            '#title' => t('Stream type.'),
            '#description' => t('Search images by:'),
            '#options' => array('author' => t('Author name'), 'tag' => t('Tag')),
            '#weight' => isset($element['#weight']) ? $element['#weight'] : 0,
            '#delta' => $delta,
            '#default_value' => isset($item['streamtype']) ? $item['streamtype'] : NULL
          );

          $element['streamtag'] = array(
            '#type' => 'textfield',
            '#title' => t('Stream tag'),
            '#description' => t('Insert author name or tag depending to the selected steam type'),
            '#required' => $instance['required'],
            '#weight' => isset($element['#weight']) ? ($element['#weight'] + 1) : 0,
            '#delta' => $delta,
            '#default_value' => isset($item['streamtag']) ? $item['streamtag'] : NULL
          );

          break;

      }

      return $element;
    }

```

The basic fieldset have a validation function and, in this one i can see the correct value in the $item. An example from watchdog()

```
Array ( [0] => Array ( [streamtype] => tag [streamtag] => tag1, tag2, tag3 ) )

```

Where can i search the error? Please help me, this problem is driving me crazy T\____T

# Answer
So it turns out Shyghar ran into an issue that I've run into more than I care to tell – which is that `hook_field_is_empty()` was returning FALSE by checking the wrong data (or something along those lines).
> 2 votes

---
Tags: 7, entities
---


title: Correct AJAX practices

text:
# Question
Title: Correct AJAX practices
I have got content types called 'Online Discussion', henceforth referred to as OD and a content type called 'Online Discussion Reply', henceforth referred to as ODR. Having Entity References (drupal.org/project/entityreference) to eachother.

When one ODR is created (via a front end custom form) it references its "parent" (the OD whose page it was created) and via Corresponding Entity References (drupal.org/project/cer) same thing happens the other way around.

In an OD's page, via theming, a specific amount of referenced ODRs are shown, the 10 latest. They are presented as rendered entities without any View's or Panel's involvement at the moment but I am open to changing that if necessary.

Each ODR has its own instance of the reply form, enhanced with quoting functionality.

Also, the ODRs can accept comments from specific roles, via a custom front-end form as well.

## The requirements:

1) I need some way to load previous (all or in batches) replies with AJAX. Currently I am firing a jQuery ajax callback to a view page that fetches the previous ODRs accordingly and I inject their HTML into the DOM. That works, but in a test-case scenario with over 200 nodes referenced, that seems to take some time

2)I need a way in which after a fixed time interval to look for new ODRs and append them giving the OD a 'livelike' behavior. At the moment I do this in the same way, and it seems to work pretty ok.

3) I need some efficient way to apply Drupal Behaviors to the new elements that come to the site so they have their contextual links functional etc. I've done that using Drupal.attachBehaviors(context); but there are issues.

## The issues so far:

I. Multiple instances of the same form on the same page.
Although Drupal handles drupal\_html\_id() on the initial OD page load, the way I use AJAX breaks the ID uniqueness. If for example I have 10 forms in my initial load, and I bring 2 more via AJAX, IDs for the first 2 will be repeated since I grab the HTML the view generated as a whole.

II. Performance issues in a 'Load all previous ODRs' case. Pretty self explanatory. Pulling 200+ entities and injecting their HTML is pretty heavy lifting.

III. Drupal.attachBehaviors - when using AJAX like the way I described, the HTML for the contextual link is produced just fine. Problem occurs with the javascript involved into it. So after some hours of researching, since there is very little documentation on this, I stumbled upon Drupal Behaviors which pretty much solved that issue, but gave me a new set of problems to deal with:

* onLoad events, now in a behavior, run each time an AJAX event is fired causing multiple event binding (unbind before bind solution at the moment)
* some onLoad events, like the collapse of the textareas the multiple forms use, cause usability issues. For example, you are typing a reply or comment, a new ODR comes into the site via the recurring ajax call and collapses your textarea.
* pretty messy and incrementally difficult to manage code to make sure I handle all the possibilities via jQuery

So, finally, the question:

**What are the best practices in a Drupal context with which to achieve the desired described result?**

# Answer
> 1 votes
First of all, you have way too many questions in here. I recommend breaking this problem up into smaller chunks and trying to solve them each, rather than dumping this whole novel into stack exchange for someone to solve all your problems for you.

Maybe that sounds harsh, but there's a reason you don't have any replies yet.

I can point you toward the Drupal's once function, which will help you address at least your onLoad conundrum. (Hint: you should not be using onLoad, ever.)

In general if you're building a site in Drupal, and you can't find a module to do what you want, and you find yourself writing a lot of PHP or javascript or custom what-have-you, you might want to consider a new approach.

There are lots of front-end frameworks that probably offer libraries to accomplish the behavior you're trying to achieve. Try finding one that comes close to solving your problem, performs well under load, and then adapt it for your use.

---
Tags: 7, views, ajax, entities, javascript
---


# Question
Title: How to avoid max execution timeout when importing a lot of nodes programmatically?
I am creating a content synchronisation module. I have a UI that allows a user to import nodes from a remote site. They enter the site url and web service endpoint, along with some other configuration options, and the program will go and fetch the nodes and import them into the database using node\_save.

I received a max timeout error while importing 357 nodes:

```
Fatal error: Maximum execution time of 30 seconds exceeded in D:\xampp\htdocs\drupal-7.15\modules\pull_content\pull_content.module on line 1188

```

So, I increased the max execution time to 360 but after 360s it timed out and I got the same error. I know that the processing hasn't frozen because I can see the nodes going into the node table at a rate of about 3 or 4 every 10s.

I don't want to keep endlessly increasing the timeout as there is the possibility that I may have to import 1000 nodes or more at one time.

Is there any way to avoid this error message other than increasing the max execution time? Maybe by running things in a batch? Or should I just make the max execution time really large?

# Answer
Yes, there is a way! It's built into Drupal core, and it's there for this exact reason and purpose. You need to use the **Batch API**. Batch lets you, well, perform operations in batches across page loads. It automates the carrying of information between these page loads and helps you to show a nice progress bar to the user.

See:
> 5 votes

# Answer
Normally, I use

```
set_time_limit(0);

```

somewhere in my settings.php file or my custom import script.

See `set_time_limit()` and `max_execution_time` for reference.

You can also look into the Batch API, but I don't have a ton of experience with it.
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Different image for markers and cluster markers Openlayers
I want to display different markers for different event types eg. skiing (little guy on skis), sailing (little boat). I am using views so this shouldn't be hard.

The fun starts when clustering. I want to use a marker with a the number of "sub" markers clustered. Also easy. But how to do this and then swap to the icon markers when zoomed past the clustering?

# Answer
> 1 votes
I'm not entirely sure what effect you're after, but I have a map that uses clustering and custom markers. I've added the code at the end of the answer. The code changes the marker dynamically: if there are visible markers of more than one type (taxonomy term) then it shows a general purpose marker; if all the visible markers belong to one type then it shows that type's marker. It works by creating a copy of the Style object with a custom context object that allows you to specify JS functions named after the placeholder that take the cluster as an argument and return a value to replace the placeholder. I've used the *delete* render intent to signify a marker's hidden and I get the feeling that might not be standard (but it works for me:). I'm not an OpenLayers guru, so no promises this is the best way!

```
var style_properties = settings.styles.service_providers;
var default_marker_path = style_properties.externalGraphic;
// Convert the path to an internal one. This can't be done via the
// OpenLayers interface.
// @see http://drupal.org/node/1166076#comment-5633868
default_marker_path = default_marker_path.replace(new RegExp('http(s)?://.*?' + Drupal.settings.basePath), '');

var options = {
  context: {
    /**
     * Dynamic attribute replacement function. Returns the path to the
     * appropriate marker for this cluster. It will return a specific
     * service type's marker if there's only one kind of visible marker
     * within the cluster; the default marker otherwise.
     *
     * @param OpenLayers.Feature cluster
     *   The cluster containing the pseudo features.
     *
     * @todo Create a TID-based index into the features array for
     *   performance benefits.
     */
    field_service_type_marker_path: function (cluster) {

      var marker_path = default_marker_path;

      for (var i = 0; i < cluster.cluster.length; i++) {
        var feature = cluster.cluster[i];
        if (feature.renderIntent !== 'delete') {
          // Feature is visible.
          if (marker_path === default_marker_path) {
            marker_path = feature.attributes.field_service_type_marker_path;
          }
          else if (marker_path !== feature.attributes.field_service_type_marker_path) {
            // There's more than one type of visible marker - early out
            // and use the default marker.
            marker_path = default_marker_path;
            break;
          }
        }
      }
      return marker_path;
    },
    /**
     * Checks through the features in the cluster and returns whether
     * this cluster should be visible (ie whether or not it has any
     * visible features).
     */
    cluster_display: function (cluster) {
      for (var i = 0; i < cluster.cluster.length; i++) {
        var feature = cluster.cluster[i];
        // I could use .getVisibility(), but there's no need at the
        // moment, because the only way that a feature might not be
        // visible is if I changed its renderIntent.
        if (feature.renderIntent !== 'delete') {
          // Any return value that's not 'none' will cause the cluster
          // to be rendered.
          return '';
        }
      }
      return 'none';
    }
  }
};

// Set up the variable externalGraphic to allow different marker images
// based on the TID.s
style_properties.externalGraphic = Drupal.settings.basePath + '${field_service_type_marker_path}';
// Set up variable display, so that the clusters can be hidden if every
// feature inside them is.
style_properties.display = '${cluster_display}';

// Set up new styles for both 'default' and 'selected' renderIntents.
layer.styleMap.styles['default'].destroy();
layer.styleMap.styles['default'] = new OpenLayers.Style(style_properties, options);
layer.redraw();

```

# Answer
> 1 votes
Checkout this post here http://drupal.org/node/1585880

It includes an example of how to get a different marker by content type.

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


# Question
Title: Change node title and node field content
I try to change the values of the title and a field of a node.

```
function module_node_view($node, $view_mode, $langcode) {
  $node->title = 'TEST';
  $node->field_description[$node->language][0]['value'] = 'CONTENT';
}

```

When I try this, nothing is changed...

# Answer
If you want to change the node title, or the content of a field, you should implement hook\_node\_presave(), which is invoked when a node is created, or updated; hook\_node\_update(), which is invoked when a node is updated; hook\_node\_insert(), which is invoked when a node is created.
If you implement `hook_node_presave()`, you don't implement the other two hooks.

The purpose of hook\_node\_view() is changing `$node->content`, which is used to build the view of the node.

The hook is called from node\_build\_content(), which is called from node\_view(). This function contains the following code.

```
  // Populate $node->content with a render() array.
  node_build_content($node, $view_mode, $langcode);

  $build = $node->content;
  // We don't need duplicate rendering info in node->content.
  unset($node->content);

  $build += array(
    '#theme' => 'node',
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  // Add contextual links for this node, except when the node is already being
  // displayed on its own page. Modules may alter this behavior (for example,
  // to restrict contextual links to certain view modes) by implementing
  // hook_node_view_alter().
  if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node))) {
    $build['#contextual_links']['node'] = array('node', array($node->nid));
  }

  // Allow modules to modify the structured node.
  $type = 'node';
  drupal_alter(array('node_view', 'entity_view'), $build, $type);

  return $build;

```

If you need to change the output of a field, or the part of a node view that shows the node title, you need to change `$node->content` in `hook_node_view()`.

As example, this is the content of `$node->content` for a taxonomy reference field. For other fields, the array can have a different structure.
> 1 votes

# Answer
I think the $node will be a object and not array. You are trying to access it like an array, hence you get php error.

```
function module_node_view($node, $view_mode, $langcode) {
  $node->title = 'TEST';
  $node->field_description[$node->language][0]['value'] = 'CONTENT';
}

```
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Submenu item linked to anchor in parent's content
I would like to have a multi-level menu where some of the menus are links not to a content node, but just for inline anchors specified in the parent node's content source.

Is there an already existing solution for this feature? If not, what method should I choose for not to spend too much time on this issue?

# Answer
> 0 votes
Try:

Special menu items

Menu Firstchild

---
Tags: routes, navigation
---


# Question
Title: Why Can't I Call Drupal Function From .inc File?
I have an inc file which I am including in my module using module\_load\_include. It contains the following function:

```
function _get_vid($vocabulary_name) {
    $vocabs = taxonomy_get_vocabularies();
    foreach ($vocabs as $vocab_object) {
        if ($vocab_object->name == $vocabulary_name) {
           return $vocab_object->vid;
        }
    }
    return NULL;
}

```

But PHP keeps complaining that taxonomy\_get\_vocabularies is an undefined function. Why? I know I've used Drupal functions in .inc files before with no issues.

# Answer
I think your module must have weight higher than the taxonomy module so that I can call any functions that are defined in taxonomy.

You can make sure your module is the heaviest one in order to run last by implementing hook\_install(). You would create a file **yourmodule.install** in your module folder which may contain the following code:

```
/**
 * Implementation of hook_install()
 */
function yourmodule_install(){
    # Fetch max module weight from "system" table.
    $max_weight = db_query("SELECT MAX(weight) FROM {system} WHERE type = 'module'")->fetchField();
    # Make sure this module is the heaviest one in order to run last
    db_update('system')
        ->fields(array('weight' => $max_weight+1))
        ->condition('name', 'yourmodule')
        ->execute();
}

/**
 * Implementation of hook_uninstall()
 */
function yourmodule_uninstall(){
    db_delete('system')
        ->condition('name', 'yourmodule')
        ->execute();
}

```
> 1 votes

# Answer
Drupal 7 version of taxonomy\_get\_vocabularies doesn't accept parameter $type. See the documentation here. Might be that.. Try with out passing NULL parameter.
> 0 votes

---
Tags: taxonomy-terms
---


title: New Drupal Modules

text:
# Question
Title: New Drupal Modules
Not sure if this kind of questions are allowed to ask here.

Are there any sites which list drupal newly introduced modules, existing modules.

Going to drupal.org and searching for a module without knowing the modules name is taking time.

**EDIT**

I want to know if somebody introduced new module is there any site that list that new module name recently introduced.

so please tell me if there are any sites which list drupal newly introduced modules, existing modules.

# Answer
> 2 votes
Perhaps drupalmodules.com is what you are after?

This page lists all new modules which has a stable release.
http://drupalmodules.com/new-modules

# Answer
> 0 votes
please visit this website for the top and basic modules http://www.mediacurrent.com/blog/jays-top-50-drupal-7-modules

or

go to this link drupal.org/project/modules and use filter criteria "Sort by" and select "Date" it will show the recent added modules

---
Tags: 7
---


# Question
Title: search result not in prioritize order drupal 7
Hi i am new to drupal 7 and also to sql query builder format.i have a requirement to search the string. in that **i hav to display exact matched string at the top followed by related matches**. i explode a string with space and searched a each word exist or not.the code as follows.

$keys -\> contain the search term

```
 $keys = preg_replace('!\*+!', '%', $keys);

$keys = explode(' ', trim(str_replace(array( '\'', '"', ',' , ';', '<', '>','!','_','-','+','@','#','$','%','^','&','.'), ' ', $keys)));;

 $query = db_select('file')->extend('PagerDefault');
 $query->fields('file', array('fid','filename'))
  ->fields('fs', array('e_id','f_subtitle_value'));

 $subquery = db_select('field_data_sub','fs');
 $subquery->Fields('fs', array('e_id','f_subtitle_value'));
 $subquery->condition('fs.e_type', 'node','!=');

 $query->leftjoin($subquery,'fs','file.fid = fs.e_id');
 $db_or = db_or();
foreach ($keys as $key) {
if(!(empty($key))) {
 $db_or->condition('filename', "%$key%", 'LIKE');
 }
}

$query->condition($db_or);
  $query->condition(db_and()->
          condition('filemime', 'image/jpeg', '!=')->
           condition('filemime', 'image/png', '!='));

```

i tried union all - wrote two query and combine it.. it fetches output but the exact searched result came twice . is that a gud way or else is there any other way.. please suggest the best way :)

# Answer
You can use default drupal's search from admin/config/search/settings and se Views module for searching specific fields. You need not write any code or Query to search in a Drupal site unless it is needed.
> 0 votes

---
Tags: search, database
---


# Question
Title: Not able to print variables of content type
I want to print variables of a particular content type, but I have not found any way. Here is my code.

```
function mytheme_preprocess_node_mytype(&$vars) {
  echo '<pre>';print_r($vars); echo '</pre>';
}

```

This function is in template.php. Is there a problem with my code?

# Answer
> 5 votes
Try this: (D7)

```
function YOURTHEME_preprocess_node(&$vars) {
  drupal_set_message('<pre>' . print_r($vars, true) . '</pre>');
}

```

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


# Question
Title: How do I restrict uploaded images to a specific aspect ratio?
What I would like to do is, using the Image field in core, to restrict uploaded images not just on resolution, but also on aspect ratio.

In other words, the image must be 2:3 width to height, and at least 200 by 300 pixels.

I know that Image Styles can manipulate the way an image is viewed. I'm not interested in that. Rather, I want to restrict uploads the same way that you can currently set min/max settings for resolution, I want to add aspect ratio.

My guess is that I'll need to write my own module to add a new check to Image's checks, but perhaps you know of a simpler way.

# Answer
> 9 votes
My advice would be to implement a custom file validator.

To see how these are used when saving files, you can check out file\_save\_upload. For an example implementation that is very close to what you want to achieve, check out file\_validate\_image\_resolution.

My super quick attempt at this

```
/**
 * Validates an image upload as having a particular aspect ratio
 *
 * @param $file
 *   - the uploaded file
 * @param $aspect_ratio
 *   - the apect ratio in the format [WIDTH]:[HEIGHT]. E.g. '3:2'
 */
function file_validate_image_aspect(stdClass $file, $aspect_ratio = 0) {
  $errors = array();

  // Check first that the file is an image.
  if ($info = image_get_info($file->uri)) {
    if ($aspect_ratio) {
      // Check that it is smaller than the given dimensions.
      list($width, $height) = explode(':', $aspect_ratio);
      if ($width * $info['height'] != $height * $info['width']) {
        $errors[] = t('The image is the wrong aspect ratio; the aspect ratio needed is %ratio.', array('%ratio' => $aspect_ratio));
      }
    }
  }

  return $errors;
}

```

---
Tags: 7, media, files
---


title: Multilingual comments form missing

text:
# Question
Title: Multilingual comments form missing
I have a website in 2 languages. The site uses panels. The nodes Comments form & comments only shows in English and not in Greek.

Has anyone encountered a similar problem? Thnx in advance.

# Answer
The i18n comments can be used for this. From the project page:

> A very simple module which would allow you to show all/any comments attached to all node translations. Just a great way to communicate in truly multi-lingual environments.
>
> For example I have node in English and Spanish. Drupal natural way would be to show comments for en/es translation separately (attached to en/es content). But i18n\_comments will aggregate all English and Spanish comments for any translations. It doesn't matter if user will leave a comment to any node translation.
> 1 votes

---
Tags: forms, comments, i18n-l10n
---


# Question
Title: How to integrate properly Kerberos based SSO in Drupal 7
I'm trying to install Drupal with Single Sign On over Active Directory.

My customer does not have any SSO suite like CAS, and their general recommendation are to use Kerberos (or NTLM as a second choice). I am clearly agreed with that.

Each time I had to integrate SSO with Active Directory using Kerberos, I use "native" product facilities, or apache mod\_auth\_kerb with headers rewrite.

Does someone implemented such a working module ? Everything I read about that is around "on developpement modules" on "snapshots realeases". We are currently using a ldap module that allow authentication over LDAP, and it seems that it provide SSO features, but I don't have any feedback on it.

So : **Should I implement SSO over Kerberos using Apache mod\_auth\_kerb, or is there a real functional module that would encapsulate all those tedious configuration and dialog ?**

What is the best pratice, at this moment ? Could you provide me "real" (anonymised) examples ?

As soon as I would installed it and put in in production (around the end of december), i would give you my feedback.

Thanks in advance

# Answer
> 2 votes
After some researches and tests, I finally made a choice.

In most cases, I'd prefer use native or add on features. This provide better integreation with the product (here Drupal) and it's more a Logic solution than a technical one (which is quite easier). **The LDAP\_SSO module allow this kind of configuration.**

Nevertheless, I was not able to configure it this time, mainly due to poor debug facilities. Even with watchdog, I am not able to know what is the matter. Moreover, my customer have clear procedure to install and use Kerberos, with Apache HTTP and mod\_auth\_kerb. **Hopefully, LDAP\_SSO module allow this too.**

After some tries, I will get back here to share with you more advanced comments, but at this time, **we clearly go to apache+mod\_auth\_kerb+fowarded REMOTE\_USER.**

## Edit a few monthes later :

That works great with Mod auth kerb on apache server and ldap module v1.0-beta12 on drupal. Even if v2.0 is available, we were facing some issues because some fields were empty and this were causing troubleshootings. But nevermind, we are able to authenticate et identify users, collect groups and map them to drupal profiles etc.

---
Tags: 7, installation, users, authentication-authorization
---


title: Schedule change of field

text:
# Question
Title: Schedule change of field
Rules does not allow data selection of fields without first knowing the node type actually has said field.

Rules only allows you to schedule components.

Rules action components can't have conditions to fulfill the first requirement.

How do I schedule a "Set a data value" action on a field?

I considered passing the field as a parameter to the component but it will only let me send "Entity" types and a binary value is not an "Entity" apparently.

# Answer
Rules action components do not have conditions, but you can also add a component that is a rule itself, not an action set, and then schedule that. Then you can just add the condition *node: has type* and then do *set a data value* however you like.
> 1 votes

---
Tags: 7, rules, actions
---


# Question
Title: Profile picture with a border color depending of the role
Is there any way to set a border color to every profile picture displayed all over the website depending on the role of the user?

I was trying to do it at least on the user profile image and on the User picture block module image following this instructions Custom node color from role but I ended in nothing.

Note: I display the profile pictures in a user search view, in the forums and in a block that display the latest forum comments.

# Answer
> 1 votes
Try hook\_preprocess\_user\_picture() in your template.php

```
function MYTHEME_preprocess_user_picture(&$vars) {
    $account = user_load($vars['account']->uid);

    foreach ($account->roles as $role) {
        $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
    }
}

```

Each user picture should then have the **role-rolename** classes added to it.
It is similar to Clive's answer you mentioned, but different hook.

# Answer
> 0 votes
I partially solved the problem with this:

```
function MYTHEME_preprocess_html(&$vars){
    global $user;

  foreach ($user->roles as $role) {
    $vars['classes_array'][] = 'role-current-' . strtolower(str_replace(' ', '-', $role));
  }

  if(arg(1) && arg(0)=='user'){
      $account=user_load(arg(1));
      foreach ($account->roles as $role) {
            $vars['classes_array'][] = 'role-visited-' . strtolower(str_replace(' ', '-', $role));
        }
  }
}

```

with this CSS:

```
.role-current-beta-tester .content_left .user_picture_block img,
.role-visited-beta-tester .user-profile .field-name-ds-user-picture img{
    border: 17px #019E96 solid;
    background: white;
}

.role-current-moderator .content_left .user_picture_block img,
.role-visited-moderator .user-profile .field-name-ds-user-picture img{
    border: 17px #37A962 solid;
    background: white;
}

.role-current-administrator .content_left .user_picture_block img,
.role-visited-administrator .user-profile .field-name-ds-user-picture img{
    border: 17px #517180 solid;
    background: white;
}

.role-current-usuario-profesional .content_left .user_picture_block img,
.role-visited-usuario-profesional .user-profile .field-name-ds-user-picture img{
    border: 17px #8A101C solid;
    background: white;
}

.role-current-usuario-no-profesional .content_left .user_picture_block img,
.role-visited-usuario-no-profesional .user-profile .field-name-ds-user-picture img{
    border: 17px #A8CE3D solid;
    background: white;
}

```

but that only works for the border of the picture displayed by the user-picture-block module and the picture of each user's profile (formatted with Display Suite). I still have the problem of the forums, my user search view and a small block that display user's latest comments on the forums (the default one of Advanced Forum module).

---
Tags: views, blocks, media, users
---


# Question
Title: How do I limit taxonomy by content type?
I want to limit the results of my code snippet below to query only items that have been used in a particular content type. How do I do that

```
<?php

$vid = 15; //vocabulary id
$num_term = 20; //limit maximum terms

//USE INNER JOIN below to only show terms with a count of 1 or more (the LEFT JOIN includes terms with a count of 0)
$query = "SELECT td.tid AS tid, name, COUNT( nid ) AS count
FROM {term_data} AS td
LEFT JOIN {term_node} AS tn ON td.tid = tn.tid
WHERE td.vid=". $vid ."
GROUP BY tn.tid ORDER BY name ASC LIMIT ". $num_term;
$result = db_query($query);
while ($term = db_fetch_object($result)) {
$items[]= l($term->name, "taxonomy/term/$term->tid") . ' (' . $term->count . ')';
}

if(count($items)) {
return theme('item_list',$items);
}

?>

```

# Answer
You would also join in the node table (on term\_node.nid = node.nid) and add node.type to the WHERE clause.

Do note there are several problems with your above code. First and foremost, as mariomc asks, any special reason why you're doing this manually instead of through Views?

Second, if you do have a good reason to do the querying yourself, do look into using placeholders with db\_query. Its primary purpose is preventing SQL injection problems (strictly speaking, if the variables really are hard coded like this, there is really no danger, but consider what happens when you decide to feed them in from somewhere else at a later date).

All in all, code that would both answer your question and is more "correct" would be (untested):

```
<?php

$vid = 15; //vocabulary id
$num_term = 20; //limit maximum terms
$type = 'story'; // Your type

$query = "SELECT td.tid AS tid, name, COUNT( nid ) AS count
  FROM {term_data} AS td
  LEFT JOIN {term_node} AS tn ON td.tid = tn.tid
  LEFT JOIN {node} AS n ON tn.nid = n.nid
  WHERE td.vid=%d AND n.type = '%s'
  GROUP BY tn.tid ORDER BY name ASC LIMIT %d";

$result = db_query($query, $vid, $type, $num_term);

// ...
?>

```
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to keep domain consistency (with or without www)?
Some search engines make a difference if the site is found in example.com or www.example.com. So it's important to redirect all users from example.com/some-page to www.example.com/some-page, or the other way around.

Is it possible in Drupal 7?

# Answer
> 5 votes
I found the answer. The .htaccess file contains the following comments.

```
# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

```

Uncommenting one of those rewriting rules is all you need to do.

---
Tags: uri, redirection
---


title: Creating a responsive long form submit

text:
# Question
Title: Creating a responsive long form submit
I have a rather long procedure on form submit (need to send several email to different addresses); when the use submits the form, the application seems to hang while it is doing a lot of work. Is there a Drupal way to show a "operation in progress" (better showing an indicator) without using Ajax and/or Ahah?

# Answer
This module looks like similar to your query Hide Submit
> 1 votes

---
Tags: 7, forms
---


title: Get scheduled rules in rule

text:
# Question
Title: Get scheduled rules in rule
I need to get the date of a scheduled rule and display it to the user.

I also would like (Not necessarily required, I can also use an invisible CCK field) to use the existence of this schedule as a condition in yet another rule.

Is it possible to get this using rules alone or do I need to use the "Execute custom PHP code" condition/action to find them?

# Answer
What about doing it the other way around? Use a date field and triggering the rule according to it?
> 0 votes

---
Tags: 7, rules
---


title: Customizing menu html

text:
# Question
Title: Customizing menu html
How do you set an id for the menu's root `<ul>` tag?

I know about the module "Menu Attributes" but that doesn't let me add an ID to the root `<ul>`, or at least I do not know how.

Also, I've seen a solution which uses `theme_menu_tree()` and a regex check, but that's just too hacky for my taste.

# Answer
> 3 votes
In D7 default theme **bartik**, you can see the main menu is rendered using a theme hook `links__system_main_menu`:

```
 <div id="main-menu" class="navigation">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#main-menu -->

```

`links__system_main_menu` is a theme hook pattern of the form \[base hook\]\__\[context\]. When links are themed with `theme('links__system_main_menu', $vars)`, `theme()` will search for and use `theme_links__system_main_menu()` if it has been defined. If not, it will use `theme_links()`.

Drupal will use MYTHEME\_links\__system\_main\_menu(), if you define it in your theme. Thus, you could implement the `hook_links__system_main_menu` as follows. Probably you will do that in the template.php file in your theme folder.:

```
function mytheme_links__system_main_menu($variables) {
  $html = "<div>\n";
  $html .= "  <ul id=\"your_id\">\n";
  foreach ($variables['links'] as $key => $link) {
    $html .= "<li>".l($link['title'], $link['path'], $link)."</li>";
  }
  $html .= "  </ul>\n";
  $html .= "</div>\n";

  return $html;
}

```

This will override the `links__system_main_menu` theme and customize HTML output for the main menu.

**\[Edit\]**

If you are looking for the quickest way, you just need to tweak your page.tpl.php by adding an extra wrapper to the menu **ul**.
For example, in the Bartik theme,

```
  <div id="main-menu" class="navigation">
    <div id="your-id">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
    </div>
  </div> <!-- /#main-menu -->

```

Then, you can access it using `#your-id ul{ }` in CSS or `$('#your-id ul')` in JS. But, the above code is just for example, you should not hack the core themes or modules. I assume you have your own theme.

# Answer
> 1 votes
You want to overwrite menu tree theming function as I mentioned in IRC. Easiest way would be to copy the attribute usage from theme\_links.

Using this method does affect all menus, but it doesn't change anything for those which doesn't use attributes.

```
// Default theme_menu_tree
function theme_menu_tree($variables) {
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
}

// Overwritten theme_menu_tree
function YOURTHEME_menu_tree($variables) {
  $attributes = array("class" => array("menu"));
  if(isset($variables['attributes']))
    $attributes = array_merge_recursive($attributes, $variables['attributes']);
  return '<ul' . drupal_attributes($attributes) . '>' . $variables['tree'] . '</ul>';
}

```

# Answer
> 0 votes
I managed to get it right with the following code, based on @Sithu's response

```
function themename_links__system_main_menu($variables) {
    $html = '<ul id="menu">'."\n";
    foreach ($variables['links']['system_main-menu'] as $key => $link) {
        if(is_array($link)){
            $html .= "<li>".l($link['#title'], $link['#href'], $link)."</li>";
        }
    }
    $html .= "  </ul>\n";
    return $html;
}

```

---
Tags: routes, theming
---


title: Subpage of a URL Alias and hook_menu

text:
# Question
Title: Subpage of a URL Alias and hook_menu
Im slowly getting back into Drupal after much time away and beginning to pick it up and the learning curve is building back up.

So much so I always like to throw out pre-defined conventions as too restrictive while keeping the rough framework to build something bigger for what I want to do.

In my case, it's a scheduler program. But mine is in the context for a church, but could work equally well elsewhere

However the idea is that each type can have a sub type, a schedule gets applied to the type and the back end calendar generates the calendar entries for the schedule. This then gets displayed in a number of ways, from an eventually RSS feed to hook into an Android application, to a Calendar and everything else in between.

Each calendar item needs to be overwritable in that it's a generic item that may have additional certain applicable details rather than being a unique entity in its own right.

This list of types should be output with a link then to each type while I alter the page then to generate a list of next upcoming schedules for that item. Click on a date and get entries for that date. etc

It's all going pretty well until I realise I need to start referring to things by database Id instead of having a nice URL because frankly, database calendar entries don't as such have a nice URL.

One of the things I would have liked to have done is to have a URL alias against a node for my event type, eg, somecategory/sometype but then to be able to use the hook\_menu system to get somecategory/sometype/% (where % could be sun, mon, tue, wed etc). Bearing in mind somecategory, sometype will be variable depending on user input, only % will have a list of specific possible - sun throu sat.

Trouble is, it doesn't look like you can do it, so I've just had to use an alias such as calendar/type/%

Any thoughts on this hook\_menu issue, and any thoughts overall? 2000 lines of code into this thing and Im wondering why Im doing this (oh yeah, I like doing things my way).

Simon

# Answer
> 1 votes
I had a similar (not quite so flexible) issue.

Basically a node lives at `node/NID` or a `url-alias` path. I didnt want to write a custom hook\_menu to make something so flexible as `somecategory/sometype/%` -- but i really think you should be able to.

I used the module view\_mode\_page

> On the manage display page for a given content type, you can assign patterns for view modes so that they will become a page at the given path. For instance, if you want to show the teaser at a specific URL, you could do node/%/teaser. If you also use Display Suite or other modules that allow you to create new view modes, you can use these modes to display one or more fields from a node at a separate URL.
>
> Restrictions: currently, the node path must be contained in the URL. This means view mode pages must follow the form \[node path/node alias\]/\[view mode url\]. These pages are added via hook\_menu. Multiple wildcard characters can be used.

I used it to set many urls for a node of the form: `'url_pattern' => 'instructors/%/'.$val`

where `instructors/%` IS a node alias and `$val` is a value from a Taxonomy Term field attached to the node. Eg, I get N-subpage urls for however many terms are in this vocabulary for each node of this content type.

I then use Display Suite to create a `dynamic field` for a custom view mode I associated for this node and url path; I also used Display Suite to create the custom view\_mode (or maybe it was the FieldUI I forget). The dyanmic field a View that takes an argument that is the wildcard in the url.

Here's a snippet of code using the view\_mode\_page API:

```
  /*
   * Implementation of hook_view_mode_page_get_patterns() from module
   * view_mode_page.
   *
   * This lets me define additional node urls (per NID) with a custom
   * view mode.
   *
   * I then use this view_mode along with Display Suite and custom Fields
   * to completely alter how the node is viewed on that page, and only
   * show a View of related downloadable course files.
   */
  function MYMODULE_view_mode_page_get_patterns($results, $content_type,  $view_mode) {
    $results2 = array();
    $defaults = array('content_type' => 'course', 'view_mode' => 'course_materials_list_view', 'show_title' => 0, 'title' => '');

    // TODO: change this to like a Taxonomy Tree lookup.
    $terms = array('activities-and-handouts', 'administrative', 'assignments', 'data-recordings-and-transcripts','lectures','quizzes-exams','readings-and-reading-handouts');
    foreach ($terms as $pos => $val) {
      $results2[$pos] = (Object) array_merge($defaults, array('url_pattern' => 'instructors/%/'.$val));
    }
    return $results = $results2;
  }

```

This basically works for me. Breadcrumbs aren't totally happy. It's NOT exactly what you're asking but might help as it's very related. Good luck.

# Answer
> 0 votes
First off, to avoid any conflict, the path for a menu handled by a module should have a part that is specific for that module; the Node module uses node as first part for its menu callbacks, and the User module uses user.
Imagine what would happen if the Node module used %title/%nid as menu path for the node pages. (%title is not a placeholder Drupal currently defines.) It would be enough the node title were user, and the node page would override a user profile, or vice versa. This doesn't actually happens because node pages have a path like node/%nid, and user profiles have a path like user/%uid. (For each user ID there would be a node with that ID; that is the reason they are not enough to disambiguate a node page from a user profile page.)

In your case, the menu path cannot be somecategory/sometype, but it should be mymodule/somecategory/sometype. (Replace mymodule with the short name of the module you are implementing.)

if somecategory, and sometype are values you could obtain from a function, you can use the approach followed by the Search module, which uses the following code in its `hook_menu()` implementation.

```
foreach (search_get_info() as $module => $search_info) {
  $path = 'search/' . $search_info['path'];
  $items[$path] = array(
    'title' => $search_info['title'],
    'page callback' => 'search_view',
    'page arguments' => array($module, ''),
    'access callback' => '_search_menu_access',
    'access arguments' => array($module),
    'type' => MENU_LOCAL_TASK,
    'file' => 'search.pages.inc',
    'weight' => $module == $default_info['module'] ? -10 : 0,
  );
  $items["$path/%menu_tail"] = array(
    'title' => $search_info['title'],
    'load arguments' => array('%map', '%index'),
    'page callback' => 'search_view',
    'page arguments' => array($module, 2),
    'access callback' => '_search_menu_access',
    'access arguments' => array($module),
    // The default local task points to its parent, but this item points to
    // where it should so it should not be changed.
    'type' => MENU_LOCAL_TASK,
    'file' => 'search.pages.inc',
    'weight' => 0,
    // These tabs are not subtabs.
    'tab_root' => 'search/' . $default_info['path'] . '/%',
    // These tabs need to display at the same level.
    'tab_parent' => 'search/' . $default_info['path'],
  );
}

```

If somecategory, and sometype are completely arbitrary values entered from users in some way, then you could use the following definition for the menu callback.

```
  $items[mymodule/%/%/%mymodule_weekday] = array(
    'load arguments' => array(1, 2),
    'page callback' => 'mymodule_calendar_view',
    'page arguments' => array(3),
    'weight' => $module == $default_info['module'] ? -10 : 0,
  );

```

```
  function mymodule_weekday_load($weekday, $category, $type) {
    // Return an array, or an object basing on the arguments.
    // Return FALSE is the arguments contain values that are not acceptable.
  }

```

For a path like mymodule/my\_category/my\_type/sun, `mymodule_weekday_load()` will be called as `mymodule_weekday_load('sun', 'my_category', 'my_type')`. When the load function returns `FALSE` the user will get a 404 error page.

The string mymodule I am using here is just an example. What a module normally use is its short name, except in the case the module is extending a menu defined from another module. For example, the Book module uses book/export/%/% as path for its exporting page, but uses node/%node/outline for its page that allows to set the outline to which the node belongs.

As examples of load callbacks, you can look at node\_load(), and user\_load().

### References

---
Tags: 7, routes
---


# Question
Title: webform_submission_insert $submission values
I am writing a module where I need to grab the submission values of a webform

I am using the webform\_submission\_insert hook found here however when I print out the $submission array using this:

```
drupal_set_message('<pre>'.print_r($submission).'</pre>', 'warning');

```

All I get is this:

```
<pre>1</pre>

```

It appears to me this hook is not working correctly and is not populating the array. How can I get the submission values?

I am using Webform version 7.x-4.0-alpha6. The webform I created has about 10 different input fields.

# Answer
> 1 votes
I was printing the array out incorrectly. Using this code to print works:

```
drupal_set_message(''. print_r($submission, TRUE) .'');

```

---
Tags: 7, webforms
---


# Question
Title: Unable to go to administration pages (access denied)
It seems I have some problems to access some functions. When I try to run my website I have these errors:

```
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'nodereference_autocomplete_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'views_access' not found or invalid function name in D:\SVN\lancaster\Dev\drupal\includes\menu.inc on line 452.
You are not authorized to access this page.

```

I tried to check if all my modules were enabled, but I can't log in as administrator in my site too. When I do it, I get the following error:

> Forbidden
> You don't have permission to access / on this server.

# Answer
> 2 votes
I recommend you to do the following:

* backup your database
* truncate drupal cache tables using phpmyadmin ui or from mysql command line
* truncate role\_permission table using phpmyadmin ui or from the mysql command line
* try to login using super administrator, the user with id 1
* if nothing change with you, try to install another drupal project and see if you get the same error messages; maybe you have an issue with your php version or configuration.

---
Tags: users
---


# Question
Title: No page style appearing on Permissions page.
The permissions page on my site has no styling/theme. It is the only administration page that has this problem. The page displays as if I have turned off styles. I am using Drupal 7. What could be causing this issue?

# Answer
I recommend you to do the following:

* delete css files under /sites/default/files/css and then checkout the administrator pages
* go to /admin/appearance and select an administrator them at the bottom of the page. If its already been selected try to use another administrator theme
* make sure "Use the administration theme when editing or creating content" is checked
* clear your cache using drupal clear cache button under /admin/config/development/performance
* Checkout Administer themes permission in the permission page /admin/people/permissions
* try to open your site with another browser
> 0 votes

---
Tags: theming
---


# Question
Title: Theme inheritance : blocks placement not inherited
I have a "Father" theme, and a "Child" theme that inherits from Father.

Css and templates are well inherited, it's ok, but blocks placement (Structure \> Blocks) won't inherit.

Is it supposed to ? If it is, do you have any idea for this to work ?

Note : I have the same custom regions defined in each .info file.

Many thanks.

# Answer
> 2 votes
Block placement per region is unique to each theme. Putting the search block in "right\_sidebar" for theme\_a doesn't put the search block in "right\_sidebar" for theme\_b.

---
Tags: 7, theming, blocks
---


# Question
Title: How to block users from editing a node of a content type? (D7)
This should be easy, but I can't figure out what I'm doing wrong: In my Drupal 7 site, I've defined a content type in the usual way. I want regular users to be able to **create** instances of that type, but not **edit** them. Trivial, right?

The content type is in place, and, in admin/people/permissions, there are entries like "My Type: Create new content" and "My Type: Edit own content". I've set the checkboxes so authenticated users have "create new content" permission but not "edit own content" permission. Just to be on the safe/superstitious side, I've cleared the cache and done a Rebuild Permissions. But, nevertheless, my regular users can still edit their nodes.

Shouldn't this work / any ideas what's wrong? Do I need to write a \_node\_access handler?

# Answer
Oops: My bad. I had given authenticated users "bypass node access" permission to deal with a pending bug in the apache\_solr module. Once I dropped this permission, everything worked the way it was supposed to.

Sorry for cluttering up things...
> 0 votes

---
Tags: 7, users
---


# Question
Title: Two forms on the same page - both submit the same
I have two forms on the same page, both called with `drupal_get_form('some_form_name', $product_id);`. The `$product_id` variable is used to fill in a `hidden` input. (The code is in a `foreach`, the `$product_id` variable is different for every form.)

In the generated HTML, the forms are correctly built. Both have different IDs, and both hidden fields have the correct value.

However, in the submit function of this forms, with the following code:

```
function some_form_name_submit($form, &$form_state) {
    dsm($form_state['values']['product_id']);
}

```

The product id is always the same. The first generated form's product id.

After some research, I found out that the hidden input `form_id` is the same in both forms. Looking into that.

Is there a way to solve this?

# Answer
> 3 votes
Found the solution. The problem was that the forms had the same form\_id -- `some_form_name`, the string passed to `drupal_get_form()`.

I generated the string with something like `drupal_get_form('some_form_name_' . $product_id);` instead of passing as second argument.

However, that means I would have to define a function for each product id. To avoid this, I implemented `hook_forms()`, so that each form id starting with `some_form_name_` would use the same callback to generate the form:

```
function mymodule_forms($form_id) {
    if (preg_match('/^some_form_name_\d+$/', $form_id)) {
        return array(
            $form_id => array(
                'callback' => 'some_form_name',
            ),
        );
    }
}

```

This way, even though each form has a different form\_id, they all use the `some_form_name` function to generate the form.

And no problem left.

# Answer
> 0 votes
Hook\_forms is an answers. There is a second way :

In your form, add in the #name of the submit, the $product\_id;

like :

```
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('submit'),
    '#name' => $product_id,
   );

```

Then, in the submit callaback, you'll find in the $form\_state\['triggering\_element'\], the product\_id value. So even if you use the same form in a foreach loop, you can know witch 'submit' have been triggered.

---
Tags: forms, commerce
---


title: Form redirect with posted data

text:
# Question
Title: Form redirect with posted data
How to transfer the submitted data *too* when redirecting a form through $form\_data\['#redirect'\]?

Like :

hook\_menu declares : page-1, page-2

page-1 having a form that when submitted triggers page\_1\_form\_submit() (in which I does the redirection)

but I'd like that once redirected to page-2, page\_2\_page() (registered as render function in hook\_menu) can access the previously submitted data!

:)

# Answer
> 5 votes
In the form submission of the first page you can copy the values in `$form_state['values']` into the session for the current user; the page callback of the other page can then access them.

```
function mymodule_page1_form_submit($form, &$form_state){
  $_SESSION['mymodule_page1_submission_timestamp'] = time();
  $_SESSION['mymodule_page1_submitted_values'] = $form_state['values'];

  $form_state['redirect'] = 'The path for the second page';
}

function mymodule_page2_view() {
  $delay = 300;
  if (!empty($_SESSION['mymodule_page1_submitted_values']) && !empty($_SESSION['mymodule_page1_submission_timestamp'])) {
    $submitted_data = ($_SESSION['mymodule_page1_submission_timestamp'] > time() - $delay) ? $_SESSION['mymodule_page1_submitted_values'] : array();
    unset($_SESSION['mymodule_page1_submission_timestamp']);
    unset($_SESSION['mymodule_page1_submitted_values']);
  }

  // ...
}

```

I use `$_SESSION['mymodule_page1_submission_timestamp']` just to avoid the second page gets the values submitted on the form present in the first page more than 5 minutes before. If you don't want such restriction, then remove any reference to `$delay`.

You could also pass the values through the URL, but there is a restriction on the URL length the browsers can handle, and that restriction depends on the browser, as long as I know.

# Answer
> 1 votes
in your submit function , add your data in the redirect url.

```
function page_1_form_submit($form, &$form_state){
$data_a = $form_state['values']['data_a_form'];
$data_b = $form_state['values']['data_b_form'];

$options = array(
    'query' => array(
         'data_a' => $data_a,
         'data_b' => $data_b,
        )
    );

$form_state['redirect'] = array('url_page2', $options);
}

```

The redirection will be

```
 www.domaine.com/url_page2?data_a=XXX&data_b=YYYY;

```

In the page\_2 form, gather datas from $\_GET variable

```
$data_a = $_GET['data_a'];
$data_b = $_GET['data_b'];

```

Don't forget to check your datas, like is\_numeric, etc ...

---
Tags: forms
---


# Question
Title: If a Views Contextual Filter using PHP code doesn't resolve, can I make Views "Display all results"
Situation:

1. Contextual filter "Has taxonomy term by ID"
2. Filter is set to "Provide default value" \> "Type: PHP Code"
3. The PHP code resolves in most cases, but on some pages it shouldn't. In those cases I'd like to do what Views does when you choose the "Display all results for the specified field" option.

Is there something my PHP code can pass back to Views that will cause it to display all results?

(Or even 'Display contents of "No results found"' because then I could use a View inside there)

Config: Views 3, D7

# Answer
> 3 votes
when you want to show all then

```
return "all";

```

;)

---
Tags: views
---


# Question
Title: Drupals clean-urls (.htaccess) breaks with mass vhost
Apache has a nifty mass vhost feature. Problem is, when I use this to reach my site, clean-urls stop working. Is there a way to combine this with clean urls?

```
<Directory /var/www/localhost/htdocs>
  Order allow,deny
  Allow from all
  AllowOverride
</Directory>
UseCanonicalName Off
LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon
CustomLog /tmp/access_log vcommon
VirtualDocumentRoot /var/www/localhost/htdocs/%0/web
VirtualScriptAlias /var/www/localhost/htdocs/%0/web

```

Obviously I've attempted to add

```
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

```

to the \<Directory/\>, but that doesn't help.

# Answer
I had to add a slash before index.php to get this working for WordPress. Has to do with VirtualDocumentRoot not setting the DocumentRoot to the same value I guess.

`RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]`
> 2 votes

# Answer
Might want to checkout http://www.latenightpc.com/blog/archives/2007/09/05/a-couple-ways-to-debug-mod\_rewrite
> 1 votes

---
Tags: .htaccess
---


title: Programatically upload a page in D7

text:
# Question
Title: Programatically upload a page in D7
I'm certainly a noob, so sorry for this if it's very basic.

I had an installation of D6 and the following code was working perfectly. But when I upgraded to D7, the page was posted, but the body wasn't being uploaded. I see that the location of the body has changed in the MySQL structure, but how do I address it in the code? Here's what was working in D6:

```
    $node->name = rand();
$node->title = $content->title;
$node->created = time();
$node->status = 1; //published
$node->promote = 0;
$node->sticky = 0;
$node->body = $content->data;
$node->type = 'page';
//$node->path = $content->path;
$node->revision = 'true';
node_save($node);

```

Interestingly, when I try to specify the path, the node\_save returns an error, but when I specify body, it fires, but the body never shows up.

Can anyone help? I've spent a lot of time on this... much appreciated.

# Answer
```
<?php
//Create node
    $node = new StdClass();
    $node->type = 'game';
    $node->title = t('@date-@time', array('@date' => format_date($om__result->date, 'short'), '@time' => format_date($om__result->time, 'custom', "h:i A")));

    //Date
    $node->field_date = array(
      0 => array(
        'value' => format_date($om__result->date, 'short'),
      ),
    );

    //Location
    $node->field_location = array(
      0 => array(
        'value' => $om__result->location,
      ),
    );

    //Home team
    $node->field_home = array(
      0 => array(
        'value' => $om__result->home,
      ),
    );

    //Visitor
    $node->field_away = array(
      0 => array(
        'value' => $om__result->visitor,
      ),
    );

    //Division
    $node->field_divsion = array(
      0 => array(
        'value' => $om__result->divisoin,
      ),
    );

    //Program
    $node->field_program = array(
      0 => array(
        'value' => $om__result->program,
      ),
    );

    //Time
    $node->field_time = array(
      0 => array(
        'value' => $om__result->time,
      ),
    );

    //Field
    $node->field_number = array(
      0 => array(
        'value' => $om__result->field_nuber,
      ),
    );

    node_submit($node);
    node_save($node);
    drupal_set_message(t('@node has been created', array('@node' => $node->title)));
?>

```
> 1 votes

# Answer
In Drupal 7, there is one thing that changes: The node body is now a field created with the Field API. As consequence, the code should be changed to something similar to the following code.

```
  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title = $content->title;
  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $content->data;
  $node->body[$node->language][0]['summary'] = text_summary($content->data);

  // [1]
  $node->body[$node->language][0]['format']  = 'filtered_html';

  $node->path = array('alias' => $content->path);

  node_save($node);

```

The other node properties you are setting are set by node\_object\_prepare(). The line I commented with `[1]` is setting the input format to "Filtered HTML"; if you want to set a different input format for the node, filter\_formats() returns information about the currently enabled input formats, including the input format ID to use with `$node->body[$node->language][0]['format']`.
> 0 votes

---
Tags: nodes
---


title: How to let CAS handle session

text:
# Question
Title: How to let CAS handle session
I am using the phpCAS library and would like sessions to be handled by that library.

I am instantiating the client this way:

```
function my_module_init(){
    ...
    phpCAS::client(CAS_VERSION_2_0,'casdomain' , 8443, '/cas',true);
    ...
}

```

I have it in hook\_init() since I want to check for user authentication on each page load.

But I am getting this error.

> phpCAS error: phpCAS::client(): Another session was started before phpcas. Either disable the session handling for phpcas in the client() call or modify your application to leave session handling to phpcas

How can I get rid of this error and have phpCAS handle the session?

Thanks.

# Answer
1. Create a copy of session.inc in your modules folder. I named my mymodule.session.inc.
2. In mymodule.session.inc find the function drupal\_session\_initialize() and replace drupal\_session\_start() with the call to the of the CAS client constructor.
3. In your module's .install file set the location of mymodule.session.inc file

function mymodule\_install() { variable\_set('session\_inc', 'path/mymodule\_session.inc'); }

function mymodule\_uninstall() { variable\_del('session\_inc'); }

As a result Drupal will create the CAS client before any session is created.
> 1 votes

# Answer
Any reason why you are not using the module cas? It seems like a fairly stable module with over 5000 people using it. I would give that a shot before attempting any custom code in hook\_init().
> 1 votes

---
Tags: authentication-authorization
---


# Question
Title: Why would some backup schedules work and others not?
I have several backup schedules set up:

* Every 15 minutes (keeping 12)
* Every 8 hours (keeping 9)
* Daily Backup (keeping 31)
* Weekly Backup (keeping 52)
* Yearly Backup (keeping 5)

The perplexing problem is that some of them seem to be working and some not, even though they're all using the default profile, and they're all enabled, and they're all being saved to the scheduled backups directory.

Here are the backups that are appearing:

```
sitename-2012-11-10T18-10-05 Sat, 11/10/2012 - 18:10 25 min  311.12 KB
sitename-2012-11-10T18-03-58 Sat, 11/10/2012 - 18:03 31 min  305.58 KB
sitename-2012-11-10T17-48-49 Sat, 11/10/2012 - 17:48 46 min  308.19 KB
sitename-2012-11-10T16-43-06 Sat, 11/10/2012 - 16:43 1 hour  303.99 KB
sitename-2012-11-10T16-43-05 Sat, 11/10/2012 - 16:43 1 hour  303.99 KB
sitename-2012-11-10T15-43-02 Sat, 11/10/2012 - 15:43 2 hours 304.01 KB
sitename-2012-11-10T14-43-00 Sat, 11/10/2012 - 14:43 3 hours 303.99 KB
sitename-2012-11-10T13-38-00 Sat, 11/10/2012 - 13:38 4 hours 303.95 KB
sitename-2012-11-10T12-33-00 Sat, 11/10/2012 - 12:33 6 hours 303.95 KB
sitename-2012-11-10T11-28-01 Sat, 11/10/2012 - 11:28 7 hours 303.94 KB
sitename-2012-11-10T10-23-00 Sat, 11/10/2012 - 10:23 8 hours 303.95 KB
sitename-2012-11-10T09-18-02 Sat, 11/10/2012 - 09:18 9 hours 303.94 KB

```

The fact that there are 12 (which is the number mentioned in *one* of the schedules) makes me think that perhaps the Backup & Restore module has a major bug: perhaps it assumes you'll only have one or two schedules, and my 5 overwhelmed it.

Is there any other reason for the behavior you're seeing?

# Answer
By creating different destinations for each schedule, the problem goes away.

Apparently Backup & Migrate simply assumes each schedule has a separate destination (although the UI gives no hint that this would be the case, and in fact gives reason to expect that there's no problem with sharing a destination).

For instance, one of my schedules is set to keep 12 copies. Rather than keeping track of which backups belong to which schedule, it merely deletes all but the last 12 backups in the directory.

At any rate, isolating each backup allows everything to work as expected.
> 1 votes

---
Tags: 7, backups
---


# Question
Title: custom private message block generates error
I created a block to generate a private message link to send a message to all the users of a group. I use the php code as the text format on the block body.

```
<?php
$group = og_context();
$og_id = $group->gid;

$query = db_select("og_membership", "ogm");
$query->condition("ogm.gid", $og_id, "=");
$query->fields("ogm", array("entity_type", "etid"));
$result = $query->execute();

$result_tmp = $result->fetchAll();
$recipients = array();

foreach($result_tmp AS $tmem)
{
$recipients[] =  user_load($tmem->etid);
}

echo '<a href=/';
echo privatemsg_get_link($recipients,$account = array(),$subject = NULL);
echo '>Send message to ehood members</a>';
?>

```

When I use this, It created me a notice message saying -

> ```
> Notice: Trying to get property of non-object in privatemsg_user_access() (line 335 of /sites/all/modules/privatemsg/privatemsg.module).
> Notice: Trying to get property of non-object in privatemsg_user_access() (line 335 of /sites/all/modules/privatemsg/privatemsg.module).
>
> ```

Although it generated the link, It creates the error. I think its somehow related to how $account is mentioned ?

i tried to send global $user instead of $account, but still creates the same error.

# Answer
> 3 votes
In this case, the problem is that privatemsg\_get\_link() uses `array()` as default value for `$account`, but then uses the following code.

```
  if ($account == NULL) {
    global $user;
    $account = $user;
  }

```

The function should use `NULL` as default value for `$account`, in the same way user\_access() does.

```
function user_access($string, $account = NULL) {
  global $user;

  if (!isset($account)) {
    $account = $user;
  }

  // ...
}

```

The error message you see is because the function tries to access `$account->uid` when `$account` is an empty array. An array doesn't have properties, and that is what the message is saying.
As the function is passing that value to `user_access()`, the same error would be raised from `user_access()`, which check the value of `$account->uid`, and for which an empty array is not the correct value to pass to its `$account` parameter, which requires an user object, or `NULL`.

It's fine to use the default values a function has, but you should check what the function does when it gets the default values for its parameters.

It is wrong to call a function as `privatemsg_get_link($recipients, $account = array(), $subject = NULL)` when you want to use the default values for its parameters. Just call the function as `privatemsg_get_link($recipients)`. With your code, you are setting `$account` to an empty array, and passing `$account` as parameter.
PHP doesn't have named parameters, but only positional parameters. If it had named parameters, it would be possible to call a function indifferently as `functioname(34, param3 = 4, param2 = 12)`, or `functioname(34, param2 = 12, param3 = 4)`.

# Answer
> 0 votes
`privatemsg_get_link($recipients,$account = array(),$subject = NULL);` is not the proper way to call a function. You should be passing in values for $account and $subject, not using what the function defines as default values. Consider this:

```
<?php
$group = og_context();
$og_id = $group->gid;

... more code ...

global $user
privatemsg_get_link($recipients, $user, 'Some subject line');
?>

```

When a function defines default values, like

```
function my_cool_function($array = array()) {
  // If the array passed to the function is empty, or if an array WASN'T passed...
  if ($array == NULL ) {
    // Create one.
    $array = array('some cool stuff');
  }
}

```

you shouldn't pass in the same default values, but rather real ones.

Also, I would verify that user\_load() returned a valid user object before passing it along. What if it returned FALSE as it couldn't load a user? Something like:

```
if ($account = user_load($row->etid)) {
  $recipients[] = $account;
}

```

**Protip!** You don't have to run `->fetchAll()` on a db\_select object if you've just run `->execute()` – you could just do

```
$result = db_select('table', 't')->fields('t', array('id'))->execute();
foreach ($result as $row) {
  print $row->id;
}

```

The fetchAll() method, among other fetch methods, is very useful if you're passing data around or using it in other ways, but if you're just iterating in a foreach() loop you don't need it.

Post back here if none of this solves the issue and I'll revise my answer. Also, do the community a favor and revise your question title to be more of a question, including the "pivatemsg" module (or whatever it's called) since this questions is explicitly regarding that module.

---
Tags: blocks, privatemsg
---


# Question
Title: How to group multiple blocks into one big block
I have a website with Drupal 7 and the customer just asked to make it "responsive design".

I need, for the design to respond correctly, to group some blocks I already have into some bigger blocks, on which i can apply the specific classes I need.

Region aren't valid for me because the website is already built and it would be really messy to change it just to add regions.

Any ideas?

Thanks

# Answer
Block Group module may help you

> This module extends the standard drupal block system with block groups. Each block group provides a new block as well as a corresponding region. Child blocks can be moved into any group region. The position and the settings of the parent block are propagated to its children. Also block groups are nestable.

Take a look. I am not sure how it will integrate with responsive style.
> 4 votes

---
Tags: blocks, theming
---


title: Setup CAPTCHA in Content Types

text:
# Question
Title: Setup CAPTCHA in Content Types
i have configured captcha module in my drupal 7 site.. but can't understand how to show a captcha in content type, so that while adding content user will have to complete the captcha.

# Answer
> 8 votes
Please check README.txt of the captcha module.

> The configuration page is at admin/config/people/captcha,
> where you can configure the CAPTCHA
> module and enable challenges for the desired forms. You can also
> tweak the image CAPTCHA to your liking.

1. Go to the configuration page - **admin/config/people/captcha**
2. Select the **Default challenge type** \- Math or Image
3. In the form list, you can define which form has CAPTCHA, for example if you want to have it on the register form, select a challenge type (Math or Image) for the FORM\_ID **user\_register\_form**

If you want to add CAPTCHA to a content type, for example, **blog**, add a new FORM\_ID "**blog\_node\_form**" and click "Save Configuration".

By default, you will not see CAPTCHA on each form when you logged in as administrator, but you can change the option in the configuration page.

---
Tags: 7, captcha
---


# Question
Title: how to resolve ubercart checkout IE Issue?
I am using Drupal 6. While checking out with IE 7 or 8, users get stuck in a loop; when they click on

they are redirect to

When users click on the submit button, they are again redirected to the review order page, as in the first image. When I searched on drupal.org, I found a "fix in Ubercart Webform Checkout Pane" module, but I am not using it.

It is working fine on Firefox and Google Chrome.

Do you have any suggestion?

# Answer
> 0 votes
I fixed this issue by blocking java-script (some java-script file) on page.tpl for this page and found this is working. the issue was i am using fancy box for my site which was loaded on all pages, and ubercart already have this so there was conflict in java-script.

---
Tags: ubercart
---


# Question
Title: Alternative to "Vote Up Down" module for?
Is there any other module like vote\_up\_down, but for Drupal 7? This one has a development version but as the author says it is unstable.

> 7.x (unstable, on development, do not use this version for production)

# Answer
Use the Fivestar module for rating. Or the Rate module. Some more details about these modules (quotes included are from their project pages):

* Fivestar:

> ... adds a clean, attractive voting widget to nodes and comments and any entity. It features:
>
> + jQuery rollover effects and AJAX no-reload voting
>     + Configurable star sets
>     + Graceful degradation to an HTML rating form when JavaScript is turned off
>     + Support for anonymous voters
>     + Spam protection to keep users from filling your DB with bogus votes
>     + Easy-to-use integration with Views module for lists sorted by rating, or filtered by min/max ratings
>     + A Fivestar CCK field for use in custom node types
>     + An easy-to-use Form API element type for use in other modules
>     + Compatible with all versions of jQuery (1.0 - 1.8)
* Rate:

> ... provides flexible voting widgets for nodes and comments. "*The cck model for voting with Drupal*".
> 5 votes

---
Tags: 7
---


# Question
Title: How to create landing pages and Main Menu based on taxonomy
I'm trying to build a website for a non-profit which has multiple locations (~6) besides the headquarters.

The frontpage needs to be generic for the whole organization and will contain content from all locations.

However, each location needs have its own page ( not only the content part but also the main menu and the header etc.) and all the content(nodes etc.) associated with this location should use the same page template associated with this location. So I've created a taxonomy term for each location and tried to use template suggestions based on the term but it didn't work.

So far I was successful creating a panel page with its own path (such as website.org/headquarters) for each location and show content only for that location by filtering via the taxonomy term but no luck for having custom main menu or custom node pages for the location.

Is there something trivial that I'm missing or is there no easy solution for this?

Thanks,

# Answer
> 0 votes
This seems like the perfect use case for Organic Groups

> Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.
>
> They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.

There is also a kick-ass set of tutorial videos from BuildAModule here that should help you set it up.

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


title: jquery code for drupal 6

text:
# Question
Title: jquery code for drupal 6
I try to implement this simple js tooltip script on drupal 6 site.

http://jsfiddle.net/wrN2u/50/

```
$(document).ready(function(){

$('#container').on('mouseenter', '#radiobtn', showBox);
$('#container').on('mouseleave', '#radiobtn', hideBox);

function showBox(e){
var x = e.pageX + 20;
var y = e.pageY + 20;
$('#hoverbox').fadeIn();
$('#hoverbox').offset({ left: x, top: y });
}
});
function hideBox(){
$('#hoverbox').fadeOut();
}

```

However, the framework is 1.8.2 The script is not working under 1.3.2 which uses drupal 6 Can somebody help me with js code for 1.3.2?

Thank you very much

# Answer
> 1 votes
if you don't want to upgrade the jQuery version. Please try this.

http://jsfiddle.net/ravindrasingh22/3HVpW/

```
$(document).ready(function() {

    var changeTooltipPosition = function(event) {
      var tooltipX = event.pageX - 8;
      var tooltipY = event.pageY + 8;
      $('div.tooltip').css({top: tooltipY, left: tooltipX});
    };

    var showTooltip = function(event) {
      $('div.tooltip').remove();
      $('<div class="tooltip">I\' am tooltips! tooltips! tooltips! :)</div>')
            .appendTo('body');
      changeTooltipPosition(event);
    };

    var hideTooltip = function() {
       $('div.tooltip').remove();
    };

    $("label#tooltip2'").bind({
       mousemove : changeTooltipPosition,
       mouseenter : showTooltip,
       mouseleave: hideTooltip
    });
});

```

HTML Code

```
<label id="tooltip2">Mouse Hover here</label>

```

CSS Code

```
#hint{
     cursor:pointer;
    }
    .tooltip{
        margin:8px;
        padding:8px;
        border:1px solid blue;
        background-color:yellow;
        position: absolute;
        z-index: 2;
    }

```

# Answer
> 0 votes
I would suggest you to add the latest jQuery library to your site. You can do that by:

1. Copying the jQuery library to your theme's JS folder.
2. Then modifying the `.info` file of the theme and adding the following line to it:
`scripts[] = JS/jquery-1.8.2.js`. Do this if you want to use the same library throughout your project. **OR**
3. If you want to use it for some particular scenario (in custom module, for example) you can use `drupal_add_js()` function to do that.
`drupal_add_js(drupal_get_path('theme', 'your_custom_theme') . '/JS/jquery-1.8.2.js');`

# Answer
> 0 votes
With jQuery 1.3.2 you can't use `on()` (or even `delegate()`) so you're left with the `live()` method:

```
$('#radiobtn').live('mouseenter', showBox).live('mouseleave', hideBox);

```

At first glance I can't see anything else that would need to change.

---
Tags: 6, javascript
---


# Question
Title: How to enable revisioning for user photo (user/profile field)?
I want to moderate pictures, uploaded as user avatars. So, I need:

1. History for user field “Photo” to see all previous photoes.
2. UI for accepting or declining new photo.

How can I implement it?

# Answer
The User Revision module would probably be your best bet

> Add revision support to users and fields like there is for nodes.
>
> For the moment all field from {users} have revisions, except for password

The picture property is contained in the `users` table so this module should do exactly what you're looking for.

The issue of a UI for accepting or declining a photo should go in another question otherwise this one will become too localised.
> 1 votes

---
Tags: media, files, nodes
---


# Question
Title: How do you rename the "save" comment button?
Does anyone know how to rename the "save" comment button? I am trying to change it to "Post". I am using Drupal 7 and the Zen sub theme.

# Answer
For Drupal 7, you need to create a custom module that implements `hook_form_FORM_ID_alter()` using code similar to the following one (replace "mymodule" with the short name of the module you are writing):

```
function mymodule_form_comment_form_alter(&$form, &$form_state) {
  if (isset($form['actions']['submit'])) {
    $form['actions']['submit']['#value'] = t('Post');
  }
}

```

comment\_form() uses the following code, to define the form buttons:

```
  // Only show the save button if comment previews are optional or if we are
  // already previewing the submission.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#access' => ($comment->cid && user_access('administer comments')) || variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || isset($form_state['comment_preview']),
    '#weight' => 19,
  );
  $form['actions']['preview'] = array(
    '#type' => 'submit',
    '#value' => t('Preview'),
    '#access' => (variable_get('comment_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED),
    '#weight' => 20,
    '#submit' => array('comment_form_build_preview'),

```

For Drupal 6, the code should be the following one:

```
function mymodule_form_comment_form_alter(&$form, &$form_state) {
  if (isset($form['submit'])) {
    $form['submit']['#value'] = t('Post');
  }
}

```

I added the `if (isset($form['submit'])) {}` part because in Drupal 6, `comment_form()` defines the form buttons using the following code, and the button you are trying to change could not be present in the form.

```
  // Only show save button if preview is optional or if we are in preview mode.
  // We show the save button in preview mode even if there are form errors so that
  // optional form elements (e.g., captcha) can be updated in preview mode.
  if (!form_get_errors() && ((variable_get('comment_preview_' . $node->type, COMMENT_PREVIEW_REQUIRED) == COMMENT_PREVIEW_OPTIONAL) || ($op == t('Preview')) || ($op == t('Save')))) {
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
      '#weight' => 19,
    );
  }

  $form['preview'] = array(
    '#type' => 'button',
    '#value' => t('Preview'),
    '#weight' => 20,
  );

```
> 19 votes

# Answer
I prefer using `hook_form_alter` vs String Overrides.

```
function YOURMODULENAME_form_comment_form_alter(&$form, &$form_state) {
  $form['buttons']['submit']['#value'] = 'Submit Comment'; //Your text for the submit button goes here.
};

```
> 2 votes

# Answer
For Drupal 6, the answers above suggesting using `hook_form_alter` will **not** work, although you'd think it would. Typically you'd do this like:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ('comment_form' == $form_id) {
    $form['submit']['#value'] = t('Post');
  }
}

```

While this appears to work, and you'll see a button with text 'Post', in fact you'll find two problems:

1. If your site is set up to force preview of comments before saving, you'll find that the 'Post' button is added to the initial comment form, where there should be only the 'Preview' button. This is easily fixed, though.
2. Your new 'Post' button won't actually submit the form - D6 comment.module looks for the button value to do its logic, and if you change it to something other than 'Save' this breaks the submit logic.

To actually make this work you'd need to hide the button and use a custom form submit handler. If I do that I'll return here and post working code.
> 2 votes

# Answer
No need for custom module or using the string overrides module. In your settings.php, around line 416, uncomment and modify the following using your overrides:

```
/**
String overrides:

To override specific strings on your site with or without enabling locale
module, add an entry to this list. This functionality allows you to change
 * a small number of your site's default English language interface strings.
 *
 * Remove the leading hash signs to enable.
 */
# $conf['locale_custom_strings_en'][''] = array(
#   'forum'      => 'Discussion board',
#   '@count min' => '@count minutes',
# );

```
> 1 votes

# Answer
As Andy Laken mentioned above

> ...new 'Post' button won't actually submit the form...

How to fix this:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'comment_form') {
    // Rename submit button.
    $form['submit']['#value'] = t('Post');
    // Add new form validator.
    array_unshift($form['#validate'], 'MYMODULE_comment_form_validate');
  }
}

function MYMODULE_comment_form_validate(&$form, &$form_state) {
  // Restore native value.
  if ($form_state['values']['op'] === t('Post')) {
    $form['submit']['#value'] = t('Save');
    $form_state['values']['op'] = t('Save');
  }
}

```

That's it! Your validate function goes first and comment module will process form with native submit value.
> 1 votes

---
Tags: 7, comments
---


title: User password valid only for one day

text:
# Question
Title: User password valid only for one day
When users forget their password they click on the reset password link. There, they enter their username, or password, and a mail goes to their inbox, instructing them on what to do.

The instructions say to follow a link that resets the password, and then redirects them to their user profile to enter a new password. Although they enter a new password, the next day (and everyday) the system doesn't recognize the password, and they have to reset it again.

Why does this happen?

How does the "reset password" work? Does it check the access date to see if the day has changed, or does it use some kind of flag to let the system know the password is valid only for one day?

# Answer
Finally the problem in my case had to do with the text that was sent with mail after user registration. When user was registered a mail was sent in his inbox with his username and a (system created) password. Then the text was providing a link to the login page, a second one linking to the auto log in page (where the user supposedly would not have to enter his password) and a third one that it is irrelevant.

So i realized that the second link was actually a link to reset your password if you forget the old one. So the user when first reading the mail he click on the second link to log in automatically but he doesn't know that the password given to him was reseted and now his log in was valid only for one day or for one use. Each time he has to reset his password.

Anyway if you have access to your database you can experiment to see if it is another issue for you. You can create a fake account in drupal. In the mail that is sent to you click the second link (something like http://mysite.com/foo/user/reset/1085/1349294892/7bc9baf9d42aa774be00a0f36090323f). Then go to table 'user' of the drupal database, find the fake user you created and modify the record of the column 'created' and put a unix-timestamp older than a day (there are online unix-timestamp creator). This way you can experiment if the password is temporary or not.
> 3 votes

---
Tags: users
---


title: How to archive drupal forums?

text:
# Question
Title: How to archive drupal forums?
How can I add archive state to drupal forums so that:

> * They are not visible in search results
> * They are shown in a different container
> * They are visible only to some users based on user-roles

I don't want to unpublish them-

I also want a spam state to differentiate unpublished and spam posts

# Answer
> 0 votes
* They are not visible in search results

http://drupal.org/project/search\_config

* They are shown in a different container

Templating system, or blocks, or panels

* They are visible only to some users based on user-roles

**EDIT**

Those 2 steps are equal, but becose my understanding problem the last point can be different.

In `/admin/people/permissions` you should have the options to allow only some roles to access the forms nodes.

---
Tags: 7, nodes
---


# Question
Title: node/add page shows 2 of every type. How do I fix this?
My node/add page (Add Content) shows two of every content type!

Here is a screenshot:

I am 99% sure this is is a database problem, but my database node\_type table looks OK and only has one of each type.

I have disabled every module I could, updated everything, and have no errors in the log.

When I point my installation at a fresh database I do not have the problem. When I point a fresh Drupal installation at my current database I do have the problem. It seems like database to me.

Using Drupal 7.15.

Any idea on how to fix this?

# Answer
I've fixed it.

The problem was that the table menu\_links had duplicates in it for the content types. How they got there, I have no idea.

The fix is to find the menu\_links table using phpMyAdmin and search for the links there were duplicates of (title link\_field using LIKE %...% operator). Then simply, drop them from the table. The reason is because the node/add page is just a page (or Overlay) view of the items in the "Add content" menu.
> 2 votes

# Answer
I'm facing the same issue but solved it by following these steps.

Go to *admin/structure/menu/manage/navigation* and check the links, if links are duplicated there then delete one of the duplicates.
> 2 votes

# Answer
I think they are duplicated in your database. see contents of `node_type` table in your database, and remove duplicated record.
> 0 votes

---
Tags: nodes, users
---


# Question
Title: Automatic Validation Using drupal_form_submit
I have a content type (call it my\_type) with some required fields. One of the fields uses the email module, so if I try and create a my\_type node using Drupal's built in node create page and I put 'notanemail' as the email address, the node will not be created and I get an error saying 'notanemail is not a valid email address'.

When I make a node programmatically using drupal\_form\_submit, it does not do the validation and the node is made even though I put incorrect values in fields.

I don't want to implement hook\_validate if I can avoid it. I would rather use the build-in validation. Is this possible?

# Answer
Field validation is made only against node form submission, so you need to imitate this in your code.

If you are using Drupal 6, try this solution:https://stackoverflow.com/a/6471821/1387163

For Drupal 7 solution can as following:

```
$node = new StdClass();

$node->type = 'my_type';
node_object_prepare($node);

// assign node field values here ...

$form_state = array (
  'node' => $node,
  'values' => (array)$node,
);
$form = drupal_get_form($node->type. '_node_form', $node);

node_form_validate($form, $form_state);

$errors = form_get_errors();

if ($errors) {
   // ...
} else {
   // ...
}

```
> 0 votes

---
Tags: nodes, forms
---


# Question
Title: Getting an email notification when a new Drush version is available
With standard Drupal modules, you get an email notification when there's an updated version.

How can we have this option with Drush?

I searched the official http://drush.org website and unfortunately there's no mailing list or RSS feed so that we know when there's a new version of Drush out.

# Answer
> 4 votes
If you go to the Drush project page on Drupal.org then you can follow the "Releases" RSS feed found at the bottom of the page.

**EDIT**

You can also use the IFTTT.com service if you want the e-mails. Just set up a rule on the site so that when the RSS feed gets updated, it sends you an e-mail.

---
Tags: drush
---


# Question
Title: Changing the text "Add to Comment" in a given content type
I have a pretty frustrating problem going on here. I have been reading the answers over at this question: How to change "add to comment" in comment form?.

But unfortunately neither of the suggested solutions worked for me. I tried with the following code in `template.php`:

```
function custom_node_view_alter(&$build) {
  if ($build['#node']->type == 'bar') {  //extra check for content type (optional)
    $build['links']['comment']['#links']['comment-add']['title'] = t('Add new review');
  }
  kpr($build);
  dsm($build['#node']->type == 'bar'); // true
}

```

I've also tried adding `comment-wrapper-<my content type>.tpl.php` to `sites/all/themes/custom/templates` but its not picking up either of these changes.

I've flushed all my caches so many times I'm getting RSI, but it's not showing the change. Am I missing something simple here?

# Answer
> 1 votes
You missed a key `['title']` in the array.

```
$build['links']['comment']['#links']['comment-add']['title'] = t('Add new review');

```

Make sure you follow the naming conventions while creating a custom module, or if you are doing it from theme replace the `custom` from `custom_node_view_alter` with the theme name (e.g. `garland_node_view_alter` for garland theme).

You can eliminate the extra check (for a while) of the content type for a while to check if the solution is working.

---
Tags: comments
---


# Question
Title: Notice: Undefined index: allowed_values in list_allowed_values()
I am getting this error

```
Notice: Undefined index: allowed_values_function in list_allowed_values() (line 239 of /var/www/html/drupal/modules/field/modules/list/list.module).
Notice: Undefined index: allowed_values in list_allowed_values() (line 248 of /var/www/html/drupal/modules/field/modules/list/list.module).
Notice: Undefined index: allowed_values_function in list_allowed_values() (line 239 of /var/www/html/drupal/modules/field/modules/list/list.module).
Notice: Undefined index: allowed_values in list_allowed_values() (line 248 of /var/www/html/drupal/modules/field/modules/list/list.module).

```

In my view I have added filters "a" and "b".

In content type "a" is list(text) with default value none. and "b" is also list(text) with default value none.

If default value is not none then I am not getting the notice.

I want the default value to be none for the fields.

What should be done so that these "Notice" do not appear.

# Answer
I had the same problem. I had deleted a field which was being referenced in a view. I deleted the field from the View and it resolved the problem.

Also if you are still seeing the notice try clearing the Views cache at *admin/structure/views/settings/advanced*
> 2 votes

# Answer
This can happen if you delete a field from the definition of a custom content type and that field is still referenced by a View. Even if you added a new field with the same name as the one you deleted the problem will persist. You need to remove the old field from the View definition and then add the new field to the View.
> 3 votes

---
Tags: 7, views
---


# Question
Title: Can I edit theme CSS without FTP access to the files?
Can I edit Drupal theme CSS files with out the ability to download/upload css files using FTP?

# Answer
Without server access of some description either via FTP or SSH (for example) - you can't edit the files.

You could, however, try CSS Injector if you are able to install modules through the UI.

> Allows administrators to inject CSS into the page output based on configurable rules. It's useful for adding simple CSS tweaks without modifying a site's official theme -- for example, a 'nighttime' color scheme could be added during certain hours. The CSS is added using Drupal's standard drupal\_add\_css() function and respects page caching, etc.
> 3 votes

---
Tags: 7, theming
---