# Question
Title: How to change user id from incremental integer to random hash?
By default drupal uses incremental user id but I want random 7 character hash, is there any module that can help me with that? If not what is the simplest way to achieve that?

from: user/1

to: user/5rey2t5

by the way I know how to generate the hash in php I'm looking for the best way to implement it.

# Answer
As it was already mentioned in comments, you can avoid such a harsh hack of drupal core by forbidding anyone to see the UIDs. The simplest solution that comes to my mind is module Pathauto (https://drupal.org/project/pathauto) which will easily translate all user/uid paths to whatever you want, usually user/username.

If you really require the hash, I believe it could be created as separate field when user is created (some logic would have to be implemented to avoid duplicates) and then used as token for pathauto automatic alias generation, but this approach seems rather silly to me. Let me know if you want more elaborate guidelines on that.
> 0 votes

# Answer
Just aliasing the path (as suggested by *m1n0*) will not be enough, as users allowed to see the user profile will still be able to connect a user name and profile to a numeric user ID by entering an URL ending with `user/ID` (where `ID` is an integer, e.g. `1` for user #1). This will let anyone permitted to view user profiles to view the user name and profile associated with `user/ID`.

As pointed out by *Jimajamma*, totally replacing the numeric user ID with a random hash is a major undertaking, since just doing it will break a lot of stuff hard coded in Drupal. No module exists that will do this for you. If you want to do this, you'll have to start from scratch.

What you need to do to avoid numeric user IDs from being associated with specific user names and profiles is to prevent non-privileged users from ever seeing the *user profile*.

Navigate to *Administration » People » Permission* and make sure that non-privileged user does *not* have the permission "View user profile".

After doing this, if a non-privileged user typed in an URL ending with `user/1` (or anURL with any other numeric user ID) a 403 status code (Permission denied) will be returned. Also user names that appear in bylines, etc. will no longer be linked to a profile when viewed by a non-privileged user.
> 3 votes

---
Tags: 7, users
---


# Question
Title: Where can I add core <item> elements with Views RSS
I'm trying to set up a podcast feed with Views RSS. I think I've succesfully set up the module and the core \<channel\> elements.

I am now trying to set up the core \<item\> elements, as explained here. However, I have no idea if I'm looking in the correct place.

I go to `admin/structure/views/view/gentle_podcast/edit/feed_1` and under `Format` I see:

* Format: RSS Feed | Settings
* Display: Fields | Settings

(I'm translating from Dutch, so labels may be off). When I click the Settings next to Display, I get a popup where I can set Title, Link, Description, Creator, Publication date and Guid.

How can I set all the other items that the documentation mentions?

Does it check the fields I've added to the view? Because I've added a field that has the URL of my podcast file (an mp3), but I don't see anywhere to set the \<enclosure\> item.

You can see the current result of my view here (as feed) and here (as page).

# Answer
> 1 votes
It sounds like you're missing a couple things. First, make sure that you have the Views RSS: Core Elements submodule enabled -- this is what allows you access to the many other fields. This may already be enabled and if so, the reason you're not seeing the fields is that you need to switch your format to RSS Feed - Fields, ex:

by clicking the 'RSS Feed' link in your Format Settings.

Now, when you adjust the settings for this, you'll see the options for the item elements you were looking for.

You'll need to add the appropriate fields from your content to have them appear in the select lists.

---
Tags: views, feeds
---


# Question
Title: Search API Solr fulltext search improve results
I use Search\_api\_solr module with drupal. I have a node with "Sony W800a TV" when I search w800 there is no result but when I search w800a I see this node in results.

How Can I Fix this?

Thanks

# Answer
You're looking to enable 'partial word' search which would allow for matching w800 with w800a. As described in this blog post, Apache Solr has this capacity built in, it just needs to be enabled by adding this line to the Solr Schema that comes with Search API

```
<filter class="solr.NGramFilterFactory" mingramsize="3" maxgramsize="25"/>

```

However, pay attention to their caution about performance issues - you want to only enable this capability on a limited field (ex. the title field) rather than a longtext field as it will greatly increase the size of your index and reduce performance.
> 1 votes

---
Tags: search
---


title: Core Testing vs SimpleTest

text:
# Question
Title: Core Testing vs SimpleTest
I have a query concerning the core Testing module and the SimpleTest module.

When I install a new site, the Testing module is available but disabled. When enabled, a list of tests are available for a whole range of resources such as nodes, users etc.

When I install SimpleTest these tests disappear along with the core Testing module. They are replaced by five example SimpleTests.

Could someone explain the differences between these two modules?

Also, is it possible to use these initial tests within SimpleTest?

# Answer
The simpletest module has been integrated into Drupal 7 core. Since then the contrib simpletest module has not seen much development. See also this issue.

If you want to start writing tests for your own modules, enable the core simpletest module (called Testing in the UI) and do not install the contrib module. Also check out the examples module, it should give you an idea on how to add tests for custom code.
> 2 votes

---
Tags: 7, testing
---


# Question
Title: filter fields of type date with the view module filters
I have a field in my database of type: timestamp in this format: yyyy-mm-dd hh:mm:ss , with the view module I would like to filter this field so for example I want to select an interval: dispaly only date from x to y. I taked a look in the view module code and there is a date filter that handel data of type date or time in this format, but when I tired to create a new view with view module and set up this kind of filter I didnt found it in the exposed filter list, the availble filters works only with int or string type: like is equal to, starts with...so how to get the time filter from the view module user interface.

# Answer
You need to enable the **Date Views** module (part of the Date project) to be able to filter using interval operators such as "Is between":

Take a look at the upvoted answer to this question for details: How do I add a date field that can be filtered by a relative value?
> 0 votes

---
Tags: views
---


# Question
Title: How to set discount only in some line item's price added to cart?
I need to achieve a discount on a Drupal site with Commerce through rules.

**Event** :
When you have to decide a product price \[ Calculating the sell price of a product \]

**Conditions** :
If the logged user have role 'role to trigger'
and there are at least 2 products in the cart with product\_type = 'magazine' and field\_mag\_type == 'tipo'

**Action** :
Take the products with field\_mag\_type == 'tipo' in the cart and discount it by 15% \[amount * 0.75\]

Can someone did something like this and want to help me?

For now I have this rule

```
{ "rules_sconto_riviste_multiple" : {
    "LABEL" : "Sconto riviste multiple",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [
      "rules",
      "commerce_cart",
      "commerce_order",
      "commerce_line_item",
      "commerce_product_reference"
    ],
    "ON" : [ "commerce_product_calculate_sell_price" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "6" : "6" } },
          "operation" : "OR"
        }
      },
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
      { "component_rules_product_is_magazine" : { "product" : [ "commerce-line-item:commerce-product" ] } },
      { "commerce_order_is_cart" : { "commerce_order" : [ "site:current-cart-order" ] } },
      { "commerce_order_contains_product_type" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "product_type" : { "value" : { "magazine" : "magazine" } },
          "operator" : "\u003E=",
          "value" : "2"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_multiply" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : ".75",
          "component_name" : "discount",
          "round_mode" : "1"
        }
      }
    ]
  }
}

```

This rule work fine but the field\_mag\_type == 'tipo' check is missing because I don't know how to check a field in all products in the cart and count if they are \> 2.

If I can't solve this I'm bound to clone the 'magazine' product type and add a new one with the same fields.. but I want to avoid it..

# Answer
> 1 votes
You should use the *Calculating the sell price of a product* event instead of the add to cart event.

The use case you are trying to implement is actually discussed in the commerce users guide. If you fail to make your rule work after going through the documentation, then please update your question with the exported rule.

---
Tags: commerce, rules
---


# Question
Title: How do I use drupal_mail() without the $to value?
I'm trying to send same email to several users at once. They should not see each other's email addresses, so I add them as `Bcc` in the header.

However, the problem is that Drupal seems to require the `$to` parameter passed to `drupal_mail()` function. I tried passing both `NULL` and an empty string but without success. System would return the `Unable to send e-mail.` message.

I don't want to use some random email address instead and I want to avoid new modules.

How can I send an email just with BCC recipients?

# Answer
You do this by putting the string `'undisclosed-recipients:;'` (notice the colon and semicolon at the end) is the `$to` parameter you pass to the `drupal_mail` function. E.g.:

```
drupal_mail('mymodule', 'send', 'undisclosed-recipients:;', $language, $params);

```

You can now add the list of bcc-recipients to the header.
> 4 votes

---
Tags: 7, emails
---


# Question
Title: create a datetime field with data module
I have installed the data module in order to create some data tables, but I have noticed that there is no datetime type given in the user interface, so how can I add some datatime fields to my data tables with the use od data module?

# Answer
To get date and time data types in the Drupal that can be used in fields, etc., install the Date module in addition to the Data module.
> 1 votes

# Answer
If everything else fails, as a dirty workaround, you can set the date field to be a varchar, with the exact date/time format you want. It is not the best solution ever, but seemed to be working properly in a project I did while ago. I couldn't run Date field as well and as far as I remember, there was a reported bug, leading towards the "Schema" module.
> 0 votes

---
Tags: datetime
---


title: Mass delete Drupal Commerce Coupons

text:
# Question
Title: Mass delete Drupal Commerce Coupons
I have used Drupal Commerce Kickstart 2 + Commerce Coupons (fixed, %) + Coupons Batch create to create coupons. Now, is there any way to remove all coupons?

# Answer
The code below should do the trick. If you have Devel installed, just open the `devel/php` page and execute this:

```
// Get all coupons on the site.
$coupons = db_select('commerce_coupon', 'c')
  ->fields('c', array('coupon_id'))
  ->execute();

// We will store here all coupon IDs, so we can delete them at once.
$coupon_ids = array();
foreach ($coupons as $coupon) {
  $coupon_ids[] = $coupon->coupon_id;
}

commerce_coupon_delete_multiple($coupon_ids);

```
> 3 votes

# Answer
Alternatively, you can use Views Bulk Operations to create a listing in Views and delete from the UI if you need to perform this operation often
> 2 votes

---
Tags: commerce
---


# Question
Title: hook_commerce_shipping_service_info() rate callback: What does the 'data' array do?
hook\_commerce\_shipping\_service\_info() allows to specify a rate callback.

```
function snailmail_commerce_shipping_service_info() {
  [..]
  $shipping_services['snailmail']['callbacks']['rate'] = '_snailmail_rate';
  return $shipping_services;
}

function _snailmail_rate($shipping_service, $order) {
  return array(
    // Amount in EUR Cent
    'amount' => 250,
    'currency_code' => 'EUR',
    // What is this?
    'data' => array(),
  );
}

```

Question: What can I do with the 'data' array in the return value?

# Answer
Prices in commerce have a data array to establish the original components and component modifiers that these might have. For example, discounts and taxes add components to alter a price after taxes.

I'd say you can use 'data' array as storage of context information like the line items do (they store the product display where the product has been added to the cart) and the price system stores the components there, so it's needed to add elements to it.

Check commerce\_price\_component\_add and commerce\_tax\_rate\_calculate for examples on where this is used.
> 1 votes

---
Tags: commerce
---


# Question
Title: Theme multiple rendered nodes as item_list
I am retrieving/rendering multiple nodes successfully with the following code:

```
$nodes = node_load_multiple($nids);

$rendered_nodes = node_view_multiple($nodes, 'custom_view_mode');

return render($rendered_nodes);

```

I would like these nodes to be rendered as an item list. I have attempted to set the #theme property of the array to 'item\_list' but it does not seem to be working. What is the correct way to theme this array of nodes returned by node\_view\_multiple()?

# Answer
> 4 votes
This should render multiple nodes using an item list.

```
$nodes = node_load_multiple($nids);
$build = array(
    '#theme' => 'item_list',
    '#items' => array_filter(reset(node_view_multiple($nodes)), function(&$node) {
        if (!is_array($node)) {
            return false;
        }

        $node = drupal_render($node);
        return true;
    }),
);

return drupal_render($build);

```

---
Tags: 7, theming
---


# Question
Title: Unusual behavior of Shopping Cart (Drupal Commerce)
I am using Drupal Commerce for a portal & I am facing a issue which is re-producible on fresh instance as well.

Suppose if I have a account on a website and I am logged in. I add some items to my cart and leave. It will remain in my cart even if I login from another system.

But if I don't login from another system at start & click "Add to Cart", item get added to my cart with help of session. Now if I login into system, only current items are in cart, not which I have added from another system in my account.

I mean, we loose those items which were in cart before.

This behaviour I checked on some other ecommerce website as well, but they add session cart into the account cart once you login.

What can be the solution of this ?

# Answer
> 1 votes
What you describe is the default behavior in Drupal Commerce, as it is supporting the idea of "multiple carts", so when you log in you get the items that you've got in your current cart and the other cart will be kept in the "background".

In fact, if you end the purchase you have once logged in, you'll most probably see that the items you had in the cart in the first place are back in there.

I'm afraid this is something you can't solve without some coding or rules, the theory here is that on the user login event, you get all the past orders from that user and combine them in the current cart of the user. This is not something you normally want as the cart pulled might be old.

# Answer
> 0 votes
According to me the best solution would be to automatically logout or close the session after pre-defined period of time. For that the 2 modules which can be used are as follows:

Session Limit

> Session Limit allows administrators to limit the number of simultaneous sessions per user.
>
> Max session is configurable, no database tables needed.
>
> By default, a session is created for each browser that a user uses to log in. This module will force the user to log out any extra sessions after they exceed the administrator-defined maximum.
>
> Assuming the session limit is 1, if a user is logged in to a Drupal site from their work computer and they log in from their home computer, they would be forced to either log off the work computer session, or abort their new login from home.

Automated logout

> This module provides a site administrator the ability to log users out after a specified time of inactivity. It is highly customizable and includes "site policies" by role to enforce logout.
>
> Features Different timeouts based on role Disabling of timeouts based on role Permission for users to set their own timeout Includes some JS mechanisms to keep uses logged in even if multiple tabs are open or if the user is working on a form for a long period of time. Includes developer hooks to allow users to remain logged in depending on your own project specific requirements Optional integration with Javascript Timer

---
Tags: 7, commerce, sessions
---


# Question
Title: Send personalized email to a particular role
I want to send a PERSONALIZED email to all users of a particular role on my site starting with for example: Hello \[first\_name\] \[surname\],

I have tried using the Rules module but was not successful.

Please is there a way to use Rules module to achieve this or is there another way?

Thanks in anticipation.

# Answer
> 1 votes
Try using the views\_send module instead. This powerful module acts like views\_bulk\_operations in that it lets you create a view to execute an action using Drupal's batch API for processing. For your case (roughly following the directions on the project page):

1. Create a view of users and add the user email field to the list
2. Add the field 'Global: Send e-mail' to activate the Views Send functionality
3. Add any other fields that you want to include in your customized email as fields in the view (ex. User: First Name, User: Last Name)
4. Finally, add a filter to filter by the particular role(s) you want to filter on.
5. You probably also want to secure the views permissions so non-authorized users can't use the view to send to your users.

If that's all setup then when you visit your page, you will see a list of all users in that role with the option to send an email to them. When you select your users and are ready to send your email, you will then see on the next page the option to use any of the fields you've selected above as tokens in your email (thus the customizable option):

---
Tags: views, rules
---


# Question
Title: How would I make a search view display results in a new page instead of on the same page?
I have view (a block) that searches my products for various fields such as sell price, title, ect. It works except all the search results appear right in that block instead of on a new page. Here is an example of what I want to do: http://www.themesdojo.com/drupads/

# Answer
> 1 votes
You can show your exposed views filter as a block, and place the block on your search page, then all submissions will show results on your view page.

Under the advanced field-set in the views UI, once you have created an exposed filter, an option will appear under the EXPOSED FORM heading that will allow you to create a block.

You can see an example of a front page search leading to a views results page here... http://www.myweddingfayre.com

---
Tags: views, search
---


# Question
Title: Advice Needed on Associating Articles by user with Nodes
I am building a national site, with 30 locations. Each locations page is built from a single content type, "venue".

For each location, the manager is given their own login details so they can keep their venue page up to date.

They will also be able to create an Article whenever they have news. All Articles will display a teaser on the main national page, but It should also appear on that managers location page, but not all of the others.

I am after some advice on how to make this happen with views. Obviously I wouldn't want to create a separate view for every location page and only display results by author.

Ideally there would be one view that I could display in a block on every venue page. It would need to get the related author information (maybe from a CCK field), and then display the article results of the owner of that venue. But how do I connect a node to a user, that a view can read?

Hope that makes sense, I'll try and explain it better if you need me to!

# Answer
> 3 votes
This is rather straightforward in Views 3.x - you just want to create a relationship based on the field that you are using to associate the content. This could be something as simple as an author but for your case it sounds like you are going to have multiple types of content that relates back to a venue, ex. articles, etc.

So you would want to use a module like entity\_reference and create a field of type entity reference, perhaps named "Related to Venue", that connects to your venue content type. Then add this field to whatever content types you have and when a user adds a new node (ex. an article) they could relate that back to the appropriate venue.

Now in your view block for the venue page, you just need to create a relationship using this field and then add a contextual filter that will find the appropriate node id from the venue page. This is a bit tricky but this is a very common task and this handbook page on d.o walks you through the basics.

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


title: Region not displaying in module

text:
# Question
Title: Region not displaying in module
I'm working on a site where much of the back-end is handled by a site-specific custom module.

I have a sidebar region and within

Within module-thing.php is a call to `<?php print render($page['sidebar']); ?>` to print a region but it is not showing anything despite the region being set with content within the Blocks administration. I'm wondering if this is expected to work from within a module.. is there something i can do to show it?

I found this (right at the top) but doesn't seem to work in drupal 7 http://www.chrischen.me/content/drupal-how-access-regions-blocks-themes-or-modules..

# Answer
The code to print page regions must be in your theme's page.tpl.php file, not in a file in a custom module.

If you want to put your code in a separate file (sidebar.php) you need to make sure it's included in page.tpl.php, like

```
include './sidebar.php'; // file is in the same folder as page.tpl.php

```

or

```
module_load_include('php', 'MYMODULE', 'sidebar'); // file is in a module folder

```

hope it helps
> 1 votes

# Answer
I found the easiest way was to do this:

```
<?php
  $region = block_get_blocks_by_region('region_name_here');
  print render($region);
?>

```

See the docs for more information: https://api.drupal.org/api/drupal/modules!block!block.module/function/block\_get\_blocks\_by\_region/7

In your module where you tried to print the sidebar region using the method used in a page template, use this snippet above instead. This method can also be used in html.tpl.php where the "usual" method cannot.
> 0 votes

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


# Question
Title: Mobile_detect php redirecting to subdomain - Stuck in a redirect loop!
I am using the following code in a module for redirection to a subdomain whenever a mobile is detected;

```
<?php

  function mobydetect_init() {
  include("PATH/TO/Mobile_Detect.php");

  $detect = new Mobile_Detect();
  if ($detect->isMobile()) {
    header('Location: http://m.mysite.com');
    drupal_exit();
  }
}

```

However when I go to my site using a mobile I get this error message;

"This web page has a redirect loop."

I have disabled to subdomain from redirecting to the main domain in Aegir. So where's the loop coming from?

# Answer
Presumably your `hook_init` runs on both domains.

You need to check you're not already on the redirected page prior to redirection.

e.g

```
/**
 * Implements hook_init
 */
function mobydetect_init() {
  if($_SERVER['HTTP_HOST'] != 'm.mysite.com'){
    include("PATH/TO/Mobile_Detect.php");
    $detect = new Mobile_Detect();
    if ($detect->isMobile()) {
      drupal_goto('http://m.mysite.com', array('absolute' => TRUE, 'external' => TRUE));
    }
  }
}

```

Note, `hook_init` doesn't run on cached pages so you may find mobile users aren't redirected on cached pages. You could try using `hook_boot` instead or else offload to the webserver conf.
> 2 votes

---
Tags: redirection, theming
---


# Question
Title: How to obtain raw View result for Drupal 5?
How do I get a raw result from a view similar to this $view-\>result for Drupal 5 ? I would like to get results from the database and run calculations before displaying to the user. I really need to gain access to the the raw data before it's themed by the Drupal engine.

# Answer
> 0 votes
I think the answer is in here somewhere but I have no way to test it out.

Check out Intro to Views 1 and especially Inserting Views where the views\_build\_view() function is discussed. From the discussion there, you should be able to do something like this:

```
$view = views_get_view('your_view');
$results = views_build_view('items', $view);

```

with `$results` now being "An array of objects containing the results of the query."

Now how you theme this is up to you to decipher :)

---
Tags: views, 5
---


# Question
Title: Admins that only control a subset of users
I am creating a page where users pay to create and edit their custom content.

These clients need to use multiple accounts with certain edit-rights - so they need their own people-management.

These are my requirements in that respect:

* Each client-admin belongs to an organization that can have multiple members
* Each organizatin "owns" certain content
* Each client-user can edit content of his organization but only if the client-admin has granted him these rights

Is there a way that I can create admins that only control a subset of users?

(I found the https://drupal.org/project/administerusersbyrole module, but with that I would need a new role for each client. Is that a good solution? )

# Answer
It looks like you're looking for Organic Groups.

> \[Organic Groups\] Enable users to create and manage their own 'groups'. Each group can have subscribers, and maintains a group home page where subscribers communicate amongst themselves.
>
> They do so by posting the usual node types: blog, story, page, etc. A block is shown on the group home page which facilitates these posts. The block also provides summary information about the group.
>
> Groups may be selective or not. Selective groups require approval in order to become a member, or even invitation -only groups. There are lots of preferences to configure groups as you need.

It is a fairly complex module, but I think it is very well suited for your use-case.
> 1 votes

---
Tags: users
---


# Question
Title: How can I restrict that only sender and receiver can download the attached file with the private message?
I am using drupal 7. I created a new file field in private messages for attachments and I want that only sender and receiver should be able to download the file attachment.

I apologize if this question is duplicate but I didn't find the answer for this.

EDIT: Just one addition. I am using Custom Field permissions module as well. And authenticated users are unable to see the attachment until "View anyone's value for field" is enabled for them.

# Answer
> 1 votes
Your question is fully answered here http://drupal.org/documentation/modules/file

Please read sections:

* Managing file locations and access
* Accessing Private Files

> You can also specify whether files are stored in a public directory or in a private file storage area. Files in the public directory can be accessed directly through the web server; when public files are listed, direct links to the files are used and anyone who knows a file's URL can download the file. Files in the private directory are not accessible directly through the web server; when private files are listed, the links are Drupal path requests. This adds to server load and download time, since Drupal must resolve the path for each file download request, but allows for access restrictions.

# Answer
> 1 votes
File attachements in a private file storage area can only be viewed by the person that has view permission granted to *node* the private file is attached to. Even if the URL of a private file attachment is known, access will be denied if the person trying to access the file is not granted the permission to access the node the file is attached to.

To control access to nodes with files attached, you can write a custom module that use the API of the ACL module to automatically create an access control list for a the node with the file attachment, consisting of only the sender and receiver of the email, when a file attachment is created or sent.

To test out the concept without having to create a custom module interfacing the ACL API, you can use the Flexi Access module. It has a GUI that lets you maintain ACLs to any node.

---
Tags: 7, files, privatemsg
---


# Question
Title: Why can't I edit Views in Drupal 6 since moving the site?
I moved a Drup-al 6 site from one hosting server to another, exporting and re-importing the DB. Everything works well but for some reason I can't edit anything in the views. Each time it says page not found which is really odd. Has something happened with paths?

I've tried rebuilding menu structures and cleared all caches etc.

Thanks :)

# Answer
I think something went wrong with SQL queries when importing the DB. Can you check if views\_display and views\_object\_cache tables are consistent?

I would try to export each view using the Export function from the old site and then import those in the new site.
> 0 votes

# Answer
In my case it was the Jquery version for the administration pages, change it to version number 1.7 instead of 1.9 and it will work.
> 0 votes

---
Tags: views, 6, nodes
---


# Question
Title: hook_form_alter not running if cache enabled
I have enabled the cache in Administer-\>Development-\>Performance. I have changed user profile form using `hook_form_alter`. But the code inside `hook_form_alter` strops automatically after few days. I thinks, it may be cache issue.

Everything I did in hook\_form\_alter is not running. I changed the submit button value. I added a custom Save and Continue button.

My Sample Code is below :

```
if($form_id == "user_profile_form" && $user->uid == 1) {
    $userid = arg(1);
    if(is_numeric($userid)) {
      drupal_set_message("Current User Id on site: ".$userid);
    }
   }

```

Attached screenshot :

# Answer
I solved it by changing `hook_form_alter` to `hook_form_form-id_alter`.
> 1 votes

# Answer
Messages set by `drupal_set_message()` goes thorough message router and may end up displayed on another page than the one you set them. If you want to add informative element to your form, use *markup* Form API element instead.

```
if($form_id == "user_profile_form" && $user->uid == 1) {
  $userid = arg(1);
  if(is_numeric($userid)) {
    $form['info'] = array(
      '#markup' => t("Current User Id on site: !uid", array('!uid' => $userid)),
      '#weight' => -9999,
    );
  }
}

```
> 1 votes

---
Tags: 7, forms
---


title: Views Filter: Has referencing entities

text:
# Question
Title: Views Filter: Has referencing entities
**I'm using the Views and Entity reference modules in Drupal 7**. I'm trying to do the following: Make a view to list nodes of type A (teasers) Expose filters to filter this list

I have other nodes (type B) that reference A nodes. **I would like to add an exposed filter in the form of "Has referring nodes"** (of type B implicitly).

**My problem** is that the only way I am able to do it is by using operators like "greater than" and I don't find a "has" operator. I can implement it as "greater than 0" and it works but it looks really ugly because the user has a text field to put the 0. **I would like to have a checkbox that toggles on/off a filter that works like "greater than a fixed value" or an actual "has" filter.**

I think the question it is Views related but Ive mentioned the Entity relation just in case its important for the problem.

Thanks for your help.

PD: I have just thought that a "is referred" filter will also work, so thats a third possible solution I'm looking for.

# Answer
> 0 votes
If you are willing to have an extra field, consider using Corresponding Entity Reference.

> It syncs the entity reference between two entity types which have an entity reference to each other, so double editing entities is no longer needed. If one entity has a reference, the other entity also receives a reference to the saved entity if it is referenced in that entity.

So basically, if properly configured, it will give you "is referred by" field you mentioned in your last paragraph.

For Drupal 6, use Corresponding node references module.

---
Tags: views, entities
---


# Question
Title: Why Calling the theme path in a multinlingual site adds a language prefix?
In my template whenever I call the path to my theme in a particular language it adds a language suffix dir like **mysite.com/fr/sites/all/themes/mytheme** while I'm expecting a path without a prefix (e.g. **mysite.com/sites/all/themes/mytheme**).

I'm use `drupal_get_path()` or `path_to_theme()`.

How can I ensure I get the right path in my template?

# Answer
> -1 votes
You can use base\_path() and drupal\_get\_path('theme', 'yourthemename') functions to get correct path.

Example:

```
$output = base_path() . drupal_get_path('theme', 'yourthemename');

```

Result:

```
/sites/all/themes/yourthemename

```

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


# Question
Title: How can I make sure all my table fields can be added in Views?
I have a custom entity. Some of the fields are available to be added from `Structure` `>` `Views`, but some are not available. I already tried adding `default` properties under `hook_schema`, but to no avail. The one particular field I would like to add is of `datetime` type.

The particular field I would like to be available from Views is this:

```
'some_datetime_field' => array(
  'description' => 'some description',
  'type' => 'datetime',
  'mysql_type' => 'datetime',
  'not null' => TRUE,
  'default' => format_date(time(), 'custom', 'Y-m-d 00:00:00')
),

```

Is there some criteria or some sort of guidelines to follow to ensure all the fields of a given entity can be added from Views?

**Update:**

so I thought I had it figured out. It turns out the field is available for adding in Views but column shows empty values.

Here's the code snippet from `hook_views_data_alter`:

```
function my_module_views_data_alter(&$data) {
  $data['my_module_table']['some_datetime_field'] = array(
    'title' => t('Timestamp field'),
'help' => t('Just a timestamp field.'),
'field' => array(
  'handler' => 'views_handler_field_date',
  'click sortable' => TRUE,
),
'sort' => array(
  'handler' => 'views_handler_sort_date',
),
'filter' => array(
  'handler' => 'views_handler_filter_date',
),
  );
}

```

What else am I missing?

# Answer
> 1 votes
To inform Views about your custom entity's properties, you need to implement `hook_views_data()`.

> Describes data tables (or the equivalent) to Views.

Fields are taken care of automatically, so it's just the properties you need to define in your implementation. The documentation page has an abundance of examples so I won't reproduce any code here.

---
Tags: views
---


# Question
Title: node has term - show all parents of this term
A node has a taxonomy term. My aim is to show a view on node page, that displays all parents of this taxonomy term and the term as well. Is it possible to acomplish in views? I use views 3 and drupal 7. Thank you.

# Answer
Although you're looking for a Views solution, if you were to do it custom, e.g with hook\_block\_info you could use taxonomy\_get\_parents

Just mentioning in case others looking for that.
> 1 votes

# Answer
You may want to look at Hierarchical Term Formatter also Hierarchical Select has some formatters for it.
> 0 votes

# Answer
Yes, it is, but my approach requires some PHP knowledge. First, you need to install Views PHP module. Then in view defintion you need to add "Global:PHP" field and in that field you enter in Output code text something like:

```
<?php
$parents = taxonomy_get_parents_all($data->field_having_term[0]['raw']['tid']);
// now $parents contains array of all parents' objects
// you can check that with dpm($parents); if you have devel module enabled

// if you'd like to print all parents' names, you can for instance
$parents_names = array();
foreach ($parents as $parent) {
    $parents_names[] = $parent->name;
}

print implode(", ", $parents_names);

?>

```

A few remarks: $data is your content and field\_having\_term is machine name of field referencing the therm. I guess there are better ways of solving this, but this one is currently working of me in Drupal 7. If someone has a better approach, comment please.
> 0 votes

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


# Question
Title: Using a drush alias with Elysia Cron - alias permission missing
**Problem**

I'm trying to run Elysia Cron with Drush. When I use the command `drush elysia-cron` in the correct folder it runs.

However when I use an alias it doesn't work: `drush @main elysia-cron`.

The alias works correctly. And after a bit of digging I found the following lines in debug:

```
"error":"DRUPAL_USER_LOGIN_FAILED"},
{"type":"error","message":"The drush command 'elysia-cron' could not be executed.",
"timestamp":1385993042.4437,"memory":60455120,"error":"DRUSH_COMMAND_NOT_EXECUTABLE"}]

```

Apparently when I use an alias it loses login permission.

The only user related function for Drush I could find is remote user, but I think that's only for running drush remotely through SSH. How can I give my alias login permission?

# Answer
> 0 votes
You could try `drush @main --user=1 elysia-cron` to force the active user to be the site admin when elysia-cron runs; however, all of the cron methods should be API calls, and therefore should not care who the active user is. Note also that the error message that you quote above simply means that part of the Drupal bootstrap is failing for you; this is not a permissions issue (because Drush does not need permission to log on as a user -- it just does it), but is indicative of some other problem.

Run `drush status` with your cwd set to your site, and run it again vi `drush @main status` from a different working directory, and compare the output, esp. vis-a-vis the `Site URI` line. Also run in --debug mode both times, and look for any other differences in the output. If you have set root and uri in your alias, it pretty much should run the same both ways.

---
Tags: 7, drush
---


# Question
Title: Add JS to specific pages AFTER all other JS
I am working with JSON to theme Google Maps in the api v3.

I have my custom JSON script as an external JS file, and I am currently referencing it in html.tpl.php after the other scripts are loaded. This works great, and maps are themed, but on any pages that don't have a GMAP on them, i get the following error in Dev Tools...

> "Uncaught TypeError: Cannot call method 'addHandler' of undefined"

So I am trying to add the JS file to just the pages that have a GMAP, in template.php I use the following under the MY\_THEME\_preprocess\_page function.

> if (isset($vars\['node'\]) && $vars\['node'\]-\>type == 'venue') { drupal\_add\_js(drupal\_get\_path('theme', 'MY\_THEME') . '/js/mapstyle.js'); }

This loads the JS for all pages that are of the content type "Venue". The problem I am having is that the JS file is loading BEFORE the gmap scripts, and the style is not being rendered.

How do i get a JS file to load after all of the other scripts? I also need to load the JS file on a views page mysite.com/venues , but as a views page doesnt have a "node/id" alias, I am struggling to figure out how to only load the JS on that page using template.php

# Answer
Using the following in my template.php file for my theme, I achieved what I wanted to do.

```
function MY_THEME_preprocess_page(&$vars) {
  if (isset($vars['node']) && $vars['node']->type == 'venue') {
    drupal_add_js(drupal_get_path('theme', 'MY_THEME') . '/js/mapstyle.js',
    array('weight' => 15));
  }
}

```

I couldn't add the JS to my .info file as it would add to all pages, so I used the drupal\_add\_js fallback in template.php, and the now the error no longer shows on a page that doesn't have a GMAP on it.
> 2 votes

---
Tags: 7, theming, javascript, google-maps
---


title: Add captcha to registration form

text:
# Question
Title: Add captcha to registration form
I'm quite familiar with PHP but do not a clue of Drupal. All I have to do is to add a captcha to the registration form. How do I do this and btw. where is this registration form module located.

I know that this a beginner's question, but nevertheless any help would be appreciated. :)

Cheers

Chris

# Answer
You can use CAPTCHA module. To add captcha in in drupal registration form there is no need to edit any single line of code. First you download and install the module then go to module settings page (**/admin/user/captcha/captcha/settings**) and enable the captcha for user registration form.
> 3 votes

# Answer
You could use the Captcha Module for this.

> A CAPTCHA is a challenge-response test most often placed within web forms to determine whether the user is human. The purpose of CAPTCHA is to block form submissions by spambots, which are automated scripts that post spam content everywhere they can. The CAPTCHA module provides this feature to virtually any user facing web form on a Drupal site.

For more configuration detail of the module go through the READMe.txt.
> 2 votes

---
Tags: users, captcha
---


# Question
Title: Restrict user profiles access with hook_menu_alter
Following this tutorial I'm trying to restrict viewable user pages (and other tabs created in views). In particular, users belonging to role coordinator need to view and edit only pages of users associated with them via en entity reference field in core profile, and see an access denied page for others. I've already queried the db to get all the users id associated with current user and put it in a session var $\_SESSION\["arUidCoordinated"\] that I use in other hooks, but I can't make it work with hook\_menu\_alter. Here's the code:

```
function mymodule_perm() {
  return array('my permission');
}

function mymodule_menu_alter(&$items) {

    $items['user/%user_category'] = array(
        'title' => 'Edit',
        'page callback' => 'user_edit',
        'page arguments' => array(1),
        'access callback' => 'my_module_validate',
        'access arguments' => array(1),
        'type' => MENU_LOCAL_TASK,
        'load arguments' => array('%map', '%index'),
        'file' => 'user.pages.inc',
      );

}

function mymodule_validate($account){

    global $user;

    $uid=arg(1);
    if (in_array("coordinator", $user->roles) AND in_array($uid, $_SESSION["arUidCoordinated"])){

        return true;

    } else {

     return false;

    }

}

```

I followed this post toot, but I can't make it work, I get "access denied" on every user/% page, or failed opening required user.pages.inc and I don't understand where I go wrong...

# Answer
All the pieces of the original user menu items are defined in `modules/user/user.module` via the User Module's `hook_menu()`. The key ones here are (IMHO) `user/%user` for viewing the user page, and `user/%user/edit` for editing it, eg pages like `user/1` to look at uid 1's user page, and `user/1/edit` to edit that same page.

So, from a logic standpoint, I am going to assume you want this:

> If a user wants to look at or edit his or her own page, allow them to do so. Furthermore, if another user has appropriate permissions, allow them to look at and/or edit these pages as well. But no one else should be able to look at any other user's pages (let alone edit them).

Ok, so how can we do this. Let's first look at the original view the user page menu item:

```
$items['user/%user'] = array(
  'title' => 'My account',
  'title callback' => 'user_page_title',
  'title arguments' => array(1),
  'page callback' => 'user_view_page',
  'page arguments' => array(1),
  'access callback' => 'user_view_access',
  'access arguments' => array(1),
  // By assigning a different menu name, this item (and all registered child
  // paths) are no longer considered as children of 'user'. When accessing the
  // user account pages, the preferred menu link that is used to build the
  // active trail (breadcrumb) will be found in this menu (unless there is
  // more specific link), so the link to 'user' will not be in the breadcrumb.
  'menu_name' => 'navigation',
);

```

Here we would want to change the `'access callback'` to include further logic, so the menu alter would only have to change that, nothing else, eg, something along the lines of this:

```
function YOURMODULE_menu_alter(&$items) {

  $items['user/%user']['access callback']='YOURMODULE_user_access';

}

```

and then you could write something like this:

```
function YOURMODULE_user_access($account) {

  if ($account->uid) { // so we don't try to look at an anonymous user

    $account = user_load($account->uid); // load the full user object (ADDITION:  was user_load($uid) in original post, oops)

    if ($GLOBALS['user']->uid == 1) { // admin super user
      return TRUE;
    }

    if ($GLOBALS['user']->uid == $account->uid) {
      return TRUE; // same user so allow (we will assume blocked users aren't logged in)
    }

    if ( /* whatever logic you need to allow coordinators to access the user is TRUE */ ) {
      return TRUE; // or return $account->status; if you want to take blocked accounts into effect
    }

  }

  return FALSE;

}

```

So, barring any brain freezes or typos on my part, the above should work for viewing, but I did just type it in freehand, so buyer beware. But, now, let's look at the original user edit menu item:

```
$items['user/%user/edit'] = array(
  'title' => 'Edit',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('user_profile_form', 1),
  'access callback' => 'user_edit_access',
  'access arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
  'file' => 'user.pages.inc',
);

```

And once again, all you want or need to do is change the `'access callback'`, eg, your `hook_menu_alter()` is now...

```
function YOURMODULE_menu_alter(&$items) {

  $items['user/%user']['access callback']='YOURMODULE_user_access';
  $items['user/%user/edit']['access callback']='YOURMODULE_user_access';

}

```

and yes, since the logic is the same, you can use the same function all over again.

Caveats: We are totally ignoring Drupal's built in permissions, eg, `user_access('access user profiles')` and `user_access('administer users')` in the above.

Also, if you find after doing this you can't load `user.pages.inc`, Drupal is most probably looking for it in your module's directory instead of the user module's where it sits, so set `'file' => drupal_get_path('module', 'user') . '/user.pages.inc'` and you should be set.

Anyways hope this stream of consciousness helps out!
> 3 votes

---
Tags: users
---


# Question
Title: how access $content array inside a block php?
I have created a block and the format of it's content is PHP CODE.

this block is available only full page of node type article.

now in my block , I want to access $content or $page array.

I used global operation such as

```
global $content;
dpm ($content);

```

or

```
global $page;
dpm($page);

```

But both of these blocks return no result.

Please guide me.

Thanks a lot.

# Answer
If you need to extract the comment of a node and put it in a block you can achieve this with a view.

Create a new view who show 'Comments' and create a block. Now you can add a contexual filter:

Comment: Nid The node ID to which the comment is a reply to.

After that select 'Provide default value' and 'Content ID from URL'

Now you can add a 'Validation criteria' and select 'Content' and check only the content type you want with this block. now set 'Action to take if filter value does not validate' to 'Hide view'

Now you can add this block to a region in the block page and you have the node's comment displayed in a block.

Let me know if this will work for you ^^
> 1 votes

---
Tags: nodes
---


title: Flexslider LI styles randomly applied

text:
# Question
Title: Flexslider LI styles randomly applied
I've got a css issue that I can't get my head around, and could really use some help.

I'm trying to style flexslider on a drupal 7 installation and some but not all of my list styles are being applied to the images, then it seems like the application is random.

In the flex slider on the bottom of this page:http://www.multibrand.visionmix.us/for-her-all

each LI item has a border but each li is also supposed to have a inset shadow applied to it. Some LIs do but most don't, and I can't figure out why.

I'm using:

Flexslider 7.x-2.0-alpha3

jQuery Update 7.x-2.3+6-dev set to 1.8

Drupal 7.23

Any ideas would be very welcome

# Answer
> 0 votes
I've got it sorted out. The images in the LIs were too bug and covering over the effect. Once I resized the images everything was fine.

---
Tags: 7, theming, javascript
---


# Question
Title: How to update header text in hook_views_pre_render
I have a view with a header of type "Global: Unfiltered text" that contains the string "Number of drivers: ".

In hook\_views\_pre\_render I count the total number of drivers in each row, and now I want to append this number to the string in my view header.

I did a print\_r on the $view object in hook\_views\_pre\_render and found 59 instances of that string.

If it was only a few I would just try replacing each one until it had the desired result - but 59?!?! Too much recursion...

So how do I find which value to update in order to update the text in my view header?

# Answer
> 4 votes
Well the important thing is to narrow down the particular view `display` you want to affect. Then you can look at the header text later. I have the following similiar code ... you should be able to use views\_pre\_render fine, I don't use that here:

```
function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'migration_audits') {
    $drupal_nids = array();
    if (count($view->result)) {
      foreach ($view->result as $i => $node) {
        $drupal_nids []= $node->nid;
      }
    }
   $sql = " ... ";
   $result = db_query($sql, array(':drupal_nids' => $drupal_nids));
    $output = '';
    foreach ($result as $course) {
      #dpm($course);
      $title = html_entity_decode($course->course_title, ENT_COMPAT, 'UTF-8');
      $instructors = html_entity_decode($course->instructor, ENT_COMPAT, 'UTF-8');
      $output .= "<div class=\"entry\">$course->quarter $course->year - $title Instructors: $instructors</div>";
    }

    $my_values = "<style type=\"text/css\">div.legacy_values { background-color: pink;} div.legacy_values div.entry { padding-bottom: 5px; }</style><div class=\"legacy_values\">$output</div>";
    $view->display['page']->handler->handlers['header']['area_1']->options['content'] = $my_values;
    $view->display['page']->handler->handlers['header']['area_1']->options['empty'] = 0;
  }
}

```

You can also do like `$view->display[$view->current_display]` usually as a safe none hard coded approach. Note that the global header regions are given names such as `area_1`, `area_2` etc as a convention by Views. I also tell Views the area is now not empty.

---
Tags: hooks, views
---


# Question
Title: Taxonomy: allow "All values" choice, visible as "All values" in results
I'm looking for an "All values" choice in a taxonomy vocabulary.
It is about mobility regions, and some "contents" might be able to be tagged as "All regions". That is coming up new in the project and I already set up a taxonomy vocabulary before to categorize by regions. Is there any simple way to do this?
In the results list, it should be refered at "All regions", and not region 1 - region 2 - etc.

# Answer
Uncheck the **Required** option from exposed form field settings. Then there will be one more option **\- Any -** will appear in filter dropdown. It will work same as **All values**.

You can also change **\- Any -** value in to **All Values** by using **hook\_form\_alter**.

****EDIT :****

So the good structure is :
\- Create a taxonomy vocabulary for the values ;
\- Create a level 1 with an "All values" term ;
\- Create a level 2 with all individual values ;
\- Add the taxonomy relationship in the views and load the field taxonomy terms for each result ;
\- Add the taxonomy as an exposed filter **with depth** ;
\- In the **settings of this filter, define a depth of -1**, so every individual value chosen will also return the parent value.
As an example, a chosen region (as a taxonomy term) will return content indexed for "all regions" parent term.
> 0 votes

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


# Question
Title: Drush update for the first time hosed my website
Running latest versions of Drupal, etc. Localhost - dev site Maintenance mode

While trying to install Commerce\_kickstart and running Drush for first time to update modules, Drupal got completely hosed.

Can not find problem in database Repaired all databases but get Drupal white screen, no error messages Phpmyadmin won't work

Can anyone offer a series of steps to attempt recovery or at least find out what went wrong?

Thanks in advance. I need ASAP.

# Answer
Probably one of the updates of your modules is messing up. Most recently I had this problem with updating Rules which broke my site the same way it did yours (WSOD).

Reverting and updating one by one can show you what went wrong.

If you use drush you can do: drush up modulename (e.g. drush up rules) to update one by one, instead of drush up which updates everything. drush up drupal only updates core.
> 0 votes

---
Tags: commerce, drush, database
---


# Question
Title: How to create a view with group by node title and no grouping on nid
I want to create a view that shows nodes with duplicate titles. I am using Views 7.x-3.7 and Drupal 7.24

To do this I created a view with 2 fields: nid and title.

I turned on Use aggregation and for the node title field set it to group results together, and for the nid field selected count.

The query generated was:

```
SELECT node.title AS node_title, node.nid AS nid, COUNT(node.nid) AS nid_1
FROM
{node} node
GROUP BY node_title, nid
LIMIT 10 OFFSET 0

```

Clearly this won't work - we can't count nids if we are grouping by the nid.

How would I change my view so the query outputted was:

```
SELECT node.title AS node_title, COUNT(node.nid) AS nid_count
FROM
{node} node
GROUP BY node_title
LIMIT 10 OFFSET 0

```

Is this even possible? And if not why not? I would ideally like to achieve this without hook\_query\_alter if possible.

---

Exported view:

```
$view = new view();
$view->name = 'duplicated_page_titles';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Duplicated Page Titles';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Duplicated Page Titles';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: COUNT(Content: Nid) */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'duplicated-page-titles';

```

# Answer
> 2 votes
If you display nodetitle as a link it won't show as a duplicate. Uncheck 'display as a link' in fieldsettings of title and you should be good to go.

I imported your view, made this change, created a duplicate titled page and my view showed duplicate results immediately grouped by title, displaying the nodecount of that title.

# Answer
> 1 votes
hope this will help, click on Query settings:**Settings**

write the below code on your module..

```
function mymodule_views_query_alter(&$view, &$query)
{
if ($view->name == 'your_view_name')
{
  //dpm($query, __FUNCTION__);
  // dpm($view, __FUNCTION__);
   $query->add_groupby('node_title');
}
}

```

best of luck.

---
Tags: views
---


# Question
Title: How do I add a prevent duplicate item RULE to my commerce site
I am learning/working with RULES in my Drupal7 Commerce store. I thought this would be a fairly simple rule to create, but I can't find a work around for my need. I have a commerce site, that has our team uniforms. Each member is entitled to one and only one patch. If they add a second patch to their cart, I want a message to appear telling them that they can only have one patch in there cart and the add to cart process stopped.

**So here is the scenario.**

* Click the Add to Cart button for first patch, order/item/patch goes into cart
* Click the Add to Cart button for a second patch, message appears "you can't do that" and item does not go into cart

Where I am stuck is, what to select in the RULES UI, so it will check to see what is in the cart, look at the sku or item number \[both of these are unique to the item\], determine if the item that is to be added a duplicate, if so, pop up warning message, do not continue the process of adding that item.

Any help would be greatly appreciated.

# Answer
> 1 votes
You're looking for the action 'commerce-order: commerce-line-items' in Rules as a way of inspecting and testing against what the user already has in their carts. The recipe outlined here goes through how to add this rule in and do some preliminary testing, I've tried to modify it for your use case:

1. Create rule, name it; Event: before adding a product to the cart
2. Add your conditions, ex. check if content is a patch
3. In Actions add Loop through commerce-order:commerce-line-items
4. Create component, single rule, name it
5. Create following variables of the component and name them as you wish:
    * Commerce line item (line item of the order from the loop of the main rule)
    * Commerce product (product added to the cart)
6. Add condition to the component: Entity has field, Entity: \[line-item-in-order\], Field: commerce\_product. this will bring us the product from actual line item in current order (shopping cart).
7. Add condition to the component: Data comparison. Data to compare: line-item-in-order:commerce-product with product-added-to-cart -- This would be where you would determine if it is also a patch
8. Add action to the component: Remove an item from a list. List: \[order:commerce-line-items\], Item to remove: \[line-item-in-order\]. This will completely remove duplicated product from the shopping cart and from the order as well.
9. Eventually add another actions. At least Display some message to the user to inform him/her that the item has been removed sounds sensible.

Come back to your main rule created in step 1. Add action to the loop and select the component you have just created in steps 4. - 9. and set the variables.

---
Tags: commerce, rules
---


# Question
Title: Content Type - turn in to Form on front end to be used
Im fairly new to Drupal. Coming from Joomla. I created content type that works flawlesly and now i would like to take that form thats in the admin area and show it on front end for public to fill out.

Is this easely possible or do i need to use the Form API and rebuild the form and some how map to the fields in DB ?

Please let me know whats the best way to go about this.

Thanks In advance

# Answer
Under /admin/people/permissions you can grant a role access to create/edit/delete content of a specific type.

Look for the sub-heading **Node** and pick your content type from any listed. I've highlighted Poll in my example.

Click here for full size image

Here is the guide for roles and permissions from Drupal: https://drupal.org/node/120614
> 1 votes

---
Tags: forms, nodes
---


# Question
Title: Stop Drupal Commerce automatically adding hyphens before product variations radio button labels
Using Drupal Commerce I have created product variations with attributes that correspond to my taxonomies. When I use radio buttons to allow the user to select a specific variation Drupal Commerce adds a hyphen to the start the radio button label. For example my taxonomy term is 'White gold' but the radio button label that is displayed is '-White gold'.

How do I stop these hyphens from being added?

# Answer
These hyphens are not being added by Drupal Commerce itself, so you'll need to look into what other modules on the site might be interacting with the form.
> 1 votes

# Answer
It's probably an effect of the use of nested taxonomy terms there. In particular the function

`taxonomy_allowed_values`

```
/**
 * Returns the set of valid terms for a taxonomy field.
 *
 * @param $field
 *   The field definition.
 * @return
 *   The array of valid terms for this field, keyed by term id.
 */
function taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
        }
      }
    }
  }
  return $options;
}

```

This part here:

```
$options[$term->tid] = str_repeat('-', $term->depth) . $term->name;

```

Adds a hyphen prefix to the term based on the term depth in the vocabulary.

It's called by `taxonomy_options_list`

You could actually add your own `option_list` function by adding this to the term\_reference field settings:

```
$field['settings']['options_list_callback'] = 'my_module_taxonomy_options_list';

```

Alternatively you may be able to `form_alter` them out from display with

```
hook_form_commerce_add_to_cart_form_alter(&$form, &$form_state);

```
> 0 votes

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


# Question
Title: How to access the user's email field with Field Permissions?
This is a sort of sequel to my previous question How to hide specific fields and the according label in a view, based on field permissions?. One of the fields I'm displaying in my view is the standard *User: Email* field. I'd like to hide this field in my view except for the administrator and the user himself/herself.

How can I do that? I can't find a way to access the field with the Field Permissions module. If someone could show me a way to do that (my previous question is solved), this question would be solved.

Or is the Field Permissions module not suitable for this situation?

# Answer
> 0 votes
I found a solution for my problem! I installed the Email Field module and added a 'Emailadress' field to the user fields. I marked it as private with the Field Permissions module. Then, I created a rule that rewrites the 'Emailadress' field with the standard email after a user account has been created or updated. Finally, I added the 'Emailadress' field to my view.

# Answer
> 0 votes
I think your issue here is a duplicate of this one: https://stackoverflow.com/questions/2727513/drupal-show-hide-fields-in-view

The two solutions are:

* in the field template, display the content depending on the user role or
* create two views displays, one for each of your user role

# Answer
> 0 votes
I think Matt's answer is very close.

I would go the route of creating *three* views displays. The first display filters the content for *Current User* only and displays the email. The second view shows the email, and the display visibility permissions is set to *administrators* only. The third view hides the email field, but makes the view visible to anyone.

The fact is that Field Permissions has no effect on the email field, because it is unfortunately one of those "special case" field in Drupal (that existed long before the Field API did).

---
Tags: 7, views, entities, users, emails
---


# Question
Title: How do I bulk delete all content posted prior a chosen date?
How can I bulk delete all content posted prior a chosen date? Let's say I want to delete every node posted before/up to year 2012, but keep the ones after 2012.

How can I achieve it in Drupal 6?

# Answer
> 1 votes
Using the Views Bulk Operations (VBO) module, you can:

1. Create a VBO view
2. Add a filter (could expose it) for content "Post date" less then required date
3. Add a bulk operation to "Delete item"
4. Save the view

With the view you just created, you can then bulk delete the selected nodes.

---
Tags: nodes, views
---


title: Creating rule to update node title

text:
# Question
Title: Creating rule to update node title
When a visitor registers on my site, I have a set of rules that create several nodes. One of those nodes is a photo gallery.

The rule for the creation of the gallery title, includes the following: *\[account:name\]'s Photo Gallery* and that works fine.

But if the user changes his name later on, the name on the photo gallery is not updated.

I have been struggling with the creation of a rule to do just that but I haven't found the option or configuration that allows me to update the node title.

Any help on this would be greatly appreciated.

Thanks. :)

# Answer
> 1 votes
You could do that with Rules.

1. Add a new Reaction Rule (e.g: Update user gallery title)
2. Event: "After updating an existing user account"
3. Action: "Fetch entity by property":
    * type = node
    * title = \[account:name\]'s Photo Gallery
4. Loop over 'list item' and add action
5. Action: "Set data value": Set list\_item item title
6. Save list\_item.

Update: rule export:

```
{ "rules_update_gallery_title" : {
    "LABEL" : "Update user gallery title",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "node",
            "property" : "title",
            "value" : "[account-unchanged:name]\u0027s gallery"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "data_set" : {
                "data" : [ "list-item:title" ],
                "value" : "[account:name]\u0027s gallery"
              }
            },
            { "entity_save" : { "data" : [ "list-item" ], "immediate" : 1 } }
          ]
        }
      }
    ]
  }
}

```

---
Tags: nodes, rules, users
---


# Question
Title: How to get the unrendered contents of a block
I have a template file in which I would like to restructure the output of a block item (the applicable block changes depending on the page you are on). Basically what I want to accomplish is to list the items that will be rendered in a region, pick out the one I want and then modify how it will be displayed. What would be the best way to accomplish this? Can I do this through the template file?

Thanks.

# Answer
The solution I went with is to use the template\_preprocess\_block() hook as it allows me to render the items as I see fit. The issue with using the block.tpl.php file is that it does not give you access to components that is used to render the block (as by this point in the process, it is already rendered).
> 0 votes

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


# Question
Title: I need to store an array of integers for configuration of a custom module - which of these is right?
This is a list that is permanently recorded that should be able to change at a later time, either adding or removing items from the array at a user's discretion.

First method:

```
variable_set('module_listOfIntegers', serialize($arrayOfInts));

```

Second method:

```
$serialized = serialize($arrayOfInts);

$num_updated = db_update('module_config')
->fields(array(
  'listOfIntegers' => $serialized,
))
->condition('config_name', 'config_name, '==')
->execute();

```

And the final method could be creating a 2nd table with a single column where each row just holds the integer. That seems a bit excessive for a simple array, though.

# Answer
For saving module config settings, I use variable\_set() in conjunction with the system\_settings\_form() function. Just also note that it and its companion variable\_get() do the serialize/unserialize for you, so, there is no need for you to be doing it.
> 1 votes

---
Tags: 7
---


# Question
Title: Trying to add a column of Mysql timestamp through hook_update
I was trying to add the column of MYSQL Timestamp to the Database Table, the Query seems to be working correctly in mysql console.But when I execute the same in db\_query() the following error is thrown.

> Failed: PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1067 Invalid default value for 'last\_update\_date': ALTER TABLE `stores` ADD `last_update_date` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00';; Array ( ) in store\_update\_7100() (line 254 of /var/www/slocamo\_app/sites/all/modules/store/store.install).

Is the Query.

```
ALTER TABLE  `stores` ADD  `last_update_date` TIMESTAMP NOT NULL DEFAULT  '0000-00-00 00:00:00');

```

# Answer
> 1 votes
While valid in SQL, there is no data type `TIMESTAMP` in the Drupal 7 database schema.

The list if valid data types is here.

This means that you cannot add this datatype to your tables through any function that goes to the Drupal API (such as `db_query`). Your SQL console is not subject to these limitations, and will allow it to be added.

So the short answer is: Drupal 7 will not let you do what you try to do.

Also, in case you're trying to add two auto-update timestamps, note the following limitation in MySQL:

> One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.

---
Tags: 7, database, updating
---


# Question
Title: Correct way to access field values? field_view_value after field_get_items?
So I want to get some field values that I need as input, sometimes for rendering. According to this page:

http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

It is a mistake to hard-code 'und' for internationalization, so to avoid this the author says that we should use field\_view\_field().

I personally, don't need all info related to the field, just the value. So I opt for field\_get\_items() and then field\_view\_value() as outlined in the blog post. But this seems a lot of work just to get a single value of a field (plus we have to find and load the node). Do we really have to do so many steps to get a simple field value? I would have thought that this would be a very common function that users need.

I'm wondering that, barring any simple method, I could just grab the value directly from field\_get\_items()\[0\]\['value'\]. Maybe the drawbacks are that it doesn't pass through any sanitation routines? You can see more info here (trying to grab 'axis1t'):

Just looking for possible alternatives because my code is becoming somewhat bloated to keep getting field values this way along with the fact that they are burried inside field\_collections.

# Answer
If you are worried about bloat, just write your own field processor and keep it all on the level. That way you are using safe values, your site won't trip over if the language settings wiggle about and you can reuse your code in your next site.

You would call it wherever you like and because you know what you're expecting to get back, you could work with it immediately.

Something like:

```
<?php
/* get the values out of a field */
function magic_field_values($node, $field_name, $delta = null){
  $field_items = field_get_items('node', $node, $field_name);
  /* if a delta value is supplied, render that item otherwise, send the lot
  back. */
  if ($delta){
    return field_view_value('node', $node, $field_name, $field_items[$delta]);
  } else
  return $field_items;
}
?>

```

Then call it with:

```
<?php
$cheese_samples = magic_field_values($node, 'field_cheese_samples');
foreach $cheese_samples as $sample {
//do stuff
}
?>

```
> 3 votes

---
Tags: entities
---


# Question
Title: Drupal rules discount matrix - look up by taxonomy term
I'm having trouble applying a complex set of discounts to my products through rules.

The discounts are basically a user-category/product-category matrix with a different discount percentage for each cell. User categories and product categories are taxonomy lists. I have added a Field Collection field (with and infinite number of values) to the user category. In this field collection I combine a product category and a discount percentage (as a decimal), and then repeat for all product categories.

So when calculating the product sale price I need to:

* Look up the product category (works fine)
* Look up the user category and load the discounts list (works fine)
* Look up the right discount in the discounts list by product category (having trouble with this)

I've been able to look up the right discount in a custom PHP action like this:

```
$product_category = $product->field_product_category['und'][0]['tid'];

for($discount_index=0;$discount_index<count($user_discounts);$discount_index++){
    $discount = $user_discounts[$discount_index];
    if($discount->field_discount_product_category['und'][0]['tid'] ==  $product_category){
        return $discount->field_discount_percentage['und'][0]['value'];
    }
}

return 0;

```

But apparently returning values out of a custom PHP block is not supported.

Next I thought to install the Conditional Rules module. I could loop through the discounts and check the current loop variable against the product category and apply the discount if it matched. Within the If I can't access my loop variable though. Can anyone suggest a method that might work? I prefer not to have to write my own module if it can be avoided.

# Answer
I managed to solve this specific problem without resorting to writing custom actions in my own module.

I created a Rules component that takes a Field Collection Item (my loop variable), my Product Category taxonomy term and Commerce Line Item for parameters. Then I moved the conditional into the component, updated the price if the Product Category matched, and called the component from my loop. It even looks reasonably comprehensible.

I only needed to re-assert the fields on my Field Collection item (in my conditions) to be able to work with it.
> 0 votes

# Answer
If you want to use rules (and with commerce I think it makes sense), and you are comfortable with PHP, I would recommend writing your own module that defines the custom conditions and actions that you need to look up and apply discounts.

In my experience, the rules interface starts to break down quickly when use cases become even moderately complex. You can spend a lot of frustrating time fiddling with the interface, trying to get it to do what you want.

By writing your own conditions and actions, you keep the complex logic in code, where you can easily debug, access, and compare any information you might need.

In addition, your custom actions and conditions will be nicely exposed in the rules interface, and keep the high-level logic of your commerce solution tidy in one place.

Docs are here: https://drupal.org/node/298486. Drupal commerce itself has many good examples of custom actions and conditions to use as reference.
> 1 votes

---
Tags: commerce, rules, entities
---


# Question
Title: On hook_form_alter setting select list options for a field
By default select options i have left empty in admin of that content type.

I am trying to alter select list option of a content type using hook\_form\_alter.

I am setting the values to select values and is getting assigned.

Only issue is that its **getting logged out** with single refresh to create form of that content type form or try to submit that form. What am i doing wrong in the code.

Thanks in advance.

```
function hook_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'product_node_form')
    {

            $users = db_select('users', 'u');
            $users->join('users_roles','ur','u.uid = ur.uid');
            $users->fields('u',array('name'));
            $users->fields('ur',array('uid'));
            $users->condition('ur.rid',6,'=');
            $users->orderBy('u.uid');
            $users = $users->execute()->fetchAll();

            $vendor_list = array("Tan" => "Tan");

            foreach($users as $key => $user)
            {
                $vendor_list[$user->name] = $user->name;
            }
            $form['field_publish_to']['und']['#options'] = $vendor_list;
    }
}

```

# Answer
> 1 votes
Try to rename the variable **$user**/ **$users**. May be your code is overwriting the default $user object of drupal. Try after renaming the variables **$user**/ **$users**.

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


# Question
Title: Issue using search_api_ranges with search_api_ajax
I have set up search\_api\_solr - integrating search\_api\_ajax, facetapi and search\_api\_ranges into the results for a better flow.

I keep hitting an issue with regards to search\_api\_ranges where initially, for example; when a search runs on a taxonomy view which returns indexed nodes with the tag 'toyota', the link is always originally structured as:

```
mysite.com/car-tags/toyota/field_car_price/%5B1000%20TO%202000%5D

```

When clicking this, a 404 page not found is returned.

However! If I run the search again, this time clicking around the other facets - seeing the ajax working nicely, it's as if something triggers the ranges api, and each link is now:

```
 mysite.com/search_api_ajax/taxonomy/term/2/field_car_price/%5B1000%20TO%202000%5D

```

When clicking this, the ajax works fine.

Anyone come across this before?

# Answer
The issue is related to `Search Api ranges` module. There is already a patch for similar problem.

Kindly check patch at https://drupal.org/node/1987232 or use the updated module. I hope it will help for you.
> 0 votes

---
Tags: search
---


# Question
Title: How to add a field to Browsing Widgets partial form?
I have a content type Task which has a field that references to other content type Project, so when I create a new Task, I can reference it to a project. I would like to add this to the Commons Browsing Widgets partial form.

How can I add a dropdown list to this form that shows the projects where user can link the task? I was trying to add it by adding it to code in .module file, in the form\_commons\_bw\_partial\_node\_form\_alter() part but I didnt manage to get it working..

# Answer
> 1 votes
It seems that you can just do this by going to your content type, edit the field you want to show and check the "Display in the browsing widget mini-form". After all the trouble it seems quite simple..

---
Tags: 7
---


# Question
Title: Node reference field share between two content types
I have Two Content types Store and Deals and one Vocabulary named as Outlets. Outlet has many terms. I have added outlets as a term reference field to stores content type, and title field of store content type is added as a node reference field to deals.

1.Store content type When I am adding a new store I am selecting some outlet terms for it and saving it.

2.Deals Content type In Deals content type when I am creating a new deal I am selecting any store in dropdown, which I have added here as a node reference of store content type. What my concern is now while selecting any store title I want its corresponding outlets to be displayed here, so that if I wish I can uncheck some of them and then save.

Any help would be much appreciated.Please find the screenshot for better understanding.

Top Image is the store content type adding a store carters Second image is the deals content type I am selecting the store which I have previously added in stores, now while selecting carters the corresponding outlets should get selected

# Answer
> 1 votes
I'm not sure you can do it with Conditional Fields, so I did it with a custom code. You have to :

1. Hook on your form
2. Get referenced node
3. Get its taxonomy value(s)
4. Check this values in your term reference field.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == "page_node_form") {
        $form['field_OUTLETS']['#prefix'] = '<div id="mytaxofield">';
        $form['field_OUTLETS']['#suffix'] = '</div>';
        $form['field_STOREREFERENCE']['und']['#ajax'] = array(
            'callback' => 'MYCALLBACK',
            'wrapper' => 'mytaxofield',
            'method' => 'replace',
            'effect' => 'fade',
        );
    }
}

