title: Alter login form redirect doesn't work

text:
# Question
Title: Alter login form redirect doesn't work
I have user login block on custom page, I try:

```
if ($form_id == 'user_login_block') {

    $form['#redirect'] = '/';//or <front>

}

```

But I am redirecting always to the same page.

# Answer
> 4 votes
The user login block form is a special case. You will see that in the #action property, it defaults to /node?destination=node. The "destination" is the important piece, as it will override many of the normal avenues you would take to redirect the form including a $form\_state\['redirect'\] in a submit handler. The code below is an example of how you can redirect the user\_login\_block form by modifying the #action property.

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ('user_login_block' == $form_id) {
    $path = 'path/i/am/redirecting/to';
    $form['#action'] = url($_GET['q'], array('query' => array('destination' => $path)));
  }
}

```

Also, take a look at hook\_form\_FORM\_ID\_alter(), which is the preferred method for altering the form for performance reasons.

---
Tags: 6, forms, users
---


title: How to theme the maintenance mode page?

text:
# Question
Title: How to theme the maintenance mode page?
What would be the best practice for theming the maintenance mode page in Drupal 7?

# Answer
You can edit or create a "maintenance-page.tpl.php" file in your theme directory and edit that to theme your maintenance page.

You can view the source on the Drupal API page
> 7 votes

# Answer
In drupal 7

The system include a default template that is located here: **/modules/system/maintenance-page.tpl.php** Now you can copy this file into your theme templates directory and modify maintenance.tpl.php or rewrite that file in your way. Than you must modify your settings.php file to instruct the system to display your template. You can enabling the $conf variable and adding the internal name of your theme:

$conf\['maintenance\_theme'\] = 'themename';

When database failure there is a particular template avaible: **maintenance-page--offline.tpl.php**
> 7 votes

---
Tags: 7, theming, maintenance-mode
---


# Question
Title: What's better to do when we create a new site project?
I need an advice about beginning a new project layout in Drupal 7. Do you think it is better starting with a basic theme, or creating from zero the project with theme of mine? I think it is probably better to begin with a basic theme also for the CSS styles that are compatible with all the browsers

What do you say?

# Answer
It depends on your site and the needs of your client, but it is probably best to start with an easy base theme and then start theming on top of that.

Some good basic base themes are:
Omega \- Best used for responsive HTML5 designs
Zen \- Good basic starter theme
960gs \- Good if you need to use a grid format.

Also, you might want to grab some other themes for administration.

Recommended administration themes:
Rubik \- Clean administrative interface
Admin \- Adds a toolbar at the top of the site, which makes Drupal easier to manage
> 2 votes

---
Tags: theming
---


title: Insert urls on content body

text:
# Question
Title: Insert urls on content body
Is there any way to insert path to images or links on a content without hard coding it? Our development environment and our production environement have different base paths so the base path of the images and links must not be hard coded.

# Answer
Try using the Pathologic module to help with this. Excerpt from the documentation...

Rule Order

Note that the order in which you include the rules may be important. In a scenario with three servers (for example, development on http://local.example.com/drupal, testing on http://example.com/drupal, and production on http://example.com) and using a WYSIWYG editor (as noted below), the following rules (paths to be matched) will work in order:

http://local.example.com/drupal/
http://local.example.com/
http://example.com/drupal/
http://example.com/
/drupal/
/

Pathologic works by stripping out the path as defined above and ensuring that what remains will work as a path relative to the site's $base\_url (the URL you see in the location bar when looking at your page), no matter which server it is on. It works down the list in order and only applies the first rule that matches a given link. Placing http://local.example.com first in the list, for instance, will rewrite http://local.example.com/drupal/about as /drupal/about, and this will NOT be rewritten further by the /drupal/ rule, so all possible permutations should be included in order of deepest to shallowest matching path. Some of the example rules may not be necessary for your situation, but it is safe to include even unlikely paths that you would like corrected (removed).

Now sit back and enjoy the fruits of Pathologic’s labor."
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Is there a nodecomment equivalent/replacement for D7?
When I build help ticket systems for folks on D6, I use one content type for the ticket and a second content type with Nodecomment for replies. This lets me ensure that only the ticket owner and the internal helpdesk can see ticket history, and keep internal-only notes unpublished (vs no ability for internal notes with a comment).

Is there an equivalent for this in D7, or a better approach to take with contrib, or do I need to write a custom module to handle this?

# Answer
@Chris You started me down the right path, thanks so much! I've tested and can implement it this way without writing any custom code:

* Create 3 content types: Helpdesk Ticket, Ticket Internal Note, Ticket External Note.
* Create a role called Helpdesk Volunteer.
* Put a node reference field on Ticket Internal Note and Ticket External Note using the node reference URL widget.
* Use the Content Access module (currently still in dev) to restrict view/edit/delete of the Ticket Internal Note content type to users in the Helpdesk Volunteer role.
* Create a view with EVA that attaches to the Helpdesk Ticket content type, set to display both internal and external notes.

Afterwards, it's just a touch of prettification and theming as needed. Add a file attachment upload field and a ticket category. Maybe implement messaging/notifications to have email notifications and reply-by-email. Fully functional helpdesk on D7!
> 1 votes

# Answer
This might be stretching it a bit, but it seems you could achieve this level of access by using the Comment Access module. The node owner would have the "approve comments on own $type" permission, and the internal helpdesk would have the "administer comments" permission. The fallbacks of this approach are that the internal helpdesk would have access to administer all comments on the site even if they were outside the ticketing system, and the ability to approve / delete comments would have to be hidden so the the comments remain unpublished.
> 0 votes

# Answer
You could also go the route of adding a node reference field to the "reply" content type and leverage the node privacy byrole module for access to the ticket. At the time of this response it only has a 7.x-1.x version available, however it has a very small code base which means it should be easier to finish a port to 7. That way you could have a View that displays the ticket node by adding a contextual filter pulling from the node ID that validates whether the user has access to the node. Then you would create an attachment display showing all responses related to the ticket so the list would show right underneath the ticket as if it were a list of comments.

You would probably have to write some glue code to pre-populate the nodereference value and hide it from the form. There are probably some other small tweaks you would have to do as well to ensure the system flows nicely from the end user's standpoint. Not a quick win at all, but another way to approach it.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: A custom template file is not properly rendered
I know this issue is covered quite well, but at the moment I'm really perplexed on this.

First, I'm using the Zen theme. In my template folder I've created page-music.tpl.php, page-gallery.tpl.php, page-bio.tpl.php, page-front.tpl.php, and so on. I've tried putting the code in the template.php for the custom pages, but I can't redefine the `zen_preprocess_page()` function. The custom pages won't render the admin menu module, or display the modules properly for that matter. The JavaScript code is all funky.

I'm not sure if I'm using the right code for the the template.php. There seems to be a lot of jumbled imformation on this matter.

# Answer
If you have path like `contact` then the `page-contact.tpl.php` will be automatically available (view the theming documentation).

You can also declare your own tpl with this code (put this in a custom.module):

```
function custom_menu() {
  $items = array();
  $items['contact'] = array(
    'title' => 'Contact us',
    'page callback' => 'custom_make_section',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function custom_make_section() {
  return;
}

```

Also a little bit easier is using the module Empty Page in order to create the custom paths you want and then these paths will provide the page-....tpl.php you need.
> 2 votes

---
Tags: 6, theming
---


# Question
Title: Which webform hook and how use to set programmatically webform target email?
First part as in title and how to detect different webforms?

Ex. function name - hook\_webform\_submission\_actions

Replace 'webform' with form id?

# Answer
If you just want to customize the target email, webform do this quite easily.
Go to `node/123/webform/emails` (where 123 is you nid) and there you can configure the recipients.
The option "component value" allows you for example to set the email regarding a select list. Configure a select list for the subject, put these values in the option textarea:

```
contact@example.com|General inquiries
marketing@example.com|Marketing

```

Then when the user will use webform the email will be sent to the direction chosen in the subject list.

If you want something more advanced, have a look at my previous answer in "pass cck email value to webform block". This will help you to detect different webform (using hook\_form\_alter.
> 3 votes

---
Tags: 6, webforms
---


# Question
Title: Input formats and WYSIWYG editor problem
I have install 2 editor: YUI and TinyMCE

But wysiwyg settings are:

Why I can't setup editor on this input formats?

# Answer
> 2 votes
Check your permission page, and make sure you have the right permissions. Also make sure there is no conflicting permissions

# Answer
> 1 votes
you need to set this in the editor settings, not under input formats. hope this helps.

# Answer
> 1 votes
In Drupal 6 you need to go to admin/settings/wysiwyg to edit these.

This image in front is a clean installation of Drupal 6 , viewing it as admin (user 1), and only having the WYSIWYG module and TimyMCE & YUI libraries installed.

You also need to have the user permission of 'administer filters'. If your screen doesn't look like the example then maybe another module is causing a permission issue (another permission might be needed to be added) or something is corrupt.

---
Tags: 6, input-formats, wysiwyg
---


# Question
Title: What are the problems with merging DB dumps?
A strategy I've used with ExpressionEngine for managing the CMS in different environments is to use Git to merge the DBs of my dev and live environments when I need to deploy something new to live. This is working really well for me, my users are creating content but I can code without fear at the same time.

I see comments here and here that make it seem like the same is not true for Drupal 6. Is this just a question of the size of the database (which I think I could cater for by ignoring certain tables), or are there other concerns?

# Answer
If you use Git to version DB dumps and merge dumps from dev. and live, you can also do that with Drupal. But the Drupal DB schema is dynamic, new modules add new tables and some configuration (mainly CCK) changes can add or remove columns or rename tables. Because of this, handling (configuration) changes with DB dumps merge is hard and error prone. That's why alternative methods like Features-driven workflow are recommended to manage (configuration) changes management between multiple environments.

See also The Development -\> Staging -\> Production Workflow Problem in Drupal and the Code driven development: using Features effectively in Drupal 6 and 7 presentations.
> 2 votes

---
Tags: 6
---


# Question
Title: How can I do the dynamic select in Drupal 7 forms?
In the following code I call the function players() which returns array of values for option. This values were defined beforehand by hand. How can I load it dynamically from the database?

```
 $form['officers']['officer'] = array(
'#title' => t('Select the officer'),
'#type' => 'select',
'#description' => t('Please, select the officer'),
'#options' => players(),
'#multiple' => FALSE,
'#empty_value' => ' ',
'#empty_option' => '- None -',

```

);

For example in the "Text Field" there is property #autocomplete which defines a path where Drupal’s automatically included JavaScript will send HTTP requests using jQuery.

```
 $form['team_name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#description' => t('Please, insert your name'),
'#autocomplete_path' => 'autofillform/teamname' ,

```

); And i created the module which handles it.

```
<?php
function autofillform_menu() {
$items['autofillform/teamname'] = array(
'title' => 'Example autocomplete',
'page callback' => 'autofillform_teamname',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
 );
 return $items;
 }
 function autofillform_teamname($string){
 $matches = array();
 $result = db_query("SELECT name FROM users where lower(name) like '".$string."%'  LIMIT 10");
 foreach ($result as $user) {
 $matches[$user->name] = check_plain($user->name);
  }
 print drupal_json_encode($matches);
 return;
 }

```

Are there any possibility to do the same with "Select" ?

# Answer
> 1 votes
In any case take a look at the first answer of this question: i think it's what you are lloking for https://stackoverflow.com/questions/5158744/drupal-7-best-practice-for-a-dynamic-select-list-in-drupal-7

---
Tags: javascript
---


# Question
Title: Using Drush to update Drupal 6 core on multisite installation
I'm running multiple sites on a single Drupal 6 installation. I'd like to use drush to update Drupal core to the latest version without having to unlock update.php via settings for each site and then going to update.php for each of the different urls (there are over 10 sites).

Is there a drush command to update drupal core and run update.php for all sites at once?

# Answer
> 1 votes
There's no one single command to do it but we use a bash script that follows this pattern:

1. ls sites folder for all directories
2. pass resulting output to `drush -l $variable sql-dump > /home/user/backup/$variable.sql`
3. pass resulting output to `drush -l $variable updb --yes`

Hope this helps.

---
Tags: 6, drush, multi-sites
---


title: user_save() returns FALSE

text:
# Question
Title: user_save() returns FALSE
I am trying to use user\_save api. i have passed the following object ($user)

```
object(stdClass)#30 (6) {
  ["name"]=>
  string(12) "user_name"
  ["mail"]=>
  string(22) "myemail@gmail.com"
  ["pass"]=>
  int(1311514302)
  ["created"]=>
  int(1311514302)
  ["status"]=>
  int(1)
  ["roles"]=>
  array(1) {
    [0]=>
    string(10) "OauthUsers"
  }
}

```

I have used the following function:

```
$user = new stdClass();
$user->name = $userdata['name'];
$user->mail = $userdata['email'];
$user->pass = time();
$user->created = time();
$user->status = 1;
$user->roles = array('OauthUsers');
user_save($user);

```

I have tried to drop the "roles" property as well, but in all the cases user\_save() returns `FALSE`.

Do you have any idea of what I am doing wrong?

# Answer
> 5 votes
UPDATED:

If you are going to create new users using `user_save()` then follow the following syntax.

```
$user = array(
   'name' => $userdata['name'],
   'mail' => $userdata['mail'],
   'init' => $userdata['mail'],
   'pass' => user_password(8),
);

```

Now call the function `user_save()` and pass the user info as second arg.

```
$account = user_save(null, $user);
if($account){
     _user_mail_notify('register_admin_created', $account);
}

```

To update values for already saved user.

```
$account = user_load(array('uid' => $userdata['uid']));
$updates = array(
    'pass' => user_password(),
    'name' => 'new_name',
    'roles' => array(
        <rid> => '<role title>';
    ),
);

user_save($account, $updates);

```

---
Tags: users
---


# Question
Title: Does you know how the CCK Private Fields module works? Any API?
Do you know how the CCK Private Fields module works?
What I'm interested in is having a user who can switch all their content profile fields to private.

Is there an API that I can call to switch all the user's content profile fields to private?
Is there any better way to have a user opt-out and become basically an invisible user?
The definition I'm getting for opt-out is to never display the user in any search, browse or page.

# Answer
> 1 votes
Looking at the description page of this module, it seems that user can do what you want:

> Overview:
>
> This module allows users to mark administrator selected CCK fields as Public (visible to everyone), Hidden (visible to node author, hidden from everyone else) or Private (visible to node author and "friends"; see requirements section below).

Regarding the option to "disappear" a user, I'm not really sure as there's a lot of place where a user can appear, however if you give this user a certain role, you can customize your views to exclude users with this role.

---
Tags: entities, users
---


title: How do I receive security updates?

text:
# Question
Title: How do I receive security updates?
On my client(s) website, I turned the update module *on*. From time to time, they receive an error message on every page about a security update. They complain about this message, and they don't want to see it, so I turn the module *off*. I still want to keep up-to-date with all the security upgrades. How do I make sure I receive security updates? Is there a feed, an email list?

# Answer
> 4 votes
All security announcements are posted to an email list as well. Once logged in, go to your user profile page and subscribe to the security newsletter on the Edit » My newsletters tab.

You can also get rss feeds for core, contrib, or public service announcements.

# Answer
> 2 votes
I personnally prefer to let update status on and register my email in `admin/reports/updates/settings`. Being subscribed to the Drupal security list is a must do, but you will receive security updates for every module on drupal.org and after a while you may don't remember which module you have installed on you client website and miss one update or have to go to his website to find out.
So, activate update status, install Disable Messages to hide the status update warning, and put your email to receive updates only for theses modules. Also in some email provider you can receive email with the plus (+) sign in the form of your\_email+update\_clientname@example.com then when you monitor various client website, you can filter the update regarding the "+".

---
Tags: updating, security
---


# Question
Title: Automate hyperlink to send variables to webform
Here's the background for what I'm tring to accomplish:

* I am using Webform 6.x-3.11 and have a generic sign-up form located at “/project-sign-up."
* The webform has a hidden field with its default value set to "%get\[project-title\]."
* I have a custom Content-type called `Project` that holds data specific to various community outreach projects.

What I am trying to do is displaying a link at the bottom of each "Project" page saying "SIGN UP!" with the "href" pointing to "/project-sign-up?project=\[project-title\]." However, I cannot figure out how to create the link through the CCK fields of the content type. I have also tried creating a node attachment through Views UI (views\_attach) to append a link (with its output rewritten) to the "Project" node, but to no avail.

Could anyone point me in the right direction?

# Answer
> 3 votes
If you are doing it in Drupal 6 then `hook_nodeapi(&$node, $op, $a3, $a4)` is to alter node object for additional information.

```
function custom_module_nodeapi(&$node, $op, $a3, $a4){
  if ($op == 'view' && $node->type == 'project') {
    $node->content['project_link'] = array(
      '#value' => l('Sign Up', 'node/[id]', array('query' => "project=" . $node->title)),
      '#weight' => 100,
    );
  }
}

```

---
Tags: nodes, webforms
---


# Question
Title: How to attach image from a list of predefined images?
Anyone had this? I have a custom content type and I want to give an option to attach an image from a list of predefined images (in my case - a list of product series logotypes). The admin interface would be a simple dropdown of logotype labels:

```
- None -
Series 1
Series 2
Series 3

```

How would I then process the selection and convert it into a real image? What would be the best practice here?

Regards, Artur

# Answer
> 1 votes
These are general guidelines as I made something like this but for D6. I would create a logotype variable in template\_preprocess\_node and then loop on you dropdown variable. For each value selected I would add an `<img src='path/to/logo1.png' alt='Logo 1' />` to your logotypes variables.
Then just display the variable in you node template.

# Answer
> 0 votes
Here you go:

```
<?php
    $logotypes = array(
        'dropdown_key1' => '[path_to_image_1]',
        'dropdown_key2' => '[path_to_image_2]'
    );

   print('<ul>');
   foreach ($element['#object']->field_logotypy['pl'] as $logo){
        print "<li>" . $logotypes[$logo["value"]] . "</li>";
   }
     print('</ul>');
?>

```

This is placed in field--field\_name--content-type.tpl.php. In the admin form, the editor selects a logotype name from a dropdown, which has predefined keys as in the $logotypes array. The values on the admin side will be the paths to actual logotype images.

What I don't like about the code is the hard-coded 'pl' language index used here. I assume though, that with some more reading I will be able to figure out how to address it better - the logotypes are actually not language-dependent.

HTH

---
Tags: 7, media, navigation
---


# Question
Title: Can I use 'drupal_add_library' inside an ajax call?
The title is pretty self-explanatory, I would like to do something like this to display a jQuery UI dialog:

```
function my_ajax_page_callback() {
  drupal_add_library('system', 'ui.dialog');
  drupal_add_js('jQuery.dialog(...)','inline');
}

```

Specifically, I would like to include the library on-demand, not on every non-ajax request. Is that possible in D7?

# Answer
> 3 votes
`drupal_add_library()` under the hood ends up putting things into the same array as `drupal_add_js()` and `drupal_add_css()`.

These get called by `ajax_render()`, so your function should work (so long as you are using ajax\_render).

However this will add the library load to every ajax request. This will slow them down some what, and most of the item you are using ajax for speed so that may not be such a good idea. Your html JS should be cached and it should only include the ui.dialog on pages where you need it. So I think you may be better off using the standard JS caching.

In simple cases you may be able to use `ajax_command_alert()` in stead.

# Answer
> 1 votes
I do not think so. You will have to do it in this way....

```
$script = '
  <script type="text/javascript">
    <!--//--><![CDATA[//><!--
    (function($){
      $("head").append("<link>");
      css = $("head").children(":last");
      css.attr({
         rel:  "stylesheet",
         type: "text/css",
         href: "/path/to/style.css"
      });
      $.getScript("/path/to/script.js");
    })(jQuery);
    //--><!]]>
  </script>
';

```

Now make the `$script` part of ajax output.

---
Tags: 7, ajax, theming
---


# Question
Title: How do I choose the "date_popup" widget for custom date field from code?
I have a custom field in a custom form element which is declared using the following code:

```
$element['data_da'] = array(
  '#type' => 'date',
  '#title' => t('Date from'),
  '#default_value' => isset($items[$delta]['data_da']) ? $items[$delta]['data_da'] : NULL,
  '#description' => t('Description for field Date from'),
);

```

When I insert data, I see three selects, one for year, one form month and one for day. I would like to use the "date\_popup" widget.
How can I do that? What should I set? Is there a '#widget' directive?

# Answer
> 5 votes
If you install the version 2.x of the Date module, you will be able to use more form fields, including a "date\_popup" field, which shows a pop-up to select the date.
The module has an option that allows the user to decide if the pop-up should be shown; if you want to override that option, you should use `variable_set('date_popup_timepicker', 'default')`. That is the default option used by the module, but if the user selects "none," then the pop-up will not appear.

About setting a custom format with the "date\_popup" field, the form field uses the "#date\_format" attribute that, in the development snapshot 7.x-2.x, is said to accept most of the formats. The default value for that attribute is the one returned by `variable_get('date_format_short', 'm/d/Y - H:i')`.
The complete list of the attributes used by the form field, reported in a comment for the `date_popup_element_info()` documentation is the following one:

* "#date\_timezone"
The local timezone to be used to create this date.
* "#date\_format"
Unlike earlier versions of this popup, most formats will work.
* "#date\_increment"
Increment minutes and seconds by this amount, default is 1.
* "#date\_year\_range"
The number of years to go back and forward in a year selector, default is -3:+3 (3 back and 3 forward).

Drupal core modules have only the "date" form field, and it doesn't use any "#widget" attribute. Third-party modules could define new attributes, though; as far as I know, no module defines "#widget" as attribute for form fields.

---
Tags: 7, datetime
---


title: View with field collection and filters

text:
# Question
Title: View with field collection and filters
I want to make a profile for musicians. They should type their skills (reference to taxonomy) and levels (radiobuttons) like flute - beginner, piano - advanced,... Then I need a view with the profile information and the skills and levels. There should be a possibility to search for the skills and levels. I tried it with a field collection field in the profile but then there is only one exposed filter for the profile field, a textfield for both the skills and levels. How can I do this? I am getting mad about it. Is there another way to make this work?

# Answer
If you would like to look at an advanced application of someone doing something very similiar to you, have a look at the Recruiter installation profile for Drupal 7. Just download, install and then look at how the views, content types, taxonomy and fields are configured. Instead of musicians and skill it is configured to software developers with skills.
> 2 votes

# Answer
I'd check this post if anyone is still looking for how to expose properties of a Field Collection. I found it helpful.

How to integrate Field collection module in Views?
> 2 votes

---
Tags: views
---


# Question
Title: Getting the value of a user reference field and using it to display information about that user
I am quite new to module development although I have experience in modifying existing 6.x block modules developed by others. I have a need to develop a 7.x module and in spite of a lot of documentation reading seem to be missing a basic starting point. I have been looking at the documentation on drupal.org and other third party sites but through my own fault seem to be missing a basic concept.

The site I am working on has a content type called project. At present there are many project pages busing this content type. One of the field types is a User Reference field, called key\_contact.

The idea is that I need to create a block that gets the key\_contact's username (stored as an id number in the key\_contact field) and then from that number perform an SQL query, on another table, to get the id's details and then display them in a block.

At present I have a View that can return the id and I have been asked to replace this view with a module that does the entire job.

Once I get the id for the key\_contact I will have no trouble with the SQL query and formatting the output how I want it. I am familiar with creating a block module.

Where I am stuck is understanding how to get the key\_contact value from the content type project page when it is loaded.

I would appreciate it if I could either be shown documentation or an example, or even an explanation, that will show me how to extract a field value from a content type like this.

# Answer
You will have to use Views for Drupal 7. First time you will have to do it manually.
Then you can convert to module using Features module. Features will give you an auto generated module that will product the same view block on the behalf of Views.
> 2 votes

# Answer
You should use Views for this. Add an argument for the user reference field, and then add the fields you want to display from your user profile. Then you can add a block display to the View and assign it to a region on the block configuration page.
> 0 votes

# Answer
I agree with the others who say that Views is a good solution for this. If you insist on not using views, you can get the current node (assuming that you're viewing a node page) using menu\_get\_object(). The information you're looking for should be available in the loaded node object.
> 0 votes

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


title: Taxonomy + Drupal Commerce binding

text:
# Question
Title: Taxonomy + Drupal Commerce binding
I'm trying to set up a testing site with DCommerce used to present product information, yet for the time being, there won't be any shopping cart functionality. I'm stuck at how to bind the products (instances of my custom product type defined in Store) with taxonomy, and also to have the URL aliases created dynamically based on that taxonomy.

Has anyone bumped inot a good case study or tutorial. I seemed to have googled the entire internet but to no avail.

Artur

# Answer
Usually how you set up product display is via nodes, so 1 node have a relationship to 1 or more products (Fx a specific t-shirt in different sizes). Since products themselves doesn't have a public display, they are rendered through the nodes you create. This means that it is also going to be the nodes that have the url.

Trying to create a node path alias based on 1 or more products is going to be very tricky, because you don't know how many products you have, what if the products has different taxonomy etc. Instead it might make more sense to using the taxonomy on the nodes, or maybe use them on both. A node with a taxonomy term is a pretty normal case which is well supported. This should fix all the problems you have with url aliasing.
> 3 votes

# Answer
It sounds like you need to set up a product display, with fields for taxonomy.

Each product in a Drupal Commerce store has an entity for each SKU number. And each product has it's own display for the item. This allows you to reference multiple SKU's with the same display (Say for instance 3 different sizes of the same shirt)

So, to walk through quickly on how to create a product and have it display on the site.

1. Navigate to http://yoursite.com/admin/commerce/products and create your product.
2. Make sure you have a product display type that references the product in the store.
    * You can do this by navigating to http://yoursite.com/admin/structure/types. You should see the default types that come with Drupal. These include Article and Basic Page. You will need to create a new type called "Product Display" (You can really call it whatever you like).
    * This new Product Display type will need to have at least one field that is of type "Product Reference" and for your instance, you will want to create another field that is of type "Term Reference" (This refers to the taxonomy term that you want for the product)
3. With this new Product Display type, you can now create a new piece of content (or node) that is of the type Product Display. So navigate to http://yoursite.com/admin/content and create a new piece of content. (You can quickly do this by going to http://yoursite.com/node/add)
    * Create a new piece of content with your Product Display type. Here you will be able to select your taxonomy term and the product SKU number that the Product Display references.
4. In order to have the path for the taxonomy term link to the product, you will need to set up URL Aliases. You need to have the PathAuto module installed, it requires the Token module as well, so grab both.

Now, there is a major bug in the token module, which is also a major bug in Drupal 7 when it comes to tokens and paths for taxonomy terms. There isn't a token for the entire path of a menu tree.

You can look at these issues:
BIKESHED: Token for a term or menu item's entire tree/hierarchy
Equivalent of "menu-path-raw"
for some more information on it and some ideas on how to overcome this problem.

For Drupal Commerce most of the early configuration is already done for you if you use an Drupal Commerce Installation Profile. You can install Drupal + Commerce with all of these fields already set.
> 2 votes

---
Tags: taxonomy-terms, commerce
---


title: CSS Class of a multi-lingual front-page

text:
# Question
Title: CSS Class of a multi-lingual front-page
In Drupal 7, in the body tag of my English home page, I see the following CSS classes (among others): html, front.

I added a French translation for this home page by clicking on the "translate" link. The body tag of my French home page has the following CSS classes (among others): html, not-front.

For the French version, how do I substitute the CSS class "not-front" with "front"?

# Answer
You could do this in the preprocess\_html function.

You should take a look at the i18n module, which allows you to have different frontages for each language, which could be an alternative (and better) way of solving the problem.
> 4 votes

---
Tags: theming, i18n-l10n
---


title: Module code not firing

text:
# Question
Title: Module code not firing
I have a custom D7 module that I have placed in sites/all/modules/custom/mymodule folder. It appears on the modules page, and when I enable it, there are no errors.

The only code inside of it is:

```
function mymodule_init() {
  exit;
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  var_dump($form_id);exit;
}

```

Yet, neither of these cause an exit. If I place an exit outside of these functions, it definitely exits.

What is the issue?

Edit: Info file contents:

```
name = My Module
description = Form modifications for user forms (register, login).
core = 7.x
version = 7.x-1.0
dependencies[] = html5_tools
dependencies[] = elements

```

# Answer
Your version string is wrong, and shouldn't be manually included anyway, but that wouldn't cause this issue.

Drupal searches recursively for modules. I just recreated the same set-up that you had, and after a cache clear (do this by visiting admin/config/development/performance and clicking "Clear all caches").
> 1 votes

---
Tags: 7
---


# Question
Title: How to use Taxonomy to tag/categories content?
I installed and enabled the Taxonomy module, created an *Event* content type, and a "International Competition" node of that type. I want to apply the tags *senior*, *male*, and *annual* to this event.

I can't figure out how to do this. I've tried reading the documentation for the Taxonomy module but can't figure out where in the CMS I am supposed to associate tags to a node.

# Answer
The steps to follow to be able to use a vocabulary with nodes of a content type are two:

* Create the vocabulary, if it doesn't exist, on admin/structure/taxonomy.
* Associate the vocabulary with the content type on; for example, for the *Article* content type, the page is admin/structure/types/manage/article/fields.

+ Add a new field, using "Term reference" as field type.
    + Click the "Save" button, and select the vocabulary that is used for the taxonomy terms that will be added.
    + Change the settings in the page that appears after you click on the "Save field settings" button.

This is different from Drupal 6, where the form to create (or edit) a vocabulary also allowed to select which content type should use that vocabulary. In Drupal 7 is changed, as a vocabulary can be associated to other entities, such as users (see admin/config/people/accounts/fields) and vocabularies (see admin/structure/taxonomy/forums/fields for the "Forums" vocabulary).
> 8 votes

---
Tags: taxonomy-terms, nodes
---


# Question
Title: Toggle translation in a multilingual site
I'm building a bi-lingual site (English and French) with Drupal 7. I want to create a link at the top right corner of my site that toggles a page between English and French. How do I do this?

I have also installed the Internationalization module. I haven't used it yet. Maybe that can help my situation.

For example, say I am on the page http://example.com/home. How do I figure out the french equivalent of that page, its URL, and print it to the right hand corner of my site?

# Answer
> 1 votes
I recommend using the Language icons module. It will provide a block where languages can be toggled with a Flag. Btw the i18n (at least in D6) provides a similar block but with no flags, you can use this instead too and add the flags with a little CSS. HTH.

http://drupal.org/project/languageicons

---
Tags: i18n-l10n
---


# Question
Title: How to set the default value of a CCK field
I got a CCK field to select a currency; this field is not required, and the dropdown displays '-None-'. I want to change that.

There's the option to let PHP-Code return the value. It says:

```
return array(
    0 => array('value' => 'value for value'),
    // You'll usually want to stop here. Provide more values
    // if you want your 'default value' to be multi-valued:
    1 => array('value' => 'value for value'),
    2 => ...
);

```

So I tried with:

```
return array(
  0 => array('value' => 'my_text'),
);

```

Drupal now tells me:

```
The PHP code for 'default value' returned Array ( [0] => Array ( [value] => my_text ) ) , which is invalid.

```

I got a list of 4 currencies to choose from, which are the allowed values in my dropdown. What do I have to do to replace '-None-' with my own default?

# Answer
> 1 votes
In order for you to use PHP you must return a simpler array:

```
return array(
  'value' => 'my_text'
);

```

Also, if all you want is to set a default value, you don't need to use the PHP option.

* First, define the allowed values (manually or via PHP, doesn't matter)
* Then click save
* Now click edit to go back to the form. Close to the top there will be a "Default Value" fieldset populated with the allowed values. Just select one!

# Answer
> -1 votes
The tip from Alex about doing this without using the PHP option is great. However, remember to set the permissions on the new cck field. Until you have done this, you will not be able to see the "Default Value" box.

.. remembering to do this will save much frustration :-$

---
Tags: 7, entities
---


title: Custom calendar

text:
# Question
Title: Custom calendar
I have a content type ("Event") with a "Date" field.
I'm using Date and Calendar in order to have a calendar rendered in a block.
I want to change the behaviour of it, and focus only on the month and day, without taking care about the year. So, the dates 10/10/2010, 10/10/2011, 10/10/2012, 10/10/\* should appear in the Calendar in every October 10th, no matter what year I'm seeing.

I thought about doing this using any of these two ways:

### First one

I could do that using Date Repeat, but I see two inconvenients here:

* I have to specify a "To:" field in the Repetitions tab, and I just want it to repeat for **every** year.
* When viewing the details of some Event node, I will see a list with all repeated dates! (Yes, I could tweak this).

If I could solve the first issue, I think I will handle the second and I'll be done.

### Second one

It would be great to have a calendar (in a month view, I only need it for a block view) where I can customize the link of each day, and make each day for every month clickable. For example, the day "October 10th, 2011" will be linked to /10102010, /10-10-2010 or whatever I specify.

Is there a way of doing this? I don't mind if I have to modify some modules or write some hooks in order to do that.

# Answer
> 1 votes
I have had better luck customizing the FullCalendar module, it should be easier to accomplish the things you want with it: http://drupal.org/project/fullcalendar

There is even an IRC channel where you can get help: #drupal-fullcalendar

---
Tags: datetime
---


# Question
Title: What is the minimum I need to get a test for a module on D7?
I have a custom module that's fairly mature and I'm just now getting around to writing tests for it. However, I'm having difficulty getting the it to show up in the tests menu. What is the bare minimum that I need to get automated testing going for my module?

I have:

`module.info`:

```
files[] = tests/module.test

```

`tests/module.test`:

```
<?php
class ModuleTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Module Test',
      'description' => 'Automated testing of Module.',
      'group' => 'Module',
    );
    function testModule() {
      $this->assertTrue(TRUE, 'Tests are working');
    }
  }
}

