# Question
Title: Unable to get Video + VideoJS to play MP4s on ANY Android device
This is a multi-part question - I'm running Drupal 7.14, w/ Video Module 7.x-2.9 and VideoJS Module 7.x-2.2, configured a Content Type to upload only MP4s, and Manage Display to use Video settings, where the Players for all Formats are set to VideoJs \- and I get videos to playback on all modern browsers - chrome, firefox, safari, ie, iphone/ipad, windows 8 smart phone, just NOT any of the android devices.

I actually tested a Samsung Galaxy S1 Tablet w/ Adobe Flash 6.3 installed, and I still couldn't get the VideoJS 3.0 Flash Fallback \[that I normally get on Firefox\].

Anyways, the other part of the question is where to actually put my .htaccess file in a multi-site installation that I have my mime type set to video/mp4 .mp4? I'm guessing this may have something to do with it on Android?

I've scoured videojs forums, video/videojs module bug tracking, and couldn't really answer this question. Any advice would help. ALso, I don't have autoplay enabled as a setting on Video Module.

Thanks,

# Answer
Many issues with playback are usually due to improperly formatted/encoded files. Different browsers/devices do not support the same media formats in their implementations of HTML 5 video. This due to mainly patent issues, open-source vs. proprietary and disagreement over which is the "best" format.

To make your video work in the latest versions of all major browsers, you will need to serve your video in both WebM format and MP4 format. To guarantee the broadest range of browser/device compatibility you may also need to include the Ogg format.

WebM: Firefox 4+, Chrome and Opera 10.6+ MP4: Internet Explorer and Safari Ogg: Firefox 3.5+, Opera 10.5+

Go to http://html5test.com/ using your test devices to see what formats are supported.

Helpful info:

http://www.longtailvideo.com/html5/#media\_formats

http://www.longtailvideo.com/html5/formats/
> 3 votes

---
Tags: files, .htaccess
---


title: Facebook Oauth field collection

text:
# Question
Title: Facebook Oauth field collection
I have Facebook Oauth set up to receive a few fields. They are mapped in the Configuration -\> Facebook OAuth settings -\> Field Mapping to fields I added to the account object.

When a facebook user tries to connect, they are prompted for permissions on these fields, and the user accepts. However, the fields are not being captured to the fields they are mapped to.

Ideas??

# Answer
It looks like I had my profile2 fields mixed up with my account fields.
> 0 votes

---
Tags: 7, social-network, authentication-authorization
---


# Question
Title: How can I filter the entire contents of a site by region?
I have a classifieds site that I created at http://www.gastonia.com. I've introduced the location module, and I am using views to search by proximity after someone types in a zipcode and distance. Everything is working fine.

I now want to experiment with filtering the entire site's displayed contents - all pages, all blocks, all views, all menus, etc. When someone types in their zip code and hits submit, every item of content is filtered for them within 25 miles of their region.

I can easily do this with Views and filters, even for blocks where arguments don't work. I also want to do this for all 770 towns in my state, which means creating views programatically. Each would have its own page / url title like Gastonia-NC and Shelby-NC and show items accordingly.

I have created the script to do that - loop through all 770, and everything actually works, except it's slow, to say the least. Maybe there is a better way to do this? Note the production site does not have the location / filter implemented, just my dev.

# Answer
> 1 votes
You can still use views then just use the views global filter module. This way they only enter their location only once then every other view on the site inherits this filter.

---
Tags: views
---


# Question
Title: Incompatible Mail System setting detected
In order to get the Newsletter (Simplenews module) to send out emails correctly (in HTML format) I selected HTMLMailSYstem in the mail system settings. Having the DefaultMailSystem setting instead, does not work, in a sense that it only sends out plaintext newsletters, not html.

The status report however is giving me the following error:

Printer, email and PDF versions - Send by email Incompatible Mail System setting detected The send by email module requires the use of the DefaultMailSystem, please configure it in the Mail System Settings page.

Is it possible to have different mail system settings for different modules? Or is there another way for me to make this work?

# Answer
SMTP Authentication Support module works best with the Print module. I has an option allow sending mail in HTML format.

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.
> 2 votes

---
Tags: emails
---


# Question
Title: Grouping or adding classes to CCK form fields
I'm looking for a way to group sections of my CCK add/edit forms so that I can give users a form with sections instead of one long page. I'm already using Fieldgroup to group fields for display so what I'm looking for is something similar for grouping fields for editing.

I realize I can do this with large amounts of CSS, jQuery or adding custom templates but I'm looking for a more elegant solution.

# Answer
You can use fieldgroup on the node edit form as well. Look just below "add existing field" and you will see "add new group"
> 2 votes

---
Tags: 7, forms
---


title: Absolute urls in Simplenews Newsletters

text:
# Question
Title: Absolute urls in Simplenews Newsletters
Is there a way to automatically convert the relative urls to absolute? For example, when uploading an image it is automaticlaly included as a relative url, so it doesn't appear in the html email when received. Is there an automated way to change this or does one need to go in the source of the newsletter and change the url for all image/link instances?

# Answer
Pathologic input filter will do that for you.

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.

Download and install the module, and then enable it for the text format you're using. It also supports the feature to bulk update your existing paths.
> 5 votes

---
Tags: emails
---


title: Voting Api From iOS

text:
# Question
Title: Voting Api From iOS
Hi I created an app for a drupal site and everything is working fine as I used the DIOS Library by workhabit the only thing that's missing is voting. I found this link http://drupal.org/node/241453 which got me close to everything working.

I just keep getting a 401 unauthorized in my response headers but I can't figure out why I'm unauthorized as I'm passing the session data and everything any help would be greatly appreciated!

My setVote method from my module looks like this

```
'actions' => array(
        'setVote' => array(
          'callback' => 'votingapi_service_set_vote',
          'access arguments' => array('edit votes'),
          'args' => array(
          array(
          'name' => 'content_type',
          'type' => 'string',
          'description' => t('Content type'),
          'source' => array('data' => 'content_type'),
          'default value' => 'node',
          ),
          array(
          'name' => 'content_id',
          'type' => 'string',
          'description' => t('Content id'),
          'source' => array('data' => 'content_id'),
          ),
          array(
          'name' => 'vote',
          'type' => 'string',
          'description' => t('Vote'),
          'source' => array('data' => 'value'),
          ),
          array(
          'name' => 'uid',
          'type' => 'string',
          'optional' => TRUE,
          'description' => t('User id'),
          'source' => array('data' => 'uid'),
          ),
        ),
        'return' => 'array',
        'help' => t('Sets vote'),
      ),

```

So I set up my code in my app like this

```
NSMutableDictionary *voteData = [NSMutableDictionary new];
            [voteData setValue:@"highdea" forKey:@"content_type"];
            [voteData setValue:nid forKey:@"content_id"];
            [voteData setValue:@"1" forKey:@"vote"];
            [voteData setValue:[[[[DIOSSession sharedSession] user] objectForKey:@"user"] objectForKey:@"uid"] forKey:@"uid"];
            [DIOSVote voteUpDown:voteData success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"%@", responseObject);
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"%@", error);
            }];

```

And here is the DIOSVote Method which I just created and added to the DIOS library

```
+ (void)voteUpDown:(NSDictionary *)vote
            success:(void (^)(AFHTTPRequestOperation *operation, id responseObject)) success
            failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {

    NSString *path = [NSString stringWithFormat:@"%@/%@", kDiosEndpoint, kDiosBaseVote];

    if ([[DIOSSession sharedSession] signRequests]) {
        [[DIOSSession sharedSession] sendSignedRequestWithPath:path
                                                        method:@"POST"
                                                        params:vote
                                                       success:success
                                                       failure:failure];
    } else {
        [[DIOSSession sharedSession] postPath:path
                                   parameters:vote
                                      success:success
                                      failure:failure];
    }
}

```

All and all here is my result

# Answer
Ended up just being a permissions issue :) had to just check the boxes so that my app had permission to vote sorry for overlooking such a small thing
> 0 votes

# Answer
Services voting api has a bug, try changing `$votes['votes']` to `$votes['value']` in the resource inc file and passing the vote value there.

Current:

```
function _services_votingapi_resource_set_votes($votes, $criteria) {

  if (empty($votes['entity_id'])) {
    return services_error(t('Missing entity ID.'));
  }

  if (empty($votes['votes'])) {
    return services_error(t('Missing votes amount.'));
  }

  return votingapi_set_votes($votes, $criteria);
}

```

vs:

```
function _scmp_services_resource_set_votes($votes, $criteria) {

  if (empty($votes['entity_id'])) {
    return services_error(t('Missing entity ID.'));
  }

  if (empty($votes['value'])) {
    return services_error(t('Missing votes amount.'));
  }

  return votingapi_set_votes($votes, $criteria);
}

```

You can then test by passing the votes array in the request.
> 2 votes

---
Tags: rating
---


title: Hide Workflow Tab For Given State

text:
# Question
Title: Hide Workflow Tab For Given State
I am developing moderation workflow using Workflow modeule. I have created different states for that. And using rules module I am putting node into one of the state based on certain event. It is working fine.

Now to emulate the Moderation process, I wanted to hide workflow tab (that appears on node page) when node is in certain state, and to display tab only when node is in one of the given states.

Is there any way I can achieve this?

-- Many thanks for your time.

# Answer
Solved it using hook\_menu\_alter and adding custom module. I have modified the access callback function to suit my needs.

Here is my code, may help user having same task:

```
    function mymodule_tab_menu_alter(&$items) {
        $items['node/%node/workflow']['access callback'] =
        'custom_workflow_tab_node_access';
    }

    function custom_workflow_tab_node_access($node = NULL) {

    global $user;

    if ($workflow = workflow_get_workflow_type_map_by_type($node->type)) {
        if ($workflow = workflow_get_workflows_by_wid($workflow->wid)) {
            $roles = array_keys($user->roles);
            if ($node->uid == $user->uid) {
                $roles = array_merge(array('author'), $roles);
            }
            $allowed_roles = $workflow->tab_roles ?
            explode(',', $workflow->tab_roles) : array();

          if (user_access('administer nodes') || array_intersect($roles, $allowed_roles)) {

      /* This is additional Condition*/

      if ($node->type == "article") {
     $current_state = workflow_get_workflow_states_by_sid(workflow_node_current_state($node));
                    if ($current_state->state == "State_name") {
                        return FALSE;
                    } else {
                        return TRUE;
                    }
                } else /*End Additional Condition */{
                    return TRUE;
                }
            } else {
                return FALSE;
            }
        }
    }
    return FALSE;
}

```

