title: Install profile

text:
# Question
Title: Install profile
I'm creating a Drupal installation profile and transfering taxonomy vocabularies through features, like this:

**my\_profile.info:**
; Features
...
dependencies\[\] = my\_profile\_taxonomy\_vocabularies
...

These vocabularies are created correctly, but I also should automatically create terms. If I put my function which creates terms into **my\_profile\_install()**, it's not working. At this moment, vocabularies are not available. Also I've tried to use direct SQL query and vocabularies are not created at this moment.

Where can I put my code for terms creation, when vocabularies are already created and available?

# Answer
You need to create a install task in .profile, install tasks are run after modules are enabled.

Here's an example you can use as a starting point:

```
<?php

/**
 * Implements hook_install_tasks().
 */
function PROFILE_install_tasks() {
  $tasks = array(
    'create_taxonomy_terms' => array(
      'display_name' => st('Create taxonomy terms'),
      'type' => 'normal', // the default
    ),
  );
  return $tasks;
}

/**
 * Install task: Create taxonomy terms.
 */
function PROFILE_create_taxonomy_terms() {
  // your stuff.
}

```

The install task is declared as normal, that means the related function will be executed. If you're going to create a lot of terms, better write a batch. See the api docs for reference:

http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_install\_tasks/7
> 7 votes

---
Tags: 7, distributions
---


# Question
Title: How to let users subscribe and be notified (email) when certain type of content or taxonomy is created?
I would like to notify users (by email) whenever a content type or taxonomy term they subscribed to is submitted.

I thought Rules may play a role in this but can't figure out how to let them subscribe to the content type/taxonomy term

Any ideas are welcome

I'm using Drupal 7

# Answer
> 0 votes
I came across the Subscriptions module and it does exactly what I needed. Here is a quote about it (from the module's project page):

> ... enables users to subscribe to be notified of changes to nodes or taxonomies, such as new comments in specific forums, or additions to some category of blog. Once enabled, all nodes will have an additional link that allows the user to change their subscriptions. Users have tab on their user screen to manage their own subscriptions. Users can also set an auto-subscribe function which notifies the user if anyone comments on posts they have made. Admins can turn this on by default.

# Answer
> 0 votes
You could do the subscription by adding the taxonomie term to the user profile. If you don't have to many content types you could add it as a simple select list to the profile. This can be done at `admin/config/people/accounts/fields`.

As you sugested you can use Rules to get triggered about creates/updates of content or taxonomy terms. You might have to implement custom rules conditions or actions in PHP in a custom module to get exactly what you need. Check the differen hooks to define your own rules conditions or actions. hook\_rules\_action\_info and hook\_rules\_condition\_info are the most interesting for you.

To lear how to build your own rules code you find many examples in Drupal core and contributed modules.

---
Tags: 7, notifications
---


title: Drupal Commerce Sale Price

text:
# Question
Title: Drupal Commerce Sale Price
On a Drupal Commerce project of about 2000 products, the client wants to set sale prices for some of the products. The client also wants to set a sale expiration per product so that after a certain date, the product is no longer on sale. Is there a module or technique that could accomplish this easily?

# Answer
Commerce Sale Price provides per-product sale prices. Someone offered to provide exactly what you want but they haven't actually done so yet. The only thorny thing about achieving this is being able to work with Commerce's precalculated price system (you'll find some links on the Commerce Sale Price project page). At first you'd think this could all be done using Rules, but as I understand it, the system requires that a discount rule either be related to some global condition such as the date (which can get checked when a View is executed) or related to the product itself (such as an *on sale* field). The problem with your requirements is that the price is related to something external (the date) *and* something attached to the product. The only way I can see around this is by having a cron run that switches on/off the normal sale price flag based on the schedule fields (and causes the precalculated prices associated with that product to be updated).

For any of the precalculated stuff to work you'll need to follow the instructions on Sale Price's project page (you need to patch Commerce and use a sandbox module).

Addendum: Having said all that, if you don't ever need to use the precalculated price as a field in a View then I think you can do things entirely with Rules.
> 1 votes

# Answer
You can use Rules in combination with price textfield attached to the product entity.

Here are the steps:

* Add a price textfield to the product entity and call is discount price or something similar.
* Add a rule that react to the Redeem a coupon event
* Add conditions: Data comparison commerce-line-item:type value = product, Entity has field: check for the price textfield from step one, check that data value is not empty, add date check for expiration.
* Under actions add a calculation that add the amount of the field to the unit price(Data/Calculate a value).
* Uses VBO to assign the discount to products in bulk.

This is a somewhat of a lengthy process but other than writing a custom module, Commerce really does not provide any other solution (at least not one that is documented anywhere...).
> 1 votes

---
Tags: commerce
---


# Question
Title: Views : Make a block related to a page (with flag/addthis/privatemsg as fields in this block)
It's difficult to explain but i'll try to do my best.

I have a basic views (Page) with all my fields displaying. My purpose is to take some of this fields to display them in a block(on the left sidebar)

**This fields i want to display in a block are:**

* Flag: bookmarks
* AddThis: Toolbox
* Private msg (send message to the author)

I follow all the screemcast "Taming the beast" (from nodeone.se) especially part 24 when Johan Falk explain how to make a block with a related content to a page (without using page manager)

When i go to my article my url is like that: **/fiches-produits-services/100** (100=\>\[nid\])

I follow this step when i create my block:

* Add my fields etc.
* Add contextual filter : **content: nid**
* click on it, go to **WHEN THE FILTER VALUE IS NOT AVAILABLE**
* Click on **Provide default value**
* Select **Content ID from url**

But after that nothing, the block isn't here. When i click on **Display all results for the specified field** on the same section, the block appears but with all the flags, the privatemsg and socials icons from all my article.

It's not the bahavior i want, i would like to have just the flag related to the article, just the link from private messages related to the article etc.

I don't know if i missed something. In the screemcast he did that with content(article) related with another content (basic page), maybe we can't do that with flag, addThis or privatemsg because it's not really a content (But i don't really know i'm new).

So if someone can help me to understand that, i'll be very grateful.

# Answer
I found a way this week to get the good behavior.

i understood my mistake! My url was like that *www.example.com/my-product/2* (made with pathauto)

When i selected **content ID from URL** my block was empty because he couldn't retrieve the good argument from the url (because my node id was in second position) But when i go to *www.example.com/node/2* it works fine

To resolve my problem i select **raw value from URL** instead of **content ID from URL** (because with that option we can select which argument we want to retrieve --that was the second for me because of my custom url)

In summary i follow this step :

* Add contextual filter : content: nid
* click on it, go to WHEN THE FILTER VALUE IS NOT AVAILABLE
* Click on Provide default value
* Select **raw value from URL**
* Select the argument you want to retrieve from the url (path component)
* I check **Specify validation criteria**
* **Validator** : content
* **Filter value format** : node id
* **Action to take if filter value does not validate** : no result

It was a stupid mistake :) but i learn some stuff :)
> 0 votes

---
Tags: 7, views, flags, privatemsg
---


# Question
Title: How do I display all the nodes in an organic group?
I'm on d7. Im trying to figure out how to display all the nodes that are in an organic group. I feel like this is a major thing that the OG module should do and don't know why I cant figure it out. I have views installed and have looked at the OG content view, but it doesn't display anything when I test it with the preview filter. Ive seen a video on how to do this with panels, but I don't have panels installed and don't plan on it. Thanks for the help.

# Answer
Here's how you can do it with views in Drupal 7. Create a new view of nodes as you normally would, but make sure you set up the appropriate relationship for it that will allow you to filter your nodes based on their group membership:

1. Add a relationship (under the 'Advanced' section of the view)
2. Select the 'OG membership: OG membership from Node' field, which is under the 'OG membership' section of the fields
3. Mark this as a required relationship on the next screen if you don't want to include nodes/content that do not have a group
4. Only after you've added that relationship will you be able to see the appropriate 'Group id' filter. Go ahead and add a 'Contextual filter', also under the 'Advanced' section and select 'OG membership: Group ID'.
5. This filter will now allow you to input the Group Id as a filter to the view through the URL (test it with www.\[your site\].com/\[your view path\]/\[group id\]) or by figuring out which group you're currently in if you set the following screen properly for the contextual filter
6. You can now test this in the view preview pane by entering in different OG id's and seeing that it should filter the list of nodes to ones only with those Groups set as their audience.

Let us know if this worked for you!!
> 17 votes

---
Tags: 7, views, organic-groups
---


title: preprocess_node_webform is not working

text:
# Question
Title: preprocess_node_webform is not working
I wanted the error messages from the webform to be customised. So I wrote following piece of code in template.php of my theme.

```
function sandesh_preprocess_node_webform(&$vars, $hook) {
 if ($vars['node']->nid == "41" && is_array($_SESSION['messages']['error']))   {
 $errors = &$_SESSION['messages']['error'];
 $find = 'email';

 for($idx = 0; $idx < count($errors); $idx++) {
  if (substr($errors[$idx], 0, strlen($find)) == $find) {
  $errors[$idx] = 'Please enter the email field';
  break;
   }
 }

}
}

```

But this is not working. Is there something wrong in the code? Or is there any other method to get customized error message in the webforms ? Thank you

# Answer
You don't need to code to do this. Have a look at the answers to this questions to find more information: How to modify user messages without hacking core user module?
> 2 votes

---
Tags: 7, webforms, theming
---


# Question
Title: Latest Best Practise: Reusing content/functionality between Drupal 7 sites
Many of the Drupal 7 websites I make have the same functionality (e.g. blogs, news section, special offers). At the moment, I have to re-create the content types, fields, blocks and Views each time. I am looking for a better way of working.

There seems to be a lot of modules that can help me, but I'm not sure which is the latest best practice.

Features \- The module seems great for exporting content types, fields, menus and views. However, it does not seem to be able to export blocks, block positions or content.

Features extra \- This module is designed for exporting blocks. However, on the project page, it says that UUID Features Integration is the future.

