# Question
Title: using same addressfield for profile2 and commerce module
I have a site with two different profiles (with different fields) where one of these are able to buy a product. In this context I want to use the same addressfield for one type in the billing information making automatic filling of a company's address.

I've tried Commerce Customer Profiles module however it seems that I am unable to merge these fields. Does anyone have some suggestions on how to use profile2 information in commerce module?

# Answer
> 2 votes
**Profile2** and **Commerce Customer Profiles** are different entities.

Even if the address field is the same, the data will need to be copied over somehow.

One way to do it would be with

hook\_field\_attach\_load

and load in the relevant address field data there, when the field is loaded.

Keep in mind:

1. That hook can be passed multiple entities
2. Ensure the user id for both entities is identical prior to merging the data.

More info on the Field Attach API

---
Tags: commerce, users, entities
---


title: Best practice to implement stores

text:
# Question
Title: Best practice to implement stores
I want to allow my site users to create stores,, in which each store can contain content. so the store is basically a page which contain specific content.

what's the best way to implement this in Drupal?

# Answer
We used OG extensively in many sites with stores that are auto-created when a user registers. You can check out one of them here - www.craftsaid.com - each "store" is an OG. We also did the same thing on Bandromeda.com.

Install Organic Groups Module - http://drupal.org/project/og Install Rules Module - http://drupal.org/project/rules