function MYCALLBACK($form, $form_state) {
    if(!empty($form_state['input']['field_STOREREFERENCE'])) {
        $nr = node_load($form_state['input']['field_STOREREFERENCE']['und']);
        foreach($nr->field_OUTLETS['und'] as $delta => $value) {
            // Add term to default values
            $form['field_OUTLETS']['und']['#default_value'][] = $value['tid'];
            // As it's not enough (I might need help on that one), I force it with the '#checked' value
            $form['field_OUTLETS']['und'][$value['tid']]['#checked'] = TRUE;
        }
        $form['field_OUTLETS']['und']['#default_value'] = drupal_map_assoc($form['field_OUTLETS']['und']['#default_value']);
    }
    return $form['field_OUTLETS'];
}

```

---
Tags: nodes
---


title: Taxonomy, views and menu

text:
# Question
Title: Taxonomy, views and menu
I have a content type "basic".

That content type is using 3 taxonomy vocabularies.

* Vocabulary 1 - 5 terms
* Vocabulary 2 - 3 terms (term1, term2, term3)
* Vocabulary 3 - 6 terms

I have a view that displays all the content from this content type. There are three exposed filters for the three vocabularies, they are displayed as a exposed filter block top of the content and they are working great.

From a left side I have menu links that show the three terms of Vocabulary 2 and it looks like this:

* Term1
* Term2
* Term3

Now the problem is if I select Term2 menu link that shows the content related to that taxonomy term and use some of the exposed filter, there are no results displayed.

I mean I'm selecting a menu link Term2 from left and than I check some term, lets say from the third exposed filter and the result is nothing, even if there's a content that belongs to that term.

Is it possible that menu to not interfere the filter results?

# Answer
Exposed filter you can use only with views. **yoursite.com/taxonomy/term/13** is not a view page. You can expose the filter as a block. And assign the block at the top of content.
> 0 votes

---
Tags: views, taxonomy-terms, routes
---


# Question
Title: How to embed private videos hosted on Amazon S3/Cloudfront using JW Player module?
Have anyone tried using the signed url option provided by the new version of Amazon cloudfront with the JW Player module? I´m using Drupal 7.

I´ve read that the idea of the signed url option is to generate the signed url at page load time with a short expiry. This way each user who loads the page gets a unique short lived URL they can access, if they share it, it will eventually expire limiting your exposure to hot-linking.

How may I add a dynamic expiring link? I know that this has more to do with how Amazon works than how JW Player works, but maybe someone can help me out because have made it through, or maybe have found a good n00b tutorial (I haven´t found any that explains how to use their services and this video player at once that I could actually understand).

Thanks in advance for any insight! Rosamunda

# Answer
> 1 votes
Use this php function to get signed url

```
function getSignedURL($resource, $timeout)
{
//This comes from key pair you generated for cloudfront
$keyPairId = "YOUR_CLOUDFRONT_KEY_PAIR_ID";

$expires = time() + $timeout; //Time out in seconds
$json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';

//Read Cloudfront Private Key Pair
$fp=fopen("private_key.pem","r");
$priv_key=fread($fp,8192);
fclose($fp);

//Create the private key
$key = openssl_get_privatekey($priv_key);
if(!$key)
{
    echo "<p>Failed to load private key!</p>";
    return;
}

//Sign the policy with the private key
if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
{
    echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
    return;
}

//Create url safe signed policy
$base64_signed_policy = base64_encode($signed_policy);
$signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

//Construct the URL
$url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

return $url;
    }