As above in custom access callback, I have used the same code, just added the additional condition and it solved my issue. :)

-- Thanks
> 0 votes

---
Tags: 7, nodes, routes, workflows
---


# Question
Title: Views Grid Display Images Thumbnail Sequently using jQuery
I am trying to make an image catalog using views grid. This is what I have done so far.

Created a views grid and gave the *test* class to each `<td>`.

```
tr class="row-1 row-first">
 <td class="col-1 col-first test">
 <td class="col-2 test">
 <td class="col-3 test">
 <td class="col-4 test">
 <td class="col-5 col-last test">
</tr>

```

Then I added my custom Javascript to my .info module file. This works since I can confirm it by viewing the page source.

```
<script type="text/javascript" src="http://localhost/menara/sites/all/themes/angela/js/custom.js?mii0ef"></script>

```

These are the contents of my `custom.js` :

```
(function($){
var lis = $('.test').hide(),    i = 0;

(function displayImages() {
        lis.eq(i++).fadeIn(200, displayImages);
})();
})(jQuery);

```

When I open Mozilla Firefox there is no Javascript error and the effects are not working.

Please guide me to solve this problem. I am following this great tutorial.

Regards,

mbahlol

UPDATE

aha i found it. this is what i do, based on stackoverflow

```
(function ($) {
$(function(){
var lis = $('.test').hide(), i = 0;
(function displayImages() {
    lis.eq(i++).fadeIn(800, displayImages);
})();
})
})(jQuery);

```

# Answer
> 0 votes
First check if your jQuery file is properly called, if its called than you can add jQuery.noConflict(); first and than replace $ sign with jQuery.

---
Tags: views, javascript
---


# Question
Title: Altering add_to_cart_form_submit() and random PDOException while adding to cart
I have created a customized product with lots of attributes to set for it. I also altered hook\_add\_to\_cart\_form\_submit() where I collect all selected attributes and calculate a new price based on the selected and configured attributes. So in my

```
function MYMODULE_add_to_cart_form_submit($form, &$form_state) {}

```

I create a big array and:

```
if (empty($form_state['line_item']->line_item_id)) {
    if ($attributes)
        $form_state['line_item']->data['context']['attributes'] = $attributes;
    $line_item = commerce_product_line_item_new($product, $form_state['values']['quantity'], 0, $form_state['line_item']->data, $form_state['line_item']->type);
    //   ...
}

```

I'm not sure if I am doing it right, I just want to store that array in the line-item table. While adding product to cart randomly I get:

```
"PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'commerce_line_item-177-0-0-und' for key 'PRIMARY': INSERT INTO {field_data_commerce_unit_price} ..."

```

error. Should I use some special format for this $attribute array? Everything is stored as BLOB in commerce\_line\_item.data field.

# Answer
> 1 votes
When you call commerce\_product\_line\_item\_new, drupal is trying to insert an already existant record to the table `field_data_commerce_unit_price` which has it's primary key defined as :

> PRIMARY KEY (`entity_type`,`entity_id`,`deleted`,`delta`,`language`),

Since the product already exists, it fails with a constraint violation error :

> Integrity constraint violation: 1062 Duplicate entry

What you are trying to do could be accomplished by adding a new **cost** item to the current order based on the attributes you mention, not by modifying the current item price which I guess is what you are trying to do.

So IMHO, you may try to have a base price for your item (or even a 0 price) and once the customer adds it to cart, add another cost item with the charges calculated based on the attributes he sets.

---
Tags: 7, commerce, database
---


title: List of all bookings in the next 3 days

text:
# Question
Title: List of all bookings in the next 3 days
In a content type i have a field date which has a start date and end date. using views i want to put filter in such a way that it display results in a date range form now to next 3 days. In a fields i can see content:dates and in filter i can see start and end like this.

After selecting content:start date i dont know waht to do screen shot like this

# Answer
> 2 votes
Try to change your "Date selection" in your second screenshot to "Text". If I remember correctly, you can now provide a text as paramaters.
There you can add things like `from: now` and `till: now +3 days`

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


# Question
Title: How to retrieve datetime from database in Drupal?
How do I retrieve a DateTime column from my MySQL database using Drupal Database API + PHP. The DateTime format is in YYYY-MM-DD HH:MM:SS(2013-02-20 23:59:59). I want to retrieve all the rows in the database that match a specific date, and then store the hour inside an array.

For example, I want to grab all the data from January 1, 2013. I then only want to store hours 00:00 to 23:59 inside my array, not the entire date.

I do not want to use any modules to accomplish this.. because I need to code it inside my custom module.

Thanks for your help!

Current Code:

```
$query = db_select('Project', 'p');
$query->fields('p', array('submissions', 'date_time'));
$query->condition('p.user_id', $user->uid);
$results = $query->execute()->fetchAll();
foreach($results as $r) {
    $rows[] = array(strtotime(date("H:i:s", $r->date_time))*1000, $r->submissions);
}

```

I plan to display the data on my Flot line graph.

# Answer
If you want the benefits of a `SelectQuery`, but with the more fine-grained control over the SQL, you can always use the `where()` method to inject (sanitised) raw SQL into the `WHERE` clause. e.g

```
$query = db_select('Project', 'p');
$query->fields('p', array('submissions', 'date_time'));
$query->condition('p.user_id', $user->uid);

// Fetch only records where date_time is greater than 30 days ago
$query->where('date_time > DATE_ADD(NOW(), INTERVAL -30 DAY)');

$results = $query->execute()->fetchAll();
foreach($results as $r) {
  $rows[] = array(strtotime(date("Y-m-d", $r->date_time))*1000, $r->numberOfPackages);
}

```

I don't know of any 'structured' way to get those sort of advanced conditions into a `SelectQuery` object so resorting to plain ol' SQL is necessary sometimes.
> 3 votes

# Answer
The code below works for me for fetching a group, so you can quickly adapt it for your own purpose.

```
$query = db_select('og')
    ->fields('og', array('etid'))
    ->condition('gid', $gid,'=');
$results = $query->execute();

$result = $results->fetchAssoc();

```
> -1 votes

---
Tags: database, datetime
---