After you have created a content type for your Group type (this can be anything you want it to be - if you're not familiar with OG it is an incredibly powerful platform that allows users to create groups to which other members may subscribe - essentially you create one content type as the "group" type itself and then any other content type can be set as "group content" that may be added to a given group) go to /admin/workflow/rules and add a rule for Event = After saving a new user account with an Action = Create a new entity with parameters of Entity type: Node, Content type: Your Group Content Type, Title: \[use tokens to create your title configuration\]

This will auto-create a Group upon registration. Otherwise you could simply create a link to node/add/store (or whatever your group content type is) from wherever makes the most sense in your site.

That is a very basic explanation - there are probably 50 ways you could implement this to accommodate your general description of your need. Hope that helps!
> 1 votes

# Answer
If each store is just a page, with no checkout process, then you could

1. Create a "Product" content type, add required fields
2. Configure role and permission to allow adding product node
3. Create a View listing products for a particular store ( by product author(s) )

Alternatively, you could look at a commerce solution such as Drupal Commerce or Ubercart, but that may be overkill in this situation when a core solution + Views may suffice.
> 0 votes

# Answer
You should check out the Organic Groups module. Also here is a link to all the projects associated with this module. Looks like there used to be a "store" feature, but that was back with Drupal 4.x. However if the store only holds pieces of content, not actual sales, then OG does a great job of managing multiple "stores" within the site.
> 0 votes

---
Tags: users, organic-groups, nodes
---


# Question
Title: Organic Groups - Include nodes as part if it on group creation
I'm looking for at way to make some nodes, eg. "About us", part of the Organic Group.

```
/
/about-us*
/more-general-stuff

```

When I create the OG I want the nodes marked with * to be part of the group.

```
/my-group
/my-group/about-us
/my-group/another-page-for-the-group

```

/my-group/about-us is a copy of /about-us, and if you edit /about-us it also updates /my-group/about-us.

/my-group/about-us could contain blocks specific for the group.

So when I tried to use views to create a page on /%/about-us, I'm not able to put blocks on that "page".

Any ideas is welcome.

# Answer
> 0 votes
You can use Rules to generate the nodes upon creation of the group. If you haven't worked with Rules it is an incredibly powerful module and is well worth the time investment to learn its intricacies.

---
Tags: organic-groups
---


# Question
Title: Programmatically import users and create each for them organic groups
I have a function that allows me to create users from the data of an external database:

```
  function _loginuser_authenticate_validate($form, &$form_state) {
    global $user;

    // Use external database.
    db_set_active('external_database');
    // …
  }

```

Now I want to create, for each user from the external database, two groups (each group with four Drupal users, a group administrator, and three normal members).
I can create a group with `og_insert_group($node);`. I can also create an admin for this group with `og_save_subscription($node->nest, $node->uid, array ('is_active' => 1, 'is_admin' => 1));`.

I don't know how to create multiple groups, and add members to these groups. I also do not know where to put the code to create groups in the LoginUser module, or in another module.

# Answer
Your explanation seems a little bit confused. Creation of an OG is as simply as creating a node.

So from what I understood you wish :

1. Get a user data from external source (how you perform this ? by cron ?)
2. Create a group for each user
3. Assign that user as group admin ?

Is it what you want to perform ?

Also take a look here :

http://drupalcontrib.org/api/drupal/contributions%21og%21og.module/7
> 0 votes

# Answer
You can definitely use the Rules module to auto-create the groups when the users are registered. If you already have the users you want to add to the groups created you should be able to also add an action to add the group members using a rule as well.
> 0 votes

---
Tags: organic-groups, database
---


# Question
Title: How to use galleria to create slideshow of Images in a Node
Can http://drupal.org/project/views\_galleria be used to create a slideshow of images in an image field on the node display page (i.e. /node/\*)?

When I go to "Manage Display" for the content type, I do not see "..Galleria.." as one of the display options for the image field that can take multiple images?

I am able to use http://drupal.org/project/views\_slideshow but it is not as nice.

Any recommendations of other decent looking slideshow modules is also welcome

# Answer
> 0 votes
this solved alot of issues with having slideshows specific to a node's image field:

http://drupal.org/project/field\_slideshow

you dont have to build any views.

# Answer
> 1 votes
Quick solutions eva module , with this you can set up a view of images with contextual filter (nid) , then attach it to the content type , then it will be available under manage display

---
Tags: nodes, javascript, media
---


# Question
Title: How to filter views "node-changed-day is not node-created-day"
I want to list node posts so, that only those ones will display which node-updated day is not the same as node-creaded day but at least next day or newer. How to filter it in Views? I'm using Drupal 6.

# Answer
> 0 votes
I just found a solution myself. There is available ”Views PHP Filter” module for Drupal6. After installing I added new filter: ”Node: Node ID PHP handler” for my Views. I left the filter options as default but filled PHP– textarea vith code below, and it worked.

```
$nodeids = array();

$result = db_query(db_rewrite_sql('SELECT DISTINCT(c.nid) FROM {node} c  WHERE c.status = 1  AND  c.changed >= c.created + 86400  - c.created % 86400  ORDER BY c.changed DESC'));

while ($node = db_fetch_object($result))  {
$nodeids[] = $node->nid;
};

return $nodeids;

```

---
Tags: views, datetime
---


# Question
Title: Major differences between Drupal-6 and Pressflow-6?
I am having a Drupal-6 site and was considering to scale it. I came across Pressflow and was wondering about the major differences between the two. I came across a similar question of Drupal-7 vs Pressflow-7 but was looking specifically for Drupal-6 vs Pressflow-6. Can anyone enlighten or share their experience of using both.

# Answer
> 5 votes
Take a look at the wiki: "Comparison - Pressflow versus Drupal".

---
Tags: 6
---


title: drupal 7.10: View of Most viewed posts

text:
# Question
Title: drupal 7.10: View of Most viewed posts
i am trying to create a most viewed posts page using views. I know how to create a page with most commented post but I can't seem to find the view count option. Any suggestions. Do i need to add a relationship?

# Answer
> 15 votes
Try using the Statistics modules. It come with Drupal core.

Documents from d.o: http://drupal.org/documentation/modules/statistics

UPDATE BELOW: (SCREENSHOT)

# Answer
> 3 votes
I know that Statistics module is in the core but I think Radioactivity module creates a more realistic solution to check the activity of a node. You can add decay profiles and you can assign energy for the different events. For example you can add 1 energy if someone view the node, you can add 5 energy if someone commented on the node and you can add 15 energy if someone flagged as favorite.

I hope it helps.

From the project page:

> This module provides a field type which can be used as a hotness metric or a regular view counter for entities and for much much more. In essense, entities receiving attention (views or actions defined by Rules) are heated while inactive ones slowly cool down.

# Answer
> 2 votes
You generally should avoid using the statistics module as it adds unwanted write queries to the database and won't be accurate while using reverse proxy caching such as Varnish.

The recommended solution would be to use Google Analytics to track your pages statistics and then the Google Analytics Statistics module to retrieve the data and expose it to views.

---
Tags: 7, views
---


title: API to display block in regions

text:
# Question
Title: API to display block in regions
I would like to display blocks in region by code, in the same way that I can use context (so: if I'm on a node\_view of type "article" display block "user login" on region "Sidebar first", for example).

I know how to load and display blocks but I don't know which is the best place to make it.

Have I to add the render function in regions template? Or have I to use a theme function to do this?

# Answer
Instead of using the admin blocks interface, if you really want to manually render blocks, you can render:

Directly in a template:

```
if ($block = module_invoke('module_name', 'block_view', 'block_delta')) {
  print render($block['content']);
}

```

Via code, with drupal\_add\_region\_content

```
if ($block = module_invoke('module_name', 'block_view', 'block_delta')) {
  drupal_add_region_content('left',  $block['content']);
}

```
> 2 votes

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


# Question
Title: How to change layout of node add/edit form with Display Suite?
Is there a way to use Display Suites to change a Layout for a Node Edit/Add form? i.e. form at: .../node/add/

# Answer
> 14 votes
That is possible yes. Display Suite contains a submodule called 'Display Suite Forms' which allows you then to select a layout and move the fields around in that layout.

Note that it's impossible though to move the individual elements in the vertical tabs. That will always remain the same and will rendered at the bottom of the layout.

---
Tags: nodes, forms, theming, display-suite
---


# Question
Title: How can I hide the user profile from users?
I'm using IP-based login to give visitors in a private network access to some parts of my Drupal 6 site. This means that all users from this private network are logged in as the same user.

Theoretically, anyone accessing the site that way could change the user password, which is something I don't really want to allow. I tried the User Protect module, but that just doesn't work at all on my site. I suspect that it is just incompatible with the IP login module.

Ideally, I'd like to hide the `/user` page entirely from certain users. They shouldn't be able to access it and shouldn't be able to change their password or any other profile information.

How can I prevent access to the user profile?

# Answer
> 1 votes
You can do this with hook\_menu\_alter changing the access callback and access arguments for the relevant user menu items.

e.g

```
/**
 * Implements hook_menu_alter
 */
function MYMODULE_menu_alter(&$items){
  // Change user view and edit callbacks to be "administer users" access only.
  $items['user/%user/view']['access callback'] = 'user_access';
  $items['user/%user/view']['access arguments'] = array('administer users');
  $items['user/%user_uid_optional']['access callback'] = 'user_access';
  $items['user/%user_uid_optional']['access arguments'] = array('administer users');
  $items['user/%user_category/edit']['access callback'] = 'user_access';
  $items['user/%user_category/edit']['access arguments'] = array('administer users');
}

```

Clear menu cache to apply.

---
Tags: 6, users
---


# Question
Title: Taxonomy term view - show node fields in the view?
Ive enabled the default view 'Taxonomy term' which overrides taxonomy term pages. How can I add fields for my nodes? Currently it says 'The selected style or row format does not utilize fields.' Thanks

# Answer
Right above "Fields" that you can't change is "Format". It's set to "Show: Content" by default. Change that to "Show: Fields".
> 2 votes

# Answer
It depends on what kind of Views "Format" you are using. For example if you have JSON data document/ Table / etc., you can change its "Field output" to Normal (if you have "Raw" it will echo only correspond id)
> 1 votes

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


title: Undefined index error in log

text:
# Question
Title: Undefined index error in log
I'm receiving the following error message in my log

```
Notice: Undefined index: und in include()(line 56 of /sites/all/themes/mysite/node--recipe.tpl.php).

```

Here is the line off code

```
$node->field_recipe_skill_audio[$node->language][0]['filename']

```

This error message is well documented but i've been unable to get the fixes working. I have try the following request.

```
$node->field_recipe_skill_audio['en'][0]['filename']
$node->field_recipe_skill_audio['und'][0]['filename']

```

# Answer
You can avoid the notice error by checking if that field has data, e.g

```
if (isset($node->field_recipe_skill_audio[$node->language][0]['filename'])) {
  /* Do stuff */
}

```

or

```
if (isset($node->field_recipe_skill_audio[LANGUAGE_NONE][0]['filename'])) {
  /* Do stuff */
}

```
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How to theme the register page (mysite.com/user/register)
How to theme the register page (mysite.com/user/register). I'm using the Omega theme.

Where do I find the template page **user-register.tpl.php** ?

I don't need to add fields to the form, I just to theme this page.

# Answer
To theme that path via a template file, you can use:

`page--user--register.tpl.php`

copy `page.tpl.php` to that filename, clear theme registry cache to apply.

Note, you may need to copy `page.tpl.php` from your base theme to your sub theme `/templates` folder to bring it into scope.
> 1 votes

---
Tags: theming
---


title: $query->limit(10) gives fatal error

text:
# Question
Title: $query->limit(10) gives fatal error
I am trying to develop a simple module in Drupal 7. I want to return a table with some data in a function, which i am able to achieve. I am stuck in the pager part though.

I used

```
pager_default_initialize($total, 10);
$html .= theme('pager', array('quantity',$total));

```

and I can see the pager below my list, also I have 21 records for now and it shows \<\< \< 1 2 3 \> \>\> which means it calculating 10 records each.

But my issue here is I can see all the 21 records at once regardless of whichever page I go to. I suppose I have goofed up my page\_query. When I tried using `$query->limit(10)` it gives error Fatal error:

> Call to undefined method SelectQuery::limit() in C:\xampp\htdocs...............

If I comment `$query->limit`, there's no error but it does not work completely. This is my query

```
$query = db_select('profile');
$query->fields('profile', array('id', 'name', 'store_name', 'company', 'city', 'email', 'phone'));
$query->orderBy('id', 'DESC');
$query->extend('PagerDefault')->limit(10);
//$query->limit(10);
$results = $query->execute();

```

Please help!

Thanks in advance! :)

# Answer
`extend()` isn't chain-able, it returns a new extended query object, so you need to assign the result back to the query object, e.g.

```
$query = $query->extend('PagerDefault')->limit(10);

```

Otherwise the query won't actually be extended and won't have the `limit()` method, hence the error you're getting.
> 4 votes

# Answer
Because you have to use range : db\_select documentation and more precisely range.
> 0 votes

---
Tags: 7, paging
---


# Question
Title: <class=""> in product title on new product type drupal commerce kickstart
I created a custom product variation called Switch Plate and on the product displays it is showing Product Name on the title I installed from the 2.0 version of Commerce Kickstart it only shows on my product not on the 2 generated products.

# Answer
Go to admin/structure/types, and click "Manage display" for your content type, which is a product display for your new product variation. Choose the "Product list" display, and make sure the title's format is set as *Default*.
> 0 votes

# Answer
There is a recent issue on this on the Commerce Kickstart's issue page; there is no solution yet, though.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: In Drupal 7, What is a good approach to copy the image from one imagefield to another imagefield?
I'd like to allow the user to upload an image once, and have it apply to 3 other image fields on the same page without requiring the user to submit the form. Afterwards I intend to apply different croppings to each image but that may not be related to this question.

Is there an existing module or solution to this? If not, what is a good place to inject this behavior client side?

# Answer
You should only use one image field, and then setup 3 *image styles* at:

> admin/config/media/image-styles

For each image style you can define a number of different actions, like cropping. When displaying the image you can use theme\_image\_style()

This is a part of Drupal core and can be extended by e.g. ImageCache Actions.
> 1 votes

---
Tags: javascript, media
---


title: Responsive MainMenu for D7

text:
# Question
Title: Responsive MainMenu for D7
I am struggling with Drupal menu. Currently my menu is not responsive. I know how to change it to become responsive using CSS. But I am wondering If there is any module that can do this easily.

Please give any menu module if available to be responsive and adaptive to different screen sizes or suggest me if there are any simple tweaks.

# Answer
This is hard to answer, because it depends very much on how your menu is designed and which navigation method you're going to use.

There's a sandbox project for the omega theme though.

Maybe this will help as well: Complex Navigation Patterns for Responsive Design
> 1 votes

---
Tags: navigation, theming
---


title: Remove title from hook_entity_view

text:
# Question
Title: Remove title from hook_entity_view
I need to remove title from rendered custom entity.

`unset($entity->title)` is not good because i still need to use its value in this rendered entity to use in markup.

css display:none is not good idea on my point of view as well.

# Answer
> 0 votes
`hook_entity_view()`, and `hook_entity_view_alter()` are not the hooks you should use to avoid an entity title is rendered, as the entity title is not generally passed to the `$build` parameter passed to those hooks.

This is the content of the `$build` parameter for three different entity Drupal defines.

* Node
* Comment
* Taxonomy term

Furthermore, the purpose of hook\_entity\_view() is adding content to `$entity->content`, not altering `$entity`. The description given in the documentation page for the hook is the following:

> The module may add elements to `$entity->content` prior to rendering. The structure of `$entity->content` is a renderable array as expected by drupal\_render().

To avoid the title is rendered for an entity, you should use a preprocess function for the template file used by the entity, and unset a variable used from the template file for the title. For example, for a node, a module could use the following code.

```
function mymodule_preprocess_node(&$variables) {
  $variables['title'] = '';
}

```

Similar code would work for comments, but in that case the function would be `mymodule_preprocess_comment()`.
For taxonomy terms, there isn't a title but there is the term name, which is printed from the template file using the following code.

```
<?php if (!$page): ?>
  <h2><a href="<?php print $term_url; ?>"><?php print $term_name; ?></a></h2>
<?php endif; ?>

```

Setting `$term_url`, and `$term_name` to an empty string would cause the following HTML output to be printed.

```
<h2><a href=""></a></h2>

```

# Answer
> 0 votes
By the comments it looks like you took care of this, but I was going to suggest using the hide() function in a template file and then print out that title variable where ever you needed it in the markup of the tpl.

---
Tags: entities
---


# Question
Title: Redirect anonym user after click on link
i have preprocess function

```
function THEME_preprocess_views_view(&$vars) {
    global $user;
    $view = $vars['view'];

    if ($view->name == 'questions_by_category' && $view->current_display == 'page') {
        $vars['header'] = '<div>' . l('Ask your question', 'node/add/question') . '</div>';
        if($user->uid == 0) {
            //this code not working
            if($_GET['q'] == 'node/add/question') {
                $path = drupal_get_path();
                drupal_goto('user/login', $path);
            }
        }
    }

```

i need to redirect anonym user to login page when he click on the link `node/add/question`, i also tried with `arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'question'` but this wont work.

The code inside `if($user->uid == 0) { }` works fine, i can redirect, but i need to redirect on click only. Also i need to redirect user back on the page after login, and this code :

```
$path = drupal_get_path();
drupal_goto('user/login', $path);

```

seems not working too.

# Answer
> 0 votes
ok i found solution, i just changed link for anonym user

```
if ($view->name == 'questions_by_category' && $view->current_display == 'page') {
        if ($user->uid) {
            $vars['header'] = '<div>' . l('Ask your question', 'node/add/question') . '</div>';
        }
        if ($user->uid == 0) {
            $vars['header'] = '<div>' . l('Ask your question', 'user/login') . '</div>';
        }
    }

```

---
Tags: 7, redirection
---


title: My hooks are not invoked by Drupal

text:
# Question
Title: My hooks are not invoked by Drupal
I am developing a module, but the hooks I am adding are not invoked from Drupal. It happens with more than one hook.

I read the documentation for the hooks, and I cannot find anything that would explain why this happens. I verified I am using the correct parameters, and returning the correct value.

What am I doing wrong? Is there anything I am missing?

# Answer
When developing a module, you should keep in mind the following notes.

* The implementation of a hook done from a module is a function whose name is prefixed with the module short name (also called *the machine name*); from the hook name, take off the *hook* part, and replace it with the module machine name. For example, the implementation of `hook_menu()` done from example.module is `example_menu()`. If the module is example\_menu.module, and the function is `example_menu()`, that is not considered the `hook_menu()` implementation for example\_menu.module.
This also means, for example, that the `hook_form_alter()` implementation in example\_form.module is not `example_form_alter()`, but `example_form_form_alter()`. As another example, the implementation of `hook_form_FORM_ID_alter()` done for altering the form returned from `user_register_form()` from example.module is not `example_form_user_register_alter()`, but `example_form_user_register_form_alter()`. (The form ID is *user\_register\_form*.)
* Generally speaking, using uppercase characters in the module machine name doesn't create problems: PHP doesn't make differences between `myModule_get_value()`, and `mymodule_get_value()`, and `$value = myModule_get_value()` would call either `myModule_get_value()`, or `mymodule_get_value()`.
Although, there is a case where using upper case characters in a module machine name would cause problems: when defining the update hooks for a module. `drupal_get_schema_versions()`, the function that returns a list of available updates, contains the following code.

```
// Prepare regular expression to match all possible defined hook_update_N().
$regexp = '/^(?P<module>.+)_update_(?P<version>\d+)$/';
$functions = get_defined_functions();
// Narrow this down to functions ending with an integer, since all
// hook_update_N() functions end this way, and there are other
// possible functions which match '_update_'. We use preg_grep() here
// instead of foreaching through all defined functions, since the loop
// through all PHP functions can take significant page execution time
// and this function is called on every administrative page via
// system_requirements().
foreach (preg_grep('/_\d+$/', $functions['user']) as $function) {
  // If this function is a module update function, add it to the list of
  // module updates.
  if (preg_match($regexp, $function, $matches)) {
    $updates[$matches['module']][] = $matches['version'];
  }
}

```

The last line executed from `drupal_get_schema_versions()` is the following one.

```
return empty($updates[$module]) ? FALSE : $updates[$module];

```

If the module name is myModule.module, `drupal_get_schema_versions('myModule')` will return just the functions with a name that starts with myModule\_update, and ends with a number; functions like `mymodule_update_7120()` will not be included because the regular expression used from `drupal_get_schema_versions()` is case sensitive. This still applies to Drupal 8, as the regular expression is still the same used in Drupal 7.
* Some hooks are called in specific moments. For example, `hook_menu()`, and `hook_menu_alter()` are called from Drupal 7 after a module has been enabled/disabled, or when the cache for the router information is cleared; `hook_init()` is not invoked for cached pages.
Once the hooks are invoked because a specific event happened, they will not called again until a similar event doesn't happen. They are not called in two successive page requests.
* Drupal caches the list of hooks implemented from a module. If you are editing the code of an enabled module to add new hooks, you first need to disable and re-enable the module, or Drupal will not notice there are new hooks.
* Ensure that a `return` statement didn't sneak its way into one of your hook functions during a refactoring. It has the potential to break not only the hook that it appears in, but to cause a chain reaction that breaks other hooks as well, making the problem difficult to locate.
> 13 votes

---
Tags: hooks
---


# Question
Title: how to add credits each month with rules?
How do I add commerce credits to a specific type of user the first in every month? I cant seem to find a date field in rules--\>add rule--\>events

# Answer
Check out Rules Example which is an example module showing how to integrate custom module with rules.

You can add a new parameter (e.g. condition - check if this is first day of the month) and perform all checks/actions you need there.
> 2 votes

---
Tags: commerce, rules
---


# Question
Title: Drupal private file system and possible sharing options
I have issues setting file system (private) for users as described here. I wonder what they ment by

"This setting is used as the preferred download method. The use of public files is more efficient, but does not provide any access control."

If i want let only user that uploaded file have access to the file, which setting should i choose, and what are drawbacks?

Moreover, could if i choose private system, could i control access by module (for exaple User relationships module, so the friends of user could download the file)

Thanks.

# Answer
> 1 votes
Private filesystem allows Drupal to run permission checks before serving the requested file.

If you are using public file system, direct links to your files will be accessible to anyone, no matter they are logged in users or anonymous.

Regarding your questions:

> If i want let only user that uploaded file have access to the file, which setting should i choose, and what are drawbacks?

You should choose *private* filesystem. Drawbacks are explained above.

> Moreover, could if i choose private system, could i control access by module (for exaple User relationships module, so the friends of user could download the file)

Check out `hook_file_download()` \- you can use it in a custom module to perform custom access checks.

Also, see this thread.

---
Tags: files
---


title: Can I disable module menu items?

text:
# Question
Title: Can I disable module menu items?
I have a module with a menu which I build like this:

in **moduleName.module**

```
function moduleName_menu() {
  $items = array(
    'title' => 'whatever',
    'page callback' => 'something_callback',
    ...
    'type' => MENU_NORMAL_ITEM
  );
  return items;
}

```

Now I want certain items to be disabled (Clicking them should do nothing, similar to using `disabled="disabled"` on a `<input type="button">`). I tried adding `'#disabled' => true`, as I would do for form items, but that didn't work. How can I disable menu items?

**UPDATE**

I tried using `myTheme_menu_link` to disable the menu items. So in the code above, I add `'disabled' => true` or `'disabled' => false` to certain menu items. Then, my `theme_menu_link` function looks like this:

```
function vitrine_menu_link(array $variables) {
    $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  if (isset($element['disabled']) && $element['disabled']) {
    error_log('Hoping to see this somewhere in the log');
    $output = '<a>' . $element['#title'] .  '</a>';
  }
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

I test it by emptying all caches, which rebuilds the menu, but still, the error I'm trying to log never get's logged. It seems as though my `'disabled' => true` never makes it to this function...

# Answer
> 1 votes
This can only be done on the theme layer. Try taking a look at `theme_menu_link()`.

# Answer
> 1 votes
As far as I know you can't disable links in that way. Depending on what you want to do I believe your options are either to add a class, programmatically or by using the Menu attributes module, and then use jQuery to disable the link, or not linking the menu item at all.

**First option**
Add a class or an id to the link, and do something like this to disable the link:

```
$('#linkid').click(function(e) {
  e.preventDefault();
});

```

**Second option**
Use the Special menu items module with the `<nolink>` option, which results in a menu item that is not linked, i.e. no `<a>` tag. You could of course do this programmatically as well, but the module is rather simple and straight forward.

This is more general solutions for menu items, which I realize it's not exactly what you are asking (a solution to your code), but it does provides solutions for your question *"Can I disable module menu items?"*.

# Answer
> 0 votes
You could use the nifty `menu_attributes` contributed project. (You can download it from here) or just `hook_menu_link_alter()` (documentation) around which that module is built.

Both these approaches allow you to add attributes (including classes) to menu links.

---
Tags: 7, routes
---


title: Taxonomy Terms jump list

text:
# Question
Title: Taxonomy Terms jump list
I have created a jump list with certain taxonomy terms, but it seems impossible to get the url right.

I have a URL pattern setup for these terms: /dealers/towns/\[taxonomy\_term\]

But in the jump list I can't find a way to get this url right, there's no way to select the actual url, how can I do this?

# Answer
You have to add a new field on the view, which is custom link. edit this custom link and rewrite the result to be something like

```
<a href="/dealers/towns/[taxonomy_term]">term</a>

```

after that click on your jump list settings and chose the newly created field
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Disable the message shown when a node is created
I'm using Rules to redirect the user to a different page after a node has been created.

Is there an easy way to suppress the sticky "XXXXX has been created" message?

# Answer
It's node\_form\_submit that is creating those messages. You could pretty easily use hook\_form\_alter on the node form and use your own version of node\_form\_submit instead. All you would need to do, would be to copy the function and add an user\_access('whatever') check before that message is created.

Alternatively, you could in preprocess\_page function, check which messages is being served, and remove unwanted ones, but that would be a bit more tricky. Should be possible with some regex. On the other hand, this method would be a bit more upgrade friendly, since you could remain using the node\_form\_submit function and would get future changes if any.
> 3 votes

# Answer
You can use Disable Messages drupal module to hide specific messages from users
> 1 votes

# Answer
If you're using D6 you can use Better Messages module.
> 0 votes

---
Tags: nodes
---


# Question
Title: Using Migrate in Drupal 6, setup and parsing XML
Is there a better walkthrough to setting up Migrate than thisdocumentation on Drupal.org? I have followed those directions, and I can't get my classes to show up in the UI. Is there anything clearer?

And how would I go about using Migrate, once it's set up, to parse a series of XML documents (one list XML that includes an additional document per node) into nodes which I can then manipulate in Views?

**EDIT** Now I've gotten my XML read and fields set up (I think), but now I can't get the nodes to save. The import has the correct number of nodes, but they don't ever get imported. The wine examples in the documentation didn't say anything about using prepareRow() or anything when you are using XML. Where are my nodes? Can I pull out that data with Views even if nodes don't import? My end use for this is to arrange everything with Views.

# Answer
> 1 votes
Yes, look at the Beer examples that come in the migrate module itself. If you want some example code and usage with some explanation I find the BTMash blog posts useful. While the BTMash blog is D7 based -- the hooks and usage of Migrate is widely similiar between D6 and D7.

---
Tags: views, 6, migrations
---


# Question
Title: How to use views and LDAP query to get a list of names in a webform?
I am using Views, LDAP query, Webform Views, and Webform to try and produce a webform that -- along with a bunch of other stuff in the webform -- has a select list of names, with emails associated, from our ldap server. So far I have gotten a View page with all the names, but I don't know how to condense that to not just be a giant list (un-collapsible) in the middle of a webform. So any idea how to do this or some similar solution so that the person filling out the form can find a name in a list of names, and for either them to see the email in a list and select/write it in another field, or for them to just select a name from a select list and have that selection effect the results(like providing an email to go with the name)?

Some other info -- the LDAP data has names and emails, as well as a variety of other information that would be useful to the people reading the results. Also, I have tried using feeds, and ldap feeds and was unsuccessful, but I would be happy if there was anyway to use both of those as well.

# Answer
> 1 votes
If you have a valid ldap query with names and emails your basically there with Views and LDAP.

You want to make a custom webform component in a module using PHP code. You can use `views_get_results` to get the results of the LDAP view as an array.

Then just build a webform component as you would a Forms API select widget with your values.

You then tell the webform to use your component in the UI.

---
Tags: views, webforms, authentication-authorization
---


title: Facebook share button not showing up

text:
# Question
Title: Facebook share button not showing up
I have installed the Facebook Share module on my Drupal 7 site and configured it accordignly to my preferences but it is not showing up on any of the pages I chose.

I just tested it even further by choosing it to be displayed every (full) node and it is showing up on basic pages, faq, and some more but not on my Ubercart products and one custom content type. It does show up on another custom content type.

Any ideas?

# Answer
I realize this isn't exactly an answer to how to get Facebook Share on all of your pages, but I figured I would toss this out there as a possible alternate solution.

I've tested a lot of the different sharing modules and I would recommend Service Links instead of Facebook Share. I've found it to be highly configurable, very flexible and it just works really really well. You may want to give it a try, perhaps it'll show up properly in the places you want it to show up.
> 2 votes

# Answer
I was finally able to resolve the problem. Just posting the solution in case it comes useful to anyone else.

As it turned out, the problem with Facebook share was display suite. The nodes that it was not working for were, of course, not random as it initially looked. They were the nodes which were using display suite. I didn't manage to find a solution to it and therefore I used the service links module (proposed by @Kenny Wyland), which had an extra feature covering the case that display suite is being used.
> 3 votes

# Answer
You can try to enable it directly in template php files (for example node.tpl.php) by using

```
<?php hide($content['facebookshare']); ?>

```

And then later in tpl, where you want button to appear:

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

```

Also make sure you eneble it for specific content type here:

**/admin/config/user-interface/facebookshare**

Also, other fb modules may be conflicting it if you have them.
> 0 votes

---
Tags: social-network
---


title: Multiple "page not found" errors in log

text:
# Question
Title: Multiple "page not found" errors in log
I am getting "page no found" errors in my website log. Maybe it is some bots that search for directories that do not actually exist. I get at least 50-100 daily of these messages.

The log says, for example:

> www.mysite.com 46.29.3.237 - - \[14/Jan/2013:17:02:33 +0100\] "GET /files HTTP/1.1" 200 683 "-" "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17"

How is it possible to get rid of that? I am just worried if there is problem on my side or it happens to any site. Thank you.

# Answer
> 1 votes
It's very likely automated programs looking to see if you have the proper restrictions on certain directories.

There's no way to prevent it from happening, but you could either turn off 404 logging or have your server log 404 errors to a different file.

---
Tags: 6, log-messages
---


# Question
Title: Inject variables only in teasers (template suggestions)
How could I detect if node type is article (in template.php) but process variables only for teaser of article, not article i full mode. (I have template suggestions so i have node--article-teaser.tpl.php). Like:

```
if ($node->type == 'article' and inject only if article-teaser.tpl.php)

```

Thanks!

# Answer
> 2 votes
In a preprocess/process function for the node template file, you just need to check the following variables:

* `$variables['teaser']` must be `TRUE`
* `$variables['node']->type` must be `'article'`

`$variables` is the parameter passed to preprocess/process functions.

---
Tags: theming
---


# Question
Title: How to display background images from CSS included by modules
I'm working to take a single page "site" built in jquery/css and convert it to a D6 module.

the code contains more than one css file which has classes like this:

```
background: url('images/stadium.jpg') no-repeat left top;

```

The question I have is: How do I get those images recognized?

Normally, in the tpl.php files I include with my module I set up my image like this and everything is fine:

```
<img src="print base_path().drupal_get_path('module','my_module'); /images/my_image.png" />

```

I don't know how to get images call from css classes to appear, and I can't build the path out all the way manually since I don't know where, or in what theme my module may end up.

If anyone has any ideas, or docs they can point me to I'd appreciate it. if you need any clarification please let me know.

Thanks! Steph

# Answer
Basically given:

```
background: url('images/stadium.jpg') no-repeat left top;

```

The image will be loaded from the path relative to the CSS file.

e.g:

```
/styles.css
/images/stadium.jpg

```

The image is loaded from the relative 'images' subfolder.

Presumably, if the design is all controlled by a module, you could drupal\_add\_css the css file and have the image files relative to that in the module folder.
> 0 votes

---
Tags: theming, 6
---


# Question
Title: ubercart checkout review button position
I use drupal 6 and ubercart 2.

I would like to change position of the checkout button on checkout/review page to the top or possibly to duplicate it (it is currently on the bottom of the page which is not very user friendly) I found a function in uc\_cart.pages.inc called

```
function theme_uc_cart_checkout_review($panes, $form)

```

Inside on the bottom I found the code for review button

```
$output .= '<tr class="review-button-row"><td colspan="2">'. $form
        .'</td></tr></table>';

```

However, moving the code above the table code, breaks whole page. (I tried this inside the .inc file, because adding the function inside template file, I got an error) What would be the correct way of achieving my task? Thank you

# Answer
your better off targeting the checkout button via CSS than mess with ubercarts tables on checkout as the $form contains all of the other code which you would need to parse to extract the button and apply it somewhere else.

Just do a position: absolute on the button.

If your CSS isn't up to par, then I would parse the $form variable and preg\_replace() it out. You'll need to have good regex skills to grab it.
> 1 votes

---
Tags: 6, theming, ubercart
---


# Question
Title: How to attach a view attachment display to an Openlayer Data Overlay display?
\[Drupal 7, Views 3, OpenLayers\]

## **THE PROPOSED SCENARIO:**

I would like to attach a view attachment display before an OpenLayer Data Overlay display. The attachment display would contain some exposed filters and a table of content data.

Using Better Exposed Filters I could enable auto submit and hide the submit button on the filter form at the attachment display, so both the attachment content table and the OpenLayer Data Overlay displays would get updated via AJAX. This would create a better user experience.

## **THE ISSUE:**

Apparently I can attach view attachment displays to any view display but OpenLayer Data Overlay displays.

## **THE QUESTION:**

Is there any work around or module implementation that could make it possible to attach a view attachment display to an OpenLayer Data Overlay display?

Another way to go would be perhaps having a block for the content data table and its filters. In this case, how could I get the AJAX on the block view to trigger the OpenLayer Data Ovelay view, so both views get the filters applied at the same time?

# Answer
The proposed scenario works just fine if you attach the attachment display to the OpenLayers Map display instead of to the OpenLayer Data Overlay.
> 1 votes

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


title: List pages on frontpage with views?

text:
# Question
Title: List pages on frontpage with views?
So, I'm relatively new to Drupal, and I'd like to make a Drupal site with a front page with a grid of links to other commonly used pages on the site. This site is intended as a sort of community page for a small town, so it would be links like Government, News, Business Directory, History, Forum, etc.

Some of these pages are basic pages on my Drupal site, some are external links, and some are links to views or modules, like the aggregator module. I'd like all of the links to be sortable and generally have the same markup. I'd also like these links to be gathered automatically, i.e. via the 'Promote to Front Page' option or something like that. I ABSOLUTELY DO NOT want to hardcode this to a basic page.

So far my solution has been to create a view with a list of title fields from pages promoted to the front page, and a special content type I named 'Link' which are actually just redirects to external urls. The problem now is that I don't know how to include special pages, like aggregator or view.

Any ideas? Is there a better way to do this? Have I missed something?

# Answer
> 0 votes
If I understand correctly, these are the steps I would take.

1. Create a `Link` content type
2. Download the Link module which will allow you to paste in internal or external URL's and store them in a CCK field.
3. Add a link field to the `Link content type`
4. Create a view that brings in all of the `Link` content types and displays them on the home page i.e (Title, Body, Link).
5. Sorting would only be possible (without custom code) if you used a table as your display type.

# Answer
> 0 votes
you will have to add a new display type in your views "PAGE" and give it a path so you can goto that page directly.

---
Tags: views, navigation
---


title: Help changing views HTML output

text:
# Question
Title: Help changing views HTML output
I have View set up to display a list of images that are related to nodes elsewhere in my site, and I've styled them so that hovering over them darkens the image and displays the node's title. Unfortunately, the title div obscures the image, and making the title into a link only affects the title text.

What I'd like to do is wrap the title div in tags, so this:

```
<div><a href="target">Title</a></div>

```

Turns into this:

```
<a href="target"><div>Title</div></a>

```

I have an inkling that I'll have to do this either with hooks or in one of the views.php files, but I'm not sure where to start; can anyone help me?

# Answer
> 0 votes
Filter title and use token like: `<a href="target"><div>[Title]</div></a>`

---
Tags: views
---


# Question
Title: prevent file upload renaming for each node
I would like to re-use some pdf files that doesn't change for my product content type and avoid to have by example:

node/product01-\> product-datasheet-01.pdf

node/product02-\> product-datasheet-02.pdf ...

but instead:

node/product01-\>|

```
                  | --> product-datasheet.pdf

```

node/product02-\>|

Already tried "File (Field) Paths" and "File (Field) Paths" modules but doesn't really fit on my needs because they works on single node.

Conf: D7+Ubercart3

thanks! LS

# Answer
Sounds like a job for:

## filefield\_sources

> * Re-use files by an auto-complete textfield
> * Attach server-side files uploaded via FTP
> * Transfer files from a remote server (cURL required)
> * Select existing files through the IMCE file browser
> 0 votes

---
Tags: 7, nodes, ubercart, files
---


# Question
Title: How to change a node add form without changing the node edit form
I'm using drupal 7

I'm writing a custom hook\_form\_alter something like this

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "rating_node_form")
        {
            // Do something
        }
}