```

I've even set up a bogus test module that's basically what's outlined above, and it works. But my module with all my functionality it in won't show its tests on the test menu. So I'm trying to see if there's anything simple I'm overlooking.

Does the test file have to be called `module.test` or can it be called `anything.test`? Does the name of the class have to be `ModuleTestCase` or can it be arbitrary? I do have my files called `module.test` and the class called `ModuleTestCase`. I've also run the module.test on the command line php to test for syntax errors and I get none. What could I be overlooking?

# Answer
What you got there will suffice. I copied the code to a project I was working on and it showed up fine.

You problem is either:

* Cache (You need to clear cache after updating the .info file)
* Overlooked, The test could be there, but you didn't see it. It will show up under the group with the name written in `name`.
> 2 votes

---
Tags: 7, testing
---


# Question
Title: Data in field_revision with Create new revision unchecked
The field\_data\_myfield and field\_revision\_myfield have the same row entries (D7 fields). All of my content types have the "Create new revision" unchecked. Is this how it's suppose to work? If yes, two questions 1) is this okay for scalability and 2) how do I stop drupal from renaming the files with \_0 even when the original is deleted -- I read that this is because revision is on. If it's not suppose to work this way, how do I fix it.

I'm using mysql.

To clarify the end goal, I don't want the entire field deleted, I would like the fields not to track data revisions. Currently if field\_body is updated, it also tracks it in field\_revision body. Ideally, drupal would only save the update in field\_body, and field\_revision\_body would be left empty. The content type is marked to not track revisions.

# Answer
**Is this how it's suppose to work?**

It depends on which storage backend you use. The default sql backend works this way.

1. It shouldn't effect speed (much) but will instead effect data storage which usually isn't a problem.
2. Drupal will not completely delete a field, but instead mark it as deleted. If you want to completely delete it, you need to delete it from the `field_config` and `field_config_instance` tables.
> 0 votes

---
Tags: 7, nodes
---


title: How to discard changes in Rules module

text:
# Question
Title: How to discard changes in Rules module
Depending on a condition I want a node's changed content not to be overwritten on the old content. That is old content should be retained and new one discarded so that node does not change.

Which action should I add? I've tried many but everytime a user saves a node, it is permanently changing the node's content.

# Answer
Create a rule for the "Content is going to be saved" event, and add a "Execute custom PHP code" action. The code you write have access to some variables by reference: `$node`, `$node_unchanged`, `$user`, `$author`, `$author_unchanged`, and `$user`.

For example, you can use the following code to set the title as it was before the node was edited.

```
$node->title = $node_unchanged->title;

