# Question
Title: do the sum of two commerce_price field with programming api
I want to do the sum of two commerce\_price fields and set the result in another one.

i've tried to just add the related \['amount'\] values and set the result into another price field but it looses the components (VAT, taxes...).

Is there a commerce api call to do that ? Such as :

```
add_price($price1,$price2)

```

returning the full added price with all it's component ?

Thx

# Answer
There is no basic price addition function, though we have API enhancements on the roadmap for Commerce 2.x. I'd take a look at what commerce\_order\_calculate\_total() is doing to figure the order total price field; you have to sum the amounts, like you've already discovered, and you then use commerce\_price\_components\_combine() to merge the two price fields' components arrays together. Hope that helps!
> 0 votes

---
Tags: commerce
---


title: How to get the path of a drush command?

text:
# Question
Title: How to get the path of a drush command?
I'm creating a starter kit for the Panopoly distro that will generate a skeleton distribution using Panopoly as a base distribution. I'm doing this with a custom drush command. The code can be seen here.

I'm using a STARTERKIT folder that contains all of the code that will be copied and go through string/token replacements. The drush command is working well however what I'm unable to figure out is how to programmatically figure out where the STARTERKIT folder is. Right now I'm relying on the user entering --include=path/to/drush.command option.

Assuming the user copies the whole project to their ~/.drush folder they can run the drush command without the --include attribute but then my command does not know where the STARTERKIT folder is.

Here is where I'm using the --include option to locate the STARTERKIT folder.

# Answer
> 1 votes
You could make a wrapper script panopoly\_starter\_kit.sh, and determine the path to the script via `$0`. Your script would then just run your drush command, supplying the --include variable. See the drush script for an example of how a bash script can find the directory that the script itself is located.

**UPDATE:**

Another option would be to use a Drush script instead of a Drush command to do your installation. You would lose your help output, but you could still process arguments and options. See `drush topic docs-examplescript` for details.

---
Tags: drush
---


# Question
Title: Adding a final review page to entityform, before submit
I have a complex entityform, where I'd like the user to see what has been entered on a final "review" page, before the data is written away.

As far as I can see the preview page, on entityforms, is shown AFTER the data is saved.

Can this be achieved?

So to be clear..

Step 1 : User enters data into form, and clicks "Review"

Step 2 : User sees all the data nicely presented, and clicks "Confirm", or "Edit"

Step 3: If Confirmed, data is written away, otherwise go to Step 1

# Answer
Rob, I created Entityforms.

> As far as I can see the preview page, on entityforms, is shown AFTER the data is saved.

Actually when the "preview" page is shown the submission hasn't been saved yet.
> 0 votes

---
Tags: 7, entities
---


title: How to reuse query conditions?

text:
# Question
Title: How to reuse query conditions?
I have a semi-new Drupal 7 site in which admins approve the accounts of managers, and managers approve accounts of their employees. That's all working great. I've been asked to make it so that managers can delete the employee accounts that are no longer needed.

Using our old CMS, when all of our SQL was hand written I could build a "where" statement like :

```
$cWhere = "WHERE e.department = 'HR' and e.manager = 12345"

```

These items are not user entered, but based on the logged in person. To show a list of employees I could run :

```
"SELECT * FROM users " . $cWhere

```

Then to delete I could run :

```
"DELETE FROM users " . $cWhere . " AND uid = " . $deleteUser

```

This would ensure that the person who is logged in and trying to delete a user had the permission to do it, because the additional conditions of manager and department were checked. Furthermore, if the conditions for the employee list are changed, the delete code is automatically updated to take the new conditions in to account with no additional work needed. For the record, the query is considerably more complex than that, but no reason to make the question harder than it needs to be.

Now I'm doing everything with db\_select. So I build the query to show the list of users. I need an additional query to check that the logged in user has permission to delete the target user. Then I would call the user\_delete() function. Is there any way to do this, or do I have to rebuild the query completely a second time?

Non-working code, but something like this :

```
if (isset($deleteUser))
{
   $chkUser = $query; //$query is an existing db_select that hasn't been ran yet
   $chkUser->condition('u.uid', $deleteUser, '=');
   $rowsUser = $chkUser->execute();
   if ($rowsUser->rowCount() == 1)
   {
       user_delete($deleteUser); //user has permission
   }
}

$result = $query->extend('PagerDefault')->limit(20)->execute();

//... loop results, output list ...

```

Note, I have tried the above with the user\_delete() commented out... but $chkUser is obviously a pointer to $query, as the list printed ends up being just the user in question. So everything works the way I need, except I've mangled my user listing query doing it this way.

# Answer
> 1 votes
You can use the function `db_and()` an `db_or()` to compile condition sets that you can the add to an existing query like this:

```
$query = db_select('Exhibitors', 'e');
$db_and = db_and();
$db_and->condition('ProductCategory', array(1,2,3), 'IN');
$db_and->condition('status', 'active');
$query->condition($db_and);

```

Example taken form here: https://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_and/7

Other than that, there is the DatabaseCondition Class that might be interesting for you too.

---
Tags: 7, database
---


# Question
Title: I can't get my module to show up in the Navigation
I'm trying to create a custom module that has a block with a form in it. I'm able to install my module, and even add the block to the content area of the site, showing my form on every page of the site. But for some reason the page I set as the form's page won't show up in the navigation, and when I try to type in the pages address to get to it, it says the page is not found.

```
<?php
require_once('/includes/functions.php');
/**
 * @file
 *
 */

 /**
 * Implements hook_block_menu()
  */

 function search_engine_menu() {
    $items = array();
    $items['results_page'] = array(
        'title'         => 'Search Results',
        'page callback'     => 'search_engine_results_page',
        'access callback'   => TRUE,
        'type'          => MENU_NORMAL_ITEM,
    );

 }

 /**
 * Implements hook_block_info().
 */

 function search_engine_block_info() {
     $blocks = array();
     $blocks['search_engine'] = array(
        'info' => t('Search Engine'),
        'cache'=> DRUPAL_CACHE_GLOBAL,
        );

    return $blocks;
 }

 /**
 * Implements hook_block_view().
 */

 function search_engine_block_view($delta = ''){
     $block = array();
     switch ($delta) {
     case 'search_engine':
         $block['subject'] = t('Search Engine');
         $block['content'] = drupal_get_form('search_engine_form');
     }

     return $block;
 }

 /**
 * Implements hook_form.
 */

 function search_engine_form ($form, &$form_state){
        $form['searchOptions'] = array(
            '#type'     => 'select',
            '#title'    => t('You can search by GWF Number, name, email address or phone number.'),
            '#options'  => array(
                'gwf'           => t('GWF Number'),
                'applicant_email'   => t('Email Address'),
                'name'          => t('Name'),
                'phone_number'      => t('Phone Number'),
                ),
            '#value'    => 'gwf',
            );
        $form['searchInput'] = array(
            '#type'     => 'textfield',
            '#title'    => t(''),
            );
        $form['submit'] = array(
            '#type' => 'submit',
            '#value'=> t('Submit'),
            );
        $form['results'] = array(
            '#type' => 'markup',
            '#value'=> 'Test',
        );

    return $form;
 }
 /**
 * Implements hook_form_submit.
 */

 function search_engine_form_submit($form, &$form_state){
    drupal_set_message('Submitted');
 }

```

# Answer
At the end of your search\_engine\_menu() function, you need to return $items. Also, you should clear your drupal cache after adding a new menu item.

```
 function search_engine_menu() {
    $items = array();
    $items['results_page'] = array(
        'title'         => 'Search Results',
        'page callback'     => 'search_engine_results_page',
        'access callback'   => TRUE,
        'type'          => MENU_NORMAL_ITEM,
    );
    return $items;
 }

```
> 2 votes

# Answer
The hook\_menu should return the $items array. Don't forget to clear the cache after.
> 1 votes

---
Tags: routes
---


# Question
Title: Drupal alias to the last node of one type
Imagine I have a node type of congress, i want to create a menu called congress.html how always go to the last node of this type.

How can i do it.

# Answer
What you want is neither an alias, nor a menu. You want a view of nodes, filtered by type and sorted by date, that displays 1 item.
> 1 votes

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


# Question
Title: Filter for all terms in a "dynamic vocabulary"
I would like to add a filter in a view to search only nodes related to terms in a specific vocabulary. The problem is that the editors continuously add terms to the vocabulary and consequently I cannot select once and for ever which are the possible terms.

I would need a filter like this: positive if the term searched, or its translation, is in the vocabulary "myVocabulary".

# Answer
> 0 votes
I believe contextual filters under the advanced options in your view is what you are looking for. You can add the term reference field there and then dynamically filter the view from the url with either the term name or term id or both depending on the options you select.

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


title: Lead Capture Popup in Drupal

text:
# Question
Title: Lead Capture Popup in Drupal
I'm looking for a solution to implement a lead capturelightbox popup form in Drupal 7. Is there module that would do this? Basically if a user is on a page after a certain amount of time (~10 or 15 seconds), a lightbox popup would go over the page they are looking at and ask them for their email.

# Answer
> The module allows to display a popup once after a certain delay on a page load. This fills a gap in popup modules family (Popups, Popup), which are designed to show popups only after a click on an HTML element, or to implement a complex behavior like modal dialog forms.

You can specify paths on which you need to display the popup without appropriate delay
> 0 votes

---
Tags: javascript
---


title: Customize drupal commerce checkout page

text:
# Question
Title: Customize drupal commerce checkout page
How do I customize Drupal commerce checkout page? I selected shipping information, billing information and payments in the checkout form builder. But the layout the fields are customized and was wondering how to change the layout of the fields like First name, last name etc...

# Answer
> 4 votes
Customize Checkout Look and Feel

There was a recent commit that made the checkout process table-less in the Commerce Issue Que. It was reverted in favor of making such a large change to the codebase on a 2.x release. That code still exists and it's all possible using theme\_ functions in your template.php

1. Go here `/modules/checkout/includes/commerce_checkout.pages.inc` and look for functions that start with theme\_
2. Add those functions that you want to your template.php in your theme or a custom module
3. Change the function word "**theme**" with your theme name or module name.
4. Make an obvious change or two
5. Clear all caches and then go through the checkout process.