# Question
Title: How do I override the HTML output of a theme function?
Let say we have theme function in module A `theme_super_a()`, this function returning some HTML. I want to write function in my own module (let's call it B) where I can get output of `theme_super_a()` manipulate it and return back to Drupal theme system. How can I do it?

Notice that I'm not interested in overriding whole theme with `hook_theme_registry_alter(&$theme_registry)`.

# Answer
> 1 votes
You will need to override the whole theme function in your own module. Because the override is done from a module level, not the theme, you will probably need `hook_theme_registry_alter` to change the theme function settings for that specific `hook_theme` component.

---
Tags: theming
---


title: Creating new content/node

text:
# Question
Title: Creating new content/node
I want to do something very simple - create a content of a specific type when a user joins a group.

Unfortunately I can not find a simple way of how it should be done.

It can be done with rules so I've been thinking about triggering one, but the details would be awfully complicated. I thought about having a template node that I would clone and edit, but how should I go for it? There are number of modules that do that in a strange way, while saying "it might sometimes not work properly", some people use things like `drupal_execute()`, I have found that `node_save()` has an option `$node->is_new = TRUE`. I found someone suggesting a use of forms, but they were always very simple and were not working with complicated/custom fields. I figured that maybe something like this could work:

```
$form = drupal_get_form('my_content_node_form');
$form_state = array();
do_some_edits($form,$form_state);
drupal_form_submit($form->id, $form_state);

```

What is a proper/simple way of dealing with this issue? What I would expect see is something like `$node = node_create($content_type)` but for some reason I can not find it.

# Answer
Provided you have a rule that triggers when a user joins a group, and a condition that checks that the group is the group you want, then add a execute PHP action to that rule that runs this code :

```
// Build a new node object
$node = new StdClass();
// set the type
$node->type = 'your_content_type';
// set the language
$node->language = LANGUAGE_NONE; // or whatever language you use.
// this fills the node with the default data
node_object_prepare($node);
// set a custom title
$node->title = 'Nice title';
// set whatever you want, for example body
$node->body[LANGUAGE_NONE][0]['value'] = 'This is some text for the body';
// Set the formatting for the text
$node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';
// Save the node to the DB
node_save($node);
// If you need the node ID
$nid = $node->nid;
// Just for debugging
watchdog('your_module','Just inserted the node with nid = '.$nid);

```

The key here is that node\_object\_prepare sets some default values for your content type.
> 3 votes

---
Tags: forms, nodes, organic-groups
---


title: HSBC Payment method for Ubercart

text:
# Question
Title: HSBC Payment method for Ubercart
I am unable to develop this but was wondering if there is any modules out there or at least some guide to work on HSBC Payment method for Ubercart 3.x ?

# Answer
> 0 votes
If you are looking for generalized payment options Ubercart CCavenue can help. On their official website they provide some economy plans as well, which is good for setting up basic payment modules in place.

---
Tags: 7, ubercart
---


# Question
Title: Create single exposed filter that does OR filter based on two fields D7 - Views 3
I have a content type *teams* and a content type *games*. *Games* has two node reference fields: *home-team* and *away-team* (that both reference content type *teams*). I want to create a single exposed filter *teams* that filters to games where either *home-team* or *away-team* matches the selected team.

For those with more experience hacking views - what approach would you take? Should I extend a handler to do this (views\_handler\_filter\_in\_operator)? Any pointers?

Or run a db\_query and pass the results to a views alter hook?

Any input appreciated.

# Answer
The answer, for me, did end up to be to extend one of the views handlers.

Here's the sauce:

```
<?php
/*
 * Shows results if team is referenced by field_data_field_home_team or field_data_field_away_team
 */
class views_handler_filter_mtairy_games extends views_handler_filter_in_operator {

  /**
   * This kind of construct makes it relatively easy for a child class
   * to add or remove functionality by overriding this function and
   * adding/removing items from this array.
   */
  function operators() {
    $operators = array(
      'in' => array(
        'title' => t('Is one of'),
        'short' => t('in'),
        'short_single' => t('='),
        'method' => 'op_simple',
        'values' => 1,
      ),
      'not in' => array(
        'title' => t('Is not one of'),
        'short' => t('not in'),
        'short_single' => t('<>'),
        'method' => 'op_simple',
        'values' => 1,
      ),
      'custom' => array(
        'title' => t('Custom'),
        'short' => t('custom'),
        'short_single' => t('<>'),
        'method' => 'op_custom',
        'values' => 1,
      ),
    );
    // if the definition allows for the empty operator, add it.
    if (!empty($this->definition['allow empty'])) {
      $operators += array(
        'empty' => array(
          'title' => t('Is empty (NULL)'),
          'method' => 'op_empty',
          'short' => t('empty'),
          'values' => 0,
        ),
        'not empty' => array(
          'title' => t('Is not empty (NOT NULL)'),
          'method' => 'op_empty',
          'short' => t('not empty'),
          'values' => 0,
        ),
      );
    }

    return $operators;
  }

  function op_custom() {
    if (empty($this->value)) {
      return;
    }
    $this->ensure_my_table();

    $this->query->add_table('field_data_field_away_team');
    $this->query->add_where_expression($group = '', $snippet = '(field_data_field_home_team.field_home_team_nid IN (:1)OR field_data_field_away_team.field_away_team_nid IN (:1))', $args = array(':1' => $this->value));
  }

}

```

Once I got views to implement the handler, I just exposed the filter and was golden.
> 0 votes

# Answer
Views 3 views have a neat little semi-hidden feature. Click the arrow on the **add** button in the **Filters** section and pick **and/or**. From here, you can create filter groups and sort your filters to use AND or OR depending on your needs. Play with it; I think you'll be able to solve your issues like this.
> 1 votes

# Answer
I realize this is an old post, but for those not wanting to write custom code, the Views filters populate module handles this nicely. It allows you to populate the values of two or more filters with just one exposed filter.

For @stars' use case, you'd:

1. Add a filters for the `home-team` and `away-team` fields.
2. Choose "`and/or, rearrange`" from the "`Filter Criteria`" section and create a new filter group (use "`AND`" for the group operator).
3. Drag both fields into the new group and "`OR`" them.
4. Add a "`Global: Populate filters`" filter.
5. Expose the new filter, label it "Teams", and check the boxes of the filters you want it to populate (`home-team` and `away-team`).
6. You may need to double-check that your new filter is part of the original `AND`-ed filter group. It should looks something like this:

```
FILTER CRITERIA
[other filters if you have them...] AND
Teams (exposed)
AND
home-team OR
away-team

```
> 1 votes

# Answer
From the views filters populate module page:

> Since Views 7.x-3.4, there is a "Global: combine field filter" built-in filter in Views, so you may not need this module.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Block body translation for Full HTML content
After block creation and put HTML content in body field I can't translate this content because of:

> The string blocks:block:1:body for textgroup blocks is not allowed for translation because of its text format.

If I change to plain text I can translate block but it is treated as plain text while displaying. Do I have to create another block with the same HTML content (translated) and select to display only in specific language?

# Answer
> 18 votes
Found it, http://drupal.org/node/1298440#comment-5127390

> In case anyone else has trouble finding this setting, it's at Configuration \> Regional & Language \> Multilingual Settings \> Strings
>
> (admin/config/regional/i18n/strings)

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


title: Creating a site tour

text:
# Question
Title: Creating a site tour
I created a site that allows people to create user accounts, login and communicate with other users, or view certain content. The site is completely finished accept for one thing. I am worried that users are going to get confused, or not know about all of the features that are on the site, so what I wanted to do, was to create a walk through tutorial of the site. I noticed there is a module for Drupal 6 that looks like it does almost exactly what I am trying to do, but I can't seem to find anything similar for Drupal 7, and I was wondering if anyone else has had any better luck. Also, I am I don't want the tutorial there permanently. I want it only there for the first few times that the user logs in, and then after that, to simply have a link saying "take site tour" on the bottom. Does anyone know of a module that can do that?

# Answer
> 4 votes
Check out the Guiders-JS module. It is a guide / walk-through for your site's pages. The Guider can show the page parts and give a short explanation about each part's functionality and purpose. This module is for anyone who is looking for a walk-through, guide, intro, or just a sequenced messaging system.

# Answer
> 4 votes
This module can do the same: Guidance

For controlling first time, you can use Rules module.

# Answer
> 3 votes
There is also Joyride JQuery for Drupal Site Tours module for Drupal 7 and Drupal 8 ships with Tour module! :)

---
Tags: 7
---


title: Drupal Commerce input price formatting

text:
# Question
Title: Drupal Commerce input price formatting
Presenting price with comma separator is working. But while editing product (or creating) I have to use price with dot separation, otherwise I'm getting warning, that field doesn't contain value. So right now I have to remember to use dot and after I see common - it's annoying. Does anyone deal with this with success?

I want to enter 24,43 as value, but it is not recognizable as value (which actually is).

Instead I have to enter 24.43, which is not accessible from num pad with current regional settings.

# Answer
This issue is what you look for - currently it has a patch that needs work. http://drupal.org/node/1450736
> 1 votes

---
Tags: 7, commerce
---


