# Question
Title: User role weaker than authenticated user
I am using LoginToboggan Module and I want to create to create a "pre-authenticated" user role that users get assigned to upon registration. After they have verified their email address they will be promoted to "authenticated" users. Obviously, pre-authenticated users should have restricted permissions.

> If "Set password" is selected, users will be able to login before their e-mail address has been authenticated. Therefore, you must choose a role for new non-authenticated users -- you may wish to add a new role for this purpose. Users will be removed from this role and assigned to the "authenticated user" role once they follow the link in their welcome e-mail.

I created a new role "pre-authenticated" and gave it weight 1 and "authenticated" weight 2 ("anonymous" has weight 0 and "administrator" has weight 4). However, whenever I give "authenticated" users the permission to do something, "pre-authenticated" users inherit this permission. It seems like Drupal treats all custom roles as being extra roles for users that already are authenticated. I already cleared my cache and ran cron.

# Answer
This doesn't appear to be documented in the LoginToboggan interface anywhere but the default behaviour actually does what you want it to do.

You need to create new role like you mentioned, a `pre-authenticated user`. After creating the new role go to LoginToboggan config page and select this new role as your Non-authenticated role and save. Now when you go back to the permission config page you'll see this new role is excluded from the `authenticated user` permissions, just like the `anonymous user`.
> 3 votes

# Answer
You may try with Rules

```
The rules module allows site administrators to define conditionally
executed  actions based on occurring events

```

You can create a rule that sets pre-authenticated role on registration and one rule that set another role after the user has confirmed it.

EDIT --------------

LoginToboggan has an option :

> **Non-authenticated role**
>
> If "Set password" is selected, users will be able to login before their e-mail address has been authenticated. Therefore, you must choose a role for new non-authenticated users -- you may wish to add a new role for this purpose. Users will be removed from this role and assigned to the "authenticated user" role once they follow the link in their welcome e-mail. WARNING: changing this setting after initial site setup can cause undesirable results, including unintended deletion of users -- change with extreme caution!

Have you set your pre-authenticated role here?
> 0 votes

---
Tags: users
---


# Question
Title: Best Practise for executing Something in Background in custom module
I have written a custom module which creates a link on the page.

When you clicking the link

```
<a href="path_to_module/lib/script.php?lotOfparameters=value>
  Do it
</a>

```

a php file is called, where all the logic of the module is done (create a node with predefined field values, create a pane for panels module and other stuff).

But i think this isn´t the recommend way to to this in Drupal. Doing this in the .php file is tooking sometimes a lot of time, so a progress bar would be nice for exmaple.

So I am looking for the best way to do logic when a button is clicked on the site.

**EDIT:** I think that was a bad description for my problem, so i try to make this better.

In my Templates, e.g. page.tpl.php and node.tpl.php, I´m printing a link to create a button. If the buttons gets clicked I want to do some stuff, i think what exactly is irrelevant. But I'm doing this with a direct link to a .php file in the link. In this .php file all things are executed. And I think THIS isnt the best way to do things in drupal.

# Answer
Extremely broad question, so an extremely broad answer...

Use the Batch API.

If you need more code examples than the docs page provides, the examples module has a lot of good, related code.
> 3 votes

# Answer
What @Clive said -- that's the best way to execute a long process in manageable chunks -- but if you also want to kick this off in the background without reloading the page, you'll want to use the Ajax framework to execute it.
> 0 votes

---
Tags: 7
---


# Question
Title: Create a Block to display Titles - even pages, view-pages, articles
In my theme I need to hide the title of content, even the content-type pages and the Views page, and put it in a separate block placed in an other region than the content one. I figured out how to pick the title from the content-type pages (plain-simple as is) but I figure some difficulties on the View Pages.

How can I hide the title of the node or the page view in the content and put in a block of another region?

Thanks for every answers!

# Answer
> 0 votes
Welcome to Drupal answers.

1. **How hide a title?** There are a lot of questions that have been answered about this topic. Here one of them.
2. **How put the title in a block?** You have different ways to achive this goal. if you only want to display the title with a content-type and the title is always in the same place, i would create a template for this content-type.

Another way to do it, you should build a module that declare a block. The content of this block(the title of the node) has to to be rebuild when a page is requested.

---
Tags: views, blocks, theming
---


# Question
Title: add css class to row with specified field value in views
I have a View, and when a certain field in the result has a specific value, I want to add a CSS class to that row.

How I can add css class to the matching row in views result in `table` result mode directly in `views` pages, without template files?

# Answer
> 9 votes
You can do this in views. The class in views supports tokens. So if you use the value of a field \[field\_value\] and put that in the class, then you can style it by using .field\_value in your css.

This way every field will get a class, but only the ones you style in css will affect how they look.

---
Tags: views
---


title: Should block titles be <h2>?

text:
# Question
Title: Should block titles be <h2>?
These `<h2>` heading tags, in the canonical sense, should be used as headings only, right?

In Drupal, it seems these block headings get `<h2>` tags, but they aren't semantic headings insofar as being legitimate paragraph headings on legitimate paragraphs.

Surely as a search spider would not readily distinguish these tags, they in fact not be `<h2>` but standard `<div>`s?