# Answer
> 0 votes
Finally found an easy way of changing the layout of the checkout pages by creating a plugin for the addressfield. Refer this link: Rearranging subfields with the Address Field module

---
Tags: commerce
---


# Question
Title: I'm unable to select and saveany text filters except for "Filtered HTML".
I've tried to edit a field in a few content types to set the filtered text format to something other than filtered html, but after I save, it has no effect. I go back to the content type, and it's back to filtered HMTL. If I select "Plain Text" form the "Text processing" setting, I can pick plain text in the "Text format" dropdown, but otherwise, it always saves back to "Filtered HTML". What am I doing wrong?

# Answer
As far as I know, this functionality is "broken" in D7, meaning that the UI is at least misleading. Here's some discussion https://drupal.org/node/1003262

What you can do is change the order of text formats at admin/config/content/formats. The default text format available to users will be according to permissions and the order of text formats.

Also see http://drupal.org/project/better\_formats. That will give you more options.

Also see How do you set a default input text format per content type?
> 1 votes

---
Tags: entities, nodes, input-formats
---


# Question
Title: How to find out which context reaction is firing?
im creating some pages that have specific layouts for tablets and mobiles, to send a targeted view and template im using context, context breakpoints and delta.

But i need some way of seeing which context reaction s being fired as on some pages an endless auto-reload is occurring, i think it might be due to some paths having multiple reactions, so im looking for some way to see which reaction is being fired and getting buggy

# Answer
You can turn on context debug under context settings (*admin/structure/context/settings*) - checkbox 'Enable debug reaction on all contexts'.

It will output debug messages for every event, condition, and reaction. This could help you determine what keeps reloading the page.
> 0 votes

# Answer
About a year ago I was working on a project where the breakpoints module would periodically send us into refresh loops. I don't remember the particulars - only that the issue was due to the cookies not being cleared properly.

Breakpoints relies heavily on cookies to determine which display to use and when the cookies aren't cleared the module receives somewhat mixed messages. I use Chrome for my development and found the extension Edit This Cookie very helpful.
> 1 votes

---
Tags: views, 7, theming
---


# Question
Title: Commerce checkout, check if checkbox is checked
I added a field to my commerce checkout form:

```
mymodule_form_alter(..) {
 ...
 if($form_id ="commerce_checkout_form") {
 $form['thisfield'] = array(
  '#type' => 'fieldset',
  '#title' => t('Contact settings'),
  '#weight' => 5,
  '#collapsible' => TRUE,
  '#collapsed' => FALSE,
 );

 $form['thisfield']['checkbox']= array (
   '#type' => 'checkboxes',
   '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
   '#title' => t('What standardized tests did you take?'),
   '#required' => TRUE,
 ),
 ....
 }
}

```

Now the form may not go to the next step if the checkbox is not checked. If i press the sumbit button now, i go to the next step with the error displayed that the field is requierd. So the error message appears, but the form still continues to the next step.

Now i don't really know how to keep the commerce form on the same step if the checkbox is not checked.

# Answer
> 1 votes
You shouldn't add the field directly to the checkout form, but rather create a new checkout pane and add the field to that.

e.g:

```
/**
 * Implements hook_commerce_checkout_pane_info
 */
function MODULE_commerce_checkout_pane_info() {
  $checkout_panes = array();

  $checkout_panes['contact_settings'] = array(
    'title' => t('Contact settings'),
    'file' => 'includes/commerce_checkout.checkout_pane.inc',
    'base' => 'MODULE_checkout_contact_settings_pane',
    'page' => 'checkout',
    'callbacks' => array('checkout_form_validate' => 'MODULE_checkout_contact_settings_pane_validate')
    'fieldset' => TRUE,
  );

  return $checkout_panes;
}

```

Put your form builder in `includes/commerce_checkout.checkout_pane.inc` \> `MODULE_checkout_contact_settings_pane`

You can then use the Commerce API to validate your checkout form in

```
/**
 * Checkout pane validation for contact_settings
 */
function MODULE_checkout_contact_settings_pane_validate(&$form, &$form_state, $checkout_pane, $order) {

  // Do some validation tests here... omitted for brevity.
  if (empty($form_state['values']['thisfield'])) {
    drupal_set_message(t('Some validation error message'), 'warning');
    return FALSE;
  }

  return TRUE;

}

```

More info: `hook_commerce_checkout_pane_info`

# Answer
> 0 votes
Inside the form\_alter you need to declare a custom validate function

```
$form['#validate'][] = 'my_module_custom_validate';

```

Inside the validate if the condition is not satisfied then generate form\_set\_error() which prevents it from submitting

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

if ($form_state['values']['thisfield'] == 1) {
//condition for checked == true
form_set_error('thisfield', 'please untick to submit the form');
}

}

```

---
Tags: forms, commerce
---


# Question
Title: How to use commerce_cart_order_product_line_item_delete?
I've set up my own custom module structure, and am trying to implement commerce\_cart\_order\_product\_line\_item\_delete. At it's most basic level, i'm trying to delete line item 70 from order 1 in my cart with the following code in my module:

```
<?php
    commerce_cart_order_product_line_item_delete(1,70,FALSE);
?>

```

I'm getting this error on the page:

Fatal error: Call to undefined function commerce\_entity\_reference\_delete() in /Users/\[username\]/Documents/Sites/\[site\_name\]/profiles/commerce\_kickstart/modules/contrib/commerce/modules/cart/commerce\_cart.module on line 1268

I've tried other methods, like the code on this page:

http://dropbucket.org/node/358

but i can't seem figure out how to find a product's ID, and in the end, I want to delete a line item from a cart which could potentially have two entries of the same product. don't want to delete the whole product from the cart... hope that makes sense.

What am I missing? thanks!

# Answer
The function accepts the $commerce\_order object not just the order\_id. You could try

```
commerce_cart_order_product_line_item_delete($order, 70);

```

`commerce_entity_reference_delete` is defined in commerce.module so it should be available, if commerce is enabled and at current version.
> 0 votes

---
Tags: 7, commerce
---


title: Content notification for updates

text:
# Question
Title: Content notification for updates
OG has a pre-installed rule "OG group content notification" for sending out notifications to group members of new posts.

Is there a similar rule for sending out notifications of updated group posts to group members?

I have read that there might be a way using Rules on How do I send notifications for followers of a group when group content is updated? but I was not allowed to post a follow-up comment there.

# Answer
> 0 votes
I realized that I did not have the Rules UI enabled. Once I enabled it, I was able to see the "OG new content notification (With Message)" rule clearly. I only need create a copy of this and edit it to my requirements.

---
Tags: rules, organic-groups, notifications
---


# Question
Title: How to export all feature components with drush?
With drush feature-export you can easily create a feature from a component. But is there a way to easily export ALL components into a feature? In the ui you can easily check all content types or all views. I tried `drush fe newfeature views_view` but it only exports one view not all of them.

# Answer
> 2 votes
Hmm ... did you try drush's built in Help topics?

I am running `drush --version`: `Drush Version : 6.2.0`

The help output for features-export is: `drush help fe`

```
Export a feature from your site into a module. If called with no arguments, display a list of available components. If called with
a single argument, attempt to create a feature including the given component with the same name. The option '--destination=foo'
may be used to specify the path (from Drupal root) where the feature should be created. The default destination is
'sites/all/modules'. The option '--version-set=foo' may be used to specify a version number for the feature or the option
'--version-increment' may also to increment the feature's version number.

Arguments:
 feature                                   Feature name to export.
 components                                Patterns of components to include, see features-components for the format of patterns.

Options:
 --destination                             Destination path (from Drupal root) of the exported feature. Defaults to
                                           'sites/all/modules'
 --version-increment                       Increment the feature's version number.
 --version-set                             Specify a version number for the feature.

Aliases: fe

```

And `drush help fc`:

```
List feature components matching patterns. The listing may be limited to exported/not-exported components.

A component pattern consists of a source, a colon and a component. Both source and component may be a full name (as in
"dependencies"), a shorthand (for instance "dep") or a pattern (like "%denci%").

Shorthands are unique shortenings of a name. They will only match if exactly one option contains the shorthand. So in a standard
installation, "dep" will work for dependencies, but "user" wont, as it matches both user_permission and user_role.

Patterns uses * or % for matching multiple sources/components. Unlike shorthands, patterns must match the whole name, so
"field:%article%" should be used to select all fields containing "article" (which could both be those on the node type article, as
well as those fields named article). * and % are equivalent, but the latter doesn't have to be escaped in UNIX shells.

Lastly, a pattern without a colon is interpreted as having ":%" appended, for easy listing of all components of a source.

Arguments:
 patterns                                  The features components type to list. Omit this argument to list all components.

Options:
 --exported                                Show only components that have been exported.
 --not-exported                            Show only components that have not been exported.

Aliases: fc

```

So you should be able to use wildcards like `%` or `*` to select all types of a component. Eg, `drush fe newfeature views_*`. Your mileage may vary ...

---
Tags: drush, features
---


title: Filefield with IMCE browse server

text:
# Question
Title: Filefield with IMCE browse server
I am having rather strange issue. I have created custom CCK with image upload field. To browse a server folders I've installed a CCK Filefield and configured it to work with IMCE , however I can't see images (uploaded with FTP), unless I upload them through IMCE itself. The strange thing is that in Description field I have also IMCE file browser wich "see" correctly all images. What am I missing? Thanks

# Answer
> 1 votes
To overcome the above problem, I have installed the IMCE for FileField module; everything started working.

# Answer
> 0 votes
Make sure you reference the files directory as "." NOT as "sites/default/files" in your IMCE profile settings. (Per the Directory instructions below: "To specify file system root, just enter .(dot) character.")

---
Tags: media, files
---


# Question
Title: "Your command line PHP installation is too old"
When trying to run Drush on my shared hosting account I get this error:

> Your command line PHP installation is too old. Drush requires at least PHP 5.3.0.
> To suppress this check, set the environment variable DRUSH\_NO\_MIN\_PHP=1

When I type `php --version`, it tells me that I am running PHP 5.2.6.

The .bashrc file has the following lines

```
export COLUMNS
alias drush='/usr/bin/php ~/public_html/drush/drush.php'
alias php='/usr/bin/php'