UUID Features Integration \- This module doesn't seem to work (although A patch is available to fix things). Apparently, it has been dropped in favor of Deploy.

Deploy \- This doesn't seem to work with blocks and is designed more for exporting nodes. I'm not really sure how it is a replacement for UUID Features.

Default Content \- Another module that seems similar to deploy. (i.e. exports nodes)

Apps \- This seems to be a completely new approach that is a replacement for features. There is very little documentation on how to use it.

StrongArm \- A lot of articles state that this module is essential for getting the most out of Features. However, I'm not sure how it relates.

I have searched quite extensively, but there seems to be a lot of conflicting information,

What is the best practice for what I want to achieve?

I would also like something that would work with Drush or a GUI so I can just select if I want a new site to have a blog, news archive special offer etc when building the new site in the first place.

# Answer
There are two more options to consider:

1. User Drush make to create your own distribution:

> Drush make is an extension to drush that can create a ready-to-use drupal site, pulling sources from various locations. It does this by parsing a flat text file (similar to a drupal .info file) and downloading the sources it describes. In practical terms, this means that it is possible to distribute a complicated Drupal distribution as a single text file.
2. Run your sites in a multi site environment. This way you can easily reuse all installed modules and themes.

> If you are running more than one Drupal site, you can simplify management and upgrading of your sites by using the multi-site feature. Multi-site allows you to share a single Drupal installation (including core code, contributed modules, and themes) among several sites.
> 3 votes

---
Tags: nodes
---


# Question
Title: Customizing the form for a field in the content edit form
I have configured a taxonomy as field of a content type, but I want to replace the checkbox label (work with iphone) with the image field of that taxonomy. (See the screenshot.)

I only know to alter node.pages.inc at row 290 by adding the following code.

```
$form['product_label'] = array(
    '#type' => 'checkboxes',
    '#title' => 'Checkboxes Title',
    '#title_display' => 'before',
    '#default_value' => array(0,2),
    '#options' => array(
      0 => 'option one',
      1 => 'option two',
      2 => 'option three',
    ),
    '#theme' => 'testmodule_checkboxes',
  );

```

product\_label is the checkbox name. The above code is to override the current checkbox field.

I think this not the best way. Can anyone provide any direction? What module can do it?

Here is the dump of the checkbox field of the form.

```
array(6) { ["#type"]=> string(9) "container" ["#attributes"]=> array(1) { ["class"]=> array(3) { [0]=> string(34) "field-type-taxonomy-term-reference" [1]=> string(22) "field-name-field-icon1" [2]=> string(28) "field-widget-options-buttons" } } ["#weight"]=> string(1) "2" ["#tree"]=> bool(true) ["#language"]=> string(3) "und" ["und"]=> array(18) { ["#entity"]=> object(stdClass)#91 (12) { ["uid"]=> string(1) "1" ["name"]=> string(5) "admin" ["type"]=> string(7) "product" ["language"]=> string(3) "und" ["title"]=> NULL ["status"]=> int(0) ["promote"]=> int(0) ["sticky"]=> int(0) ["created"]=> int(1344929691) ["revision"]=> bool(false) ["comment"]=> string(1) "1" ["menu"]=> array(12) { ["link_title"]=> string(0) "" ["mlid"]=> int(0) ["plid"]=> int(0) ["menu_name"]=> string(9) "main-menu" ["weight"]=> int(0) ["options"]=> array(0) { } ["module"]=> string(4) "menu" ["expanded"]=> int(0) ["hidden"]=> int(0) ["has_children"]=> int(0) ["customized"]=> int(0) ["parent_depth_limit"]=> int(8) } } ["#entity_type"]=> string(4) "node" ["#bundle"]=> string(7) "product" ["#field_name"]=> string(11) "field_icon1" ["#language"]=> string(3) "und" ["#field_parents"]=> array(0) { } ["#columns"]=> array(1) { [0]=> string(3) "tid" } ["#title"]=> string(4) "icon" ["#description"]=> string(0) "" ["#required"]=> bool(false) ["#delta"]=> int(0) ["#type"]=> string(10) "checkboxes" ["#default_value"]=> array(0) { } ["#options"]=> array(1) { [14]=> string(16) "Work with iphone" } ["#value_key"]=> string(3) "tid" ["#element_validate"]=> array(1) { [0]=> string(29) "options_field_widget_validate" } ["#properties"]=> array(4) { ["filter_xss"]=> bool(true) ["strip_tags"]=> bool(false) ["empty_option"]=> bool(false) ["optgroups"]=> bool(false) } ["#after_build"]=> array(1) { [0]=> string(30) "field_form_element_after_build" } } }

```

The problem is that I can't find the image (filename) which is a custom field of the taxonomy. I want to replace "work with iphone" with the uploaded image. How can I do this?

# Answer
first of all use hook\_form\_alter to alter any form. so in your custom module something like this

```
function CUSTOMMODULENAME_form_alter(&$form, $form_state, $form_id){
   if ($form_id == 'FORM_ID'){
     --
   }

```
> 1 votes

---
Tags: entities
---


# Question
Title: How to change error message of the webform
> **Possible Duplicate:**
> preprocess\_node\_webform is not working

How can I change the default error message of the webform ? For example "The name field is required" to "Please enter your name". Where should I make changes to achieve this ?

# Answer
You can use drupal\_set\_message().
> 1 votes

---
Tags: 7, webforms
---


title: Remove form elements with ajax

text:
# Question
Title: Remove form elements with ajax
I have made a form with form loop as I am setting the `$form_state['number']` for the fields count.

I want to remove a full row after clicking on remove button in front of row by taking *row\_id*. So I want to ask is there any way to pass id of row in submit function of remove button or check which button pressed and fetching id of that button in submit function.

```
 for ($i = 1; $i <= $form_state['number']; $i++) {
    $form['myform'][$i]['email'] = array(
        '#type' => 'textfield',
        '#size' => 18,
        '#autocomplete_path' => 'mypath',
        '#prefix' => '<div id="feedbackrow_'.$i.'">',
    );
    $form['myform'][$i]['roles'] = array(
        '#type' => 'select',
        '#options' => array('' => '', 'master' => 'master', 'student' => 'student'),
    );
     $form['oldfeedbackmarkup'][$i]['remove'] = array(
       '#type' => 'submit',
       '#value' => t('Remove'),
       '#submit' => array('mysubmit_button'),
       '#ajax' => array(
              'wrapper' => 'myform_wrapper',
              'callback' => 'submit_by_ajax',
        ),
        '#prefix' => '<div class="form-item">',
        '#suffix' => '</div></div>',
    );
}

```

# Answer
> 1 votes
It's actually easier than you think :)

You can access a $form\_state\['triggering\_element'\] in your ajax callback function.

Something like this:

```
function my_ajax_callback($form, $form_state) {
  $ps = &$form_state['triggering_element']['#parents'];
  $k = $ps[2]; // field collection row number
  $collection = $form[$ps[0]][$ps[1]][$ps[2]];
  $element = $ps[3];
  ...

```

that was the snippet to access a changed textfield inside a field collection with multiple rows. Just adopt it for your particular form structure.

---
Tags: 7, ajax
---


title: List Box Elements

text:
# Question
Title: List Box Elements
> How to Move values of one list box to another in form module in Drupal and reverse of it? The values of Listbox are coming from Database

# Answer
Just fiddling with JS should not be enough. Assuming you've built your form using FAPI, it should not accept your form result, as the backend does not know about this options.

You need to make sure Drupal is accepting the options you changed with JS. Please have a look at this discussion at d.o. . You have more than one option to solve this. Either make an AJAX call back rebuild the lists including the changed options. You could also change the options with JS only (as suggested in the other answers) and run your own validation handler to accept the options.
> 0 votes

# Answer
```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == "YOUR_FORM_ID") {
        /*Copy options from one element to another*/
        $form['LIST_BOX_2']['#options'] = $form['LIST_BOX_1']['#options'];
        /*Reverse options in the second element*/
        $form['LIST_BOX_2']['#options'] = array_reverse($form['LIST_BOX_2']['#options']);
    }
}

```
> 0 votes

# Answer
Check here for javascript: http://devblog.jasonhuck.com/2008/03/08/combo-select-boxes-in-jquery/
> 0 votes

---
Tags: forms
---


title: Creating a "Remind User" link in Views

text:
# Question
Title: Creating a "Remind User" link in Views
I've created a View that lists when a user has last logged in, using table format. I'm wanting to add a field that's a link to remind the user to login again (I've used a UID field and am rewriting the output to be a link, with UID as an argument at the end).

**What's the most sensible way to trigger an email via Views?**

Thanks!

# Answer
Instead of Views, I would use Rules + Rules Scheduler (bundled with Rules). This will allow the site itself to automatically send e-mail reminders at intervals you specify. Johan Falk explains how to set this up in his Rules Scheduler screencasts.

EDIT: To do this in Views, I would add the Flag module, which also integrates with Rules. Set up a flag for "Send reminder e-mail" (give permissions only to admin, etc.) Then, write a rule that sends an e-mail that is triggered on the event "User is flagged..." Last, add the flag as a relationship in your view and then add a flag link.

You will have to consider what to do about unflagging users. By default, the user will show up as flagged after a reminder is sent, which might be nice because you'll know that the user has already received a reminder. However, if you need something more sophisticated, you could make an additional rule that automatically unflags the user after he/she is flagged and keep track of the number of reminders you have sent by using flag's count property (also accessible via rules/views).
> 1 votes

---
Tags: 7, views, rules, emails
---


title: Order nodes via drag 'n drop

text:
# Question
Title: Order nodes via drag 'n drop
I'm looking for an easy way for my clients to re-arrange the order of nodes. When creating a content type I added a "weight" field for them to change, but of course with a lot of content this is a lot of work.

Is there any module that allows drag 'n drop to change the order of nodes being displayed in a view?

# Answer
> 1 votes
I think the Nodequeue module is just the module for this job.

