# Question
Title: How can I print a block (the language switcher) without the block-related classes?
I'm not sure if this question is phrased correctly; I'm happy to accept any solution that accomplishes my aim.

**GOAL**: I am trying to print the language switcher block in the header of my theme without the block-related classes, because the theming for these classes assumes that the block will be printed in the main content area of the page.

Usually, I've been adding the language switcher block as a *widget* using the Panels module. When I do this, no block-related classes are printed, and it's much easier to style the CSS. However, I can't add the widget in the header because I'm not using Panels Everywhere and Panels only overrides the main content area of the page.

I looked in locale.module and tried calling the block directly via `local_block_view()`, but this still adds the CSS classes that I don't want.

Is there a way to print the block without the block classes? Or, barring that, how can I remove the classes for this specific block?

# Answer
> 2 votes
Digging `locale_block_view()` out of locale.module:

```
/**
 * Implements hook_block_view().
 *
 * Displays a language switcher. Only show if we have at least two languages.
 */
function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

```

shows that it is "just" theming up some links. So, you have a couple options here that may work depending on what exact divs/CSS you want/don't want:

1. Override `theme_links()` to use "links\__local\_block" and wrap it in some divs that you can apply CSS to.
2. Stuff all the guts above in a custom module's `block_view()` so you can override its block CSS.
3. Add different or additional classes to the `$variables[class']` array,
4. Include, or override in your theme, a different locale.css file,
5. Override the `block.tpl.php` for this specific block, eg, `block--locale.tpl.php` (see: http://drupal.org/node/1089656) (copy it out of `.../modules/block/block.tpl.php` and into your theme and change the classes)

---
Tags: blocks, i18n-l10n
---


# Question
Title: How do I put this custom CSS and JavaScript into a certain block?
I'm having a hard time getting this: http://dev.chrisruno.com/sahshe/quiz/ To go into a block in this node: http://sahshe.chrisruno.com/?q=node/22#

I've successfully included the two Javascript files I need, but I can't figure out how to apply the css to ONLY what is inside the block. I've only gotten as far as including the CSS file in my theme's .info file, but that makes the whole site look crazy.

# Answer
In very broad strokes, in your module's `block()` or `block_view()` hook, you would do something like this:

```
 drupal_add_js(....);   // see http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7
 drupal_add_css(....);  // see http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_css/7

```

and to have the CSS apply only to that block, look at what Drupal's block theme functions wrap the block with, and then using one of those ids or classes, cascade your CSS accordingly, eg, instead of:

```
.content {
  ....
}

```

use:

```
#BLOCK-ID .content {
   ....
}

```

or:

```
.BLOCK-CLASS .content {
   ....
}

```

Of course, you would return as the block's content either the HTML or a renderable array of it.
> 1 votes

---
Tags: nodes, blocks, javascript, theming
---


# Question
Title: D7 Why I cannot just copy a template file from a module to my custom theme to override it?
I'm using the TimeField module with a custom theme (a subtheme of the Bootstrap theme) and I want to change how the output is rendered.

There's a `timefield.tpl.php` file located at

> sites/all/modules/timefield/theme/timefield.tpl.php

which I want to modify copying it to

> sites/all/themes/my\_theme/templates/

but when I do so the copy is ignored and the original file is loaded instead.

I'm a Drupal newbie but I like to learn, so any advice or link to a resource to understand where the problem lay is fine.

# Answer
Create tpl file for field field--field-name.tpl.php. place it to your theme.

> if Field name is: **field\_page\_photos**
> then File name will: **field--field-page-photos.tpl.php**

copy `sites/all/modules/timefield/theme/timefield.tpl.php` code to above tpl file. make changes and clear cache.
> 1 votes

---
Tags: 7, theming
---


title: How to pass link to Read More manually

text:
# Question
Title: How to pass link to Read More manually
I enabled the blog module and I created the blog called test blog. I created the template file as `page--blog.tpl.php`. Here is my code:

```
   <!--ip_mainLeft starts here-->
    <div class="ip_mainLeft">

        <h1 class="ipMainHeading">News</h1>
         <?php
        $type = "blog";
        $nodes = node_load_multiple(array(), array('type' => $type));
        foreach($nodes as $news):
        ?>
        <!--newsEnclose starts here-->
        <div class="newsEnclose">

            <!--newsDateInfo starts here-->
            <div class="newsDateInfo">

                <span class="news_date"><?php print date( "j",$news->created); ?></span>
                <span class="news_month"><?php print date( "M Y",$news->created); ?></span>

            </div>
            <!--newsDateInfo ends here-->

            <!--newsText starts here-->
            <div class="newsText">

                <h1 class="newsTextHeading"><a href="<?php print $node->nid; ?>">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a></h1>
                <p><?php $body = field_get_items('node', $news, 'body');
                        $teaser= $body[0]['safe_summary'];
                        print $teaser; ?></p>

                <a href="javascript:;" class="ip_readMore">+ Read More</a>

            </div>
            <!--newsText ends here-->

        </div>
        <!--newsEnclose ends here-->

```

If the heading or ReadMore button is clicked. I want to display full blog content of particular node in the blog content type. How to pass the link in anchor tag.

# Answer
> 0 votes
missed value in `href`. replace below code.

```
<h1 class="newsTextHeading"><a href="/node/<?php print $node->nid; ?>">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a></h1>

```

---
Tags: 7, nodes
---


title: How to get Term ID by its custom field?

text:
# Question
Title: How to get Term ID by its custom field?
I'd like to get Term ID by its custom field. I would like to do this using EntityFieldQuery().

Here's what I have so far:

```
  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', '1')
    //I need help with this line:
    ->fieldCondition('field_foo', $fieldValue)
    ->range(0,1)
    ->execute();

```

**Update** \- I'm providing screenshots to make it more sense.

Here's a view of the custom field

I'm basically trying to get "myTermName" Name field, by "myValue" Foo field.

# Answer
There is undefined value in `fieldCondition`. there are some examples listed below. try one of these format.

```
->fieldCondition('field_foo', 'tid', array('12','13'), 'IN')
->fieldCondition('field_foo', 'value', 'spotlight', '=')
->fieldCondition('field_foo', 'fid', 'NULL', '!=')
->fieldCondition('field_foo', 'tid', $value)
->fieldCondition('field_foo', 'value', $year. '%', 'like')
->fieldCondition('field_foo', 'value', NULL);

```
> 3 votes

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


title: How to override webform in template.php

text:
# Question
Title: How to override webform in template.php
I've followed different tutorials but I cannot seem to override a field on my webform via a function in template.php.

> Theme is called: 'myTheme'
> Id of the form is: 'webform\_client\_form\_76'
> Id of the input: 'edit-submitted-henkilotiedot-etunimi'
> Name of the input: 'submitted\[henkilotiedot\]\[etunimi\]'

The function I think should work:

```
function myTheme_webform_form_76 (&$vars) {
    $vars['form']['submitted']['edit-submitted-henkilotiedot-etunimi']['#value'] = t('Name');
}

```

What is the correct format to override webform elements?

# Answer
```
function [themename]_form_webform_client_form_76_alter(&$form, &$form_state, $form_id) {
// code of altering
}

```
> 1 votes

---
Tags: webforms, theming
---


# Question
Title: Drupal Views in Glossary mode removing pager
I am adding alphabetical page to the view using glossary mode. I am able to create the alpha pager but the issue is, when I click on the alphabet the alpha pager doesn't appear again. I have to go back to view the alpha pager.

# Answer
From what I remember, you have to create the Glossary display of the view, and then you set the results page as an Attachment of that view display (attachment being the view display type).

Views ships with a default Glossary view, it's just disabled. I would suggest enabling that and take a look to see how that does it.
> 1 votes

# Answer
I found the solution to this problem. This link explains how to resolve this issue http://drupal.org/node/349739
> 1 votes

---
Tags: views
---


title: Modify value only if node is new

text:
# Question
Title: Modify value only if node is new
I am using the following function to alter the node's data before saving it to the database.

```
function mymodule_node_presave($node) {
  if ($node->type="mytype") {
    if ($node->is_new) {
      $node->status = 0;
    }
  }
}

```

How do I know that the node is new and not updated/edited? In the example, you may see I have used `$node->is_new`, and I need to make sure that is correct. So is it?

# Answer
The `is_new` property is set by the node\_save function, which is the same function that will invoke hook\_node\_presave \- so your are safe in your assumption that this property will be present.

If you were not doing this in hook\_node\_presave, another way of testing if a node is new is by checking if the `nid` property is present and non-zero:

```
if (empty($node->nid)) {
  // ... this is a new node ...
}

```
> 6 votes

---
Tags: 7, nodes
---


# Question
Title: Automatically fill fields taking value from user profile
I have a custom content type "Holiday". There is role for users, "Sponsors". Only the sponsor users can create this "Holiday". "Holiday" has many fields. Three of them are:

1. Sponsor Name
2. Sponsor About
3. Sponsor image

Also users have fields as name, about and image. Now i want that when a sponsor user is logged in and he/she creates a "Holiday" then the above three fields, i.e, 1. Sponsor Name 2. Sponsor About 3. Sponsor image are automatically filled in from the Sponsor user profile information, ie., Sponsor name is automatically filled in as the user name (who is logged in and creating the "Holiday"), Sponsor about from the User:about and Sponsor image from the image field provide for user. How can i achieve this.

Any suggestions?

Thanks

# Answer
> 1 votes
use the form api and hook\_form\_alter http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_alter/7 and set the values of the form items to the items you specify WIth form api you can specify a default value which you can set to what is in the user profile.

# Answer
> 0 votes
First of all, sponsor should be a node author. So you don't need to store any additional fields in node, just override `node--[type].tpl.php` to display author fields.

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


# Question
Title: Create a multistep Webform and set to "non-linear" with sidebar showing which steps have been completed?
I have several steps in my Webform that require certain values to pass each step.

This is done by Webform Validation and seems to work fine, however how can I turn the Webform into something that's "non-linear" allowing users to jump to any page they want to complete with ease.

Ideally I'd want to move the titles for each multistep page to a sidebar menu which would show the status of whether that page is completed or not.

Is there any modules that do something similar already?

# Answer
> 1 votes
I searched for how to create this functionality, and found this on the drupal site Link for creating multi-step webforms

---
Tags: webforms
---


# Question
Title: Setting up sub sections with their own editors
I'm new to Drupal (v7.21) and hoping to use it for a site that contains several sections each run by a separate owner and their team of editors. Just wanted to ask if it would be possible and how I could go about it. The type of flow I'm looking for is:

```
Main Site
- Forum
- Store

  Section One
  - Blog
  - Book

  Section Two
  - Blog
  - Book

```

As normal the Admin would have overall control with each section having an 'owner' that can edit their sections Blog, Articles etc. The owners would also be able to give an 'editor' role to other users so they can edit content within the section.

It would be helpful if the urls for the site were:

```
domain.com/
domain.com/forum/
domain.com/store/

domain.com/sectionone/
domain.com/sectionone/blog/
domain.com/sectionone/book/

domain.com/sectiontwo/
domain.com/sectiontwo/blog/
domain.com/sectiontwo/book/

```

If I haven't included enough information please let me know. Any help would be greatly appreciated.

# Answer
Organic Groups is probably what you're looking for. Checkout the following help resources.
> 1 votes

---
Tags: routes
---


# Question
Title: Is there a list of default fields and default widgets for drupal 7
Where can I a list of available (in the core) fields and widgets and their names so I can reference them when adding fields to my own node-type definitions ?

# Answer
> 2 votes
To get a list of all field definitions use `field_info_fields()`

> Returns all field definitions.
>
> Use of this function should be avoided when possible, since it loads and statically caches a potentially large array of information. Use field\_info\_field\_map() instead.

You can ignore the second paragraph of that as `field_info_field_map()` hasn't actually been included in a Drupal release yet.

For widgets use `field_info_widget_types()`

> Returns information about field widgets from hook\_field\_widget\_info().

---
Tags: entities
---


# Question
Title: Using EntityFieldQuery's FieldCondition on file fields (or complex fields)
I see plenty of examples of using FieldCondition on basic fields but in my case I would like to query if the file field holds a specific file name.

The structure in the entity object (with language undefined) is:

```
$entity->field_file['und'][0]['filename']

```

This is what I have tried:

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', $type)
  ->propertyCondition('status', 1)
  ->fieldCondition('field_file', 'filename', $tokens[1], '=')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

```

Perhaps it is having trouble because of the \['und'\]\[0\] not sure? Thanks.

Here is the detailed error:

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_data_field_file0.field_file_filename' in 'where clause': SELECT field_data_field_file0.entity_type AS entity_type, field_data_field_file0.entity_id AS entity_id, field_data_field_file0.revision_id AS revision_id, field_data_field_file0.bundle AS bundle FROM {field_data_field_file} field_data_field_file0 INNER JOIN {eck_downloadable} eck_downloadable ON eck_downloadable.id = field_data_field_file0.entity_id WHERE (field_data_field_file0.field_file_filename = :db_condition_placeholder_0) AND (field_data_field_file0.deleted = :db_condition_placeholder_1) AND (eck_downloadable.status = :db_condition_placeholder_2) AND (field_data_field_file0.entity_type = :db_condition_placeholder_3) ; Array ( [:db_condition_placeholder_0] => rnd13_poster_pack.pdf [:db_condition_placeholder_1] => 0 [:db_condition_placeholder_2] => 1 [:db_condition_placeholder_3] => downloadable ) in field_sql_storage_field_storage_query() (line 582 of C:\www\sr14\modules\field\modules\field_sql_storage\field_sql_storage.module).

```

# Answer
> 2 votes
A file field only contains the `fid` (file ID) relating to the file. The extra data you see (filename, uri, etc.) are loaded by the file module, but are actually contained in the `file_managed` table, which is not a field table.

Since `EntityFieldQuery` doesn't support `JOIN`s you're out of luck, unless you alter the query a bit later on, e.g.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->addTag('customtag');

...

function MYMODULE_query_customtag_alter(QueryAlterableInterface $query) {
  $query->innerJoin('file_managed', 'file_managed', 'file_managed.fid = field_data_field_name.fid');
  $query->condition('file_managed.filename', $something);
}

```

That will obviously need some tweaking for your specific situation.

---
Tags: files, database
---


# Question
Title: Add ubercart catalog paths to xml sitemap
The catalog paths don't appear in the xml sitemap with ubercart 3 and drupal 7. How can this be done.

# Answer
> 0 votes
Updating to 7.x-3.4 solves this problem.

# Answer
> 0 votes
Make sure that you have **XML sitemap node** enabled.

Go to **/admin/structure/types** and make sure that your product type in set for inclusion in the XML Sitemap by default. If you have to change it, then if the pages you already have are set to 'default' they will react properly. If they are set to 'exclude' you will have to edit each page and change it.

Then go to **/admin/config/search/path/patterns** and set your catalog path to `catalog/[term:name]` and your catalog product page paths to `catalog/[term:name]/[node:title].`

If you have to regenerate your aliases, make sure that you retain the old alias, or use the Redirect to issue a 301 redirect for old aliases.

Then regenerate the site map. These steps should cover off any reason why the paths are not in your current sitemap.

---
Tags: ubercart, xml-sitemap
---


# Question
Title: cant see the list of databases in Feeds Database module UI tab
I have installed the feeds module and Feeds Database module so i can migrate contents inside my non drupal datase to a drupal 7 one. But i cant see the list of databases in the Feeds Database tab. Anyone can help?

Here's a code of my database in settings.php

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'karljay',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),

  ),
   'test' =>
  array (
    'test' =>
    array (
      'database' => 'joan',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),

  ),
);

```

this seems to be the right code cause i can see the test database now in the database's list in drupal but i have a database error when i import something using feeds. and here's my error

and to add more details here's my query

```
$q=msyql_query("SELECT subject from forumthreads");
$result=mysql_fetch_array($q);

```

and here's my mapping

i only have one field cause this is a test if i can really use feeds to migrate many data from other database

# Answer
> 2 votes
The documentation for this module is poor, but the solution is simple.

The module picks up the $databases array defined in your settings.php file. In most installations, only one database 'default' is defined. Use the format for 'default' and define a second database say 'test', listing the correct connection credentials. The 'test' database will show up in the drop down. The module removes 'default' from the list because it makes no sense to map a database to itself.

I think better documentation for Feeds Database is in order :). However, the core Database API can be configured for multiple databases. See Database Configuration.