```

How I can fix this?

# Answer
> 2 votes
I had a similar problem and I was able to specify what version of PHP Drush will use by adding the following to my .bash\_profile file:

```
export DRUSH_PHP=/usr/local/php53/bin/php

```

That got mine working. I had tried a more general approach where I specified PHP 5.3 for my command line generally, but this didn't work. Specifically targeting Drush is what it took for me.

---
Tags: drush
---


# Question
Title: Open a specific View node with a link in an image
I'm stumped. I'm not even sure how to ask the right questions to search out an answer.

What I have is a View of User Account images in a gallery. So far so good. I have another view of all User Account fields data presented as a node. So far so good there as well.

I want to click on the User Image in the gallery and go directly to that User's node in the other view.

The problem is not with attaching a URL to an image, but enabling sequential URLs to call the correct View node.

I feel like I'm missing some organizational overview understanding here. Maybe it's simple and I'm a doof.

Thanks for any insight.

# Answer
> 0 votes
From what I gather there are two possible approaches to this:

1. Either add a field for Link and then "Rewrite Results" to the content by referencing the node\_id. Or do the rewrite on the image itself to the appropriate node\_id. You might have to massage the urls for the other View or find a pattern to make this work.
2. Add a relationship to the gallery view to the Node that contains the UA fields. Add this relationship to the image field and then work it that way.

Hope this helps!

---
Tags: 7, navigation, views
---


# Question
Title: I'm trying to make a module that searches LDAP for users
I want to be able to search LDAP users by first name, last name, or email, and in the results show the user's picture, first/last names, role, and email. I've looked into it a little and found the LDAP module for drupal, but all I see is syncing with users. Is this something I can do using this module? Am I going to have to sync the LDAP db with a table in my MySQL db and then reference that table?

# Answer
> 1 votes
I think you'll find that LDAP modules for Drupal are primarily for allowing LDAP users to *use* Drupal.

My understanding of what you're saying is that you just want to display the LDAP users, sort of like a directory system?

If Drupal doesn't have to really interact with your LDAP users, you should be able to create your own module for this pretty easily.

There are quite a few LDAP functions in PHP: https://www.php.net/manual/en/ref.ldap.php

Create a module that makes use of them, and then passes the data over to a node for display purposes.

# Answer
> 1 votes
I have toyed alot with the LDAP module. It can do exactly what you want assuming you're not a newb with LDAP or Drupal. I *highly* recommend you read the official drupal LDAP documentation -- pretty much all your answers may be found there.

If the LDAP module seems complex -- it's in my opinion because LDAP (and the ldap vendors) simply *are* complex.

The LDAP module lets you connect to and query an LDAP service. It has many submodules:

> * LDAP Servers. Stores connection information for ldap servers and relationships between ldap and drupal users. Also contains api functions for LDAP project.
> * LDAP User (7.x-2.x branch). Controls provisioning and synching mappings of Drupal user fields and properties to and from LDAP Entry attributes.
> * **LDAP Query. Stores individual queries that can be leveraged by other modules such as LDAP Feeds and LDAP Views.**
> * LDAP Authentication. Authentication via user credential checking or single sign on methods such as NTLM.
> * LDAP Authorization. Conversion of ldap user data to drupal roles, organic group memberships and other authorization consumers.
> * **LDAP Feeds. Fetchers for LDAP Queries and LDAP Users to integrate with Drupal Feeds module.**
> * **LDAP Views. Views module integration for LDAP Query resultsets**
> * LDAP Help. Helper module for debugging configuration issues with other LDAP Modules.
> * LDAP Test (7.x-2.x branch). This is simply for automated test coverage and never needs to be enabled; the simpletests will enable it while running. It contains the mock ldap server and related helper functions.

I have bolded the key submodules found in the documentation relevant to your question. You can save an LDAP Query (a raw LDAP search query -- this has nothing to do with Drupal and 100% pure LDAP usage knowledge) and use it within a Drupal View or via the Feeds module.

Understanding whether you want a drupal View or leverage the Feeds module to populate a content type or something else is where you're understanding of Drupal will be helpful -- and specifically these 2 modules.

As an example here is a stored query to run against ldap:

And its test result:

**EDIT** In short, yes LDAP lets you Sync or create/add LDAP "users" into Drupal. It may also be used to simply query and essentially use and "show" LDAP data on your site. What modules you choose to do that with -- and your approach is up to you (Views or Feeds processing). Writing this stuff from scratch sucks. Use the LDAP modules and the tools outlined here :)

---
Tags: authentication-authorization
---


title: Highlight valid form element

text:
# Question
Title: Highlight valid form element
I'm using clientside validation module. It highlights only errors. How to display for example a green mark beside **valid** form elements?

# Answer
The Clientside Validation module adds classes 'valid' and 'error' to all form elements. You could use the class 'valid' to add the green mark simply with some css.
> 1 votes

---
Tags: forms
---


# Question
Title: Module to rotate the content continously
Any one knows how to rotate the content of particular content type continuously from down to upward direction without pausing.

The contents should rotate continuously together. I have used `viewTicker` and `view slideshow` and `content glider` modules.

Please tell me other module.

# Answer
Jcarousel might help you for creating slide shows. It works even with views so you can create a views slideshow with it. It also have an automatic slide rotation which I think you were after. https://drupal.org/project/jcarousel
> 0 votes

---
Tags: 7
---


# Question
Title: Why are no tests shown on testing overview?
I want to run DrupalWebTestCases on my custom Drupal 7 module.

Following the Tutorial at https://drupal.org/simpletest-tutorial-drupal7 i'm stuck at running the tests:
also after cache deletion no other Tests than for SimpleTest are found on the `/admin/config/development/testing`-page.

I'm using the contributed SimpleTest module, added the `testing_api = 2.x` setting to my modules .info.

mymodule/mymodule.info:

```
name = Mymodule Reports
core = 7.x
php = 5.3
files[] = tests/*.test
testing_api = 2.x

```

mymodule/tests/mymodule.test:

```
/**
 * @file
 * Mymodule reports module tests.
 */

class MymoduleReportsTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'MymoduleReports',
      'description' => 'Ensure that the locking of nodes functions properly.',
      'group' => 'Mymodule',
    );
  }

}

```

What i'm doing wrong?

# Answer
Instead of using

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

```

in mymodule/mymodule.info it should be

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

```
> 1 votes

---
Tags: testing
---


title: Save Node Title By database query

text:
# Question
Title: Save Node Title By database query
I am trying to update a node title by database query as

```
 $num_updated = db_update('node') // Table name no longer needs {}
  ->fields(array(
    'title' => "custom_title",
    'status' => 1,
  ))
  ->condition('nid', $nid, '=')
  ->execute();

```

The above code is updating the node title in node table, but on node display I am not seeing the updated title.

The reason I am not using node\_save() to update node title is to by pass auto entity label functionality for updating node title.

# Answer
> 3 votes
If you want to bypass just one functionality, you need to go thorough all your modules, see what they are doing on `node_save()` and emulate it with your queries. Most common thing people forget is to update revisions, menus and clear cache. But your way is discouraged.

Instead, you should be able to configure Automatic Entity Label not to override title, if the title is set manually, like on the screenshot below:

If you need to deny users title generation, you can change this setting in code with `variable_set()` just before call to `node_save()`, and revert it just after.

# Answer
> 3 votes
You also need to update the node\_revision table. You either need to create a new revision for that node or update the latest one.

---
Tags: nodes
---


# Question
Title: why do I receive wrong Notice: Undefined index?
There is a view and content type both called `activities` and this is `views-view-fields--activities--block.tpl.php`

```
<div class="element">
<div class="image"><?php print $fields['field_activities_image']->content;?></div>
<div class="text">
    <div class="head"><?php print $fields['field_activities_title']->content;?>    </div>
    <div class="body"><?php print $fields['field_activities_summary']->content;?>    </div>
</div>
</div>

```

this block is displayed in the `front--page.tpl.php` and it works right. There is another block of this view and that block is displayed in the node page. this block only contains 10 `title`. the problem is drupal reports this warning in the node page:

```
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)

```

The ID of the block that is displayed in the node page is `block_1` but it tries to use `views-view-fields--activities--block.tpl.php`. how can I solve this warning?

# Answer
> 3 votes
I think that the name `views-view-fields--activities--block.tpl.php` is a suggestion for all blocks of the view activities - to get better specified template name check template information in that view. ('Information' link under Other -\> Theme in the view builder) I *think* that the template name should be something like `views-view-fields--activities--[block_id].tpl.php`.

Change the `block` machine name if necessary.

Also, its a good practice to utilise this in templates to prevent such warnings:

```
<?php if (!empty($fields['field_activities_image'])):?>
  <div class="image"><?php print $fields['field_activities_image']->content;?></div>
<?php endif; ?>