title: anchor (#) in url alias

text:
# Question
Title: anchor (#) in url alias
I want to open same page from different contents. So I need to generate link like `/testimonials#group-1` for these contents. I used pathauto module for this. I made pattern for this category `testimonials#[node:title]`. But this URL get encoded by browser `/testimonials%23group-1` and it gives me no page found error.

So how can I put anchor (#) in URL alias which can give me output like `/testimonials#group-1`.?

# Answer
> 3 votes
I think you are trying to add anchors to a node's alias to define multiple sections in a node, which is *impossible* since an **anchor destination** is not part of a **path** and therefor not part of an **alias**. For more information, see the W3 introduction on links in HTML.

**Creating a anchor**: If you would like to subsection your node's body, you should use anchors in your code:

```
<a name="anchorOne"> ... </a>

```

If you're using the WYSIWYG module, make sure you've got the `Anchor` plugin enabled, so you can create the anchors through the nicely builtin anchor plugin's GUI, which makes it that much easier.

**Linking to an anchor**: After creating an anchor, you can link to that section by making a hyperlink as follows:

```
<a href="/path/to/node#anchorOne">Link text</a>

```

To build the above link in the Drupal-way:

```
<?php print l('Link text', 'path/to/node', array('fragment' => 'anchorOne')); ?>

```

Or to only build the URL including the anchor destination:

```
<?php print url('path/to/node', NULL, 'anchorOne'); ?>

```

# Answer
> 1 votes
It's called a fragment identifier, and is done with the l() function:

```
$options = array('fragment' => 'group-1');
l('Anchor', 'path', $options);

```

# Answer
> 0 votes
First of all, set the Pathauto pattens for the content type **testimonial** to */testimonials/\[node:title\]*. This could later on be useful if you display one testimonial as a node, for instance if you don't include the full node in the view below.

Then create a view that lists all your testimonials, and show them as a page on the URL */testimonials*. Use the style Unformatted, and make sure you include the Title in the rows class (using the "Style \> Style \> Settings" in views), you could be use **Anchor-\[title\]** (show you later on why the 'Anchor\_'-part).

Then make a special versions of the views-view-unformatted.tpl.php (eg. views-view-unformatted--.tpl.php) and put it in your own themes folder (where it fits).

```
<?php foreach ($rows as $id => $row): ?>
  <div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

Make a small PHP snippet that fetches the rows styles and then find the one class that contains the "Anchor-Title".

```
<?php foreach ($rows as $id => $row): ?>
  <div <?php if ($classes_array[$id]) { print 'class="' . $classes_array[$id] .'"';  } ?>>
    <?php
      if ($classes_array[$id]) {
        $classes = explode(" ", $classes_array[$id]);
        for ($i=0;$i<count();$i++) {
          if (strpos($classes[$i], "Anchor_") === 0) {
            list($tmp, $anchor) = explode("_", $classes[$i]);
    ?>
    <a name="<?php print $anchor; ?>"></a>
    <?php
          }
        }
      }
    ?>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

Perhaps the code can be optimized, but that's only something to get you started...

BTW: To create a "menu" on the top, you could add a header to the view that's containing a view that makes links out of titles. Eg.

```
  <a href="#Title">Link text</a>

```

---
Tags: 7, uri, path-aliases, navigation
---


# Question
Title: Problem with form submit handler using system_settings_form for module admin
I have a module which creates an admin backend. I create the form as below. The submit handler is called, but for some reason there is no form state.

Any idea what's wrong please?

```
     //in hook menu
    'page arguments' => array('carousel_form'),

    function carousel_form($form, &$form_state) {
       $form = array();

      /* first fieldset */
      $form['fieldset_1'] = array(
      '#type' => 'fieldset',
      '#title' => t('Carousel slide 1'),
      '#description' => t('Configure the first slide of the carousel here'),
      '#required' => TRUE,
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
       );
       //more fields etc etc

      $form['#submit'][] = 'my_custom_handler';

      return system_settings_form($form);
      }

      //create a handler

      function my_custom_handler($form, &$form_state) {
      $file = file_load($form_state['fieldset_1']['pic_1']);
      //causes error, Undefined index: fieldset_1

      }

```

# Answer
> 1 votes
Not quite...`$form_state` *is* defined (or at least will be if you have a standard installation of Drupal).

The problem is the submitted values are in `$form_state['values']`, not `$form_state`. Also, Unless you have `#tree` set to `TRUE` on `$form['fieldset_1']` the values will be collapsed, and the hierarchy you're expecting won't be there.

This should work:

```
$file = file_load($form_state['values']['pic_1']);

```

---
Tags: 7, forms
---


# Question
Title: Views rewrite output including the wrapper divs?
I have 3 fields in a view and I want to rewrite the output in a fourth field. like this

```
[field1][field2][field3][field4]

```

But I want to have a wrapper div around each field like in the field settings. The problem is I could do something like this:

```
<div class="mywrapper">
  <div class="field1">[field1]</div>
  <div class="field3">[field2]</div>
  <div class="field3">[field3]</div>
  <div class="field4">[field4]</div>
</div>

```

But with this even if the field is empty the divs with the css classes will stay alive. I dont want that. If the field is empty dont display it with the `<div>`.

If I just display the field, there are no wrappers at all.

# Answer
> 0 votes
I found the answer myself. I use the modul views\_fieldsets.

---
Tags: views, entities
---


# Question
Title: How do I do git clone with drush to download the HEAD version of a module?
Is there any way to clone or pull the HEAD version of a module in drupal.org git repository?

For example, if I'm on Drupal 7, and the last branch of Views is 3, I would like to do:

```
drush git-clone views

```

to achieve something equivalent to:

```
cd sites/all/modules/
git clone --recursive --branch 7.x-3.x http://git.drupal.org/project/views.git

```

Ideally, using `drush git-clone views-3x` should clone the 3.x branch explicitly.

Is this possible or am I dreaming? This would be really useful for developing.

# Answer
> 10 votes
```
drush dl views-7.x-3.x --package-handler=git_drupalorg

```

**Update:**

True, if there are commits after the dev release was packaged, you will need to run `git pull` to advance to HEAD after checking out via drush dl. If there is no packaged dev release, and Drush checks out a stable release, then you need to run `git checkout 7.x-3.x` after drush dl.

There is no Drush command to do a verbatim git clone; part of the "value add" of drush dl is that it grabs published releases. If git clone is what you want, perhaps a short bash script would be your best solution. Something like this:

**Usage:**

```
$ clonedev views 3

```

**Example script:**

```
#!/bin/bash

MODULE=$1
VERSION=$2

DRUPAL=$(drush status "Drupal Version" --pipe | sed -e 's/\..*//')
if [ -n $DRUPAL ] ; then
  cd $(drush drupal-directory modules)
else
  DRUPAL=7
fi

git clone --recursive --branch $DRUPAL.x-$VERSION.x http://git.drupal.org/project/$MODULE.git

```

Modify to suit.

---
Tags: drush, version-control
---


# Question
Title: user can not view nodes of custom content type
I have created a user with the rights to view, edit and delete nodes of all the content types including some custom content types. On admin / content page it shows the list of contents of all content types except one custom content type.

**little edit** Its showing the contents of that content type when I am adding the content from that user but not showing the contents of that content type posted as user1

When we try to filter the contents to *banner* content type it shows no results, when we filter the contents to other content types including some custom content types it shows the filtered list.

I checked the permission for that content type for the user role which was not defined earlier but even after granting the permissions its not showing up.

After defining the permissions I have also rebuild the permission but the result is still the same.

# Answer
I assume that you just forgot to *publish* the content. Since the first user has access to every content, he can see *unpublished* content from the userX, but userX cant see unpublished content created by user1. To change this behavior you could give userX the permission "bypass node access".

For further explanation take a look at the official documentation:

http://api.drupal.org/api/drupal/modules!node!node.module/group/node\_access/7

> In determining access rights for a node, node\_access() first checks whether the user has the "bypass node access" permission. Such users have unrestricted access to all nodes. user 1 will always pass this check.

**Edit:** As mentioned in the comment, although this solution solves the initial answer, in most cases it isn´t good to give the "bypass node access" to a large number of users. In the case which is described in the comment, you should use a more sophisticated module for content pushblishing like the Workflow Module.
> 0 votes

---
Tags: nodes, users
---


# Question
Title: How can I turn a list of Aliases into a menu structure?
I'm in a massive migration from a home grown CMS. So far I've been successful at using Feed Import to slurp in CSV exports of the old MySQL database. The old database contained page URLs. So I just mapped this over to Page Alias!

Now I'm searching for a more automated way to take this

```
/program/science/thesis
/program/math/core_requirements
/program/science/projects
/program/literature/great_works_collection
/program/literature/great_authors_showcase

```

into a menu structure like this:

```
Navigation Menu
+- Program
  +-science
    +-thesis
    +-projects
  +-math
    +-core_requirements
  +-literature
    +-great_works_collection
    +-great_authors_showcase

```

Yes, I could do this manually, but I have over two thousand imported pages.

Is there an Alias URL to Menu structure script or module that may help me along?

## Update:

Based on feedback below, I decided to pull a list of URLs from the CSV file using the following pipe line. That is, I pulled only 5th column (the URLs), sorted the output, filtered urls that had "/programs/", and cut off the trailing quote

```
awk -F ',"' '{print $5}' programs.csv | sort | grep programs | sed "s/\"//g"

```

After that was exported to a file, a ran the following to generate the child items of the menu:

```
cat programs.just.urls.txt | awk -F '/' '{print $3}' | egrep -v "php$" | uniq

```

# Answer
> 2 votes
I'd give the Menu Export/Import module a go.

> This module helps to export and/or import menus. Using it you can easily copy menus from one Drupal site to another.
>
> It also allows developers to quickly build a new Drupal site by creating empty content and menu items referencing it. The module may be used in ensemble with Node export that allows to add content to your Drupal site. In this case, menu import allows to batch-arrange existing content into a given menu structure, using a very simple text file.

I guess you could possibly use Excel or something to take your list of aliases and split the paths to columns which would give you the menu title (in the last column of the split).

From there you have the menu link titles and paths, so it's just a case of getting it into the format that the module expects.

---
Tags: routes, migrations, path-aliases
---


title: How to add classes to comments?

text:
# Question
Title: How to add classes to comments?
I've put the following code above `print render($content['comments']);` in `comment-wrapper.tpl.php` of our theme to add `question` or `answer` class to every comment:

```
    foreach($content['comments'] as &$c) {
      if(is_array($c) && array_key_exists('#entity_type', $c) && $c['#entity_type'] == 'comment') {
        $uid = $c['comment_body']['#object']->uid;
        $c['#attributes']['class'][] = $uid == 1 ? 'answer' : 'question';
      }
    }

```

The generated HTML however has no `question` or `answer` classes. Please help me to correct the error.

# Answer
> 1 votes
The following code worked for me, put it in your theme's template.php and replace `theme` with the name of your theme:

```
function theme_preprocess_comment(&$vars) {
  $element = $vars['elements'];
  $comment = $element['#comment'];

  if(array_key_exists('#entity_type', $element) && $element['#entity_type'] == 'comment') {
    $vars['classes_array'][] = $comment->uid == 1 ? 'answer' : 'question';
  }
}

```

Although I think the extra checks for entity type is not necessary since this theme is only applied to comments.

# Answer
> 1 votes
I think your ternary statement is off in that code.

I would also suggest an alternative approach. You can use `hook_preprocess_comment()` in a template.php file or in a custom module. With this you can hook into the comment before it's rendered to the page, run each comment through an logic test and add a class to the entire comment, or add an html chunk before or after the comment's html. See more on hook\_preprocess and render arrays.

---
Tags: comments, theming
---


# Question
Title: user relationship status as a visibility rule per panel pane
how make a visibility rule based on UR status I've made a function to get the status between the visitor and the visited profiles

I ask if the module provide it or could i make it appear in visibility rules for panels module if it provide any hooks for that

# Answer
From: http://drupal.org/node/1185210

> User Relationships provides individual panel pane visibility checks based on relationship status.
>
> In order to use this functionality:
>
> Make sure that the User context has been enabled for the current variant (most likely current user)
>
> Add a new visibility rule for the pane you would like to control
>
> Select 'User Relationship' and configure for your use case.

That being said, I wrote those instructions for Drupal 6 while porting this feature to 7 and there may be bugs with the 7.x implementation. If you find anything make sure to post what you find on the issue queue.

If you want to customize your implementation further that code would be a good starting point, and please post any additional visibility rules back to the queue.
> 0 votes

---
Tags: users
---


# Question
Title: Are there any security concerns with getting the UID by simply querying the sessions table against the visitor's cookie?
In the High Performance JavaScript Callback Handler I'm attempting to use my own code to get the current user's ID.

To give a quick rundown, by returning data at a much lower bootstrap level (`DRUPAL_BOOTSTRAP_DATABASE`) I can return a page in ~90 milliseconds instead of the ~1500 milliseconds that a full bootstrap takes on this server. For simple content that any user can see, such as a published, publicly-viewable node, there aren't any security concerns. But if I need to perform any kind of access check, I need to know the current user's UID. I'm getting the UID by querying the sessions table for their sid/ssid. Consider this code:

```
  $session_name = session_name();
  if (!empty($session_name)) {
    if ($uid = db_query("SELECT uid FROM {sessions} WHERE sid = :sid", array(':sid' => $_COOKIE[$session_name]))->fetchColumn()) {
      $account = new stdClass();
      $account->uid = $uid;
      $account->roles = array();
      $account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
      $account->roles += db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = :uid", array(':uid' => $account->uid))->fetchAllKeyed(0, 1);
    }
  }

```

I am not yet including logic for their ssid (HTTPS), as I just wanted to get a proof of concept working quickly.

**Are there any security concerns that I'm missing here?** I've gone through session.inc and, while I'm completely ignoring the anonymous user handling, page caching, etc., none of those really matter to me within the context of what I'm doing. If I don't have an authenticated user, I don't need to create a new session for them or anything like that, they just get an access denied response from the server.

**Edit:** I should add that, with the above $account, permissions checks like `user_access()` and `node_access()` can be run.

**Edit 2:** Here's the original issue where I'm dialoging on this particular topic within the js module: http://drupal.org/node/1922406

# Answer
The approach is vulnerable to a man-in-the-middle attack but just like any connection that isn't encrypted (HTTP). An attacker could use this to read the comments of nodes they otherwise don't have access to.

Otherwise, without knowing more context of how this used and displayed I can't say there are no other security concerns. I'll comment on a possible XSS issue with your comment display code at http://drupal.org/node/1922406.

I would recommend that you check for the session cookie though:

```
if (!empty($session_name) && !empty($_COOKIE[$session_name])) {

```
> 1 votes

---
Tags: 7, security, sessions
---


title: PHP Custom Form Render warning

text:
# Question
Title: PHP Custom Form Render warning
I'm receiveing the warning

Strict warning: Only variables should be passed by reference in eval() (line 2 of D:\wwwroot\tixers\modules\php\php.module(80) : eval()'d code).

Everywhere I've looked tells me its a render error but I can't find anything wrong. The form works and submits all my info to the database, but there warning still shows up.

If you need the code for the module let me know and I will reply to it.

THANKS!

I use

```
<?php
print drupal_render(drupal_get_form('sellTickets_form'));
?>

```

then in the form 'sellTickets\_form

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

$form['team'] = array(
    '#type' => 'textfield',
    '#title' => t('Team Name:'),
    '#size' => 30,
    '#required' => TRUE,
);

```

......break for forms.....

```
$form['total_points'] = array(
    '#type' => 'textfield',
    '#title' => t('Total Points Awareded'),
    '#size' => 30,
    '#required' => TRUE,
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);
return $form;

```

}

```
function sellTickets_form_validate($form, &$form_state){
}

function sellTickets_form_submit($form, &$form_state) {
    global $user;
    $uid = $user->uid;
    $team = $form_state['values']['team'];
    $price = $form_state['values']['price'];
    $section = $form_state['values']['section'];
    $row = $form_state['values']['row'];
    $seat = $form_state['values']['seat'];
    $quantity = $form_state['values']['quantity'];
    $opponent = $form_state['values']['opponent'];
    $date = $form_state['values']['date'];
    $location = $form_state['values']['location'];
    $description = $form_state['values']['description'];
    $total_points = $form_state['values']['total_points'];
    $organization = $form_state['values']['organization'];

    db_query("INSERT INTO ticket (
    `TEID`, `price`, `location`, `date`, `organization`, `section`, `row`, `seat`, `quantity`, `opponent`, `description`, `points`)

    VALUES ('".$team."', '".$price."', '".$location."', '".$date."', '".$organization."','".$section."', '".$row."', '".$seat."', '".$quantity."', '".$opponent."', '".$description."', '".$total_points."');"
);
}

```

# Answer
> 2 votes
`drupal_render()` takes it's first argument by reference. This'll fix it:

```
$the_form = drupal_get_form('sellTickets_form');
print drupal_render($the_form);

```

---
Tags: 7, forms
---


title: Can't assign roles in admin panel

text:
# Question
Title: Can't assign roles in admin panel
The day before yesterday I created a new role (writers), and when, after adding quite a few modules, I wanted to add another earlier today, I discovered there was no way for me to do this anymore, nor to edit the role I already created. Now, I am a newby with Drupal, only started out about 4 days ago, so I probably (un)ticked a box somewhere I shouldn't have, so I hope someone can help me out figuring out how to change this?

I added a screenshot of the page I think the possibility to administer roles should be. :) (link)

Thanks in advance!

# Answer
Looks like you're on `/admin/people/permissions`, which is the page for configuring permissions per role. You want to be on `/admin/people/permissions/roles`, which is the page for configuring the roles themselves. If you can access `/admin/people/permissions/roles`, you'll be able to add more roles there.

If you get an 'Access Denied' error when you try to access that page:

1. Go back to `/admin/people/permissions`.
2. Make sure you've given the 'administrator' role all permissions.
3. Go to `/user`.
4. Click the 'Edit' tab.
5. Scroll down and make sure your account has the role 'administrator'.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Scalable way to add custom css/js to a page
So I'm working on a site where the ability to add custom javascript is core to the site's functionality. Right now, I'm using the Code Per Node module to handle this, but I have a feeling it's going to be a bit unwieldy when I'm dealing with 20 or 30 pages with custom javascript. Also, I'd love to have a way to keep the js in source control, not the database.

In my mind, the idea solution would be able to either upload or reference an existing javascript file to be loaded in a script block at the bottom of the page. Or, alternatively, pay close attention to how I'm calling things on the DOM and just have all of javascript files minified into one that would be called by my theme's `.info` file.

Is there a better alternate approach to this problem?

# Answer
I had a theme, called bikeswitzerland. There I had a file template.php, where I added the following code:

```
function bikeswitzerland_preprocess_page($vars)
{
       $nid = array_keys($vars["page"]["content"]["system_main"]["nodes"]);
       $nid = $nid[0];

       $alias = drupal_get_path_alias("node/" . $nid);
       $theme_path = drupal_get_path('theme', 'bikeswitzerland');

       switch($alias)
       {
       case 'ask-us':
              drupal_add_css($theme_path . "/css/ask_us.css");
              break;
       };
}

```

Use preprocess\_page hook in your theme. Upload your css files into a dir and create a table in the database, that stores the mapping between the page aliases/urls and appropriate css files.

Then inside the function check, what is the current page url and attach the appropriate css, like I did. And you'll solve your problem.
> 2 votes

---
Tags: 7, javascript, performance
---


title: Best Drupal module for mailing lists?

text:
# Question
Title: Best Drupal module for mailing lists?
I am working on a Drupal based site for a church and one of the items is a method for each group to have discussions.

I immediately thought OG would be a good fit but after consideration I'm not sure it will be enough by itself.

The goals are:

1.) Users will be able to join a group or groups.

2.) Each group will have private content for members only.

3.) Each group will also have a mailing list for 2-way communication (so I don't believe SimpleNews will work). Ideally, when a user is approved to join a group they will also be subscribed to that groups mailing list.

OG will be a good fit for the first 2 items.

I'm not sure about the third.

I've used Mailman in the past but it appears the mailman modules for Drupal are limited to Drupal 6.

What is the best way to achieve this in Drupal 7?

# Answer
Use the Message module along with the message notify module. Message module is Drupal 7's answer to activity-streams and a flexible Messaging & Notifications system.

http://drupal.org/project/message http://drupal.org/project/message\_notify
> 1 votes

# Answer
I have used http://drupal.org/project/og\_mailinglist quite successfully on a Drupal 6 site, but I have not checked the progress on the 7.x-1.x-dev branch that is in progress. It looks like some people are using it; see: http://drupal.org/node/1920282
> 1 votes

---
Tags: 7, emails, organic-groups
---


# Question
Title: Why is my form_state being reset after submission?
I have a menu item with page callback:

```
function my_menu() {
  $items = array();
  $items['my/action/%ctools_js'] = array(
    'title' => 'do something',
    'page callback' => 'my_action',
    'page arguments' => array(2,3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
}

function my_action($js = NULL, $nid = NULL) {
  $form_state = array('nid' => $nid);
  if(!$js) {
    drupal_build_form('my_action_form', $form_state);
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state['ajax'] = $js;
  $form_state['title'] = t('Form Title');
  $output = drupal_build_form('my_action_form', $form_state);
  $commands = array();
  if (!empty($form_state['finished'])) {
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ctools_ajax_command_redirect('challenges');
  } else {
    ctools_modal_form_render($form_state, $output);
  }
  print ajax_render($commands);
  exit;
}

function my_action_form($form, &$form_state) {
  // form fields defined here
}

function my_action_form_validate($form, &$form_state) {
  // $form_state['finished'] = true;
}

function my_action_form_submit($form, &$form_state) {
  $form_state['finished'] = true;
}

```

If I uncomment out the line in `my_action_form_validate` The modal form dismisses and the redirect works. But with that line commented out when I try to set the `$form_state` var in submit, the modal doesn't dismiss and doesn't redirect. The form submit code executes (calls to `drupal_set_message` work fine), but by the time it gets back to the conditional (line 11) in `my_action`, `$form_state` has been set to default and a blank form reappears in the modal popup. How can I dismiss the modal window after submission?

# Answer
> 2 votes
The issue was in the callback frunction `my_action()`. I was using the `ctools_modal_form_render()` function wrong. In the end I replaced the call to `ctools_modal_form_render()` with `ctools_modal_form_wrapper()`:

```
function my_action($js = NULL, $nid = NULL) {
  if(!$js) {
    $form_state = array( 'nid' => $nid );
    return drupal_build_form('my_action_form', $form_state);
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    'title' => t('My Action Form'),
    'ajax' => TRUE,
    'nid' => $nid
  );
  $output = ctools_modal_form_wrapper('my_action_form', $form_state);
  if ( !empty($form_state['executed']) ) {
    $output = array();
    $output[] = ctools_modal_command_dismiss();
  }
  print ajax_render($output);
  exit;
}

```

---
Tags: 7, forms, chaos-tool-suite, javascript
---


# Question
Title: How to create slideshow with views using images from node's field
I have a field in **Page** content type. Field's type is **Image**. It can contain **unlimited** number of images. I want to use this field for **Slideshow** (module `views_slideshow`). I need to create view for showing content of this field sorted by field's delta and showed like Slideshow. I have a problem with sorting, and showing field items as images (I also need to apply images style to my images).

Is it possible?

# Answer
You might have more luck with galleryformatter it's easy to use and works.

The module allows you to select a gallery formatter for an image field.
> 1 votes

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


# Question
Title: Inclusion of SEO-related content in the header using structured Microdata
I am currently looking at the SEO of our site, and I will be using Schema.org Microdata in the head and 'rich snippets', as well as including Facebook OpenGraph data.

What is the best way to include this information in the header, extract it from the content etc.?

Are there any modules that can help out with this task? Are there any best practices?

# Answer
> 1 votes
You can use Drupal hooks and functions like

You could also call drupal\_add\_html\_head from other API hooks such as hook\_node\_view, hook\_ctools\_render\_alter, hook\_init etc..

e.g:

```
/**
 * Implements hook_preprocess_html
 */
function mytheme_preprocess_html(&$vars) {

  $content = drupal_get_title() ? drupal_get_title() : variable_get('site_name', 'Drupal');
  // Add open graph title to head
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => strip_tags($content)
    )
  );

  drupal_add_html_head($element, 'fb_social_open_graph_title');

}

```

---
Tags: 7
---


# Question
Title: Which module facilitates looking up database schemas of custom content type?
I am setting up some reports using DB API to query custom content fields, and rendering them in tables and charts. I am looking for a way to easily look up the names of tables and fields in the Drupal DB.

**My Question**: Is there a Devel-type module that provides an easy reference of the live DB schema?

Currently I'm using drush sql-cli and/or phpmyadmin, so the solution should be something simpler than that.

# Answer
I think the Schema Module can handle that...

> * Schema documentation: hyperlinked display of the schema's embedded documentation explaining what each table and field is for.

I confess I haven't tried it but the module page mentions

> the INFORMATION\_SCHEMA database that the Schema module uses to inspect the database.

so I imagine it has the functionality you're looking for, plus inspection of the live db if you need it.

Or if you don't mind wading through a large krumo array you can always use `drupal_get_schema()`

```
dpm(drupal_get_schema());

```
> 2 votes

# Answer
You can list db tables with

* mysql: show tables;
* psql: \d

However, a better way to get field information would be via a Drupal module and use:

To get the detailed field and instance information.

Table information for each field is also stored in the info structure.
> 0 votes

---
Tags: database, charts
---


# Question
Title: D7: Import localized menu programatically
I'm constructing a site that has 6 localized versions (English, German, Russian etc.). So the site is supposed to have a localized navigation menu with a common structure across the languages.

I've decided that importing menu items though several Drupal API calls would be the quickest way to create the menu structure I need. So I've learned how to save menu links with `menu_link_save()` function and they even get their language field set correctly... but those imported items in different languages mix with each other and get displayed all togeher :-(

When I open and save some imported menu item through Drupal administrative interface it starts behaving properly and gets displayed only when the site is in it's language. Also the 'options' database field for this item becomes populated with some additional data compared to other imported items.

So my question is: what i18n API or some other function should i call to save menu items with all needed options? Maybe there is a better way to painlessly import menus?

Thanks in advance!

# Answer
> 1 votes
You dont need to play directly with i18n. All you need is the correct configuration. It also has a difference between **translated** and **localized** items. Translated items may point to different pages and may have different description (besides other customization). Localized item is the same item with just a different title on the menu for each language.

I think you want a **translated** item. Here is the recipe with some comments:

```
 <?php
 $menu_item = array(
    'link_title' => 'The menu link title',
    'menu_name'  => 'machine-name-of-the-menu', // It uses '-', not '_'
    'customized' => 1, // Must be 1 in order to not dispaly the link in any language
    'link_path'  => 'node/' . $node->nid, // menu_link_save() does not like aliases. Then 'nid' is used
    'language'  => 'en', // language is required in order to make the item translatable
  );
  $mlid = menu_link_save($menu_item); // You don't need to receive it in a variable
  $ml = menu_link_load($mlid); // I'm loading $mlid just to display the result and verify it
  print_r($ml); // Use print_r() only if you are testing on the block "Execute PHP"

```

I had a **hard** time to figure out the need of 'customized' and also the path alias issue.

---
Tags: routes, i18n-l10n, importing-exporting
---


title: Repeated Attempts to register accounts

text:
# Question
Title: Repeated Attempts to register accounts
I have a site with a many users, and public registration is not allowed, I'm the only one who can create accounts. I'm pretty new to drupal, and looking in the log messages I see this FREQUENTLY! What is this all about? Is someone trying to hack my site (sorry for the newb-termanology) but is this some sort of sqli or something I should be worried about? This happens often, and I'm wondering if my site has any vulnerabilities I should be worried about.

Thanks for helping shed some light on the situation!

page not found 02/20/2013 - 2:56pm register'). Anonymous
page not found 02/20/2013 - 2:56pm .url('user/register'). Anonymous
page not found 02/20/2013 - 2:56pm register'). Anonymous
page not found 02/20/2013 - 2:56pm .url('user/register'). Anonymous
page not found 02/20/2013 - 2:56pm register'). Anonymous
page not found 02/20/2013 - 2:56pm .url('user/register'). Anonymous
page not found 02/20/2013 - 2:56pm register'). Anonymous
page not found 02/20/2013 - 2:56pm .url('user/register'). Anonymous
page not found 02/20/2013 - 2:56pm register'). Anonymous
page not found 02/20/2013 - 2:56pm .url('user/register'). Anonymous
page not found 02/20/2013 - 2:56pm register'). Anonymous
page not found 02/20/2013 - 2:56pm .url('user/register').

# Answer
> 1 votes
I wouldn't call it "hacking", but someone (person or automated script) is definitely trying if you accidentally "left the door open". They found out that you didn't. Don't worry about it... As long as you keep your site up-to-date with security updates!

---
Tags: users
---


# Question
Title: How to create a webform submission table with values from the form itself?
I find the current webform submission table completely inadequate when forms are submitted by anonymous users - you can't tell one from another other than by its submission date which not helpful in many instances. I would like to create a new webform submission table that can display specific fields from the submission itself to help identify who the submission is from. Ideally if I could accomplish this with views that would be great, but I am not adverse to creating a module if need be. Has anyone done this before and what would be the best approach?

Thanks.

# Answer
> 1 votes
Unfortunately, the current stable release of the Webform module doesn't support getting to any of the webform submission fields through Views.

However, if you look at this issue on Drupal.org: http://drupal.org/node/680386, you'll see that **integration with views** is a highly desired feature! That's why there's so much activity on it! The good news is that (look at this comment: http://drupal.org/node/680386#comment-6480250) there's actually a patch applied to version 7.x-4.0-alpha6 of the Webform module, so you can test this new integration functionality.

Let us know if it works well!

# Answer
> 0 votes
Webform 4.X is the way to go if you want to use views.

If you are only trying to change the column headers/info (or don't want to upgrade to 4) you can use the provided hooks: `theme_webform_results_table_header` & `theme_webform_results_table.`

Webform includes 'webform.api.php' in the module that doesn't include working code, but rather documents all of the hook usage in webform.

---
Tags: 7, views, webforms, forms
---


# Question
Title: Hide already purchased products (or allow purchasing the product only once)
I have a view with a list of product displays, and I would like to hide all the products that are already purchased by the current user. This would allow purchasing products only once per user.

I've tried to modify the view and add a relationship with the order, but I can't find the relationship "Order". As explained in the similar issue http://drupal.org/node/1221372 , I also tried to create a view of "Commerce Order". I think this would work for displaying a list of purchased products, but not for displaying a list of non-purchased products, because a view of 'Commerce Order' displays results with orders, not results without orders.

Can anyone help me? :)

# Answer
> 1 votes
I would use Content Access to restrict access to nodes by role, then I would make a special role that is required for viewing this product. Then I would create a Rule where buying that product triggers that role being removed from the user.

---
Tags: commerce, views
---


title: Hook to render all active Facet

text:
# Question
Title: Hook to render all active Facet
Is there a possible hook or something else that can be written to display all the current active facet link i.e the selected facet. i want to display to the user in breadcrumb format all the facet they have selected and give them the option to remove it thanks

# Answer
There is a bock for this.

You can create/configure the block from Configuration-\>Search and Metadata-\>Current Search block (admin/config/search/current\_search)

Create a new Search Block and choose a type: Active Items. In pattern enter from tokens below: \[facetapi\_active:active-value\] Then go to your blocks page and activate your new block.

See the screenshot how my settings look like.
> 0 votes

---
Tags: 7, hooks, search
---


title: Add classes to these links

text:
# Question
Title: Add classes to these links
I don't think this is hard at all but beeing a beginner at PHP and Drupal I need some help to do this.

I want to be able to add classes to my navigation elements that are outputted with this code:

```
function mytheme_menu_link__menu_block__1($variables) {

$element = $variables['element'];

$sub_menu = '';

if ($element['#localized_options']['attributes']['title'] != 'misc' && $element['#localized_options']['attributes']['title'] != 'something') {

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }

    if ($element['#original_link']['in_active_trail'] == 0) {
        $output = ''.$element['#title'].'';
    }
    else {
        $output = ''.$element['#title'].'';
    }

    $link = l($output, $element['#href'], array('html' => TRUE));

    return $link;
}
else {
    return '';
}
}

```

If the menu item is active, it should have class X, otherwise class Y. Could someone explain how I add this?

------------------------- Correct Answer -------------------------------

Here is the correct code that longboardnode helped me come up with.

```
function mytheme_menu_link__menu_block__1($variables) {

$element = $variables['element'];
$sub_menu = '';

if ($element['#localized_options']['attributes']['title'] != 'misc' && $element['#localized_options']['attributes']['title'] != 'something') {

    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    }

    if ($element['#original_link']['in_active_trail'] == 0) {
        $output = $element['#title'];
        $class = 'activeClass';

    }
    else {
        $output = $element['#title'];
        $class = 'otherClass';

    }

    $link = l($output, $element['#href'], array('attributes' => array('class' => array($class)), 'html' => TRUE));

    return $link;
}
else {
    return '';
}

```

}

# Answer
I hope I understand your question. If you want to add class to l(), then it must be an array, so your "$link=..." line would read

```
$link = l($output, $element['#href'], array('attributes' => array('class' => array('YOUR_CLASS_NAME')), 'html' => TRUE));

```

You can also read more and see other examples in Drupal's l() documentation

Hope this helps.
> 2 votes

# Answer
You have to insert your desired class as attribute in your l() like:

```
if ($element['#original_link']['in_active_trail'] == 0) {
    $output = ''.$element['#title'].'';
    $class = 'activeClass';
}
else {
    $output = ''.$element['#title'].'';
    $class = 'otherClass';
}

l( $output, $element['#href'], array(
  'attributes' => array(
    'id' => '',
    'class' => $class,
  ),'html' => TRUE))
);

```
> 1 votes

---
Tags: theming, routes, hooks
---


title: How to export nodes as XML?

text:
# Question
Title: How to export nodes as XML?
I need to export all polls of a D6 site in XML format so that they can be imported to Django. Node export module states that one can choose to export nodes in xml using drush. However I could not find any docs to describe how to do so. I tried:

```
drush node-export-export --type=poll --file=xpoll

```

It exports the polls but in array format. I also could not figure out how to do so using the module's GUI.

So appreciate your help to get the nodes XML, preferably using a drush command.

# Answer
`drush help node-export`

You can pass `--format` to supply the format of the output. Try doing `drush node-export-export --type=poll --file=xpoll --format=xml`
> 6 votes

# Answer
Here's how to export your nodes in XML format using the **GUI**:

* Enable the "Node export XML" module.
* Then, in `admin/settings/node_export`, in "Format to use when exporting a node :", check "XML".

Then, to export nodes, you have 2 options :

* if you want to export a single node, you have a "Node export (XML)" tab at the top of each content.
* if you want to export many nodes, you need the VBO module to perform bulk operations. To enable "node export actions" in the "admin\_content" VBO view (`/admin/build/views/edit/admin_content`), click at the right of "Style : bulk operations" and check "node export (XML)" in the "Selected operations" fieldset. You're now able to bulk export your polls using the "Node export (XML)" option in the "Bulk operations" select area.
> 3 votes

---
Tags: nodes, drush, importing-exporting
---


title: Modify arrays in form alter

text:
# Question
Title: Modify arrays in form alter
I'am having an issue which i cannot understand it , for example i have the following lines:

```
$form['field']['und'][0]['#type'] = 'select';
$form['field']['und'][1]['#type'] = 'select';
$form['field']['und'][2]['#type'] = 'select';
$form['field']['und'][3]['#type'] = 'select';

```

it works as expected , but if i try to change this hard coded method to :

```
foreach ($form['field']['und'] as $field)
            $field['#type'] = 'select';

```

it is not working anymore as expected...After a call like

```
 print render($form['field']);

```

for the first paragraph the result is good , as expected. But for the second paragraph it is not working anymore, the result is like nothing has been modified in the array. In the dsm($form) result either way the value of '#type' key is modified... I cannot understand the behavior. Please help!

# Answer
> 2 votes
Like PHP documentation says: In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

```
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

```

http://php.net/manual/en/control-structures.foreach.php

---
Tags: 7, theming, forms
---


# Question
Title: Getting a custom field to appear correctly in Rules using entity form module
I have written a custom field widget called foo which is inserted into an entity form to provide an autocomplete to another web service. I am trying to get the field data to be sent in an email via Rules. I am able to get the entityform tokens using List, text and the standard widgets to show in the email body and the list. However the form field defined in custom widget "foo" appears \[entityform:field\_foo\] rather than \[entityform:field-foo\] which means that the send email rule in Rules appears to ignore it.

From my understanding, I believe that I need to create declare a token using hook\_token\_info():

```
function MYMODULE_token_info() {
  $info['types']['foo'] = array (
    'name' => t('Foo'),
    'description' => t('Tokens related to the foo widget'),
    'needs-data' => 'entityform'
  );
  $info['tokens']['foo']['organisation'] = array (
    'name' => t('Janet'),
    'description' => t('Custom foo widget field'),
    'type' => 'entityform'
  );
  return $info;
}

```

and then declare hook\_tokens():

```
function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);
  if ($type == 'entityform' && !empty($data['entityform'])) {
    $elementform = $data['entityform'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'field-foo':
           $replacements[$original] = str_replace('_', '-', $name);
           break;
      }
    }
  }
  return $replacements;
}