return array('node' => $node);

```

Similar code is usable in the version for Drupal 7 of the Rules module; what changes is the variables to which the code has access.
> 1 votes

---
Tags: rules
---


# Question
Title: Dealing with hook_cron when configuration is required
What's the best way in dealing with functions that require configuration in a hook\_cron?

Example (pure fiction):

My hook\_cron calls function\_close\_ticket, this function has various variable\_gets all of which have defaults but those defaults may not be relevant to the users setup (they are however relevant to a default casetracker setup), especially if the user has customised casetracker a lot.

Would I be best leaving as is and letting hook\_cron fire or wrapping the function inside in a call to get the state of a user configurable variable? Or is there some other way of dealing with this problem?

# Answer
> 1 votes
If you require configuration, then you shouldn't provide a default value using variable get (You provide an empty default value instead). If the no value is set, you should make a log using watchdog and exist without doing anything, since the conf was missing.

If you can provide a default settings that would make everything work, that would be a better option, since the user don't have to do any setup, be can if he wants to.

The checks should not really happen in cron, but in the function actually doing whatever needs to be done.

# Answer
> 0 votes
In addition to making a watchdog entry as googletorp suggests, if the module simply doesn't work without a user setting up some configuration options, you should consider implementing `hook_requirements()` so that if a user checks their site status report, they'll be prompted to visit the configuration page.

---
Tags: 6
---


# Question
Title: Why would my Cron run fail when run by system crontab, but succeed when run manually?
The Cron tasks on my website run perfectly fine if I manually execute cron. However, I have the server set up to automatically run cron every hour. When cron is executed automatically it fails... every time. The error message is always about memory usage exceeding the allowed levels (which are already rather high). Most of the time, though not always, this error is thrown from the Date module. I do have a feed set up that pulls from a large Google calendar, so I've been thinking that might be the problem. But why would it succeed when run manually? I understand that when run manually it's run as my admin user, and when run automatically it runs (correct me if I'm wrong) as an anonymous user. Does that have something to do with the failure/success pattern?

---

Edit: Posting the actual cron command as requested

`/bin/php5 -q /path/to/my/account/public_html/cron.php`

# Answer
> 3 votes
Check to see if you have a php-cli.ini file being loaded. From the command line, do:

```
$ php -i |grep ini