# Answer
> 2 votes
I think DraggableViews is what you are looking for. Here is a quote about it (from the module's project page):

> ... makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.
>
> Have you ever rearranged Blocks, sorted Taxonomy terms or reordered Menu items at the Drupal administration pages? All these pages use the tabledrag.js javascript that enables Drag'n Drop on HTML-tables.
>
> With DraggableViews you can apply this tabledrag.js to any Views-generated table.

---
Tags: views
---


# Question
Title: Query parameters from $_GET vs. using the Drupal menu path
Page callbacks can receive wildcard arguments through the Drupal (6 and 7) menu system and using this results in quite nice and clean URLs. Core uses this for things like loading the nodes by their node id. The alternative is to use straight query parameters from $\_GET as usual in PHP. Core seems to use this in a few places, for form redirects, the pager etc.

When would it be appropriate to bypass the menu system and just use a query parameter? What are the pros and cons of the two options for parameter handling?

# Answer
There's a page with a logic that puts it together and that is determined by path. Core never bypasses the menu router. Parameters are somewhat orthogonal to this. For example, a page doesn't change in itself just because there's a form in it that uses a destination to redirect to said page so we do not add it to the clean URL. Pager is a little different because you could argue that path/to/some/view could become path/to/some/view/1 path/to/some/view/2 as it is paged but how do you differentiate real arguments (like a node id) from a pager? It's better to use a query parameter.
> 1 votes

---
Tags: routes
---


# Question
Title: How do I hide one word from a view result column
I have a view which displays content overview using a table. I have joined two columns, a and b, in the table.

I want the column to display like the red square... currently they show as the red ellipse. Column a is "moderation state" and column b is "publish time".

# Answer
> 0 votes
Since I want to display an item from two different tables, I used an if-else statement.

```
if ($row->state == 'published') {
  echo "$date";
}
else {
  echo "$row->state";
}

```

---
Tags: 7, views, workbench
---


# Question
Title: How can I change the css classes on a menu's ul when it is placed in a particular region?
Drupal 7: I am struggling to figure out a way to change the menu structure that is printed when I place a menu block in a particular region.

What I want to do is change the classes on the ul when the menu is printed to a sidebar.

Everything I can find, and attempt will change the structure for all menus, but I need to print them differently depending where I put the menu.

Also, I need it to work for any menu I place in the region if possible. I will be creating menus for different areas of the site, and I hope I can get this to work based on the region that the menu is placed in.

Thank you

# Answer
I'll give a couple answers to this and I'm basing it on the Twitter Bootstrap theme because of your comment back to onirio. I had the same issue using the same theme.

If all you want to do is change the class name once (it doesn't sound like it, hence the second answer - stay tuned), then you can visit the function "twitter\_bootstrap\_preprocess\_page" in twitter\_bootstrap/template.php. Within there, you will find this construct:

```
  $variables['primary_nav'] = theme('twitter_bootstrap_links', array(
  'links' => $variables['main_menu'],
  'attributes' => array(
    'id' => 'main-menu',
    'class' => array('nav'),
  ),

```

Simply, change the 'nav' to be whatever you want it to be. That will change it everywhere. Better would be to do as I did and sub-theme and change that rather than the actual Twitter Bootstrap theme.

Second answer:

If you want to do something more interesting, then consider instead where the aforementioned code is used. It is used in the function "twitter\_bootstrap\_twitter\_bootstrap\_links" found within includes/modules/theme.inc. You will see that function using these variables as such:

```
   links = $variables['links'];
   $attributes = $variables['attributes'];
   ...
   $output .= '<ul' . drupal_attributes($attributes) . '>';

```

So, if you want to get more fancy, then you'll need to modify the way that the ul is built. That may be served through researching or posting another more targeted question? Again, doing this in a sub-theme would be best.
> 2 votes

# Answer
You don't need to change or add new classes because each region has already a class. You need to specifically reference each menu class () in your stylesheet by adding first your region class name:

```
#region-menu ul.menu li {display: inline...}

#region-sidebar-first ul.menu li {display: block...}

etc...

```

so check you won't interfere.

Make sure the main menu has a unique reference as #region-menu to avoid inheritance.
> 4 votes

# Answer
You're going to have a hard time strong-arming Twitter Bootstrap's CSS structure into Drupal. The functions in Drupal that build the menu tree structure (including adding in the UL) are completely unaware of where the menu ends up. I'm sure you will run into lots of other situations like this.

One option is to create a custom module and manually build each menu in code. You would need to write database queries rather than utilizing the functions available in the API to build the menu structure. You can look at any contrib module that requires custom menu structure for examples. Superfish and MegaMenu would give good guidance.

The option I would suggest is keeping your own fork of the Twitter Bootstrap code that is customized for your Drupal site. If you utilize git to do this and keep patches of your customizations, you shouldn't have a problem merging in any future updates to Twitter's code.
> 0 votes

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


# Question
Title: Right way of data organasing and structuring
I have the following structure of the site that is revealed in main menu hierarchy:

* News
+ news category 1
+ news category 2

* Documents
+ document category 1
+ document category 2

All the pages mostly will be presented with a single Content Type. But for different places in menu hierarchy page regions should consist of different blocks.

e.g., for a node from "news category 1" there will be a search block placed in the sidebar, for th enode from "document category 2" -- the login block.

I see a quite moot "solution" for this. I will have to turn nodes' urls into somewhat like "mysite.org/news/category1/..." and set visibility options to blocks through url patterns. Is it a right way to follow? But in this case the editor (not me) will have to invent and handcode url aliases when creating node and it seems to me very unreliable to entrust him with the site structure.

Another way -- create different content types for every categories and generate aliases automatically but it seems to me a bit crazy.

What do you think about that?

# Answer
If your categories are pre-defined and won't change then I think your solution of using blocks regions and block visibility settings may be the best. If you need more complex visibility settings the Context module should be able to help.
> 0 votes

---
Tags: uri
---


# Question
Title: Pre-cautions to take when manipulating table structures
There are some use-cases for modifying the tables manually in the database. One such, when using MySQL, is "downgrading" all cache\_\* tables from InnoDB to MyISAM, to get better performance.

Another use case is text fields storing data that require 4 byte encoding, instead of the normal 3 bytes. Manually this would look like:

`ALTER TABLE t1 DEFAULT CHARACTER SET utf8mb4, MODIFY col1 CHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;`

And then when interacting with this field ones need to issue `SET NAMES 'utf8mb4'` to ensure the connection passed data properly.

Is there any functionality in DBTNG to handle such odd use-cases, in part or in whole? Or will one need to handle them entirely manually? Are there any other pre-cautions one should take, to reduce the risk of future problems in this type of case.

# Answer
I'm not aware of any support for either of those changes in DBTNG, it's just something you need to do manually.

Luckily that means that once you've done it there's no chance of DBTNG knowing or caring about it - everything should continue to work as you expect.
> 1 votes

---
Tags: database
---


# Question
Title: How should I deal with Views URL parameter "page" in Google web master tool?
I have node view which has pager with URL parameter "page". I want Google bot crawls all the pages ( `page=1` `page=2` `page=3...` ) but regard all of them as just one and only the first page (without parameter "page") should appear on the search result.

On the webmaster setting page I have set URL parameter for "page" as below but now I'm getting duplicated title and description.

> How does this parameter affect page content: `Paginates`
> Which URLs with this parameter should Googlebot crawl: `Every URL`

What's the best way to configure URL parameter for Views "page" on Google Webmaster Tools?

# Answer
There is no "best way" I think. It depends on your site niche. I have a blog and it has page=X like URL params. I have set it as "paginates" and "Crawl all pages" same as your setup. It now crawls and shows all pages. That duplicate title problem is still there at my site. I don't mind it because I didn't receive any dupe problem from Google.

If you really want to change it, you can do it in template.php level.

```
function THEMENAME_preprocess_html(&$vars) {
 if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0){
   $vars['head_title'] = str_replace('|', '('.t('Page @pager', array('@pager' => $_GET['page'] + 1)).') |', $vars['head_title'], 1);
 }
}

```

This will rewrite your HTML title tag's content to "My Blog Posts (Page 2) | MyAwesomeBlog" on Pages where a pager is set. We add 1 to the pager value because when you are on page=1, it's actually the second page for human users.
> 0 votes

# Answer
Try Nodewords module for Drupal 6 or Meta tags for Drupal 7. These modules will allow you configure the NOINDEX and NOFOLLOW parameters for listing pages in order to get only 1st page in SERP.
> 0 votes

# Answer
Unfortunately I don't see a setting in Google Webmaster Tools to do this however, you could actually do this in your robots.txt file that ships with drupal by adding at the bottom:

Disallow: /\*?page=

Disallow: /*?page=*&\*

Disallow: /*?page=0*
> 0 votes

---
Tags: views, paging
---


title: display only one comment in node page

text:
# Question
Title: display only one comment in node page
I'd like to display only 1 comment (the most recent one) in node page. And I don't want the pager to be displayed too.

Is there any way to do it without writing custom module?

Could I use mytheme\_preprocess\_page($variables){} for that?

Thanks in advance.

# Answer
First install and configure "Comment goodness" module - it will allow you to sort comments to display newest first.

Then in your template.php create.

```
function THEME_preprocess_comment_wrapper(&$variables) {
   // Remove pager.
   unset ($variables['content']['comments']['pager']);
   // Leave only latest comment.
   $last_comment_id = reset(element_children($variables['content']['comments']));
   $variables['content']['comments'] = array (
     $last_comment_id => $variables['content']['comments'][$last_comment_id]
   );
}

```
> 1 votes

---
Tags: nodes, comments, paging
---


title: Show all the upload fields

text:
# Question
Title: Show all the upload fields
Is there any way to show all the upload fields on a node? Right now a user has to upload a single file and then get another field and so forth. Instead I would like to show the max number of permitted upload fields.

# Answer
The add another option only appear if you choose unlimited in field settings. If you choose an exact number say 5, it will display 5 image upload fields always. Its the default property.
> 1 votes

---
Tags: media, files
---


# Question
Title: How do I override recurring text/strings with icons/images?
I'm not sure this is possible or if there is a module that does this already, that's why I am asking :) Think of String Overrides except to turn strings into an image.

I ran into the module Iconify which basically adds icons to the admin config headings, and I was wondering if there is a way to use icons/images to replace specific recurring strings. For example: Say I would like to change the "View" link on the Page content type into an icon of an eye. Or the "Edit" link into a little pencil.

How can I achieve what I am trying to do?

# Answer
> 3 votes
Drupal allows you to override almost anything and what you are referring to here is the theme()ing of various pieces. In your specific example, 'View' and 'Edit' are tabs/local tasks on a node page, and they are themed something like this in Drupal 6:

```
/**
 * Generate the HTML output for a single local task link.
 *
 * @ingroup themeable
 */
function theme_menu_local_task($link, $active = FALSE) {
  return '<li '. ($active ? 'class="active" ' : '') .'>'. $link ."</li>\n";
}

```

and this in Drupal 7:

```
/**
 * 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 theme_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));
  }

  return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";
}

```

So, to change this from text to a graphic, you would create a theme function of your own in your theme's template.php file:

```
function YOURTHEME_menu_local_task(....

```

that looked at either `$link` or `$variables['#link']` and output an image instead of the text.

And if php isn't your forte, but jQuery is, you could also do it in the browser with something like:

```
$('.tabs a[href$="edit"]').html('<img src="edit.jpg">');

```

which would replace the text of your edit link with an image. If you went this route you would put this in a suitable drupal behavior wrapper in your theme or custom module as well.

---
Tags: media
---


# Question
Title: Force render the block programmatically?
Is it possible? For example, if the module's block meets your needs but it a block (not a page) and you want to use ready solution. Writing in a tpl.php file something like `render(desired_block)`, i.e. to get an output markup of the block for reuse.

# Answer
Not sure what version of Drupal you are using but here is how I rendered a block in drupal 7.

```
<?php
  $block = block_load('MODULE_NAME', 'DELTA');
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>

```
> 2 votes

---
Tags: blocks, theming
---


title: Create a view from specific Node ID's

text:
# Question
Title: Create a view from specific Node ID's
I want to create a view with specific nodes. How can I tell views specific node ID's in a list to display?

So for example, I want an unformatted list with node id's 33, 30, and 15.

I tried using the Filter Criteria: Content:NodeID. The problem is that it only allows for numeric value evaluation. It works when i specify using ONE node id. If I add another, it doesn't display anything. If I add another filter using Content:NodeID and specify another node. It also doesn't do anything.

It allows for a regex, but I'm not sure that even with a regex it would allow me to drop in a list of NID's.

# Answer
If specific means fixed, you can use fixed value for context filter.

1. Add contextual filter *Content: Nid*.
2. Allow multiple values for this filter in *More* fieldset.
3. Input your NIDs as a default value, where `+` means OR:

In some cases Nodequeue can be useful.
> 6 votes

---
Tags: 7, views
---


# Question
Title: Why is Drupal displying missing core tables for an external DB?
I'm using an external non Drupal DB to import some data from. The importing itself work, but I also get error like the ones below:

```
Uncaught exception thrown in shutdown function.

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'lager_db.semaphore' doesn't exist: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 480420510502a64252605e0.49437518 ) in lock_release_all() (line 269 of /srv/www/002/drupal/includes/lock.inc).

```

Why is Drupal even looking to base tables in that Database and how do I get rid of these errors?

My DB setup in settings.php:

```
$databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => '002_db1',
    'username' => '002_u1',
    'password' => 'password',
    'host' => 'localhost',
    'prefix' => '',
    'collation' => 'utf8_swedish_ci',
  );

$databases['lager_db']['default'] = array(
    'driver' => 'mysql',
    'database' => 'lager_db',
    'username' => 'username',
    'password' => 'password',
    'host' => '192.168.60.130',
    'prefix' => '',
    'collation' => 'utf8_swedish_ci',
  );

```

# Answer
> 2 votes
If I had to guess you called db\_set\_active() in some code and forgot to switch back to your master drupal database, so "drupal" execution continued after you intended it to with the current database set as your alternate.

The lager\_db probably has no semaphore table, but drupal's trying to call it anyways. You should switch back to drupal at the end of your custom code (or as necessary) with `db_set_active();` it passes the `'default'` parameter if none is given.

---
Tags: 7, database
---


# Question
Title: How can we divide the price if the customer select certain attributes?
I am working on a magazine site where the magazine can be subscribed. When users subscribe, we want to allow them to choose between full payment and monthly payment. I have used a "payment\_type" attribute for the payment option, and I want to divide the total price by the number of months when user selects the monthly payment option.

How can I achieve this?

# Answer
Why dont you try the Rules module? It is great for that kind of automation.
> 1 votes

---
Tags: 7, ubercart
---


title: Loading view data using XMLRPC

text:
# Question
Title: Loading view data using XMLRPC
I need to load data from a Drupal View into an external (non-Drupal) site using PHP.

I'm using XML-RPC for PHP.

I'm able to connect to the system and login, but I'm unable to retrieve a View. I get the following error: HTTP/1.1 401 Unauthorized: Missing required argument view\_name

I haven't been able to find documentation on format of the RPC call required for views and how the session id is passed. Any pointers would be greatly appreciated. Code below. The name of the view I'm trying to get is "configurations".

```
require_once ("xmlrpc.inc");

// SYSTEM.CONNECT
$f = new xmlrpcmsg('system.connect');
$c = new xmlrpc_client($XMLRPC_SERVER);
$r = &$c -> send($f);

// SYSTEM.CONNECT SUCCESS
if (!$r -> faultCode()) {

    print('system connected...');
    $v = php_xmlrpc_decode($r -> value());
    $system_sessid = htmlspecialchars($v["sessid"]);

    // USER.LOGIN
    $f_login = new xmlrpcmsg('user.login', array(php_xmlrpc_encode('USERNAME'), php_xmlrpc_encode('PASSWORD')));
    $c_login = new xmlrpc_client($XMLRPC_SERVER);
    $c_login -> setDebug(1);
    $r_login = &$c_login -> send($f_login);

    // USER.LOGIN SUCCESS
    if (!$r_login -> faultCode()) {

        $v = php_xmlrpc_decode($r_login -> value());
        $sessid = htmlspecialchars($v["sessid"]);
        print('logged in...' . $sessid);

            $f_configs = new xmlrpcmsg('views.retrieve', array(php_xmlrpc_encode('configurations-xmlrpc')), array(php_xmlrpc_encode('configurations-xmlrpc')), array(php_xmlrpc_encode('configurations-xmlrpc')));

            $c_configs = new xmlrpc_client($XMLRPC_SERVER);
            $c_configs -> setDebug(1);
            $r_configs = &$c_configs -> send($f_configs);

            if (!$r_configs -> faultCode()) {
                print('got configs');
            } else {
                print('error getting configs...');
            }

        } else {
            print('error logging in...');
        }
} else {
    print('error connecting to system');
}

```

# Answer
> 0 votes
I think you forgot to send the the view\_name that is a non-optinal argument. Check the code of the resource:

```
'view_name' => array(
  'name' => 'view_name',
  'type' => 'string',
  'description' => 'The name of the view to get.',
  'source' => array('path' => '0'),
  'optional' => FALSE,
),

```

---
Tags: services
---


# Question
Title: Get all fields for a given content type including title
I'm using field\_info\_instances($entity,$bundle) to read through every field in a given content type in their weighted order. However, field\_info\_instances does not include the node title. Why not and how can I remedy it so its added to the $fields array for sorting and processing in this scenario:

```
<?php
function do_something($content_type){
    $fields = field_info_instances("node",$content_type);
    usort($fields,"sort_stuff");
    foreach($fields as $field_name=>$value){
        do_something($value);
    }
}

function sort_stuff($a,$b){
    return $a['widget']['weight']-$b['widget']['weight'];
}
?>

```

# Answer
The node title is not a field handled from the field API. If you want to know if a content type has a title, you can use the following code.

```
$types = node_type_get_types();

if (isset($types[$content_type]) && $types[$content_type]->has_title) {
  $title = $types[$content_type]->title_label;
}

```

The code you are looking for is the same code used by Drupal to sort the fields (and extra fields) in admin/structure/types/manage/article/fields.

The function that handles that page is field\_ui\_field\_overview\_form().

Basing on the code of that function, I wrote the code you would need to get the list of fields, and extra fields, with their label, and weight.

```
  $fields = array();
  $instances = field_info_instances('node', $content_type);
  $extra_fields = field_info_extra_fields('node', $content_type, 'form');

  // Fields.
  foreach ($instances as $name => $instance) {
    $field = field_info_field($instance['field_name']);
    $fields[$instance['field_name']] = array(
      'title' => $instance['label'],
      'weight' => $instance['widget']['weight'],
    );
  }

  // Non-field elements.
  foreach ($extra_fields as $name => $extra_field) {
    $fields[$name] = array(
      'title' => $extra_field['label'],
      'weight' => $extra_field['weight'],
    );
  }

```

Notice that the extra fields don't contain just the title, but every extra field for which a module returned information in hook\_field\_extra\_fields(). There are modules that add fields to the node editing form, and implement `hook_field_extra_fields()` to allow the users with the right permission to decide the order in which their fields appear. For example, if you have installed the Mollom module, the page I shown in the previous screenshot becomes the following one.

Notice also that it is easy to notice which fields are not implemented using the field API if you look at admin/structure/types/manage/article/fields: For those fields, the Field column doesn't contain a link. That is what happens for the fields labelled Title, and Mollom.
> 9 votes

---
Tags: entities
---


# Question
Title: Changing the output order of Nodewords meta tags in head
I have a request to change the order that meta items are printed in the head using the contrib module Nodewords in D6. More specifically the property would like the description to appear before the keywords (per their SEO consultant).

Is this possible? Fruitless? Stupid?

I have searched with no results so far.

# Answer
You can implement hook\_nodewords\_tags\_alter which will alter the rendering of the tags. It accepts `function MODULENAME_nodewords_tags_alter(&$output_tags, $tag_options) {}`.

But why do you want to do this ? Any SEO insight you might share with us ?
> 1 votes

# Answer
I'm going to add hook\_nodewords\_tags\_info\_alter() to the next release of 1.x: http://drupal.org/node/1730808

Damien McKenna Nodewords maintainer
> 1 votes

# Answer
If you are using the branch 6.x-2, you need to implement `hook_nodewords_tags_info_alter()` to alter the weight index contained in the array returned by the implementations of `hook_nodewords_tags_info()`.

The weight is used by `_nodewords_output_tags()`, which is the function that renders the HTML output for the meta tags. Once the function has built the array of HTML strings to output, it sorts the array using the following code:

```
if (count($output)) {
  array_multisort($weights, $output);

  return implode("\n", $output);
}
else {
  return '';
}

```

`$weights` is the array containing the weight of every output meta tag.

I don't see any reason to change the weight of a meta tag, if not in a specific case where a meta tag consumer looks for two meta tags, and uses the first one that finds. Without a specific and valid reason, changing the weight of meta tags is useless, as meta tag consumers don't normally depend from the order meta tags are present in the HTML output.

`_nodewords_output_tags()` is called after the implementations of `hook_nodewords_tags_alter()`; altering the order of the array items in `hook_nodewords_tags_alter()` doesn't then have any effect.

```
nodewords_load_all_includes('nodewords.hooks.inc');
drupal_alter('nodewords_tags', $output_tags, $options);
$output = _nodewords_output_tags($output_tags);
drupal_alter('nodewords_tags_output', $output, $options);

```
> 0 votes

---
Tags: 6, meta-tags
---


# Question
Title: Front page meta tags and multisite configuration
I have a multisite install with 4 different URLs. How do I setup the meta tags (keywords and description) for each URL?

It seems like the keywords and description are the same for all of the URLs.

# Answer
> 1 votes
It depends on how your sites are structured. Are all three basically the same site only available via different URLs?
First off, be aware that this can penalize you for having the same content available via multiple URLs, search engines don't like that. You should use Nodewords' ability to hardcode a specific base URL to pick one of the domains to say that one is the primary domain; the others are secondary that will help avoid penalties.

That, of course, is if you're using Drupal 6; for Drupal 7 there are other options.

Disclaimer: I am the maintainer of the Nodewords module.

# Answer
> 0 votes
Here are some modules to consider for answering this question (including a quote from their project pages):

* Domain Meta Tags.

> Provides meta tags for individual domains by integrating Nodewords and Domain Access modules. At the moment only provides keywords and description settings.
* Nodewords Page Title (Views, Panels, Non-nodes).

> Leverage the power of nodewords custom pages to set the page title using wildcard paths and global tokens. Great for tough-to-reach page titles in Views, Panels, and other non-node paths!
* Nodewords by Path.

> Extends the Nodewords module to allow per path rules for populating meta tag values. If the Token module is installed, certain tokens can be used to populate the values with dynamic data.

---
Tags: multi-sites
---


# Question
Title: How to set canonical urls to migrated data
I have a new site, to which all the articles from my four old sites are migrated. Now in a search engine,if anyone searches and clicks on any article's link it should redirect to the same article in the new site.

How can a get this in Drupal?

Please tell me about **canonical url** of **nodewords** module?

# Answer
> 0 votes
The canonical URL informs websites that the current URL is the authoritative location for the content contained on this page. This is useful if you're sharing content across multiple domains, have content available via feeds on other sites, etc.

With Nodewords (6.x-1.14-beta1 and above) it will automatically assign the canonical URL tag for the current pages using the page alias, so search engines will index e.g. /products/flying-monkey rather than /node/42. Also, with the 1.14-beta1 release I've made a concerted effort to make it "just work" out of the box, so you should get reasonably useful meta tags just by enabling the modules.

Also, if your content is available via multiple domains you can hardcode which domain the content is available from, that way even if the content loads on all of the old URLs the search engines will present the *canonical* one as the preferred page.

Disclaimer: I am the maintainer of the Nodewords module.

---
Tags: uri, migrations
---


# Question
Title: Pages are not searchable by Google anymore
After migrating my Drupal website to WebHosting, I noticed that my pages aren't searchable by Google. It finds nothing, even though it should clearly find my website. Same thing happens when I want to know the ranking of my website. I haven't used the Pathauto module yet, but I think it should find the domain main page at least.

Do you know where the fault could be?

# Answer
> 2 votes
Has the old IP address and DNS been deleted?

Can you provide a bit more information please? Is the site being crawled by any search bots? Check the reports/recent hits file. Is your sitemap downloadable in Google Webmaster Tools? If so, when was it last downloaded/crawled?

Without knowing a few of those things above its difficult to say, but check the following also:

* If you had previously specified geographic targeting in google webmaster tools, make sure that the new IP address resolves to the same geographic zone.
* Check in Google Webmaster Tools whether you specified "www" in front of your domain name, and check the rewrite rules in .htaccess or your server config files. If you have the Pathauto/Nodewords modules installed, start by checking the canonical URLs in your page source code, checking that they match against the sitemap.

In response to your other questions: navigate to \[ YOURDOMAIN\**/admin/reports/hits \] when logged into drupal. Here you will see recent hits. Clicking on each one will show you the date, time and page that was visited and importantly the IP address. You can then check these using an IP lookup service. Normally googles crawler starts with an IP of \[ 66.*.**.\*** \].

when search engines look up a website, they look up the IP address first. Check the old IP address, if you still have it, using a tool such as ip-lookup which is a web page where you can check where an IP address resolves to.

When you open your GWT account you can tell google to return your site without the www, but this isn't likely to be the problem.

You'll see from the recent hits report whether google has crawled your site, this in turn tells you whether it is likely to be available yet in Google Webmaster Tools. You should follow the setup instructions google provides to open a GWT account, its straightforward.

you haven't changed the .htaccess file which in most cases is fine. However, depending on you system setup you may need to. From what you've said I expect its a basic setup without any additional server rules such as caching and rewrites. By the way, if you want to provide your web site address I'll look into it for Ya!

# Answer
> 2 votes
Check your root folder for a robots.txt file. Using Google Webmaster Tools you can test this; see Block or remove pages using a robots.txt file.

# Answer
> 0 votes
I suggest using Metatag to add lots of rich meta data to the pages, and XMLSitemap to notify the search engines that the content is available & updated. Other useful modules include Site Verify (http://drupal.org/project/site\_verify) to add the necessary meta tags / files to inform several search engines that your site legit. Also, have lots of good content :-)

---
Tags: search, 7
---


# Question
Title: Adding a Meta tags CMS function to drupal 7
I would like to be able to manually configure the meta tags, keywords and description,for each individual page of the sites. I couldn't find any module out there for drupal 7 that does so. Anyone have heard of such a module? If not how hard would it be to make this a custom module ?

# Answer
There is a complete rewrite of the old drupal 6 module nodewords in progress now - it is called metatags. However the metatags module looks like it is still in the initial development phase, so you might be better off using http://drupal.org/project/metatags\_quick \- which already has a stable 7.x release

There is no releases on the project page, but you could clone the git repo and help with the issue queue and submitting patches back etc
> 1 votes

# Answer
As a co-maintainer of the Meta tags module, I personally think it's the best option, but of course I'm biased. We are making great strides to stabilise it; I suggest trying out the latest and letting us know how it works for you.

Disclaimer: I am the maintainer of the Nodewords module.
> 0 votes

---
Tags: 7, meta-tags
---


# Question
Title: Single Sign On using PURL domain modifier and different TLDs
I have an organic groups implementation using purl and spaces to set the active space when you visit a domain modifier such as example1.org vs example2.org. The cookie domains are different, so I'm wondering if there is any single sign on solution that will allow sessions to be transfered from one domain to another in some fashion.

Should I use something like facebook connect, and not allow users to sign onto the site with their regular drupal credentials?

# Answer
> 1 votes
Have also been looking into this the last few days and came across this

http://drupal.org/project/services\_sso\_client

Seems that it will do exactly what you want to do.

---
Tags: cookies, authentication-authorization
---


# Question
Title: db_query() PDOException (no parameters were bound)
I have a relatively simple query that is executed via db\_query()-\>execute; For some reason this causes a PDO Error, which I assume has to do with the way drupal handles the input. Any ideas on what causes this error and how to avoid it?

```
db_query('
    INSERT INTO {account_floodprotect} (ipaddress, soapcount, mailcount)
    VALUES (:ipaddress, :soapcount, :mailcount)
    ON DUPLICATE KEY UPDATE
    soapcount = soapcount + :soapcount,
    mailcount = mailcount + :mailcount',
  array(
    ':ipaddress' => $ip,
    ':soapcount' => $soapcount,
    ':mailcount' => $mailcount,
  ))->execute();

/*

```

ERROR CAUSED:

```
PDOException: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound

```

The table involved:

```
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| ipaddress  | varchar(255)     | NO   | UNI |         |                |
| soapcount  | int(10) unsigned | YES  |     | 0       |                |
| mailcount  | int(10) unsigned | YES  |     | 0       |                |
| updatetime | timestamp        | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+

```

# Answer
> 11 votes
Don't need `execute()`

```
db_query('
    INSERT INTO {account_floodprotect} (ipaddress, soapcount, mailcount)
    VALUES (:ipaddress, :soapcount, :mailcount)
    ON DUPLICATE KEY UPDATE
    soapcount = soapcount + :soapcount,
    mailcount = mailcount + :mailcount',
  array(
    ':ipaddress' => $ip,
    ':soapcount' => $soapcount,
    ':mailcount' => $mailcount,
  ));

```

# Answer
> 3 votes
I think it'll be the parameters after `ON DUPLICATE KEY UPDATE` that are causing the problem; `db_query()` is fairly picky about which parts of the query string it will or won't do parameter replacements for.

The simplest way around it is to use the `db_merge()` function. Your query would look something like this:

```
db_merge('account_floodprotect')
  ->key('id')
  ->fields(array(
    'ipaddress' => $ipaddress,
    'soapcount' => $soapcount,
    'mailcount' => $mailcount
  ))
  ->expression('soapcount', 'soapcount + :soapcount', array(':soapcount' => $soapcount))
  ->expression('mailcount', 'mailcount + :mailcount', array(':mailcount' => $mailcount))
  ->execute();

```

---
Tags: 7, database
---


# Question
Title: How to modify user messages without hacking core user module?
When "themeing" modules, especially core modules, as far as I know it is a good idea to take the module specific tpl.php files, duplicate the ones you need, and modify them once they're in the relevant theme directory.

However, what if I want to modify a .inc file? Is it the same process as with tpl.php files, or is there a better workflow? Basically what I would like to do is change some of the user status messages found in user.admin.inc in the core Drupal 7 User module. I'm not sure if editing this file directly is a good idea. Thoughts?

# Answer
> 4 votes
You can't override an .inc file by copying it to your theme, but you can override most of the function with your template.php; for example, any form can be altered using `hook_form_alter()`, or any function whose name starts with "theme" can be override by using `YOURTHEME_functionaname()` in your theme template.php.

# Answer
> 4 votes
Take a look at String Overrides module, which allows to overwrite everything passed through `t()`. So, it works for “the strings in the module that's already installed”.

There are other ways to alter data in Drupal, but I’m sure in your case overwriting needed.

String Overrides just uses core drupal overwrite behavior, but adds nice UI to control it. Let me point you again to core comments for string overwriting:

> First, check for an array of customized strings. If present, use the array ***instead of*** database lookups. **This is a high performance way** to provide a handful of string replacements. See settings.php for examples. **Cache the $custom\_strings** variable to improve performance.

# Answer
> 0 votes
In a comment you said you wanted to replace the string for the error message "The name \[username\] is not allowed." That error message is returned only from Drupal 6 core, or from a Drupal 7 module; the function that in Drupal 6 shown that error has been removed from Drupal 7, together the functionality of allowing/not allowing some usernames. Drupal 7 can disallow some IPs from being used when accessing a Drupal site.

In Drupal 6, the function showing that error message is user\_admin\_access\_check\_submit(), which contains the following code.

```
  switch ($form_state['values']['type']) {
    case 'user':
      if (drupal_is_denied('user', $form_state['values']['test'])) {
        drupal_set_message(t('The username %name is not allowed.', array('%name' => $form_state['values']['test'])));
      }
      else {
        drupal_set_message(t('The username %name is allowed.', array('%name' => $form_state['values']['test'])));
      }
      break;
      // …
 }

```

The same message is shown at least from the User restrictions module, which is the third-party module that implements the functionality that has been removed from Drupal 6. I am one of the maintainers of that module, even though I didn't touch its code from months.

To change that message I would implement `hook_form_alter()` to add a new validation handler that alters the error message, if the error message is shown during the validation of a form, or to add a new form submission handler, if the error message is shown during the submission of a form.

In both the cases:

* The messages set with drupal\_set\_message() are saved in `$_SESSION['messages'][$type]`, where `$type` is status, error, or warning. Keep in mind you don't see the string `'The username %name is not allowed.'` but the string where %name is already replaced with the username. You would need a regular expression to find that message, and replace it with the string you prefer.
* The error messages set with form\_set\_error() are returned from $errors = &drupal\_static('form\_set\_error, array());`. The array follows the format`$error\[$field\_name\] = $error\_message\`. Also in this case, the string you are looking for contains the username, and you need to user a regular expression to find the error message. You need to alter this array if the error message is set in a form validation handler.

Keep in mind that:

* The error message, in Drupal 6, and the User restrictions module, doesn't mean the username contains spaces when it should not. It means there is a rule that doesn't allow a user to use a specific username; for example, there could be a rule that disallow usernames matching fun%boy (it's a regular expression used from MySQL, and other database engines), and the error message would appear when the username is fun boy, fun-boy, fund boy, or funxxxxxxxboy.
* In Drupal 7, spaces in usernames are allowed; they are not allowed at the beginning of the username, at the end of the username, or when there are 2 or more spaces in row.

---
Tags: users
---


# Question
Title: Rule to check if a node has a translation?
Just wondering if I can create a this rule:

1) check if a node (when viewed) has the translations for all enabled languages.

2) If the it doesn't, then create the translation (for all enabled languages)

# Answer
> 1 votes
Out of the box: no.

If you are willing to code, check the rules API. It lets you add your own conditions and actions.

If you don't need any of the rules functionality you can of course just implement hook\_node\_view.

---
Tags: rules, i18n-l10n
---


# Question
Title: show field of entity for editing according to path
I have an entity with many field (about 200) collecting information about buildings (area, height, conditioning system, ...)
my client has asked me to show specific fields in groups for editing, where user can choose from menu "group 1" and see only those fields
it is also possible that users will only visit some groups they want, and leave some of groups un-edited for later
how do i show specific fields of one entity, according to path? /node/1/edit/g1 for fields 1 to 20, node/1/edit/g2 for fields 21 to 30 and ....

extra info: i'ts not about permissions at all, the same user, will fill group 1 today, will comeback tomorrow and fill group2 if wanted to
field collections looks promising, can it do that? instead of deciding by user permission, deciding by path?

# Answer
One way to do it is by using field gropups and custom permissions. Start by installing field groups module to make it possible to group your fields at all. Move your fields into different control groups and use for example tab groups and tab items in a way to make the editing page pleasing.

If you want detailed asccess rights for different user groups, add some code to do this.

Add your own permissions by using **hook\_permissions()** For example

```
function my_module_permissions() {
  return array(
     'edit group1' => array(
      'title' => t('Edit group1 section'),
      'description' => t('Edit field group group1 in Building.'),
     ),
   );
}

```

In a **hook\_form\_alter()** function, you can hide/show field groups like this:

```
// Check if the current user has rights to see this group and its fields
if(!user_access('edit group1', $user)) {
 // Loop through all group fields and hide them
 foreach($form['#groups']['group1']->children as $index => $groupField){
   $form[$groupField]['#access'] = FALSE;
 }
}

```

You don't have to hide the group itself, hideing all it's fields will render it invisible.

Then it's just a matter of settings the right permissions to the right user groups.

Pros:

* Detailed permissions just for the things you need
* Field groups are pleasing to use :-)

Cons: You need to do some coding

**Second way**

An other way is to use field collections module where a collection itself will be treated as fields in a sense. I guess by adding field permissions you will be able to control each fild collection's permissions.

Pros: no coding :-)