```

The other avenue I was exploring was whether this token needs declaring to Rules via hook\_rules\_data\_info() but I cannot see why so I have not explored it further as the entity form appears to be pushing it through to Rules, just not creating the token so that the email can see it.

# Answer
> 0 votes
I have managed to find a work around using hook\_tokens(). Through viewing the $data array, I was able to find the field and write some code which manipulated the incorrect field and created the token correctly for Rules by walking through the field array.

```
function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
 $replacements = array();
 $sanitize = !empty($options['sanitize']);
  if ($type == 'entityform' && !empty($data['entityform'])) {
    $elementform = $data['entityform'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
       case 'field-foo':
         $name = str_replace('-', '_', $name);
         $field = $elementform->name
         $replacements[$original] = $field[und][0]['value'];
         break;
      }
    }
  }
  return $replacements;
}

```

I would be happy to learn if there is a better way of achieving this goal in Drupal.

---
Tags: 7, entities, tokens
---


# Question
Title: How would I use entity wrapper to insert new values into an entity property list? bundle?
I would like to save a list of values into a entity property.

```
foreach ($results as $result)
{
   $wrapper->title->set(value);
}

```

Can an entity property hold an array of values or would I use an entity reference defined as a field for each of my values?

Thanks

# Answer
> 1 votes
A field can only hold multiple values if it's been explicitly set to hold more than one value (this is an option when creating the field - see "How many values the field will store" at http://drupal.org/documentation/modules/field-ui ). In that case, the correct syntax using the entity metadata wrapper is to use array operator \[\] as follow:

```
$tids = array(....);
$wrapper = entity_metadata_wrapper('node', node_load(1));
foreach ($tids as $tid) {
  $wrapper->field_taxonomy[] = $tid;
}

