# Question
Title: Previous/ next navigation in taxonomy terms
Due to some complex project, I would like to organize navigation between taxonomy terms programmatically, with generation of custom links.

Example of navigation I need in vocabulary "fruits" with following terms, situated in same order in taxonomy management admin module :

* ***apple*** -\> has next link to *apricot*
* ***apricot*** -\> has previous link to *apple*, has next link to *banana*
* ***banana*** -\> has previous link to *apricot*, has next link to *cherry*
* ***cherry*** -\> has previous link to *banana*

The question, is : what is the most convenient method to get the id of previous and next term, in the same order as they organized in vocabulary ?

It's seems what in current taxonomy API of Drupal 7 there is no specific functions to do it in simple way.

# Answer
> 1 votes
We will make a view, load the term from contextual argument, get its weight into $static variable, and check on each row if row's term's weight is higher than our arg's one.

1. Create a view of terms, order them by weight.
2. Display only 1 item.
3. Add and hide taxonomy term: weight field.
4. Add a contextual filter : Taxonomy term: Term ID
5. Add a PhP filter and :

Setup code :

```
$static = taxonomy_term_load($view->args[0]);
$static = intval($static->weight);

```

Filter code :

```
if(intval($data->taxonomy_term_data_weight) < $static) {return TRUE;}

```

If you're sure that your terms have **following weight**, you can use that filter code :

```
if(intval($data->taxonomy_term_data_weight) == intval($static - 1) || intval($data->taxonomy_term_data_weight) == intval($static + 1) ) {return TRUE;}

```

to get the next and following terms. But careful with 0 and last values... :)

And of course, in that case, you have to display *all* items in the view.

# Answer
> 1 votes
You can use taxonomy\_get\_tree() to do this.

```
function get_previous_term($vocab, $term) {
  $tree = taxonomy_get_tree($vocab->vid);
  foreach ($tree as $index => $t) {
    if ($t->tid == $term->tid) {
      if (isset($tree[$index-1])) {
        return $tree[$index-1]->tid;
      }
      // $term is the first term in the list.
      return FALSE;
    }
  }
  // not found!
  return NULL;
}

function get_next_term($vocab, $term) {
  $tree = taxonomy_get_tree($vocab->vid);
  foreach ($tree as $index => $t) {
    if ($t->tid == $term->tid) {
      if (isset($tree[$index+1])) {
        return $tree[$index+1]->tid;
      }
      // $term is the last term in the list.
      return FALSE;
    }
  }
  // not found!
  return NULL;
}

```

I tested this on my localhost and it seems to be working.

```
$vocab = taxonomy_vocabulary_machine_name_load('tags');
$term =  taxonomy_term_load(2);
$prev = get_previous_term($vocab, $term);
$next = get_next_term($vocab, $term);
dsm("Prev " . $prev);
dsm("Next " . $next);

```

This code only works for flat vocabularies. If the terms in the vocabulary have hierarchy, you have to take `depth` and `parents` of `$t` into account when trying to find the previous/next term in `get_next_term()` and `get_previous_term()` functions.

# Answer
> 1 votes
As of my view, if you are doing this via some custom module then we can adopt the API taxonomy\_get\_tree()

Now only using that the problem won't be solved. Now, this API gives an associative array of the terms for a particular Vocabulary. So for that array use a foreach loop. In that loop check for the first element and for the last element. This will give you the first and last page for the pager. If other elements are not of the first or last then use the iterator's count to make the link. Its better to use a hook\_theme() implementation and use of theme('list\_item') as well. But if you are not using custom module then the idea with Views will work for you. But again, using views\_php module is not supposed as a good practice. Also for this block caching will not work I think.

# Answer
> 1 votes
Here's another solution using a simple lightweight `db_select` query on `taxonomy_term_data`.

It provides two functions, one to get the next term, and one to get the previous.

The idea is to select the next ( or previous ) term in the same vocabulary with a weight greater ( or less than ) than current term, ordered by weight and limited to one result. A static cache is used so query only performed once per page load.

```
/**
 * Return next term id by weight
 * @param $term taxonomy term object
 * @return int term id or FALSE if none exists
 */
function EXAMPLE_next_term($term) {

  // Use static cache
  $next = &drupal_static(__FUNCTION__ . '_' . $term->tid, FALSE);

  if(!$next){
    $next = db_select('taxonomy_term_data', 'td')
      ->fields('td', array('tid'))
      ->condition('weight', $term->weight, '>')
      ->condition('vid', $term->vid)
      ->orderBy('weight')
      ->range(0,1)
      ->execute()
      ->fetchField();
  }

  return $next;

}

/**
 * Return previous term id by weight
 * @param $term taxonomy term object
 * @return int term id or FALSE if none exists
 */
function EXAMPLE_previous_term($term) {

  // Use static cache
  $previous = &drupal_static(__FUNCTION__ . '_' . $term->tid, FALSE);

  if(!$previous){
  $previous = db_select('taxonomy_term_data', 'td')
    ->fields('td', array('tid'))
    ->condition('weight', $term->weight, '<')
    ->condition('vid', $term->vid)
    ->orderBy('weight')
    ->range(0,1)
    ->execute()
    ->fetchField();
  }

  return $previous;

}

```

Example usage:

```
if($tid = EXAMPLE_next_term($term)){
  $next_term = taxonomy_term_load($tid); // Load full term
  $link = l($next_term->name, 'taxonomy/term/'.$next_term->tid);
}

```

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


# Question
Title: How to display the same field with various nodes in the same row using Views?
How do I do something similar in Views with the below SQL query?

```
select nid,
title AS title1,
type AS node_type,
(select title from node,
field_data_field_node_reference_id
where
node.nid = field_data_field_node_reference_id.field_node_reference_id_target_id
AND
field_data_field_node_reference_id.entity_id = 1)
AS title2,
(select nid from node,
field_data_field_node_reference_id
where
node.nid = field_data_field_node_reference_id.field_node_reference_id_target_id
AND
field_data_field_node_reference_id.entity_id = 1)
AS nid2
from node
where nid=1;

```

The output in MySQL would be:

```
nid | title1     | node_type |   title2        | nid2
1   | Some Title | MyNode    |   Another Title | 69

```

As you can see, they share a relationship by a field called 'field\_node\_reference\_id\_target\_id'. Both values, 'title1' and 'title2', are from the *same* table called 'node'. I would like to avoid writing my own SQL queries, so is there a way to get views to display a similar output (e.g. node titles in the same row that share a relationship)?

# Answer
Yes, simply

1. Add the field relationship your View
2. Add the required fields to the view
3. On the relevant field configuration form, select the relationship to use.

For example:

* "Title" ( no relationship ) to select from base table and
* "Title" ( with relationship ) to select from related data.
> 3 votes

---
Tags: 7, views
---


title: Customized search block

text:
# Question
Title: Customized search block
I have a requirement in which there are two fields for search. One is text field and other is select box. The text field is for keywords and the select field are taxonomy terms. I need to fetch the values in both fields from text file and it should be autocomplete and display the results accordingly.

Please Help.
Thanks in Advance

Riya

# Answer
You can try Custom Search module. This module alters the default search box in many ways. If you need to have options available like in advanced search, but directly in the search box.

The module adds options to select:

* which content type(s) to search, which specific module search to use (node, help, user or any module that implements search),
* advanced criteria For all these choices, there are options to switch between a select box, checkboxes or radio buttons,
* You can also customize the selector label and the default `- Any -` text.
> 1 votes

---
Tags: taxonomy-terms, search, ajax
---


# Question
Title: How to make services node output of file to use external URL instead of public:// URI
I've got a basic web service defined in Drupal that returns JSON describing existing nodes on the server. Contained in the output is the key-value pair:

```
"uri":"public://audio_snippets/01 Australias.m4a"

```

Is there a way for the client website that consumes this service to convert the `public://` URI into something a browser can actually download, like http://www.mywebservice.com/audio\_snippets/01Australias.m4a

# Answer
> 1 votes
There is parse\_url

Like

```
<?php
$url = file_create_url($field[0]['uri']);
$url = parse_url($url);
$path = $url['path'];
?>

```

OR file\_create\_url

```
$usablepath = file_create_url($filesyspath);

```

OR

```
$path = str_replace('public:/', variable_get('file_public_path', 'sites/default/files'), $uri);

```

---
Tags: files, services
---


# Question
Title: Views: Change path and redirect old to new path?
I would like to change the path for one of my Views. How do I redirect the old Views path to the new one including all the variables that may follow the old path?

# Answer
Try http://drupal.org/project/redirect for Drupal 7. It provides an administrative interface to manage page redirects.
> 0 votes

# Answer
Use this Path redirect module to redirect path.

> This module allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status.
> 0 votes

---
Tags: views, redirection, path-aliases
---


# Question
Title: How do I find if a taxonomy term is used?
I'm using drupal6 taxonomy.The content type 'B' is using a tag field which can use the title of the some of nodes of the content type 'A'.If any node of 'B' tagged a name or title of a node of content type 'A', I want to display one message in the respective node of 'A'.

Alternatively, is there any way to find if www.mysite/category/tag/term doesn't gives the "Page not found" error? This is to find if the term is used, or not.

# Answer
> 1 votes
First of all I want to thank whom all gave response to my post.And my answer is,I get the title from the url of content type 'A'(wwww.sitename.com/xxx/yyy/title-raw i get the value of title-raw that is the title of that node.) And the taxonomy term page of content type 'B' has the url as www.sitename.com/category/content\_type\_b\_machine\_name/term name. so i checked the last term of the taxonomy term page in its url with the title-raw of content-type 'A' If the www.sitename.com/category/content\_type\_b\_machine\_name/title-raw-con-type-A doesnot gives a "400" (page not found error)page then the title is used as a taxonomy term.

# Answer
> 3 votes
If you have the term name, you can use the following code.

```
$nodes = array();

if ($term = taxonomy_get_term_by_name($term_name)) {
  $result = taxonomy_select_nodes(array($term->tid), 'or', 0, FALSE, 'n.sticky DESC, n.created DESC');
  while ($row = db_fetch_object($result)) {
    $nodes[] = $row->nid;
  }
}

if (!empty($nodes)) {
  // The taxonomy term is used from at least a node.
}

```