```

---
Tags: 7, files
---


# Question
Title: How to properly works in Chrome as a Drupal administrator?
Not sure if is there I can do from the Drupal side, then I'll close this question if not suitable here...

I use Chrome to admin my drupal sites and I noticed that after some hours (let's say 3 or 4 hours) the site start to take more time to load admin pages. I resolve this by clearing the Chrome cache. This is ok but then I loss all stored data in Chrome.

Is there I should do within the drupal configuration to avoid this?

# Answer
When you clearing the chrome cache it will ask for some options(shows a dialogue box with checkboxes), there you only need to check the **Empty the cache** checkbox and uncheck all other checkboxes and then click on **Clear browsing data**. Then it will only clear your browser cache not all chrome data.
> 1 votes

---
Tags: performance
---


# Question
Title: Create a view that links to another view
I'm trying to create a view that works as category page (aggregates a list of titles from content pages I've created). I need that list to link out to another view that is used to display photo galleries. Am I approaching this the correct way?

I want it to be dynamic so the customer can create photo galleries and they will automatically populate in the category page; then, a link send you to the proper display view.

# Answer
Suppose the name of views are view1 and view2 as content pane.You have to link view2 to view1.

For linking one view to another you would have to follow some simple steps:

1. In view2 you have an option under **PANE SETTINGS** 'Link to view' and select **Yes**.
2. In view1 also you have an option under **PANE SETTINGS** 'Link to view' and select **Yes**.
3. Now decide the place where you want to display view2.
4. Suppose its the footer region. Go to the footer region and add a **Global:View area**.
5. There you have a list of all views. Select view2 and save the view.

This way you can let one view execute under another view.
> 1 votes

# Answer
Solution to this issue:

Use a tag, on your content page, that has the same url as your gallery view has. Make sure that the order of your fields, in the views config page, has the title field coming after the tag field.....in order for the tokens to appear in the rewrite section of the title field. Add the content:tag token to your title field, as the link url. Now you have a category page that uses titles to link to view galleries. Create view as a block to offer list on other pages.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to prevent button to use validation function?
I have a form with a `submit` type element and a `button` type element.

For the form I have a `validation` and a `submit` handler functions.

The validation should occur only when I click on the `submit` type button, but it is also getting used when I click on `button` type element.

How can I prevent `button` type element from using the validation function.

P.S.

I have used `button` type for `#ajax`.