```

and see what ini file is being loaded. If there's a cli ini loading, it may not have the same memory limit as your 'normal' php.ini.

# Answer
> 1 votes
I second trying drush. I was having basically the same problem - I could run cron manually, but could not get curl, wget, lynx, or any of the other crontab variants working. I tried drush cron, and that worked, so... I stuck this in crontab:

45 * * * * /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 /usr/bin/drush --root=/path/to/your/drupal/root --uri=yoursite.com --quiet cron

Works for me. Saved my sanity.

# Answer
> 0 votes
Depending on what your cron is attempting to do, you might need to specify that it runs as an admin, not anonymous: `drush -u 1 cron`.

# Answer
> 0 votes
@Entendu was right, it was using a different .ini file than the actual site was using. So when I initiated the cron run manually it was using an .ini file with a higher memory limit than the CLI .ini file. To solve the problem, you could edit the .ini file for the CLI. Or, if you don't have access to it, you can specify that cron should use a different .ini file using the `-c` flag... `/bin/php5 -c /path/to/your/php.ini /path/to/your/cron.php`

---
Tags: feeds, cron
---


title: How to disable access to a node

text:
# Question
Title: How to disable access to a node
What I want is whenever a registered user saves a page type node - that specific node should be made inaccessible to the user.

So if a registered user has save node/122, node/122 should be made inaccessible to the user.

How can I do it?

# Answer
> 1 votes
Easy! When a new Page is created, just change its owner to a different user with appropriate role and permissions. In our case, let's say to *admin*.

First, install the Rules package, enable *Rules* and *Rules Admin* modules.

Navigate yourself to the *Rules | Triggered rules | Add a new rule* page:

**Label:** Detach page from creator
**Event:** After saving new content

Make sure the new rule is active. Save changes and on the next page *Add a condition*:

**Select the condition to add:** Content has type
**Content types:** Page

Save and *Add an action*:

**Select an action to add:** Load a user account
**User id:** 1

Save and again, *Add an action*:

**Select an action to add:** Set the content author
**User, who is set as author:** Loaded user

Done! This changes the node creator and the original author has control over it no more.

As you will see, this is just the quickest solution to your problem. Rules module enables you to go wild and achieve heaps of stuff that you would normally expect separate modules to be put together for. To get the idea, have a look at how I used Rules (in conjunction with Flag) to keep track of Recently viewed nodes in Drupal.

Note that the node creator always has view permission to the node, as long as they have `access content`, without which CMS wouldn't make much sense. Anyway, to keep track of the original creator, for display or so, you can use the CCK's *User reference* module.

# Answer
> 0 votes
For each content type that is associated with the Node module, the module defines the following permissions: create, edit any content, edit own content, delete any content, and delete own content. You can allow users with a role to create nodes of a specific content type, and not allow those users to edit those nodes; what the Node module doesn't allow is to forbid users with a role to view nodes basing of their content type.

If the question is how an administrator user can hide content from the ordinary users, then an administrator user can unpublish a node. This can be done in the node edit page, using the form fields in the "Publish options" field set; alternatively, it can be done from admin/content/node (admin/content in Drupal 7) selecting the nodes to unpublish and the "Unpublish" ("Unpublish the selected content" in Drupal 7) option in the "Update options" field set.

---
Tags: users
---


# Question
Title: Custom links to switch language in Drupal 6
In my case, I wanted to print the language switch links directly in page.tpl.php, for example with:

```
<a href="what_to_put_here">English</a>
<a href="what_to_put_here">Deutsch</a>