# Answer
> 5 votes
'heading' != 'paragraph heading' (in fact there's no such thing as an HTML paragraph heading). A heading tag is used to denote the heading of a section (a conceptual section, not necessarily a `<section />` tag) - it doesn't have to be above, or any where near, a paragraph.

If you're interested in SEO, whatever you do don't convert them from an `<h2>` to a `<div>`. A `<div>` carries no semantic weighting whatsoever, while an `<h2>` does. If you're not happy with `<h2>`, obviously choose something else, but for the love of Matt Cutts not a `<div>` :)

Personally the only tags I'd recommend are `<h2>` (which is standard for adding a heading to a section in any website, not just a Drupal one) or `<h3>`, if you're already using `<h2>`'s to markup more semantically important sections elsewhere in the page.

# Answer
> 0 votes
Every taxonomy page has a list of H2, linking to the articles listed on the page. I'd assume 10 H2s on a page could hurt your SEO. And if you add a few blocks on the page, everything gets even more confusing. I'm using H3 for taxonomy pages and H2 for block titles. Everything else should be H3, although H3 weighs so much less.

---
Tags: theming
---


# Question
Title: Drupal 6 - Theme custom search form results
I have a **custom search form** written in my custom-module. On submit, i have used do\_search api and then I have made some modifications/customization with the results.

Now having my customized results, how can I render them?

**Work so far**---\>

* In **custom-module.module**

```
function custom_module_search_ticket_form_submit($form, $form_state) {
   // do_search()
   //  customizations (in the sense, removed few results according to my requirements. Otherwise the result-object/array format is same as of core search results)

    return theme('rootcandy_my_search_results', $results, $type);
}

function custom_module_theme() {
  return array(
    'rootcandy_my_search_result' => array(
      'arguments' => array('result' => NULL, 'type' => NULL),
      'template' => 'rootcandy-my-search-result',
    ),
    'rootcandy_my_search_results' => array(
      'arguments' => array('results' => NULL, 'type' => NULL),
      'template' => 'rootcandy-my-search-results',
    ),
  );
}

```
* Rootcandy is the theme I have used. In rootcandy's **template.php**

```
function rootcandy_preprocess_rootcandy_my_search_results (&$vars)  {
  // copied lines from core search module's search.pages.inc function template_preprocess_search_results(&$vars)
}

function rootcandy_preprocess_rootcandy_my_search_result (&$vars) {
  // copied lines from core search module's search.pages.inc function template_preprocess_search_result(&$vars)
}

```
* Under rootcandy theme folder, **Added below tpl.php files**

```
rootcandy-my-search-results.tpl.php  (copied from core search's search-results.tpl.php)
rootcandy-my-search-result.tpl.php   (copied from core search's search-result.tpl.php)

```

Now I have done this much, clearing cache, after everything; Submitting my custom-search-form renders nothing, other than the form. When I print my customized results, they are fine. Theming part is not working.

Where is the mistake? Plz help !

# Answer
> 0 votes
Whatever u have done so far is correct. Only thing left now is to render the content from ur preprocess 'rootcandy\_preprocess\_rootcandy\_my\_search\_results' to ur 'rootcandy-my-search-results.tpl.php'. U have to start debugging in this way.

1. Check ur $vars\['form'\] contains ur form values in 'rootcandy\_preprocess\_rootcandy\_my\_search\_results'
2. create a variable in preprocess and try using it in ur rootcandy-my-search-results.tpl.php. Eg: $vars\['testing'\] = "this is to confirm that variable is working in rootcandy-my-search-results.tpl.php"
3. if you print $testing in ur rootcandy-my-search-results.tpl.php and it gives "this is to confirm that variable is working in rootcandy-my-search-results.tpl.php" Which means its working fine.
4. Then you can pass ur form results to the tpl file. Eg: $vars\['result'\] = drupal\_render($vars\['form'\]\['result'\]);

Try this. Ur first goal will be making sure u can get ur preprocess values in ur tpl file.

---
Tags: theming, search
---


# Question
Title: How come my views suddenly take full width?
I don't know what I've changed but now 2 of my views are full width. Here's 2 screenshots from a view how it was and how it is now. How can I change this back to normal?

# Answer
> 0 votes
Though it is cut off in the screenshot you have above, the spitfire.jpg image is forcing that cell to 968px wide (968x478) which is larger than your main cell.

This is more a CSS question than a Drupal one so to bring it back to Drupal, I would recommend that you create an image style for this imagefield so that all images are resized according to the width of your main cell. Check out the image module documentation for guidance on how to create styles, you would then just need to tell views to use your new style for your view. Alternatively, you can use one of the existing styles (ex. thumbnail, small, medium, large) to have views display an image that would fit on your page:

# Answer
> 0 votes
Schnippy's answer is completely correct.

Your Spitefire image is displaying at it's full dimensions, 968x478.

The simplest and fastest solution would be to upload a new spitefire image which has a maximum width of 620px, then ensuring that no other images wider than 620px are uploaded in the future.

---
Tags: views
---


# Question
Title: Use username password on different subdomain
I now have a website which is using drupal. This is the 'main' website on the www domain. I would like to build a small gimmick which is only accessible to my users. This gimmick site is probably not using drupal at all.

Is there a way to duplicate the login procedure for my subdomain so that only users from my main site can use the gimmick site?

thanks in advance

# Answer
Yes,there is no problem using drupal user table, you just need implement you site and connect to data base that Drupal install on it and then just need use `user table` , only one note remain that the password saved with `md5` method in user `table`.
I thing is not complex, the summery of answer is `connect to db` use `uid`(or `name`) and `password` field of `users` table .

**as sample code :**

```
<?php

$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="drupaldb"; // Database name
$tbl_name="users"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = md5(mysql_real_escape_string($mypassword));

$sql="SELECT * FROM $tbl_name WHERE name='$myusername' and pass='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// want to want
echo "congratulation ,you login";

}
else {
echo "Wrong Username or Password";
}
?>

```
> 1 votes

---
Tags: users, subsites
---


# Question
Title: Organic Groups: Audience field is missing
I seem to have a problem with Organic Groups. I follow the instructions by the book but when I want to create content the audience label and field is missing! Thus I can't select the group to which the content is visible.

This in contrast to the settings where it is stated that it must appear... .

All my permissions seem right.

Does anybody have a workaround?

# Answer
You can add the field to the content type. Configuration\>OG field settings. In Bundles, select Node\>Group Content (or whatever your group content type is called). Then in Fields, choose Groups Audience. Then click the Add field button.
> 0 votes

---
Tags: organic-groups
---


title: Administer menus and menu items

text:
# Question
Title: Administer menus and menu items
I've given my newly created user the permission to "Administer menus and menu items " however, when I log in as the new user I cannot administer the menus... Why might this be? The user doesn't have the permission to administer blocks, if that makes any difference?

# Answer
> 2 votes
Based on the comments, I think the issue is that your user needs the "Use the administration pages and help" permission, under the System category.

# Answer
> 0 votes
You may need to enable the followings in `#overlay=admin/people/permissions`

```
Contextual links
Use contextual links
Use contextual links to perform actions related to elements on a page.

Overlay
Access the administrative overlay
View administrative pages in the overlay.

Toolbar
Use the administration toolbar

```

---
Tags: routes
---


# Question
Title: Devel query log not showing module enabling queries?
I enabled "display query log" in Devel. However, I've noticed not all queries are logged, for instance when enabling/disabling a module there is no "update system set status = 1.." query shown. Why is that? Thanks.

# Answer
I found the answer: enable/disable module calls are ajax requests and the devel display query log doesn't show queries from the ajax request.

BTW, if you want to use hook\_exit() you will notice it is not fired for ajax calls that use exit() and not drupal\_exit(). However, if you need something to be run at runtime end, you can use PHP register\_shutdown\_function() in your module (in your hook\_init() for instance).
> 1 votes

---
Tags: debugging
---


# Question
Title: all modules that use the field api module
Sorry if this is a basic question, is there a way to browse all modules created with the fields api. I am looking for some interesting ways to format and use fields.

# Answer
You can find all the info to format fields in the field API

* If you want to know how **core modules** implements the Field Api, you have to enter in every hook info page and there you will find the modules that implement this concrete hook. You can also follow the links to see the code.

Here an example of hook\_field\_delete and the location on web page:

* On the other hand, if you want to know what **contributed modules** have implemeted the field API, you will have to look in the contributed modules page and make a filtered search with *core = 7.0* and *module categories = Fields*.
> 0 votes

---
Tags: entities
---


# Question
Title: Field Collections not displaying in Content Template
I'm using Content Templates (Contemplate) module to style a node display for a content type that uses Field Collections. When I view the node's display page before changing anything in the Content Template, the Field Collections display fine. As soon as I tick the "Affect body output" checkbox to adjust the template, the Field Collection content no longer shows up on the display. The header is there, but the content is gone.

How can I get the Field Collection content to display? Is there an incompatibility issue with Content Templates and Field Collections?

This is a Drupal 7 site... and, before you ask, I need to use Content Templates for theming due to a somewhat locked down development environment.

# Answer
Not necessarily an answer, but a viable workaround:

The Field Collection content is available to views, so I made a view block that prints out the Field Collection content where the contextual relationship is the node's NID. That block gets displayed on this content type only. With some Javascript trickery, I'll be able to position it where it needs to go.

I'm open to a real answer, but for now, this is all I've got.
> 0 votes

---
Tags: theming, nodes, entities
---


# Question
Title: restrict user to libarary tab in media file selector in media module
I want use `media file selector` as image field in content type . media module provides it to select and upload image by popup, but I dont want user can upload image ,I just want only user can select file from library tab in `media file selector`. any body know how can I achieve this job?

# Answer
> 2 votes
To prevent user(s) from uploading files, remove the following permission from their role (admin/people/permissions)

> edit media

For the role to still be able to access the library of media that has already been uploaded, ensure that they still have the permission

> Import media files from the local filesystem

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


title: font icons in drupal

text:
# Question
Title: font icons in drupal
I want to use font icons in some of the headings in my Drupal 7 website.

For that I have downloaded and enabled Fontello module along with icon module and enabled that. The module home page says that " ... upload the bundle via this module's configuration page " But there is no configuration page for this module.

Please guide me how to use icon fonts in Drupal.

# Answer
> 1 votes
I have not used this module before, but from the info file it seems that the admin page is at

> admin/config/media/icon

and from there it looks like you upload at

> admin/config/media/icon/import

---
Tags: 7, theming
---


title: Using drush on drupal 8?

text:
# Question
Title: Using drush on drupal 8?
Dursh works very well with my Drupal 7, but when I try running Drush on Drupal-8 directory it throws some error message,

```
$drush pm-list

Command pm-list needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment to run[error]
this command.
The drush command 'pm-list' could not be executed.                                                                                [error]
A Drupal installation directory could not be found

```

could anyone tell me the solution for this problem?

any help is appreciated. Thank you.

# Answer
> 10 votes
Which version of drush? https://github.com/drush-ops/drush#drush-versions has a nice table, but in short you need the `master` branch from github if you want to work with Drupal 8.

# Answer
> 0 votes
I have not used drush with drupal 8, but these errors are sometimes experienced with D7 if you run drush from outside a site directory (eg sites/mysite.com) if the 'default' site is invalid or not defined.

Is it possible this might be the case here?

---
Tags: drush, caching, 8
---


# Question
Title: How do I display tokens in a block using PHP code?
What is the way to use tokens in PHP code?
I need to show the user profile picture URL, but the following code doesn't work.

```
<?php
  echo "[current-user:picture:url]";
?>

```

How do I display tokens in a block? I am using Drupal 7.

# Answer
> 2 votes
I dont recommend using PHP in a block for many reasons.

I would recommend you to use proper implementation of hook\_block\_view and hook\_block\_info to do you custom PHP codes in there.

# Answer
> 1 votes
Unless you have a specific reason to use tokens for this purpose, you could just get the profile picture url directly from the user object:

```
global $user;  // get the current user
$user = user_load($user->uid); // load all fields etc for user object
$picture_url = $user->picture->uri;
echo $picture_url;

```

I totally agree with saadlulu above though - much better to put this code into a module.

Not sure if it suits your purposes, but a quick search of d.o also brings up an existing contributed module that will display the user picture for you:

https://drupal.org/project/user\_picture\_block

# Answer
> 0 votes
You could try token\_replace

```
token_replace($text, array $data = array(), array $options = array())

```

> **Parameters**
>
> **$text:** A string potentially containing replaceable tokens.
>
> **$data:** (optional) An array of keyed objects. For simple replacement scenarios 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.
>
> **$options:** (optional) A keyed array of settings and flags to control the token replacement process. Supported options are:

---
Tags: 7, blocks, tokens
---


# Question
Title: Can not find field_image(image) in drupal 7.24
I am new to Drupal. I am using a beginners guide pdf to get accustomed to it. It says at point 10 that :

* Now, we will move on to the image property. We are going to use an existing field for this property. In the Add existing field section, enter image for the Label. Select Image: field\_image (Image) from the Field to share drop-down, and click on the Save button.

But in my installation:

I find no `field_image (image)`! What has happend?

# Answer
> 0 votes
An image field will only appear as an "existing field" if it has already been defined for some content type. The tutorial you're following assumes it does exist. It look like this is not the case in your configuration. By default, the standard *Article* content type has an image field. You may have removed it, or deleted the *Article* type.

If there is no existing type with an image field, you need to add it as a new field, as shown below:

If no *Image* field appears in this menu, you may need to enable the core **Image** module. To do so, navigate to: *Home » Administration » Modules*. Then locate the **Image** module in the core sectio, make sure there is a tickmark next to it, and click *Save configuration*.

---
Tags: media
---


# Question
Title: Create order in drupal commerce programmically with product cost change in order
I have a shop with one product, I want have a feature that user only determine how much he/she want to pay and then pay it.after complement payment manager of site according of amount money he/she paid, create a custom product and sent it.
My idea is create custom porduct with 1$ cost and then create a form and get the amount value from user,then I want create an order programmically and in order update the price with the value that user entered. How can Implement this?

I want something like this enter link description here

# Answer
finally this is my solution for do this job

before I create a product, save it product id, in my custom function I change it's cost and add to order

```
global $user;

  // Sanitize just in case
  //862 create by myself as custom porduct
  $product_id = 862;
  $price=  floatval($form_state['values']['field_suggest_your_price']['und'][0]['value'])*100;
  // Load product
  $product = commerce_product_load((int)$product_id);
  $product->commerce_price_usd["und"][0]["amount"]=$price;
  commerce_product_save($product);
  if((empty($product->product_id)) || (!$product->status)){
    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }
//$product->commerce_price["und"][0]["amount"]=$price;
//$product->commerce_price_usd["und"][0]["amount"]=$price;
//dsm($product);

  // Attempt to load existing order for user from session
  $order = commerce_cart_order_load();
  if(!$order){
    $order = commerce_cart_order_new($user->uid);
  }

  // Save new order to get order id
  if(empty($order->order_id)){
    $order->revision = FALSE;
    commerce_order_save($order);
  }
  $order_id = $order->order_id;

  // Wrapper for easy field access and adding line items, order passed by reference
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  // Save new line item to get line item id
  commerce_line_item_save($line_item);
  // Add line item to order wrapper
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save order with new order number and line item added
  $order->revision = FALSE;
  $order_wrapper->save();

  if(!empty($order->order_id)){
    drupal_set_message(t('Thank you, your %product is ready for checkout.',
                         array('%product' => $product->title)));
    drupal_goto('checkout/'.$order->order_id);
  }else{
    drupal_set_message(t('Sorry, there was a problem building your order. Please try again later.'), 'error');
    drupal_goto(); // frontpage
  }

```
> 0 votes

---
Tags: commerce
---


# Question
Title: How to go to external website from within a module?
I have created a custom module in which when a user enters a valid id, it should them take them to an external website. The problem I am having is redirecting to the external website. The code I am using in my module is to do the redirection is:

```
  // clear out the output buffer
  ob_start();
  while (ob_get_status()) {
    ob_end_clean();
  }
  return header("Location: $external_url");

```

This doesn't work. What should I be using to accomplish this?

Thanks.

# Answer
You should use `drupal_goto` to redirect to a URL.

```
drupal_goto($external_url, array('referral' => $referral_url));

```
> 3 votes

# Answer
You should use drupal\_goto()

This question is answered in more detail here:

What API function do I use for redirecting to external URLs?
> 1 votes

---
Tags: 6, redirection
---


# Question
Title: change image size in media file selector of media module
how can I change the size of the image that show in media file selector popup in media module , I don't know which image style this module use, and how can I change the image style which is currently used or active.

# Answer
> 4 votes
The media module adds the image style 'square\_crop' when it is enabled

you can alter this image style to change the display of thumbnails in the media browser (admin/config/media/image-styles/edit/square\_thumbnail).

I believe the theme css also uses css to define the size, so to see the effect you will also need to make some changes in whichever theme is selected for the media browser (admin/config/media/browser):

```
.media-item img {
 border: 2px solid transparent;
 display: inline-block;
 margin-left: -2px;
 height: auto; /* override this in you theme */
 width: 100%; /* and this */
}

```

---
Tags: 7, nodes, media
---


# Question
Title: Getting total vote results for several nodes in a view (Drupal 7, Views 3)
This is the problem: I have a Drupal 7, Views 3 site with a certain node type with a Fivestar field on it. I want to get total scores not for one node, but for all the nodes in a view.

For example, let's say our nodes are "restaurants". A person can write a review for this restaurant and give it a score.

Okay, now imagine some of these restaurants are thai restaurants. Now imagine I want the average score for all the thai restaurants in a view. Be careful about this, I don't want the average for one of the restaurants, but for ALL the restaurants in a given category. That's clearly a work for views, but how? How do I do that?

Thanks in advance.

# Answer
> 0 votes
First, thanks both for your replies. For some reason I didn't receive the notifications on your help, so after a lot of "wall-hitting" I found a solution related to Israel Morales' advice:

1 - Israel Morales was right on its explanation, but please notice that if your sort the result set by any field with unique values, such as Date, the aggregation process will never happen. That was my mistake, That was added when creating the View, I forgot to remove it in the first place. 2 - Views aggregation works fine for numeric values, but it falls short working with strings. Then i discovered VIEWS AGGREGATOR PLUS module. To work with this module you better deactivate Views own aggregator and use the one included in the module, because they are separated processes and it can become a mess. It only renders tables, but it adds quite interesting options to work with strings. For example, it can show data like this:

Who were you at the restaurant with?

Alone : 12 Friends : 25 Couple : 16 Family : 9

# Answer
> 4 votes
Create a view:

* Use Agregation.
* Use fields.

Add fields in this order remove everything else:

* Taxonomy or (Category) as you call it. (Aggregation settings = Group results).
* field\_rating (or your five star field). (Aggregation settings = Average).

Filters.

* Published (YES).
* Content type = (restaurants).

What you need to do in resume, is to call all the nodes of type "restaurants" group the results the taxonomy field by Aggregation and AVERAGE all the ratings.

---
Tags: views, rating
---


# Question
Title: Drupal Multisite (subdomain) Not Working
Drupal 6, default installation, default .htaccess, default http.conf for Apache.

`sites/` directory looked like this:

```
all
default
subdomain1.maindomain.com

```

`default` site and `subdomain1` working well.

Added a new directory, `subdomain2.maindomain.com`. It has the same ownership and permissions as `subdomain1.maindomain.com`. It contains `default.settings.php`, the out-of-the-box one, and `settings.php`, which is a copy of `default.settings.php`. The permissions and ownership of the two files are correct.

The 'sites' directory now looks like this:

```
all
default
subdomain1.maindomain.com
subdomain2.maindomain.com

```

Visiting `subdomain2.maindomain.com` returns an error. Visiting `subdomain2.maindomain.com/install.php` returns an error. I can download an example file from `maindomain.com/sites/subdomain2.maindomain.com/files/example.txt` when it is located at `/sites/subdomain2.maindomain.com/files/example.txt`.

Basically, I've followed all the steps in the docs, and I'm unable to create another 'subsite' accessible from a new subdomain. What am I doing wrong? What else should I be doing?

# Answer
> 1 votes
If you want to run several sub-domains on the same code base you need to make sure that either both the sub-domains resolve to the same IP address as your main domain, or that your main domain supports wildcard DNS. You also might consider giving Subdomain module and Domain Access module a try.

# Answer
> 0 votes
Check that subdomain2.maindomain.com should point to the same directory as is subdomain1.maindomain.com in the cpanel. This directory is the root of Drupal installation.

Firstly simply create a symbolic link ( ln -s subdomain1.maindomain.com subdomain2.maindomain.com ) and see if the subdomain2 is accessible. Otherwise it is configuration issue with Apache/Cpanel.

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


# Question
Title: How do I get a form element to display in a lightbox?
I'm currently using Drupal 7 and I'm using the Form API to generate the form. What I'd like is for certain fields to be represented by a link, which when clicked on, opens the field in some kind of lightbox. This is what I tried, but it doesn't seem to work:

```
  $form['snvisdt_note']=array(
  '#prefix' => "<a href=\"/screen #snvisdt_note_div\" rel=\"lightmodal\" title=\"Add Note\" >note\</a> <div id=\"snvisdt_note_div\" style=\"display:none;\">",
  '#type' => 'textarea',
  '#title' => 'Add More Information',
  '#suffix' => "</div>",
  );

```

"screen" is the name of the page the form is on. I am trying to do this in Lightbox 2, but would be happy to use some other solution, if it works. Can someone please give me an example of what would work?

# Answer
If you want to display `form` element into popup, then I would suggest you to use `ctools` api. It will provide you functionality to create a custom popup to render content.

> Ctools provide Modal dialog functionality to display element in modal.

You need to follow below step for the same:
> 1 votes

# Answer
I think you should create the whole form and for the field you need to open in lightbox you should add the `#prefix` property containing the link which triggers the lightbox. Also, be sure to hide the actual form element in css using it's ID

Eg:

```
#edit-field-somefield { display: none; }

```

The link should be something like this:

```
<a href="#edit-field-somefield" rel='lightbox'>Add more</a>

```

Hope this will help you get on the right track.
> 0 votes

# Answer
In Addition to Marius Ilie, To create a link in the form you can use #item from the form api like,

```
$form['snvisdt_note'] = array(
    '#type' => 'item',
    '#title' => t('Add More Information'),
    '#markup' => l(t('note'), "javascript:void(0)", array('fragment' => '','external'=>true,'attributes' => array('rel' => 'lightbox' , ))),
    );

```
> 0 votes

# Answer
This is what you are looking for replace the href to the following `/screen #div_id > *` that should do the job. I faced the same issue a while ago. (notice the spaces)
> 0 votes

# Answer
I would suggest you have a look at modal forms.

> Modal forms make use of the modal feature in the ctools module to open some common forms in a modal window.

Refer to some of the common forms already implemented like the login form.
> 0 votes

---
Tags: 7, forms, javascript
---


title: Editing a Design Suite Template File

text:
# Question
Title: Editing a Design Suite Template File
I'm using the Design Module for a Drupal 7 site and have created a simple 1-column views display using the module and I want to take that template file that it has created and edit it more.

At the bottom of the layout options I am given a location of where the template should be along with the name of it, but it's not there.

Is it possible to edit a layout (template file) that Display Suite has created? Where can I find those template files?

# Answer
> 1 votes
The source template file you are looking for should be called **ds-1col.tpl.php**. It is in the mentioned folder.

1. Copy the file to the **templates** folder within your theme.
2. Then rename the file to ds-1col--ds-views-account-wins-page.tpl.php
3. Make the adjustments you desire.
4. Flush your caches and you should see the changes.

Read more about views template files here which function really similarly.

---
Tags: 7, display-suite
---


# Question
Title: Login into drupal site from a non drupal login form?
I have a pop up for login in php that contains username, password text fields, a selectbox and a submit button. The current scenario is after filling details, selecting value from the select box and then clicking on submit button takes me to the site developed in joomla, changing select box value and submitting the login form takes me on a site developed in wordpress as a logged in user. Now what I want is to provide a third value in selectbox of login pop up,upon selecting which I will be logged in into drupal site. Should I use any web service, if yes then what is the process for that? Kindly suggest me an optimal solution.Thanks in advance.

# Answer
> 2 votes
I found solution after navigating a number of urls and so sharing this with those who are looking for the answer :

I used **ajax** call and **curl** functions to fulfill my requirement.

The steps I followed are:

1. I used ajax to call a local curl file on selection of a particular value in dropdown on login popup.

```
   function restapilogin1(){
      var email = $('#apploginusername').val();
      var password = $('#apploginpassword').val();
      var program = $('#apploginprogram').val();

if(program == 'DrupalTest'){
    data={username:email,password:password};
    $.ajax({
        url: "<?php echo $root; ?>modules/mod_loginpopup/islogin_drupal.php",
        type: "POST",
        data: data,
        dataType: "html",
        success: function(response){
            if(response == 'error'){
                $(".popup_login_status").html('The username or password you entered is incorrect.');
            }
            else{
                var login_url = 'http://localhost/drupal-test/testlogin_1.php?user='+ email +'&pass='+ password;
                window.location.href = login_url;
            }
        },
        error: function(err){
            console.log(err);
        }
    });
}

```

}
2. The curl file is sending http request to drupal file to chek user authentication.Following is islogin\_drupal.php (contains curl functions for sending http request to different server)