```

Please note that in your original example you use the field 'title' - however that is a special drupal field, and it cannot be made to be multi-valued.

---
Tags: entities
---


# Question
Title: Form API : display the same form again with AJAX, but with different values, on submit
I originally posted this question on StackOverflow.com but I realize this place is more appropriate... If ever I get useful answers on S.O. I will post them here.

My point is, I never found an (even dirty) way to do what I intend to do, and never managed to find an answer, although it seems quite improbable that no one ever had the same request and/or problem.

Which is, by the way...

## Calling the same form again with AJAX, but with different values than those previously entered by the user

### The idea

I've got a Drupal Form (a normal form built with Drupal Form API) with textfields and an AJAX-ified submit button. This form is displayed through an AJAX call and is itself AJAX-ified, so.

When I click on 'Submit', I want to do some stuff like looking in the database, updating some values, etc, based on what the user entered in the form. And then, *I want to ajax-display the same form again, but with different values than those entered by the user in the first instance of the form*.

Everything goes fine with doing whatever I want during the processing, but whatever I do, no matter what, I face the same problem again and again :

### The problem

When the new instance of the form is displayed, it is displayed with the previous values (those entered by the user). I never was able to display other values than those previously here in the form when "Submit" was clicked in the previous instance of the form.

## Simple example

What I'm actually trying to do is quite complex, with several ajax\_commands and a bit of processing, but here is a simpler example that faces exactly the same problem :

```
function ajax_first_callback_to_my_form($type = 'ajax') {
// here the first instance of the form is ajax-called. No problem with that.

    $mail = 'example@mail.com';
    $first_message = 'Please enter an email address...';

    $commands = array();
    $commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($mail, $first_message));
    $page = array('#type' => 'ajax', '#commands' => $commands);
    return($page);

}