# Answer
> 2 votes
I think that you could use the function drupal\_http\_request (in a module or in a template).

This functions returns the response of the request (200 if it's ok, and so on).

# Answer
> 2 votes
Try using `taxonomy_get_term_by_name('term name')`. It should return an empty array if no term is found, so just check with the `empty()` function.

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


# Question
Title: Access denied when user tries to edit his Content Profile
I’m having a strange problem on one of my Drupal sites running Drupal 6..

I’ve the Content Profile module installed and using Tab Tamer to create some tabs on the “My Profile” page where one of these tabs is “Edit my Profile” which directs to **domain.com/user/uid/profile/profil**

It works fine for me as Admin, it works fine for other users that are just regular registered users, but for one user both the “Edit my profile” tab is gone and when I try to manual enter the URL I get an access denied. I can’t seem to find anything different about the particular user when comparing to other registered users.

I’ve googled the problem and found that there is (or at least has been) some issues about the permission in the Content Profile, but since it works for everyone but this user I’m not sure that whether this is a bug in the permissions with the module or there is some strange other permissions that denies this user access.

I tried to change to users role to administrator, and then he has access to editing his profile – but when changing it back, same issue occurs.

Does anyone have similar experience or a solution for this problem?

# Answer
> 1 votes
1. Edit the node as an administrator
2. On the node edit form, under "Authoring Information" set the author to the content profile user
3. Save content profile node with updated author information.

# Answer
> 0 votes
The solution is to save that profile by administrator (remember to save owner as this user -\> not admin)

---
Tags: 6, users
---


# Question
Title: Why can't I have hyphens in my db_query()
I am trying to SELECT all the rows in my MySQL where a field matches a variable using the db\_query() function. The variable is not a user input, it is retrieved from another database table based on the user currently logged on, so basically the variable is safe, but it does contain hyphens. Obviously without the hyphens the queries won't work properly, but for some reason if I include the variable the database query stops working.

When I say it stops working, I can use the functions in the object that is returned but whenever I try to get individual fields I get an error. In case it affects any suggestions, the query has two more 'comparisons' but without the third, containing hyphens, the query could return more than one row. I only want either one or zero rows to be returned.

Anybody any ideas?

UPDATE: The code I have looks something like this:

```
global $user;

        $ukey = "A-B-C";

        $result = db_query("SELECT NAME FROM ukeys WHERE uid = :uid AND EMAIL = :email AND GENERATEDKEY = :key", array(
            ':uid' => $user->uid,
            ':email' => $user->mail,
            ':key' => $ukey
        ));

        if($result->rowCount() == 1){
            $name = $result->NAME;

```

And the error comes on the bottom line where I try to get the NAME from the results.

# Answer
Make sure you use proper placeholders in your db queries, as per the Drupal API.

E.g in D7:

```
$query = db_query("SELECT * from {foo} WHERE bar = :bar", array(':bar' => $bar));

```

or

```
$query = db_select('foo', 'f')
  ->fields('f')
  ->condition('bar', $bar, '=')
  ->execute();

```

More info:

UPDATE: Now the the original SQL has been posted, the problem appears to be

1. Lack of use of fetchObject, fetchAssoc etc.. on the database result

You should be able to use

```
if($result->rowCount() == 1){
  $name = $result->fetchObject()->NAME;
}

```

As an aside, better to limit the query if you only want one record returned, e.g

```
$name = db_select('ukeys', 'u')
  ->fields('u', array('NAME'))
  ->condition('uid', $user->uid)
  ->condition('EMAIL', $user->mail)
  ->condition('GENERATEDKEY', $ukey)
  ->range(0,1)
  ->execute()->fetchfield();

```

That will return the $name value only, or FALSE if no record exists.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Copy the images to the public folder after form submit with PLupload in a custom module
I have a custom module to create galleries using PLupload to upload multiple files. These files have a ".tmp" extension in my "/tmp" folder.

Here is an extract of my $form\_state\['values'\]:

```
[0] => Array(
    [tmppath] => temporary://p17g31n52jo4fvj31ds01efd189b4.tmp
    [tmpname] => p17g31n52jo4fvj31ds01efd189b4.tmp
    [name] => photo_1.jpg
    [status] => done
)

```

How do I save the files in my public folder with the good extension (like .jpg)? I've tried using file\_save\_upload() or file\_copy() but without success.

Can anyone help me?

I'm on a local server (wamp) as administrator with all permissions. The folders (tmp and site/default) are writable.

I copy here some extracts of my code.

*hook\_form() :*

```
$form['create']['photos'] = array(
    '#type' => 'plupload',
    '#title' => 'Photos',
    '#upload_validators' => array(
        'file_validate_extensions' => array('jpg jpeg gif png'),
    ),
    '#plupload_settings' => array(
        'runtimes' => 'html5',
        'chunk_size' => '1mb',
    ),
);

```

*hook\_form\_validate() :*

```
$file = file_save_upload('photos', array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
));

if ($file) {
    if ($file = file_move($file, 'public://')) {
        $form_state['storage']['file'] = $file;
    } else {
        form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
} else {
    form_set_error('file', t('No file was uploaded.'));
}

```

It returns "No file was uploaded." I don't understand what I should put as first arguments to the *file\_save\_upload* function.

# Answer
> 1 votes
I finally manage to do what I want...

I didn't understand how to use `file_copy` ans its `$destination` argument. We can put a file path, not only a folder path. So, I can save my file.jpg correctly.

My code :

```
$values = $form_state['values']['create'];
$photos_count = count($values['photos']);
for ($i = 0; $i < $photos_count; $i++) {
    $path = $values['photos'][$i]['tmppath'];
    $name = $values['photos'][$i]['name'];
    // set file datas as an object to pass it in file_copy()
    $file = (object)array(
        'uid' => 0,
        'uri' => $path,
        'filemime' => file_get_mimetype($path),
        'status' => 1
    );
    // copy the file in the correct folder
    if ($file = file_copy($file, $filepath . '/' . $name)) {
        drupal_set_message('Success');
    } else {
        drupal_set_message('Error', 'error');
    }
    // set the field datas for saving the node with an array
    $node->field_album_photos[$node->language][$i] = (array)$file;
}

```

Have a nice day !

---
Tags: 7, forms, files
---


# Question
Title: Search result issue with Search API module
I'm working with `Drupal-7`; where i have installed so many different modules in it. one of them modules is `"Search API"`.

The problem what i'm facing is Result of searched keyword. whenever i use to search for a particular keyword it working for the Exact match with that key word.

**For example :** `keyword = "Drupal" ;` then result only retrieved if this exact word will match with the content of database. but i would like to get result which are having any of these characters.

**For example :** `keyword = "Dru" ;` then also all the result will retrieved which is having only word `"Dru"` as well as `"Drupal"` & etc..

In short now Query is working with `"="` operator but i would like to make it with `"LIKE"` operator.

**What should i do in which page to get resolve this..?**

I have tried to many things but not get success.

# Answer
If you are not using Apache Solr in the back-end, then you will have to use the Fuzzy Search module in conjunction with the Search API module. This module provides drupal sites with a fuzzy search engine to allow for broader keyword matches including partial or misspelled keywords.

\*Note: At time of writing this there is some incompatibility with Search API 7.x-1.0-rc1 and Fuzzy Search 7.x-1.x-dev (2011-May-12). To get these two working together, you will need to use the search\_api 7.x-1.0-beta10 until the Fuzzy Search maintainer gets the module caught up to the current release of Search API.
> 1 votes

# Answer
Another alternative is using the Porter-Stemmer module, even though it doesn't exactly allow searching for partial words: It tries to reduce words to their root words. If, for example, you look for *walking*, the search will return any page containing *walk*, *walks*, *walking*, or *walked*, whose stem word is *walk*. It doesn't allow to search for *walking* using *king* as search string.

If you were using Apache Solr as search back-end, searching for partial matching would be implemented in Apache Solr.
> 0 votes

---
Tags: search
---


title: Manage node body in git

text:
# Question
Title: Manage node body in git
For a new blog, I like to have the post text stored as markdown (or an other suitable format) on github. But I want to have all the nice features of drupal (comments, nodes, captcha, menu syste, categories, etc.) for the whole blog.

What options do I have to make Drupal retrieve the node body from git (path, branch, tag), render it, and show it as it would have been entered directly into the body text field?

I don't mind whether an import task fetches the content every now and then or if this is done online.

I'm actually open for all ideas as long I can have people forking and improoving the content and at the same time not loosing all the nice things of drupal.

Update: If possible I'd prefer a *use this module solution*. If this doesn't exist coding hints are of course welcome as well.

# Answer
If the content you are importing is not supposed to be edited, I would suggest to follow the same method used on Drupal.org for some nodes: Implement hook\_node\_view().
In the Drupal.org case, the hook is used to output dynamic content for nodes that once were written using the PHP filter.

This method would allow showing the updated content without to periodically import the content into the node body, it avoids creating revisions for the node, and it avoids having a node body that is edited, and made different from the Github content.
To improve the performance, you can cache the values grabbed from the github, and avoiding accessing it (through `drupal_http_request()`) too frequently.
> 2 votes

---
Tags: nodes, version-control
---


# Question
Title: Copy value of field into the value of a different field
How can I copy the value of one field into another during a node edit?

I'm trying to take the value of a text field and have it populate the title field. I'm thinking I can use the Ajax framework and `$form_state`, but I haven't quite got it yet. Or, is there a way to do this on submission? The Title field is hidden so Ajax isn't required.

In case this helps, the scenario is this: user edits a node, fills in one text field and that value automatically populates the Title field in addition to the current field.

# Answer
> 2 votes
@Volker's tip gave me everything I needed and it's pretty simple as it turns out.

```
if (!empty($form_state['values']['some_other_field'])){
  $form['title']['#value'] = $form_state['values']['some_other_field'];
}

```

Set that in a `hook_form_FORM_ID_alter` and it works great. The part I didn't have was the #value.

---
Tags: 7, forms
---


# Question
Title: How can I manually send order details email to customer in Ubercart?
I have a cron job to read orders from the Ubercart database table, and manually send the order email to the customer.

Usually, when customers checkout in Ubercart, they will get their order email straight away. But in my situation we don't want to automatically send the order to customer because we have some process that needs to be completed before we programmatically send the order email to customers.

How can I manually send the customer's order email in Ubercart?

# Answer
You can try hook\_cron in a custom module and get all orders using uc\_order\_status\_list the return value may contain the email address of the buyer. If not get the order id, use uc\_order\_load to load the order. Get the email of buyer.

And you're done.
> 0 votes

# Answer
Yes, you can. In the Ubercart store administration section go to orders and you can see your orders there then select the order you want to email and go to invoice and there is the option to email the order:
> -1 votes

---
Tags: ubercart
---


title: Cron Cache not working

text:
# Question
Title: Cron Cache not working
I'm using the Cron Cache module to empty my cache tables especially the cache\_form table who take 200Mo in 2 days ,but the probleme is that i notice that the module is not working anymore for few days ago .I'm thinking that it's the expire module maybe ??!!
Please any help ..
**NB:**
I launched the cron 2 times in 10 min (in 24 hours) and nothing happened on the database while i'm configurating my module to flash the cache tables every 24 hours

# Answer
I Uninstalled the expire module and the Cron cache module returns to work as usual
> 0 votes

---
Tags: caching, cron
---


# Question
Title: How can I get major version updates with drush pm-update?
I often check for updates to my modules using `drush pm-update`. However, this check does not check for succeeding major versions. For example, if I am using Mollom 1.1, `drush pm-update` will not alert me that there is a 2.3 version available as well. Is there a way to tell drush to give me all possible updates, including major versions?

# Answer
> 7 votes
You can explicitly ask Drush to tell you all of the available releases for a specific project using the pm-releases command:

```
$ drush pm-releases mollom
------- RELEASES FOR 'MOLLOM' PROJECT -------
 Release         Date         Status
 7.x-2.x-dev     2012-Dec-19  Development
 7.x-2.3         2012-Oct-22  Supported, Recommended
 7.x-1.x-dev     2011-Dec-20  Development
 7.x-1.1         2011-Jul-09  Supported, Installed

```

However, what you want to do -- to have pm-update(code) automatically notify you when there is a newer major release -- is not supported. I have opened a feature request in the Drush issue queue for you: http://drupal.org/node/1880970

**UPDATE:**

Regarding kiamlaluno's comment, you can force the update using pm-download:

```
$ drush dl mollom-7.x-2.3
$ drush updatedb

```

I think that it would be more difficult to write a script to check for updates with pm-releases than it would be to enhance pm-updatecode to show this information. If you'd like to help out, please post a patch at the issue I linked to above.

---
Tags: drush
---


title: Menu with argument from views

text:
# Question
Title: Menu with argument from views
I want to create menu block for each user on sidebar. In it there would be links like Videos, Images, Bio.

So i made view with argument and url is usertype/%/videogallery

It is working fine, but how can i add this as a menu item so when someone visits user3 profile the url in the block menu is leading to Videos, Images Bio with url usertype/user3/videogallery

# Answer
> 0 votes
Just use views to create a block with your "menu" links and then make it show up in the sidebar for all "usertype/*" and "usertype/*/\*" pages.

That view will also need a contextual filter "userid from url" similar to your other view. You can "rewrite the url" to create the links.

---
Tags: 7, views, routes
---


# Question
Title: Drupal 7 Theming: Generate styles to a file instead of inline
In my field.tpl.php, I have used PHP to write a string of CSS. The content of the string varies according to the field options.

I then add this string of css to my theme using drupal\_add\_css(). The style is then added to my theme, but it is added inline.

Is there a way to make the string of CSS to be written to an external stylesheet instead?

# Answer
> 1 votes
If you change the content of the CSS file every time the template file is invoked, then you could use code similar to the following one. The code is longer than it should be because I am using a custom function whenever the equivalent Drupal function would output a message error.

```
function mytheme_data_save($data, $destination, $replace = FILE_EXISTS_RENAME) {
  if (!file_valid_uri($destination)) {
    watchdog('file', 'The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', array('%destination' => $destination));
    return FALSE;
  }

  if ($uri = mytheme_unmanaged_data_save($data, $destination, $replace)) {
    // Create a file object.
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid      = $user->uid;
    $file->status   = FILE_STATUS_PERMANENT;
    // If we are replacing an existing file re-use its database record.
    if ($replace == FILE_EXISTS_REPLACE) {
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $file->fid = $existing->fid;
        $file->filename = $existing->filename;
      }
    }
    // If we are renaming around an existing file (rather than a directory),
    // use its basename for the filename.
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
      $file->filename = drupal_basename($destination);
    }

    return file_save($file);
  }

  return FALSE;
}

function mytheme_unmanaged_data_save($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  // Write the data to a temporary file.
  $temp_name = drupal_tempnam('temporary://', 'file');
  if (file_put_contents($temp_name, $data) === FALSE) {
    return FALSE;
  }

  // Move the file to its final destination.
  return mytheme_unmanaged_file_move($temp_name, $destination, $replace);
}

function mytheme_unmanaged_file_move($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $filepath = mytheme_unmanaged_file_copy($source, $destination, $replace);
  if ($filepath == FALSE || file_unmanaged_delete($source) == FALSE) {
    return FALSE;
  }
  return $filepath;
}

function mytheme_unmanaged_file_copy($source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  $original_source = $source;
  $original_destination = $destination;

  // Assert that the source file actually exists.
  if (!file_exists($source)) {
    if (($realpath = drupal_realpath($original_source)) !== FALSE) {
      watchdog('file', 'File %file (%realpath) could not be copied because it does not exist.', array('%file' => $original_source, '%realpath' => $realpath));
    }
    else {
      watchdog('file', 'File %file could not be copied because it does not exist.', array('%file' => $original_source));
    }
    return FALSE;
  }

  // Build a destination URI if necessary.
  if (!isset($destination)) {
    $destination = file_build_uri(drupal_basename($source));
  }

  // Prepare the destination directory.
  if (file_prepare_directory($destination)) {
    // The destination is already a directory, so append the source basename.
    $destination = file_stream_wrapper_uri_normalize($destination . '/' . drupal_basename($source));
  }
  else {
    // Perhaps $destination is a dir/file?
    $dirname = drupal_dirname($destination);
    if (!file_prepare_directory($dirname)) {
      // The destination is not valid.
      watchdog('file', 'File %file could not be copied, because the destination directory %destination is not configured correctly.', array('%file' => $original_source, '%destination' => $dirname));
      return FALSE;
    }
  }

  // Determine whether we can perform this operation based on overwrite rules.
  $destination = file_destination($destination, $replace);
  if ($destination === FALSE) {
    watchdog('file', 'File %file could not be copied because a file by that name already exists in the destination directory (%directory)', array('%file' => $original_source, '%destination' => $destination));
    return FALSE;
  }

  // Assert that the source and destination filenames are not the same.
  $real_source = drupal_realpath($source);
  $real_destination = drupal_realpath($destination);
  if ($source == $destination || ($real_source !== FALSE) && ($real_source == $real_destination)) {
    watchdog('file', 'File %file could not be copied because it would overwrite itself.', array('%file' => $source));
    return FALSE;
  }
  // Make sure the .htaccess files are present.
  file_ensure_htaccess();
  // Perform the copy operation.
  if (!@copy($source, $destination)) {
    // If the copy failed and realpaths exist, retry the operation using them
    // instead.
    if ($real_source === FALSE || $real_destination === FALSE || !@copy($real_source, $real_destination)) {
      watchdog('file', 'The specified file %file could not be copied to %destination.', array('%file' => $source, '%destination' => $destination), WATCHDOG_ERROR);
      return FALSE;
    }
  }

  // Set the permissions on the new file.
  drupal_chmod($destination);

  return $destination;
}

```

This is how you should use the code.

```
if (($file = mytheme_data_save($data, 'public://mytheme_css') !== FALSE) {
  if ($instance = file_stream_wrapper_get_instance_by_uri($file->uri)) {
    $url = $instance->getExternalUrl();
    drupal_add_css($url, array('type' => 'external'));
  }
}

```

With the code I am using, the file used to contain the CSS styles is deleted the first time the cron tasks are executed, if the file has been created 6 hours earlier.

# Answer
> 0 votes
To add external stylesheet - you need to set `type - external`like this

```
drupal_add_css('http://fonts.googleapis.com/css?family=News+Cycle', array('type' => 'external'));

```

More info about - here

# Answer
> 0 votes
Seems to me like you could use something like `file_put_contents` (see http://php.net/manual/en/function.file-put-contents.php) to write an external CSS file and then use `drupal_add_css` to add the external stylesheet that you just created with PHP.

I hate inline styling too.

---
Tags: theming
---


title: How can I send a coupon to visitors?

text:
# Question
Title: How can I send a coupon to visitors?
I need something which could seems a little strange, but it's a client request...

I have a site selling products using the Commerce module. All is working fine.

I need to allow the visitor to request a **Discount Coupon** in the following way:

1. The buyer see the full display for the product.
2. The product has a price of: 10,00 $
3. Bellow the price there is a form to allow the visitor to request a **Discount Coupon**
4. This form has 2 fields: one is email and the other one is called: 'I want to pay'. The visitor enter the price he/she wants to pay: 8,00 $ and the email.
5. The form is sent and some calculation are done based in: if the value of 'I want to pay' is \>= than the price of the product (10,00 $). Then the condition is true and the visitor receive an email with a **Discount Coupon**
6. The buyer enters this Discount Coupon and pay 8,00 $ for the product.

Can I do this with Rules and Commerce Coupon. Do I need some other module?

# Answer
> 1 votes
I think this can be done via Rules and the Commerce Coupon Module. But you may need to write custom Rules condition and event. But first, from your question it is not clear that the form of email and price that you are saying is line items? I am assuming that those are line items and displayed in the Product display. So in that case in a custom module,

1. We will use the action "When an order is first paid in full" and create a new custom condition to check if the line items are set or not for the payment made. This can be done via creating a new file as "custom\_module.rules.inc". In that file create a new hook as **hook\_rules\_condition\_info()**

```

/**
 * Implements hook_rules_condition_info()
 * @return array $conditions
 */
function custom_module_rules_condition_info() {
  $conditions = array();
  $conditions['agree_to_mail_coupon'] = array(
    'label' => t('Check if user paid for Coupon Code'),
    'group' => t('Coupon'),
  );

  return $conditions;
}

function agree_to_mail_coupon() {
  //This conditions only return TRUE or FALSE.
  if(your line item check condition) { // Add logic to check for the line items. you will get API from api.drupalcommerce.org
    return TRUE;
  } else {
    return FALSE;
  }
}

```
1. Then create a new Event to send the mail. But you need a function to create the coupon code. So via commerce\_coupon.module API list you will get commerce\_coupon\_create or other functions to use. So to create a custom event that will get the email address and the coupon code and send the mail you need the following,

```

/**
 * Implements hook_rules_action_info()
 * @return array $actions
 */
function armory_commerce_commission_rules_action_info() {
  $actions = array();
  $actions['send_coupon_code'] = array(
    'label' => t('Send Coupon code'),
    //Add your parameters in the parameter array. Given are some demo below
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
      'component_name' => array(
        'type' => 'text',
        'label' => t('Price component type'),
        'description' => t('Price components track changes to prices made during the price calculation process, and they are carried over from the unit price to the total price of a line item. When an order total is calculated, it combines all the components of every line item on the order. When the unit price is altered by this action, the selected type of price component will be added to its data array and reflected in the order total display when it is formatted with components showing. Defaults to base price, which displays as the order Subtotal.'),
        'options list' => 'commerce_line_item_price_component_options_list',
        'default value' => 'base_price',
      ),
      'round_mode' => array(
        'type' => 'integer',
        'label' => t('Price rounding mode'),
        'description' => t('Round the resulting price amount after performing this operation.'),
        'options list' => 'commerce_round_mode_options_list',
        'default value' => COMMERCE_ROUND_HALF_UP,
      ),
    ),
    'group' => t('Coupon Discount'),
  );

  return $actions;
}
function send_coupon_code($line_item, $component_name, $round_mode) {
     //Add your coupon generation code
     //Use Drupal_mail to send email to the user
}

```

I haven't tested this one as it's a unique type of requirement. But this will be a basic logic to solve the issue. You may need to do a fair bit of R&D to get it working. I appreciate if you ask if you found some questions & queries.

---
Tags: 7, commerce, rules
---


title: print html entities in link drupal

text:
# Question
Title: print html entities in link drupal
```
l('Visit Website »', 'http://' . $site->purl_prefix . '.' . $base)

```

I have a link I want to print like this the » is not getting parse properly it is still showing up as the character code in the link.

# Answer
> 1 votes
Just pass `html => TRUE` as an option:

```
$options = array('html' => TRUE);
l('Visit Website »', 'http://' . $site->purl_prefix . '.' . $base, $options);

```

From the docs:

> **'html' (default FALSE):** Whether $text is HTML or just plain-text. For example, to make an image tag into a link, this must be set to TRUE, or you will see the escaped HTML image tag. $text is not sanitized if 'html' is TRUE. The calling function must ensure that $text is already safe.

---
Tags: theming
---


# Question
Title: field->raw problem with date in views-view-field.tpl.php (add classes to day and year in date)
I have a template (views-view-field.tpl.php) and I'm trying to get the raw value of the date field so that i can reformat it and add classes to each seperate part of it (ie day, date, year).

This is what I'm doing:

```
foreach ($fields as $id => $field)
{
if  ($id == 'field_date_published')
{
echo $field->content //outputs string to page as themed expected ie 23 Oct
echo $field->raw     //simply outputs 3 digits ie 234
}
}

```

My question is how can i get the raw value of the time so that i can manipulate day, month and year with specific css classes.

Please do not suggest i solve this problem in any way other than getting the raw data in the template file. I know there are other methods to solve this but i have come to the limit of my understanding in the template file and need to find new avenues of learning to progress.

Thanks in anticpation,

# Answer
> 1 votes
This looks like a "feature" in views, for some reason the entity\_id is returned in the "raw" property, instead of anything related to the date.
So you will have to work with the "content" property and just make sure you get what you need there - in the view fields settings, set formatter to "plain" and in style settings HTML to none. This way the content will be just the date value from the database.
Check what type of a date field you are using - some of them are stored in the database as the integer timestamp, some as the textual representation of the date. If you want to work with the timestamp, you will have to either change the type of the field, or convert it in the template (probably not very good performance).
For the formatting, you can use the DateObject from the date module, it even has the handy to\_array which might be of help :).

---
Tags: views, datetime, theming
---


# Question
Title: theme('radios',$variables['element']) not working
Trying to manipulate a form that can be a select / radios or text field based on the user configuration...

If the user wants to use radios for the form... then my module will render the using standard drupal render system.

However when I use theme('radios',$variables\['element'\]) it doesn't work at all... the output is:

```
<div id="some-id" class="form-radios"></div>

```

However if I use: drupal\_render\_children($variables) it works perfectly...

Any clues on why theme('radios') behave differently as the rest of the form API items?

This is the code I'm using:

```
  $form['radio_test'] = array(
    '#type' => 'radios',
    '#title' => 'test',
    '#options' => array( 'a', 'b', 'c' ),
  );

  dpm(theme('radios',$form['radio_test']));

```

And this is the output

```
<div class="form-radios"></div>

```

# Answer
> 1 votes
A radios form field uses a process function (form\_process\_radios()) which is the function that expand the form element, and add its child elements (the single radio elements a radios element is made of).
When you call theme(), that process function is not called, and those child elements are not added.

theme\_radios($variables) executes the following code.

```
  $element = $variables['element'];
  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  $attributes['class'] = 'form-radios';
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
  }
  if (isset($element['#attributes']['title'])) {
    $attributes['title'] = $element['#attributes']['title'];
  }
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';

```

As `$element['#children']` is not set, what you get from `theme('radios')` is an empty `<div>` element with some CSS classes, and attributes.

Differently, when `drupal_render()` is called:

* Any #pre\_render, #process, #theme\_wrappers, and #post\_render function is called
* Any child element is rendered

---
Tags: forms
---


# Question
Title: How to disallow users with certain emails form posting?
On a Drupal 6 site, I struggle with some persistent spammer who uses different tricks to escape any regexp spam filters. Whenever I delete him, he always uses certain email provider (e.g. somerandomname@blablamail.com) to register again.

So I am wondering how can I disalow blablamail.com altogether so that either users can not register with this email provider, or better, they can not post anything after registration?

# Answer
> 1 votes
You can add access rules from admin/user/rules.

The help for that administration page says:

> Set up username and e-mail address access rules for new and existing accounts (currently logged in accounts will not be logged out). If a username or e-mail address for an account matches any deny rule, but not an allow rule, then the account will not be allowed to be created or to log in. A host rule is effective for every page view, not just registrations.

Keep in mind the rules use the SQL regular expression, which means that:

* *%* matches any number of characters, even zero characters
* *_* matches exactly one character

# Answer
> 1 votes
You can create an access rule and deny creating an account or logging in with an account that matches certain criteria.

Go to *admin/user/rules* and add a new rule. In your case, the access type should be *deny*, rule type should be *e-mail*, and the mask can be '*%@blablamail.com*' for instance. You can test your new access rule by clicking on the *Check rules* tab afterwards.

---
Tags: advertising
---


# Question
Title: assign role after registration (male female)
I need users to check male/female option when creating an account. Then I need to automatically assign a role male/female to the users. How can this be achieved? Is there any module which I can use?

# Answer
> 3 votes
You can add a **field** to the user entity at *admin/config/people/accounts/fields*. Let's use the *List (text)* type and call it "field\_gender" with the possible values of *female|Female* and *male|Male*. Display it on the user registration form.

Then you can use **Rules module** to react e.g. when someone creates an account and perform various actions. The idea is that you create two different rules for assigning either the male or the female role.

* Install Rules if you haven't already done so, and create a new rule at *admin/config/workflow/rules/reaction/add*. Choose a name for it and tag it if you want. The rule should react on the following event: ***After saving a new user account***.
* Add a condition in the next step and choose *Data comparison*. Then type or select *account:field-gender* in the data selector.
* Choose the data value in the next step to be *Female*.
* Now your condition is ready, add an action, select *Add user role*, then choose the female role.
* Repeat these steps and create a rule for assigning the male role.

---
Tags: 7, users
---


# Question
Title: Pass a multi value argument to a panel view
Is there a way to pass a multi value argument from panels to a panel view?

I have a node with an entity relation field on it and load this node as context in page manager.

I have also a view which accepts a multi value argument (contextual filter). Not multiple arguments I mean an argument where you have multiple nids normally separated by comma if you would enter them in the url.

I want to pass the nids from the entity relation field on the node loaded as context to the view I load in a panel on the same page.

Maybe it is more understandable by describing it step by step.

* I created a page manager page with a path /admin/something/!nid
* The node identified by !nid is loaded as a context so I have all the field values on the node.
* The node has a field that stores a small amount of other nodes as references.
* I want to pass the nids of the referenced nodes to a panel view as argument number one.
* I have done this with one nid but have no idea how to do it with multiple ones.

Any ideas? Thanks!

# Answer
The entity context provided by CTools uses tokens to provide keywords for the given context.

So if you implement your own token which uses a node object as data source it will end up among your node context keywords, and you can pass it to the view as an argument.

Check out this answer to get an idea how to implement tokens.

Your token replacement method should extract the referenced node IDs from the loaded node, and concatenate '+' or ',' between them (it depends on how your argument is configured in the view).
> 1 votes

---
Tags: views, panels
---


# Question
Title: What hook can I use to modify Views Datasource JSON output?
I'm using Views and Views Datasource to generate a JSON feed for my site. I've got a Video field which has both a video and a thumbnail image.

I want to include the url of the thumbnail image in my json feed. I add the Video field to my list of fields in the View and I choose the "Video thumbnail" format instead of the "Video Player" format so that it will show the thumbnail instead of the video. When I do this in a normal View it works perfectly. However, when I do it with a JSON document view, it doesn't work properly. It renders the url to the video instead of rendering the url to the thumbnail image.

I'm going to create another question which talks about how to get this to work properly, but THIS question is my backup solution.

I can rewrite the field so that it includes the fid of the thumbnail image, so my current idea is implementing a hook that will allow me to post process the rendered json or manipulate the data structure before it gets converted to json so that I can just lookup the image by its fid and then replace that piece of data in the array with the proper image url.

I have tried MANY hooks so far, but none of them provide data which represents the json data.

* hook\_views\_pre\_view
* hook\_views\_pre\_render
* hook\_views\_post\_render
* hook\_views\_post\_execute

My guess is that Views Datasource is processing the data after I've seen it in my hook implementations.

What hook can I use so manipulate the data structure before it gets converted to json or alternatively, what hook can I use to manipulate the json string after it has been converted to json?

# Answer
I find my 1st answer informative regarding auxillery information regarding views and views\_datasource. So here's 1 way I think you get the url you want.

You said:

> My guess is that Views Datasource is processing the data after I've seen it in my hook implementations.

It is, look at what views\_json\_view\_pre\_render() is doing:

```
function views_json_views_pre_render(&$view) {
  if(isset($view->plugin_name) && $view->plugin_name == 'views_json') {
    // Support for Video field.
    if(!empty($view->result)) {
      // Process each View result.
      foreach($view->result as $row => $result) {
        // Only process the entity fields defined by the View.
        foreach($view->field as $field_name => $field) {
          if($field instanceof views_handler_field_field) {
            if($field->field_info['type'] == 'video') {

              // Get the Video URL.
              $video = $field->get_value($view->result[$row]);
              // -- See this line !!
              $url = file_create_url($video[0]['uri']);
              $render_array = array(
                '#type' => 'markup',
                '#markup' => filter_xss($url),
              );
              // Substitute embed code with URL. @todo Add support for escaped embed codes.
              // See this line !!
              $view->result[$row]->{'field_'. $field_name}[0]['rendered'] = $render_array;
            }

```

If its a video field views\_json is taking each of the results and replacing the embed code with the URL of the video. This is what you're seeing.

So how do you fix this. You write your own hook\_views\_pre\_render() that runs *before* views\_json's pre render. In your pre render function you change `$video[0]['uri']` to whatever url you want -- ultimately thats the value views\_json will use. If you can get the FID or the full url to the image here you should be able to easily set that value.

So in your own module you'd write 2 functions:

```
// File: mymodule.install
function MYMODULE_install() {
// Set the weight of the mymodule.module to a value lower than views_datasource's views_json module.
  db_update('system')
   ->fields(array('weight' => -1))
   ->condition('name', 'mymodule')
   ->execute();
}

// File: mymodule.module
/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render(&$view) {
  if(isset($view->plugin_name) && $view->plugin_name == 'views_json' && $view->name == 'YOUR_SPECIFIC_VIEW') {
    // Support for Video field.
    if(!empty($view->result)) {
      // Process each View result.
      foreach($view->result as $row => $result) {
        // Only process the entity fields defined by the View.
        foreach($view->field as $field_name => $field) {
          if($field instanceof views_handler_field_field) {
            if($field->field_info['type'] == 'video') {
              // Change the video uri to the image you want ...
              $view->result[$row][0]['uri'] = /* some logic here */;
            }
          }
        }
      }
    }
  }
}

```

Your pre render hook will run before views\_datasource's. It simply alters the url to whatever you want. Then views\_datasource's views\_json hook runs and just uses it as its supposed to -- you just slipped in the correct value. This should work. Code is untested.
> 4 votes

# Answer
See this issue queue. Currently (some people) think field formatting in Views is brittle. It will change in Drupal8 it looks like.

I haven't done this but this *very* complete issue post discusses how to alter a view field currently:

> Currently Views Datasource is hardcoded to use the the default Field API formatters that come with each field. I've spent enough time researching this issue and talking to the likes of @merlinofchaos (he must hate me at this point) to conclude that the problem is not in Core or Views itself. Both provide the appropriate infrastructure to completely customize the Field API rendering experience from within Views. The way that Views allows us to customize the field rendering experience is via the use of Views Plugins.
>
> The problem with Views Datasource is that it implements Views plugins strictly via OOP inheritance. While that is perfectly O.K. if no one ever wished to override this module's behavior, it doesn't work once you need to say something like: "render me all the fields, regardless if they are empty or not", or things like "allow HTML in the title field, because that's what my manager requested". To further complicate matters, if you implement your own Views plugin, there's no clear way of telling Views Datasource: "hey, use my Views plugin!". In other words, without extensive patching or forking, there seems to be no elegant way to tame Views Datasource.

TLTR: make your own field formatter that outputs the explicit URL you want. The player stuff you describes probably looks at the view mode destination (the HTML destination, page vs feed vs json from Media) and is altering the output someway as you describe.
> 1 votes

---
Tags: 7, views, hooks
---


# Question
Title: How do I access a taxonomy term's field(s)?
Specifically, I'm trying to access a field called 'logo' inside of a couple taxonomy terms (Tweet and Wikipedia edit), which is an image. I have a news feed on the front page of my site, and for each feed item that has a term reference to one of these image beside each feed item in the feed. What would be the best way to go about exposing or accessing the logo field from each taxonomy term?

# Answer
> 8 votes
If you are going to be accessing the content of what drupal call entities (data objects, like nodes, users, taxonomies etc), you might considder using the entity module. It adds some nice helper functions. What Nikit writes is not possible, you would do something like this:

```
$term_id_1 = $node->field_term['und'][0]['tid'];
$term_id_2 = $node->field_term['und'][1]['tid'];

```

Then you would have to load the terms etc. Instead with the entity module you can do.

```
$images = array();

$node_wrapper = entity_metadata_wrapper('node', $node);
foreach ($node_wrapper->field_term as $term_wrapper) {
  $images[] = $term_wrapper->field_image->value();
}

```

`$images` will now be an array with the image field object that holds info like uri, fid etc.

# Answer
> 5 votes
Using `taxonomy_term_load` and `taxonomy_term_load_multiple` will provide you with the fully loaded term object including any custom fields.

Alternatively, use `taxonomy_get_tree` with the final parameter (`$load_entities`) set to `TRUE`.

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


# Question
Title: SQL error for anonymous users on Views Nivo Slider block
I have created a slideshow using the Views Nivo Slider module and added it as a block to the home page of my site (running Drupal 6). Everything works great, but for anonymous users I am getting 2 MySQL errors and the block does not display.

You can see the error message by going here: http://staging.thespanishacademy.com

Naturally, I suspect permissions issues but have triple checked everything, flushed all caches, rebuilt node permissions to no avail.

Any help would be appreciated. I'm also including the exact error message below for historical purposes.

warning: Invalid argument supplied for foreach() in /home/spanish/public\_html/staging/sites/all/modules/views/plugins/views\_plugin\_query\_default.inc on line 924.

warning: Invalid argument supplied for foreach() in /home/spanish/public\_html/staging/sites/all/modules/views/plugins/views\_plugin\_query\_default.inc on line 1000.

warning: Invalid argument supplied for foreach() in /home/spanish/public\_html/staging/sites/all/modules/views/plugins/views\_plugin\_query\_default.inc on line 924.

user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM node node INNER JOIN node\_access na ON na.nid = node.nid WHERE (na.grant' at line 2 query: db\_query /\* Anonymous : db\_query */ SELECT COUNT(*) FROM (SELECT DISTINCT FROM node node INNER JOIN node\_access na ON na.nid = node.nid WHERE (na.grant\_view \>= 1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm = 'content\_access\_author') OR (na.gid = 1 AND na.realm = 'content\_access\_rid'))) AND ( (node.status = 1) AND (node.type in ('home\_page\_slideshow')) )) count\_alias in /home/spanish/public\_html/staging/sites/all/modules/views/plugins/views\_plugin\_pager.inc on line 141.

user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM node node INNER JOIN node\_access na ON na.nid = node.nid WHERE (na.grant' at line 2 query: db\_query\_range /\* Anonymous : db\_query\_range \*/ SELECT DISTINCT FROM node node INNER JOIN node\_access na ON na.nid = node.nid WHERE (na.grant\_view \>= 1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm = 'content\_access\_author') OR (na.gid = 1 AND na.realm = 'content\_access\_rid'))) AND ( (node.status = 1) AND (node.type in ('home\_page\_slideshow')) ) LIMIT 0, 5 in /home/spanish/public\_html/staging/sites/all/modules/views/plugins/views\_plugin\_query\_default.inc on line 1150.

# Answer
When you enable content\_permissions together with the rest of cck submodules, the fields you created aren't visible to anonymous users per default. Due to this, views doesn't add any columns to the select statement and you end up with a faulty select. So the solution is to either setup some permissions or switch content\_permissions off.
In case you need to setup permissions on fields, i think Field Permissions is nicer - you can select the fields that will be affected, by default all is shown.
> 1 votes

---
Tags: views, 6
---


title: Code highlighting in CKEditor

text:
# Question
Title: Code highlighting in CKEditor
How can I highlight the code section and reserved words for common languages like c/c++/Php etc ? I have tried the GeSHi Filter, but it does not work with the CKEditor. Am I doing something wrong ? Can anyone suggest some workable solution for the CKEditor?

# Answer
> 1 votes
If you're having trouble with the Geshi Filter, you could try the alternative http://drupal.org/project/syntaxhighlighter module.

---
Tags: wysiwyg, input-formats
---


# Question
Title: How to handle simultaneous editing and deletion of nodes?
This is a slightly different version of the question about what happens when two people are editing and saving the same node. My version involves node deletion instead of editing:

1. Alice starts to edit the node (/node/123/edit).
2. Bob starts to edit the same node (/node/123/edit)
3. Alice deletes node 123 via the Delete button on the form and the followup "are you sure" page.
4. Bob, not knowing the node has been deleted, hits the Save button on the form.

Currently, Bob gets a 404 error back from the server -- "The requested page '/node/123/edit' could not be found." This makes good sense, since the node has in fact gone away, but in a perfect world I would trap the doomed request and send back something a little more helpful, perhaps redirecting the user to a more reasonable page. Is there any way to do this, short of major surgery on the forms API? I can't think of one, to be honest -- it's the web server here that's unhappy, not Drupal -- but I thought I'd ask... Maybe there's a hook out there that I don't know about?

# Answer
A better solution may be to use content locking to prevent double editing.

for example: http://drupal.org/project/content\_lock
> 3 votes

# Answer
You can also use the Workbench module

> Workbench provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:
>
> * A unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time.
> * The ability to control who has access to edit any content based on an organization's structure not the web site structure
> * A customizable editorial workflow that integrates with the access control feature described above or works independently on its own
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: extract list of user id's from views to tag a content automatic
I want to extract a list of users id's from views to automatic tag the user generated content.

The function is important because a company should be able to make a list of users receiving their ads. These ads are a defined content type they are able to make and it would be great if these user id's could be tagged automatically. This is the only way (as I see it) I am able to control which users are exposed to these ads, because in most instances its only part of a group that should be exposed to it.

Can anyone help me with making this functionality, either in code or through modules I do not know about.

# Answer
Perhaps you could use Views Bulk Operations to list the advert nodes and assign the relevant field information though 'Modify entity values' action

It will allow you to filter and select the adverts to update then batch update them.
> 0 votes

# Answer
If the companies need to target who sees their ads, perhaps you could create a Taxonomy of ad categories, then tag the ad nodes with them.

Add a taxonomy term field to the advertisement content type and to your users (you could call it `field_ad_category`), and use Views to show only ads that match the viewer's ad categories.

Would need bit more info about how/where the ads need to show up to give more detail about the Views settings.

\*Edit: The core Statistics module can keep track of page views out of the box, and integrates nicely with Views. Perhaps you can add a field to the advertisement content type that specifies how many hits the company has paid for, then additionally limit the View to ads with `field_max_hits` greater than their total views (a field made available in Views by the Statistics module).
> 0 votes

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


# Question
Title: When should the second drupal_bootstrap() parameter be used?
The parameters accepted from drupal\_bootstrap() are two; the second is defined as follows:

> `$new_phase`: A boolean, set to FALSE if calling `drupal_bootstrap()` from inside a function called from `drupal_bootstrap()` (recursion).

I am not clear what that means, considering that statistics\_exit() calls `drupal_bootstrap()` using just one argument, thus using the default value (`TRUE`) for the second one.
`hook_exit()` is invoked from \_drupal\_bootstrap\_page\_cache(), and `statistics_exit()` should be considered a function called from `drupal_bootstrap()` that calls `drupal_bootstrap()`.

Yet, `statistics_exit()` is not using `FALSE` as second argument of `drupal_bootstrap()`.

The only functions I found that use `FALSE` as second parameter are module\_hook\_info(), and \_drupal\_bootstrap\_page\_cache(), which contain the following code.

```
  // module_hook_info()
  // This function is indirectly invoked from bootstrap_invoke_all(), in which
  // case common.inc, subsystems, and modules are not loaded yet, so it does not
  // make sense to support hook groups resp. lazy-loaded include files prior to
  // full bootstrap.
  if (drupal_bootstrap(NULL, FALSE) != DRUPAL_BOOTSTRAP_FULL) {
    return array();
  }

```

```
  // _drupal_bootstrap_page_cache()
  // Check for a cache mode force from settings.php.
  if (variable_get('page_cache_without_database')) {
    $cache_enabled = TRUE;
  }
  else {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
    $cache_enabled = variable_get('cache');
  }

```

From the code of the first function I could understand I should use `FALSE` when I need to get the current bootstrap phase, and in that case I would use `NULL` as first argument.
From the code of the second function, I could understand that the second parameter is an internal parameter, I should not pass in my functions, as the only case a function of mine is being called from `drupal_bootstrap()` (also indirectly, through a function that is called from `drupal_bootstrap()`) is when I implement `hook_boot()`, or `hook_exit()`.

Did I misunderstand what said in the `drupal_bootstrap()` documentation? If it so, when exactly should a call to `drupal_bootstrap()` use a value for the second parameter that is different from its default value?

# Answer
> 1 votes
Without looking more closely, I can't say why `statistics_exit()` doesn't use the second parameter, but to answer your question...

The `drupal_bootstrap()` function only ever needs to be called with `$new_phase = FALSE` to prevent an infinite loop inside the core bootstrap code. Unless you're modifying core, *you'll always want to leave the second parameter at its default value* (`TRUE`).

The key is in this part of `drupal_bootstrap()`:

```
// When not recursing, store the phase name so it's not forgotten while
// recursing.
if ($new_phase) {
  $final_phase = $phase;
}

```

Calls to `drupal_bootstrap()` outside the bootstrap process always specify the final phase to bootstrap to (or only get the current phase, in which case, the second parameter doesn't matter). When you call `drupal_boostrap()`, you'll be initiating the bootstrap process and setting the `static $final_phase` variable, so you'll need `$new_phase = TRUE`.

---
Tags: 7, bootstrapping
---


title: Commerce quantity limit

text:
# Question
Title: Commerce quantity limit
In Commerce Line Items quantity field which is an integer field, user can not enter more than 9999, what should i do to unlimit the field?

# Answer
Although that limit appears sane to me, to adjust the maxlength, look at

commerce\_line\_item\_field\_widget\_form

```
  $element['line_items'][$line_item_id]['quantity'] = array(
    '#type' => 'textfield',
    '#datatype' => 'integer',
    '#default_value' => $quantity,
    '#size' => 4,
    '#maxlength' => max(4, strlen($quantity)),
  );

```

You could use hook\_field\_widget\_form\_alter and adjust the `#maxlength` property there.
> 2 votes

---
Tags: commerce
---


# Question
Title: How do I change the currency display from USD to $?
I haven't been able to find a way to change the display of a price from 1.23 USD to $1.23. How do I change the currency display from USD to $?

# Answer
> 2 votes
You could try

hook\_commerce\_currency\_info\_alter

For example,

```
function EXAMPLE_commerce_currency_info_alter(&$currencies, $langcode) {
    $currencies['USD']['symbol'] = '$';
    $currencies['USD']['symbol_placement'] = 'before';
    $currencies['USD']['code_placement'] = '';
}

```

See commerce\_commerce\_currency\_info for the default currency info implementation.

---
Tags: commerce
---


# Question
Title: product display image not showing drupal
I have a question about Drupal Commerce (I'm using Drupal 7). I've added a number of products and created a multi-product display for them. I added a product image (it's common for all these products) to the product display. I also have a view of all product displays with images. But when I click and go to the product price and add to cart form, the product image does not show up. What am I missing??? (I did the same on the localhost before and everything worked fine, but probably I forgot to configure something)

# Answer
I believe you need to add a relationship to your view between the node and the product display.

Hope this helps...
> 0 votes

# Answer
You should add the product image to the product entity itself, rather than the product display node.
> 0 votes

---
Tags: views, commerce
---


# Question
Title: How to make rendered product variations show in a grid rather than a list?
I need to present some product variations rendered in a grid, without any cart options. The idea is to have the user click a link to the product and present a page with the variations.

The easiest way I manage to do this is: in content-\>manage display I only show the field:Product Variations, with the format:Rendered Product, which gives me exactly what I want. Except it is displaying the rendered variations in a vertical list rather than the nice grid like it shows by default in the product list view.

Where does the presentation of this rendered product variation elements come from?

I'm using the default theme:commerce kickstart omega.

# Answer
> 1 votes
You can quite easily create a View display to list your products in a grid.

1. Add a new View ( Admin \> Structure \> Views )
2. Add a page display
3. Add relevant filters for entity type etc..
4. Set the style to "Grid" layout
5. Tinker from there with fields etc..

That should do it.

---
Tags: commerce
---


title: Theme suggestion or theme overridden

text:
# Question
Title: Theme suggestion or theme overridden
I have two template override - **user-profile.tpl.php** and **views-view-fields--myviewname.tpl.php**. To take effect those templates, I had to place them into the default enabled theme.

The main problem is that I use the default theme "bartik" and I got to place them into "themes/bartik/templates/" to let the drupal theme system know them.
I know it is not a good idea because it is just like hacking. I should use a custom theme or sub-theme from bartik, but I don't want to write any theme.

The only clue is that I have a custom module and I shall put them into that module ( sites/all/modules/mymodule/templates ). Then, I shall make a theme suggestion to let the theme system use them.

How can I do this or any better idea?

# Answer
> 0 votes
I resolved this using hook\_theme\_registry\_alter(). I placed my theme files in **sites/all/modules/mymodule/theme** and then altered the theme registry with the hook.

```
function mymodule_theme_registry_alter(&$theme_registry){
    if( isset($theme_registry['user_profile']) ){
        $theme_registry['user_profile']['template'] = drupal_get_path('module', 'mymodule').'/theme/user-profile';
        $theme_registry['user_profile']['theme path'] = drupal_get_path('module', 'mymodule').'/theme';
    }
}

```

# Answer
> 1 votes
when you create a sub-theme you do not need to create any "new" template, but you can change something from the "main-theme". So try to create a new sub-theme and put that files into sub-theme.

M.

---
Tags: 7, theming
---


# Question
Title: Create custom display of element using field values
Lets say I have a Company content type that contains the following fields:

* Company Name
* Company Description
* Company Logo Image
* Company Website URL

I use the Entity Reference module to relate companies to Articles. When displaying an article page I would like to show the company logo which should link to the URL with the description on-hover. If I were using a view I'd do a rewrite for something like this:

```
<a href="[Company-Website-URL]">[Company-Logo-Image]</a>
<div class="tooltip">[Company-Description]</div>

```

How could I do something similar for the actual individual article page?

# Answer
I assume you have an entity reference field "Company" in the content type "Article". You could implement hook\_node\_view() to achieve this on the individual article node page. Check the following example code:

```
function mymodule_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        if( $node->type == 'article' ){
            // load the entity reference 'company' in full
            $company = node_load($node->field_company[LANGUAGE_NONE][0]['target_id']);

            $logo        = $company->field_logo[LANGUAGE_NONE][0]['uri'];
            $logo        = '<img src="'.file_create_url($logo).'" />';
            $website     = $company->field_website[LANGUAGE_NONE][0]['safe_value'];
            $description = $company->body[LANGUAGE_NONE][0]['safe_value'];
            // delete the default entity reference display
            unset($node->content['field_company']);
            // add the company logo to the node view
            $node->content['logo'] = array(
                '#markup' => l($logo, $website, array('html'=>TRUE))
            );
            // add the company description to the node view
            $node->content['tooltip'] = array(
                '#markup' => '<div class="tooltip">'.$description.'</div>'
            );

        }
    }
}

```

API reference for functions used in the hook.
> 2 votes

# Answer
You should use Views module for that.
1 - let's create new view (show: content, type: company)

2- we want to create block not a page display, then press "continue & edit".

3- now add the three fields (Company Logo Image,Company Website URL,Company Description) but you should exclude them from display, yes all of them.

don't forget to delete the title field or exclude it from display too.

4- add (Global: custom test) field and uncheck (create a label), in the text field you can use "REPLACEMENT PATTERNS" to recreate what you want exactly, like this:

`[Company-Logo-Image]

[Company-Description]
`

when you finish click save.

5- now you have to add a "CONTEXTUAL FILTERS", search for the Reference field you
added to your content type, in (WHEN THE FILTER VALUE IS NOT AVAILABLE) section select "Provide default value" then select from the type list "Content ID from URL" and save the field and the views too.

Finally you should display the view in the node page, so you can do this by two ways:
A- using display suite module you can add this view as dynamic field and put it it the region you want.

B- by php code (you can use computed field module to write php code in a field)

`<?php
$viewname = 'YOUR_VIEW_NAME';
$display = 'VIEWS_DISPALY';
print views_embed_view($viewname, $display);
?>`

you should notice you can get the Your view machine name ($viewname ) from the url while you are editing the view setting:
admin/structure/views/view/\[View\_machine\_name\]/edit/block\_1

and the display of you view:
admin/structure/views/view/View\_machine\_name/edit/\[block\_1\]

if you need any help just tell me.
> 0 votes

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


# Question
Title: Can't disable css caching and aggregation
I've recently installed some modules including wysiyg, ckeditor, ajax comment, b2 nice comments.

I then noticed that my css files became cached and aggregated when inspect my pages. I unistalled all the modules and double checked the options in the performance menu which were correctly disabled.

The weirdest thing is that I restored the files and DB to an older version and it didn't help. I ported the site to another directory within the server (under a different domain) and the problem disappeared.

Anyone with similar experiences or ideas as to what might be the cause ?

# Answer
Does your theme use the core Color module? I believe that module compiles and caches CSS files with the updated color values whenever the theme color pallet is changed. Just an idea.
> 1 votes

# Answer
Found it. It turns out it wasn't drupal at all. My web host introduced an extra option to optimise page performance, which was ticked by default when you visted their control panel page by default. Very sneaky.

I guess the moral of the story is to remember that there drupal is not the lowest layer in your website !
> 1 votes

---
Tags: theming, caching
---


title: can't find node_export_feeds module

text:
# Question
Title: can't find node_export_feeds module
I want to migrate nodes from a drupal 6 site into a fresh drupal 7 site. Looking at the node export module, under **Migrating nodes between Drupal versions ** it says you need to enable *node export feeds* and use the feeds module in D7 to import. Obviously I downloaded and installed the node export module and enabled all the submodules, but there simply isn't any node export feeds module listed within those.

All I'm seeing listed on my sites modules page under node export is:

* Node export
* Node export DSV
* Node export features
* Node export files
* Node export relation
* Node export serialize
* Node export XML

# Answer
You must enable the Node Export Feeds module and the Feeds module on the **D7 site** and import the nodes via the Feeds user interface from the D6 site.

Make sure you enable the Feeds Import and Feeds Admin UI modules as well on the D7 site
> 0 votes

---
Tags: 6, updating, importing-exporting
---


# Question
Title: How do I use Drush correctly to restore a site via the arr command?
I am having an issue with the Drush arr command working correctly. I use drush to backup an archive on a testing server and then move it to a live server, or vice versa when needed.

Here is a typical command I use for restore

```
drush arr --db-url=mysql://name:pass@localhost/mydb

```

The database credentials on the test server are different from the live server. When drush completes the restore process it does so correctly and then says "the database credentials are appended to the bottom of the settings.php file"

That's great, and it indeed appends the correct information about the database, but this never works.

drupal always tries to read the original database configuration that comes before the appended information.

So, I always have to open up an editor, open up the settings.php file, scroll down to the bottom, remove the appended information, then manually go back and change the config information.

This is a huge waste of time.

How do I use this command correctly to avoid that? I want to seamlessly be able to type the command and immediately start using the site without having to manually edit anything.

Also, given that the database config variable is an array, how do I just tell the settings.php file, via drush, to use one or the other? If I have config for a testing environment and a live environment, I simply want to tell it which one to use as needed.

EDIT:

I wanted to add some more information as to the errors I get as well as the settings.php information.

So, immediately after using the command above, this is the error I get on the server I am restoring to:

```
PDOException: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost'
(using password: YES) in lock_may_be_available() (line 167 of
/var/www/vhosts/domain.com/httpdocs/includes/lock.inc).

```

Here is what the settings.php file contains for the original db configuration:

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

```

Here is what is appended to the end of the settings.php file:

```
// Appended by drush archive-restore command.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'driver' => 'mysql',
      'username' => 'name',
      'password' => 'pass',
      'port' => '',
      'host' => 'localhost',
      'database' => 'livedb',
    ),
  ),
);

```

This looks to be the same except that the sequence for the config is different than the original. Even so, I get the error as stated above. Could the config property sequence be causing this?

# Answer
> 3 votes
settings.php is just an executable php file, so it seems on the surface that there should be no reason for you to do the editing step described above as long as

a) you have not inserted anything in your settings.php file (like a 'return' statement) that halts execution before the end

and

b) the database information that Drush writes at the end of settings.php is the same as the database information you hand-edit into the normal location.

If you are doing the editing information because the database information on your testing server is DIFFERENT than the database information on your production server, then you would be better off using sql-sync to migrate your database from one to the other, and migrate your code with either drush rsync or a version control system such as git. By default, drush rsync will not transfer your settings.php file, so you can customize it in each location and not have to worry about it being overwritten. If you use a vcs, you could exclude settings.php e.g. by using a .gitignore file.

Finally, I should add that it is only viable to use sql-sync or archive-dump/restore to move a whole site from testing to production BEFORE you have user generated content. If you ever have users who create accounts, add content, post comments, etc., copying the whole site will overwrite all of that information. Usually, folks copy the database from live to test only, and copy only code from test to live. To move configuration, look into the features module, or drush ctools export bonus.

**Update:** archive-dump / archive-restore does support changing database specs, and seems to be working correctly per your use case described above. Note, however, that you said in your updated text that the two db records are the same, but in fact they have different database names. This, I expect, is as it should be; I further presume that the database info archive-restore is writing to the end of settings.php matches the info you pass in on the command line.

---
Tags: 7, drush
---


# Question
Title: Which node table in Drupal 6 stores the node published date, created date timestamps?
I need to write a query to retrieve all nodes and their published dates for a Drupal 6 website and I would like to know which database table holds the nids and the timestamps. I am aware that there are 6 tables dedicated for storing info related to nodes.

I know about node\_load but I do not want to use that?

# Answer
> 1 votes
The node created and updated timestamps are stored in the base "node" table.

e.g

```
$result = db_query("SELECT nid, title, changed, created FROM {node} ORDER BY nid ASC LIMIT 10");

while($row = db_fetch_object($result)){
  // drupal_set_message($row->title);
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}

```

---
Tags: 6, nodes, database
---


# Question
Title: When using the webform module, is it possible to get information on the submitter's device (Mac/Win/Android), browser version, etc.?
I'm using Webform 3 on Drupal 7. I have a form on my site for people to report problems with the website itself. Many of these reports ultimately turn out to be browser- or OS-specific, but often users do not add such information in their initial report.

Is there any way to automatically capture the browser and OS information, etc. in Webform upon submission?

# Answer
It appears webform allows a default value using %server variables, but only for authenticated users.

> In addition to %get and %post, the following super tokens may be used, though only with logged-in users: %server, %cookie, and %request. For example %server\[HTTP\_USER\_AGENT\] or %session\[id\].

For authenticated users, try adding a User Agent field with a default value of %server\[HTTP\_USER\_AGENT\]

If your form submissions come from anonymous users, you may need an alternative way to add the %server tokens.

Other $\_SERVER variables documented here: http://php.net/manual/en/reserved.variables.server.php
> 2 votes

---
Tags: webforms
---


# Question
Title: Removing Divs of form elements with profile2 fields
I want to remove the extra divs that get added like in the following example (user-register-form):

```
<div class="field-type-text field-name-field-phone-number field-widget-text-textfield form-wrapper" id="edit-profile-parent-field-phone-number">
  <div id="profile-parent-field-phone-number-add-more-wrapper">
    <div class="form-item form-type-textfield form-item-profile-parent-field-phone-number-und-0-value">

    <label for="edit-profile-parent-field-phone-number-und-0-value">phone number <span class="form-required" title="This field is required.">*</span></label>
    <input class="text-full form-text required" type="text" id="edit-profile-parent-field-phone-number-und-0-value" name="profile_parent[field_phone_number][und][0][value]" value="" size="60" maxlength="255" />
    </div>
  </div>
</div>

```

I already did YOUR\_THEME\_form and YOUR\_THEME\_form\_element in template.php to get rid of extra divs. But this only works for the standard fields of a form it seems.

I am using profile2 and profile2\_regpath modules and it seems as if they add themselves extra divs for the fields that are specific to the profile fields. But I can't figure out how to overwrite this behavior.

Any help or hint appreciated.

And just in case it is already written somewhere: I used the search function and could only find the standard solution for normal fields. Nothing specific to profile2 module.

Oh and some details: I'm using Drupal 7. If anything else is needed, please tell me.

Thank you, best regards.

# Answer
You can use a theme\_field override to adjust the field markup.

e.g, for body field on article content type:

1. Copy theme\_field to `template.php`
2. Rename function to `THEMENAME_field__body__article($variables)`
3. Clear theme registry cache
4. Modify theme function markup to suit.

Note, the theme function naming convention required the "field\_" prefix on field names, e.g THEMENAME\_field\__field\_example\__article()
> 1 votes

---
Tags: forms, users
---


# Question
Title: how to install commerce_kickstart on an environment with PHP memory_limit less than 128M?
I tried the full core install aproach and got a warning that I only had 96M on php `memory_limit`and kickstart needs 128M. tried anyway and sure enough got a memory error at the very end of the installation. I looked around my host and I'm sure I can't change that.

How can I make this installation work?

# Answer
> 1 votes
Try the methods listed here to increase the PHP memory\_limit value

If none of those work, you may need a new host for that application.

---
Tags: commerce
---


# Question
Title: How to Integrate Non-Gregorian Calendars in Calendar Module?
I plan to create a simple event calendar on Drupal 7 that uses the Arabic Calendar (Hijri) instead of Gregorian (western) calendar. Instead of developing a new module, I was wondering if I can use the capabilities of Calendar Module and make it use Hijri Calendar instead of Georgian calendar in views and in the calendar template. The mini-calendar should be Hijri Calendar. No need for Month or Year calendars.

There is a module called Calendar Systems that adds the support of Hijri Calendar to Drupal but I'm not sure how it can be integrated with the Calendar Module or Views.

What are my options?

# Answer
> 1 votes
You can use the latest development snapshot of the Calendar Systems module. It works fine.

# Answer
> 0 votes
It is currently not possible. However, the calendar systems module appears to be working on Views integration, but unfortunately for D6. There's some code there that you might be able to use.

The Calendar module issue that I have linked to also links to a wiki page where you can participate in discussions on this subject.

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


title: Display comment count in a view

text:
# Question
Title: Display comment count in a view
Using views I would like to display the number of posts by a user. This will include a count of nodes as well as comments.

e.g.

Jon
Nodes: 10
Comments:6

Jane
Nodes: 22
Comments: 9

etc....

I have created a view of type user. I can find the user: content relationship and with aggregation turned on, I can get the node count. However I do not see a user: comment relationship o get the comments that the user has created. Am I missing something?

# Answer
This small Views user: comments relationship patch should be just the ticket: http://drupal.org/node/1773966

> ...I ended up creating a "User: Comments authored" relationship. Very useful. Combined with aggregation and using "count distinct" it allows a user view to include # comments authored and # of nodes authored.

Direct link to patch: http://drupal.org/files/views-uid\_comment\_relationship.patch
> 7 votes

---
Tags: views, comments
---


# Question
Title: JQuery accordion works in admin but not for anonymous
D7.18 I have a similar problem to another question but the solution did not work for me. I have added my jquery accordion file (accordion.js) to the subtheme.info file and a file called accordion.js to the subtheme folder. The accordion.js code is

```
(function($) {
Drupal.behaviors.accordion = {
attach: function (context, settings) {
   //code starts
  $("#accordion").accordion({
  autoHeight: false
  }
  );
   //code ends
  }
 };
 })(jQuery);

```

The accordion effect works correctly when logged in as admin but does not when logged out. Firebug shows for the anonymous user but none of the other classes that are shown when logged in as admin. I am using the Omega Theme. I am completely stuck as to how to resolve this

# Answer
> 1 votes
jQuery UI is bundled with core in D7 ( see /misc/ui ). To add jQuery Accordion JS you can just go:

e.g, in template.php

```
function THEMENAME_preprocess_html(&$variables) {
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.accordion');
}

```

After that, clear all caches and check the javascript files have been added in the HTML source of the page as anon.

---
Tags: javascript, navigation
---


# Question
Title: space character in url is coming up as '%20'
one of my clients website (built on D7) has the '%20' sign coming up in url as a result of a space. My only way around till now has been to use'-' instead of a space between the product names. But i cannot have a '-' between every products name. Please advise

* A 'non html/non - technical / not sure what plugins we have already installed' person

:|

# Answer
> 4 votes
%20 is a standard replacement for the space character in URLs.

If you're using pathauto for clean urls ( presumably ), it should remove those from the URL, and replace with hyphens.

/admin/config/search/path/settings

> SEPARATOR
>
> Character used to separate words in titles. This will replace any spaces and punctuation characters. Using a space or + character can cause unexpected results.

Check that a hyphen "-" character is being used there.

The regular product title can have spaces, but pathauto should replace those with the separator character in the URL.

---
Tags: uri
---


title: Sending webpage through email

text:
# Question
Title: Sending webpage through email
I've implemented `hook_menu` and in page callback there is a function in my module which retrieves some records randomly and theme them with `theme_table`. Now I want a button on the page for sending this page exactly as it is to a predefined email address without refreshing the page because of randomly selected records.

I placed a button through simple HTML code but don't know how I can implement it's `onClick` function. Or is there any better way to do that? Thanks

# Answer
> 0 votes
It is simple javascript... The returned value can easilly be sent through ajax (there are good tutorials on sending mails with ajax).

```
<button onClick="alert(document.getElementsByTagName('body').innerHTML())" value="serialize">

```

You might run into trouble though, at first email clients can have trouble accessing images from remote locations (eg. from your own url). So you might have to attach them to the mail.

Also most email clients are very picky when it comes to css. They refuse to load a remote sytlesheet. You will have to hardcode all css classes in the respective elements, the old fashioned way... By using the object style attribute.

```
<body style="background: red; font-size: 9pt;">

```

So as you see it is harder then just sending the HTML to an email receipient. In fact you might want to have a look at HTML2Canvas (or other alternatives) to make a 'screenshot' of a webpage and just send one image.

---
Tags: 7, ajax, javascript, emails
---


title: Spam filter in signatures?

text:
# Question
Title: Spam filter in signatures?
Since otherwise great spam module does not check user signatures for spam, I have hard times fighting spammers who just put their spam links in their signatures in the forum so basically they rendered my custom spam filters useless.

I appreciate if you have some suggestions to resolve this problem.

# Answer
> 0 votes
OK, a better answer in the context of forum signatures only ( assuming D6 forum\_signature module ) could be

Preprocess the signature.tpl.php template file and add the spam check

in template.php, function sig might be `THEME_preprocess_signature`, so try both, if first doesn't work.

```
function THEME_preprocess_signature_forum(&$variables){
  $content = $variables['signature'];
  $test = spam_content_is_spam($content, 'signature_forum');
  if (!empty($test['is_spam']) && $test['is_spam']){
   $variables['signature'] = t('This signature has been removed by our spam filter, please contact the site administrator for assistance');
  }

}

```

Then clear theme registry cache.

I don't use those modules myself, but such an approach, with a little tweaking, could work.

# Answer
> -1 votes
Ban any spammers by IP address, either:

1. One at a time from Admin \> Config \> People \> IP Blocking
2. Block the range at the webserver config level ( firewall, virtualhost or .htaccess )

You may also want to add reCaptcha to user registration, if suitable.

---
Tags: nodes, advertising
---


title: Drupal6 sidebar code?

text:
# Question
Title: Drupal6 sidebar code?
I got this Drupal 7 code from a theme and I am trying to convert it to Drupal 6.

### .info file

```
regions[sidebar_a] = 'Sidebar A'
regions[sidebar_b] = 'Sidebar B'

```

### Template file

```
<?php if(isset($variables) && isset($variables['sidebars'])): ?>
  <?php if (isset($variables['sidebars']['left'])): ?>
    <?php foreach($variables['sidebars']['left'] as $value): ?>
      <?php if (!empty($page['sidebar_'.$value])): ?>
        <div id="sidebar-<?php echo $value; ?>" class="col-<?php echo $value; ?> sidebar left tb-height-balance tb-region tb-scope tb-sidebar tb-left">
          <?php print render($page['sidebar_'.$value]); ?>
        </div>
      <?php endif; ?>
    <?php  endforeach; ?>
  <?php endif; ?>
  <?php if(isset($variables['sidebars']['right'])): ?>
    <?php foreach($variables['sidebars']['right'] as $value): ?>
      <?php if (!empty($page['sidebar_'.$value])): ?>
        <div id="sidebar-<?php echo $value; ?>" class="col-<?php echo $value; ?> sidebar right tb-height-balance tb-region tb-scope tb-sidebar tb-right">
          <?php print render($page['sidebar_'.$value]); ?>
        </div>
      <?php endif; ?>
    <?php endforeach; ?>
  <?php endif; ?>
  <?php if(isset($variables['sidebars']['hidden'])): ?>
    <?php foreach($variables['sidebars']['hidden'] as $value): ?>
      <?php if (!empty($page['sidebar_'.$value])): ?>
        <div id="sidebar-<?php echo $value; ?>" class="col-<?php echo $value; ?> sidebar right tb-height-balance tb-region tb-scope tb-sidebar tb-right tb-hidden">
          <?php print render($page['sidebar_'.$value]); ?>
        </div>
      <?php endif; ?>
    <?php endforeach; ?>
  <?php endif; ?>
<?php endif; ?>

```

# Answer
> 0 votes
Functionality aside, I think the basic structure for D6 would be:

```
<?php
if(isset($sidebars['left'])):
  foreach($sidebars['left'] as $value):
    if (!empty(${'sidebar_'.$value})): ?>
    <div id="sidebar-<?php echo $value; ?>" class="col-<?php echo $value; ?> sidebar left tb-height-balance tb-region tb-scope tb-sidebar tb-left">
      <?php print ${'sidebar_'.$value}; ?>
    </div>
    <?php
    endif;
  endforeach;
endif; ?>

```

---
Tags: theming, 6
---


title: What does views UI Module do?

text:
# Question
Title: What does views UI Module do?
I'm new to drupal and I have read about view UI module in many places but was not able to find what exactly it is.Can any one help me on this ?

# Answer
Views UI module gives you a nice user interface to create, and edit your views. A "view" here means what the Views module produces; it could be a slideshow, a page with a table, a block of recent comments, etc.

You can turn that module off if you have finished making all the views, and the site is ready to go on production. Your views will work no matter you have the Views UI module enabled, or not.
> 3 votes

---
Tags: views, 7
---