```
   $username = $_REQUEST['username'];
   $password = $_REQUEST['password'];

   $data = array("username" => $username, "password" => $password);

   $data_string = json_encode($data);
   $url='http://localhost/drupal-test/testlogin.php';
   $ch = curl_init($url);
   curl_setopt($ch, CURLOPT_HEADER, false);
   curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
   curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
   curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Access-Control-Allow-Origin: *',       'Content-Type: application/json'));
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
   $result = curl_exec($ch);
   curl_close($ch);
   $json_result = json_decode($result, true);
   echo $json_result['res'];

```
3. I created a file in drupal root directory to check user authentication and return success/failure message.Here I used **user\_authenticate()** function.

```
$postdata = file_get_contents("php://input");
$string = json_decode($postdata);
$username = $string->username;
$password = $string->password;

//change this line and put your username and password instead of 'admin' and 'password'
$account = user_authenticate($username, $password);
if ($account) {
    $user = user_load($account, TRUE);
    drupal_session_regenerate();
    $token = 'sucess';
}
else {
    $token = 'error';
}

echo json_encode(array('res' => $token));

```
1. I created a new file in drupal root directory that is being called on success of ajax call. This file takes the username and password from query string and log in the user accordingly.

```
    //this gets the root of the drupal installation
    define('DRUPAL_ROOT', getcwd());
    //require the bootstrap include
    require_once './includes/bootstrap.inc';
    //Load Drupal
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    global $user;

    $account1 = user_authenticate($_GET['user'], $_GET['pass']);

    $user = user_load($account1, TRUE);
    drupal_session_regenerate();
    drupal_goto('http://localhost/drupal-test/');

```