Cons:

* By adding field collection you adding a new layer of abstraction wich might complicate things for you later on.
* field collections isn't supported by all modules you might use - check it before starting this path.
* It will get a bit messy in the permissions hanlding page
> 0 votes

---
Tags: entities
---


# Question
Title: One node on multiple pages with tabbed navigation between fields
I would like to create a Product content type with multiple fields and then showing those fields on seperate pages, let me give you an example:

I create a product type content named "Car" that has fields like "Mileage", "Color", "Year" and so on. When you open this content's page, you see the "Mileage" by default and you have a few tabs with "Color", "Year" that you can click to show those fields.

One possible solution I found is to use the Field Groups module, but I am looking for another one because the different sections will be heavy, lots of images and styling and I worry about that jQuery show, hide implementation will result in laggy, slow experience for the visitor.

Also it would be ideal if we could have a different URL for the sections like, car/mileage, car/color and so on.

Is there a rock solid solution for this?

Thank you.

# Answer
This is fairly easy to implement so I think you're right not to want to include a whole module to do this. There's loads of ways to do this but here's one way I've done it recently:

In an overridden node.tpl.php, individually print out the fields you'd like tabbed in a wrapper. Within the wrapper you'll also need to print the links for each tab, with a href pointing to the ID of the item it's related to. Something like this:

```
<div class="tabs">
  <ul>
    <li><a href="#field1"><!-- Field Label --></a></li>
  </ul>

  <div id="field1">
    <!-- Field Content -->
  </div>
</div>

```

You can then write some simple jQuery to show and hide the tabs on click:

```
$('div.product_tabs ul a').click(function () {
  $('div.tabs > div').hide().filter(this.hash).show();

  $('div.tabs ul a').removeClass('selected');
  $(this).addClass('selected');

  return false;
}).filter(':first').click();

```

You could easily extend this so when the URL is visited with the fragment identifier on the end, the correct tab is shown.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Can't understand how to invoke my own theme() function
i have made formexample.module, from **Drupal 7 Pro Development**

```
function formexample_menu() {
    $items['formexample'] = array(
        'title' => 'View the sample form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('formexample_nameform'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

function formexample_nameform() {
    $form['name'] = array(
        '#title' => t('Your name'),
        '#type' => 'fieldset',
        '#description' => t('what people call you'),
    );

    $form['name']['user_name'] = array(
        '#title' => t('Your name'),
        '#type' => 'textfield',
        '#description' => t('please enter name'),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    return $form;
}

```

and a theme function and preprocess function

```
function formexample_theme() {
    return array(
        'formexmaple_nameform' => array(
            'render element' => 'form',
            'template' => 'formexample-nameform',
        ),
    );
}

function template_preprocess_formexample_nameform(&$variables) {
    $variables['name'] = $variables['form']['name'];
    $variables['submit'] = $variables['form']['submit'];
}

```