---
Tags: 7, feeds
---


title: Add variable to rule before execution

text:
# Question
Title: Add variable to rule before execution
I'm looking for a way to alter the variables before a rule is executed. Specifically, I'm trying to add a list of users who should be notified of a new comment so that I can create a loop and send an email to each.

I have implemented `hook_rules_event_info_alter` as follows:

```
function mymodule_rules_event_info_alter(&$events)
{
    $events['comment_insert']['variables']['affected_users'] = array('type' => 'list<user>', 'label' => 'Anyone that should be notified about a new comment.');
}

```

However, I am at a loss as to which hook needs to be implemented in order to fill in this variable before it is used. (On my site the default will be the node author, however there are some nodes where several users should be notified).

# Answer
The implementation should be placed into the file `MODULENAME.rules.inc`, which gets automatically included when the hook is invoked.
> 0 votes

# Answer
In the end I discovered I don't actually need to create my own variable to do this, instead I can add the list of members via the views conditions. Select 'Entity has field' and choose you list field. Now when you add a loop, the field will come up in the data selectors.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Simplest way to let writers edit Views headers/titles without Views UI access?
What's the simplest\* way to enable non-technical writers, editors etc to *edit the text* in Views headers, titles, footers etc, without needing to enable Views UI on a production site, train these non-technical staff to use some of it, and grant them Views UI permissions?

---

It's common for content staff - writers etc - to have nothing to do with site building tools like Views UI. It's not their remit or expertise. Also, they'll usually be editting content on the production site, while site builder UI tools like Views UI are often disabled on production sites to reduce unnecessary memory consumption (less PHP files to parse for hooks).

But, the text content of the title fields, view headers, etc is within their remit and expertise. What's the simplest way to bring these text snippets - but not the whole Views UI - within their reach?

\*Here, '**simplest**' means minimal extra modules, minimal complexity in workflow, minimal overheads) Options using Panels are fine in my case. Ideally, I'd prefer to avoid needing to use Display Suite.

---

The workaround I'm using at the moment, which just about works (but I'm sure there's a simpler way) is this:

* I have a custom taxonomy vocabulary, 'Text Snippets'
* Each Text Snippet has a name describing to editors where in the interface it is used
* Each Text Snippet description contains the HTML to be used
* The views' headers are set to 'Render entity' with the ID of the appropriate Text Snippet term written in
* To stop the internal-use-only term name being displayed, I have a custom template in my theme templates folder, `taxonomy-term--text_snippets.tpl.php`, containing nothing but `<?php print preg_replace("/<p[^>]*>[\s| ]*<\/p>/", '', $description ); ?>` (the preg\_replace regex removes empty paragraphs)

---

I'm aware of a module, Snippets, which seems to have a similar idea, but it's not at all clear what the intended usage is, there's very little information - blank readme file, documentation is only placeholders - and the very low usage stats and queue history don't fill me with confidence.

# Answer
> 3 votes
You can use the Views UI: Edit Basic Settings module:

> "Views UI: Edit Basic Settings" places edit tabs on Views pages, similar to node pages, and allows users with the correct permission to modify their header, footer, title, empty text, or number of items to display. This module also provides a separate interface that displays a list of views. All Views are defined by you, so you can exclude certain Views.

# Answer
> 1 votes
Make a Taxonomy Vocabulary "Views Title", add terms. Each term represents a 'view'. Taxonomy is entity, so it is field-able. For example, you can use the description field as View's Header; Term name as view's title.

Assign permission to manage "Views Title" Taxonomy for your editor.

Within you module, use "hook\_views\_pre\_render", alter the view title/header to be term's name/description.

---
Tags: views, workflows, nodes
---


# Question
Title: Add user to a group after the user makes a comment in that group
is this possible in Drupal Commons (Drupal 7) using Rules:

If a user makes a comment on a post in a certain group, have a rule which makes the user a member of the group automatically.

Why do I want to do this? Well, the contributors block in Drupal Commons is not showing all those who comment in a group. I found that the reason for this was that the particular user is not yet listed as an active member of the group.