```

---
Tags: theming, blocks
---


title: URI for actions of services

text:
# Question
Title: URI for actions of services
I have defined the following service.

```
'salesforce_subscriptions' => array(
    'operations' => array(
      'delete' => array(
        'help' => 'Remove subscriptions from SalesForce',
        ...
        'args' => array(
          array(
            'name' => 'ids',
            'type' => 'string',
            'description' => '',
            'source' => array('param' => 'ids'),
            'optional' => FALSE,
          ),
          array(
            'name' => 'API key',
            'optional' => FALSE,
            'type' => 'string',
            'description' => 'The api key',
            'source' => array('param' => 'api_key'),
          ),
        )
      )
    ),

```

How can I access this? The endpoint of the service is: endpoint. I can access the index service by: www.example.com/endpoint/salesforce\_subscriptions

How can I access delete?

# Answer
You should be able to access it via

```
www.example.com/endpoint/salesforce_subscriptions/[ids]/delete

```

If that doesn't work, you may need to experiment with the id parameter source, e.g path argument vs param

For more info and example, see the node resource definition here:

`_node_resource_definition`
> 1 votes

---
Tags: services, uri
---


# Question
Title: Can't disable module when it defines an field type used by a custom entity
I have created a module that creates a custom entity (using hook\_entity\_info etc.), defines a field type (using hook\_field\_schema and hook\_field\_info), and then creates an instance of the field type with my custom entity (using field\_create\_field and then field\_create\_instance).

This all works great until I try to uninstall the module and am told "Drupal (Field type(s) in use".

Whilst this is true they won't be in use once the module is uninstalled!

Short of going into the DB and starting to delete rows out of the field\_config and field\_config\_instance table how do I get round this problem?

Here I am creating the field instance in hook\_enable:

```
function emtr_enable() {

    field_cache_clear();
    field_associate_fields('emtr');

    if(field_info_field('emtr_denominations')) return;

    $field = array(
        'field_name' => 'emtr_denominations',
        'type' => 'field_emtr_denominations',
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
        'translatable' => FALSE,
    );
    field_create_field($field);

    $instance = array(
        'field_name' => 'emtr_denominations',
        'entity_type' => 'emtr_safe_check',
        'bundle' => 'emtr_safe_check',
        'label' => 'Denominations',
        'required' => false,
        'widget' => array(
            'type' => 'number'
        ),
        'settings' => array(
            'target_type' => 'emtr_safe_check',
            'handler_settings' => array('target_bundles' => NULL),
        ),
        'display' => array(
            'default' => array('label' => 'inline', 'type' => 'number_integer'),
        ),
    );
    field_create_instance($instance);
}

```

And here is my uninstall hook:

```
function emtr_uninstall() {
    if ($instance = field_info_instance('emtr_safe_check', 'emtr_denominations', 'emtr_safe_check')) {
        field_delete_instance($instance);
    }
    if (field_info_field('emtr_denominations')) {
        field_delete_field('emtr_denominations');
    }
    field_purge_batch(100);
}

```

And hook\_field\_schema:

```
/**
 * Implements hook_field_schema
 */
function emtr_field_schema($field) {

    $columns = array(
        'denomination_value' => array(
            'type' => 'int',
            'not null' => FALSE,
        ),
        'denomination_tid' => array(
            'type' => 'int',
            'not null' => TRUE,
            'default' => 0,
        ),
    );
    $indexes = array(
        'denomination_tid' => array('denomination_tid'),
    );
    return array(
        'columns' => $columns,
        'indexes' => $indexes,
    );
}

```

Just in case my hook\_field\_info and hook\_entity\_info are in a pastebin here.

# Answer
> 1 votes
So as Clive suggested I solved this by creating a helper module called emtr\_fields.

The emtr\_fields module creates the entity and has the field schema.

Then the main emtr module creates the field and it's instance.

To remove all of this again first the emtr module has to be disable AND uninstalled (it has to be uninstalled as the field and it's instance is deleted in hook\_uninstall), and then the emtr\_field module can be disabled and uninstalled.

I also found some documentation on this on drupal.org here:

Module cannot be disabled because Drupal claim "Field type(s) in use"

Moving field(s) definitions into a separate module of a installed module.

Field types should be defined by one module and implemented by a separate module.

---
Tags: 7, entities
---


# Question
Title: How to programmatically add a facet to Facet API based on returned facet values?
I would like to programmatically and conditionally show a facet block, if the returned values match some certain criteria. I have not found any solutions so far. For example, if a facet returns 25 apples, I would like to show an additional facet that does some calculation on this value.

# Answer
If you used Search API, this code should help you:

```
$delta = facetapi_hash_delta(facetapi_build_delta('search_api@INDEX_MACHINE_NAME', 'block', FACET_NAME));
print render(module_invoke('facetapi', 'block_view', $delta));

```
> 2 votes

---
Tags: search
---


# Question
Title: Which nid to use for translated node in a menu
I'm not using the Entity Translation but only the i18n modules.

For example in the main menu I want to translate "contact us". So in the German translated menu do I need to give the nid of the German version of English node "contact us" ? Or the original English version one?

EDIT: In the figure node/59 refers to English node while the German version is node/800. So for German menu("contact us") which one do I need to feed? node/59 or the node/800. I fed node/59 for all the translated menu items but then they'd all redirect to English one. I thought that i18n should be able to figure and select the translated node automatically. Looks like I'm missing something.

# Answer
First off, the modules that you mentioned are just fine. You need to edit the menu and specify in the translation options fieldset:

* Either "Translate and localize", which essentialy means that you can keep translated menu items in the same menu
* Or "Fixed Language", which means that the whole menu is fixed on ione language, so you would need a second menu for a second language and so on.

If you select the "Translate and localize" option, which I would usually prefer, then you add a normal menu item say in English, and then in the list of menu items there will be an operation available for each one of the menu items named "translate". This is where you select the translated language of a second menu entry. Alternatively, you can access translate for within the menui item edit itself.

The idea is that each menu item has its language specified, so when you give the node/nid of a different language (or canonical url of any language) it shouldn't matter, provided that you have linked translated content (nodes) as well in the content administration.
> 0 votes

# Answer
In Drupal 7 you can use **Locale** core module to translate.

**Locale** : Adds language handling functionality and enables the translation of the user interface to languages other than English

* After enabling the **Locale module** , add German language using `admin/config/regional/language`.
* Use English words to create menus.
* After creating the menus use `admin/config/regional/translate/translate` link to translate English string to German.

+ Search for the string. I'm using **About Us** to translate. Click the corresponding **edit link** to translate.
    + Enter **German** string
> 1 votes

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


# Question
Title: How to create specific role permissions for authenticated users in Drupal 7
I'm developing a Drupal 7 based site. As an administrator of a site I want to add some specific access permissions for authenticated users. By default in Drupal authenticated users can read the content. And they can view the author of content. I want to disable the feature of viewing the author, but only for concrete contents. When an authenticated user creates content, I want to make him able to choose "creating a content as anonymous author", i.e. other users can read and comment that content, but unable to see it's author. And additionally this feature shouldn't affect quantity of content posted by that user. When the user creates content it will be incremented in "Number of content created by this user", whether content was created as "anonymous author" or not. I've looked up in "People \> permissions" , but couldn't find a permission like that. I know a little PHP, so if the answer requires a knowledge of PHP, go ahead.

# Answer
You could have a look at User points module, you also need userpoints\_nodelimit, part of User Points Contributed modules to limit the number of nodes a specific user is allowed to create. For the deletion of nodes you'll need the rules modules so you can give the user a point back.

You could write your own implementation, but depending on your skills this might be harder, in short you need to implement:

* an access callback where you check the user and the number of available points
* use hook\_menu\_alter to replace the access callback of 'node/add'
* implement hook\_node\_delete and hook\_node\_isnert to change the counter
> 2 votes

---
Tags: users
---


# Question
Title: Auto URL Aliasing for Custom Menu Paths with Term Id
Here is my problem.

1. I have created a view with path as groups/% where % is a term id.
2. Now, i would like to create auto aliases for all groups/% with % as a term name.

Ideally i would like to add this alias path on creation of a term related to particular vocabulary. Is there any module that will do this out of the box ?

PATH AUTO MODULE: As far as i know it allows to set patterns only for taxonomy term paths and node paths for different content types.

But, how to set patterns for custom menu paths ?

# Answer
> 1 votes
Solved it using hook term insert update delete and pathauto helper function.

```
/**
 * Implements hook_taxonomy_term_insert().
 */
function your_module_taxonomy_term_insert($term) {
  // Do it only for Group Categories term
  if ($term->vid == 3) {
    module_load_include('inc', 'pathauto');
    $path = array();
    $path['source'] = 'groups/' . $term->tid;
    $path['alias'] = pathauto_cleanstring($term->name);
    path_save($path);
  }
}

/**
 * Implements hook_taxonomy_term_update().
 */
function your_module_taxonomy_term_update($term) {
  // Do it only for Group Categories term
  if ($term->vid == 3) {
    module_load_include('inc', 'pathauto');
    $conditions = array();
    $conditions['source'] = 'groups/' . $term->tid;
    $path = path_load($conditions);
    // Delete old alias if user erased it.
    if (!empty($path['pid'])) {
      path_delete($path['pid']);
    }
    $path = array();
    $path['source'] = 'groups/' . $term->tid;
    $path['alias'] = 'groups/' . pathauto_cleanstring($term->name);
    path_save($path);
  }
}

/**
 * Implements hook_taxonomy_term_delete().
 */
function your_module_taxonomy_term_delete($term) {
  // Do it only for Group Categories term
  if ($term->vid == 3) {
    path_delete(array('source' => 'groups/' . $term->tid));
  }
}

```

# Answer
> 1 votes
I am not sure whether we should take this way or not but I found this:

We can save new path alias using path\_save() function.

Here is how I managed it:

I called the function after submission of node or group node.

Then I called a custom function and fetch the real URL of the node i.e in your case it will be group/tid.

Now I retrived term name from term id and created new alias with term name.

Called path\_save() function with necessary information.

# Answer
> 0 votes
You can use one of these modules to do this in Drupal 7 for all the Custom Paths whether they are created from custom modules OR from Views/Blocks:

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


# Question
Title: Is this a good way to make fields accessible for an empty entity object?
I have a function, my\_entity\_create(), which returns an empty object for my entity with properties: isnew, name, etc...

I want my fields attached to this empty object so I can set their values. I accomplished this by calling the function below and adding the results to my object in my\_entity\_create(). Now I can set $my\_entity\_obj-\>field\_my\_field\['und'\]\[0\]\['value'\] = 'some value'. I save it with entity\_save() and it works.

My question: is there a better way to do this? I'm trying to learn to do things 'the drupal way'... or just the best way if there is not a drupal best practice for a certain task.

```
function _get_fields_for_bundle($bundle)
{
    $result = db_select('field_config_instance', 'f')
        ->fields('f', array('field_name'))
        ->condition('entity_type', 'my_entity_type')
        ->condition('bundle', $bundle)
        ->execute()
        ->fetchAllAssoc('field_name');

        return array_keys($result);
}

```

# Answer
> 0 votes
I too was looking for an answer to this question, however you question has provided me with the best answer so far.

My implementation of your solution was to call your function in my entity create function and then loop over the values attaching the fields as empty arrays:

```
function MY_ENTITY_create($values = array()) {
    $entity = entity_get_controller('MY_ENTITY')->create($values);
    foreach(_get_fields_for_entity('MY_ENTITY') as $field) {
        $entity->{$field} = array();
    }
    return $emtr_safe_check;
}

function _get_fields_for_entity($entity) {
    $result = db_select('field_config_instance', 'f')
        ->fields('f', array('field_name'))
        ->condition('entity_type', $entity)
        ->condition('bundle', $entity)
        ->execute()
        ->fetchAllAssoc('field_name');

        return array_keys($result);
}

```

As my entity does not have a bundle, but my module does define several different entities I modified your function slightly to handle loading fields for different entities with bundles of the same name.

I would still be interested to see other peoples solution to this problem.

---
Tags: 7, entities
---


# Question
Title: How to display the recent user revision in a views block with contextual filters?
We are having a Setup where we need to be able to display User Revision Fields via Views Blocks. We are using the User Revision Module and even fixed a Bug on the Contextual Filter Plugin of that Module. Lets say the Url is /user/abc/revision/123 everything with a Contextual Filter for the VID on the Path works fine. The Problem comes when we want to display the last Revision trough the same View because it has not the Revision Url pattern. it is only user/abc Do i have to write a custom Contextual Filter which can differentiate the Url ? And what is then used instead of the VID ?

# Answer
> 0 votes
I ended up using PHP Code in the contextual filter:

```
$cpath = explode('/',current_path());
$path_uid = $cpath[1];
if (array_key_exists(3, $cpath)) {
  $path_vid  =  $cpath[3];
  return $path_vid;
}
else {
  $result = db_query("SELECT vid FROM {user_revision} u WHERE uid = (:uids) ORDER BY vid DESC LIMIT 0,1", array(':uids' => $path_uid))->fetchField();
  return $result;
}

```

Would be nice to put this in a custom module so if have to make changes and do not have to touch every display of the view.

---
Tags: users, views, uri
---


# Question
Title: Installing the Media Module + WYSIWYG Module on Acquia Cloud
I'm trying to get the Media module (and it's dependent WYSIWYG module) working on an Acquia Cloud environment. Normally, this isn't too bad locally but Acquia has a strange file structure that is giving me some headaches.

I have installed and activated both WYSIWYG along with Media but neither are working correctly. WYSIWYG needs CKEditor to work and wants it to be included in `sites/all/libraries` (outside of the normal modules folder). Acquia doesnt give you access to add in libraries like that.

Media isn't showing the library when a user accesses a content-type with an image field that use's Media's 'Media file selector' widget.

Im guessing a lot of this is due to path problems, but the only documentation Acquia has about their file structure is here (and this mostly pertains to the files folder - not core + contrib paths): https://docs.acquia.com/cloud/files

So my question is two fold:

* How do you get CKEditor into an Acquia Cloud instance with the WYSIWYG module?
* Why wouldnt media show its library? Am I leaving another module out maybe? Path issue?

# Answer
Short answer: turn off livedev in your Acquia Cloud dev environment.

Longer Answer: I was trying to drush my modules and do basic site building in their environment using the livedev option. But they don't let you run `mkdir` and `scp` live in their environment via CLI.

Their recommended workflow will have you add your modules/libraries locally, commit via git and then push up to their environment.
> 1 votes

---
Tags: wysiwyg, media, acquia-cloud
---


title: Error on when to load node?

text:
# Question
Title: Error on when to load node?
I have problem when our taxonomy term is linked with node but when i am clicking on term they go front page of site instead of current page our code given below:

```
$ch1 = db_query("SELECT th.tid FROM taxonomy_term_hierarchy th
  INNER JOIN taxonomy_term_data td ON th.tid=td.tid
  INNER JOIN field_data_field_books book ON book.field_books_tid = th.tid
  WHERE td.vid = '6' AND th.parent = $ch AND book.entity_id = $nid
 ")->FetchField();

$chap1=taxonomy_get_children($ch1);
foreach($chap1 as $ca1){
    $link = l($ca1->name, 'node/' . $ca1->nid)."<br>";
    print $link;
}

```

How to handle this problem?

# Answer
"$ch1" contain tids.

The function "taxonomy\_get\_children($ch1);" retrieve all children term id and not related nid...

You can retrieve all nid linked with a term with this function taxonomy\_select\_nodes

I will suppose $ch1 contain your tids in an array

```
foreach($ch1 as $tid){
    $nids  = taxonomy_select_nodes($tid);
    $nodes = node_load_multiple($nids);
    foreach($nodes as $node){
        $link = l($node->title, 'node/' . $node->nid)."<br>";
        print $link;
    }
}

```

I can't test this code, if it's valid tell me and i will remove this line :)
> 0 votes

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


title: Display Main menu only on login page

text:
# Question
Title: Display Main menu only on login page
I am using **Webform module** and I used main menu to display the form on `Login page`. I want to display menu only on `Login page` but `Main menu` is also displaying on `front page`. Is their any way to hide displaying `main menu` on `front page`.

# Answer
> 1 votes
You have 3 simple options (And even more with preprocessors, but I won't go into that):

1. Most themes auto output the primary and secondary menu (configured in Appearance -\> Global/THEMENAME -\> Settings). You can turn it off on the theme settings, and use the Block system (Structure -\> Blocks -\> Main menu -\> Configure) to put it on the pages (2 valid urls):

```
/user
/user/login

```

pages only.
2. (This is exactly the same as 1 except it's not database configuration, it's a code edit) Edit the `page.tpl.php` and comment out the lines that go something like:

```
if($primary_menu) { print $primary_menu; }

```

and again use the block system to output the main menu block on the login page (2 valid urls - see 1)
3. Or alternatively you can create a new custom menu, stick your form link there, and use the block system to assign it to the login page (2 valid urls - see 1). And leave your Main menu empty.

# Answer
> 0 votes
In Drupal 7 use **Block Visibility settings** to control the block Visibility.

Use PHP code:

```

    <?php
        if(/* Your conditon */){
            return TRUE
        }
        else{
            return FALSE;
        }

    ?>

```

---
Tags: routes
---


# Question
Title: Create user login programmatically in Drupal 7
The questions is very simple and the task is difficult. Which functions I need to create a new login form from scratch in Drupal 7?

The reason I need this is because I modified the default login form. It connects to a web service with two different methods and it has different validates, depends from a user roles and lots of customized stuff.

Right now to login as admin, I have to comment my custom module, so I can use the default login form.

I need to create a new login form on different page that will be dedicated to admin user.

# Answer
It's not going to be possible to list all of the functions involved as your mileage will vary depending on what you need to do.

Basic steps:

1. Read up on and understand the Form API; try out a few examples so you're familiar with it.
2. Create a form function in your module, to be delivered in whatever method makes sense (a menu callback or embedding directly, for example). This will involve using drupal\_get\_form(), and viewing the user login form code will be useful here.
3. Create a validate handler for the form which does any validation you need. See `user_login_default_validators()` for the login form defaults.
4. Make use of `user_login_finalize()` in your form's submit handler to log the user in. You'd be best off copying the logic from `user_login_submit()` almost directly.
> 2 votes

---
Tags: users
---


# Question
Title: How to programatically change a user image field to match the user's latest completed goal?
I created several goals with the Goals module. Every goal has an associated image.

My users have an image field 'Last goal' and I'd like to change it to the image associated with their latest completed goal. As this doesn't seem possible with the Rules module, I'd like to create a custom module. I found in the `Goals API` that I can use `hook_goals_completed_goal($goal_id, $uid)`, but I'm stuck there.

How can I grab the user's 'Last goal' field and change it to `goal_img`?

# Answer
> 1 votes
I finally found the answer thanks to the Devel module and the user\_save API page! After investigating a random goal with `dpm(goals_load(GOAL_ID));`, I wrote the following code:

```
 function top_goals_completed_goal($goal_id, $uid) {
    $user = user_load($uid);
    $goal = goals_load($goal_id);
    $fid = $goal->goal_img['und'][0]['fid'];
    $img_title = $goal->goal_img['und'][0]['filename'];

    $edit = array();
    $edit['field_last_goal']['und']['0']['fid'] = $fid;

    user_save($user, $edit);
}

```

# Answer
> 0 votes
I have not used the goals module, but it looks interesting.

I realise that you have tackled this using user badges already, but it sounds like it might not be easiest to tackle this by adding the image to the **goal**.

As the project page mentions user points and user badges, I would suggest that rather than adding the required image to a goal directly, you install the user badges module, create a 'badge' to match each of the goals you have setup, and attach the image to the **badge** instead. You could then use the goal completion action in rules to award the user badge to the user.

---
Tags: media, 7
---


title: TinyMCE for comment textarea

text:
# Question
Title: TinyMCE for comment textarea
I'm Drupal beginner and I can't figure out one small thing.

How can I use TinyMCE for comments ?

Please, see image below:

I have already defined some custom formats and WYSIWYG profiles, but can't figure out how to "attach" them;

Thanks.

# Answer
> 0 votes
First go to /admin/structure/types and edit your content type. Click on the "Comment Fields" tab at the top of the page and then edit the comment field. Here you can choose the text format that your comment field will use.

Now go to /admin/config/content/wysiwyg and choose the text editing you want to use for your text format. You can also edit any configuration setting your editor of choice here.

---
Tags: views, comments
---


# Question
Title: How to edit the template of a node teaser that is sent in a newsletter email?
I have a content type for my newsletter, it has an entity reference field that displays the latest articles of my site in a teaser format.

I tried to edit the teaser display in my node.tpl.php like this:

```
<?php if ($teaser): ?>
    <!-- teaser template HTML here -->
  <?php else: ?>
    <!-- regular node view template HTML here -->
  <?php endif; ?>

```

in the website all is correct, what i put inside the if, is working but just in the website, but when i send the newsletter, the email arrives with something very different (something like a standard format), could you please tell me were can i edit the way my newsletter send the emails?

# Answer
I think it would be easiest to change the teaser in the Manage Display tab under the appropriate content type. That will apply everywhere.

However if you have custom theme stuff you want to accomplish you'll have to make sure you're affecting the correct theme. It sounds like the e-mail generator may be using a different theme to send the e-mail?

A simple way to test for this is putting `<h1>HELLO</h1>` in a template that you think it's using.
> 1 votes

---
Tags: theming, emails
---


# Question
Title: Child menu items not displayed in drupal
I've a sub-menu like this:

I'm trying to build a custom theme, I just copied which contains following code:

```
<?php if ($main_menu || $secondary_menu): ?>
  <div id="navigation"><div class="section">
    <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Main menu'))); ?>
    <?php print theme('links__system_secondary_menu', array('links' => $secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Secondary menu'))); ?>
  </div></div> <!-- /.section, /#navigation -->
<?php endif; ?>

```

**This is how its being displayed:** Note that not even the HTML for child menu items are generated.

Yes, I've *Show as expanded* option checked for "Publications".

PS: Why does drupal make even such simple things difficult. No wonder, its losing ground to wordpress.

# Answer
> 2 votes
Try this:

```
<?php
$menu_name = variable_get('menu_main_links_source', 'main-menu');
$tree = menu_tree($menu_name);
print drupal_render($tree);
?>

```

Also Drupal doesn't make things hard, you just don't understand it yet.

It is just a tool suited to specific tasks. If you just want to make a blog then don't use Drupal, just use Wordpress.

If however you want a very powerful CMF (Content management framework, not system) to create complex systems with lots of inter-related entities then continue to learn Drupal - I think it's the best tool for the job.

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


# Question
Title: Theme the "Add to cart" form on the product display page
I have a Drupal Commerce project setup on top of D7-22. I've overridden the template file for my product display (`node--product-display.tpl.php`), and have managed to render the product fields, as well as the Add-to-cart form with all of the attributes. I know that `<?php print render($content)?>` will actually render the `<form>` for the attributes and Add-to-Cart button, but I would like to customize the HTML layout of the form and add some other elements to it. For example:

1. I'd like to position the *Add to Wishlist* button next to the *Add to Cart* button
2. I'd like to add some HTML next to one of the attribute fields that is rendered (the Size select box).

Using the Devel module, I was able to pick up fields like `product:commerce_price` and `product:sku`, but none of the attributes or buttons within the actual `<form>`. I'm currently using jQuery to inject HTML into the form...but it's a hack am not all that comfortable with pushing into production.

Is there any way in my `tpl.php` file to print out the form attributes, quantity textbox and buttons individually?

Cheers!

# Answer
> 1 votes
Here's a good start on your first form alter for add to cart:

```
function MODULENAME_form_alter(&$form, &$form_state, $form_id){
  // Add to cart form overrides
  if(substr($form_id, 0, 30) == 'commerce_cart_add_to_cart_form'){
    kpr($form);
  }
}

```

# Answer
> 0 votes
To edit the "add to cart" form you can use `hook_form_alter()` or edit the function `commerce_cart_add_to_cart_form()` in `commerce_cart` module. In there you can add a second submit button called "wishlist" and add the HTML to the attribute widget. The `commerce_cart_add_to_cart_form()` function is quite long but it should be doable.

---
Tags: 7, commerce, theming
---


# Question
Title: How do I insert a view into an article based on filters that are only defined at node publish?
I have a website that uses data in tables. I want my copywriters to use a filtered view which will be in the node edit form to create the view they want for a particular article then somehow insert code into the page so that the data shows.

The views that are created will be different every time so this cannot be a pre-defined view as such, more a view with the filters that they decide to use at the time they publish the article.

Does anyone know how I might achieve this?

# Answer
So if I understand correctly you have a node edit page, with a view provided by the views module with exposed filters, probably in a block in block somewhere on the page.

Your copywriter will then put some parameters into the exposed filters and get some results.

If this is a custom view that you have made then there are not going to be any pre-made modules that suit your needs so to put the content that is returned into the body your options are:

1) Copy and paste

2) Write some jQuery that runs upon clicking the view row that insert the copy into the body

Here is some information on adding js in Drupal.
> 0 votes

---
Tags: views
---


# Question
Title: Allow users to upload files and attach to specific nodes
Here's what I'd like to do:

I have nodes A, B, C, and D

I want users to be able to upload files using a file field on node D, but then for those files to actually show on nodes A, B, or C, depending on what the user specifies during the upload process. So node D is just acting as an upload form of sorts -- it wouldn't show any of the uploaded files.

Is this possible to do with existing modules?

# Answer
> 0 votes
In a word, No.

At least not the way you are asking the question...

You need to be thinking about node types as well as just A, B, C & D.

I would look into the views module (tutorial here).

This would mean you could upload your files to nodes of a particular type, and then create several views that display different files uploaded based on your custom parameters.

It's a bit hard to be any more specific based on the broadness of your question.

---
Tags: views, files
---


title: Taxonomy Term Path to Search

text:
# Question
Title: Taxonomy Term Path to Search
Running Drupal 7:

Problem: I have a vocabulary that contains a list of faculty, within each faculty member term page is a list of research interests (a separate vocabulary) that are clickable. Currently they go to their individual term pages.

Goal: How can I make those "Research Interests" clickable and simply make it go to the search page with that term as the search query?

# Answer
> 1 votes
I see two options to achieves this.

The first one is to alter the `page callback` for the `taxonomy/term/%taxonomy_term` path through an implementation of `hook_menu_alter`. In the custom page callback, when displaying a term from your vocabulary, use `drupal_goto()` to redirect to the search page. And for terms in other vocabularies, you can re-use `taxonomy_term_page()` to preserve the original behavior.

The second option is to implement `hook_entity_info_alter()` to alter the `uri callback` of the `taxonomy term` entity type. In the custom URI callback, when getting the URI for a term of your vocabulary, returns the URI of the search page. For terms in other vocabularies, you can re-use `taxonomy_term_uri()` to preserve the original behavior.

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


title: Incorrect Time showing on frontend

text:
# Question
Title: Incorrect Time showing on frontend
I have installed the Date Module and added a date field to one of my content types, the widget I'm using is `Popup Calendar`. The problem I'm facing is that when I choose a date it seems to get stored and displayed correctly in the administration, but at the frontend the date is shown with two hours added to it.

For example if I set the fields value to `2014-12-12 10:00:00` its displayed as `2014-12-12 12:00:00` when I'm visiting a frontend page.

Like some of the comments have pointed out this might be because the frontend is displaying a visitors local time, but still I don't get why the time differance is two hours, when the differance between Findland and Sweden is only one hour.

I guess this has do do with some `Regional settings` or similar.

# Answer
> 3 votes
Maybe try this:

```
// Example: Assume we have a node with nid 1 which contains a single
// language-neutral date field named field_date.
$node = node_load(1);
$date = $node->field_date[LANGUAGE_NONE][0];

// Create a date object.
$date_object = new DateObject($date['value'], new DateTimeZone($date['timezone_db']));
// Convert from the database time zone to the user's time zone.
$date_object->setTimezone(new DateTimeZone($date['timezone']));

// Example: Print a formatted date.
print date_format_date($date_object, 'custom', 'Y m d');

```

Source: Convert a date field to the correct time zone

# Answer
> 1 votes
If you're printing the date yourself, you could try loading the date with the given timezone to see what's returned.

```
// Just for fun, load a node that you know has the date field.
$node = node_load($nid);

// Grab the date value and timezone.
$date_value = $node->field_time['und'][0]['value'];

// For testing, try both the field timezone, and the server default.
$date_timezone = $node->field_time['und'][0]['timezone'];
$default_timezone = variable_get('date_default_timezone', '');

// Produce the new date.
$date = new DateTime($date_value, new DateTimeZone($date_timezone));
echo $date->format('Y-m-d H:i') . '\n';

$date = new DateTime($date_value, new DateTimeZone($default_timezone));
echo $date->format('Y-m-d H:i');

// If you use Devel, just dpm it and see what you get back.
dpm($date);

```

---
Tags: 7, datetime
---


# Question
Title: Redirect User: Delay + Intermediate page
I have been trying to get a quick easy way to redirect the user, no matter where they go to the site straight to the user login page. But before I do, I want to redirect them to another page saying some message like "Sorry, you need to be authenticated to view blah blah... you are being redirected to the login page".

I currently have:

```
function mytheme_preprocess_page(&$vars, $hook) {
  global $user;
  if ($user->uid == 0 && arg(0) != 'user'){
    drupal_goto('user/login');
  }
}

```

# Answer
Before the goto call you can add drupal\_set\_message( $message, $status);

Its the more straightforward solution, although the message will be displayed inside the login page and there wont be any delay.

Or just change the goto path to a custom... 'user/sorry' page with your message, and something like:

```
 <div onLoad="setTimeout('myRedirect()', 6000)"></div>

```

and a JavaScript function

```
function myRedirect(){ window.location = "user/login"; }

```

Add the standard "if you are not redirected, click here" link in case JavaScript is disabled.
> 1 votes

---
Tags: users, redirection
---


# Question
Title: How do I change the default product on the "Add to cart" form with combined products
How can I set for example the mp3 as first item? Now it takes the `products (product reference)` from a product display node and display it in order of product creation.

In this example the "CD" was created before "MP3", but I want to be able to always display MP3 before CD.

I use a view with an add to cart field and the option `"Attempt to combine like products on the same line item in the cart."` checked.

>

# Answer
That checkbox you've mentioned is irrelevant, if I understand your request properly. The Add to Cart form assumes whichever product you reference first is the default product when it first builds the form (i.e. it has a product reference field value delta of 0).
> 0 votes

---
Tags: views, commerce
---


# Question
Title: How to theme maintenance page for omega subtheme?
Drupal's "Theming the Drupal maintenance page" gives a good overview for theming the maintenance page for 'normal' themes:

1. Copy `modules/system/maintenance-page.tpl.php` to your theme's templates directory
2. In the `settings.php` file, enable the `$conf['maintenance_theme']` variable
3. Copy you `page.tpl.php` contents into `maintenance-page.tpl.php` and edit as necessary

But my site uses an Omega subtheme, so I don't have a `page.tpl.php` (well, it's not quite the same as these instructions are anticipating). I'm a little lost among all the omega templates & regions.

How do I theme my omega subtheme's maintence page to look like the rest of my site?

# Answer
There's always a parent template, even if you don't see it in your base\_theme.

The inheritance will go:

1. omega\_subtheme template of NAME
2. then omega template of NAME
3. then drupal core template of name

So you'll need to copy the drupal core templates. They can be found in

```
DRUPALROOT/modules/system

```

You can find page.tpl, maintenance-page.tpl.php and all the base templates.
> 1 votes

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


# Question
Title: Javascript/jQuery fail after AJAX Referesh
I'm using Drupal 7 with **Drupal Commerce** and the **Commerce Product Option** module. Design goal is to have a visual product configurator for choosing custom furniture - an area on the **Add To Cart Form** where product images update as the user selects individual line item options.

So far I've implemented a semi-successful solution that uses jQuery to (A) modify the line item form to modify the product display area, and (B) add handlers to form elements. This javascript is attached to the form via a custom module, **hook\_form\_alter()** and **$form\['#attached'\]\['js'\]** which references a javascript file with a defined Drupal.behavior.

```
(function ($) {
 Drupal.behaviors.prod_form = {
   attach: function (context, settings) {...

```

The problem I'm having is with the Product Display form, which provides the user a SELECT list (ID=edit-product-id) to choose a specific product from a family of related products (4 seat sofa, 3 seat sofa, loveseat, etc.). Upon initial display everything works, however if the user selects another product the javascript form modifications fail. Looking at the console.log it seems as though the jQuery selectors are failing because they are being called before the form item exists. (no elements are found with selector ...).

I suspect the issue is related to when ajax is called vs. when the elements are being drawn, but stuck on how exactly to resolve. Any pointers or suggestions will be greatly appreciated.

Chris

# Answer
The CSS id may change on ajax refresh.

E.g edit-product-id, edit-product-id-1

Make sure your js can target the new form markup.
> 1 votes

# Answer
Try attaching the JS code using the `#after_build` function, somthing like this where the module is 'x'.

```
/**
 * Implementation of hook_form_alter.
 */
function x_form_alter(&$form, &$form_state, $form_id){
    $form['#after_build'][] = 'x_after_build';
}

function x_after_build($form, $form_state){
    if($form['#form_id'] === 'commerce_xyz_form'){
       drupal_add_js(/* ... */);
    }
}

```
> 0 votes

# Answer
If you don't want to target every possible id selector the product select list can have, you can add a #process element to the forms product\_id field and use inline javascript in the #process function. For example, in your form\_alter:

```
$form['product_id']['#process'][] = 'process_product_id';

```

Then add the process\_product\_id function that would look something like this and you can determine the id by using $element\['#max\_delta'\]:

```
function process_product_id($element, &$form_state, $complete_form) {
  drupal_add_js('jQuery(document).ready(function () { jQuery("product_id_' . $element['#max_delta'] . '").{more jquery code here}});', 'inline');
}

```
> 0 votes

---
Tags: forms, commerce, javascript
---


# Question
Title: Importing nodes with Node export is creating them in "unpublished" status
I'm importing content from one D7 site to another using the Node export module. However, when importing the content in the new site, the nodes are getting created in unpublished state. I have to publish them manually.

How can I have Drupal import the nodes in published state?

# Answer
At admin/config/content/node\_export there is Reset values on import \> \[your node type\] \> Published checkbox, which is not checked by default. Checking this will **reset** the published status, which means nodes will be **unpublished** (that's how I interpret that anyway). So leaving it unchecked will not change the status. There seems to be no way to force nodes to be published.

If needed, on the new site nodes can be mass published at admin/content.
> 0 votes

---
Tags: importing-exporting
---


title: cache_menu items are huge

text:
# Question
Title: cache_menu items are huge
Drupal 7.24

I have been stonewalled by an interesting problem on a D7 site. Essentially the cache\_menu table was getting very large but not just in items (6300 odd) some of the items are enormous.

Its a new record for me, one of the items is 1.24 mb and 26 of them are between 800k and 1mb.

The site went down when it was being git with slightly elevated traffic, its running on a load balanced AWS cluster with RDS at the back, there's no lack of resources for a 20 simultaneous connections site.

i truncated the cache\_menu and regenerated everything by browsing the site and all but a few of the items are gone now but there are still the 1.2mb one and a handful of the 800kb ones.

I followed this link - http://drupal.org/node/1234830 from here Huge cache\_menu table and it appears that this particular issue has been resolved for 7.13+ so i am thinking its something architectural going wrong.

There's no core hacks, we've got an impressive search system using a logic server network (running on SOLR externally) that does hook into taxonomy terms. The site is essentially a portal of links.

Could someone give me some pointers on where to start track this issue down?

edit: CID/sizes in cache\_menu, query:

```
SELECT cid, LENGTH(`data`)/1024 as `size KB` FROM cache_menu WHERE LENGTH(`data`)/1024 > '300' ORDER BY `size kb` DESC;

```

Result

```
links:management:tree-data:en:ec99d3452fef1ede622e66c68ba908b1dad455aa71f5e68648aeec6488b89c88
1094.2188
links:main-menu:all-cid:0:1:en
839.4873
links:main-menu:tree-data:en:ec99d3452fef1ede622e66c68ba908b1dad455aa71f5e68648aeec6488b89c88
815.6230

```

# Answer
> 3 votes
I suspect that you have some very large menus in your site. Rebuilding menus is a an expensive operation, and menu trees can vary page-to-page, user-to-user, etc. As a result, that data gets cached in `{cache_menu}`.

My suggestion is to query in your favorite SQL tool, and `print_r()` the data column for the large entries to see if anything looks out of the ordinary. In general, the data will be your menu tree with everything from the various `hook_menu()` entries added in. Modules that add extra data onto menu entries (like Menu Attributes) will have there data here, too.

You need to profile to see where the problem is actually happening.

It could be the result of a less-than-ideally configured MySQL instance. If you do have 1M cache entries, then you may want to bump up the query cache result set limit (I think this defaults to 128K).

You may also want to investigate using memcache or redis as your cache backend.

However, if you really do have huge menus, then the slowdown could be from unserializing all of that data. If this is the case, then you need to figure out a strategy to cache the menu output when your pages are being built up. Enabling block level caching may help, or you may need to make your own menu blocks, and cache that output yourself. Panels caching may be worth investigating.

It may sound odd, but you may also want try to disabling caching for `{cache_menu}`. The easiest way to do this is to install one of the dummy cache modules, and configure it to just use that cache backend for `{cache_menu}`.

---
Tags: 7, caching, users
---


title: How to override supersized.shutter.css

text:
# Question
Title: How to override supersized.shutter.css
I'm not the best in php manipulation that's why I'm asking.

```
function supersized_libraries_info() {
  $libraries['supersized'] = array(
    'title' => 'Supersized',
    'website' => 'http://www.buildinternet.com/project/supersized/',
    'download url' => 'https://github.com/f3ndot/supersized/tree/3718ae83f0945e327cc09530b959c5a8b049871f',
    'version arguments' => array(
      'file' => 'slideshow/js/supersized.3.2.8.min.js',
      'pattern' => '/Version : (\d+)/',
      'lines' => 4,
    ),
    'files' => array(
      'js' => array(
        'slideshow/js/jquery.easing.min.js',
        'slideshow/js/supersized.3.2.8.min.js',
        'slideshow/theme/supersized.shutter.min.js',
      ),
      'css' => array(
        'slideshow/theme/supersized.shutter.css',
        'slideshow/css/supersized.css',
      ),
    ),
  );
  return $libraries;
}

```

That's the all code of supersized\_libraries\_info() function. I wan't to hook that using hook system so for my theme it suppost to be mytheme\_supersized\_libraries\_info() right?

Then I wan't to just edit css location so that supersized.shutter.css will be in placed in my theme location.

(My code!)

```
function koko_supersized_libraries_info($variables) {
  $libraries['supersized'] = array(
    'files' => array(
        'css' => array(
        path_to_theme() + '/css/supersized.shutter.css',
        'slideshow/css/supersized.css',
      ),
    ),
  );

```

I just want to edit the css property of that object. I don't know how to get to there. Mine edit just doesn't work at all (nothing happends).

I want to clear css array and then set mine values.

# Answer
To alter the value returned from an implementation of `hook_libraries_info()`, a module or a theme needs to implement `hook_libraries_info_alter()`. As with other alter hooks, there isn't a way to override the value returned from a specific module, so the hook name is the usual one: `modulename_library_info_alter()` or `themename_library_info_alter()`.

As side note, you code contains also an error: The parameter is `$variables`, but the code is using `$libraries`.
> 0 votes

# Answer
Like `@kiamlaluno` said, you need to implement `hook_libraries_info_alter()`; however, you should change your code too into something like this:

```
function koko_libraries_info_alter(&$libraries)
{
   if( isset( $libraries['supersized']))
      $libraries['supersized']['files']['css'][] =
    path_to_theme().'css/something.css';
}

```

This way you only insert an additional CSS at the bottom of the library CSS files, and if the library changes its filenames, or (more likely) add more files, you wont need to change your hook as well. Note that `$libraries` is passed by reference.

You only ensure that your custom CSS is always the last to be valued.
> 0 votes

---
Tags: hooks, theming
---


# Question
Title: Converting Simplenews Subscribers to Users
I was wondering if there is a way to convert SimpleNews subscribers into actual Drupal users?

Currently, I have something similar going on using custom fields in the user-register form, but wanted to know if I can leverage the Simplenews module for my needs.

I want to create a block where users can register to receive weekly e-mails in which they receive information about our weekly ad.

Cheers,

Elm

# Answer
this may be useful http://bouteillenicolas.com/expertise-drupal/simplenews-save-subscribers-info

All you have to do is use rules, create a webform, and then use rules that handdles that webform and create the suscriber and the the user using the information sended through the webform
> 0 votes

# Answer
From the simplenews api:

```
/**
 * Act after a new subscriber has been created.
 *
 * @ingroup subscriber
 */
function hook_simplenews_subscriber_insert($subscriber) {

}

```

This is a hook function that is executed every time there is a new subscriber. You must use this function in your module replacing 'hook' by your module name. Try the following code:

```
/**
 * Implements hook_simplenews_subscriber_insert().
 *
 */
function mymodule_simplenews_subscriber_insert($subscriber) {
  $user = new stdClass();
  $user->name = 'happyUser';
  $user->mail = $subscriber->mail;
  $user->pass = 'password';
  $user->status = 1; // omit this line to block this user at creation
  // save the user
  $user = user_save($user);
  // connect the subscriber with the user
  $subscriber->uid = $user->uid;
  simplenews_subscriber_save($subscriber);
}

```
> 0 votes

---
Tags: 7, users, emails
---


# Question
Title: Is it possible to use image styles in Views field rewriting?
I would like to add "no results" behavior to an image field displayed in Views, such that the image from an alternate field is displayed. Ie., if Image1 is empty, display Image2.

Is it possible to use an image style in the rewrite code? I'm sure I can display the second image, using something like `<img src="[field_Image2]">`, but how can I specify that the image be displayed using the `max_height_125` image style?

# Answer
> 1 votes
I figured it out! What you have to do is include a copy of the second field, set to "Exclude from display" in the options, and arrange the fields such that Image2 comes before Image1 in the list. You can set the image style in the options for Image2, and that information will get carried over when Image1 is empty and gets rewritten using the behavior specified in the "No results" option. Also, you don't have to write `<img src="[field_Image2]">` in the rewrite area. All you need is the token for the other field, like `[field_Image2]`.

---
Tags: views, media
---


# Question
Title: How not to display some required fields on registration form?
My user form is pretty long and many of the fields are required. However I don't want to discourage lazy users from registering. I would like them to register and pay first then make them fill out the required fields when they edit their profile. I would like the required fields to be required when editing their profile but do not want to show them on the registration form. Right now making a field required automatically puts it on the registration form. How do I prevent this? Thanks.

# Answer
The Field Permissions module did exactly what I wanted.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 0 votes

# Answer
First make fields not required and then use the Field Validation module. You can validate each field as per your requirement.

> The following validators are currently included:
> •Regular expression
> •Numeric values (optionally specify min and / or max value)
> •length (optionally specify min and / or max length)
> •number of words (optionally specify min and / or max words )
> •Plain text (disallow tags)
> •Must be empty (Anti-Spam: Hide with CSS)
> •Words blacklist
> •number of selections (optionally specify min and / or max selections )
> •Unique
> •Match against a field
> •Match against a property
> •Specific value(s)
> •Require at least one of several fields
> •Equal values on multiple fields
> •Unique values on multiple fields
> •PHP Code (powerfull but dangerous)
> •URL (support internal path and external url validation)
> •Email
> •Pattern (Regular expression lite)
> •Date range2
> •Date range(living in sub module date validation, deprecated in future)
> 2 votes

# Answer
User Role Field will perfectly achieve this objective and it is lightweight.

```
This module allows you to specify role specific fields. When creating a new field,
you specify for what roles this field is enabled.

```

All you have to do is enable the module, specify required fields, but only make them enabled for specific roles (e.g authenticated user). Make sure the fields are not enabled for anonymous users so that they do not show on the user registration form.
> 1 votes

# Answer
Use the profile2 module and make those fields required on the profile type.

That way they don't get in the way of registration.
> 0 votes

---
Tags: 7, users, entities
---


# Question
Title: Save image in any weight and immediately reduce it
I am building a site using drupal 7. I created a node form for users to write content and upload images (using the core image field).

Is it possible to let users to upload images of 5-10 MB (and more), and immediately reduce the weight of the image to only 1 MB, and only then save it on my Drupal site?

My goal is that user will be able to upload any image size they want, but still save space on my Drupal site.

# Answer
> 1 votes
I'm finding that drupal 7 does that out of the box (although it's possible I have a module doing it. Rather than fixing the size of the file, set the max pixels for the image and drupal will resize it (and thus reduce the size) on upload.

---
Tags: media
---


# Question
Title: Way to display View block only when a specific option is selected in Facet
I have a view block which I want to display on page only when a specific item in facet is selected (eg Year) . I am struggling to get this done , I tried with contextual filter but it seems it doesnt work with Solr index . Any pointer on how can i control the behavior of display of my view block on facet combo.

Thanks! Carol

# Answer
In common situation, when facet is active - you have GET params in your url. You can use it as condition for programmatically display view. For example

```
if (!empty($_GET['my_facet'])) {
  print views_embed_view('view_name', 'display_name');
}

```
> 0 votes

---
Tags: views, search
---


# Question
Title: Can a Panel be converted to a Mini-Panel?
I have a panel. I have my link to the panel. What I can't do is put that page as a block. Honestly, I'm not sure the purpose of a panel if you can't put it anywhere other than link to it.

I read you can use mini-panels to make a block. Is this accurate? If it is can I convert a Panel that I already have into a Mini-Panel so that when I go to the blocks, I will see that Mini-Panel and be able to assign it to a region?

Am I misunderstanding things?

Thanks.

# Answer
> 1 votes
Yes and no. Panels is a module with a whack of facets. Based upon the context of your question it sounds like you created a page via the panels interface. So. That's a page and that's why you can only really link to it ( or override another drupal generated page.

Mini panels are exposed as blocks and also as elements usable in other panel facets (like pages or other mini blocks).

You'll have to create a new mini panel from scratch but all the elements you used to create that custom page are available to you. If you made custom elements just check the make reusable and then they'll be available to your mini panel.

---
Tags: blocks, panels
---


title: Secure Pages Domain Access for Drupal 7

text:
# Question
Title: Secure Pages Domain Access for Drupal 7
I ran into a problem using Secure Pages with multiple subdomains. Secure Pages only seems to allow you to put one domain for SSL and not secure pages. I found the following module in Drupal 6, but I'm wondering if there is another project people know about to solve this problem in Drupal 7?

https://drupal.org/project/securepages\_domain

# Answer
> 2 votes
You can actually just leave the base URL and Secure URL blank to not have it redirect to an inappropriate subdomain than you're on currently.

To restate my problem, I had multiple subdomains sharing one database where the Secure Pages module was implemented. If I put down a base and secure URL using one subdomain, I would get redirected to that instance from other subdomains not listed there when https was needed for that subdomain.

This is an undocumented solution as far as I'm aware, so I hope it helps someone else out.

---
Tags: 7, security, domain-access
---


title: Taxonomy Access Control

text:
# Question
Title: Taxonomy Access Control
I'm creating a site which will have multiple 'store' sections, with each store's staff needing to edit their own content, but not anyone else's.

The eventual layout will look something like this.

* Store One
    + Page A
    + Page B
* Store Two
    + Page C
    + Page D

This is fine - I figure I should have a vocabulary for 'Stores' and a term for each Store, and then use an access control module to limit page editing based on term.

Now, the complexity: we also need a certain amount of custom information displayed on the front page for each store (think opening hours, location etc). I figure the best place way to achieve this is to have a set of custom fields for each term, and then display them in a view that also lists the pages for the store.

**Thus the problem:** How do I allow a store to edit their term (and it's custom fields) but not others?

Will gratefully receive to any and all potential solutions.

# Answer
I have a similar use case on my site. I ended up making stores a content type for that very reason. Entity reference is your friend cause you can create page a and b and link em to the store content entity.
> 0 votes

# Answer
I think you would like the Workbench suite of modules. The Workbench Access module allows you to only allow certain users to edit sections of your website, so you could set the permission at the store level and it would cascade down to all of the pages associated with the store. It works well with taxonomies.

https://drupal.org/project/workbench
> 0 votes

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


title: Vote Results Zero

text:
# Question
Title: Vote Results Zero
I am fairly new to this drupal and I can't seem to get the rate widget integrated into views so i can output a chart on my custom page. I set up the relation to "vote results" and set to the the custom widget I created on rate. I have tried every option the field "vote results" is zero. My configuration is as follows:

Rate widget: name: Reviews tag: vote\_tag type: options

Views: Relation Filter: Vote Results tag: vote\_tag aggression: Number of votes

Fields: Vote results: value Vote: value

the vote results gives me a zero and also how can I print out the label of the option rather than than value. It is display correctly in results page of the node but I can't print a chart using that data or integrate into view

# Answer
> 0 votes
VotingAPI module provides an API for other modules to cast votes on any entity. There are many modules that support VotingAPI, such as FiveStar, Rate, etc.

Making use of VotingAPI actually depends on your approach.

FiveStar module, for example, does NOT save data to VotingAPI-related in certain widgets. First, you need to make sure you are actually recording values to VotingAPI. Fivestar module requires VotingAPI by default, but does not use it for these widgets.

(img)

If you are using some other module or unsure, check `votingapi_vote` table to see if there are actual data in the table.

In Views, the relationship's configuration is *very* important.

* **Value type**: Points
* **Vote tag**: (choose the tag)
* **Aggregation function**: Number of votes

---
Tags: views, theming
---


# Question
Title: How to exclude current node from a block view?
I created a block view listing nodes of the content type: **cars**.

I added the block to the second sidebar.

After, I created 2 nodes of this type with the titles: **car-1** and **car-2**.

Then the view block shows these 2 nodes. So far so good.

If I visit the page **example.com/car-1** I see the block listing both the car 1 and car 2 nodes. I want to exclude the **car-1** node from the block since I'm at: **example.com/car1**

**This is what I did in the view:**

```
1.  Click on add under "contextual filters".
2.  Choose Content:nid.
3.  Under "when the filter variable is not available, choose "provide default value".
4.  From the drop down menu select "content id from url".
5.  Scroll all the way down to the bottom of the window and click on the
6.  "More" link.
7.  Click "Exclude"

```

I works fines if I visit a node, but the block is not shown in any Views (i.e.: in the **frontpage** view )

I know that the reason is that the Content nid is not present in a view, but don't know how to workaround this.

# Answer
> 1 votes
One option is to clone the block, make it show everything (remove the contextual filter and the exclude setting) and in block configuration (via admin/structure/block) configure it to show on all pages except node/\*.

Another option, if you want to have everything in one display and don't mind using php, is to use Provide default value \> PHP code:

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  return arg(1);
} else {
  return 0;
}

```

The exclude checkbox must be on.

So this is giving the sql the node id to be excluded, normally the current node id, and when there is no node id, the node id to be excluded is 0, in other words don't exclude anything as there is no nid 0.

Without checking that the second argument is numeric, this wouldn't work on the default front page as it would have 'node' but not have nid.

# Answer
> 0 votes
A use case for Page Manager / Panelizer. This is ment to be for this type op content page creation.

An other way is the context module. In that case you can define on which pages which context is used. Good example of this is in the julio distribution (www.drupal.org/project/julio)

If you are interested in the Page Manager way, watch this screencast http://nodeone.se/sv/node/702

---
Tags: nodes, blocks, views
---