function display_my_form($mail, $message) {
// the function used to display the form.
// it can be called by the first ajax callback (the previous function in this example)
// or by the ajax callback triggered by clicking 'submit' on the form itself.

    $form = drupal_get_form('my_form', $mail, $message);

    $display = '<div id="my_ajax_wrapper">';
    $display .= render($form);
    $display .= '</div>';

    return $display;

}

function my_form($form, &$form_state, $mail, $message) {
// the form constructor

    $form = array (
        'email' => array (
            '#type' => 'textfield',
            '#default_value' => $mail,
            '#suffix' => '<div id="my_message">'.$message.'</div>',
        ),
        'submit' => array (
            '#type' => 'submit',
            '#ajax' => array (
                'callback' => 'my_ajax_callback', ),
        ),
    );

}

function my_ajax_callback($form, &$form_state) {
// triggered by clicking 'submit' in the form

    $mail = $form_state['values']['email'];

    if ($mail == 'correct_mail@gmail.com') {
        $new_mail = 'different_mail@gmail.com';
        $new_message = 'You entered a correct email and here is your new one';
    } else {
        $new_mail = $mail;
        $new_message = 'You entered an incorrect mail, please correct it';
    }

    $commands = array();
    $commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($new_mail, $new_message));
    $page = array('#type' => 'ajax', '#commands' => $commands);
    return($page);

}

function my_form_submit($form, &form_state) {
// my_form submit handler

    $form_state['rebuild'] = true; // appears necessary, otherwise won't work at all

}

```

Okay, it was quite a long piece of code but it seemed useful to fully understand my question.

### Processing stuff happens correctly...

All the stuff I want to do in my\_form\_submit or in my\_ajax\_callback is properly done. If I check the variables in display\_my\_form() they are correctly updated.

### ... but the new instance of the form doesn't take it into account

But whatever I can try, the next time the form is displayed with AJAX, the email field will be 'example@mail.com' as its default value (or any different mail entered by the user), and the message div will be filled with 'Please enter an email address...'.

I tried MANY ways of doing this differently, putting the after-submit processing in the ajax callback, in the my\_form\_submit function, using $\_SESSION variables instead of passing them through the different functions, using the database... None of this works.

### What to do ?

Quite annoying. This is not the first time I encountered this problem. Last time I could find a workaround, simply by giving up this idea of re-displaying the same form through AJAX, but now I really would appreciate being able to do this.

Could the problem be related to $form\_state\['rebuild'\] ?

By the way, I'm curious about it : have you encountered this problem before ? Is it something simple which I'm missing out ? If it's a bug, could this bug be Drupal-related, or AJAX-related... ?

Any help or ideas will be truly appreciated. Thank you for your time.

# Answer
> 0 votes
I came up with a solution to this one :

If you are to display the same form again with AJAX, for instance with this function (called by your AJAX callback), no matter what you'll do, it will display the same values again and again :

```
// It doesn't work :

function display_my_form($mail, $message) {

    $form = drupal_get_form('my_form', $mail, $message);

    $display = '<div id="my_ajax_wrapper">';
    $display .= render($form);
    $display .= '</div>';

    return $display;
}

```

**If you want to change the fields values when refreshing the form**, you have to update the form manually, after having called it again, by adding this kind of line :

```
// It works :

function display_my_form($mail, $message) {

    $form = drupal_get_form('my_form', $mail, $message); // $variables are simply ignored if the form is already displayed. Rebuilding it won't change a thing.

    $form['email']['#default_value'] = $mail; // update a part of the form
    $form['email']['#suffix'] = $message; // update another part of the form

    $display = '<div id="my_ajax_wrapper">';
    $display .= render($form);
    $display .= '</div>';

    return $display; // sends $display to our AJAX callback, and everything's fine now

}