```

How can I accomplish this without using the "Language switcher" block? I checked all the modules that comes with the Internationalization project, but I didn't see any `hook_block()` implementation that outputs the language switcher block.

UPDATED: I wanted something like: This site is on **russian**, **english** and **kazakh** languages. This cannot be done with language switcher block.

i've tried this way in page.tpl.php:

```
<?php
$way = drupal_is_front_page() ? '<front>' : $_GET['q'];
print '<span id="switcher">'. 'на ' . l('русском', $way). ', ' . l('казахском', 'kk/'.$way). ' и ' . l('английском', 'en/'.$way) .'</span>';
?>

```

Default language is russian - mysite.com, when i switch to an english - mysite.com/en, as you see it adds prefix 'en'. But now if i want to switch on kazakh language - mysite.com/kk from english the link looks mysite.com/en/kk == it adds en to my URL. How to make this correctly?

# Answer
What doesn't work for you with the language switcher ?
If you want to reproduce its behavior, have a look at its code and try to do something equal.

Here is some code:

```
$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
$languages = language_list('enabled');
$links = array();
foreach ($languages[1] as $language) {
  $links[$language->language] = array(
    'href' => $path,
    'title' => $language->native,
    'language' => $language,
    'attributes' => array('class' => 'language-link'),
  );
}
drupal_alter('translation_link', $links, $path);
//dpm($links);

foreach ($links as $link) {
  echo t('Link for ') . l($link['title'], $link['href']) . '<br />';
}

```
> 2 votes

# Answer
Use the `language` option of the l() function. Same URL, different language and Drupal should take care of it for you:

```
<?php
$way = drupal_is_front_page() ? '<front>' : $_GET['q'];
$languages = language_list();
print l('slovak', $way, array('language' => $languages['sk'])) . ', '
  . l('czech', $way, array('language' => $languages['cs'])) . ', '
  . l('english', $way, array('language' => $languages['en']));
?>

```
> 1 votes

---
Tags: theming, i18n-l10n
---


# Question
Title: How to change a custom field on form save
In the node type page I've added one Integer field "field\_article\_rejected". When in rejected stated it contains 1.

**But when a registered user changes and "Saves" it I want to set the value of it to 0.**

Also the registered user does not have read/write permission on this field. But if needed I can give the user permission for this field but I'll hide it in "Display fields"

How to do it?

I'm working on Drupal-6.

To explain what I'm doing: I've created an article directory. So an user will log-in and create an article type of page. So now this page will be shown as "Submitted articles" block using views.

But as an admin when I reject it then I want this article to be shown under "Rejected Articles" block to the user. So I want to use field "field\_article\_rejected". When 0 it means user has sumbitted and when 1 then it means rejected by admin.

# Answer
> 1 votes
You create a custom module that will include hook\_form\_alter(). Something like this:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    global $user;

    if (in_array('admin', array_values($user->roles))) {
      //admin role is not a default role
      //do nothing
    }
    elseif (in_array('authenticated user', array(values($user->roles))) {
      //remove editable field and replace it with a label
      $form['article_field_rejected']['#access'] = FALSE;
      $form['article_field_rejected_label'] = array (
         '#type' => 'item',
         '#default_vale' =>  isset($field['article_field_rejected']['#value']) ? $field['article_field_rejected']['#value'] : '0',
    }
    else {
     // For everyone else disable field and do not display it
     $form['article_field_rejected']['#access'] = FALSE;
    }
}

```

If you don't replace the field with a label, then the use can still alter the value by editing the browser.

# Answer
> 1 votes
I assume you're already using the *Content permissions* module and have only enabled `edit field_article_rejected` to the appropriate role, let's use `content admin`.

Now, we're going to use the Rules module to reset the field back to 0 each time the node is saved by a user that does NOT have the `content admin` role, most likely the owner.

**Label:** Reset article rejected
**Event:** Content is going to be saved

*Add a condition*

**Select condition to add:** User has role
**User:** Acting user
**Negate:** (checked)
**Select role(s):** content admin

*Add an action*

**Select an action to add:** Populate a field
**Content:** Saved content
**Field:** field\_article\_rejected
**Article rejected:** 0

It only takes 5 minutes to configure a rule. No custom module needed, no code whatsoever. :-)

# Answer
> 0 votes
You need to create a custom module that implements hook\_form\_alter within this you can target your form by `$form_id` then within that you can use something similar to below:

```
global $user
if (in_array('registered user', array_values($user->roles)) {
  $form['field_blah'][0]['value'] = 0;
}

```

Your `$form` structure may be different.

---
Tags: forms, 6
---


# Question
Title: Newbie - I want to trigger an action when a user creates / updates a profile
I would like to trigger an action when a user creates or updates a profile.

What classes should I look for?

I search for the documentation but I didn't understand it much. Can you point me to the right direction?

Thanks a lot

# Answer
> 3 votes
You can use the Rules module for that.

http://drupal.org/project/rules

Create a new triggered rule and set it to fire on event "User account has been created" or "User account has been updated." If you're using Content Profile, you'd set the event to be "after saving new content" or "after updating new content" and specify the node type was whatever you're using for content profiles.

---
Tags: rules
---


title: Executing a Python script from Drupal

text:
# Question
Title: Executing a Python script from Drupal
I'm trying to execute a python script from Drupal using this:

```
exec('/usr/bin/python name_of_the_script.py')

```

But it does not work. Although, if I'm on the php console (`php -a`), then it works fine.

The `name_of_the_script.py` file has all the permissions.

I thought maybe it was the `python` command that didn't have all the permissions.

So I checked it with this command:

```
which python
ls -lisa /usr/bin/python

```

> **694 0 lrwxrwxrwx 1 root root 9 2011-03-09 18:41 /usr/bin/python -\> python2.6**

Similarly I also used this command:

```
ls -lisa /usr/bin/python2.6

```

> **369 2240 -rwxr-xr-x 1 root root 2288240 2010-04-16 10:06 /usr/bin/python2.6**

It seems everything is OK.

Do you have any suggestions?

# Answer
> 1 votes
Adding **2\>&1**

```
exec('/usr/bin/python script.py 2>&1');

```

Pointed me to the right direction.