this is template file for this theme() - **formexample-nameform.tpl.php**

```
<div id="formexample_nameform">
<?php
    print render($name);
    print render($submit);
?>
</div>

```

**my question is:** how and where to invoke this `theme('formexample_nameform')` , i thought i should insert `function template_preprocess_formexample_nameform` to my template.php file(with **template** rename to my theme name) but its not working for me

# Answer
You just need to set it on the `$form` element inside your form function:

```
function formexample_nameform($form, &$form_state) {
  $form['#theme'] = 'formexmaple_nameform';
  // ...

```

When you use `render element` with a theme the variable on which you set `#theme` is the one that's passed through to the theme/preprocess functions.

Don't forget to add `drupal_render_children()` at the bottom of your template file or the form won't render correctly:

```
echo drupal_render_children($form);

```
> 0 votes

---
Tags: theming
---


# Question
Title: Translation issues-How can we set admin in default English language in multilingual site
> **Possible Duplicate:**
> Do not translate the admin area / How can I set the language of the admin area to English?

I have a problem with a multilingual website.I used English and Arabic as two languages .Done all the laguage settings.But when i tried to translate a basic page content to arabic ,the whole admin turned to arabic and showed rtl mode.I need to fix it asap.Please guide me.

NB: i have all the modules related to multilingual site at local and transferred the whole files and same database to server.At local it was working fine.But at live it won't!.please