```

Contrary to easy belief one (such as... me) can first have about it, the form doesn't take into account the variables it's being sent with drupal\_get\_form, when already constructed and recalled by AJAX.

It's just not enough to update the variables, and do drupal\_get\_form again. You have to do drupal\_get\_form, and afterwards manually update the parts of the form you want updated.

Hope this will help someone.

---
Tags: forms, ajax
---


# Question
Title: How to set access permission to roles due to the content's vocabulary
There is only one Content Type in my site and two vocabularies ,say, vocabulary1 and vocabulary2. Now I don't want some roles to access some content due to their vocabulary.

Can I set access permission to roles due to the content's vocabulary???

thanks!

# Answer
Have you tried these Drupal modules (quotes included are from their project pages):

> Access control for user roles based on taxonomy categories (vocabulary, terms).
>
> * Automatically controls access to nodes (based on their taxonomy terms).
> * Configuration page for each user role.
> * Three node access permission types: View, Update, Delete.
> * Two term access types: View tag, Add tag.

> The ACL module, short for Access Control Lists, is an API for other modules to create lists of users and give them access to nodes. It has no UI of its own and will not do anything by itself; install this module only if some other module tells you to.
> 0 votes

# Answer
Yes. There are a number of ways.

# 1 Look at taxonomy\_access http://drupal.org/node/200631. This permissions model almost duplicated 'organic groups' functionality with taxonomy. Organic groups is another way of restricting content to a particular 'community of interest' which is likely to be related to a particular information slice. Two possible module/solution oriented approaches.

The next two solutions involve module/code writing.

# 2. Create a custom menu that runs the display. This could invoke a view block or any other block. Write an access callback. e.g.

```
// test interface for the editors report. It is intended to be put in a block.
$items[HOTTOPICSNOTIFY_MODULE_NAME . '/editors-report/%'] = array(
    'title' => 'Editors Report',
    'access callback' => 'hottopicsnotify_access_callback',
    'access arguments' => array(3),
    ...
  );

```

Then in the callback write your logic. % may be the taxonomy term, meaning that you can use this to query against allowed users.

Check out the menu examples module at api.drupal.org/api/examples/menu\_example

# 3 Create node-access realms and assign them to people. e.g. when you save a node under a taxonomy make sure it has a realm relating to the taxonomy

```
/**
 *
 *
 * This marks a node as being applicable to a particular type of permission related to a taxonomy.
 *
 *
 * @param type $node
 */
function hottopics_node_access_records($node) {
  $grants = array();

  if ($node->type == 'hot_topic_research' || $node->type == 'hottopics') {
    $grants[] = array(
      'realm' => 'view_hottopics_fish_biology',
      'gid' => 1,
      'grant_view' => 1, // unpublished content is fine.
      'grant_update' => 1,
      'grant_delete' => 1,
      'priority' => 100, // bigger numbers make this more authoritative
    );

  }

  return $grants;
}

```

See hook\_node\_access\_records

Then hook\_node\_grants gets called when the user tries to access the content, or it is brought up in a views index. This is the strength of this approach, you can use existing views module generated blocks.

```
/**
 * Provide access to a realm to a user.
 *
 *
 * @param type $account
 * @param type $op
 * @return int
 */
function hottopics_node_grants($account, $op) {
  $grants = array();

  if ($op == 'view') {
    // Hot topics editorial board gets all hot topic grants
    $roles = array_values($account->roles);
    if (array_search('editorial board admin', $roles) !== FALSE || array_search('editorial board member', $roles) !== FALSE) {
      $grants['view_hottopics_fish_biology'] = array(1);
    }

  }
  return $grants;
}

```

See hook\_node\_grants api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_grants/7
> 0 votes

---
Tags: users
---


# Question
Title: How to add custom css files in a theme from drupal.org?
I am using the Zen theme on my site, but would like to add custom CSS files that the theme should use. How can I achieve this?

# Answer
> 2 votes
While you can add your own styles to the Zen theme, it would require that you hack the theme.

What you should do instead when using Zen, is to use it as a base theme, and create what's call a subtheme. That is a theme that will use the styles, templates etc from the Zen theme, but where you can custom overrides, alterations and additions without changing Zen itself.

There is a detailed handbook page where you can read about how this is done and what to be aware of.

Within the Zen theme there is also located a start kit for your subtheme that will help you to do most of what needs to be done, and documentation on what to do in the README file in the theme.

# Answer
> 2 votes
Add the CSS styles to the theme.info file with the following line.

```
stylesheets[all][] = css/layout.css

```

---
Tags: theming
---


# Question
Title: When should I not use Views for listing content?
Views is the most popular module of Drupal 7. I don't doubt it's the best solution for listing content on Drupal, as one of the Drupal strengths.

However, Views is not used everywhere. For example, this video shows how to create a product catalog in Drupal Commerce using Taxonomies and Menus.

This question is to ask for the cases where Views shouldn't be used, and why.

# Answer
> 1 votes
That's quite a subjective question, but generally speaking, use Views if

1. You need it done quickly
2. You need to allow flexible UI edit access
3. You don't mind a slight performance hit
4. You need Views for some other module integration ( VBO, views\_data\_export etc.. )

Otherwise, you can use custom page callbacks

1. If you don't mind taking a bit longer to build
2. You don't need UI edit access
3. You want the fastest performance.
4. You want to do something Views can't do, or that is much easier to do custom.
5. You are a capable developer.

# Answer
> 0 votes
1. Don't use views if you are considering using more than a small number of 'relationships', 'contexts' or 'filters'.
2. Put these in code as you may spend a lot of time trying to get the view stable. Putting into your head all the things under the various views options can be difficult. Use 'features' to help with version managing changes and avoid chaos from 'accidental clicking'.
3. If you find yourself inserting things with \[php\] tags it is probably pushing it too far as editing php using the views interface is difficult.
4. If you have 'relationships' or other computer science things and you need editors to be able to make specific changes to the view you may want to write a custom module that only exposes the options that need to be changed. Most editors don't understand what a 'relationship' is and few people have the understanding to model them in their head.
5. If you are experienced writing php but not configuring views, then consider writing code. Views has it's own expertise that needs to be mastered.

---
Tags: views, performance
---


# Question
Title: php include inside .tpl.php template file
I have 2 template files where I want to use a common piece of template code. Is it ok to do an include of the chunk of template code I want to use?

Example model.tpl.php:

```
include('/path/to/template.php.tpl');
<!-- Other Template Code -->

```

# Answer
> 5 votes
Its better to modify the shared template inside `hook_theme` and use Drupal theme engine:

```
<?php print theme('your_shared_template_file', $args); ?>

```

---
Tags: theming
---


title: How do I restore a site using drush?

text:
# Question
Title: How do I restore a site using drush?
I have been learning drush and I loving it. i am having a tough time understanding how to backup and restore my site. Often I bork my site and just need to quickly restore it. These are the steps I am following and I am met with the following error:

```
Destination directory /Users/Nigel/Sites/sitename/ already exists.      [error]

Unable to restore files to /Users/Nigel/Sites/sitename/

```
1. cd to my Drupal installation.
2. Create a Drush archive dump (code and db in one)

drush ard
3. Grab my backup (e.g. sitename.20130221\_055426.tar.gz) and place it back into the root of my Drupal installation

drush arr sitename.20130221\_055426.tar.gz

There is a similar question How do I use Drush correctly to restore a site via the arr command? , however the issue and thus the answer has to do with different db credentials, rather than the steps to restore a site.

I am obviously doing something completely wrong here. Any help would be appreciated.

# Answer
Try adding --overwrite to your restore command, that will let you overwrite an existing site.
> 2 votes

---
Tags: drush
---


# Question
Title: template_preprocess_html(&$vars) dynamic code
I have an html template variable called "sitepage" that needs to be set by a module based on node relationships.

Is there a way to set html.tpl variables from a module?

```
function dc_preprocess_html(&$vars)
{
    $vars['sitepage'] = '/*Insert Business Logic as described below*/';
}

```

The logic for what the sitepage should be is as followed:

1. If we are on a car model or car make page then find the car make node and check to see if there is a node reference to an Advertiser node.
2. Using the advertiser node, check the field "field\_sponsor\_site\_page" to determine the site page

I can easily do this in the module code, but need to do this so I can put the variable in html.tpl.php

The way it works now:

I have 2 pages in play:

1. Car Detail Page: `model/[Car Make Node FIELD_COLLECTION_ID]`
2. List Cars of a particular model: `makes/[Car Make Node Id]`

A car make node has a node reference to Advertiser. The advertiser has a sitepage that needs to be inserted into html.tpl.php in both cases based on this business logic

# Answer
try

```
hook_module_implements_alter()

```

to alter the hooks order
> 0 votes

---
Tags: theming
---


# Question
Title: New custom content type not showing up in 'Create content' menu
I have created some new content types but they automatically don't show up in the 'Create content' menu - what do I have to do to get them there. I am currently logged in as user 1 so it shouldn't be a permissions issue.

# Answer
I think you are facing the same problem I've experienced. Probably you disabled the navigation menu link "Add Content" and its respective sub-menu items. Then, they won't show up at the path **node/add**.

See this Q/A: No content type problem
> 1 votes

# Answer
Try clearing your cache on Drupal.
> -1 votes

---
Tags: routes, nodes
---


# Question
Title: How to add content in custom menu block?
I have own menu type "Footer menu". When I add new content, "Footer menu" is not display in Menu setings. Where is the problem?

# Answer
It's in the Content Type's settings screen under "Menu settings", you have to tick the Footer Menu to make it available for selection.
> 1 votes

---
Tags: routes, nodes
---


# Question
Title: What's the purpose of the authmap table?
I'm trying to create multiple websites with Drupal Multi-site feature, and I need to understand how the *authmap* table is used.

What's the purpose of the authmap table?

# Answer
The "authmap" table is used when a user is authenticated using an external site, for example an OpenID server.
For example, in my test site I have used OpenID to create an account. In that table, I then found the user ID of the user account created by Drupal, and the OpenID URL used to authenticate the user (the one provided by the OpenID server).

The comment in user\_external\_login\_register() gives a short explanation of how that table is used, and which functions the modules integrating with an external authentication server should use.

> Helper function for authentication modules. Either logs in or registers the current user, based on username. Either way, the global $user object is populated and login tasks are performed.

Keep in mind that in Drupal 8 the "authmap" table, and the functionality provided by the functions using it have been removed. Any module providing the integration with an external authentication server will need to use its own database table, which is what the OpenID module did in Drupal 8, before being dropped off.
> 11 votes

# Answer
The authmap serves as a helper to external authentication.

For example, if you use user\_external\_login\_register() in a module of yours that performs this authentication , this module will be associated with the external user in authmap table
> 2 votes

---
Tags: 7, database
---