---
Tags: users
---


# Question
Title: How to log user in to multiple drupal sites?
I have multiple drupal sites on the same server (VPS). Thise sites has separated d7 core and db. All sites has own domains: domain1.com, domain2.com, domain3.com..

When user logs in to one site I need him to log also in to the another site. This should be done in single sign on so user does not have to log first to one site and then to another.

How to automatically log user in to the both/multiple sites?

# Answer
You are looking for Multisite Login module

> Multisite Login allows a user to login to all sites in a multisite configuration, even though the multisites do not share domain names.
>
> NOTE: if you are using several sites on the same domain (ex. politicker.com, nj.politicker.com, ny.politicker.com, etc.), then you do not need this module. The multisite functionality in Drupal core has the ability to share logins for sites like these without additional modules.

also take a look at CAS module.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Array to string conversion in DrupalDefaultEntityController->cacheGet()
I have a content type that has a multi-value taxonomy field. When I create a new item and select several values, I am presented with the following error:

> Array to string conversion in DrupalDefaultEntityController-\>cacheGet() (line 369 of /path/to/drupal/installation/includes/entity.inc).

The values are saved and everything appears to be working, but having this error appear every time is a little distracting, especially for the office staff who are actually entering the data.

Why does this happen?

# Answer
There's a *very* quick fix already, posted several weeks later after IntegrityFirst's answer.

See https://drupal.org/comment/7812787#comment-7812787 and this patch: https://drupal.org/files/drupal7.entity-system.1525176-104.patch (thanks to Molot for link to core bug thread).

It turns out that there *is* a function in Drupal core that supports multidimensional array diff causing this bug, but it's just not used there.

So, fix is to replace `array_diff_assoc` (not recursive) with `drupal_array_diff_assoc_recursive` (recursive, as it comes from its name) at line 364 of `includes/entity.inc` (see `DrupalDefaultEntityController::cacheGet` if line number differs or if patch fails).
> 9 votes

# Answer
**Problem:**

Since PHP 5.4 this notice appears when an array is compared as the string "array". The problem is in the file includes/entity.inc in the method cacheGet which gathers items from a static cache.

On line 369 it uses array\_assoc\_diff which compares the array indexes and values and returns the difference of the two arrays. Unfortunately it doesn't do this recursively meaning if it is a multidimensional array it will use "array" as a string and compare it with the other array. This is what causes the notice to occur.

It seems that the code is flawed and not performing the proper function get a given item from the cache.

**First Solution:**

The first solution I came up with to resolve this issue was to loop through each item of the condition and use the key of the conditions to check if the entity value for that key isset. If it it isn't set then there is a difference. This would mean that the entities with that key would be unset. I don't like using nested foreach loops though this came to me as the most immediate solution to resolve the problem.

The fix was to replace lines 369 to 371:

```
if (array_diff_assoc($conditions, $entity_values)) {
  unset($entities[$entity->{$this->idKey}]);
}

```

With this piece of code:

```
foreach ($conditions as $key=>$values) {
    if (!isset($entities[$key])) {
        unset($entities[$entity->{$this->idKey}]);
    }
    elseif ($conditions[$key] !== $entity_values[$key])
    {
        unset($entities[$entity->{$this->idKey}]);
    }
}

```

**Second Solution:**

A second thought I've had is to add a new function that has a similar functionality as the php function array\_diff\_assoc except that it does the comparison recursively. While looking through the on-line PHP manual I found a function that would accomplish that.

Place this at top of entity.inc after the opening php tags:

```
function array_diff_assoc_recursive($array1, $array2) {
    $difference=array();
    foreach($array1 as $key => $value) {
        if( is_array($value) ) {
            if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
                $difference[$key] = $value;
            } else {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if( !empty($new_diff) )
                    $difference[$key] = $new_diff;
            }
        } else if( !array_key_exists($key,$array2) || $array2[$key] !== $value )     {
            $difference[$key] = $value;
        }
    }
    return $difference;
}

```

Replace what you see on line 369 from:

```
if (array_diff_assoc($entity_values, $conditions)) {

```

With this code:

```
if (array_diff_assoc_recursive($entity_values, $conditions)) {

```
> 5 votes

---
Tags: taxonomy-terms
---


# Question
Title: User 1 becomes anonymous on node/add, access denied messages
I had been developing a Drupal site locally and put it up online recently without much problems. Our server runs in PHP Safe Mode, but I've already got most of the website working nicely. The only weird thing that is happening now is that I, as the User 1/Admin with all permissions configured correctly and accordingly, have been unable to add any new nodes. I can manipulate views, add content types, change the appearance, use deltas and contexts, administer users, and do pretty much everything except add new content. I have been working around this by using Devel to generate some nodes, but this is clearly a flawed work flow. Oddly enough, I can view the list of current content and edit any node I please. I just get "Access Denied" when I got to http://www.example.com/node/add. For all content types. And they do show up in the administer menu, so I don't think it has anything to do with the content suddenly being unavailable.