Thank you!

# Answer
The answer is ... yes, it is possible ... and easy to do ... with Rules.

If anyone coming across this is new to Rules or needs a refresher I highly recommend Johan Falk's free screencast series. It's excellent. http://nodeone.se/en/learn-the-rules-framework

See the screenshot for how I did it, and also the exported Rule below.

```
{ "rules_lambeth_comment_join_group" : {
"LABEL" : "lambeth comment join group",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "og", "comment" ],
"ON" : [ "comment_insert" ],
"IF" : [
  { "entity_has_field" : { "entity" : [ "comment:node" ], "field" : "og_group_ref" } }
],
"DO" : [
  { "og_subcribe_user" : {
      "user" : [ "comment:author" ],
      "group" : [ "comment:node:og-group-ref:0" ]
    }
  }
]
}
}

```
> 0 votes

---
Tags: rules, organic-groups, 7
---


# Question
Title: User click on log in when user already logged in so should throw message.
I am write some code for user login. But i want when user click on log in button every ,that time checks user already logged in or not . if user logged then throw the informative message and if not throws error. How i do this.. Please help me..

# Answer
You can check value of field `uid` of global variable `$user`:

> `global $user;`
>
> Contains preferences and other account information for logged-in users. When a user is not logged-in, the `$user->uid` property is set to 0.

http://api.drupal.org/api/drupal/developer!globals.php/global/user
> 1 votes

---
Tags: users
---


# Question
Title: How to create a page on which users can upload files?
Maybe it's a question of logic. I'm new to Drupal.

Drupal 7: I want to have a page 'upload' which should be displayed in the main menu, on that page users should be able to upload files (pdf etc), which afterwards will be listed on a second page 'downloads'.

I created a content type 'uploads' with all the fields I need (title, description, file, tags). **How do I get that content type inside a static page?** Until now I can only access that uploading process when I hit 'add new content' on the home page.

# Answer
To create page 'downloads' you can use Views module and create page that contain listing of nodes of your content type.

To create 'Upload page' you can just add link to `node/add/YOUR-CONTENT-TYPE` to main menu.
> 2 votes

---
Tags: files
---


# Question
Title: Limiting Views diplays to a role — two displays are stuck together
I have a View with two displays, one for role1 and one for role2. When I set the access control for the first display to role1 and save the View, then set the access control for the second display to role2, it changes the first display to only be accessible to role2 as well. Have I encountered a bug, or could there be some set of configuration options causing this?

# Answer
> 2 votes
When you set the persmissions for a display, the following popup box shows up

below the title, there's an option that allows you to change the access restrictions to "All displays" or "This page(override)"

# Answer
> 0 votes
I think this may be a bug in Views. Here is the workaround that worked for me:

1. Edit both of the displays and change "This page (override)" to "All Displays".
2. Set one of them to the way you want it.
3. Edit the other display and change it back to "This page (override)".
4. Set that one the way you want it.

It seems to happen that a display cloned from another display confuses Views, but this fixed it for me.

---
Tags: views, users
---


title: Adding images to the right sidebar

text:
# Question
Title: Adding images to the right sidebar
Can anyone please tell me, using very simple terms, how to add an image to the right sidebar?

# Answer
1. Upload image to server using FTP or via some file manager module, like IMCE, elFinder, etc.
I strongly suggest put it in somewhere inside `/sites/default/files` (sub)directory.
2. Navigate to `admin/structure/block/add` to start creating new block
3. Set empty title
4. For body field select format 'Full HTML' and enter code
`<img src="/sites/default/files/YOUR_IMAGE_NAME.jpg" alt="IMAGE_DESCRIPTION"/>`
5. From region selection list, select 'Sidebar second' or similar
6. Below you can set the details of where block will be displayed (optional)
7. Click 'Save' button
> 1 votes

---
Tags: nodes
---


# Question
Title: Body and Subject fields in Mail Function
I can't get it working. What am I doing wrong?

```
$name = $form_state['values']['name'];
$rname = $form_state['values']['rname'];
$email = $form_state['values']['email'];
$message = $form_state['values']['message'];

$params = array('current_conditions' => $data);
$message = drupal_mail('wow', rand(0, 999), $email, $language, $params, FALSE);
$message['body'][] = 'test';
// Only add to the spool if sending was not canceled.
if ($message['send']) {
    drupal_set_message('Success!');
}

```

# Answer
The last parameter you are passing to drupal\_mail() is `FALSE`. That parameter is telling the function if sending the mail. The documentation describes the parameter as follows:

> `$send`: If TRUE, drupal\_mail() will call drupal\_mail\_system()-\>mail() to deliver the message, and store the result in `$message['result']`. Modules implementing hook\_mail\_alter() may cancel sending by setting `$message['send']` to `FALSE`.

As its default value is TRUE, just leave out that parameter, and the mail will be send, if other modules don't set `$message['send']` to `FALSE`.
> 2 votes

# Answer
Your code only prepares message for sending it later. Example of sending e-mail immediately:

```
<?php

$my_module = 'foo';
$my_mail_token = 'bar';
$from = variable_get('system_mail', 'organization@example.com');
$message = array(
  'id' => $my_module . '_' . $my_mail_token,
  'to' => 'test@example.com',
  'subject' => 'test',
  'body' => array(
    'line 1',
    'line 2',
  ),
  'headers' => array(
    'From' => $from,
    'Sender' => $from,
    'Return-Path' => $from,
  ),
);
$system = drupal_mail_system($my_module, $my_mail_token);
// The format function must be called before calling the mail function.
$message = $system->format($message);
if ($system->mail($message)) {
  // Success.
}
else {
  // Failure.
}

?>

```

Edit: changed to better example
> 0 votes

---
Tags: 7, emails
---


# Question
Title: How does the mapping of the Feeds module work?
Does the mapping of the tables from source to destination should be completed, if I have 6 fields in the source table? Should I list all 6 fields, or can I only put 1 field to map if I only want that field to be imported?

# Answer
You can import as few or as many source fields as you want. You do **not** have to include all of them! The source table or cvs row or whatever does not have to match your destination entity exactly. It's OK to just take the parts you need. I frequently use the feeds module with csv files, and import just a portion of the columns that are actually present in the file.

Naturally, just make sure none of those missing fields are marked as required on the destination entity...
> 3 votes

---
Tags: feeds
---


# Question
Title: Override theme function for menu callback
**What I am looking for:** I have a custom node link which, when clicked, displays a custom HTML content (option selections) in a lightbox. I need to pass an argument to the HTML content to generate the HTML code.

**What I did:** I created a menu callback with one argument, and a template file for this "page" that does the processing and display the HTML content in the lightbox. I guess it's a little bit overkill and it takes quite some time for the whole render to be computed.

Would it be better (faster) to override the render with theme function? If that's the preferred solution, how to do? Create a `my_theme_page()` function in `template.php` file?

Or can I generate the HTML in the callback function?

Any help would be appreciated.

# Answer
> 0 votes
After a lot of googling, I found a nice solution to my problem.

First, one needs to register its menu with callback (in a custom module):

```
function MY_CUSTOM_MODULE_menu() {
  $items = array();
  $items['my_link_url_path/%'] = array(
    'title' => 'content title',
    'page callback' => 'MY_PAGE_CALLBACK',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
   );
   return $items;
}

```

Then the HTML content you want to be in the lightbox has to be printed in the callback function (you can define this function in your custom module file) as follow:

```
function MY_PAGE_CALLBACK($MY_PASSED_ARGUMENT = NULL) {
  print 'This is my HTML content displayed in the lightbox: Arg = ' . $MY_PASSED_ARGUMENT ;
}

```

The trick comes from the fact that you do not return, but print directly the output. No theme layers will be processed.