# Answer
> 1 votes
You are looking for two Form API entries:

`#ajax['prevent']`:

> **Description**: A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image\_button'. Multiple events may be specified separated by spaces. For example, when binding #ajax behaviors to form buttons, pressing the ENTER key within a textfield triggers the 'click' event of the form's first submit button. Triggering Ajax in this situation leads to problems, like breaking autocomplete textfields. Because of that, Ajax behaviors are bound to the 'mousedown' event on form buttons by default. However, binding to 'mousedown' rather than 'click' means that it is possible to trigger a click by pressing the mouse, holding the mouse button down until the Ajax request is complete and the button is re-enabled, and then releasing the mouse button. For this case, 'prevent' can be set to 'click', so an additional event handler is bound to prevent such a click from triggering a non-Ajax form submission. This also prevents a textfield's ENTER press triggering a button's non-Ajax form submission behavior.
>
> **Values**: String. Possible values: One or more jQuery events, with multiple events separated by space characters.

`#limit_validation_errors`:

> **Description**: Provides an array of sections which are parts of $form\_state\['values'\] which should be validated, implying that sections which are not listed should not be validated. This is normally used in multistep forms in the case of a "back" button, for example, where '#limit\_validation\_errors' =\> array() would mean not to validate anything as form values on the current page are to be discarded anyway. #limit\_validation\_errors does not have any effect if #submit is not set. More discussion is in the form\_set\_error() documentation.
>
> **Values**: array indicating sections of the $form\_state\['values'\] which should be validated.