Looking at the action/error log, I find that those "Access Denied" errors are happening to "Anonymous," even though I have clearly logged in. I have tried flushing all the caches, rebuilding permissions, and still no luck. I also tried making another admin account, and that user runs into the same problem. Does anyone know what this might be and how I can fix it? It's kind of important to be able to add content.

**EDIT: This is on Drupal 7.14**

# Answer
Those who come and find this question unsolved can use the solution at d.o which is

> Solved it!! It had to do with the .htaccess file! I needed to comment the following with regard to SSL Certificates.
>
> ```
> # SSL Certificates
> #  RewriteCond %{HTTPS} !=on
> #  RewriteRule (user|admin) https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
> #  RewriteCond %{HTTPS} !=off
> #  RewriteRule (node/*/edit|node/add/*) http://%{SERVER_NAME}%{REQUEST_URI} [L,R]
>
> ```
>
> I am not entirely clear on why it suddenly worked, but obviously it has something to do with these rewrite rules.
> 1 votes

---
Tags: users, sessions
---


# Question
Title: Count the number of content flagged by logged in user
I want to get the number of items (content) flagged by the logged in user.

```
<?php
  $flag = flag_get_flag('flag1');
  print $flag->get_count($nid);
?>

```

The above line would display the total number of times that content is flagged. How can i get number of items flagged by the logged in user. Lets say user A has flagged Content 1, Content2 and Content 3. Then the output needed is something as:

Number of Items flagged by \[current:user\]: 3

Thanks

# Answer
> 3 votes
This work for me in normal block (no in views):

```
<?php
global $user;
$uid = $user->uid; //Logged in user ID
$result = db_query("SELECT COUNT(*) FROM flagging WHERE uid=:uid and fid=2", array(':uid' => $uid))->fetchField(); //fid = ID your flag
print $result ." flagged items";
?>

```

# Answer
> 1 votes
This should work , untested:

```
$result = db_select('flag_content', 'fc')
->fields('fc', array('content_id'))
->condition('content_type', $flag->content_type)
->condition('uid', $user->uid)
->condition('fid', $flag->fid)
->execute();

$flagged = $result->fetchCol();
return array('content_flagged_by_user' => $flagged);

```

You could also try Rules integration with Flag

# Answer
> 0 votes
You can use this Flag API function: flag\_get\_user\_flags()

Suppose you want to get number of times `node A` was flagged by current logged in user:

```
$flag = flag_get_user_flags('node', 'NID_OF_A');

```

---
Tags: 7, users, flags
---


title: Always show next page link in pager

text:
# Question
Title: Always show next page link in pager
```
function mythemename_pager_next($text, $limit, $element = 0, $interval = 1, $parameters = array()) {
  global $pager_page_array, $pager_total;
  $output = '';

  // If we are anywhere but the last page
  if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {
    $page_new = pager_load_array($pager_page_array[$element] + $interval, $element, $pager_page_array);
    // If the next page is the last page, mark the link as such.
    if ($page_new[$element] == ($pager_total[$element] - 1)) {
      $output = theme('pager_last', $text, $limit, $element, $parameters);
    // The next page is not the last page.
    } else {
      $output = theme('pager_link', $text, $page_new, $element, $parameters);
      //$output = '<li class="custom-pager-next"><a class="active" href="javascript: void(0)"><img width="10" height="19" title="" alt="Previous" src="/' . path_to_theme() . '/img/pager-previous.png"></a></li>';
    }
  }

  return $output;

```

}

How to make NEXT PAGE link visible on last page? For example we have 3 pages and i am on the 3rd page and i should see NEXT page link. Please assist to me with function above, thanks!

# Answer
> 1 votes
The line

```
if ($page_new[$element] == ($pager_total[$element] - 1)) {

```

Will never fire because of the earlier line:

```
if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {

```

So if the current page is equal to (or higher) then the last page it will skip the whole code.

Try removing that line (and the corresponding closing bracket `}`). I hovever don't know if it will keep working then because the following function seems to be assuming it can never load a pager higher then the current page. So prepare for some unexpected behavior.

```
$page_new = pager_load_array($pager_page_array[$element] + $interval, $element, $pager_page_array);

```

---
Tags: 6, paging
---


# Question
Title: Behavior for #datepicker onselect not working
i have a datepicker in a webform. I want to be notified when a date is selected in the datepicker. In my form template i drupal\_add\_js a js starting with :

```
Drupal.behaviors.booking_form_tma = {
    attach: function (context, settings) {
        for (var id in Drupal.settings.date_popup) {
            alert('found');
            var datepicker_settings = Drupal.settings.date_popup[id].settings;
            datepicker_settings.onSelect = function(dataText) {
                alert('selected: ' + dataText);
            };
            $('#' + id).datepicker(datepicker_settings);
        }
    }
};

```

The behavior attach code gets called only once, after the page gets loaded and never reach the alert: i guess the datepicker is not present in the div at this time. When the datepicker icon is clicked, the datepicker gets injected in a div but the behavior is not called and so nothing happen. None of the alert in the code above are shown.

Why doesn't it work?

# Answer
> -1 votes
```
jQuery(document).ready(function() {
    jQuery(".datepicker").datepicker({
        showOn: "button",
        buttonImage: "/images/calander.png",
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        maxDate:'0',
        onSelect: function (selectedDateTime){
                //alert("here");
            }
    });
 });

```

you can also write above code in js file

---
Tags: datetime, javascript
---


# Question
Title: How to use PHP Evalution in rules scheduling
I have a rules component that i want to trigger on specific time that is set by end user. in my case i have a form where user create rental property and select the rent date there. then i have another form of alerts where user can set alerts related to rentals. like user wants alert before 2 days of rental date. I am able to set the rental date but unable to get the value of alerts section to check what value the end user has set to get an alert. I tried to put sql query in 'PHP Evaluation section' but in scheduling section it shows the blank date. Rule that i have creatrted:

component: Schedule reminder to end user Rule: Schedule rental alerts action: schedule component evaluation data-selector:node:field-rental-start-date php evaluation: $query = db\_query("SELECT field\_days\_before\_the\_rent\_value FROM field\_data\_field\_days\_before\_the\_rent"); foreach($query as $result){$res = $result-\>field\_days\_before\_the\_rent\_value;} return $value - $res;

Please help me here how i can get the field\_days\_before\_the\_rent\_value.

# Answer
After struggling so many days I found the solution that how we can do scheduling using php evaluation. To do this I have simply pick the value in data selector(under my rule) that is set by user in his rental form as shown in my 1st screen short. Now I need to schedule that rental date according to the alerts set by user in alert section (screen short2) where i was stuck.Under PHP evaluation section we have to use $value variable that returns the value that we selected in data selector.In case of dates it returns the timestamp not the actual date. So then I used PHP code to add/substract the days according to the user set in alert section and succeed to do scheduling.

I hope it will helpful for others.
> 1 votes

---
Tags: 7, rules
---


title: Can't change add to cart button value

text:
# Question
Title: Can't change add to cart button value
I can't change 'Add to cart' button value (site http://zoo812.ru)

Now it is value="Добавить в корзину", I want to change it to value="buy"

I inserted

```
function ivanco_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
    $form['submit']['#value'] == t('Buy');
}

```

in template.php, but it does absolutely nothing.

String overrides also doesn't work.

There is no js code linked with it nor any other mentions about it in theme files.

You see, there is Catalog View, and each item's displayed with Evo.

I can do this with JS of course, but it wont be elegant..

# Answer
> 3 votes
I've used this code and worked fine:

```
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['submit']['#value'] = 'CUSTOM BUTTON VALUE';
    //dpm($form);
  }
}

```

---
Tags: views
---