Just add your link somewhere (with the lightmodal rel attribute if you are using Lightbox2 (http://drupal.org/project/lightbox2):

```
<a href="/my_link_url_path/345" rel="lightmodal">Click me</a>

```

This will display 'This is my HTML content displayed in the lightbox: Arg = 345' in a lightbox.

Note: don't forget to empty the cache when changing your menus...

---
Tags: 6, theming, routes
---


# Question
Title: How can we autocreate an organic group during registration
How can I do this using the rules module?: User registers (as profile type a) -\> create organic group using field value from registration and make the user the manager/admin of the group

I have also the modules Profile 2 and Profile2 Registration Path.

# Answer
Creating a group is really just creating a node.

Create a rule that reacts on "After saving a new user account". Add Action: Create a new entity.

Set content type to: Group.

You can set the title of the node (the name of the group) to the new user's name or any value you want using available tokens.

Set the author of the node to the new user (it's usually called "account" in rules) and the new user will be the owner/manager of the group.
> 0 votes

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


# Question
Title: drupal bootstrap theme working with superfish
I hope this will not be too confusing, apology if it is

My situation:

1. I used superfish so that I can have a navigation menu with dropdown submenu when the mouse hovering the nav items.
2. I used bootstrap theme to make the whole site responsive
3. I use 'main menu' instead of 'navigation' as my navigation menu bar
4. I customised the menu style by changing 'default.css' in superfish, bootstrap.css and style.css in bootstrap theme.
5. I have unchecked main menu in appearance tab under the theme setting so that the main menu will not show up twice while I'm using superfish.
6. I am using drupal 7, superfish-7.x-1.8 and bootstrap-7.x-2.x-dev

When the screen size is reduced, the menu bar disappears and the small button in the corner will show up. When clicking this button, the main menu items should be shown as a drop down menu. My problem is: because I unchecked the main menu, the main menu items will not show up when clicking this small button. But the superfish menu (which is main menu, but set in superfish menu) will be there without changing style for small screen. How can I make the superfish menu items behave the same way as normal main menu + bootstrap?

I really don't know how to explain this more clearly and I am really frustrated by bootstrap theme now :(

Any help would be very much appreciated!

thx

# Answer
> 2 votes
Superfish allows you to add custom css classes to the menu items. If you prefer to do it that way

you might want to first select the classes from bootstrap that you want to use to style your superfish menu items. Second add those classes correspondingly in the superfish menu block settings(click configure next to the block).

I also added a html wrapper under advanced HTML settings around the main UL element which is simply , (comma denotes the beginning and ending wrapping elements).

Let me know if that helps!

# Answer
> 0 votes
This is from the http://drupal.org/project/superfish webpage:

> Important notes:
>
> v1.9-beta5 is stable enough to be used on production sites. You can use it with the Superfish library v1.2-beta2. The latest development release (Feb 8) should be used if you're starting a new site that requires a responsive (or small-screen compatible) navigation. It requires the latest Superfish library (click the ZIP button in the Github or click this link). If you're upgrading you must add the path to sfsmallscreen.js plugin manually (which should be sites/all/libraries/superfish/sfsmallscreen.js) by going to Superfish module configuration page (admin/user-interface/superfish) and adding the full path at the end of the list of the library files.

Have you tried that? I would try 7.x-1.x-dev

---
Tags: routes, navigation
---


# Question
Title: what is the importance of delimter in a feeds module
Guys what is the importance of the delimiter in feeds module. cause i only leave it as is. i dont change it so maybe its the one causing the instability of my import process.

By the way im trying to import large files from database which i converted in to chunks of csv files, which i have no luck in accomplishing. So can someone enlighten me the role of delimiters in csv and in feeds module

# Answer
> 1 votes
The delimiter in csv (comma separated values) files is a comma, usually. It may be changed. The delimiter expected by Feeds must match the delimiter used in the csv files, or feeds cannot detect where one value ends and the next begins.

---
Tags: feeds
---


# Question
Title: views related content block // show content with specific initial letter
i have a content-type with this fields:

```
title field
starting letter // term reference -> stores term in vocab "starting letter"
car brand // term reference -> stores term in vocab "car brand"
car model // term reference -> stores term in vocab "car model"
Image field

```

i have created a view that hast the url: example.com/vehicles/audi (the term audi comes from the vocab "car brand" in views this looks like vehicles/%)

on this page with the url example.com/vehicles/audi i want to show a block that contains a list of other cars which name starts with the letter A like:

```
Acura
Alfa Romeo
AMC
Ascari

```

the same should be work with brand starting with B, C and so on. i need a contextual solution.

my problem and what i dont unterstand: how do i set this thing up, because i dont have the term "A" in my url which i could filter with the contextual filter. i just have the term "audi". can anyone help me please?

# Answer
Set argument for second view using `hook_views_pre_view()`.

```
$view->set_arguments(array('A'));

```
> 0 votes

# Answer
I never use php in admin interface, in my opinion it's not right. Because later it's too difficult to remember where you place your custom logic... I advise you to create a custom module and place your code there.

As for your method, I guess PHP contextual filter requires returnable value. So let's try this:

```
$parent_view = views_get_page_view(); // Get vehicle view
$arg = $parent_view->args[0]; // Get vehicle view argument
$letter = $arg[0]; // First letter of argument
return drupal_strtoupper($letter);

```
> 0 votes

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


title: Discount select list

text:
# Question
Title: Discount select list
I've checked for a similar question but nothing helped me. So, i want to add a list in shopping cart with 3 options: a) No discount b) 70% discount c) 65% discount When the user selects, lets say 70% discount, the discount will be added in total amount and after that is going to select the payment method.

I'm doing this because there is no available module for deposit. The 30% of deposit that i want is like 70% of discount.

Thanks and i hope there is an easy solution that i couldn't find

# Answer
> 0 votes
Try doing this with the Commerce Discount module. With it, you can create discounts that are either hard-coded dollar amounts or are percentage based. You'll use the second option.

This module uses Rules to calculate the discount amount based on a product price or the entire order amount. Read more on the module documentation page: http://drupal.org/node/1706132

---
Tags: commerce
---


# Question
Title: "basic page" content type: how would I restrict access to a page for only 1 role
If I created content that is of "basic page" content type that is mapped to a URL path settings as an alias how would I restrict access to that page to only 1 role?

If the user is not logged on then how can I redirect the user to a login page and then after that send them back page to the originally requested page?

Note I only want to restrict access for this one page and not all pages that have "basic page" content type.

# Answer
> 0 votes
Use `hook_node_view()`

```
function mymodule_node_view($node, $view_mode, $langcode) {
  $user = $GLOBALS['user'];
  // Check user->roles
  // If user hasn't access to current node
  drupal_set_message(t('You have to login before continue...'), 'status');
  drupal_goto('user', array('query' => array('destination' => 'node/' . $node->nid)));

}

```

# Answer
> 1 votes
This can be acheived by using a combination of content access and login toboggan modules. You'll be able to restrict pages and prompt user to login to access them.

# Answer
> 1 votes
The Anonymous Login module will intercept restricted page requests from anonymous users, give them a login form, then take them back to the requested page when they are logged in.

You can certainly restrict access to a single role on a particular page using Content access. Just go to the Access Control tab of the content type and check 'Enable per content node access control settings '.

The problem as I see it is that the drupal menu system checks a user's access permissions before displaying a menu item, so your anonymous users and the users without the restricted role will never be able to go to the restricted content through a menu item. The only way to direct them to the content is through a hard coded link in a page or an email.

---
Tags: redirection, users
---


# Question
Title: move fields in the user profile form in fieldsets
I want to move the email address fields in the user profile form (user/1/edit) in a custom fieldset. I have this code:

```
$form['change_mail'] = array(
    '#type' => 'fieldset',
    '#title' => 'change email address cake',
    '#weight' => 6,
    '#collapsible' => FALSE,
    '#tree' => FALSE,
);

$form['change_mail']['mail'] = $form['account']['mail'];
unset($form['account']['mail']);
$form['change_mail']['confirm_mail'] = $form['account']['confirm_mail'];
unset($form['account']['confirm_mail']);

```

But I get an error when I try to change my email address: `undefined index 'mail' in user_account_form_validate() (line 1232 of /modules/user/user.module).` Apparently, I can't 'unset' the fields. But I don't know how to get rid of them.

# Answer
As you mentioned the problem appears in `user_account_form_validate()` because you changed the `account` index from `$form['account']['mail']` to `$form['change_mail']['mail']`

the issue is with this line `form_set_value($form['account']['mail'], $mail, $form_state);`

In order to achieve what you are looking for you need to replace existing form validation with a custom validation as the following code:

```
function MODULE_NAME_form_user_profile_form_alter(&$form, &$form_state, $form_id) {

  $form['change_mail'] = array(
    '#type' => 'fieldset',
    '#title' => 'change email address cake',
    '#weight' => 6,
    '#collapsible' => FALSE,
    '#tree' => FALSE,
  );

  $form['change_mail']['mail'] = $form['account']['mail'];
  unset($form['account']['mail']);
  $form['change_mail']['confirm_mail'] = $form['account']['confirm_mail'];
  unset($form['account']['confirm_mail']);

  $form['#validate'][0] = 'MODULE_NAME_user_account_form_validate';
}

function MODULE_NAME_user_account_form_validate($form, &$form_state) {
  $form['account']['mail'] = $form['change_mail']['mail'];
  // original validation function
  user_account_form_validate($form, $form_state);
}

```
> 4 votes

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


# Question
Title: feeds module cannot handle csv files exceeding 8gig?
I am trying to import a very big CSV file into my Drupal 7 site using the Feeds module, but I get the following error:

> Warming: POST Content-Length of 40245470 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

How can I fix this?

# Answer
> 5 votes
8388608 bytes is 8MB, not 8GB. 40245470 bytes is \< 40MB.

Your PHP settings are limiting the maximum POST content length to 8MB, which is why you're getting the error.

To fix, edit your php.ini file and add/update these lines:

```
post_max_size=50M
upload_max_filesize=50M

```

# Answer
> 1 votes
Not many things could handle this. For importing massive amounts of information from an external database, you are better off to do it using Feeds and Feeds Database. Even then you will probably be best to do it progressively in chunks.

If you are intent on using csv files, then export them from your original database using limited queries and create several files:

```
SELECT ......... LIMIT 100 OFFSET 0;
SELECT ......... LIMIT 100 OFFSET 100;

```

and so on until you have all the information.

---
Tags: feeds
---


# Question
Title: Add another node in create content Drupal 6
I am searching for a way to add content in node/add/page (for example) with a "Create another node (of this content type)" button. The button would add another form, and when the forms are submitted, Drupal would create 2 nodes.

Is there already a module that does this? How can I differently achieve this?

# Answer
Try out Multi Node add module.

> This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
> 1 votes

---
Tags: 7, nodes
---


title: Approve public organic group

text:
# Question
Title: Approve public organic group
Our organic groups is set up so that any authenticated user can create a group. What we need is for any group created to be private (accessible only to group members), but if the creator requests it be public, then the group is initially created as private and be in a published usable state, but a request will be sent to a groups admin for the group to be public (which will then list it in a group directory and anyone can request to join).

I'm using Drupal 7 and the latest version of OG. I have it set up so the group visibility defaults to private right now.

Any way to do this with rules? I've tried creating a "list in public directory field" associated with the group content type and then I figured when a group was added, a rule could check if that field was checked and do some event to notify an admin. But I'm not sure where to start with the "React on event" drop down as it doesn't seem anything suits what I'm trying to do.

I'm open to other ideas.

# Answer
After having lots of fun with rules, I have found a solution. Whew!

I created a rule:

```
Events:
Before saving content

Conditions:

Content is of type - Parameter: Content: [node], Content types: Community Group

AND

Data comparison - Parameter: Data to compare: [node:group-access], Data value: Public - listed in the...

Elements:

Set a data value - Parameter: Data: [node:group-access], Value: Private - accessible only...

```

I also send an email and show a message on the site, but that's not to important to the nitty gritty of the rule.

The purpose of my rule is that when a user selects "public" for a group, that the group is created as "private" but a request is sent to a Group Admin to review and change to public once approved. In the meantime, the user can still add members and use the group in a private state.
> 0 votes

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


# Question
Title: Use drush to download drupal core files directly into directory rather than subdirectory
When you use `drush dl` normally, it will download drupal into a subdirectory ie: *drupal-7.16*

I would like to skip creating the subdirectory and just install the drupal root directory files into the pwd or destination directory. ie: */var/www/install.php*

**Can this be done with drush commands?**

Other shell workarounds also welcome and will be considered for answer status if this is impossible with drush.

# Answer
> 22 votes
```
drush dl drupal --destination=/var --drupal-project-rename=www

```

# Answer
> 1 votes
Drush usually creates a sub directory, But you can easily copy all the files from this sub directory "/var/www/drupal-7.12" to its upper folder "/var/www/" with this code

```
mv * .* ..

```

# Answer
> 1 votes
You can specify the name of the destination folder to download Drupal into via the --destination parameter. For example:

```
$ cd /var
$ drush dl drupal --destination=www

```

**Aside:** Note that it's probably better to put your site in /var/www/mysite.org rather than directly in /var/www; someday, you might want to put a second site on the same server.

---
Tags: drush, installation
---


title: How do I get the logged user ID?

text:
# Question
Title: How do I get the logged user ID?
I am developing a module with a form to ask for the email frequency; when users choose a value, and save it, I store it in the *users* table, but it doesn't work. It works only when I hard code the user ID.

```
global $user;
$uuid = $user->uid;

function emailf_form_submit($form, &$form_state) {
  $bb = $form_state['values']['emailf'];
  $query = db_update('users')
    ->fields(array('email_f' => $bb))
    ->condition('uid', $uuid, '=')
    ->execute();

  drupal_set_message('Email frequency successfully changed');
}

```

# Answer
It works when `$uuid` is initialized inside the function.

```
function emailf_form_submit($form, &$form_state) {
  global $user;
  $uuid = $user->uid;

  $bb = $form_state['values']['emailf'];
  $query = db_update('users')
    ->fields(array('email_f' => $bb))
    ->condition('uid', $uuid, '=')
    ->execute();

  drupal_set_message('Email frequency successfully changed');
}

```
> 2 votes

---
Tags: forms
---


# Question
Title: correct way to implement multipule users registration form
I want to create a site where users get to chose between being an employee or employer.

So when users first go to the registration they need to be asked which role will they be, and on that choice a different registration form will appear.

What would a good implementation method be? Thanks

# Answer
> 1 votes
First you need to use Profile 2 module and create two separate profiles for employee and employer roles.

Then you can use module Auto Assign Role or Profile2 Registration Path to allow users select which role do they want to register with.

# Answer
> 0 votes
You could create a multi-step form in a module that gives the user the opportunity to make that choice and once the form is completed by the user you could store the data.

# Answer
> 0 votes
You could use Field conditional state module and Rules for this. Add a select list with employer and employee option and depending on which one the user selects, show or hide fields relevant for each role. Then create a rule that assigns new users a role based on the value of the select field that they selected.

---
Tags: 7, users
---


title: Drupal Yslow Performance

text:
# Question
Title: Drupal Yslow Performance
Hello I am using drupal 7 and yslow tool in ff.

it shows me grade B

**Grade F on Make fewer HTTP requests**

This page has 11 external Javascript scripts. Try combining them into one. This page has 5 external stylesheets. Try combining them into one.

**As i am not able to combine all javascript and css files.**

I also enabled cache . but i don't know how it work.

**Grade F on Add Expires headers**

There are 75 static components without a far-future expiration date.

i also made changes in .htacess file still not working .. Please let me know

Grade C on Put JavaScript at bottom

i am using iframe in my website . How to include javascript at bottom for this?

Anybody have idea please let me know.

Thanks

# Answer
for **Grade F on Make fewer HTTP requests**

Locate them at `admin > configuration > development > performance`. There you'll see two options:

Aggregate and compress css files.
Aggregate Javascript files
> 4 votes

---
Tags: views, 7
---


# Question
Title: How can i make a Slide Show for my Home Page with the following requirements
How can I make a Slide Show for my Home Page with the following requirements:

1. The image would link to any content
2. The caption would be different for all images of the slide show
3. The slide show would be responsive
4. The images can be added, deleted from the CMS itself by the client/admin
5. Navigation controllers
6. Place a link "Sign Up" on top of the slide show which takes the user to the sign up page

I tried with Views Nivo slider but it has open issues regarding rewrite results. Are there any other modules? Views slideshow is one but I am not able to configure it as per my exact requirement.

# Answer
> 2 votes
Views slideshow has solutions to be responsive, see: http://drupal.org/node/1510526

You can also embed a custom slideshow navigation using views and a `global counter` in the view, using Tokens you can replace the counter text with whatever you want. An example of this can be found here: http://blog.urbaninsight.com/2012/01/03/building-slideshows-with-navigation-based-views

All of your criteria are met by Views Slideshow I believe, you just have to get crazy with CSS. I have made the following slideshow with Views Slideshow using the navigation tutorial above, Views, Views Slideshow and Nodequeue.

**example view slideshow config**

**default rendering of ViewsSlideshow in Admin area, an un-themed slideshow**

**Final themed slideshow with custom navigation**

In my case I overlay the navigation into the view, I had to use jQuery to achieve some of the dimensions at runtime and CSS3 stuff for opacity of my overlay div.

# Answer
> 0 votes
Read documentation for slideshow. this tutoral may help you. To making responsive slider, see here. Make views slideshow responsive - remove inline styles

# Answer
> 0 votes
You can use this module http://drupal.org/project/views\_galleriffic ,its nothing but the support module for views . You can customize the slideshow with thumbnail,content of slideshow,prev ,next button and pagination through view fields.

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


title: Undefined index q

text:
# Question
Title: Undefined index q
I have 2 websites on the same server. They both use the same modules.

In one of them, I get the following notices:

> Notice: Undefined index: q in current\_path() (line 355 of /var/www/drupal/includes/path.inc).
> Notice: Undefined index: q in l() (line 2424 of /var/www/drupal/includes/common.inc).
> Notice: Undefined index: q in arg() (line 2792 of /var/www/drupal/includes/bootstrap.inc).

Does anyone have any idea about what can cause these notices?
The website is working perfectly, and I know I can put some error\_reporting in the settings.php, but it won't solve the problem.

# Answer
> 0 votes
Never mind, That was a stupid mistake of mine in my custom theme.

# Answer
> 0 votes
Line 355 of /includes/path.inc contains this code:

```
return $_GET['q'];

```

So, we can suppose, that $\_GET\['q'\] is undefined. According to documentation, this variable is initialized in drupal\_path\_initialize function during bootstrap. It's code:

```
function drupal_path_initialize() {
  if (empty($_GET['q'])) {
    $_GET['q'] = variable_get('site_frontpage', 'node');
  }
  $_GET['q'] = drupal_get_normal_path($_GET['q']);
}

```

Maybe, the function drupal\_get\_normal\_path gives undefined value for 'site\_frontpage' var?

---
Tags: 7
---


# Question
Title: Print list of attached taxonomy terms on search result items
First off, let me start by saying I am fairly new to Drupal, I come from a heavy Wordpress / Joomla background. On to my question:

I have looked for hours for a way to print a list of the taxonomy terms attached to a search result item. I need it to be as automated as possible (i.e. I need get the nid & vid from the node automatically if possible). I was able to get the nid using the following:

```
$nodeID = $variables['result']['node']->nid;

```

I do not need any fancy formatting, or hierarchy, I just need a comma separated list of the attached terms for each item on the search results page. If possible, I would also like to limit the depth to 5, but that is not a primary concern.

Here is what I have so far:

```
// Add List of Terms to Search Result Items
    $vid = 4;
    $terms = array();
      if (isset($node->taxonomy)) {
        foreach ($node->taxonomy as $voc) {
          if ($voc->vid == $vid) {
            $terms[] = $voc;
          }
        }
      } else {
        // check db in case node doesn't have terms
        $terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);
      }
      return $terms;

    $terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);
    // To store the new terms (if necessary...)
    if ($terms) {
        foreach ($terms as $term) {
            // Each term has the properties:
            // $term->tid
            // $term->vid
            // $term->name
            // $term->description
            // $term->weight
            // To just print the results use something like:
            print $term->name . ',';
        }
    }

```

Any help you guys can provide would be immensely appreciated!

# Answer
You almost have it. How I'd do it is like this. First, in (I assume you are doing this already) hook\_preprocess\_search\_results:

```
function YOURMODULE_preprocess_search_results(&$variables) {

  // the vid you are restricting your results to...
  // it is really up to you to define the logic of how
  // to determine this, but you could use a variable...
  $vid=variable_get('YOURMODULE_search_result_vid', 4);

  $taxonomy=$variables['result']['node']->taxonomy;

  if ($taxonomy) {

    $terms=array();
    foreach($taxonomy as $t) {
      if ($t->vid == $vid) {
        $terms[]=$t->name;
      }
    }

    if ($terms) {
      $variables['terms']=implode(',', $terms);
    }

  }

}

```

will, assuming no typos and brain fades on my part, produce a `$terms` variable you can access in `search-result.tpl.php`.

Now, for step 2, copy the default one out of `.../modules/search` to your theme. The default D6 one basically looks like this, with the large intro comments removed:

```
<dt class="title">
  <a href="<?php print $url; ?>"><?php print $title; ?></a>
</dt>
<dd>
  <?php if ($snippet) : ?>
    <p class="search-snippet"><?php print $snippet; ?></p>
  <?php endif; ?>
  <?php if ($info) : ?>
  <p class="search-info"><?php print $info; ?></p>
  <?php endif; ?>
</dd>

```

so in there, you can change it up basically like this:

```
<dt class="title">
  <a href="<?php print $url; ?>"><?php print $title; ?></a>
</dt>
<dd>
  <?php if ($snippet) : ?>
    <p class="search-snippet"><?php print $snippet; ?></p>
  <?php endif; ?>
  <?php if ($info) : ?>
  <p class="search-info"><?php print $info; ?></p>
  <?php endif; ?>
  <?php // THE NEW STUFF FOLLOWS... ?>
  <?php if ($terms): ?>
    <p class="search-terms"><?php print $terms; ?></p>
  <?php endif; ?>
  <?php // ...END OF THE NEW STUFF ?>
</dd>

```

and with some CSS styling of your new `search-terms` class, be on your way.
> 1 votes

# Answer
If I'm understanding the requirement in the question, then another approach that might be worth exploring is to use Display Suite. The module can take over the display of search results. To replicate Drupal's default search you configure the Search Results view mode with title and snippet. You can then add additional fields, such as a term reference field.

If you have a lot of content types, the configuration process is a bit tedious as you find yourself configuring many near identical view modes. On the other hand, if you have a lot of content types, you are almost certainly going to gain, because some of those content types will benefit from having customised search results, i.e. for content types with a key image, you can display a thumbnail of the image in the search result. And, as per question, you can display taxonomy terms. Because it's part of Display Suite, you can also do some clever formatting without using templates, e.g. have a two columns search result or create code fields to combine two fields on your node into one etc.

See also documentation for configuring search display using Display suite on drupal.org
> 0 votes

---
Tags: 6, taxonomy-terms, search
---


title: Database API join fields

text:
# Question
Title: Database API join fields
i've got a database query with a join like this:

```
$query = db_select('node', 'n');
$query->condition('n.nid', 0, '<>')
  ->fields('n')
  ->range(0, 50);

$query->leftJoin('field_data_field_prospekt_owner','prospekt','prospekt.revision_id = n.nid');

```

Let's say I want to get the fields from my 'field\_data\_field\_prospekt\_owner' table in the result. How do I go about that?

i tried extending the fields function like `query->fields('n,prospekt')` but this throws an error.

`query->fields('n')->fields('prospekt')` isn't working, unfortunately. I'm getting a error:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1051 Unknown table 'prospekt': SELECT n.*, prospekt.* FROM {node} n {} LEFT OUTER JOIN {field\_data\_field\_prospekt\_owner} prospekt\_2 ON prospekt.revision\_id = n.nid WHERE (n.nid \<\> :db\_condition\_placeholder\_0) LIMIT 50 OFFSET 0; Array ( \[:db\_condition\_placeholder\_0\] =\> 0 ) in main() (Zeile 42 von /var/www/asvg/prospekt\_iframe.php)

# Answer
You should do

```
$query->fields('n')->fields('prospekt');

```

See the documentation for more info.

Note that querying field tables this way is not recommended as the tables are created dynamically. You should only fetch field data via APIs.
> 1 votes

# Answer
If i provide the fields to select for the joined table, it works... But it doesn't if i want to select all the fields by omitting the second parameter to `SelectQuery::fields()`. The work around is to call the latter after the join so that the whole query would look like:

```
$query = db_select('node', 'n')
  ->condition('n.nid', 0, '<>')
  ->fields('n')
  ->range(0, 50);
$query->leftJoin('field_data_field_prospekt_owner','prospekt','prospekt.revision_id = n.nid');
$query->fields('prospekt');

```

If i provide the fields for `prospekt` in the query builder, it works also:

```
$query = db_select('node', 'n')
  ->condition('n.nid', 0, '<>')
  ->fields('n')
  ->fields('prospekt', array('col1', 'col2'))
  ->range(0, 50);
$query->leftJoin('field_data_field_prospekt_owner','prospekt','prospekt.revision_id = n.nid');

```
> 0 votes

# Answer
I was looking for another problem when I dropped on your question.

You can add your field using addField such as:

```
$query->addField('prospekt','prospekt_owner_value','owner');

```

You can use the field alias 'owner" to access the returned value.
> 0 votes

---
Tags: entities, database
---


# Question
Title: Submit a custom form as a webform submission
I have a custom form i created using FAPI and i wanted to submit the values into the webform database table and/or content type as a node. i wasnt sure of the "drupal Way" of doin this. Here's my current submit function, Please tell me if im doing this correctly or if not what is the correct way? (P.S. i dont want to use a different r another module or save to my own custom table.)

```
function contracts_webform_submit($form, &$form_state) {
 module_load_include('inc', 'webform', 'includes/webform.submissions');
 module_load_include('inc', 'webform', 'includes/webform.components');
 global $user;

$node = $form['#node'];
$sid = $form_state['values']['details']['sid'] ? (int) $form_state['values']['details']['sid'] : NULL;

// If there is no data to be saved (such as on a multipage form with no fields
// on the first page), process no further. Submissions with no data cannot
// be loaded from the database as efficiently, so we don't save them at all.
if (empty($submission->data)) {
 return;
}

 // Save the submission to the database.
if (!$sid) {
 // No sid was found thus insert it in the dataabase.
 $form_state['values']['details']['sid'] = $sid = webform_submission_insert($node, $submission);
 $form_state['values']['details']['is_new'] = TRUE;

 drupal_set_message(t('The form has been submitted.'));
 }
}

```

# Answer
Without really knowing much else about the custom requirements of your form it's difficult to give a complete answer however your on the right track by using Webform.

You should recreate as much of the form as you can using webform as a base rather than FAPI. Then you can use FAPI to alter (hook\_form\_alter) the existing form that webform outputs.

Your custom FAPI code can then be worked into the way webform works, you may have to massage some of the data based on your requirements though.
> 1 votes

---
Tags: hooks, webforms, forms
---


# Question
Title: A view I wrote has bugged handlers so I want to alter the query manually. How do I get the current view display?
The view handler for locations is broken when the locations are in field collections.

I need to rewrite the view query, replacing 3 joins with 2 other joins, for the query to work.

I don't want to mess with other displays of the view - how do I get the currently used display with `hook_views_query_alter()`?

# Answer
> 0 votes
If you already know the machine name of the view then you can wrap your code in an if statement.

```
function hook_views_query_alter(&$view, &$query){
    if($view->name == 'name_of_view_to_alter'){
        //do stuff to the query
    }
}

```

hook\_views\_query\_alter takes two arguments &$view and &$query. If you don't already know the machine name, of course install devel and use dsm($view) to find what you need. Also very helpful calling that on the $query variable as well. I just did something very similar.

---
Tags: views
---


# Question
Title: How to use views to display different information sources
On my home page I want to have a series of 'blocks'. Here is a graphic illustrating what I would like to achieve

The first two would be updated with the latest two blog post, the third would be the Facebook feed iframe, then the last three would be images promoting a different page on the site via a link.

I currently have each of these blocks prepared as separate views. Each of these are hard-coded into page.tpl with views\_embed\_view(). This isn't ideal as I want to be able to easily add and remove these boxes from within the Drupal admin.

How do I create a 'master view' to display on the front page that will hold these separate views?

# Answer
It seems there are many ways to achieve the same result in Drupal. In the end I went for 'Context'. By using 'Panels', it does not appear to be flexible enough to easily add extra blocks when needed.

* Set the condition to `<front>`
* In reaction add `blocks`
* Then drop in all the required views into `content`
> 1 votes

---
Tags: views
---


# Question
Title: Prevent Anonymous users info to be displayed in my views
I am making a list of users for views categorised in my table, however, there are users that are "Anonymous" and i dont want them to show up in the table. Is there any way of fixing it?

# Answer
> 1 votes
I think that if a user is showing up in your users table (and thus users view), they must have an **account** on your system, so they would, at a minimum, be an 'Authenticated' user. But they probably have no other roles other than 'authenticated'.

So try the following to filter them out of your users view:

1. Add a filter to your users view
2. Select the 'User: Roles' filter and configure it as the screenshot below:

Let us know if this worked.

p.s. I'm assuming you have Drupal 7 here, since that's what the screenshots are showing -- Views under Drupal 7, but it really helps to tag your question with the version of Drupal you're running.

# Answer
> 1 votes
You can add a filter: `user ID (!= 0)`

---
Tags: views
---


# Question
Title: Caption box on my slideshow jumps when you refresh cache
When you access my site for the first time, the caption box on the slideshow starts lower by about 50px then adjusts itself to the correct position. Pressing Ctrl-F5 also recreates the problem.

Is there a way I can set a breakpoint within the CSS or Drupal so I can step through to find whats causing the problem? Also, any clues whats causing the problem?

thanks

website: www.terrafirmasouth.co.uk

# Answer
> 0 votes
This is a css problem, sorry. If I add position:absolute to my pagers block then the jumping stops, however, my pager block then appears under the text below the slide and the pagers cant be clicked on. I will follow up on stack overflow for css queries.

---
Tags: views
---


# Question
Title: How can i list all display suite layout templates used
Is there a way to list all display suite templates that are currently being used in the various view modes?

To clarify: I have many content types, and many view modes, AND many custom made ds layouts. It's becomes a big mix and i would like to get an overview which ds layouts are being used by which view mode / content type.

# Answer
> 1 votes
I think he's asking to get an overview of of which bundle / view mode uses which template file.

That's currently not easy to fine in the backend - however this is something we want to add add some place.

The fastest way to get an overview is to go to the database and look into the 'ds\_layout\_settings' table. The 'layout' column holds the machine name of the template used.

# Answer
> 0 votes
yes, go to to the content or select the content type from Structure/Content Type, select the content type e.g. Projects, then select Manage Display, then scroll to the bottom, and you will see a drop down, select that and you will see all the layouts possible

---
Tags: display-suite
---


title: Help With Audit log Setup

text:
# Question
Title: Help With Audit log Setup
I'm setting up an audit log for a large network of Drupal 7 sites with dozens of editors and 5 developers.

These events are already covered: Content Create, Content Update, Content Delete, User Login, User Logout, User Create, User Update (hook\_user\_update).

But I'm having a hard time logging:

* Change in permissions
* Change in settings

Any ideas how to go about logging that to watchdog?

# Answer
> 1 votes
Both of these are forms, so you can do something with a `hook_form_alter`. The easiest thing to do is do a View Source, find the form, and look at the ID on the `<form>` element.

The permissions form is `user_admin_permissions`. My suggestion would be to alter the form to add a new submit handler, eg

```
function mymodule_form_user_admin_permissions_alter(&$form, &$form_state, $form_id) {
  $form["#submit][] = 'mymodule_log_permission_change';
}

```

The settings changes are going to be tricky, as they are spread across many, many forms. The idea is the same, you just need to figure out whether you are on a setting for or not. You could alter all of the important setting forms, or you could try using the base `hook_form_alter()` and check the `$form_id`. You could also try checking the URL from withing the submit handler, as many of the settings live under `/admin`.

---
Tags: 7
---


# Question
Title: How do I set the "Save draft" button by default on all webform nodes?
I have a situation where, when I create a new webform node, its "Save draft" button must be there by default.

How can I achieve this?

# Answer
> 2 votes
```
/**
 * Implements hook_webform_node_defaults_alter().
 */
function mymodule_webform_node_defaults_alter(&$defaults) {
  $defaults['allow_draft'] = '1';
}

```

# Answer
> 0 votes
Have you tried installing the Save Draft module?

---
Tags: webforms
---


# Question
Title: Will the site load slower when using a sub-theme of a sub-theme?
In Drupal, you have a base-theme, and maybe a sub-theme. That sub-theme can also have another sub-theme.

Will Drupal be slower when using 3 themes, where each of them is a sub-theme of the previous one, or doesn't this affect the performance?

# Answer
> 8 votes
**TL;DR** Have as many sub-themes as you want, it's not a problem.

**Longer answer** All types of inheritance, theming or otherwise, will have a performance penalty, and really all logic that you perform will have that effect; **However**

1. With proper caching enabled, only the very first request that uses the sub-sub-theme, is actually going to notice a difference. After that you will have aggregated css/js files from all three (or more) involved themes, and all of this becomes a non-issue until you clear the cache, after which you will again need to aggregate the files *once*.
2. With a pretty big generalization, the performance cost is roughly going to be linearly proportional to the number of changes you make. So if you don't make a lot of changes, you won't see a big effect.

Generally speaking, I suggest you approach the problem the other way around. Organize your theme/solve your problem in a way that is efficient for you as a human. *Then* worry about how to make it efficient for a machine only when necessary.

Since your site isn't written in assembly, your entire site is a huge performance problem, but in the vast majority of cases, a cpu performing literally trillions of calculations in a second makes that a non-issue.

---
Tags: 7, theming, performance
---


# Question
Title: How to remove selected topics from aggregator feed?
In my Drupal feed aggregator generating a separate website feed into my website. However, my client dislike some topics on that feed therefore, is it possible to remove selected topic from that feed ?

# Answer
Probably you must implement hook\_aggregator\_fetch for this job.
> 0 votes

---
Tags: feeds
---


# Question
Title: Show cached pages with boost for logged in users
I have a website that is only available to logged in users, I want to increase performance with boost by caching pages for authenticated users would i just edit the code above?

http://drupal.org/node/509694

here it says this code is what prevents boost from caching for logged in users

```
<?php
  // For authenticated users, set a special cookie to prevent them
  // inadvertently getting served pages from the static page cache.
  if (!empty($user->uid)) {
    boost_set_cookie($user);
  }

```

# Answer
No, because it will break your site for logged in users. Try Authcache module instead.
> 1 votes

---
Tags: 6, caching
---


# Question
Title: What are best practices for Drupal 7 my.conf settings?
I posted the following wiki to GDO to try to consolidate best practices for Drupal implementations: http://groups.drupal.org/node/289613

There's just so much written out there, but the documentation is often old or very personalized to one person's my.conf file.

What have other folks used. Starting with https://tools.percona.com/wizard seems to be the best approach, but the Wizard doesn't know anything about Drupal.

# Answer
> 3 votes
You need to profile this yourself, every server is different - there's not really any such thing as 'best practice' here; get mysqltuner up and running, and follow the recommendations.

Don't try to think of it in terms of Drupal, rather in terms of any web application which needs optimising. If you get too hung up on the 'Drupal' aspect you'll end up looking in the wrong places to optimise

---
Tags: performance, database
---


title: How can I get count of deleted rows

text:
# Question
Title: How can I get count of deleted rows
How can I get count of deleted rows after `db_delete`?

```
db_delete('node')
  ->condition('uid', 1)
  ->execute();

```

something like

```
$count = db_delete('node')
  ->condition('uid', 1)
  ->execute()->columnCount();

```

doesn't work

# Answer
The delete query will return a query object for all methods except -\>execute(). Methods can be chained until the query has been assembled. Execute() completes the chain.

Try:

```
$count = db_delete('node')
  ->condition('uid', 1)
  ->execute();

```
> 7 votes

# Answer
You can get count of deleted rows as follow:

```
db_delete('node')
  ->condition('uid', 1)
  ->execute();

$count = db_query('SELECT ROW_COUNT()')->fetchField();

print($count);

```
> 2 votes

# Answer
Next expression works:

```
$count= db_delete('node')
  ->condition('uid', 1)
  ->execute();

dpm($count);

```

db\_delete returns count of deleted rows after execution.
> 2 votes

---
Tags: 7, database
---


# Question
Title: change customer email address in ubercart
Is it possible to to change customer's email address in already created order? I have some customers who type wrong email address and complain that they did not receive any email... I tried to change it in customer's info but new email is not reflected in already created order. Thank you

# Answer
> 0 votes
This is a known issue with ubercart. The only way to change it, currently, is to find the order in the uc\_orders table, and to update the primary\_email field in the record.

# Answer
> 0 votes
I found a solution - go to users account, change email address, this will not be reflected in orders. You go to the order edit page, section customer info, search for existing customer, put corrected email address, system will find new address and you can use it.

---
Tags: 6, ubercart
---


# Question
Title: How to set variables in an installation profile?
I cannot find any documentation on the variables\[\] array in an installation profile info file. I can set some variables successfully in that file and others give me an invalid format error when I visit the settings page to check them after the install. The ones that I would like to set are:

```
variables[site_403] = <front>
variables[user_cancel_method] = user_cancel_block
variables[update_check_frequency] = 7
variables[update_notification_threshold] = security
variables[update_notify_emails] = myemail@example.com

```

In Drupal the source it looks like update\_notify\_emails is probably an array. Is there a way to make this setting an array via this .info file? I am trying to set these using the info file or the install hook rather than exporting the variables as features using a strongarm.inc due to these best practice recommendations linked on this distribution developers guide page.

# Answer
You should be able to set these in the `.install` file in your profile. I've struggled with this well, and the `.install` seems to be the best way to do it.

```
<?php
/**
 * Implements hook_install().
 *
 * Performs actions to set up the site for this profile.
 *
 * @see system_install()
 */
function customProfile_install() {
  /*
    Other cool functions...
   */

  variable_set('site_403','<front>');
  // etc....
}

```
> 5 votes

---
Tags: 7, distributions
---


# Question
Title: How to send notification email to individual users
I want to send notification email to some users when a node is created in my site. The author should select the individual users in the node creation form and then after save the node email will be sent to those users. I use **Entity Reference** and **Rules** modules to do that but I don't know how set the right action.

# Answer
I just implemented the same thing this morning. I hope my solution will help you, but it probably depends on if your content type field is set up like mine.

My user list is presented via an Entity Reference view that I created. Users check off who they want email sent to and save the content type.

My rule is as follows:

```
Event:
    After saving new content

Conditions:
    Content is of type
        Parameter: Content: [node], Content types: User message

Actions:
    Add a variable
        Parameter: Type: List of user items, Value: [node:field-people]
        Provides variables: List of members to email (members_to_email)

    Loop
        Parameter: List: [members-to-email]
        List item: Current member (member)

        Send mail
            (contents of email listed here)

```

You'll obviously have different names for your content type, node field, variable names, etc. but hopefully this will get you started in the right direction. If you want the export of the Rule instead of what I posted here, let me know. I thought that showing you what I did through the interface might be an easier start for you.
> 2 votes

---
Tags: rules, entities, notifications
---


title: Forum Post urls with Pathauto

text:
# Question
Title: Forum Post urls with Pathauto
I'm using Drupal (v7.21) with Pathauto and Advanced Forum and would like the paths to be formatted like:

```
domain.com/forum
domain.com/forum/the_topic_name
domain.com/forum/the_topic_name/the_post_name

```

Under Forum Paths 'Pattern for forums and forum containers' is set as:

```
[term:vocabulary]/[term:name]

```

And under Content Paths I've set 'Pattern for all Forum topic paths' as:

```
[node:taxonomy_forums]/[node:title]

```

This is working except for the Posts which are missing the /forum/ part:

```
domain.com/the_topic_name/the_post_name

```

I could manually get this to work by setting the 'Pattern for all Forum topic paths' as:

```
forum/[node:taxonomy_forums]/[node:title]

```

But I'd rather have it set using a pattern if possible.

Any ideas?

# Answer
> 2 votes
you can add pattern like `[node:content-type]` or `[node:content-type:name]`. So the actual pattern will be `[node:content-type]/[node:taxonomy_forums]/[node:title]`

# Answer
> 0 votes
From the answer by monymirza it works as:

```
set Pattern for all Forum topic paths as
[node:content-type:machine-name]/[node:taxonomy_forums]/[node:title]

```

It also works with:

```
set Pattern for all Forum topic paths as
[node:taxonomy-forums:vocabulary]/[node:taxonomy-forums:name]/[node:title]

```

But if you have a Topic within sub Forums/Containers it won't show them in the urls for Topics. So from more research I found that you can get Topics to show the correct path with:

```
set Pattern for all Forum topic paths as
[node:taxonomy-forums:vocabulary]/[node:taxonomy-forums:parent]/[node:taxonomy-forums:name]/[node:title]

```

You then need to set the pattern for the Forum/Container paths as they are separate:

```
set Pattern for forums and forum containers as
[term:vocabulary]/[term:parent:name]/[term:name]

```

For both of these if you have multiple levels of sub categories you can keep extending this with 'parent:parent' like:

```
set Pattern for forums and forum containers as
[term:vocabulary]/[term:parent:parent:parent:name]/[term:parent:parent:name]/[term:parent:name]/[term:name]

```

If I've missed anything please let me know as I'm very new to Drupal.

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


# Question
Title: Integrating file management with Organic Groups
Using Drupal 7 and OG 2.x. I'm looking for a file manager to use so that each group has a files tab with the ability to create, move, delete files/folders for their group and read/write permission is only for the members of the specific group.

Is filedepot the only module for this? I have found elfinder, CKFinder, and IMCE, but it's unclear whether these are reasonably simply to integrate with OG.

Has anyone integrated a specific file manager with OG and is happy with how it's working?

# Answer
My final answer is that elFinder was the file manager that ended up being the easiest to implement and it works nicely. Filedepot was promising, but by design, only a filedepot administrator can create a top level folder in Organic Groups mode. This means that if you have your site set up so users can create groups, it will fail creating the folder for the group unless you make all users fildepot admins. There may be a way to change this functionality in the code, but I didn't investigate it I also ran into trouble showing filedepot in a view and/or panel. So, I couldn't get a filedepot display to show up for each organic group.

If you use panels, elFinder shows up as "File Manager" under Miscellaneous when adding content to a panel. So, it was really easy to display an elFinder manager in each organic group. I did have to modify a few lines of code to grab the id of the current group, so that a correctly named directory was created the first time anyone opens elFinder in the group without a directory already being there.
> 0 votes

# Answer
Partial answer is that CKFinder doesn't integrate with OG out of the box, or easily at all. They do offer an access control list, but you would need to know the specific directories and specific people who need access. It won't work to create folders/permissions on the fly when creating groups or add/remove permissions as members are added/removed to the group. They mentioned that a custom plugin may be possible to do to modify the access control list but that it would be quite a bit of work. Java was recommended for the custom plugin.
> 0 votes

---
Tags: organic-groups, files
---


title: Entity Field Query

text:
# Question
Title: Entity Field Query
I don't think I am yet grasping how entity field query works, all I want to do is get the ids of all the nodes connected to my node via an entity reference, how do I write that?

# Answer
You want to find the entity IDs that are referenced from a node you've already loaded?

If the reference field is called 'field\_reference', then:

```
global $language_content;
$langcode = $language_content->language;
$references = $node->field_reference[$langcode];
$target_ids = array();
foreach ($references as $delta => $reference) {
  $target_ids[] = $reference['target_id'];
}

```

Your mileage may vary with the language stuff.

Note that you usually want to keep track of the entity type (e.g. 'node' or 'user'). You can't really do anything with an entity without knowing its type.

So you might want something like:

```
$target_ids[$reference['target_type']][] = $reference['target_id'];

```
> 3 votes

---
Tags: entities, database
---


# Question
Title: Drupal Commons: notify all users on creation of new group
In Drupal Commons (D7) I'd like to have all users notified by email when a new group is created.

Is there a way to do that?

# Answer
> 0 votes
You can use the Rules module and set it to fire an action, when a group is created.

CVS Instructions You could also implement this User register notify

But since Drupal Commons uses Organic Groups you might be able to use this Organic Groups Notifications but take a look at the Rules module and Flag module.

best regards

---
Tags: 7
---


# Question
Title: Drupal Commerce Free Shipping For Some Products
Drupal 7, Commerce

The Setup: A store with two products. They are a shippable item and a gift certificate.

The shippable item has a number of shipping options available.

Gift certificates have free shipping, and always go via first class mail.

I added a 'free shipping' shipping method. Unfortunately this always shows up in all checkouts, so someone could order a hundred shippable items and then select free shipping.

When I 'configure component' for the free shipping method, it lets me define a rule as to how this method is applied.

In this rule, I need to make a loop that goes through all line items, and if there are only products marked with a field called 'field\_free\_shipping', then show this method.

However.... Rules sucks. :-) I can make a loop, but then I can't ask it about the product node or the field.

What am I doing wrong? Any assistance appreciated.

I'll be adding a bounty to this question when it becomes eligible.

# Answer
In such a simple scenario, where you only have two products, I would just use the condition *Order contains a particular product* to look for the shippable product to enable the paid shipping service. I'd then use the same condition negated to enable the free shipping service.
> 2 votes

---
Tags: 7, commerce
---


title: Add bulk groups with a new module

text:
# Question
Title: Add bulk groups with a new module
I want to do (in Drupal commons version 6.25) some kind of bulk OG-Management.

On How to programmatically assign/add new groups to the OG in Drupal Commons 6.25, Fuzzy76 says:

> Doing this through PhpMyAdmin will probably be very cumbersome. You would need to add records to node, revisions, any CCK-tables (if your group nodes have CCK fields), og, og\_uid (for group memberships) as a minimum. For addding content to your groups, you would need to add to node, revisions (CCK-tables if necessary) and og\_ancestry.
>
> It is a bit easier creating a group programmatically:
>
> ```
> $groupnode = new stdClass();
> $groupnode->type = 'gruppe'; // Group node type
> $groupnode->status = 1;
> $groupnode->uid = $owner_uid;
> $groupnode->title = $title;
> $groupnode->body = $body;
> $groupnode->og_selective = $group_acces_level;
> $groupnode->og_register = OG_REGISTRATION_NEVER;
> $groupnode->og_directory = OG_DIRECTORY_CHOOSE_FALSE;
> $groupnode->og_private = variable_get('og_private_groups', OG_PRIVATE_GROUPS_CHOOSE_FALSE);
> $groupnode->{_integration_cGroupType}[0]['value'] = $cGroupType_content; // CCK field
>
> node_save($groupnode);
>
> if ($groupnode->nid) {
>   og_insert_group($groupnode);
>
>   // Set space (if spaces_og is used)
>   //$ogspace = spaces_load('og', $groupnode->nid, TRUE);
>   //$ogspace->controllers->variable->set('spaces_preset_og', $spacepreset);
>
>   og_save_subscription($groupnode->nid, $owner_uid, array('is_active' => 1, 'is_admin' => 1));
> } else {
>   dpm('OG creation failed :(');
> }
>
> ```

Can anybody help me to port over the code (above) to a module?

# Answer
> 0 votes
If you have a naming pattern for the groups, you could use the Automatic Nodetitles module or the Automatic Entity Label module to give the groups a default name and use the Devel module to generate the groups.

Also since groups are nodes, you could use one of those node import modules to bulk upload the groups from an excel sheet.

---
Tags: organic-groups
---


title: how to style or theme organic groups

text:
# Question
Title: how to style or theme organic groups
How can i present groups on my group-list page similar to this site - http://www.popsugar.com/community/groups . i want there to be a picture, group title, short description of the group and total number of members.

further, how can i go about giving groups an option to have profile picture? I presume i'll have to use views but am not sure how. i am using drupal 7 and zen sub theme.

# Answer
> 2 votes
checkout this awesome og video tutorial, it will show you most of the steps needed. To add a picture to a group you just add a field type "photo" to your group node. And to display the list of groups you'll use views. I haven't figured out yet how to show the count of members that belong to each group. I posted that as a separate question.

# Answer
> 0 votes
Groups are nodes so add a field for image and groups owners can add image to their groups. You can upload a default image to the field for groups without images.

The listing can be done with views and two-column grid view will give you that listing style. I believe Groups module also comes with a group listing view. Edit it to add your image field and other field that you need. Use css to float the image. You can use firebug to look at how they theme the list on that website.

---
Tags: organic-groups
---


title: User taxonomy by location

text:
# Question
Title: User taxonomy by location
I am trying to add taxonomy to my user location.

User A lives in Berkshire, UK, User B clicks at "berkshire, Uk" in Profil of User A and get a list of all Users who lives there. For example look at my picture.

If I have only 1 field like city or country it would be no problem. Any suggestions?

# Answer
Create a taxonomy called Location with hierarchy like Country \> City. That's really it. You can use views to style the output page.
> 0 votes

---
Tags: 7, theming, taxonomy-terms, location
---


# Question
Title: How to pass an array to drupal7 form select as value of #options?
This problem makes my head burn all day. Please see the code below. I got a variable $region\_value contains the region value with the same structure listed in the code. However different page has a different region value, so I have to use a variable to store it, it's not static.

```
$region_value = array(0 => 'US', 1 => 'EU')
//form code details have been left out.
//the below code define the form.
$form['region_options'] = array(
                '#type' => 'select',
                'prefix' => 'Region',
                '#options' => $region_value,
                               );

```

now I get the problem, cuz drupal can't accept the value of $region\_value, something wrong happened cuz the $region\_value's can not be passed into the form function itself in template files, it might be caused by the drupal core settings. I know it's not a good choice to write functions or other customer variables in the template files, but it's convenient for simple test, you don't have to dump the cash.

So my problem is, is there a mean to pass a variable value into the form function?

```
//variable set here
$options = array('foo' => 'bar',...)
//form define function goes here
function region_form($form, &$form_state) {
            $form['submit'] = array(
                                   '#type' => 'select',
                                   '#options' => $options,
                                   );
            return $form;
          }

```

Much appreciated for all advises.

# Answer
> 5 votes
Have a look at the Form API docs for select lists. `#options` is the correct property to set the options, and `#default_value` is used to set a default value.

Using `#value` means the user input will be ignored, and whatever you've set as `#value` will wind up being the submitted value. Since you're declaring a non-multiple select list, that value needs to be an integer (not an array) anyway.

Try something like this:

```
$region_value = array(0 => 'US', 1 => 'EU');
$form['region_options'] = array(
  '#type' => 'select',
  '#prefix' => 'Region',
  '#options' => $region_value,
  '#default_value' => 0, // e.g. Set US as default selected value (appropriate array key from $region_value)
);

```

# Answer
> 0 votes
after a dig on drupal's document, I found the solution myself, if some one got the same problem like me, please check the drupal's page

drupal form generatation guild

at the bottom of this page you will find how to pass additional arguments into the form function.

Gold luck.

---
Tags: forms
---


# Question
Title: automatic logoff when leaving a page for a particular user and node/page combination
I have a request for 1 user only ($user-\>name) that after they leave a particular node/page ($node-\>title) that they be automatically be logged off of drupal. Leaving this page includes navigating to another page or closing the tab or browser window. How could the automatic logoff when leaving a page for a particular user and node/page combination be accomplished?

# Answer
> 0 votes
AFAIC you can get current node id from Drupal JS object. Having those id you can send Ajax request to Drupal which performs logout (http://api.drupal.org/api/drupal/modules!user!user.pages.inc/function/user\_logout/7)

About JS events for this task you should look on other forurms

---
Tags: users
---


title: Drush css-js cache clear error

text:
# Question
Title: Drush css-js cache clear error
There are times when I run `drush cc css-js` and I get the following error:

'css-js' cache is not a valid cache type

Does anyone know why this may happen?

Thanks,

# Answer
The latest dev releases of Drush (both 8.x-6.x and 7.x-5.x) now provide a better error message when attempting to select a specific cache type (e.g. css-js) without first selecting a working Drupal site. c.f. http://drupal.org/node/1954552

Note also that when selecting a Drupal site, `cd /path/to/drupal/root` only works if settings.php is stored in a directory called "default". Otherwise, you will need to instead `cd /path/to/drupal/root/sites/mysite.com` before using drush cc css-js. You can also use the --root and --uri parameters, e.g. `drush --root=/path/to/drupal/root --uri=http://mysite.com cc css-js`
> 1 votes

---
Tags: drush
---