---
Tags: ajax, forms
---


# Question
Title: Autocomplete several fields with values based on the selected value of an user reference field
UPDATE: the code is now cleaner and shorter. An autocomplete field triggers the ajax callback which reloads a field. The whole thing works for one field but not so well for multiple fields.

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_id_form') {
$form['triggering_field_id'][LANGUAGE_NONE][0]['value'] += array(
    '#autocomplete_path' => 'my_auto_path',
    '#ajax' => array(
        'callback' => 'my_ajax_callback',
            'wrapper' => 'my_ajax_wrapper',
            'method' => 'replace',
            'effect' => 'fade',
        ),
    );

    $form['dependant_field1'] += array(
        '#prefix' => '<div id="my_ajax_wrapper">',
    );
    $form['dependant_field2'] += array(
        '#suffix' => '</div>',
    );
  }
}

function my_module_menu() {
    $items = array();

    $items['my_auto_path'] = array(
        'title' => '',
        'page callback' => '_my_auto_path',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function _my_auto_path($string) {
  $string = array(':s' => $string . '%');

  if ($string) {
    $results = db_query("SELECT name FROM {users} WHERE name LIKE :s", $string);

    $items = array();
    foreach ($results as $result) {
        $items[$result->name] = $result->name;
    }
    print drupal_json_encode($items);
  }
}

function my_ajax_callback(&$form, &$form_state) {
    if (user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']) != FALSE) {
        $user_obj = user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']);
        $user_id = $user_obj->uid;
        //let's get another field from user's object:
        //$user_whatever_userfield = $user_obj->whatever;

        $form['dependant_field1'][LANGUAGE_NONE][0]['value']['#value'] = $user_id;
        //Do the same for the 2nd field but need to return both fields at the same time...
        //$form['dependant_field2'][LANGUAGE_NONE][0]['value']['#value'] = $user_whatever_userfield;
        return $form['dependant_field1'];

        //another way, with ajax commands:
        //but I can only replace the whole <input> instead of just the val() of each field.
        //$commands = array();
        //$commands[] = ajax_command_replace("#dependant_field1_id", $user_id);
        //$commands[] = ajax_command_replace("#dependant_field2_id", $user_whatever_userfield);
        //return array('#type' => 'ajax', '#commands' => $commands);
    }
}

```

# Answer
> 1 votes
I just found the solution to my problem: Every AJAX command runs and replaces the defined element. The trick is to predefine the values for all fields I need to update, within the callback. Then, these values remain in tact within the array of the newly rendered fields using the AJAX commands. Here is my updated callback:

```
function my_ajax_callback(&$form, &$form_state) {
    if (user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']) != FALSE) {
        $user_obj = user_load_by_name($form_state['values']['triggering_field_id'][LANGUAGE_NONE][0]['value']);
        $user_id = $user_obj->uid;
        // and another user attribute:
        $user_whatever_userfield = $user_obj->whatever;

        $form['dependant_field1'][LANGUAGE_NONE][0]['value']['#value'] = $user_id;
        $form['dependant_field2'][LANGUAGE_NONE][0]['value']['#value'] = $user_whatever_userfield;

        $commands = array();
        $commands[] = ajax_command_replace("#dependant_field1_wrapper", render($form['dependant_field1']));
        $commands[] = ajax_command_replace("#dependant_field2_wrapper", render($form['dependant_field2']));
        return array('#type' => 'ajax', '#commands' => $commands);
    }
}

```

Also, I changed the position of my wrapper to have a wider range, in order to include all the fields I want to ajax-update. As every AJAX command will be recreating each form element, if the form element lives within a wrapper (added in form\_alter), the wrapper will also be rendered and that causes an HTML mess. So having one hidden field above & another hidden field below my fields makes life easy. The new wrapper encloses these hidden fields and leaves all other fields clean when regenerated from the callback.

# Answer
> 0 votes
As @Quentin Campbell said, "you would need a jQuery script that will watch the autocomplete field for changes, and then run script to fetch the rest of the user data from user object (via a AJAX call) and then fill in the values of the other fields."

The correct Drupal way to do it is to **use the Drupal AJAX Framework**. This framework will allow you to send a command to Drupal, receive the fields values and then in your JS you will fill the form fields.

---
Tags: forms, ajax
---