I was writting in a file ( inside the script that hadn't enough permissions )

chmod 666 name\_of\_the\_file.txt totally solved the issue!

Thanks!

# Answer
> 0 votes
Most likely it's a permission of your webserver that is causing this. You should take care as things could turn out badly should your drupal site be compromised.

---
Tags: files
---


title: Remove all added classes to body tag

text:
# Question
Title: Remove all added classes to body tag
How do I remove all the classes that are being added to the body tag? Currently my body tag is :

```
<body>

```

This however is rendered as

```
<body class="lightbox-processed admin-nw admin-vertical admin-df">

```

# Answer
Those are added there via Javascript of the Lightbox and Admin Menu modules. You can either disable those modules or modify/override their Javascript. You could also use custom Javascript to remove the classes from the body element. Anyway, the question is, why would you want to remove the classes?
> 1 votes

---
Tags: 6, theming
---


# Question
Title: Can two nodes have same URL using Pathauto?
I know that Drupal allows same url for multiple nodes. But I've a scenario: a registered user creates and submits an article as an unpublished node and assigned an URL by pathauto based on its title. At the same time another user creates an article with same title in unpublished form. Will it too have same url?

I'll not "publish" those nodes anytime. I'll (as an admin) simply create a new node and copy paste contents.

# Answer
> a registered user creates and submits an article as an unpublished node and assigned an URL by pathauto based on its title. At the same time another user creates an article with same title in unpublished form. Will it too have same url?

No. pathauto by default will append a number to the end of the URL to differentiate between them.
> 1 votes

# Answer
Sorry, but Drupal does not allow same URL for multiple nodes.
> -1 votes

---
Tags: uri
---


# Question
Title: Force user to fill in at least text area or file
A registered user is creating a node with a body and file field. I want to force the user to either fill the body with 300 chars or select a file. At least one needs to be selected/filled.

How can I do it?
Can I do this using the Rules module?

# Answer
I don't know how you could achieve this with rules. You could however create a small custom module that adds a form validation function to the node edit form. The validator would check that the appropriate conditions are met.

**Edit:** something like this would work I think for content type *page*.

```
/**
 * Implements hook_form_FORM_ID_alter for page_node_form.
 *
 * @see module_validate
 */
function module_form_page_node_form_alter(&$form, &$form_state) {
  $form['#validate'][] = 'module_validate';
}

/**
 * Form validator for page_node_form.
 */
function module_validate($form, &$form_state) {
  // This strips HTML tags - to disable, remove the filter_xss() call.
  $body_length = drupal_strlen(filter_xss($form_state['values']['body'], array()));

  // We're assuming the field is called 'file' and we're checking the first file.
  $file = $form_state['values']['field_file'][0];

  // Rather than checking against 300, we should perhaps call node_get_types()
  // and find the configured word limit.
  if (body_length < 300 && !$file['fid']) {
    form_set_error('body', t('Please ensure that you either enter 300 characters into the body field, or upload a file.'));
  }
}

```
> 2 votes

# Answer
I don't believe the Rules module can be used for validation. There may be modules out there to allow you do some custom validation but for your particular case, you may want to write your own, small validation module using `hook_node_validate`
> 1 votes

---
Tags: 6, forms
---


title: Tao overriding parent reset.css file.

text:
# Question
Title: Tao overriding parent reset.css file.
I wish to override one of the default css files provided from the theme I am inheriting from. According to Creating a sub-theme page I need to do the following:

> **Overriding inherited style sheets:** Specify a style sheet with the same filename in the sub-theme. For instance, to override style.css inherited from a parent theme, add the following line to your sub-theme's .info file:
>
> `stylesheets[all][] = style.css`
>
> You will also need to create the style.css stylesheet file; if you simply wish to disable the imported styles, you can create an empty file.

My parent theme (Tao) has a reset.css file. In mytheme I have added the following to mytheme.info

```
stylesheets[all][]   = reset.css

```

I have then create a blank file called `reset.css` and it is in the root of my theme. I have run `drush cc all` but the parent css file is still being read.

What am I doing wrong?

# Answer
> 0 votes
Tao inclueds reset for print and for screen so you should override like so.

```
stylesheets[print][]   = reset.css
stylesheets[screen][]   = reset.css

```

Using the `all` array will only override other items in the `all` array not both `screen` and `print`

---
Tags: 6, theming
---


# Question
Title: Adjusting module weight: what are the risks and things to look out for?
Today I changed the weight of a custom module of mine in order to change the execution method of hooks (hook\_form\_alter). I've changed the weight to 1 value heavier than the other module's weight. This seemed the safest thing to do instead of giving it a "random" weight of 100. The original module is a core module (translation) so I hope I didn't break anything.

When adjusting the weight of a module in order to change the execution order of hooks, what are the things to look out for and what are the risks involved?

What I can think of: unwanted behaviour as result of high coupling.

# Answer
> 10 votes
Well there isn't a general answer to this, it really depends on the modules. Some of the things I would take into consideration (In Drupal 6) :

* hook\_boot is called as modules are loaded ; so only modules that are lighter than you have been included. If you rely on code from another module that is heavier than you, make sure you include them manually.
* If a module has by default a weight other than 0, then it means that this module specifically set this weight. Check that module's .install file, as this is most likely where the weight is set - and with a bit of luck there will be a comment explaining why ! (this may be true even if the weight is zero)
* Modules that set either a very low or very high weight usually have a good reason for it (*must* run before/after everything else). Typically development modules do this, though others might as well. Keep these modules first/last unless you have a good reason for it.
* Look at the module's dependencies (the ones the module depends on, and the ones that depend on this module). Ideally keep these modules in the same order. If you must change the order, the only way to understand the consequnces is to look at the code.
* Use common sense. Information that is added by a module (say to a node on node load) will not be available to modules lighter than this one.

# Answer
> 3 votes
I honestly don't think there's a general answer for this. What happens when you adjust the module weight depends highly on the modules involved, and if you change the weights of too many modules, I would imagine that you could end up with some unpredictable results.

That being said, if you want to minimize your risk, just consider precisely what it is that your module is doing. What data are you modifying? Are you making major changes to data structures, or are you changes more cosmetic? The biggest risk, I would think, would be changing existing data in an unexpected way. If you're careful and you adjust module weights sparingly, you shouldn't have too many issues.

---
Tags: 7, hooks
---


# Question
Title: Drupal 7 Artisteer generated theme fatal error with media gallery
Before I start, I know that some of you may have your opinions on Artisteer, and I respect that it may not be the best way to create a theme, especially for Drupal 7, but to be truthful, I have no coding knowledge of Drupal; so I would ask politely you could focus on the following problem rather than commenting your opinions, please...

I am trying to create a website using Drupal 7 and the Media Gallery module. All goes perfectly when I am using an 'out of the box' theme, but when I set my Artisteer generated theme as default and navigate to '/galleries', the page loads as text only and I recieve the following error at the very bottom of the page (there is content above):

> Fatal error: Cannot use object of type stdClass as array in /home/accusername/public\_html/D7GFx/sites/all/themes/D7GFx/drupal7\_theme\_methods.php on line 229

To me, everything in the file looks fine and I can't imagine what needs changing, but of course I have not coded for Drupal before! With the blank lines included `function D7GFx_node_preview($variables) {`, is on line 229, and all seems to be well inside that function. Quite interestingly though, if I completely remove the function, the line number of the error just changes?! I hate posting massive amounts of code, but I have a feeling that to get this problem solved as soon as possible it may be nessercary to post the whole of the `drupal7_theme_methods.php`; AND I need to sort this website out as quickly as I possibly can: so here it is:

```
<?php

/* Drupal 7 methods definitons */

function D7GFx_breadcrumb($variables) {

  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {

    // Provide a navigational heading to give context for breadcrumb links to

    // screen-reader users. Make the heading invisible with .element-invisible.

    $output = '<h2 class="element-invisible drew-postheader">' . t('You are here') . '</h2>';

    $output .= '<div class="breadcrumb drew-postcontent">' . implode(' » ', $breadcrumb) . '</div>';

    return $output;

  }

}

/**

 * Returns HTML for a button form element.

 *

 * @param $variables

 *   An associative array containing:

 *   - element: An associative array containing the properties of the element.

 *     Properties used: #attributes, #button_type, #name, #value.

 *

 * @ingroup themeable

 */

function D7GFx_button($variables) {

  $element = $variables['element'];

  $element['#attributes']['type'] = 'submit';

  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'] . ' drew-button';

  if (!empty($element['#attributes']['disabled'])) {

    $element['#attributes']['class'][] = 'form-button-disabled';

  }

  return '<span class="drew-button-wrapper">'.

    '<span class="drew-button-l"></span>'.

    '<span class="drew-button-r"></span>'.

    '<input' . drupal_attributes($element['#attributes']) . ' />'.

    '</span>';

}

/**

 * Override or insert variables into the page template.

 */

function D7GFx_preprocess_page(&$vars) {

  $vars['tabs'] = menu_primary_local_tasks();

  $vars['tabs2'] = menu_secondary_local_tasks();

}

/**

 * Returns HTML for a single local task link.

 *

 * @param $variables

 *   An associative array containing:

 *   - element: A render element containing:

 *     - #link: A menu link array with 'title', 'href', and 'localized_options'

 *       keys.

 *     - #active: A boolean indicating whether the local task is active.

 *

 * @ingroup themeable

 */

function D7GFx_menu_local_task($variables) {

  $link = $variables['element']['#link'];

  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {

    // Add text to indicate active tab for non-visual users.

    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';

    // If the link does not contain HTML already, check_plain() it now.

    // After we set 'html'=TRUE the link will not be sanitized by l().

    if (empty($link['localized_options']['html'])) {

      $link['title'] = check_plain($link['title']);

    }

    $link['localized_options']['html'] = TRUE;

    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));

  }

  //added drew-class

  $link['localized_options']['attributes']['class'] = array('drew-button');

  return '<li>' .

      '<span class="drew-button-wrapper">'.

      '<span class="drew-button-l"></span>'.

      '<span class="drew-button-r"></span>'.

      l($link_text, $link['href'], $link['localized_options']) .

      "</span></li>\n";

}

/**

 * Returns HTML for a feed icon.

 *

 * @param $variables

 *   An associative array containing:

 *   - url: The url of the feed.

 *   - title: A descriptive title of the feed.

 */

function D7GFx_feed_icon($variables) {

  $text = t('Subscribe to @feed-title', array('@feed-title' => $variables['title']));

  return l(NULL, $variables['url'], array('html' => TRUE, 'attributes' => array('class' => array('feed-icon', 'drew-rss-tag-icon'), 'title' => $text)));

}

/**

 * Returns HTML for a node preview for display during node creation and editing.

 *

 * @param $variables

 *   An associative array containing:

 *   - node: The node object which is being previewed.

 *

 * @ingroup themeable

 */

function D7GFx_node_preview($variables) {

  $node = $variables['node'];

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

  $preview_trimmed_version = FALSE;

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

  $trimmed = drupal_render($elements);

  $elements = node_view($node, 'full');

  $full = drupal_render($elements);

  // Do we need to preview trimmed version of post as well as full version?

  if ($trimmed != $full) {

    drupal_set_message(t('The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication.<span class="no-js"> You can insert the delimiter "<!--break-->" (without the quotes) to fine-tune where your post gets split.</span>'));

    $preview_trimmed_version = t('Preview trimmed version');

    $output .= <<< EOT

<div class="drew-post">

        <div class="drew-post-body">

    <div class="drew-post-inner drew-article">

<div class="drew-postcontent">

      <h3>

      $preview_trimmed_version

      </h3>

    </div>

    <div class="cleared"></div>

    </div>

            <div class="cleared"></div>

        </div>

    </div>

EOT;

    $output .= $trimmed;

    $preview_full_version = t('Preview full version');

    $output .= <<< EOT

<div class="drew-post">

        <div class="drew-post-body">

    <div class="drew-post-inner drew-article">

<div class="drew-postcontent">

      <h3>

      $preview_full_version

      </h3>

    </div>

    <div class="cleared"></div>

    </div>

            <div class="cleared"></div>

        </div>

    </div>

EOT;

    $output .= $full;

  }

  else {

    $output .= $full;

  }

  $output .= "</div>\n";

  return $output;

}

/**

 * Return a Artisteer themed set of links.

 *

 * @param $content

 *   An object with node content.

 * @return

 *   A string containing an unordered list of links.

 */

function art_links_woker_D7($content) {

  $result = '';

  if (!isset($content['links'])) return $result;

  foreach (array_keys($content['links']) as $name) {

    $$name = & $content['links'][$name];

    if (isset($content['links'][$name]['#links'])) {

      $links = $content['links'][$name]['#links'];

      if (is_array($links)) {

        $output = get_links_html_output_D7($links);

        if (!empty($output)) {

            $result .= (empty($result)) ? $output : ' | ' . $output;

        }

      }

    }

  }

$terms = get_terms_D7($content);

  if (!empty($terms)) {

  ob_start();?>

   <?php

  $result .= ($result == '') ? ob_get_clean() : ' | ' . ob_get_clean();

  $result .= '<div class="drew-tags">' . render($terms) . '</div>';

  }

  return $result;

}

function get_terms_D7($content) {

    $result = NULL;

    foreach (array_keys($content) as $name) {

        $$name = & $content[$name];

        $field_type = isset($content[$name]['#field_type']) ? $content[$name]['#field_type'] : NULL;

        if ($field_type == null || $field_type != "taxonomy_term_reference") continue;

        $result = $content[$name];

    }

    return $result;

}

function get_links_html_output_D7($links) {

    $output = '';

    $num_links = count($links);

    $index = 0;

    foreach ($links as $key => $link) {

      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.

      if ($index == 0) {

        $class[] = 'first';

      }

      if ($index == $num_links) {

        $class[] = 'last';

      }

      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))

          && (empty($link['language']) || $link['language']->language == $language_url->language)) {

        $class[] = 'active';

      }

      $link_output = '';

      if (isset($link['href'])) {

        // Pass in $link as $options, they share the same keys.

        $link_output = l($link['title'], $link['href'], $link);

      }

      elseif (!empty($link['title'])) {

        // Some links are actually not links, but we wrap these in <span> for adding title and class attributes.

        if (empty($link['html'])) {

          $link['title'] = check_plain($link['title']);

        }

        $span_attributes = '';

        if (isset($link['attributes'])) {

          $span_attributes = drupal_attributes($link['attributes']);

        }

        $link_output = '<span' . $span_attributes . '>' . $link['title'] . '</span>';

      }

if (strpos ($key, "comment") !== FALSE) {

          if ($index > 0 && !empty($link_output) && !empty($output)) {

          $output .= ' | ';

        }

        ob_start();?>

         <?php

        $output .= ob_get_clean();

        $output .= $link_output;

        $index++;

        continue;

        }

if ($index > 0 && !empty($link_output) && !empty($output)) {

          $output .= '&nbsp|&nbsp';

        }

        ob_start();?>

         <?php

        $output .= ob_get_clean();

        $output .= $link_output;

        $index++;

    }

    return $output;

 }

```

Once again, sorry for the amount of code. You may not even need to see it but I just want to cover everything, so that I can find the solution to my problem in optimum time!

Many Thanks in Advance,

Andy

# Answer
I apologise profusely to anyone who has tried to help me, or to anyone who has even looked at this question. I don't know why, but when I oppened the file today to add `dpm($variables)` after line 229, I found that line 299 was `$field_type = isset($content[$name]['#field_type']) ? $content[$name]['#field_type'] : NULL;}` as oppossed to `function D7GFx_node_preview($variables) {`, which would explain alot.

There, I found and used this post on the Artisteer forums, which has worked a treat!

Again, I can't imagine what's happened and why I got the wrong line, but #### happens! Sorry to everyone, especially tostinni! I feel so guilty now, you even asked what was on that line. I know it's no excuse, but I was very tired and stressed when I replied to you comment!

With Thanks and Kind Regards,

Andy
> 1 votes

---
Tags: 7, media, theming
---


# Question
Title: Webform add data along with submitted values
I'm using Webform 6x 3.11 and have passed a *nodeID* into a hidden field called `hidden_key`. I have created a custom module to implement `hook_form_alter()` whereby I am trying to add additional data (along with the data that is being submitted) to the submission results.

This additional data is based on some calculations performed on the value in the hidden field, ie: getting some details about the node based on the *nodeID*. Here's what I currently have:

```
<?php
    function custom_form_proc_form_alter(&$form, &$form_state, $form_id) {
        if ($form_id == 'webform_client_form_33') {
            $form['#submit'][] = 'custom_form_proc_submit';
        }
    }

    function custom_form_proc_submit($form, &$form_state) {
        $node = node_load($form_state['values']['hidden_key']);
        $pool_title = $node->title;
        $pool_category = $node->field_category[0]['value'];

        // ?????
    }
?>

```

Where you see my `?????` is where I am stuck. Along with whatever data gets submitted with the form, I would like to add these 2 custom fields to the submission results so that it looks like:

**Fullname:** Mr So-and-So
**Email Address:** someone@test.com
**Pool Category:** `$pool_category`
**Pool Title:** `$pool_title`
**Availability:** Yes

I would really appreciate your help! Thank you!

# Answer
**SOLVED:** okay, after playing around a bit, this was actually easy and much simpler than I anticipated.

Firstly, instead of passing the nodeID to the hidden field, I simply went with this option for those that are similarly stuck.

```
function custom_form_proc_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_33') {
        $node = node_load($_GET["n"]);
        $form['submitted']['pool_title']['#default_value'] = $node->title;
    }
}

```

When the form renders, my disabled textfield `pool_title` is automatically populated, and submitted along with the results. Something tells me this isn't as simple as this, but if anyone foresees an issue with this approach (like with other validation/email submission/data store
> 1 votes

# Answer
I think the simplest way to do it would be to create another hidden field to store the calculated value. Then you can use `hook_webform_submission_presave()` to do the calculation and store the result in `$submission->data[$cid]` where `$cid` is the component ID of the destination component.
> 4 votes

# Answer
For webform submission it is best to use `hook_webform_submission_insert($node, $submission)`.
`$submission->data` will contain all the submitted values arranged against form components ids.

See my implementation how I arranged a webform as user register form.

```
function user_register_webform_submission_insert($node, $submission){
// Load information about form components
$comps = $node->webform['components'];
$fields = array();

//Extract the component info to get form_key=>cid to resolve relation
foreach($comps as $cid => $comp_info){
    $fields[$comp_info['form_key']] = $cid;
}

// Load the submitted data (field values)
$data = $submission->data;

//Prepare a user info
$user = array(
    'mail' => $data[$fields['mail']]['value'][0],
    'name' => $data[$fields['name']]['value'][0],
    'pass' => user_password(8),
    'status' => 1,
    'init' => $data[$fields['mail']]['value'][0],
    'roles' => array(2, 3),
);

$account = user_save(null, $user);
}

```
> 3 votes

---
Tags: 6, hooks, webforms, forms
---


title: i18n, path alias doesn't work

text:
# Question
Title: i18n, path alias doesn't work
I set path auto alias of content type page to:

> \[language\]/\[title-raw\]

I am using Content Translation module.

I created english version of selected page. Alias was generated ok.

But even if I am admin, I have 404 when I want to view this page.

Could somebody give me any advice?

**EDIT**

I change pathauto alias setting to

> \[title-raw\]

still 404.

If I use raw address of page (node/232) it works.

**EDIT 2**

After recreate page, alias works ok (:

# Answer
In the Workflow settings of the type page you should choose Multilingual support: enabled or eabled with translation if you want to have the page in 4 different versions on their own.

If you simply choose enabled you can e.g. make as many path aliases as languages are active for one and the same page. If you choose "with translation" you can make translation nodes after creating the page. There is also a rules integration, that makes you all translation nodes automatically.

If you enable Multilingual support you will see in pathauto autmoatic section, that you can choose a path for every enabled language. The prefix you shouldn't use, because itis handled by drupal and/or modules itself. You can change the behaviour in the languages menu under site configuration.
> 1 votes

---
Tags: 6, uri, i18n-l10n, path-aliases
---


# Question
Title: field update on field with no permission
I have a field (selectbox) that is configured to not be shown (no 'view' permission) on a particular role, nor not to be edited (no 'edit' permission) by the same role. This role is only able to edit other fields. So normally, when this role edits the content, he should not see this particular field. But I want this field to automatically get updated via 'Triggered Rules'. I don't want anyone able to see this field in the first place. For example:

Price Range Field:

* Lowest to 1M
* Between 1M to 5M
* Between 5M to 10M
* Greater than 10M

This is my set up so I could use this in exposed filter views to filter price ranges.

When that role enters some price in 'field\_price', a trigger updates the price range field.

I do not have a problem with creating a new content, the price range gets filled out properly. However, when editing this content, I get this error 'Price Range: Illegal value'. When I make this field permissible for this role, this field gets updated properly.

I'm quite sure there is a way to this without doing any complicated stuffs.

Thanks in advance!

# Answer
I would use a Computed Field for this purpose, then you can define in PHP how to populate it.
Or you can populate it with a hook\_nodeapi submit.
> 1 votes

---
Tags: 6, entities
---


# Question
Title: How to enable "find content" for a role in Drupal 7?
I created a role called "Writer". When a writer logs into the system, they have the black toolbar across the top of the page. They have the "add content" link which is great. How do I enable the "find content" link for a writer?

# Answer
> 3 votes
Go to admin/people/permissions and enable "Access the content overview page "

---
Tags: 7, users, nodes
---


# Question
Title: How to disable "publish" content for a particular role?
I created a role called writer who should have the ability to create content, but not be allowed to publish it. A person with the admin role can review the content then publish it.

Also, if a writer edits existing content, it can not be immediately published to the website. Only an admin can publish it after review. Until then, the old version is displayed.

How do i disable the ability to publish for a person with the writer role?

# Answer
Just unchecked publish checkbox on content type setting page and hide this field with CSS if user has writer role or remove it programmatically on the same condition with hook\_form\_alter
> 1 votes

# Answer
You might also want to take a look at The Workbench module. Out of the box it gives three important solutions:

* a unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time.
* the ability to control who has access to edit any content based on an organization's structure not the web site structure
* **a customizable editorial workflow that integrates with the access control feature described above or works independently on its own**
> 0 votes

---
Tags: users, nodes
---


title: AutoMenu and Tokens

text:
# Question
Title: AutoMenu and Tokens
I am working in Drupal 6.22 and want to know if anybody knows of a way to get tokens working with the AutoMenu module? Its become a bit of an issue from a usability perspective and want to have this working with my breadcrumbs (using menu\_breadcrumb).

For instance I have the ability to create multiple galleries, which fall under `/media/galleries/[gallery-title-raw]`, and the breadcrumb reads accordingly as `Home > Media > Galleries > [gallery-title-raw]`. It would make sense then for individual photos (photo node) to fall under its parent gallery. So when a user navigates to the full node for the photo, the breadcrumb should read: `Home > Media > Galleries > [gallery-title-raw] > [photo-title-raw]` and a hidden menu item for the photo is automatically created.

Here's hoping that someone out there found a way to make this work :)

Cheers!

# Answer
The Custom Breadcrumbs module integrates nicely with tokens and allows for per content type breadcrumb trails. If your photos are linked to your gallery via a nodereference or something else that already has a token, using Custom Breadcrumbs would work without any coding. If you are using a gallery solution where the photo content type doesn't have a token for the gallery it is associated with, you will have to implement the Token module's hooks to add that data as an available token for use in Custom Breadcrumbs.
> 1 votes

---
Tags: 6, routes, tokens
---


# Question
Title: is there a way to make template for set of nodes?
Is it possible to make a template for set of nodes in Drupal 7 for example page--node--\[601-602-603-604\].tpl and if so what is it?

# Answer
> 4 votes
You can't do like you explain.

What you can do instead is to add a custom template suggestion for the specific nodes in the preprocess\_node function to make the nodes use a specific template that can have any name.

# Answer
> 0 votes
I use this to style a page of nodes of a certain content-type or a node of certain type.

```
function THEMENAME_preprocess_page(&$variables, $hook) {
   //some other stuff
    if (isset($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__type__'. $variables['node']->type;
    $variables['theme_hook_suggestions'][] = "page__node__" . $variables['node']->nid;
  }
}

```

Then you would have page--type--machine\_name.tpl.php, etc...

---
Tags: nodes, theming
---


# Question
Title: Display all terms from a specific vocabulary in my template
I have a page where I want to display the terms for the vocabulary named "Services" in an unordered list. The Page is in no way associated with the vocabulary, I just want to display the terms at the end of the article. What should I type in my file?

# Answer
> 2 votes
I wouldn't type anything in a file.

Instead, use the Views module and create a block view that lists all of the terms in that vocabulary, then display that block immediately after the main content on the specific page that you're talking about.

---
Tags: 7, nodes
---


title: Rotate through views result weekly

text:
# Question
Title: Rotate through views result weekly
I have a content type called "Tips of the Week" and in a Views block. I would like to display one tip at a time, but have it display the next tip in a week's time based on the content's post date. If a tip is added, it is entered into the rotation of the tips.

A tip might not be added every week, so I do not think it can be solely based on the post date of the tips. Instead, is there a way to cycle through the offset.

I have tried different sort criteria, and the closest one I could find was random, but that changes every time the page loads.

How can I accomplish this?

Thanks!

# Answer
> 0 votes
Add a date field to your tip of the week content type. That date field will indicate when the tip becomes visible on the site. Order your view by date (descending), and filter out all entries where the date field is greater than the current date.

If you want to write some code, you can add a hook that runs when you submit the form, and, if you leave the date field blank, have it select the maximum value of the date field out of the database, add a week to that, and fill the date in automatically.

# Answer
> 0 votes
You should try arguments in Views. Add Date (Node Posted) as an argument.

**Action to take if argument is not present:**

Select *Provide default argument*
and then *Current Date*

Select *Granularity:* as week

Check *Node: Post date* from Date Fields

They way for every week tip of current week will be filter to show.

---
Tags: 7, views
---


title: Forbid the publication

text:
# Question
Title: Forbid the publication
I created a new role for the user to write.
How do I forbid the publication to a redactor?

# Answer
If I understand the question, I think you want the Workflow module. You probably also need the Revisioning module, and potentially the Module Grants and Rules modules.

I don't recall testing this particular workflow, though. It is also worth noting that workflows can be a pain to set up, and adding workflow to an existing site can be problematic because existing nodes will not have a workflow yet (some scripts to fix this are available if you poke around).

This question is tagged for Drupal 7, which presents a problem with this solution. Workflow and Module Grants don't have D7 versions yet. There are discussions about ports in the issues, but nothing has been released yet.
> 2 votes

# Answer
Check out the publish content module. It's available for d6 and d7.
> 1 votes

# Answer
## I asked a related question. And here's the answer someone gave me

Just unchecked publish checkbox on content type setting page and hide this field with CSS if user has writer role or remove it programmatically on the same condition with hook\_form\_alter

Use the revisioning module to prevent writer's from publishing "revisions of existing content".
> 0 votes

---
Tags: 7, users
---


# Question
Title: db_query() doesn't seem to run in module
I have a custom user-management module in my Drupal 6 site. We are a corporate subscription service and needed a way for a subscribing company's primary user to delete other users from their company. When this happens, we need to not only delete the Drupal user record for that person, but also make some changes to a record in another mySQL database that's connected to one of our internal non-Drupal systems. There's a lot of jquery stuff involved, but the main thing is that a user clicks a delete link next to a name in a list of users. The link looks like this:

```
http://mysite.com/account/manage/disappear/1/182741

```

The final three params are what we use - disappear is the action (there are also promote and demote, which allow the primary user to change the type of account other users have), 1 is the Drupal ID of the primary user (in this case, I'm logged in as user 1), and the final param is the ID from our non-Drupal database. From that ID's record, we can find the Drupal account ID we need to delete (as well as other info we need for this function that are not specifically Drupal-related.)

Most of it works correctly - the user is deleted and the email is sent, but the query that's supposed to update our other database doesn't seem to be running. Can anyone help me out? Is there a way to debug queries? I know I'm dealing with the correct records; the error\_log line right inside the disappear case returns the correct values.

Here's the function (I've stripped out the promote and drop actions since they work. Also, Viola is our intranet app where the non-Drupal database lives)

```
function user_manage_function($action, $uid, $viola, $email_prefix = '', $email_domain = '') {

    // action = delete, promote or drop?
    // uid = the UID of the primary user, as a security measure
    // viola = the Viola people ID of the person we want to promote, delete or drop
    // email fields = if the PU adds an email address, we need to verify it

    global $user;

    if ($user->uid == $uid) { # just a sanity check to make sure we know the current primary user

        // see what their UID is ... set $vuid = the drupal uid of the promoted/dropped/deleted user
        $people_row = db_fetch_object(db_query("SELECT institute_uid, email FROM {ismi.new_people} WHERE id = %d", $viola));
        $vuid = $people_row->institute_uid;
        $viola_email = $people_row->email;
        $data = 'pending';

        if ($vuid) {

            switch ($action) {

            case "disappear":
                error_log("inside main disappear - vuid=$vuid and viola=$viola");
                  $quer = db_query("UPDATE {ismi.new_people} SET active = 0, insitute_uid = 0 WHERE id = %d", $viola);
                    user_delete(array(), $vuid);
                    $message = array(
                        'to'                =>  'test@test.com',
                        'subject'       =>  t('User deleted by primary user'),
                        'body'          =>  t($user->name . ' (' .$user->mail.') just deleted the Institute website account for '. $viola_email),
                        'headers'       =>  array('From'=>'test@test.com'),
                    );
                    drupal_mail_send($message);
                    break;
            }

            $data = 'success';
    }
  }
}

```

# Answer
> 3 votes
You write that

> but also make some changes to a record in another mySQL database that's connected to one of our internal non-Drupal systems

so I figure that you need to query a different MySQL database, but in your don't change the active database using `db_set_active`. This is most likely the root to your problem.

If the `SELECT` query works, then the code you have provided should work just fine.

A simple way to test your problem, would be run `db_query` on a known record and see if you can alter it. Devel also offers query logging, which would allow you to log the actual `UPDATE` and alternatively try to run the raw query through a MySQL interface.

Another explanation could be that you have the ismi.new\_people table in the Drupal db, so you in fact are updating the wrong table/database.

Another possible problem is database permissions. Do your DB user have read only access?

---
Tags: database
---


title: Drush, Views and Page Manager

text:
# Question
Title: Drush, Views and Page Manager
I've got several custom modules I have written and they make liberal use of Views, Panels and the CTools page manager. I've exported the views, panels and page variants into the module code, and am wondering if there is any way I can use drush to revert my production site to the new views/panels/variants after I do the rsync, rather than logging in and commencing the click, wait, click routine.

# Answer
> 0 votes
There is `drush views-revert`, which alone will give you a list of views to revert, or can also take multiple views names as arguments, as in `drush vr archive frontpage`.

So far, nothing like that exists for Panels.

However, if you were to use the Features module to export the Views and Panels, instead of a custom module, you could use the drush commands that Features provides.

---
Tags: views, panels, drush, chaos-tool-suite
---