# Answer
Try setting your language detection to be "user preference" first. That way your account setting will override any other detection.
> 0 votes

---
Tags: i18n-l10n
---


title: Get content type identifier on Views

text:
# Question
Title: Get content type identifier on Views
I am on Drupal 7 and configuring Views. I can easily add a field that displays thew node's content type. But it seems it will bring only the friendly content type name. Is there any way I can pull the content type's system name (like 'content\_type\_system\_name')?

Thank you.

# Answer
In your field settings at the end you've a "More" section, click there and then check the "Output machine name"'s option.
> 4 votes

---
Tags: views, nodes
---


title: Let users manage certain field

text:
# Question
Title: Let users manage certain field
I'd like to give a set of users the ability to manage certain fields, such as adding items to a list. Is this in any way possible with existing modules?

Example: Editing a node Try to select XYZ for field FOO XYZ isn't an option Go to admin page and add XYZ to FOO Can now select XYZ from FOO

# Answer
I think the module Field Permissions allows you to do what you're looking for. Or at least in the documentation it write "Create own value for the field".
> 0 votes

---
Tags: 7, users
---


# Question
Title: How can I get a count of users with a certain role?
I have a rather complicated profile completion process on my site. As users create their profiles, they are awarded more roles.

For my own information, I'd like to be able to quickly check the number of users with role ABC. I'd also like to be able to quickly know how many users have role ABC and role XYZ, as well as how many users have role ABC and role EFG.

Is there a quick way to do this in Views or some other module? I don't want to see a list of all users; I just want to know how many have a given role (or combination of roles).

# Answer
> 2 votes
You should create a view with filter criteria "role" then you expose it and allow multiple selection.

Then you can create an header or footer (always in view) and add this piece of code

```
<?php
  $view = views_get_current_view();
  print $view->total_rows;
?>

```

You should have the php filter enabled. This works for me.

---
Tags: views
---


title: open atrium features

text:
# Question
Title: open atrium features
I installed Open Atrium, and there are no default features showing under the features admin panel. No shoutbox, wiki, blog or calendar. Did I choose a stripped down version of Open Atrium to install by accident?

# Answer
> 3 votes
No, you have to turn those features on if you'd like to use them.

Create a group and then in that group go to Settings -\> Customize Features, here you can enable the features you need.

---
Tags: distributions
---


# Question
Title: How to change error-message displayed @ failed form-element validation to be different than the element's '#title" text?
I'm writing a custom form module.

Using Drupal7's FormAPI, I create a checkbox, the label/text diplayed next to it is set as described here

```
http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#checkbox

```

with the #title property,

```
    $form['test'] = array(
    '#type'     => 'checkbox',
    '#title'    => t('This is the text that gets displayed next to the checkbox'),
    '#required' => TRUE,
    );

```

which then displays in the browser,

```
[ ] This is the text that gets displayed next to the checkbox

```

Ih there's an error in submission that involves that checkbox, e.g. in the example above being required but not being checked, an error box is shown across the top content-area that says

```
"X  The This is the text that gets displayed next to the checkbox field is required"

```

I want to change that displayed error message to something other than the label/text. For example, on error,

```
"X  Selecting the displayed checkbox is required."

```

or

```
"X  You forgot to check the required checkbox.  Please try again."

```

How do I set the error-message text to be different that the assigned label/text?

# Answer
Using a basic form in a custom module:

```
    function customform_demo($form, $form_state) {
    $form['test'] = array(
        '#type' => 'checkbox',
        '#title'    => t('This is the text that gets displayed next to the checkbox'),
        '#required' => TRUE,
    );

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

    return $form;

}

```

You can set a custom error message in the form validation function. Here is a basic example with some comments:

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

    // Test for existing form errors
    if (form_get_errors()) {

        // Save errors
        $form_errors = form_get_errors();
        $drupal_errors = drupal_get_messages('error');

        // Clear form errors
        form_clear_error();

        foreach($drupal_errors['error'] as $key => $error) {
            if (in_array($error, $form_errors)) {
                // Unset form errors
                unset($drupal_errors['error'][$key]);
            }
        }

        // Rebuild drupal errors
        foreach($drupal_errors['error'] as $key => $message) {
            drupal_set_message($message, 'error');
        }

        // Validate form field and set error message
        if ( $form_state['values']['test'] === 0 ) {
            form_set_error('test', t('You forgot to check the required checkbox. Please try again.'));
        }

                // Add more validation tests and error messages

    }
}

```
> 3 votes

---
Tags: 7, forms, hooks
---


# Question
Title: Drupal 7 context module fails to load on front page
I have the context module installed on Drupal 7. It worked perfectly fine for a long time. But, recently when I try to add or remove a reaction(block) for a context the related page fails to load. I get an error: "The website encountered an unexpected error".

Has anyone had a problem like this?

# Answer
> 0 votes
Figured it out. I had another reaction added that was causing the issue. I removed the reaction and it seems to work now.

---
Tags: 7
---


# Question
Title: Create Alias URL to taxonomy term page with TID
I am trying to figure out how to create a url-alias friendly url to a taxonomy term page with only the tid of the term. I know drupal does this automatically in the node, but I am trying to do this in a block.

e.g. Where the term is "Texas" with tid 34, and the alias is to the taxonomy page is "/location/texas"

So, instead of creating a url to this "/taxonomy/term/34", I would like to create a url to the aliased version of that link, to /location/texas, just with the TID.

Using Drupal 7.15

Thanks!

# Answer
If what you are asking is, "How can I create a link to a taxonomy term path alias if all I have is the TID," you can use drupal's built in `l()` function in any php function or template. For example, if `taxonomy/term/34` exists and `location/texas` exists as its alias and `$tid` equals 34...

```
<?php print l('Texas Taxes', 'taxonomy/term/' . $tid); ?>

```

...will create `<a href="/location/texas">Texas Taxes</a>` because `l()` will by default look up and use the alias for any system path.
> 11 votes

# Answer
If you created an alias;

> /location/texas

to

> /taxonomy/term/34

Then you can already create a link pointing to /location/texas. If you want to include the tid in the alias. Then just modify your alias to include the tid. Something like;

> /location/texas/34

or

> /location/34/texas

or

> /location/34
> 0 votes

---
Tags: 7, taxonomy-terms, path-aliases
---


# Question
Title: Core Search Module in Drupal 7.14 and Hidden Fields
In one of my content types I have a text field for extra zip codes served by clients that I have set to "hidden". My core search module does not seem to be indexing hidden fields. What's the deal?

# Answer
> 2 votes
This behavior is the correct behavior for Drupal search out of the box. The default search module only indexes fields that are not hidden in the default display view mode as Clive suggested on 8/10. This prevents anonymous users from searching and returning results hidden from their view, yet exposed via search. The exact mechanics of it vary in application from D6 to D7 but both use a concept of search index version of the node which is used to create the indexes in the database. You can alter what the search indexes by modifying this view of the node.

In D6 you would be able to get around this by altering the node\_api for the search index as shown here: http://drupalib.interoperating.info/node/246.

In D7 you can choose to enable fields to be indexed that are normally hidden in the default view. Edit the content type and go to the manage display tab of that edit screen. Below the fields portion of that edit screen is a collapsed portion of the page for custom display settings. Open this section and select the Search Index view mode. This will now allow you to alter the fields used to index the node. Keep in mind the relevant results portion of the node will be blank in search results unless you also alter the search result view mode. In this way you can have different results indexed than the visible fields in other node view modes.

You may also choose to implement the search api module, or make this field visible to the world in your default view mode and handle obscuring it through css or the theme layer.

---
Tags: 7, search
---


title: Re: Relation Module

text:
# Question
Title: Re: Relation Module
I have/had been working on a 'self-learning' development project based on a D7 stack and utilsing the http://drupal.org/project/recruit* however the author earlier this year ceased development. I had continued with it, but as I continuously upgraded D7.14 and it's modules, found that the above had become no longer useable. Very recently I came across' http://drupal.org/project/relation so am now currently looking to re-build the previous functionality with Relation and the Views/Panels/Rules stack and have studied the online tutorials such as: http://nodeone.se/en/introduction-to-relation which gives me the impression that Relation is the right road for this project and many other Drupal projects I may creatively develop. (\*I don't want to use any of the other similar O-T-S packages nor 'hack' them).

Whilst Relation looks very promising and appears extremely functional to my needs, I'd appreciative (by way of comments/feedback here) opinions (from other Drupal developers (who have a longer programming experience than my current 12 months P/T learning) in that I am indeed focused on the correct module to provide the similar required functionality. Thanks in advance.

# Answer
> 1 votes
At first, I simply agreed with Boombatowers assesment, that you are on the right way.

However, after reading the description of the Recruit page more carefully, I notice that it actually provides integration with Relation already.

I'm not familiar at all with the Recruit module, but I see a large risk that you simply end up duplicating a lot of the effort that has already gone into Recruit. Getting co-maintainership or Taking over the existing module may end up saving you vast amounts of time.

# Answer
> 1 votes
I am not familiar with the specific functionality that the recruit project attempts to provide, but from reading the project page it seems like there are a number of relationships that would be well suited for relation. One thing I have used relation for in more complex scenarios is to keep track the state between two objects with a field on the relation which seems like something you may need to do.

From what I can tell what you propose makes sense, but I do not have all the details.

---
Tags: entities
---


# Question
Title: Limiting nodes returned per group in a view
Using Drupal 7, I've created a view to render a list of most recent content types grouped by taxonomy. I can set a global limit for items returned but I'd instead like to limit it per group. So if I've got the terms "Apples", "Bananas" and "Carrots" I'd like to get the top three Apples, top three Bananas and top three Carrots. Currently I'm getting results such as top two Apples and one banana or top three apples.

**UPDATE**

I actually found a way to do it without creating multiple views. There's a module called Views Grouping Row Limit that does exactly that I'm looking for!

# Answer
> 1 votes
If I were trying to accomplish this, I'd create multiple views attachments to do this. Then you can limit the number for each easily in the pager settings.

---
Tags: views
---


title: How do I modify the login block markup?

text:
# Question
Title: How do I modify the login block markup?
I want to change the source order of the "Create new account"/"Forgot your password?" links and the Submit button, so the Submit button comes first.

I am able to modify certain contents of the login block by using this function.

```
function THEMENAME_form_user_login_block_alter(&$form, &$form_state){
  $item = array();
  if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
    $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
  }
  $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('If you forgot your password, click to request a new password via e-mail.'))));
  $form['links']['#markup'] = theme('item_list', array('items' => $items));
}