```

it seems that both the node add form and the node edit form are using the same form ID. I'm wondering if there is a way to determine weather you are editing or adding a node and make changes to the form accordingly. Do they always have to be the same exact form?

# Answer
node\_object\_prepare(), which is called from `node_form()` (the form builder for the node editing form), executes the following snippet to verify if a node is being added, or edited:

```
  // If this is a new node, fill in the default values.
  if (!isset($node->nid) || isset($node->is_new)) {
    foreach (array('status', 'promote', 'sticky') as $key) {
      // Multistep node forms might have filled in something already.
      if (!isset($node->$key)) {
        $node->$key = (int) in_array($key, $node_options);
      }
    }
    global $user;
    $node->uid = $user->uid;
    $node->created = REQUEST_TIME;
  }

```

In your case, you could use code similar to the following one:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "rating_node_form") {
    $node = $form_state['node'];
    if (!isset($node->nid) || isset($node->is_new)) {
      // The node is new.
    }
  }
}

```
> 10 votes

# Answer
Or you can check if the second argument `arg(1) == 'add'`

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'rating_node_form' && arg(1) == 'add') {
        // Do something
  }
}

```
> 3 votes

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


title: Upload files to create nodes

text:
# Question
Title: Upload files to create nodes
I am trying to create an online catalog of products, that could be filtered, sorted, etc, and I followed these steps:

* I have created a content type (product)
* I have created a view where I can view and filter/sort these products

Now, the major problem is to manually enter hundreds of products! I have product descriptions in Excel, and image files with links, but I don't know how to upload everything in bulk.

How could I do this?

# Answer
> 1 votes
**Maximum flexibility:**

I would use the Migrate module. It has CSV support, and there's even direct spreadsheet support in the works. Migrate documentation.

It will require some coding, yes, and Migrate module is not the easiest module to get a grip on, so if you're new to coding, you may need some help with that, but I think it's by far the best solution.

**Easier implementation:**

The Feeds module claims that it can

> Import or aggregate CSV files

I haven't used that particular piece of functionality myself, but from previous use of Feeds, I'm under the impression that this could be configured from the UI, and thus wouldn't require any code. Feeds documentation.

---
Tags: nodes
---


title: Drupal form menu

text:
# Question
Title: Drupal form menu
I have a menu callback, and I want to add a form on it using the following code.

```
function parking_calculator_menu() {
  $items['admin/parkingcalculator'] = array(
    'title' => 'Node parkingCalculator',
    'description' => 'Adjust node parkingCalculator options.',
    'position' => 'right',
    'weight' => -5,
    'page callback' => 'get_form',
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

function get_form() {
  $form['short-term-parking'] = array(
    '#title' => t('Short term parking'),
    '#type' => 'fieldset',
    '#description' => t('Short term parking.'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

  $form['short-term-parking']['free_time'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => t('Free time'),
    '#default_value' => variable_get('free_time', 1),
    '#description' => t('Please enter Free time.')
  );

  $form['short-term-parking']['long-term-starts'] = array(
    '#title' => t('Long term starts'),
    '#type' => 'textfield',
    '#default_value' => variable_get('long-term-starts', 1),
    '#required' => TRUE,
    '#description' => t('Please enter Long term starts.')
  );

  $form['short-term-parking']['first-hour-cost'] = array(
    '#title' => t('First hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('first-hour-cost', 1),
    '#required' => TRUE,
    '#description' => t('Please enter First hour cost.')
  );

  $form['short-term-parking']['each-hour-cost'] = array(
    '#title' => t('Each hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('each-hour-cost', 1),
    '#required' => TRUE,
    '#description' => t('Please enter Each hour cost.')
  );

  $form['long-term-parking'] = array(
    '#title' => t('Long term parking'),
    '#type' => 'fieldset',
    '#description' => t('Long term parking.'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );

  $form['long-term-parking']['free_timel'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => variable_get('free_timel', 1),
    '#title' => t('Free time'),
    '#description' => t('Please enter Free time.')
  );

  $form['long-term-parking']['long-term-startsl'] = array(
    '#title' => t('Long term starts'),
    '#default_value' => variable_get('long-term-startsl', 1),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('Please enter Long term starts.')
  );

  $form['long-term-parking']['first-hour-costl'] = array(
    '#title' => t('First hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('first-hour-costl', 1),
    '#required' => TRUE,
    '#description' => t('Please enter First hour cost.')
  );

  $form['long-term-parking']['each-hour-costl'] = array(
    '#title' => t('Each hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('each-hour-costl', 1),
    '#required' => TRUE,
    '#description' => t('Please enter Each hour cost.')
  );

  $form['valet-parking'] = array(
    '#title' => t('Valet parking'),
    '#type' => 'fieldset',
    '#description' => t('Valet parking.'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );

  $form['valet-parking']['first-hour-costv'] = array(
    '#title' => t('First hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('first-hour-costv', 1),
    '#required' => TRUE,
    '#description' => t('Please enter First hour cost.')
  );

  $form['valet-parking']['each-hour-costv'] = array(
    '#title' => t('Each hour cost'),
    '#type' => 'textfield',
    '#default_value' => variable_get('each-hour-costv', 1),
    '#required' => TRUE,
    '#description' => t('Please enter Each hour cost.')
  );

  return system_settings_form($form);
}

```

With this code, I get the following error message:

> Recoverable fatal error: Argument 1 passed to drupal\_attributes() must be an array, null given, called in /var/www/html/APIG01JO2012039/includes/form.inc on line 3252 and defined in drupal\_attributes() (line 2366 of /var/www/html/APIG01JO2012039/includes/common.inc). The website encountered an unexpected error. Please try again later.

Why am I getting that error?

# Answer
The page arguments hook\_menu() expects is an array, not a string.

```
function parking_calculator_menu() {
  $items['admin/parkingcalculator'] = array(
    'title' => 'Node parkingCalculator',
    'description' => 'Adjust node parkingCalculator options.',
    'position' => 'right',
    'weight' => -5,
    'page callback' => 'drupal_get_form',
    // You used:
    // 'page callback' => 'get_form',
    // The correct value is the following one:
    'page arguments' => array('get_form'),
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to make scheduled Feeds importers run consecutively?
I have two Feeds importers that need to run in a specific order. For example:

1) Importer 'Films' imports all the films showing at a cinema, creating 'film' nodes.

2) Importer 'Showtimes' imports the show times for each film, creating 'showtime' nodes.

Both importers are scheduled to run every day. 'Showtimes' must always run after 'Films' is fully imported, as it creates node references to film nodes.

Things I have tried:

**Using Rules instead of Job Scheduler**. I created a custom rules action using this code:

```
while (FEEDS_BATCH_COMPLETE != feeds_source('my_importer_id', $node->nid)->import());

```

I created a rule that triggers on cron with two actions: import films, import showtimes. This kind of works but when I look at the newly created nodes, showtime nodes are being generated *before* all the film nodes are created. So I guess rules actions aren't processed sequentially...?

**Using Feeds Rules to chain one import onto another**. Feeds Rules provides a 'after Feeds import' rules event.

So I tried creating a rule that triggers 'showtimes' importer (using my custom action above) after 'films' importer has run. But I ran into a problem applying a condition on the rule provided by the module. I'm not convinced this is the best method anyway.

Thanks

# Answer
> 4 votes
You've entered that territory where you would be better served by a custom module than trying to force Rules to do what you want.

If I were posed with this problem I would do the following:

1. Create two CRON jobs one for each of the importers in a new module. See hook\_cron().
2. Turn off all of Feeds default importing for those feeds.
3. Install Elysia Cron.
4. Schedule your cron jobs with Elysia to run at appropriate intervals leaving enough time for the first to complete before running the second.
5. For extra credit you could programatically check that the first import is complete before allowing the second to run.

# Answer
> 1 votes
I tried creating 2 different cron jobs for each of my importers. But what did you put into hook\_cron for the importer? I put in the following:

```
$name = 'FEED_NAME';
$source = feeds_source($name);
$source->import();

```

But when I ran my cron job it only imported 2% and locked my feed importer... Any suggestions?

---
Tags: 7, rules, feeds
---


title: Drupal Commerce and Views Trouble

text:
# Question
Title: Drupal Commerce and Views Trouble
I am using Drupal Commerce and Views to make a products page that has a number of elements on it that are somewhat complex.

So far my page is a simple view that lists products as a table that also has some filters that users can modify to sort through products. However I am having trouble adding fields to that view to add the other elements i want to display.

**What i need:**

* I need to add a "Add to cart" button for each product displayed.
* I also need to add a product image that changes to the smaller displayed images when clicked.
* In addition I also want to add a number of custom text fields that do not change when the user is applying the filters to the page.

**What I have done so far:**

* I have attempted to use Views Field View and create sub views and add them to a parent view, however I am having trouble getting the sub views to show up.
* Found a couple of sites that show methods of adding "Add to Cart" buttons manually by editing the files. But i wanted to make sure there was not module for it already.

If anyone can point me in the right direction i would appreciate it.

# Answer
It sounds like you need to make a View of product display nodes, and not product entities.

The product display node has the product reference field on it, which provides the 'add to cart' formatter.

You can also show the product image and add other arbitrary text fields to the display node
> 3 votes

---
Tags: views, commerce
---


# Question
Title: How to set a specific taxonomy with Rules during feeds import?
Using Feeds, Drupal creates automatically a Rule "before saving a content imported by feeds".

In my XML file I've got a unlimited value field that goes into one unlimited value field in my content type and I would like to create a rule that populates another field in my content type with one specific term grabbed from the XML field.

i.e One item in the XML file has got terms:

**Fruit, Sicily, Oranges**

Another item has got other terms:

**Nut, Sicily, Chestnuts**

From here I need to grab just Fruit or Nuts.

So I've created two Rules:

The first one checks if the field contains the term Fruit.

1. Event: Before Saving a node from xml feed
2. Condition: Data comparision TRUE with term ID of **Fruit**.
3. Action: Here I would like to grab **Fruit**.

The second Rules is similar to the first one, but it checks if it contains **Nut**.

I've tried to set the Action with Set data value -\> Target field node:field-type:Taxonomy(Name) -\> Set a fixed value. It does not work.

I would like to know how to set the Action. If it's not possible using Rules, how do I achieve this aim?

Thanks in advance.

# Answer
> 1 votes
**Solution**

Rules

1. Before saving a node from xml feeds
2. Data comparision TRUE with rem id **Fruit**
3. Set data value -\> node:field-taxonomy-type -\> click on "Switch to direct mode input" and it will show the terms for that Vocabulary.

---
Tags: 7, rules, feeds
---


# Question
Title: granularity of views filter on date field
I have a content type which has a date field. That date field collects:

* Year
* Month
* Day
* Hour
* Minute

I've created a view with a filter on that field. The granularity I can filter with only goes down to day. Even if I use `operator: is greater than` and `Relative date: now`, the contents of the view only change once a day. That means that hour and minute are not taken into consideration.

Any ideas on how to solve this?

# Answer
1) Double check your field is collecting the correct date attributes. 2) Make sure "Date Views" is enabled under Modules (Requires: Date API, Views, Chaos tools).

If the above are okay then try creating a new date field making sure you're collecting all date attributes. This should rule out any issues there might be with the field. It could also pay to try create a new date field in a different content type and see how views reacts.

If the new date field doesn't work and views still can't filter down to seconds granularity then try a new test view.

Tested with no problems on Drupal 7.18, Date 7.x-2.6 and Views 7.x-3.5.
> 5 votes

---
Tags: 7, views, datetime
---


# Question
Title: Ubercart Ajax change attributes on checkout
I want to change the Product Attributes on checkout page by ajax. But when I save it by `uc_order_product_save()` in my ajax request and go to the preview step the attributes are gone.

It seems that preview step retrives the $order from form storage but not mine saved order. It is here:

```
function uc_cart_checkout_form_validate($form, &$form_state) {
$order = $form_state['storage']['order'];

```

How can I access to the storage order object in form to save attributes?

Thanks.

# Answer
> 0 votes
This may not be the best/proper way to do it, but I have manipulated product attributes in

`function uc_cart_view_form($form, &$form_state, $items = NULL)`

it is located in uc\_cart.module

$items is filled with products and you can loop through and review/assign attributes.

---
Tags: 7, ubercart
---


# Question
Title: How to export the contents of nodes in a view
I have a view that displays content based on some criteria. I would like to export all of the content of the results of the view into a text document or Excel spreadsheet, as I am intending to edit them for a book. Any idea how to do this?

# Answer
Take look at these modules: Views Data Export, Views Excel Export

Here is screencast about *Views Data Export*

http://www.lullabot.com/articles/module-monday-views-data-export
> 1 votes

# Answer
The module I use for this is http://drupal.org/project/views\_data\_export

You create a new style and attach it to your existing page/pane, you can export:

* CSV
* Microsoft XLS
* Microsoft DOC
* Basic TXT
* XML
> 1 votes

---
Tags: views
---


title: Add custom image in Views (No field)

text:
# Question
Title: Add custom image in Views (No field)
I have field structure in Views page. And i want add a image every page item. But not want create img field.,

I search this options in my Views, found 'custom text' option but not found a solution.

Is it possible? How? Thank you.

# Answer
> 2 votes
You need to add the image in that view's template file.

For views hook suggestions refer to this page http://api.drupal.org/api/views/theme!theme.inc/group/views\_templates/7

It would be best if you copy the default `views-view-fields.tpl.php` from views module to your theme directory and add the image there.

# Answer
> 2 votes
If the image can be considered data, I'd do as others have said and put it either in the views definition (which you've said you don't want to do), or place the image using the views template.

However, if the image is purely presentation, I'd sooner use CSS to place the image as a background image.

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


# Question
Title: How can anonymous users be allowed to post while still maintaining content integrity?
A little background: As you see on http://charlotte.ebayclassifieds.com, if you click 'post an ad' and then choose a category, you can fill out the form and submit content without having to sign up. This is all done and managed by sending validation emails to the email address field which, when clicked, allow a user to manipulate their content.

Can similar functionality be achieved in Drupal. I don't mind writing a module, but before I do, I want to make sure I am not reinventing the wheel.

I have a Drupal based local classifieds site for my community at http://www.gastonia.com. The site is growing in anonymous traffic, but few users are signing up to post. After a couple feedback loops with the community, almost everyone is saying that the one barrier to entry is having to sign up for an account, check email, validate, figure out how to navigate to post an ad, etc - indeed there are 7 steps necessary to go through before an ad actually gets published. It's too much..

We have reworked the architecture to be able to get it down to two clicks - click to post, then click to save. More specifically, a user clicks on 'Add content' and the node/add form pops up (there is now only one content type in the new architecture); Then, when they are done, they click save.

Originally I thought about the Inline Registration module, but it is still in DEV and the logic really is not there to support if the user comes back to post again with the same email address (without loggin in). I could alter it, but then we are back to writing a module.

I also thought about Rules - could rules handle similar functionality as the ebayclassifieds site or what I am trying to do? It would all be based on an email filed in the node/add form (CRUD functionality).

What direction or recipe would you suggest to achieve the functionality? Of course the ultimate goal here is to allow anon users to post; create an account behind the scenes for future use; allow use of the anon form even for users with emails that already have accounts (and assign content accordingly.) all while maintaining the security (from spam, bots) that is afforded by having a user sign up and authenticate an account.

EDIT: 4/1/2013 Gisle Hannemyr has revived the Anonymous Publishing module which is very close to achieving the goals described here and in other posts. Please take part in the the thread to provide some community feedback as to how to make the module bug free and better: http://drupal.org/node/1957644

# Answer
> 7 votes
I don't think this is possible with rules alone.

You need to alter the submission form in order to capture the verification email address, and you also need some logic to ban spammers and recognise returning visitors.

I am the maintainer of a project named Anonymous Publishing. It looks as if this module does what you want.

It still in development, but a Drupal 7 version has been used at several of my production sites without any issues. Please check it out.

You may also want to look at the answers under this question.

# Answer
> 2 votes
I achieved something similar to this on a recent project by creating a new menu callback – something like `example.com/anon_user` – which provides a form that doubles as a login and a registration form. This allows the user to very quickly go through the registration process OR to login without making them perform too many actions. It's actually been received fairly well.

Here's some simplified code to demonstrate this:

```
function example_form($form, &$form_state) {
  // Don't let authenticated users use this form.
  global $user;
  if ($user->uid != 0) {
    return MENU_ACCESS_DENIED;
  }

  // Let the user know what they can do.
  $form['intro']['#markup'] = "Already have an account? Login here. Don't have an account? Enter your email address and create a password and we'll setup an account for you.");

  $form['login'] = array(
    '#type' => 'fieldset',
    'user_email' => array(
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => t('E-mail Address'),
    ),
    'user_pass' => array(
      '#type' => 'password',
      '#required' => TRUE,
      '#title' => t('Password'),
    ),
  );

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

  return $form;
}

```

Validate it however you need:

```
function example_form_validate(&$form, &$form_state) {
  if (!valid_email_address($form_state['values']['user_email'])) {
    form_set_error('user_email', 'You entered an invalid email address.');
  }
}

```

In the submit handler, we need to figure out if this email already exists and attempt to log them in. If it doesn't exist, try to create an account for them.

```
function example_form_submit(&$form, &$form_state) {
  global $user;

  // Does this account already exist?
  if ($user_name = db_query("SELECT name FROM {users} WHERE mail = :mail", array(':mail' => $form_state['values']['user_email']))->fetchField()) {
    // Attempt to log them in.
    if ($account_id = user_authenticate($user_name, $form_state['values']['user_pass'])) {
      drupal_set_message('You have been logged in.');
      $user = user_load($account_id);
    } else {
      drupal_set_message('You have an account here, but you entered the wrong password.', 'error');
    }
  }

  // Create the account.
  else {
    // Use their email address as their username. Or handle this with a more complex login form.
    $account_name = str_replace('@', '_', $form_state['values']['user_email']);
    $account = user_save(null, array(
      'name' => $account_name,
      'pass' => $form_state['values']['user_pass'],
      'mail' => $form_state['values']['user_email'],
      'init' => $form_state['values']['user_email'],
      'status' => 1,
      'access' => REQUEST_TIME,
    ));
    // Log 'em in to their new account.
    drupal_set_message('Your account has been created and you have been successfully logged in!');
    );
    $user = user_load(user_authenticate($account->name, $form_state['values']['user_pass']));
  }
}

```

This is a pretty simple example. You could add password requirements, password confirmation via a 2nd field, a username field, better warnings, etc. The more restrictions the longer the process, so that's something to keep in mind.

# Answer
> 2 votes
There are many ways you can go about lowering the "registration hurdle":

* use Facebook connect to allow login with a facebook account (I use and like fboauth module)
* there are other social login modules that support google, paypal, yahoo, openid, etc.
* you can change the registration option to not require email confirmations.

To answer your last question:

> What direction or recipe would you suggest to achieve the functionality? Of course the ultimate goal here is to allow anon users to post; create an account behind the scenes for future use; allow use of the anon form even for users with emails that already have accounts (and assign content accordingly.) all while maintaining the security (from spam, bots) that is afforded by having a user sign up and authenticate an account.

I suggest to use a "anonymous node registration" feature (I can share code if you like). I adds "name" and "email address" fields to a "node add" form.

If the email doesn't exist already it will create a new user account. It uses the firstname to create the username and adds numbers if necessary to make it unique.

The password is set randomly and displayed to the user after submitting the node with a link to change the password.

Also, email confirmations won't prevent spam bots from signing up. I highly recommend the spambot module.

# Answer
> 2 votes
There's also this module now too: Create and Register

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


title: Zen sub-themes, sass vs inheritance

text:
# Question
Title: Zen sub-themes, sass vs inheritance
I may be running into two conflicting methodologies here.

Basic Drupal theme philosophy is to sub-theme and only change what is different from the sub-theme.

I am using taxonomy hierarchy and theming their views slightly different.

```
Taxonomy       Theme
--------       -----
Zone           MyBaseTheme
-Arts          ArtsTheme (change the header image)
--Dance        ArtsTheme (change the header image)
---Company1    Comp1Theme (change the header image and menu items)
---Comapny2    Comp2Theme
--Theater      ArtsThee
---Thespians1  Thesp1Theme
---Thespians2  Thesp2Theme
-Sports        SportsTheme
--Boys         SportsTheme
---Football    FootballTheme
---Baseball    BaseballTheme
--Girls        etc
---Field Hockey etc

```

This would seem to mean the I could subtheme off of zen then only make some minor changes for each. Common stuff such as font size and spacing would be done in MyBaseTheme. Zen seems to use a large font for instance so I want to make it smaller.

I could change the banner images in each sub-theme off of MyBase.

So far so good except...

Zen seem to want to use the SASS methodology for CSS coding.

Copying Starter Kit stuff is getting me whole copies of every CSS attribute for every sub-theme. I don't want copies, I want inheritance.

Anyone ever run into this problem? Thoughts?

# Answer
see this issue queue How to Approach Sub-Sub themes with Zen?

You dont copy zen starter kit for every sub-theme. You basically copy the .info file and template.php and create your theme folder. If you copy zen starter kit for every theme you'll run into the problem your seeing you end up "spamming" css files everywhere.

Sub-themes are best built smallest to biggest. By which I mean start off with the smallest number of .info file attributes and build up to the subtheme you want.

With so many subthemes you should be able to come up with 1 generic "base sub-theme" you then base all your subthemes off of in code.

Every sub-theme needs 1 uniquely named CSS file to properly fire off inheritance.
> 1 votes

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


# Question
Title: alphabetize the taxonomy term page without views
Is it possible to alphabetize the taxonomy page without using views?

for example:

```
THE TERM'S NAME
- A node
- B node
- C node
- D node

```

Thanks.

CLARIFICATION: I know I can reset the terms themselves to alphabetical, but that does not reset how the node teasers on the taxonomy term page are displayed (these remain in the order they where created). Resetting the display of teasers is what I am trying to achieve.

# Answer
The taxonomy module uses the taxonomy\_term\_page function to build the page that list the nodes attached to a term. But the function that really do the query is the taxonomy\_select\_nodes that is called by this previous function.

Remember: Never hack core

So you can implement a custom module and use the hook\_menu\_alter to rewrite the `page callback` for the `taxonomy/term/%taxonomy_term` path using a new function based on the `taxonomy_term_page` to call your custom `taxonomy_select_nodes` function that perform the changes you need to order the nodes that way.

You'll need to do something like this:

```
function mymodule_menu_alter(&$items) {
  // Rewrite the taxonmy term page callback
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'mymodule_taxonomy_term_page';
}

```

After that you'll have to implement the mymodule\_taxonomy\_term\_page function in order to be able to make the changes you need on the `taxonomy_select_nodes()` call:

```
function mymodule_taxonomy_term_page($term) {
  # code...

  if ($nids = mymodule_taxonomy_select_nodes($term->tid)) {
    # code...
  }
  # code...
}

```

Finally:

```
function mymodule_taxonomy_select_nodes() {
  # code...
}

```

You'll must `JOIN` the node table to build the query in the `mymodule_taxonomy_select_nodes` function because the taxonomy\_index table doesn't have the node title.

Notice that will change the behavior of all taxonomy term pages.

For more info about how to create a custom module see http://drupal.org/node/361112.
> 5 votes

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


# Question
Title: What's the solution to the system.theme.css bug?
I just traced a styling problem back to `system.theme.css` (in `/modules/system`). I discovered that this problem has existed in D7 since at least 2006, and that Dries opted against fixing it as of 2011, to avoid the risk of affecting existing themes.

I disabled the entire file (`system.theme.css`) and don't notice any differences on my site, either the public facing side or the administrative UI. Is there any reason to keep it around?

The bigger (and real) question, though is: ***what is the accepted solution to this problem?*** I can see several possibilities, but all have potential drawbacks, and I'm sure (since every user of D7 faces this ugliness) there are others who've tried several approaches and can advise all of us which are best.

Here are some possibilities:

* edit the file
* delete the file
* override the offending selector (`tbody`) with a different rule in another CSS file
* something else I haven't thought of

I don't really like the idea of modifying core, so the first two are not great, but I don't want a bunch of CSS being loaded that isn't being used either. What is the normal solution to this?

# Answer
It's got to be option 3 (overriding the offending selector (tbody) with a different rule in another CSS file) really, the only potential drawback is a few extra bytes of data to download and a fraction of a millisecond in processing time at the client end to apply the override. Both so small as to be unnoticeable.

CSS was built to be cascading so overriding a previously set style is well in keeping with the spirit of the 'language'. This has always annoyed me too and I pretty much instinctively add the override style when creating a theme from scratch. It hasn't caused me any problems to date and I can't see it doing so in the future.

That said, if you don't *need* the styles from system.theme.css the best thing to do would be to remove it completely with `hook_css_alter()`
> 2 votes

---
Tags: 7
---


# Question
Title: Alternative to .htaccess compression with Boost
My hosting provider doesn't support mod\_deflate directives in .htaccess to provide compressed HTTP responses.

I am using Drupal 7 with Boost and wish to compress HTML, CSS and JS responses.

Is there another alternative to doing this with .htaccess?

# Answer
> 0 votes
Core should support .gz for CSS & JS. This requires .htaccess rules though. For core they should already be included.

Looks like I never got around to gzip for Boost for 7.x. You can follow the issue here http://drupal.org/node/1416214

---
Tags: performance, .htaccess, caching
---


title: How to control CSS cascade?

text:
# Question
Title: How to control CSS cascade?
I've got a module building/theming question I was hoping to get some help with today?

I'm building two custom modules that create their own pages to be displayed on. Adding CSS and JS though "drupal\_add\_css" and "drupal\_add\_js" has worked just fine. the problem I'm having is that the CSS/JS is not the last CSS/JS that gets added when the page is called. The theme css is still being called last and overriding some of my styles.

So my questions are: can I unset the theme css from the module for the page where my mod appears? is that the right way to do things? or would it be better practice to rename my IDs/classes where conflicts occur?

Thanks!

Stephanie

# Answer
> 0 votes
The theme layer loads after your module has, so you won't be able to modify that part yet. I think you can just set the weight on your functions: http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_add\_js/7

Or just rename your ID's and classes to be specific to your module to reduce conflicts. I usually would name my ID's or classes nothing to generic, usually a shorthand for the name of the module then the name of the id or classes i want to reduce conflict.

---
Tags: theming, 6
---


# Question
Title: How to limit number of nodes a user can create per day?
In order to curb ardent spammers in Drupal 6, I'd like to limit the number of forum nodes that an authenticated user can create per day. So for example ordinary users can not create more than 3 posts each day. I am wondering how can I do so? Thanks

# Answer
> 1 votes
For Drupal 6 I have used Node Limit Number with great success.

> Limit the amount of nodes or comments your users create over a given time period. This module has been rewritten to integrate with Rules. Instead of going to a page to assign limits you now just need to create rules. A default rule has been provided as an example.

The 2.x branch also integrates with the Rules module to make it really flexible.

---
Tags: nodes, rules, advertising
---


title: Updating my custom module to Drupal 7

text:
# Question
Title: Updating my custom module to Drupal 7
I have updated a module from Drupal 6 to Drupal 7, but the following code doesn't work anymore. I have updated the .info file, but the module still doesn't work.

```
function header_image_block($op='list',$delta=0,$edit=array()) {
   if ($op=='list') {
     $blocks[0] = array(
       'info' => t('Header image'),
     );
     return $blocks;
   }

   elseif ($op == 'view') {
     $block = array(
       'subject' => 'Header Images',
       'content' => changeHeader(),
     );
     return $block;
   }
}

function changeHeader() {
  $output = '';
  $output = '<img src = "' . base_path() . 'sites/all/themes/optimiza/images/imge-header.png" border = "0" />';
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load($nid);
    $path = $node->field_head_img[0]['filepath'];
    if ($path != '') {
      $output = '<img src = "' . base_path() . $path . '" border = "0" />';
    }
  }
  return $output;
}

```

# Answer
> 3 votes
In Drupal 7, instead of `hook_block()` there are more hooks:

In short, you need to split the Drupal 6 code for `hook_block()` between those hooks.

As side notes:

* Every function implemented from a module should be prefixed by the module short name
* To load the node, you should use the following code.

```
if ($node = menu_get_object()) {
  // The page is a node page.
}

```
* To access the content of a field, you should use the following code.

```
$items = field_get_items('node', $node, 'field_head_img');
$path = $items[0]['filepath'];

```
* To output an image, you should use theme('image'), or theme('image\_style'). As you are outputting a field, you should use field\_view\_field(), as in the following code.

```
$output = field_view_field('node', $node, 'field_head_img');

```

---
Tags: hooks
---


# Question
Title: How do you update the default value for a field programmatically?
How do you update the default value for a field programmatically? I know you can get the field instance info by calling field\_info\_instance, but how do you update that info?

# Answer
> 1 votes
The `field_update_instance()` function is the standard method

> Updates an instance of a field.

You can take the array returned by `field_info_instance()`, make your changes, then pass it back to `field_update_instance()` and the changes will be saved.

---
Tags: 7, entities
---


# Question
Title: Sidebar Menu like on Myspace (for each profile)
I have several content types. Bio, images, videos etc. for each user. Now i want to have sidebar menu like on Myspace profiles where the menu reacts only to user you are watching.

Is there a module for this or i should use views and how ?

# Answer
> 0 votes
You might start with the Author Pane module:

> Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.

---
Tags: 7, routes
---


# Question
Title: How to search views with exposed filters
I have a page view with exposed filters (4 checkboxes with ajax calling) which user can change.

I want to change default search, to searching only results which appears in this view.

How can I do that?

# Answer
> 2 votes
Views filter populate should help you with your issue. What you need to do is don't expose the Title, Body, and Location in the Filter Criteria of your view. Then add Populate filters and expose it and select Title, Body, and Location as your filters.

# Answer
> 0 votes
I think you want your view to display results ONLY when one of the checkboxes is checked. Am I right ?

If it's the case, in your view's Exposed Form section, you have to choose `Input required` as the Exposed form style.

# Answer
> 0 votes
Click on the *Global:Populate filters (exposed)* Under **Filter Criteria**, make sure your body and location are checked.

Also, make sure your **Operator** are set correctly. For instance, set your **Filter Criteria** to something like this:

* Content: Published (yes) AND
* Content: Type (= your content)
* AND
+ Content: Title (contains) OR
    + Content: body (contains) OR
    + Content: location (contains) OR
    + Global: Populate filters (exposed)

---
Tags: views, search
---


# Question
Title: Copy whole field from one entity to another
i want to copy a field from one entity to another while processing a rule. my current code looks like this:

```
<?php
    $entity_created->field_ort = $entity_fetched->field_ort;
?>

```

but instead i get an error message:

```
Notice: Trying to get property of non-object in eval() (Zeile 3 von /www/www/sites/all/modules/rules/modules/php.eval.inc(125) : eval()'d code).

```

so i found this site http://drupal.org/node/1000200 which tells me that i need to do this more like this:

```
<?php
    $entity_created->field_ort['und'][0]['value'] = $entity_fetched->field_ort['und'][0]['value'];
?>

```

but what about lists and other fields? is there a more generic approach? i need to copy about 5 or more fields.

# Answer
> 0 votes
That issue and the following code seems to have no bearing on the opening problem. Trying to get property of non-object, it literally means that $entity\_fetched is not an object. Dump it into a file to see what it is.

---
Tags: 7, entities, rules
---


# Question
Title: How to show the node delete tab and put a view in it?
I would like to show a '**Delete**' tab near the 'View' and 'Edit' tabs in the node page and insert a custom warning message and a view in it. If I create a view tab page with path /node/%/delete it works fine, but the submit button is missing and I can't figure out how to add it. Any idea?

# Answer
By creating a view with path /node/%/delete, you have completely replaced the existing page (the delete confirmation form). According to Drupal logic, this is normal behavior.

What I would do is:

1) Do not use the *page* display of your view, but add a *block* display to the view. Add your message as view header. Place that block above the main page content and restrict it to the node/\*/delete path.

2) Create custom module, implementing hook\_menu\_alter with one line of code (credits):

```
function MODULENAME_menu_alter(&$items) {
  $items['node/%node/delete']['context'] = MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE;
}

```

Of course you need to replace `MODULENAME` with the actual name of your module.
> 4 votes

# Answer
You can use hook\_menu\_alter to add the tab and hook\_form\_alter to add your message to the page. You can then create a view block and add the block to the content area for the node/\*/delete path. Use the following code and replace MYMODULE with your module name:

```
/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/%node/delete']['context'] = MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE;
}

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id=='node_delete_confirm'){
    drupal_set_message('my msessage');
  }
}

```
> 1 votes

---
Tags: 7, views, routes
---


# Question
Title: Drupal commerce based recommendations engine
I want a shop where experts join the shop and each expert recommends his favorite products.

* Expert's user profile will show his recommended products.
* Users can vote recommendations up and down, much like happens in amazon.
* The product's page will show the recommendations for that product.
* The expert will also be an affiliate.

Possible architecture:

* Commnets may be themed to be recommendations, together with voting stars.
* Affiliates may be added with the Post Affiliate Pro integration.

Questions:

* From your experience, what are the best modules / drupal commerce extensions to support this scenario?
* Is there another, internal affiliate solution?

Thanks

Amnon

# Answer
> 1 votes
I would not use comments to be recommendations but I would use nodes. This will give more flexibillity.

Here is a possible architecture:

I would use the flag module to let user flag (recommend) a product. On flagging, I would use hook\_flag to create a new node (content type: recommendation). This node would reference to the product. The new node would contain a body field that will contain the actual recommendation. Finally, I would attach the rate module to this node so that users will be able to vote on it.

As far as I know the flag 3.x module is now an entity, which means that you can attach fields to the flag. So, another possible architecture would be to use the flag itself for storing the recommendation. Have not tried this though but seems interesting.

---
Tags: commerce, rating
---


# Question
Title: How to change Webform field value after a webform has been submitted
I have a webform with a hidden field having a default value of No. How do I change this value to Yes after a webform has been submitted using Rule? I'm using Drupal 7.x. Thank you.

# Answer
> 6 votes
You should make a custom module, rather than using Rules.

Your module will implement the hook\_webform\_submission\_presave, as shown also in webform.api.php inside webform directory.

Your function should look like this (well, this could be your entire .module file):

```
function mymodule_webform_submission_presave($node, &$submission) {
  $component_id = 3; //that's your hidden field
  $submission->data[$component_id]['value'][0] = 'Yes';
}

```

Making a custom module is very easy, take a look here.

---
Tags: 7, webforms
---


# Question
Title: Can I have a GROUP BY as an expression? Without an alias
I want to be able to achieve the following query.

```
SELECT FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*(60)) AS datetime,
ROUND(MAX(value), 2) AS value
FROM  my_values v
WHERE (datetime > '2012-12-15 00:00:00') AND (datetime < '2013-01-01 00:00:00')
GROUP BY ROUND(UNIX_TIMESTAMP(datetime)/60)
ORDER BY datetime;

```

You'll notice that my groupby clause is dynamic, so far in Drupal I have:

```
$select = db_select('my_values', 'v')
  ->condition('datetime', '2012-12-15 00:00:00', '>')
  ->condition('datetime', '2013-01-01 00:00:00', '<')
  ->groupBy('gbdatetime')
  ->orderBy('datetime', 'DESC');
$select->addExpression('FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60)', 'datetime');
$select->addExpression('ROUND(UNIX_TIMESTAMP(datetime)/60)', 'gbdatetime');
$select->addExpression('ROUND(MAX(value), 2)', 'value');

```

This achieves the desired results, however It'd be great if I could do a `GROUP BY ROUND(UNIX_TIMESTAMP(datetime)/60)` without requiring the alias `gbdatetime`.

So, my question is can I have a `GROUP BY` as an expression?

# Answer
You could also use the following code.

```
$select = db_select('my_values', 'v')
  ->condition('datetime', '2012-12-15 00:00:00', '>')
  ->condition('datetime', '2013-01-01 00:00:00', '<')
  ->orderBy('datetime', 'DESC');
$select->addExpression('FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60)', 'datetime');
$select->addExpression('ROUND(MAX(value), 2)', 'value');
$select->groupBy('ROUND(UNIX_TIMESTAMP(datetime)/60)');

```

Using `print (string) $select`, I get the following output.

```
SELECT FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60) AS datetime, ROUND(MAX(value), 2) AS value
FROM
{my_values} v
WHERE  (datetime > :db_condition_placeholder_0) AND (datetime < :db_condition_placeholder_1)
GROUP BY ROUND(UNIX_TIMESTAMP(datetime)/60)
ORDER BY datetime DESC

```
> 1 votes

# Answer
This can be achieved like so:

```
$select = db_select('my_values', 'v')
  ->condition('datetime', '2012-12-15 00:00:00', '>')
  ->condition('datetime', '2013-01-01 00:00:00', '<')
  ->orderBy('datetime', 'DESC');
$select->addExpression('FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60)', 'datetime');
$select->addExpression('ROUND(MAX(value), 2)', 'value');

$groupBy = &$select->getGroupBy();
$groupBy['gb'] = 'ROUND(UNIX_TIMESTAMP(datetime)/60)';

$result = $select->execute();

```

Which creates this query:

```
SELECT FROM_UNIXTIME(ROUND(UNIX_TIMESTAMP(datetime)/60)*60) AS datetime,
ROUND(MAX(value), 2) AS value
FROM my_values v
WHERE (datetime > '2012-12-15 00:00:00') AND (datetime < '2013-01-01 00:00:00')
GROUP BY ROUND(UNIX_TIMESTAMP(datetime)/60)
ORDER BY datetime DESC

```
> 2 votes

# Answer
You can include any SQL expression with addExpression

> An expression can be any arbitrary string that is valid SQL. That includes various functions, which may in some cases be database-dependent. This method makes no effort to correct for database-specific functions.
>
> $alias: The alias for this expression. If not specified, one will be generated automatically in the form "expression\_#". The alias will be checked for uniqueness, so the requested alias may not be the alias that is assigned in all cases.
>
> Source: http://api.drupal.org/api/drupal/includes!database!select.inc/function/SelectQuery%3A%3AaddExpression/7
> 1 votes

---
Tags: database
---


# Question
Title: Any other ways I can stop the <front> page from being cached by boost?
My drupal 7 site has Boost module (7.1.beta1, the version previous to the current release) installed and I didn't change any settings from the stock install. I saved the settings configuration with the `<front>` exception, generated the htaccess code, added it to my root htaccess file, turned Drupal core cache for anonymous users off... Everything works, ie, pages get cached to the boost cache directory and anonymous browsing is served from the boost cache. Only problem is that the front page is being cached even when my boost setting exception using the default `<front>` should be preventing the front page from being cached. I apologize if this is a redundant thread,I searched but mostly people have the opposite problem (ie, they want the front page cached-whereas I don't). I've also cleared the cache via /performance tab after enabling it and made sure there wasn't a boost cache for the front page .

Does anyone know why the boost exception setting isn't working for the front page? Is there perhaps another way to hack boost for this one page to not be 'boosted'? Thanks.

# Answer
> 1 votes
What is the actual url of your front page? If your frontpage is the default ( /node ) then you need to add both 'node' and '' to your exceptions list. Boost treats them differently and keeps a copy of each page in the cache.

You can inspect the cache files that boost creates (these are actually plain html files) in the cache apache root folder.

---
Tags: 7, caching
---


# Question
Title: How do I reference another field properly?
In Drupal 7, how can I properly reference another field with the Computed field module?

# Answer
It's best to turn on the devel module and do a dsm() on the $entity object to see what fields are available to you. Even if you think field\_name would work, there are other arrays inside that field variable.

In the case below i am parsing a URL link from another field and exploding it via the dashes. Since my field\_sell\_link is a "link field" i had to add the \['url'\] at the end of the field reference instead of the usual \['value'\]. I didn't find this out until I did a dsm on $entity. You can also do a `set_message(print_r($entity));` too.

let me know if this helped anyone.

Example code for the PHP code section:

```
$ebay_url = isset($entity->field_sell_link['und'][0]['url']) ?
  $entity->field_sell_link['und'][0]['url'] :
  'zero/one/two/three/nothing-here-asdf/last';

if (isset($ebay_url)) {
  $url = explode('/', $ebay_url);
  $pattern = '/-/';
  $replace = ' ';
  $entity_field[0]['value'] = 'testxxx' . $url[3];
}
else {
  $entity_field[0]['value'] = "";
}

```
> 0 votes

---
Tags: 7, entities
---