# Question
Title: restrict to subdirectory not work and media module load all images in public://
I use a media module to select file from library, in field option on my field I specify a custom sub directory(it's name is `gift_cards`) that I have been created in public path. but when the media file selector popup triggered I see all images instead images that on `gift_cards`. where is the problem, and how can I restrict my custom field to load only image that are in `gift_cards` directory?

one suggest is using filedeop module , but I don\`t want use this module (this is big module with more feature but my needs is something tiny) , restrict to show only custom sub directory in public://

# Answer
# Option 1

Media Browser Plus module states that it will allow

> Personal and public “folders”

Which might answer to your needs

# Option 2

Views Media Browser should allow you to specify a view to use as the media browser - you could then filter the view based on file path or other file attribute to get the result you are after.

# Option 3

If you are using v2 of Media module you can apparently define a View with a 'views media browser' display to create your media module listing. Media module 2.x is currently in alpha, so take care if you wanted to go down this route, and obviously do not test on live site.

see https://drupal.org/node/1547884
> 3 votes

---
Tags: 7, nodes, media
---


# Question
Title: How to order unions separately in db_select?
I have a UNION query, where the second part of the UNION should be ordered separately, not the complete UNION.

The resulting query should look like this:

```
(
  SELECT id, fname FROM tab1 WHERE fname = 'Frank'
) UNION (
  SELECT id, fname FROM tab2 WHERE lname = 'Sinatra'
  ORDER BY fname DESC
)

```

My question is: How can I order the second part of the UNION? I know, I could use a db\_query, but I'd like to join this db\_select in another db\_select. And I think I cannot join an executed db\_query result and a db\_select object.

Here is my current code:

```
$subquery1 = db_select('tab1','t1');
$subquery1->fields('t1',array('id','fname');
$subquery1->where('fname=:fname',array(':fname'=>'Frank');

$subquery2 = db_select('tab2','t2');
$subquery2->fields('t2',array('id','fname');
$subquery2->where('lname=:lname',array(':lname'=>'Sinatra');
$subquery2->orderBy('fname','DESC');

$subquery1->union($subquery2);

$result = $subquery1->execute();
...

```

The resulting query is:

```
(
  SELECT id, fname FROM tab1 WHERE fname = 'Frank'
) UNION (
  SELECT id, fname FROM tab2 WHERE lname = 'Sinatra'
)
ORDER BY fname DESC

```

# Answer
> 2 votes
I found the answer not in Drupal, but in MySQL:

I added a new column to the subqueries with an indicator of the query. The first sub query has the sort column value "0\_" and the second one "1\_".

Here is the drupal db\_select code:

```
$subquery1 = db_select('tab1','t1');
$subquery1->fields('t1',array('id','fname');
$subquery1->where('fname=:fname',array(':fname'=>'Frank');
$subquery1->addExpression("'0_'",'sort_column');

$subquery2 = db_select('tab2','t2');
$subquery2->fields('t2',array('id','fname');
$subquery2->where('lname=:lname',array(':lname'=>'Sinatra');
$subquery2->addExpression('1_','sort_column');
$subquery2->orderBy('sort_column', 'ASC');
$subquery2->orderBy('fname','DESC');

$subquery1->union($subquery2);

$result = $subquery1->execute();
...

```

# Answer
> 0 votes
I don't know this will help, but you can try:

```
$subquery1 = db_select('tab1','t1');
$subquery1->fields('t1',array('id','fname');
$subquery1->condition('t1.fname', 'Frank')

$subquery2 = db_select('tab2','t2');
$subquery2->fields('t2',array('id','fname');
$subquery1->condition('t2.lname', 'Sinatra')
          ->orderBy('t2.fname','DESC');

$query = Database::getConnection()
  ->select($subquery1->union($subquery2))
  ->fields(NULL, array('id','fname'))

```

---
Tags: database
---


# Question
Title: Do I have to create a module for just one _alter function?
I want to write a hook\_entity\_info\_alter function.

Do I have to create a module just for this one function?

# Answer
> 2 votes
No...

All alter hooks are also run for themes, so you don't have to create a module.

e.g.

```
function MYTHEME_entity_info_alter(&$info) {
  // ...
}

```

---
Tags: 7
---


title: How can I theme Media fields?

text:
# Question
Title: How can I theme Media fields?
I use Media + File Entity projects.
I have content type with field\_media\_picture (widget: Media file selector) which then connected with Media image file.
The Media Image file type has field\_picname (text).
I've Managed display for the Media Image file type to display: image file and field\_picname.
I've created field--field\_media\_picture.tpl.php:

```
<?php print render($items);?>

```

This code show image + field\_picname. It's OK.

But how can I get these fields (image and field\_picname) separately in PHP?
I want to theme these fields individually.

# Answer
I've themed these fields through code:

```
<?php
hide($items[0]['field_picname']);
print render($items);
print render($items[0]['field_picname']);
?>

```

But I'm not sure the code is the best.
> 1 votes

---
Tags: theming, media
---


# Question
Title: How do I export nodes into separate XML files?
I have used Views Data Export to create XML files of the nodes and can filter and limit them as i wish. However, I need to create a separate XML file for row/node rather than have them combined in a single XML file/feed.

In addition to that ideally the file name should match the value of a certain field.

How do I go about it?

My first thoughts are to either: 1) Create a new module reads an XML feed created with Views Data Export and then parses the data and makes a new file from each item and uses the value of the ID field to name the file 2) Make a modified version of views data export and insert some code that would create a file for each record rather than a new row in a doc.

Is there a better 3rd option or module that already does this? If not which of the two options will be easier/best?

**Example current output in single file:**

```
<file_information xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <asset_data>
    <upn>SOMEID123</upn>
    <title>Some title 1</title>
  </asset_data>
  <asset_data>
    <upn>SOMEID124</upn>
    <title>Some title 2</title>
  </asset_data>
</file_information>

```

**Desired output:**

File name someid123.xml

```
<file_information xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <asset_data>
    <upn>SOMEID123</upn>
    <title>Some title 1</title>
  </asset_data>
</file_information>

```

File name someid124.xml

```
<file_information xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <asset_data>
    <upn>SOMEID124</upn>
    <title>Some title 2</title>
  </asset_data>
</file_information>

```

This is for internal project that only 2 people will ever use and is just to cut down on the amount of mindless manual copy and pasting so doesn't need to have optimum performance or handle many hits/vistors. The process will be import spreadsheet with many records export an xml file for each record. Whether these files get written to disk or download to user doesn't matter.

Thanks for any tips/advise

# Answer
> 0 votes
I wrote a script to parse the XML and split each of the nodes, add the header and footer xml, save them in separate files, zip them up and then provide a download link. Works pretty well but does add an extra step to the output.

---
Tags: views, feeds, importing-exporting
---


title: Main Menu Tab Help

text:
# Question
Title: Main Menu Tab Help
I am able to add a new tab in the Drupal Main Menu however I only want it to display when a user logs in. In other words this tab should not appear on the site until a user is authenticated.

Thanks

# Answer
You can create another menu and set access to it in User Permissions
> 0 votes

# Answer
You can go to your page.tpl.php where you print your menu and surround it with this code :

```
    <?php
    global $user;
    if ( in_array('authenticated user', $user->roles))
    {
        // print your menu
    }
    ?>

```

This hides the menu if the user is not logged in.

I hope it helps you.
> -1 votes

---
Tags: 7, routes
---


# Question
Title: Script for collecting all translatable strings in the codebase?
I have hundreds of strings in my code-base that which translation i.e. strings inside **`t()`** function.

Is there a script that can traverse through my code-base and collect all the strings and export them to an excel file?

Or else, Is there any other way?

# Answer
By default, every string you wrap in the t() function is going to be added to the localization database by the core Drupal locale module as soon as Drupal encounters the occurrence. You can then use the translation interface to search for these new strings and update them manually or export a Gettext Portable Object Template file

http://example.com/admin/config/regional/translate/export

These files are in text format and easily editable by non-technical users, ex:

```
#: misc/tabledrag.js
msgid "Hide row weights"
msgstr ""

```

There are a number of tools available for working with gettext files, I would recommend the Localization client module for doing this work within the Drupal interface. There is also an option to convert these files to excel and back using csv2po but I haven't used this:

http://docs.translatehouse.org/projects/translate-toolkit/en/latest/guides/using\_csv2po.html
> 1 votes

---
Tags: 7, i18n-l10n
---


title: programmically change price of product

text:
# Question
Title: programmically change price of product
I want have a product that user can change the price of it to custom ,I want programmically change the price of product when user submit a custom form with entered price.

my require is I want to have product that according to entered value by user ,product price change and then add to his/her `cart`. really I dont know how can I achieve it. appreciate any urgency help

# Answer
> 0 votes
I found simple method, load product and then update product:

```
  $product = commerce_product_load((int)$product_id);
  $product->commerce_price_usd["und"][0]["amount"]=$price;
  commerce_product_save($product);

```

# Answer
> 3 votes
I suppose the existing answer is fine if every customer gets a unique version of the product to purchase. However, it should be obvious that if more than one person uses this it would fail.

You should instead look at what we recommend in this video tutorial:

http://www.drupalcommerce.org/videos/tutorials/donations-custom-line-item-types

The main idea is that you can enrich the line item with custom pricing information and then use the product sell price calculation system to swap in the appropriate custom price.

---
Tags: commerce
---


# Question
Title: Anonymous users randomly get 404 errors on front page
I have a drupal 6 site that will occasionally serve up a 404 error to anonymous users on the home page only. It happens 2 or 3 times a day and I cannot figure out what is causing it. I can clear it by logging in and flushing the cache, or going to site information and re-saving that form.

We are using the mobile tools module which I thought might be conflicting somehow, but I can't find any issues in the issue queue related to this. We are using caching, but it's just standard drupal caching.

I've also tried checking the server logs and watchdog and I can't find anything useful. Does anyone have any ideas?

# Answer
It looks like it was due to a permissions issue. I set all files and folders to the correct permissions and it seem to fix the issue.

I also updated to the latest dev version of the mobile tools module.
> 0 votes

---
Tags: theming, 6
---


# Question
Title: How to build and embed the output of a Message entity created by the Message module?
I need to, given the `mid` (= Message ID), generate the Message content for a specific view mode. How can I do this?

It seems to be complicated by the fact that a Message is an entity (created by the Message module), and there are multiple Message types, each of which have their own fields and rely heavily on tokens.

I'm hoping for something simple like:

```
$message = message_load($mid, $view_mode);
$output = drupal_render(entity_view($message));

```

... but everything I've found that loads Messages seems to rely on weird wrappers and stuff and I haven't been able to find a working solution no matter how much I tinker with it.

# Answer
there's a better one:

```
$build = $message->buildContent('my_view_mode');
$output = drupal_render($build);

```
> 1 votes

# Answer
Got it.

```
$message = message_load($mid);
$build = $message->view();
$build += array(
  '#theme' => 'message',
  '#entity' => $message,
  '#view_mode' => 'full',
);
$output = drupal_render($build);

```
> 3 votes

---
Tags: 7, entities, message-subscribe
---


# Question
Title: Fatal error: Cannot redeclare MYTHEME_preprocess_page()
I'm new at Drupal, so please help to solve the problem. :) I've found an article: Change templates based on path alias

It describes my situation. But when I include described code or just this line:

```
function lm_sr4_preprocess_page(&$vars) {}

```

In mywebsite.com/sites/default/themes/lm\_sr4/template.php it just causes this error:

Fatal error: Cannot redeclare lm\_sr4\_preprocess\_page() (previously declared in /var/www/sites/lmsr2.video-site.ru/sites/default/themes/lm\_sr4/template.php:11) in /var/www/sites/lmsr2.video-site.ru/sites/default/themes/lm\_sr4/preprocess/page.preprocess.inc on line 10

Here's all template.php code:

```
<?php

/**
 * @file
 * Template overrides as well as (pre-)process and alter hooks for the
 * lm_sr4 theme.
 */

function lm_sr4_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'ep') {
    $vars['theme_hook_suggestions'][] = 'page__epcustomtemplate';
  }
}

function lm_sr4_views_tree_inner($variables) {

  $view = $variables['view'];
  $options = $variables['options'];
  $rows = $variables['rows'];
  $title = $variables['title'];
  $result = $variables['result'];
  $parent = $variables['parent'];

  $items = array();
  foreach ($result as $i => $record) {
    if ($record->views_tree_parent == $parent) {
      $variables['parent'] = $record->views_tree_main;
      $items[] = $rows[$i] . call_user_func(__FUNCTION__, $variables);
    }
  }
  return count($items) ? theme('item_list', array(
    'items' => $items,
    'type' => $options['type'],
    'attributes' => array(
      'class' => array(
        'menu',
      )
    )
  )) : '';
}

function lm_sr4_omega_layout_alter(&$layout) {
  if (arg(0) == 'eparchies') {
    $layout = 'eparchy';
  }
}

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

# Answer
> 3 votes
You have the function `lm_sr4_preprocess_page()` declared twice; once in template.php (line 11) and once in preprocess/page.preprocess.inc (line 10).

You need to merge those two functions together, you can only declare a function once in PHP.

# Answer
> 1 votes
The error said you are use function name as name used by another fucntion `Fatal error: Cannot redeclare lm_sr4_preprocess_page() (previously declared in /var/www/sites/lmsr2.video-site.ru/sites/default/themes/lm_sr4/template.php:11) in /var/www/sites/lmsr2.video-site.ru/sites/default/themes/lm_sr4/preprocess/page.preprocess.inc`

**you just need change you function name and every thing work correctly. :)**

---
Tags: theming
---


# Question
Title: How to perform a REST request after a node created using rules?
I have a backend service written by Python, which is exposed a JSON api. And I want drupal to perform an HTTP POST/PUT/PATCH/DELETE... request with json data (which is an output of a node) to the backend when a node have been created/modified/deleted.

I think that rules module should do this job. The trigger part and condition part are ok, but I can't find a suitable action part.

I hope to find a module that provides some rule actions, is able to let me define the JSON structure being used (using token etc.), is able to perform an HTTP request(GET/POST/PUT/DELETE) and let me handle the response (notify users or save to a status field).

When I google solutions, I only found two possible modules:

But it seems not support authorization (OAuth/HMAC/token/...), and the data has to be HTTP query string (?name=value&name2=value2&...).

This is a very powerful module, allows to define a series of actions: transform a node to a data structure and save as a variable, call http request with the variable and save the response as a result variable, handle the result at last. BUT, it only supports GET method (only option), query string, and no HTTP headers.

With these modules, I can work out a backup solution: my backend service may supply an endpoint that handles formed data, or supply an endpoint that receives a node id then make a HTTP request callback to Drupal (with services module).

Do I miss any module that do similar thing? Or is there any better solution?

P.S.: I'm not familiar with PHP, so I don't want to write any PHP code.

# Answer
> 1 votes
Guzzle is similar to Web Service Client and there is also Web Rules but I assume Guzzle would require some coding. Guzzle is a powerful HTTP client and library and itself can do whatever you want.

The reason there are few user interfaces to what you want is that they're annoying to build and add next to nothing to your client website. The UIs dont make the website any faster, they're just bloat.

This is why Views and ViewsUI are decoupled so you can turn 1 off in production environments.

---
Tags: rules, 8, actions
---


# Question
Title: How to create a pie chart of user points and taxonomy terms?
I have 3 terms in `Taxonomy > User Points`: *Articles*, *Comments* and *Favorites*. I created some rules to grant user points of one of these categories, based upon the users' actions. So far, everything works fine.

Now, I'd like to create a pie chart of the user points per category for the profile pages. For example, such a pie chart might look like this:

How can I achieve this?

---

**Edit:** I'm working with User Points 7.x-1.0.

# Answer
> 1 votes
There are a number of chart modules for drupal.

If you used the charts module, it has views integration, so assuming you are using the user points module, and that user points has view integration, you should be able to create a view with items grouped by term and display as a chart.

## *Update*

Replicated your environment as above, updated the userpoints module to 7.x-1.x (dev), installed charts module (and included google charts module to test), constructed view of userpoints with contextual filter on user and the chart works perfectly! Thanks for asking the question, I have suddenly thought of loads of places I could use similar graphic incentives.

Here is the exported view - in this example it uses taxonomy terms article, page and comments:

```
$view = new view();
$view->name = 'points_chart_userpoints';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'userpoints';
$view->human_name = 'points_chart_userpoints';
$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'] = 'userpoints table block';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$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'] = 'chart';
$handler->display->display_options['style_options']['library'] = '';
$handler->display->display_options['style_options']['label_field'] = 'tid';
$handler->display->display_options['style_options']['data_fields'] = array(
  'points' => 'points',
  'tid' => 'tid',
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'points' => '#2f7ed8',
  'tid' => '#0d233a',
);
$handler->display->display_options['style_options']['width'] = '';
$handler->display->display_options['style_options']['height'] = '';
$handler->display->display_options['style_options']['xaxis_labels_rotation'] = '0';
$handler->display->display_options['style_options']['yaxis_labels_rotation'] = '0';
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['label'] = 'no points';
$handler->display->display_options['empty']['area']['empty'] = TRUE;
$handler->display->display_options['empty']['area']['content'] = 'no points found';
$handler->display->display_options['empty']['area']['format'] = 'filtered_html';
/* Relationship: Userpoints: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'userpoints';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Userpoints: Current points in category */
$handler->display->display_options['fields']['points']['id'] = 'points';
$handler->display->display_options['fields']['points']['table'] = 'userpoints';
$handler->display->display_options['fields']['points']['field'] = 'points';
/* Field: Userpoints: Points category */
$handler->display->display_options['fields']['tid']['id'] = 'tid';
$handler->display->display_options['fields']['tid']['table'] = 'userpoints';
$handler->display->display_options['fields']['tid']['field'] = 'tid';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Chart (block) */
$handler = $view->new_display('block', 'Chart (block)', 'block');

/* Display: Table (block) */
$handler = $view->new_display('block', 'Table (block)', 'block_1');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'points' => 'points',
  'tid' => 'tid',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'points' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'tid' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;

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

```

---
Tags: 7, taxonomy-terms, users, userpoints, charts
---


# Question
Title: Create a panel with related group content based on a view
I'm using groups (Drupal 7) and have set up panels to show related content for each group. So that if I look at a particular group node it also shows associated group news items, members, etc. The main content is the group body field.

I now want to show a view that displays a list of related content (group messages) for a group as the main content. This should also show the associated group members and news items in a related pane, as it does in the main group panel. I can't see how I can relate the group to the view. It is straightforward to relate the view to the group but not vice versa.

Is it possible to relate the group to the view based on an argument in the path? When I create a new panel the contextual options are all about the node being viewed or the group, but nothing for views or the path.

Or alternatively, is it possible to add a variant to the main group panel page that shows the view I want to display instead of the group body field? How could I create a different context for this? Would it be possible to do it using a path?

Many thanks in advance,

Ben

# Answer
You need to setup an extra relation (you can use the default provided og content view). The relation should be: OG membership: Group Content from OG membership The Content group that is associated with the OG membership.

The relation in that one should be OG Membership from node.

Then you can add fields to content as you would, and you can choose Group node from OG membership as a relation. This is how you can pull all info from the main group node.
> 0 votes

# Answer
> Is it possible to relate the group to the view based on an argument in the path?

Yes, it is. In the view, in the contextual filters select the radio button "Provide default value", there you can decide which kind of field you want to give. If you want to get the path you should select "Row value from url" and then choose the "path component" (The numbering starts from 1, e.g. on the page admin/structure/types, the 3rd path component is "types".)

I hope this helps you.
> 0 votes

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


# Question
Title: With a 'review' node type and a node reference to a 'product ' node type limit number of user reviews to one
In a **product** node type with a **review** node type that has a reference field to it, how do I only permit one review per user per product node? Do I use the Rules module and if so how do I configure the rule? Do I make a custom query and then unset the Add Review button/link on the product node in a custom module or in template.php?

(edit) Take the example of product reviews on Amazon or muffler repair reviews on Yelp. The user who makes the review gets one review per listing or item. After they create the review, they can edit it but can't make another one for that listing or item. Seems logical. Likewise the Fivestar rating widget only allows one vote per item so having several reviews for an item will not permit more than just one Fivestar rating.........

Unless somebody has a better solution, I'm going to test -- since the Fivestar widget makes the database query anyway -- if it has been set by the user on the node view. If true then I will disable the Node Reference URL widget button in the links area. If I need more security, I will create code or a Rue that tests on the Node Add page if the Fivestar widget has already been set to disable the Node Add page and redirect the user back to the product.

# Answer
> 3 votes
You might need to try a custom module for this. Rules are too generic as you can only control a user's right to create a type of content. If I was to write a module for this, it would go something along these lines:

• Use hook\_form\_alter to add an extra validation function to your Review node form • Check if the user has submitted a review before in the db • Throw an error if a record exists in the database

Something like the following code should work, but this is untested.

**Edited to note that this is Drupal 6 code but if you use it as a template it shouldn't be too far away.**

```
<?php

function MYMODULE_form_alter($form_id, &$form) {
    // If the form is a "review" node form
    if ($form_id == 'review_node_form') {
        // Add an extra validation function
        $form['#validate'][] = 'MYMODULE_user_node_limit';
    }
}

// Validation function
function MYMODULE_user_node_limit($node) {
    // Get our logged in user's details
    global $user;
    // Run a database query (something like this)
    $sql = "SELECT {node}.uid \n"
    . "FROM {content_type_review}, {node} "
    . "WHERE {content_type_page}.field_node_ref_nid = {node}.nid "
    . "AND {node}.nid = %d"
    . "AND {node}.uid = %d";
    $result = db_query($sql, $node->nid, $node->uid);
    if ($result === FALSE) {
        // Throw error
        drupal_set_message('You have already submitted a review of this item.', 'error');
    }
}
?>

```

**Edited to answer additional comment by asker**

Regarding the comment made by Adam S - you could use the code I have already posted in conjunction with the Drupal 7 equivalent of Drupal 6's hook\_nodeapi. Here is a list of Drupal 7's node hooks for you to have a look at. Also, have a look at Eric London's Drupal 6 example of a problem similar to yours of limiting a user's node writing privileges. Apologies for not providing an exact Drupal 7 example but if you follow the basic premise of Eric London's link but modify it in conjunction with my code, you should be able to solve your problem.

# Answer
> 1 votes
For what it's worth, I took a slightly different approach that might be useful. It isn't perfect, but works very well for me. I borrowed heavily from the solution here:

How to limit a user to one vote when using Fivestar?

But I didn't like changing my theme. I wanted to to it in the form alter, as I wanted to control things before they got to the browser (so other #validate solutions weren't right for me). Anyway, here is my approach:

```
<?php
function MYMODULE_form_alter($form_id, &$form, $form_id) {
    switch($form_id) {
        case 'comment_node_product_form':  //Modifications to the voting for five star on comment forms
            MYMODULE_fivestar_limit_votes($form);
            break;
    }
}

/**
 * Function to limit votes on a particular node to one per user.  Also requires users to be logged in to vote.
* This assumes that you are passing in a node as the entity for which the vote is recorded.  That little bit would
* of course be more flexible if done differently.
*
* @param unknown $form
* @param string $voteTag
* @param string $entityType
*/
function MYMODULE_fivestar_limit_votes(&$form, $voteTag = 'rating', $entityType = 'node') {
    $path = drupal_get_path('module', 'fivestar');
    // These are likely added already, but no harm done just in case
    drupal_add_js($path . '/js/fivestar.js');
    drupal_add_css($path . '/css/fivestar.css');
    $replacement = false;
    $is_login = user_is_logged_in();
    $nid = $form['#node']->nid;

    $rating = votingapi_select_single_result_value(array(
        'entity_id' => $nid,
        'entity_type' => $entityType,
        'tag' => $voteTag,
        'function' => 'average',
    ));
    $lang = $form['field_product_rating']['#language'];
    $widget = $form['field_product_rating'][$lang][0]['rating']['#widget'];
    if ($is_login) {
        if (isset($rating)) {
            $voting_message = "<div>You have already rated this.</div>";
            $replacement = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => $voteTag, 'widget' => $widget)) . $voting_message;
        }
        // The 'else' here is to leave the form alone.
    }
    else {
        $fivestar_links = l('Login', 'user/login') . ' or ' . l('Register', 'user/register');
        $voting_message = "<div>Only registered user can rate this content type.<br/>$fivestar_links to rate this content type.</div>";
        $replacement = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => $voteTag, 'widget' => $widget)) . $voting_message;
    }
    if ($replacement) {
        $form['field_product_rating']['#type'] = 'markup';
        $form['field_product_rating']['#markup'] = $replacement;
        $form['field_product_rating']['#tree'] = false;
        unset($form['field_product_rating']['und']);
    }
?>

```

---
Tags: 7, nodes, rules
---


# Question
Title: Need way semi complex way to display author posts in views
So I have an interesting request and I'm hoping some of you guys here might know a decent way to solve this. On one of our homepages we have a block that shows current authors posts. This was a simple view that just showed authors posts sorted by date. However now they want something a bit more specific detailed below.

In stead of just random posts, the first request is that is shows 5 post but of each post they should all be a specific author and NOT repeated in any way. For instance you have Author A, B, C, D , and E. The view would look like this.

A = His/her latest post

B = His/her latest post

C = His/her latest post

D = His/her latest post

E = His/her latest post

So each highlighted author shows their latest post and none of those authors repeat.

The next thing they want is an ability to pick and choose WHO those top 5 authors will be. So one week it might be A, B, C, D, and E; but they next week it could be F, A, H, J, and Y. This seems like a fairly complex view and not to mention the interfaced required for the UI portion. Thoughts?

# Answer
If you're marking stuff to include in some front page view of recent stuff this way I would just make a Nodequeue and let staff pick the items in that listing by hand. When you say "i want to pick them ..." you basically are throwing automation out the window.

If you really wanted to you could make a `SmartQueue` with your sql SELECT statement to do the automated logic -- the nodequeue UI would still allow overriding of the automatic generated list by your site users.
> 2 votes

# Answer
~~It looks like you might want to use views\>advanced\>other **aggregation** to make the posts **distinct** on the author field.~~

## Summary

Create a view of nodes that displayed recent posts by selected authors, then ensure that each author did not repeat by making them distinct.

To allow the site administrators (or other users by role) to *select* authors I would suggest using a flag to indicate the top authors. You could then sort the view by the flag date (make sure you create a relationship to the flag) and limit the view to 5 results

## Solution (updated)

To 'filter by distinct', install views\_distinct module, and in your view of recent nodes by selected author, set a filter (in author uid field settings) based on the author uid field:

Here is an export of an example view of article nodes (does not include flag selection for portability):

```
$view = new view();
$view->name = 'drupal_answers_97449';
$view->description = 'http://goo.gl/gQLr2A';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'drupal answers 97449';
$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'] = 'Top 5 authors';
$handler->display->display_options['use_more_always'] = FALSE;
$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['query']['options']['distinct'] = TRUE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$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',
  'name' => 'name',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Author uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'node';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['label'] = 'author';
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* 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'] = 'post title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

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

```
> 4 votes

---
Tags: views, 7, chaos-tool-suite
---


# Question
Title: Drupal 6: Move the 'Add new comment' link to the bottom
Like the subject says. I'd like to move the 'Add new comment' link to the bottom of the comment list. The only thing we're using them for a is a forum, and this is how we want them set up. I can't seem to find out to move this section in the template.

# Answer
> 0 votes
Since Drupal is such a highly configurable system, there are a few ways to accomplish what you want. Here's just one example.

The first part of the equation is to remove the link from the node's links array. This approach removes it during the theme call.

```
<?php
/**
 * Override theme_links() so we can remove or alter any links we don't need.
 */
function MYTHEME_links($links, $attributes = array('class' => 'links')) {
  unset($links['comment_add']);

  // Rather than include all the original theme_links() code in this function,
  // we can just call it directly here.
  return theme_links($links, $attributes);
}
?>

```

After that, you have a few options of where to readd the link. The primary function that builds the display for comments and comment controls is `comment_render()` in `comment.module`. It builds the comments display using a few different theme calls, so it's up to you where you want to add the link back in. Probably the easiest approach is to copy the file `/modules/comment/comment-wrapper.tpl.php` into your theme folder and add the code for the link there. Alternatively, you could either put it above or below the comment controls form (by overriding `theme_comment_controls`), or by overriding any of the other comment theme functions. Whichever approach you take to adding the link back in, you can get the code for the link from the `comment_link()` function -- open up `comment.module` and search for "Add new comment" to find the link code.

Good luck!

---
Tags: 6, theming, comments
---