```

And this template does pick up the changes and allow for markup changes around the form, but simply outputs the form in one variable. How do I modify the $content variable and print each element out separately to swap item locations?

### block--user--login.tpl.php

```
<div id="user-login-top">
  <?php print render($title_prefix); ?>
  <?php if ($block->subject): ?>
    <h2<?php print $title_attributes; ?>><?php print $block->subject ?></h2>
  <?php endif;?>
 <?php print render($title_suffix); ?>
</div>
<div id="user-login-block" class="block block-<?php print $block->module ?>">
  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>
  </div>
</div>
<div id="user-login-bottom" class="block-bottom"></div>

```

This example uses straight markup out of Firebug and it does function, but there should be a cleaner way to do this by printing variables that already contain the markup, and that doesn't remove the "Create new account" option if the site registration is restricted.

# Answer
> 8 votes
you can change the weight of the links like this:

```
$form['links']['#weight'] = 10000;

```

now it should be after the submit button :)

---
Tags: 7, theming, users, forms
---


title: Include AF container in pathauto URL

text:
# Question
Title: Include AF container in pathauto URL
I am using the 'Advanced Forum' module with Drupal 7, in conjunction with the 'pathauto' module. I would like to include the parent forum, if not the container of the parent forum as well, in the URL of the forum topic, so it is like: `forums/catergory/forum/topic-title`. However, I can not seem to find compatible tokens/replacement patterns in order to do so, so I was hoping somebody here could provide a solution for me, please!?

So far all I have is: `forums/topic-title`!

# Answer
> 0 votes
I haven't figured out the replacement pattern for forum containers, but I did achieve this:

> www.mysite.com/forums/forum-name/topic

using this pattern:

> forums/\[node:taxonomy\_forums\]/\[node:title\]

hopefully someone figures out the rest!

# Answer
> 7 votes
After several hours, and help from the user spovlot in #drupal-support, we have a working answer for D7:

(edit: this has been tidied up some more!)

Pattern for all forum topic paths:

forum/\[node:taxonomy-forums:parents:join-path\]/\[node:taxonomy-forums:name\]/\[node:title\]

*combined with*

Pattern for forum and forum containers:

forum/\[term:parents:join-path\]/\[term:name\]

This gives a result of:

/forum/container/sub-forum/title-of-a-post

Note that:

/forum is the name of the forum (i.e. no a forum, but a description) Any number of containers and sub-forums will work. (forum/container/sub-a/sub-b/title-of-a-post)

Hope it helps!

# Answer
> 2 votes
Container and forum hierarchy is just a taxonomy (*Forums* by default). That's why you can't see any forum-related replacement tokens in the Pathauto configuration. All the vocabulary and term related tokens apply though.

Make sure the *Forums* vocabulary is the top vocabulary for the *Forum topic* node type at `admin/content/taxonomy` and configure Pathauto like follows:

**Pattern for all Forum topic paths:** `[vocab-raw]/[termpath-raw]/[title-raw]`

That will result in aliases like `forums/container/forum/topic` which I believe is exactly what you're after.

---
Tags: 7, nodes, path-aliases
---


title: Rehash Drupal 7 passwords into SHA1

text:
# Question
Title: Rehash Drupal 7 passwords into SHA1
I need to sync my user database with another user database; the other user database uses SHA1 as hash with USERNAME:PASSWORD as algorithm.
Is there a way to rehash it that I can store it in the database?

Do you have any idea?

It should be possible to edit the user/\*/edit form and hash the password on my own and save it afterwards, or am I wrong? If it can work, can you give me any tip on how?

I did a bit reasearch about editing the user\_profile\_form (for example: Making a username/password syncronization scheme - D7) where I read that `$form_state['values']['pass']` could give me the password in plain text to hash it on my own and insert it into my database.
Afterwards I directly tried to investigate more and tried to displa me the password with `dpm($form_state['values']['pass']);`, but I noticed (controlled with `dpm($form, '$form info for $form_id '.$form_id);`) that theres no values.

How can I get the plain text password in user\_profile\_form or is it impossible and only possible in user\_register\_form (as stated in topic above). In my user\_registe\_form is no password entered, because I use the method to get a link with E-Mail were you can login one time and change the password with user\_profile\_form.

Thank you!

# Answer
There are a couple of ways to do this.

You need to look into the function user\_authenticate.

In that function, you will see there is a call to `variable_set()` that sets the path to the variable `password_inc`. So, basically you could overide the path of this file, change it so it points to your custom password.inc, in a custom module out of core code. In that file you would redefine the same functions with your own logic.

There could well be a simpler way of doing this. I know single-sign on can also be easily done with Drupal 7 as there are functions that make this easily available out of the box. Maybe look at OpenID code or other contrib modules if you choose to use that path.

Good-luck!
> 2 votes

---
Tags: 7, users
---


# Question
Title: Two branches of theming: templates and functions
Here is the description of theming overrides in Drupal. That (pdf page) great colorful scheme is relevant to Drupal 6, however, as I got that, there are no basic changes in the 7th version that are worth mentioning now. Anyway, Drupal (`theme()` function) either calls hook as a function (i.e. `theme_smthing`) or as a template, i.e. `template_preproces_smth() -> template_process_smth() -> smth.tpl.php`

When I have to override deafault Drupal markup, what way I should do this: with theme\_ ... or template\_ ... ? Why are there two mechanisms that do the same think? (Or it's resonable and I just haven't understood proper;y what id writen there). Can anybody explain these basics?

Thank you.

# Answer
Theme functions and preprocess functions do not do the same thing. A preprocess function is a precursor to a theme function. Instead of a a theme function, a template file can be used.

Preprocess functions are created when a module implements `hook_preprocess()`. The documentation for that hook explains that the purpose of a preprocess function is to prepare variables for use within a theme function or template. Also, not all theme functions have a complimentary preprocess function.

Similarly, a theme function (or template) is defined from a module that implements `hook_theme()`. A theme function or template is the place where the variables previous prepared in the preprocess function are printed to the screen and wrapped with any desired HTML markup.

So, the idea is that a preprocess function **prepares** the variables/data in question and the theme function **presents** the data to the user, usually wrapped in HTML markup.
> 2 votes

---
Tags: theming
---


# Question
Title: Is it possible to build a high-traffic Drupal community website without hacking?
I would like to find out from anyone that has built a high traffic Drupal community website ( a website with at least 500,000 visitors a month, with anywhere from 10,000 to 20,000 authenticated users at any one time ), is it is possible to create this kind of site without having to do a high level of hacking to make Drupal scale? Can standard Drupal scale without a lot of query and other types of hacking / coding?

Can I install Drupal, configure the modules I need, and then add more hardware and functionality (APC, Varnish, Memcache, etc) without having to do query hacking? How do people deal with Drupal's high number of database queries without hacking, or is there no way around having to hack? If you have built this type of community site with numerous authenticated user, what were the biggest hurdles and stumbling blocks when it comes to performance and scalability? I already know about auth cache and pressflow.

# Answer
> 12 votes
Drupal can serve high-load sites without hacking.

You need to use memcache to store Drupal caches not in db but in memory. For Drupal 6 you need to use Pressflow core. You need to use Drupal cache mechanism, its configuration much depends on what users do you have most - anonymous or authenticated.

For anonymous users Varnish can dramatically increase site performance.

Don't forget to configure cache for each View and Panel on you site.

Also Drupal 7 can work with MySQL's master-slave architecture.

Don't forget to use cdn for loading static content such as images, css, js and files uploaded by users.

If you will have search on your site - I advise you to use Apache Solr.

I have created several high-loaded sites and haven't hacked any query that was provided by Drupal core. In some cases only queries that were provided by views module were altered - but this is not a hack.

But don't think you can built a high-load Drupal site without deep knowledge of Drupal architecture, API and lot of useful modules.

# Answer
> 0 votes
Yes, you can scale Drupal to 6.7 billion static page views per month, or to 220 million highly dynamic authenticated page views per month in a secure and resilient production system.

This is transparent PHP/Drupal scaling that does not require deep knowledge of Drupal architecture.

http://jkmickelson.net/books/drupalee-drupal-enterprise-edition-drupal-6

---
Tags: 7
---


title: Add custom field to taxonomy terms

text:
# Question
Title: Add custom field to taxonomy terms
I am writing a module that creates a vocabulary through code. Here's what I use:

```
$new_vocab_name = 'my_categories';
$vocab_obj = (object) array(
   'name' => t('My Categories'),
   'machine_name' => $new_vocab_name,
);
taxonomy_vocabulary_save($vocab_obj);

```

How do I add custom fields for terms that will be in this vocabulary? E.g., I want to add an image field for each term.

# Answer
I think this article will be usefull for You because taxonomy is one of entity types: Working programmatically with fields in Drupal 7

So You should set "entity\_types" as taxonomy.
> 1 votes

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