# Question
Title: How can I print Views Exposed Filter widgets individually using views-exposed-form--mypage.tpl.php?
I have five exposed filter widgets that appear on this page. I would like to group three of them together and add a title above that group of three so that my layout goes from:

*views default*

* A
* B
* C
* D
* E

*what I want*

* A
* TITLE

+ B
    + C
    + D
* E

Since this customization is specific to one page, I added a `views-exposed-form--mypage.tpl.php` in my theme's template folder.

The code looks like this:

```
<div class="views-exposed-widgets clearfix">
    <?php foreach ($widgets as $id => $widget): ?>
      <div id="<?php print $widget->id; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>
          </label>
        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>
          <div class="views-operator">
            <?php print $widget->operator; ?>
          </div>
        <?php endif; ?>
        <div class="views-widget">
          <?php print $widget->widget; ?>
        </div>
      </div>
    <?php endforeach; ?>
    <?php if (!empty($sort_by)): ?>
      <div class="views-exposed-widget views-widget-sort-by">
        <?php print $sort_by; ?>
      </div>
      <div class="views-exposed-widget views-widget-sort-order">
        <?php print $sort_order; ?>
      </div>
    <?php endif; ?>

```

Instead of the foreach loop, how can I print the individual widgets?

# Answer
> 1 votes
```
<div class="views-exposed-widgets clearfix">
    <?php foreach ($widgets as $id => $widget):
       if ($id == 'SOMETHING_ID_THATIDENTIFY_B') {
         print '<div id="BCD">'.t('TITLE');
       }
       else if ($id == 'SOMETHING_ID_THATIDENTIFY_E') {
         print '</div>'; //Closing #BCD
       }
    ?>

      <div id="<?php print $widget->id; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>
          </label>
        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>
          <div class="views-operator">
            <?php print $widget->operator; ?>
          </div>
        <?php endif; ?>
        <div class="views-widget">
          <?php print $widget->widget; ?>
        </div>
      </div>
    <?php endforeach; ?>
    <?php if (!empty($sort_by)): ?>
      <div class="views-exposed-widget views-widget-sort-by">
        <?php print $sort_by; ?>
      </div>
      <div class="views-exposed-widget views-widget-sort-order">
        <?php print $sort_order; ?>
      </div>
    <?php endif; ?>

```

---
Tags: 7, views
---


# Question
Title: On a multilingual website using i18n, should I set the built-in Drupal English or my custom English as the default source language for strings?
I have a multilingual website with five languages. Because I wanted to extensively customize Drupal's built-in English, I also created a custom language, "U.S. English." I then disabled the built-in Drupal English; the site now uses my custom U.S. English as the default language.

However, I'm confused about which language I should select to be the "Source language" for string translations on the i18n module's admin/config/regional/i18n/strings page. Should I select my custom "U.S. English" or the built-in Drupal English? How does the default language affect string translations?

EDIT: Please note that I am asking about the i18n module's "Source language" for string translations, not the site's default language. Clearly, I need to set the default language of the site on admin/config/regional/language to my custom U.S. English; if I do not, users of the site will not see it. The "Source language" for string translations (at admin/config/regional/i18n/strings) is separate from the default language, and I don't understand whether I should set it to my custom language or the Drupal default.

# Answer
I18N is a beast of a module. I will try to answer this but have no I18N setup on hand, so this is from memory.

As you have probably realised, depending on how things are configured the default language is normally used as fallback when translations are not available. So, keeping this in mind, you would use your U.S English to translate/modify the entries you want, and set it as default. Source language would be set to the original English.

It used to be one would need to export and re-import translations but that is not the case anymore.

There is a warning to heed, ripped from http://drupal.org/node/1279668 (good reference on your topic btw):

> In contrast to Drupal's standard localization system, which always translates from English, strings will be translated from the source language. By default the source language is the site's default language, so changing the default language could break these translations. You can set which language is used as the source language via Administration \> Configuration \> Regional and language \> Multilingual settings \> Strings.

As this message states clearly things may break along the way, backing up your data is very important while you are tweaking this.

PS: Much better and simplified I18N support is upcoming in D8, \*YEAH! *

Good-luck!
> 4 votes

# Answer
I think you should use your own defined English language, I mean which one you created. Because, for example, if you changed the word "Save" into "Submit" and in your i18n module you choose built-ind Drupal English you will have "Save" for word to translate and no "Submit".
> 1 votes

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


title: Change URL of ?q=user

text:
# Question
Title: Change URL of ?q=user
By default, Drupal uses `site.com/?q=user` or with clean URLs enabled, `site.com/user` to display the user login page. However, that is conflicting with my hosting provider's own rewrite settings, where navigating to that link brings up the actual web server admin login. Is there a way to override this?

# Answer
I think your hosting provides default cpanel url is `/admin`

In that case you need Rename Admin Paths module.

**The purpose of this module is to secure drupal backend by overriding admin path.**

**Overview**

This module allows you to:

rename path like '/admin/...' to '/something/...'

rename path like '/user/..' to '/something else/..'
> 1 votes

# Answer
Give the page an alias using the built-in Path module.
> 0 votes

---
Tags: users, uri
---


title: Check parent term when checking subterm

text:
# Question
Title: Check parent term when checking subterm
I have a client with a really large taxonomy, which is used for a certain node type. My client wants that the parent term of a chosen subterm, to also be used for a node.

Let's say that this is the taxonomy:

* Parent1
    + Child1
    + Child2
* Parent2
    + Child3

If the user checks (they are printed as checkboxes) either child, its parent term will also be used.

Is there already a module for that, or something, or do I have to write my own?

Drupal 7

# Answer
> 2 votes
Taxonomy Term Reference Tree Widget has this option. install and select it as your taxonomy reference widget and check `Select parents automatically` in field instance setting form

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


# Question
Title: Custom sort to preserve order of referenced nodes
I have a node type that references other nodes. When viewing node of Content Type A, I have set up a view that displays all references to nodes of Content Type B on a gmap.

This is the code from a template file that overrides the display of view\_one; it calls the map in from another view.

```
<?php
  $view = views_get_view('view_one');
  $view->set_arguments(array($fields['nid']->raw));
  $view->execute();
  $contents = $view->result;

  foreach($contents as $content) {
    $nodes[] = $content->node_field_data_field_B_content_nid;
  }

  if (isset($nodes)) {
    $args = implode(',' , $nodes);
    $view = views_get_view('linked_map');
    $view->set_display('map');
    $view->set_arguments(array($args));
    $view->execute();

    $markup_map = $view->render($args);

  }
  else {
    $markup_map = '';
  }
?>

```

It displays beautifully. The only problem is I want to use numbered markers, so that the list is in the same order as the referenced nodes in the main view ("view\_one"). Is there some way that I can either utilize a "sort" that won't rearrange the list, or write a custom sort that will preserve the existing order?

I am using the Views module version 7.x-3.1.

# Answer
> 1 votes
Draggable Views will let you define your own manual sort, and keep it consistent across different displays.

---
Tags: theming, views
---


# Question
Title: How to set the permission for each file separately for downloading?
want to add a functionality of uploading files so that users can download these files.

First is there any module to provide this functionality (Uploading files from admin and then on front end, users can download these files).

Second If I upload some files then can I set the permission on the specific files. My requirement is that some files will be only downloadable for registered users. The anonymous user could not be able to download the file. And the 2nd scenario is that some files will be required the admin approval. Means if a user click on the file for download, a notification will be sent to the admin, then if admin approved it then the user can be able to download the file.

Any Idea about this.

Thanks in Advance.

# Answer
> 1 votes
You have to set your site's file management to private, and then use a module or code your own management stuff using the files API.

# Answer
> 0 votes
for first file module (from core) provide this functionality, you can upload files and other can download it

for second part Field Permissions module has some of these features.

---
Tags: users, files
---


# Question
Title: Is there a way to pop form errors off the display stack and/or prevent their display?
I have a Drupal 7 form which I'm allowing the user to submit via AJAX. If the user does not fill out required fields, or enters invalid information, I can return that and alert the user via the `form_get_errors()` function. The problem is that these values are still on the "display stack" (not the correct term, I'm sure) - when the user refreshes the page, or navigates to another one, these previous errors are displayed.

Is there a way to set these errors not to display once I've grabbed them with `form_get_errors()`?

EDIT: The session variable 'messages' is set at `$_SESSION['messages']['error']`, which is where the display of the errors is driven from. I could wipe this out by doing something like `unset($_SESSION['messages']['error'])`, but I feel like this is very hacky. The `drupal_static_reset()` function also will not help, since it doesn't eliminate the values in the messages array.

# Answer
> 1 votes
If you know the message was the last one set, a simple hack is to just:

```
array_pop($_SESSION['messages']['error']);

```

Just be aware this only removes the message, your form will still be in error state.

# Answer
> 0 votes
Yes its pretty common.. :)

But I have used the same technique, that is to unset the $\_SESSION array.

Some of the modules store the errors as $\_SESSION\['module\_name\]\['messages'\]\['error'\], which is good so that you dont unset some else's message.

I have used AJAX for form submit many times, but still haven't run into a better or more Drupal way to do this.

Will be glad to find something better than unset or array\_pop ;)

# Answer
> 0 votes
I believe you can grab all the themed error messages by `theme('status_messages', array('error'))` which in turn calls `drupal_get_messages()` which unsets the messages that got displayed. Or if you want a structured array of messages you can call `drupal_get_messages('error')` straight away. I'm not 100% certain this works for form errors, but I hope this helps.

Edit: Sorry didn't notice this question was from December 2011 -.-

# Answer
> 0 votes
This will help you.

```
drupal_get_messages($type = NULL, $clear_queue = TRUE);

```

---
Tags: forms, ajax
---


# Question
Title: How can I prevent a form from being displayed in the privatemsg module?
I am trying to remove the "Block a user" fieldset, username text and input field, and "Block user" button from the "Blocked users" page as shown below.

The code I'm trying to change is in the pm\_block\_user module:

```
/**
 * Formbuilder function to build a simple form to block users.
 */
function pm_block_user_list() {
  global $user;
  $form['new'] = array(
    '#type'   => 'fieldset',
    '#title'  => t('Block a user'),
  );
  $form['new']['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#autocomplete_path' => 'messages/user/autocomplete',
    '#description'        => t('Separate multiple names with commas.'),
    '#required'          => TRUE,
  );
  $form['new']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Block user'),
    '#validate' => array('pm_block_user_block_validate'),
    '#submit' => array('pm_block_user_block_submit'),
  );

  $header = array(
    array(
      'data' => t('Username'),
      'field' => 'u.name',
      'sort'  => 'asc',
      ),
    array(
      'data' => t('Operations'),
      ),
  );

  $select = db_select('pm_block_user', 'pmb')->extend('PagerDefault')->extend('TableSort')
    ->fields('pmb', array('author'))
    ->condition('pmb.recipient', $user->uid)
    ->limit(20)
    ->orderByHeader($header);

  // Only show existing users, therefore join users.
  $select->innerJoin('users', 'u', 'u.uid = pmb.author');

  $rows = array();
  foreach ($select->execute() as $row) {
    $rows[] = array(
      theme('username', array('account' => user_load($row->author))),
      l(t('unblock'), 'messages/block/' . $row->author, array('query' => drupal_get_destination())),
    );
  }
  $form['#header'] = $header;
  $form['#rows'] = $rows;
  return $form;
}

```

Here is the code I tried in my template.php based on these instructions for removing unwanted elements from forms:

```
function MYMODULE_pm_block_user_list($form) {
  unset($form['new']['#title']);
  unset($form['new']['#type']);
  return drupal_render($form);
}

```

However, this code hides the "Username/Tom/Operations/unblock" section, not the "Block a user" section which I am trying to hide.

# Answer
The following code does it for me:

```
function MYMODULE_form_pm_block_user_list_alter(&$form, &$form_state, $form_id) {
  unset($form['new']);
}

```

This should help if you didn't know about it.

`hook_form_FORM_ID_alter();`

Also there's the more generic `hook_form_alter()`.
> 2 votes

---
Tags: forms, privatemsg
---


# Question
Title: How do I migrate the content of a specific type?
I wanted to backup all the contents of specific content type, and I want to install those data in different machine. Can anyone suggest me some good module which could help me do this?

I have tried the Backup module, and the Migrate module, but they back up the entire database. I want to backup specific contents alone but I couldn find any modules to do that.

I could use either the Node Export module or the Feed module to back up specific content. Node export gives various options like you can export the data to CSV, XML or in text format which can be then imported using node import.

# Answer
> 2 votes
If you can get a CSV of the particular nodes you wish to migrate, then the Feeds module will do exactly what you want.

Worst comes to worst you can generate an RSS feed in Views of the content on your original site and then import using Feeds to the new site from that RSS feed.

---
Tags: 7, migrations
---


# Question
Title: subfolder installation user block login and destination issue
I have installed drupal 6.22(fresh installation) on my localhost in which i have set user block on header. Now my problem is when i looked to action of user login form, here i can see my folder name is there.

Say My url : http://localhost/drupal6/

So i can find my form action : /drupal6/node/85?destination=node%2F85

Now after login my url becomes http://localhost/drupal6//drupal6/node/85?destination=node%2F85 and I got page not found error.

And that actually creates issue on redirection.

I want to mention that i have installed 6.22 cause we need to make changes to older version. TIA. What could be the actual reason? Do I need to create a custom user login block for the same? or any issue in url function though i have not changed core files or not added any custom login module. My active theme is garland.

Edit:

Without login go to "http://localhost/drupal6/admin/settings/site-information", It shows access denied message then login using your account and you will face page not found error.

Cause in browser its showing me "http://localhost/drupal6//drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information".

Just try out in your any setup on localhost or on subdomain installation. Its not working as expected.

After login url should be "http://localhost/drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information" instead page not found. TIA

EDIT : MOD-Rewrite

# Answer
> 1 votes
Finally i found the issue of redirection. I have checked form.inc file from where i have found that drupal\_goto function from common.inc file is called.

Now by debugging that form.inc i found that drupal\_redirect\_form calls drupal\_goto with different options. In subfolder case (i.e. my case) drupal\_goto function i have found that $path has value like '/drupal6/' default. So what i have hacked is

```
$folder_name = '/drupal6/';
$length = strlen($folder_name);
$path_check = substr($path,0,$length);
$path_len = strlen($path);
$remaining_path = '';

if($path_check == $folder_name) {
    $remaining_path = substr($path,$length,$path_len);
    echo $path = $remaining_path;
}

```

So now my problem of adding two folder name like 'http://localhost/drupal6//drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information/' have been solved but as you know that this is core hack and i dont like it. Any better solution???

I know that if i transfer this site from my localhost to internet than that would not create any problem without making this kind of small hacks.

# Answer
> 0 votes
Modify line 94 of `.htaccess` to look like this:

```
RewriteBase /drupal6

```

Here are the contents of that file: http://drupalcode.org/project/drupal.git/blob/HEAD:/.htaccess

# Answer
> 0 votes
I am not sure how you installed it, but would look into $base\_url in your settings.php file (sites/default/settings.php) and see where it is pointing, and if drupal6 is not your actual web server root, then it should look something like

`http://localhost:PORTNUMBER/drupal6`

You can also look in `admin/settings/site-information` and make sure it is showing to the left of default front page, eg, it should look like this:

`http://localhost:PORTNUMBER/drupal6 [ node ]`

NOT

`http://localhost:PORTNUMBER [ drupal6/node ]`

# Answer
> 0 votes
Check line 107 in your `.htaccess` file. Try uncommenting that line, and ensure that line 103 is commented out.

Example:

```
  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

```

Also, just in case, ensure that you have `mod_rewrite` enabled on your localhost.

---
Tags: blocks, users, redirection
---


title: Multiple images in field and views

text:
# Question
Title: Multiple images in field and views
I have a view that creates JSON for me. The view has a field that multiple images, title, body and some other data fields on it. The image field can have multiple images. How can I show all the images? I know multiple field settings would show all the images but then it would loop all the info multiple times (as many times as there images) and I don't want this to happend.

I have also tried "Display all values in the same row" and putting Simple separator as "," but it only shows the first image.

What I want is the JSON would be something like this:

```
"nodes" : [

{
  "nid" : "124",
  "title" : "This is the node title",
  "field_shot_desc" : "Short description text",
  "Body" : "<p>Curabitur blandit tempus porttitor. Nulla vitae elit libero, a pharetra augue.</p>\n",
  "field_images" : "http://www.domain.com/sites/mytheme/files/styles/browser-thumb/public/rest1.jpg","http://www.domain.com/sites/mytheme/files/styles/browser-thumb/public/rest2.jpg",

},

```

So the images would be separated with , or something so I can manipulate them in JS later.

# Answer
Here there is a piece of code I wrote for the same problem. It checks if the field is an array and start a for loop to print the field. I've used this in an external page who gets json through a json view from drupal. I hope this can help you. If you rewrite it in a simple way, please let me know. I'm using drupal 6, with NO "Display all values in the same row".

This Check if the field has got more than one img:

```
var image =  your_img_field;
    function isArray(image) {
   if (image.constructor == Object)
      return true;
   else
      return false;
}

```

If the field has got more than one img, it counts the array and return the size:

```
if (isArray(image) == true) {
Object.size = function(image) {
    var size = 0, key;
    for (key in image) {
        if (image.hasOwnProperty(key)) size++;
    }
    return size;
};
var size = Object.size(image);

```

Here the for loop to print (in my views the array starts from 1)

```
for (i=1; i<size+1;i++){
$("ul").append("<li><img src=\'"+image[i]+"\' /></li>");
}
}

```

If the field img has not more than 1 img it prints the single img.

```
else {
$("ul").append("<li><img src=\'"+image+"\' /></li>");
}

```

PLEASE, CHECK QUOTES AND DOUBLE QUOTES IN THE IMG TAG `<img src=\'"+image+"\' />`
> 1 votes

# Answer
You should probably use the view template to rewrite the output to fit your needs.

This thread has the information you need to find the correct file, but your use will be slightly different.

It only involves simple PHP string manipulation, probably with an `implode` somewhere.
> 0 votes

---
Tags: views, media
---


# Question
Title: Checking which radio button was clicked on a cck form using Javascript or Jquery
I have a content type which I am loading in a block as a form. I am looking to know which radio button out of 2 buttons was clicked so that I can display additional fields. What is the best way to achieve this using JavaScript?

```
<div class="form-item">
 <label>I am: <span class="form-required" title="This field is required.">*</span></label>
 <div class="form-radios"><div class="form-item" id="edit-field-org-or-part-value-organizer-wrapper">
 <label class="option" for="edit-field-org-or-part-value-organizer"><input type="radio" id="edit-field-org-or-part-value-organizer" name="field_org_or_part[value]" value="organizer"   class="form-radio" /> Organizer</label>
</div>
<div class="form-item" id="edit-field-org-or-part-value-participant-wrapper">
 <label class="option" for="edit-field-org-or-part-value-participant"><input type="radio" id="edit-field-org-or-part-value-participant" name="field_org_or_part[value]" value="participant"   class="form-radio" /> Participant</label>
</div>
</div>
</div>

```

# Answer
You can try .change() But you should haver the radio button under the same div.

I've used it in drupal 7

```
function foo() {
var field = $('#YOURFIELD').val();
  alert(field);
}

$('#YOURFIELD').change(foo);

```

Read this http://api.jquery.com/change/ to know more about .change()
> 0 votes

# Answer
If you want to have an 'other' type of field you could use: http://drupal.org/project/select\_or\_other

I maintain custom code to achieve what you want (on very long fake multistep forms) and don't recommend this, it quickly becomes very unmanageable.
> 1 votes

---
Tags: entities, javascript
---


title: vote for users on drupal7

text:
# Question
Title: vote for users on drupal7
I need the functionality to be able to have a vote widget on a profile page. So users can be voted for and the user with the most votes wins.

(the users profile page is done with panels & views)

Ive played around with the flag module and it somewhat works for what I want, also the vote module, but it seems to only work on nodes and comments and doesnt work on user pages...

Any advice is greatly appreciated

# Answer
You can try to add fivestars module to your website, but then your users will be voted with stars instead of flags.

If you dont mind that you have to:

1. install fivestar module
2. add a field on your user profile of type "Fivestar Rating"
3. add a rule so people cant vote on themselves using rules module.

hope this helps
> 3 votes

---
Tags: 7
---


# Question
Title: Wysiwyg with ckeditor and custom configuration
Is there any way to add custom configuration to ckeditor when using through the wysiwyg module?

Using the ckeditor module there is an advanced option and there it is possible to edit that.

# Answer
Take a look at this Denver DrupalCon2012 Talk: What-you-see-not-always-what-you-get-it-can-be

Google Docs here
> 1 votes

---
Tags: wysiwyg
---


# Question
Title: CCK nodereference is returning empty nid when no node is selected
For testing purposes I've installed CCK module on vanila drupal, created new node type and attached CCK nodereference to it.

After creating new node, I've notice in node.tpl.php the following structure:

```
    [field_my_node_reference] => Array
    (
        [0] => Array
            (
                [nid] =>
                [safe] => Array
                    (
                    )

                [view] =>
            )

    )

```

As you can probably notice, there is a key $node\['field\_my\_node\_reference\]\[0\]\['nid'\] that is null.

In order for me to fully understand CCK - why CCK gives empty keys when nothing is selected?

Any answer is appreciated !

# Answer
You are looking at a node in CCK's post `build_content()` phase. When you add a node reference field to a node, CCK adds the 'nid' portion to the database, and when you build or display the content, it creates the 'safe' and 'view' portions. If you were doing this manually, you could do something like:

```
$foo=node_load(27);

```

and if $foo had a nodereference, $foo would contain

```
[field_my_node_reference] => Array
(
    [0] => Array
        (
           [nid] =>
        )
)

```

eg, you could `print 'my nid is ' . $foo->field_my_node_reference[0]['nid'];'`

and it would print out `my nid is [blank]` if unset, or `my nid is 593` if set. Now, when CCK comes in and gets all fancy, it creates the safe and view pieces, and these are set up by those widgets you select in the display fields portion of CCK before getting to node.tpl. (You can do this yourself by calling `$foo=build_content($foo);` in a module and looking at `$foo` again.) Anyways, CCK works all of that up into the $content variable it aggregates things together into for your node.tpl as well as in the $node variable it has in there if you yourself want to get fancier, eg, `print 'this is a link to my node: ' . $node->field_my_node_reference[0]['view']` would normally print out 'this is a link to my node:' followed by the title of the node linked to it. All changeable via those display options/widgets.

But as to why it has empty keys, they are just part of the data structure created to ensure everything up and down the workflow works together as well as it does, eg, the safe and view portions are blanks where a link would probably go if the field was set, so that makes sense. And a NULL is in nid since it hasn't been set.

But...just plop in some content and you will see everything fill up all nice :)
> 2 votes

---
Tags: 6, entities, nodes
---


# Question
Title: CDN, SEO and image styles: 301 on GET request
Recently I installed the CDN module. To avoid duplicate content I added a RewriteRule to my Apache config:

```
RewriteCond %{REQUEST_URI} !(^/(.*)(.js|.css|.jpg|.jpeg|.gif|.png)) [NC]
RewriteCond %{HTTP_ACCEPT} !(.*image.*|.*css.*|.*javascript.*) [NC]
RewriteCond %{HTTP_HOST} ^(static1.domain.com|static2.domain.com)$ [NC]
RewriteRule ^(.*)$ http://domain.com$1 [L,R=301]

```

This is working, except when I'm using image styles. If the image exists everything works, but when it doesn't exist, I get a 301 to http://domain.com/index.php

---

**These are the current situations using the implemented RewriteRule**:

* GET static1.domain.com - 301 to http://domain.com \- *OK*
* GET static1.domain.com/image.jpg - 200 - *OK*
* GET static1.domain.com/sites/domain/files/styles/.../image.jpg when file exists - 200 - *OK*
* GET static1.domain.com/sites/domain/files/styles/.../image.jpg when file doesn't exist - 301 to http://domain.com/index.php \- *WRONG*

How do I force the image style file to be created when browsing to it from a static URL?

# Answer
> 1 votes
Apache directives are context sensitive. Since the RewriteRule was in a VirtualHost, the directives were different than normal.

This is the working version:

```
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST} ^(static1.domain.com|static2.domain.com)$ [NC]
RewriteRule ^(.*)$ http://domain.com$1 [L,R=301]

```

The RewriteRule behaves different than in the original post, it just checks for files instead of types of files, it behaves like described in drupal\_sensei's answer.

# Answer
> 1 votes
I dont really understand your question, but we handled a similar problem. We also did rewrtie for all images to static server (different server running lighttpd). On the lighttpd the files folder was mounted as well, so all files are in sync.

We also had a domain that forced back to one of the webservers (varnish\>drupal), and not to use the CDN server . If the file did not exist in the static server it got rewrtitten (temporary) back to the webserver, which created the imagecache file. From that moment, the file was there and it would always be there.

```
attr = lighty.stat(lighty.env['physical.path'])
 if (not attr) then
 lighty.header["Location"] = "http://directto.webserver.com"  .. lighty.env["request.uri"]
 return 302
end

```

Hope this can help.

---
Tags: media, 7, cdn
---


title: Rename the taxonomy menu in drupal 7

text:
# Question
Title: Rename the taxonomy menu in drupal 7
I have taxonomy menu as the menu in my page.Here when i edit the taxonomy menu it is not getting updated in my menu.Can anyone help menu to fix this issue.

For example let say I have taxonomy menu item hello.Now i go to `structure-->taxonomy-->Home page menu--->list` links and I edited the hello to test.When I come to my home page it still showing the hello and it is not getting updated.

# Answer
> 1 votes
When you edit your vocabulary, on "Structure \> Taxonomy \> Home page menu \> Edit" there should be a "Select to rebuild the menu on submit" checkbox. This helped in my case.

Because the following warning, you should consider making a backup before doing this.

> This will delete then re-create all of the menu items. Only use this option if you are experiencing issues like missing menu items or other inconsistencies.

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


# Question
Title: referencing a field in a node in hook_node_api
I am using drupal 6. I have a simple question:

Here's a snippet of code from my hook\_node\_api function: ...

```
case 'presave':
    {
        if($node->type == 'example')
        {
            if($node->content['field_alert']['#value'] == TRUE)
            {
                //do something
                drupal_set_message('Your update will be emailed out.');
            }
        }
    }
   break;

```

I want to reference the value of a field named field\_alert inside of a node type "example" but I'm doing it properly since its not working. How do I do this?

# Answer
> 1 votes
If memory serves it should be something like this:

```
if (!empty($node->field_alert[0]['value'])) {
  //do something
  drupal_set_message('Your update will be emailed out.');
}

```

---
Tags: hooks, nodes
---


# Question
Title: How to get the node title of a refernced node
I'm using Drupal 7, and trying to work some magic from within a hook\_node\_presave() function.

I have a node reference field, and I'm trying to get the name of the referenced node rather than nid. When I trace out the field (`$node->field_my_name`) I get the following

```
Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [nid] => 23
                )

        )

)

```

I wondering if there is a way to get the title without doing a full load of the referenced node. Is there anyway I can do this with a token? Would this no be an issue if I were using entity reference rather than references?

# Answer
You could use entity\_label() function.

The function takes the entire entity as an argument, and it should already be loaded.
I would just load the node. As the other author suggested, it is very likely to be already cached in a `hook_node_presave()` call.
> 1 votes

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


title: Get the NID from url

text:
# Question
Title: Get the NID from url
> **Possible Duplicate:**
> Get a node ID from the URL

I have two content types which one referenced to another by url widget, when i click on the link the node id passing with the url.
How can i get this nid from the url?
Is there some function for that? Thanks

# Answer
If you are wanting to use the nid of the node reference field inside a node template, you could grab it as `$node->FIELDNAME[0]['nid']` (D6 anyway, add an \['und'\] or something similar in the mix for D7 :) Otherwise, a lot of other examples are given in the article @refineo references above.
> 1 votes

---
Tags: nodes
---


title: Is db_query() limited to MySQL?

text:
# Question
Title: Is db_query() limited to MySQL?
I know db\_select and Drupal's Database Abstraction Layer work across database implementations as long as there is a driver (mysql, postgresql and sqlite drivers included in core). But what about db\_query? Should I patch contributed modules to make sure they work with sqlite?

# Answer
Any function that is part of the database abstraction layer in Drupal 7 works with every database engine for which there are the necessary classes to work with that database engine.

If you look at the code of db\_query(), you will notice it is generic enough to work with every database engine.

```
function db_query($query, array $args = array(), array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';
  }

  return Database::getConnection($options['target'])->query($query, $args, $options);
}

```

This code is not different from the code executed by db\_select().

```
function db_select($table, $alias = NULL, array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';
  }
  return Database::getConnection($options['target'])->select($table, $alias, $options);
}

```

If you compare those functions with the code executed from db\_delete(), you will notice the functions are essentially wrappers around `Database::getConnection()`.

```
function db_delete($table, array $options = array()) {
  if (empty($options['target']) || $options['target'] == 'slave') {
    $options['target'] = 'default';
  }
  return Database::getConnection($options['target'])->delete($table, $options);
}

```

It is `Database::getConnection()` that, indirectly, builds the object necessary to execute the queries in the database engine, using the following code.

```
  $driver_class = 'DatabaseConnection_' . $driver;
  require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
  $new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
  $new_connection->setTarget($target);
  $new_connection->setKey($key);

```

As SQLite is supported in Drupal 7, `db_query()` doesn't need to be altered to execute optimized code for SQLite, as the code that it is optimized for that database engine is already contained in the DatabaseConnection\_sqlite.
> 4 votes

# Answer
db\_query works for all databases, see http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db\_query/7
> 0 votes

---
Tags: 7, database
---


title: Desaturate not working in image styles

text:
# Question
Title: Desaturate not working in image styles
I have an image style which has Desaturate and Scale & Crop turned on.

I call it using this:

```
<a href="<?php print image_style_url('gallery_full', $image['uri']); ?>"><img src="<?php print image_style_url('gallery_thumb_grey', $image['uri']); ?>" /></a>

```

It outputs the image resized but doesn't desaturate it. There are no errors.

Any ideas?

# Answer
> 1 votes
This is kind of a crappy answer, but the fix was to switch to using ImageMagick. I still don't know what was wrong with GD.

# Answer
> 0 votes
I found the following discussion on g.d.o to be the most helpful for my particular case of an Ubuntu 8 LTS server which comes with outdated GD libraries.

http://groups.drupal.org/node/35764

Essentially, the only way to get Drupal 7 image desaturation working, without resorting to imagemagick, is to recompile php using the `--with-gd` option.

---
Tags: 7, media
---


title: Secure Login in Drupal

text:
# Question
Title: Secure Login in Drupal
I'm designing a sensitive site and I want that login/passwd is not sent as plain text. I don't want to provide https connection or maintain a SSL certificate as it can easily be compromised on shared hosting.

For non-admin users login using openid will solve this issue but how do I do it for Admin(uid=1) ?

For admin login one way is to use a secured VPN of another country to login and once session cookie is placed I can close VPN and use my normal internet connection.

Any ideas?

Although this question isn't version specific but I need it for D6 site.

# Answer
If you're already using OpenID, then that should work, but if you dont want to add yet another module and *you have access to a server over ssh*, you can temporarily route all traffic in a tunnel through the server, which will effectively secure all internet traffic, and allow you to connect to the site and send the password "in the clear" as it were over HTTP, but the SSH tunnel would encrypt it before it left your machine.

If you happen to be on a mac, i highly recommend using Sidestep.app to facilitate quickly connecting/disconnecting from the tunnel.

http://chetansurpur.com/projects/sidestep/

For this to really work for you and not be a complete annoyance, I repeat, you need to have SSH access to a server already set up, ideally, with public key access configured.
> 2 votes

---
Tags: users
---


# Question
Title: different colors for different order statuses
Is it possible on store/orders page to use different colors for different order statuses? This feature can be handy. Or doe's someone know how to implement it? thank you

# Answer
> 1 votes
Here's a possible Drupal-only solution that can get you there. You're going to need access to your theme css file to add a class for each of your order statuses, ex something like this:

```
.order-status-pending { color: yellow; }
.order-status-closed { color: green; }
.order-status-problem { color: red; }

```

Now go to views and edit the 'orders' view that is added by Ubercart and then select the field for 'order statuses' from the Fields display section. Next, select 'Style Settings', 'customize field HTML', 'Create a CSS class' and then use the tokens to add your custom class there, ex:

```
order-status-[status]

```

You could also rewrite the output of the field using the replacement tokens to something like this:

```
<span class='order-status-[status]'>[status]</span>

```

This won't work on multiple word order statuses, but you could use jquery instead to do this kind of conditional styling, using their much more powerful selectors.

---
Tags: 6, ubercart
---


# Question
Title: Having trouble POSTing value for a select element with SimpleTest
I am trying to write a SimpleTest for a form that already exists. The form passes tests for GET, valid HTML and having the select element, which looks like this:

```
<select id="edit-buid" name="buid" class="form-select">
  <option value="1">New Business Unit</option>
</select>

```

The relevant code from my test case is:

```
$this->drupalGet('path/to/form');
$this->assertFieldByName('buid', NULL, 'form has buid field');

$edit = array(
  'buid' => 1,
);

$this->drupalPost('path/to/form', $edit, t('Save'));

```

I have tried passing the string "1" and array(1) and array("1") as well, but the test always fails with:

"Failed to set field buid to 1"

How can I make the test pass with the correct option selected?

# Answer
After talking this through, I realized that I had not created the database records necessary to fill the select element *in the test case*. So, during the test, there actually was no `<option value="1">`. The lesson is to think carefully about the entire context when writing test cases.
> 2 votes

---
Tags: forms, testing
---


# Question
Title: Keeping development database in sync with production database
Here is my process for developing, this is more of a MySQL question then Drupal.

1. Have a local dev environment. This includes a local mysql and a copy of the drupal site. all under version control.
2. When the site is ready, I dump my database and set up a production database, I then create a production instance of the site from my repository.

So the issue I am running into is a user is adding content to the production site. And I am creating database changes on the development version of my site. The two versions are now out of sync. One solution for this is every time I want to develop on my local version I dump the production's database and load it. So I am wondering how this problem is usually approached. Is there something like mysqldiff that will only load data that is not reflected in the database?? Are there any drush tools that will help with keeping drupal databases in sync?

# Answer
> 2 votes
It really depends on what you're changing in the development environment. If you're adding/removing modules, content types, custom fields, etc.. I can't think of a really good way to do this in any sort of trustworthy automated way.

Also I am SURE there must be modules for exporting Drupal content. A quick search turned this up: http://drupal.org/project/node\_export

---
Tags: 7
---


# Question
Title: How do I know what variables are available for a theme function?
I am using the Menu block module. In one template I have used `kpr($page);` to see what hooks the menu block is calling. I then created the correct function in my theme's template.php file `mytheme_menu_block_wrapper__1()`. The examples I have read suggest that this should not take any arguments.

So what I'm really interested in learning is how to debug drupal.

Is there a function that I can call that will show me all the available variables, something like `drupal_special_dump()` that would show all variables I can use? Any help would be appreciated.

# Answer
> 8 votes
The Devel module, and it's fantastic `dpm()` function, is the most widely used debug method for Drupal (at least I'm pretty sure it is).

It can be used on any variable, including arrays and objects, and will post a message to the standard message area containing a nicely structured representation of the variable. It looks something like this:

You would use it as simply as:

```
function mytheme_menu_block_wrapper__1($vars) {
  dpm($vars);
}

```

FYI I think all theme functions in Drupal 7 will receive at least one argument which will contain the data for that theme function. That argument is represented by `$vars` in the above example.

If you're looking to get hold of a list of variables that have been defined for the whole page request you might want to look at the PHP `get_defined_vars()` function instead.

# Answer
> 1 votes
For theme hooks, the variables that are available will be passed to the hook, usually named $variables. :-)

But here's a big list of all the theme hooks: http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme/7

---
Tags: 7, theming, hooks, debugging
---


# Question
Title: How to add separator option in Form API 'select' element?
Is there a way with the Form API to specify that one or more *#options* in a 'select' element should be disabled? I would like to insert a separator in my dropdown options that is not a selectable value.

# Answer
> 7 votes
If it's really a separator you're looking to add then it might make more semantic sense to use `<optgroup>`s to group your select options.

You can do this with the form API simply by wrapping each group you want in the `<select>` in an array, keyed by the title you want for the label:

```
$form['test'] = array(
  '#type' => 'select',
  '#title' => 'test',
  '#weight' => -10000,
  '#options' => array(
    'Group 1' => array(
      1 => 'Group 1 Item 1'
    ),
    'Group 2' => array(
      2 => 'Group 2 Item 1',
      3 => 'Group 2 Item 2'
    )
  )
);

```

That will produce a select list like this:

---
Tags: forms
---


# Question
Title: How to search through database of businesses/how to build the content template?
sorry in advance for the more than likely simple/beginner/waste of time question(s). Anyway, I'm working on building a business ratings site of sorts (Yes, I know, way overdone. Don't worry about it! :D). However, since I know very little programming and am completely new to Drupal (7), I don't quite know the best way to go about building the basic nodes, how to add an itemized search function to the site, or how to get the listings to show up in said search. I've done as many searches as I can think of, but I think the problem is that I don't know what I don't know, and therefore am searching the wrong things.

I guess for me those are all different ways of asking a similar question. How do I build the template node for the business page so that it can be searched for and sorted based on its characteristics. For instance, when creating the basic content type template, how would I build it so that the listing can be searched, for instance, by state?

I need to display the address of the business on its page simply because of the nature of the site. So, is there a way for a search to pick up on that, and display it in a search sorted by the state that it's in? Do I need to somehow link that field to a taxonomy term of some sort? Also, what module would be the best to use for adding that type of search to the site?

I'm not sure whether this is helpful, but the modules that I have installed so far in my journey toward building this site/solving this problem are: Views, CTools, Display Suite, and Custom Search. I'm guessing that I will be able to use custom search for the actual search function, but I haven't delved into using it yet since I haven't figured out how to build what it searches.

Sorry for what I'm sure is a silly post, and thank you in advance for any help anybody may have to offer.

# Answer
The two major approaches to adding locations in Drupal 7 are location/gmap and addressfield/geocoder. Comparing these two sets of modules in detail is the subject of a book, *Mapping with Drupal*, and is outside the scope of this post. Unfortunately, both approaches are still under heavy development and in all honesty you will likely encounter a fair number of bugs either way. At the moment, I would choose the Location approach because it has working proximity search (show me all businesses within 100 km of me).

If I were approaching this project, rather than using the built-in Drupal search, I would use the Views modules and filters (exposed filters) to allow users to search. Once you are proficient with the Views module (Node One has an excellent series of screencasts on learning Views), you will probably find it easier to work with and customize than the basic Drupal search.

A few tips on location- If you do install the location module it provides a "location directory" view by default, though it is disabled. You can enable this view and play with it; it creates an index of all your nodes that have locations attached to them. This should give you some idea about how to build location-based search in Views.

If you do use location, choose Location CCK (which will eventually be named to fields for D7), not the Node Location submodule. They are mutually exclusive and Location CCK is the direction that the next major release of the Location module will take.
> 1 votes

---
Tags: search
---


# Question
Title: Why is the block template for User Login not used on user/login page?
If I dpm() the theme\_hook\_suggestions in template\_preprocess\_block on a standard page with the user login block on it, I get block\_*user*\_login as a suggestion.

If I go to user/login (while logged out), I don't get any pertinent suggestions. It doesn't even seem to use block.tpl.php when renderedon user/login. I know it's actually rendering that block because it prints out the description I gave it.

# Answer
> 1 votes
The `user_page()` function returns the form directly (i.e. not in a block) for the user login page. As such it won't fire `template_preprocess_block` and your `dpm()` call will never run. If it wasn't called directly in this manner then the User module would inadvertently become dependent on the Block module being enabled, and this shouldn't be the case.

Also, just in case it helps: `dpm()` will only print out a message for users who have the correct permissions to view them. By default this doesn't include anonymous users.

If you want to change it (temporarily of course, anonymous users really shouldn't have access to variable printouts), go to http://mysite.com/admin/people/permissions and make sure the Anonymous User role has the "Access developer information" permission ticked.

---
Tags: 7, blocks
---


# Question
Title: Is there an easy for my authenticated users to search other authenticated users?
I would like to allow my authenticated users the option to search through other authenticated users profiles (like when you allow people to change the filters on a view of content).

I've been searching through modules and documentation for a while now and can't seem to figure out how to solve this problem.

I was hoping that maybe their would be someway to create a view of users? Is that possible? If not, how can this be achieved?

# Answer
There is a default user search. You can go to "your\_site/search/user" to try that out. You can set the permissions at "admin/people/permissions" to allow only authenticated users to use this search.
> 4 votes

---
Tags: 7, views, users, search
---


title: Using custom token in node body

text:
# Question
Title: Using custom token in node body
I am trying to minimize my workload in the future by putting recycled content into tokens, so that I only have to update the token as opposed to updating each individual node that uses the same content. I have little experience with tokens, so my question is very basic.

Example of what I want.. say I have the following on dozens of different nodes:

Item 1: $29.99

Rather than having to update each node when 'Item 1' gets a price change, I'd rather have each node just using a token for 'Item 1', so that I only have to update the token instead of all the nodes. I've installed the Custom Tokens module, but don't understand how to display my custom token in the node's content body. If I set the custom token name as "token-1", how would I display the token in the actual content? ie. \[token-1\], \[custom:token-1\] etc don't work.

Any help would be greatly appreciated!

# Answer
> 9 votes
You'll want to have the Token filter module installed and configured in your text formats to use tokens in the node body.

# Answer
> 2 votes
Try `token_replace` in `hook_nodeapi` for D6 or `hook_node_load` for D7

token\_replace

> Parameters
>
> **$text**: A string potentially containing replaceable tokens.
>
> **$data:** (optional) An array of keyed objects. For simple replacement scenarios 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.
>
> **$options: (optional) A keyed array of settings and flags to control the token replacement process. Supported options are:**
>
> language: A language object to be used when generating locale-sensitive tokens. callback: A callback function that will be used to post-process the array of token replacements after they are generated. For example, a module using tokens in a text-only email might provide a callback to strip HTML entities from token values before they are inserted into the final text. clear: A boolean flag indicating that tokens should be removed from the final text if no replacement value can be generated. sanitize: A boolean flag indicating that tokens should be sanitized for display to a web browser. Defaults to TRUE. Developers who set this option to FALSE assume responsibility for running filter\_xss(), check\_plain() or other appropriate scrubbing functions before displaying data to users.

hook\_nodeapi

hook\_node\_load

---
Tags: nodes, tokens
---


title: I need a module like Pageflip

text:
# Question
Title: I need a module like Pageflip
I need a stable Drupal module version like Pageflip. Can any one suggest the module which I am searching?

The existing Pageflip module is still a beta version; I need a module that has a stable release.

# Answer
> 3 votes
As kantu's comment suggests, there is no formal "approval" system for modules on drupal.org. Instead, module maintainers decide when to release their modules and what version number to assign them.

As pageflip is a highly specialized module, I doubt that there is another module that has similar functionality (a quick search returned none). However, since it is beta 5, it is probably stable enough to use in production, as Countzero pointed out. The alternative would be to write a module yourself, but since the pageflip module is already far along in its development it would probably be best for everyone if you would extend and contribute back to the pageflip module (assuming you were going to write your own module).

How do you really know whether the module is ready for production? First, look at the list of open reported bugs. In this case there are only 3 for the 6.x series, so it shouldn't take you very long. If these bugs don't affect you, the module is probably safe to install.

---
Tags: 6
---


# Question
Title: What Drupal development environments are available besides XAMPP?
I am using XAMPP for almost 2 years. Recently i found some articles that suggests that XAMPP is loading some extra libraries/dlls which is not required for a Drupal development environment. Is there any other options that i can adopt for Drupal development besides XAMPP?

I found nginx.

# Answer
> 4 votes
I think it's best if your local development environment matches the environment of the servers your site(s) are actually hosted on as much as possible. I've used XAMPP with Drupal and I haven't ever had problems relating to extra libraries being loaded.

That said, if you're looking for a Drupal-optimized solution, Acquia, the company run by the founder of Drupal, provides a Dev Desktop which allows you to set up and host Drupal quickly on Windows or OS X. This works similarly to XAMPP but it's easier to set up. (Warning: Acquia's Drupal distribution is slightly different than the standard Drupal from drupal.org. However, you can easily replace the Acquia Drupal distribution with the one from drupal.org if you want.)

For a different approach, you can try Drupal Quickstart, which is a Virtualbox VM that includes an install of Ubuntu Linux pre-configured with (as per the project page):

> * Support for Drupal 7 and Drupal 6
> * Ubuntu Linux, Apache, MySQL, APC, XDebug, IMAP, UploadProgress
> * Firefox (with developer plugins) and Chrome
> * Drush, drush make, and custom drush commands
> * Install scripts for: Apache Solr, Aegir, Hudson, and Oracle
> * Netbeans and Eclipse, configured with XDebug
> * XHProf and Webgrind profilers. Emails logged as files
> * cvs, subversion, git, bazaar

This is the "whole development environment in a box" solution.

---
Tags: 7
---


# Question
Title: I can't change the currency to € for the Drupal Commerce module
I can't change the currency to €.

In admin/commerce/config/currency I set the currency to €. (see capture 1)

But the products still show the $ simbol.(see capture 2)

Is this a bug?

**As StryKaizer commented I need to change it as well in every product. My problem is that I have many products. Is there any way to do it in the database through a query?**

# Answer
I've experienced this bug myself in an older version of Commerce. Updating to the latest stable version of Commerce fixed the issue.

Also make sure to change the currency on your product(s) too, as changing the global currency won't change it on any already defined products.
> 3 votes

---
Tags: commerce
---


# Question
Title: Drupal node templates which apply to more than one content type. Possible?
I've started looking at content type specific `node.tpl.php` files. However, say I have two content types, and wish both to be displayed in a similar manner, but not apply this to every content type (at the level of `node.tpl.php`).

It seems a bit of an overkill to have two identical files for `node--contenttype_1.tpl.php` and `node--contenttype_2.tpl.php` which are the same? Is there a way to have a multi-content-type template for this?

In case you're wondering the reason for having two different content types in the first place, one is a simpler version of the other, has different URL generation rules (via pathauto), and fewer fields associated with it.

# Answer
> 8 votes
Implement a preprocess function that adds a template suggestion.

Assuming your theme is called `EXAMPLETHEME`, your content types are `content_type_1` and `content_type_2` and the template file is called `node--example.tpl_php`, add the following function to the file `template.php` of your theme:

```
function EXAMPLETHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'content_type_1' || $node->type == 'content_type_2') {
    $variables['theme_hook_suggestion'] = 'node__example';
  }
}

```

# Answer
> 0 votes
An "evil" suggestion would be to create a symlink `node--contenttype_2.tpl.php` which points to `node--contenttype_1.tpl.php`. I have actually used stuff like this on production sites.

---
Tags: 7, nodes, theming
---


title: Is it possible to have "pseudo-nodes"?

text:
# Question
Title: Is it possible to have "pseudo-nodes"?
Is there a way to expose content from other databases to Drupal so Drupal sees them like nodes? Importantly, this should work without making actual node entries in the Drupal database.

This would mean writing a module which specifies how to translate my proprietary content into Drupal node format, so one could write theming functions for that content, or use the Views module on it, etc.

Currently my module just displays the content directly on its own, without bothering to provide seamless Drupal integration into Views.

# Answer
> 2 votes
It really depends on what you are trying to accomplish.

If you need *any* Drupal feature, like commenting and tagging, or want to integrate with modules like Fivestar or Flag, then you need a node (or other entity). If you want to get into the theming system, then I think you have no real choice. The way I normally accomplish this is to have a hook that runs `hook_node_load`, does a call out to the remote system (either REST or direct DB), and then builds up a data structure and sticks it somewhere in `$node`. You then have some preprocess functions to make the data available to the node templates, or you have a `hook_node_view` to get the data into the `$node->content` render array. The next time I need to do this I will likely try to use the Field Storage API with content types defined by `hook_node_info`.

With this approach, the only thing the node is really used for is to have a `$nid` / `$vid` pair available to the rest of Drupal for other modules to work. The content type that you are using typically only needs on field in it to store the primary key in the remote system. I usually also copy over the title to the node to make it easier to identify in the admin UI.

Though all of this may seem hard, it is actually pretty straightforward and mostly easy to implement if you are familiar with the API.

Just remember that what you need to do *now* may not be what you want to do in the *future*. Preparing for this by having true nodes available may make better sense in the long run.

---
Tags: nodes
---


title: Display some content on selected pages

text:
# Question
Title: Display some content on selected pages
My project runs on Drupal 6, and I'm using Views.

I have a main menu with two submenus (menu -\> sub1 -\> sub2).

This image shows what it looks like on my "edit panel."

The box with an orange border is the second submenu, and the one with a black border contains the item content assigned to this second submenu.

All the items from all submenus assigned to first submenu (main menu -\> sub1 -\> sub2.1, sub2.2, sub2.3 ...) are showing up already in the first submenu. (Th first submenu is a drop-down in the main menu; I don't want to have all submenus in the main menu, but just the first one.)

I want to hide them from there and display only the item that belongs to ie. sub2.1 or sub2.3. When I click sub1, I see all items from all sub2; when I click sub2.1, I see the correct items assigned to this submenu.

# Answer
> 1 votes
To understand what may be going wrong in your attempt it would help to clarify a few things about which modules do what.

* Your menus are handled by either core menu or another of the menu modules that build upon it. They display links and and any selection reroutes the browser to a new URL.
* Views is a User interface to query the database in which all of your content is held. If you select the settings tab in the main views page you can set the actual SQL query to be displayed in the preview area. This is helpful in understanding what is being searched for in your settings, although you will need some understanding of queries to make sense of it. A view is called either by using the defined path in the URL or by placing the view in a panel (Which you have done here).
* Panels is primarily a module to handle the display of content. However, it works very closely with Page Manager module.
* Page Manager intercepts URL requests and acts upon them in accordance with rules you establish for selection and contexts. Panels and Page Manager collaborate together and switch between themselves regardless of where you start in the UI.

When you select a menu item it is requesting that the browser go to a specified URL (menu). That URL request should be requesting the panel page (panels and page manager) which in turn is requesting the view that you have placed in it (Views). For your example, once the request is made menus, panels and page manager are done. Your real issue is with the views, so you must focus on the view module and your definition.

In order to help the view distinguish between various levels of content you can add a field to the content type that defines its level. You can then expose that field to views by selecting it as a filter and setting the value you want for that article. You can create multiple view pages within the View definition to address different filter settings needed for placement in each of your panel regions. By categorizing the menu-selection/articles and providing separate view pages (within the same View definition) you can refine your control of the displayed content.

You can also limit the number of articles displayed by a view by selecting the options under pager in the view definition page and telling how many pages/articles to display.

You can learn more about Views at nodeone.se

---
Tags: views, 6, panels
---


# Question
Title: Show all users except profile being viewed (views, panel node)
I've got a view of type "users". I have it filtered to a certain "role". There are only 12 ppl in this role (it is for a calendar, and someone is sponsored each month). When viewing a users profile I want to show a list of the other 11 below that user. I currently have it listing all 12, I cant figure out a filter to exclude the current profile being viewed.

I have to be missing something easy

# Answer
the last checkbox on the settings of the contextual filter - exclude :) (under more)
> 1 votes

---
Tags: 7, views, panels
---


title: How should I use drupal_lookup_path()?

text:
# Question
Title: How should I use drupal_lookup_path()?
I want to get the node ID to load the nid fields.
How can I get the node ID from the current URL using this function?

# Answer
> 3 votes
That's not what `drupal_get_path()` is for; it's for getting the internal router path for a URL given a path alias, and vice versa. It also allows you to wipe aliases, but it's not a good way to try to get the current page's node ID.

What you're looking for is the `arg()` function, which simply splits the current router path (the value contained in `$_GET['q']`, which for a node page will be, for example, `node/1`).

```
// With a router path of node/123
$entity_type = arg(0); // $entity_type is equal to 'node'

$nid = arg(1); // $nid is equal to 123

```

# Answer
> 2 votes
As Clive said, that is not the purpose of `drupal_lookup_path()`. If you want to get the node ID associated with a path, you just use code similar to the following one.

```
if ($node = menu_get_object('node', 1, $path)) {
  // $node->nid is the node ID.
}

```

That code is for the case you are interested in a specific path, and not the current one. If you are looking for the node associate to the current path, then the code can be simply written as the following one.

```
if ($node = menu_get_object()) {
  // $node->nid is the node ID.
}

```

`"node"`, and `1` are the default values for the first two parameters, and you can avoid passing any parameters if you are interested to get the node object associated with the current path.

Consider that:

* The function returns `FALSE` if the current path (or the path passed to the function) doesn't have any node associated, for example because the path is user/1.
* If there is a node associated with the path, the node object is the one returned from node\_load(), which then uses entity\_load() to get it.
* Differently from the approach followed using `arg()`, `menu_get_object()` always return the right node object. Suppose the site have enabled node revisions; if you would use the following code, you would always get the same node object, even if the path is (for example) node/8/revisions/14.

```
if (arg(0) == 'node') {
  $node = node_load(arg(1));
}

```

This is not a case limited to node revisions being enabled. For example, there could be a module that defines a menu callback for paths like node/8/linked/12, and that would show the node page for the node with the ID equal to, e.g., 23. Using the code calling `arg()` I shown, you would load the node that is not associated with the current page, which is not what happens with `menu_get_object()`.

Once you have the node object, you can access to the fields loaded with it, or you can pass the node object to any entity function, to get more information about the node.

---
Tags: nodes
---


title: Redirecting based on parts of URL

text:
# Question
Title: Redirecting based on parts of URL
Is there a module for Drupal that would allow me to perform redirects based on parts of the URL?

For example, if the URL contains this-string-to-redirect, e.g. example.com/this-string-to-redirect/node/content, then redirect to another path.

# Answer
If you want to do this yourself, quick and dirty, it would be something like this:

```
function yourmodule_init() {

  $foo=drupal_get_path_alias($_GET['q']);
  $bar=explode('/',$foo);

  if ($bar[0]=='this-string-to-redirect') {
    $bar[0]='redirect-me-here';
  }

  $baz=implode('/',$bar);

  drupal_goto($baz);

}

```

You might also want/need to throw in a weight of -1 to make sure your module runs early by putting:

```
function yourmodule_install() {
  db_query('UPDATE {system} SET weight = -1 WHERE name = "yourmodule"');
}

```

in yourmodule.install but a quick look just now shows globalredirect's weight at the default of 0 so this may be unneeded.
> 3 votes

# Answer
If the Path Redirect module (whose Drupal 7 version is the Redirect module) doesn't help you, it might be worth taking a look at Global Redirect as well.

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

> ### Global Redirect
>
> GlobalRedirect is a simple module which…
>
> * Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
> * Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
> * Checks if the current URL is the same as the site\_frontpage and redirects to the frontpage if there is a match.
> * Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
> * Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
> * Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.
> * Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect\_admin module. In Drupal 6, the settings page is bundled into the module.
> 0 votes

---
Tags: 6, uri, redirection
---


# Question
Title: Can I use Panels context keywords in PHP functions?
I'm using the privatemsg module and I would like to display the number of unread messages a user has on his/her profile page. I attempted to use %user, which is the context keyword for the user currently being viewed.

According to the privatemsg API documentation, the function for this is privatemsg\_unread\_count(). I tried calling the function like this:

`privatemsg_unread_count("%user");`

But I get an error: `Notice: Trying to get property of non-object in privatemsg_unread_count()`

The function takes an account argument, which as far as I can tell (I'm not very skilled in PHP) is an array that stores the values for a given user. Am I going the wrong way with trying to use the context keywords?

# Answer
> 0 votes
Yes, it is possible to use Panels context keywords in PHP functions.

My mistake was that %user does not return a user object. However, context keywords can be used like this:

`$account = user_load(%user:uid);`

Here, the context keyword `%user:uid` will successfully evaluate to the ID of the user currently being viewed.

# Answer
> 0 votes
Just call the function without any argument and it will return the unread message count for the current user.

---
Tags: 7, panels
---


# Question
Title: How to make exposed filter show results on another page?
> **Possible Duplicate:**
> Expose Views filters both in a block but in the actual view also

I have a Views-based page (Page A) with exposed autocomplete filter. I want that filter form to appear in a block on Page B, but the search results should be displayed on Page A.

Unfortunately I have to search open value fields (node title), which eliminates Better Exposed Filters from play.

Does anyone know of a ready module that could work for me?

# Answer
In Advanced section : EXPOSED FORM Exposed form in block:No -\> set it to yes
> 2 votes

# Answer
I'm not quite this is what you are looking for, but, check out this page:

http://timeline.med.utoronto.ca/page/historical-or-individual-artifacts

If you want that to happen (filters are exposed), results shown in block in the content section, you simply have to turn on Ajax in your View Advanced settings. If it is off, the View will load the results on a separate page.
> 0 votes

---
Tags: blocks, views
---


# Question
Title: Media: Specify display used for File field on content type's Manage Display tab
I'm using the Media module (7.x-1.0) to support images and videos. According to the latest best practices I've been able to find, you're supposed to use a File field on your content type to display the media. For example, add a field called "Media" of type File to the Article content type, then use the "Media file selector" widget.

That part is fine, but I'm struggling to actually display the attached file. On the "Manage Display" field for the Article content type I only have four options (shown below). None of these map to any of the display modes defined for File entities (via the File entity module included in Media 7.x-1.x).

I've looked through the issue queue for Media and found some similar questions, with no solutions. There appears to have been a "Media" formatter available for the now deprecated "Media Asset" field type which allowed you to choose which File display mode should be used. This isn't available for the File field type, which is what Media recommends you use.

Has anyone been able to successfully choose a File display mode for a File field using the Media module?

# Answer
Please see http://drupal.org/node/1390878
> 1 votes

---
Tags: files, media
---


# Question
Title: Drupal 6 administration menu like the one on Drupal 7
I build a lot of sites, mostly on Drupal 7, so when I have to use Drupal 6 I am totally lost on the admin options, (even using the administrative menu bar).

Since I can't find any module for this issue, I am wondering if I should give it a try to build a module myself to rename and rearrange the admin menu items, but I am not sure, if this is even possible or if that will cause any path issues in modules later.

# Answer
Why not building your own menu with the most used functions and show it only for you? I do this all the time for D6 and D7.
> 0 votes

---
Tags: 6, routes
---


# Question
Title: How to set a default image on a Drupal 7 Media field
I have a non-required `field_thumbnail` that is of type "Multimedia asset", and the widget type is "Media file selector". However on the field's settings page there is no option to specify a *default* value. I've also perused the Administrative section seeking configuration in the Image styles, and File styles, but neither permit a default image to be used.

What would be the recommended way to get a default image, when a user does not select any media object for the given node?

# Answer
> 3 votes
Whenever I need to do this I just use a plain old Image field and use the Media File Selector as the widget. That way you can specify a default image for the field and still use the nice popup media browser.

So far I haven't found any benefits to using a Multimedia Asset field type over an Image field type in this situation, but that's not to say there aren't any or won't be any in the future.

**EDIT**

At the code level the following might help you get started:

```
// Implement hook_field_info_alter to add a setting for the multimedia field type
function MYMODULE_field_info_alter(&$info) {
  $info['media']['settings'] = array(
    'default_asset' => NULL
  );
}

// Implement hook_field_settings_form on behalf of the media module
function media_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];
  $form['default_asset'] = array(
    '#type' => 'media',
    '#title' => 'Default Multimedia Asset',
    '#description' => 'The default asset to use when none is selected',
    '#default_value' => $settings['default_asset']
  );

  return $form;
}

```

That will add a default multimedia asset picker to the field settings. Then you just need to work out how to inject that default value into the field display when it's otherwise empty. I would guess at the use of something like `hook_field_prepare_view()` for this.

Note that there's no way to restrict the *type* of the default multimedia asset as those types are set at a per instance level, not at the field level. If you want to do it at the instance level much of the same code above will help but you'll have to extend it further to restrict the type of media based on the checkboxes on the instance form.

---
Tags: media
---


# Question
Title: How to change "Your name" label in comments form?
I have a blog with comments and I need to change the "Your name" field to something different and make it a required field.

Can I do this from `hook_form_comment_form_alter()` hook in `template.php` or in a comments template?

# Answer
You can do it in a `hook_form_alter()` function like you suggest:

```
function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $label = t('New label');
  if (isset($form['author']['_author'])) {
    $form['author']['_author']['#title'] = $label;
  }
  else {
    $form['author']['name']['#title'] = $label;
  }
}

```
> 8 votes

---
Tags: 7, forms, comments
---


# Question
Title: setting the url to a function in a custom module
I am trying to make a link in a view which, when clicked on, will call a function in a custom module to make a database call. I have made a link by making a Global:custom text field (because thats the way it seemed I had to do it from some posts online), set it to a path accompanied with some arguments. I made a custom module used the hook\_menu:

```
function example_menu() {
$items = array();
$items['path_name'] = array(
'title' => t('Example'),
'page callback' => 'my_callback',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}

```

where function my\_callback does a database call.

When I click on the link I just get a blank page with nothing on it. Which pieces am I missing here? The first thing I thought was that I needed to route the link to a page (hence the name 'page\_callback') but how would I do this? All I really want done is a database call, I don't mind if you stay on the same page.

EDIT: Additionally, what I have found is that on the content management page there ares some errors on top which tell me that I'm missing arguments 1 through 4 (there were four arguments), which definitly can be part of the problem. The function starts off:

```
function example_my_callback($staff_action, $first_name, $last_name, $email)

```

and the url for the link was path\_name?staff\_action=\[varible name found in views\]...etc Is there any issue here?

# Answer
> 1 votes
The page callback function generates the html that is shown on the page when you surf over to it, so, you would do something like this in it:

```
function my_callback() {

  // do your db stuff

  if ( // success ) {
    return '<div>Success</div>';
  else {
    return '<div>Failure</div>';
  }

}

```

And a link to it is just like any other html link, it goes to a page. If you want to stay on the current page, you will need to do it via ajax/ahah or something similarly fun with javascript/jquery etc.

# Answer
> 1 votes
The page callback must be the name of the function that will return the data from database

You must create a function like this :

```
function my_callback(){
// here you will connect and pull up data from the database
return $your_data;
}

```

Also don't forget to clear the cache and read about the database API here

---
Tags: 7, routes
---


title: PHP code does not work

text:
# Question
Title: PHP code does not work
I'm using Drupal 7.
I wrote the following code in a token field, but when I refresh the node page, it doesn't show anything.

```
if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid);
  $s = $node->field_name['und']['0']['value'];
  echo $s;
}

```

Can you advise me what I should do?

# Answer
Try removing the quotes in `['0']` in the following line.

```
$s = $node->field_name['und']['0']['value'];

```
> 3 votes

# Answer
If you don't have a debugger installed (which makes everything very nice. Both xDebug and zend play nicely with Eclipse, but I've found only xdebug works well with neabeans) then I would add in some echoing statements throughout your code. For example, I would write:

```
print('Before If');
if (arg(0) == 'node') {
  print('Inside If');
  $nid = arg(1);
  print("nid is $nid");
  $node = node_load($nid);
  print("Loaded node.  node is $node");
  print('node->field_name is ' . print_r($node->field_name);
  $s = $node->field_name['und']['0']['value'];
  echo $s;
}
print('After If');

```

And see what the result is. From what you've given, it's impossible to diagnose the problem, but I suspect that your array access isn't right. The print statement above should let you see what is going on.

Another approach is to try commenting out the entirety of your code, seeing if it works, then adding lines in one at a time until the white screen comes back. Then you know where the problem is. If you do that WITH the print statements I've added you should have a really clear idea of what's happening.

Also, try to have a look at your apache error file. Often php errors are recorded there. As to where it is, it really depends on your system's configuration, but you can google for some common places for your operating system, or ask whomever set up your apache install.

Without knowing much, I would assume that your array is the problem. Try commenting that out first.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Why are my radio buttons not displaying?
I'm working on enhancing a search form on a site I inherited. I'm trying to add a radio button set to allow the user to narrow potential search results, but I cannot for the life of me get the radio buttons to display. The label displays, but the buttons themselves do not.

Here's the function in template.php:

```
function ismiv3point1_search_block_form($form) {
    $form['search_block_form']['#title'] = '';
    $form['search_block_form']['#value'] = 'Search mysite.org';

    $form['submit']['#type'] = 'markup';
    $form['submit']['#value'] = '<input type="image" name="submit" value="Search the Site" src="/icons/search.png" alt="Search the Site" />';
    $form['submit']['#weight'] = 2;

    // this is the new field I'm trying to add
    $form['image_switch'] = array(
        '#type' => 'radios',
        '#title' => t('Image Switch Radios'),
        '#prefix' => '<br /><span style="color:#fff">',
        '#suffix'   => '</span>',
        '#weight' => '3',
        '#options' => array(
            1 => t('Images'),
            2 => t('All'),
        ),
        '#default_value' => 1
    );

    return '
    <div id="search-box" style="margin-top: 10px; margin-bottom: 0px;">'.drupal_render($form).'
        <div id="search-loading"></div>
        <div id="current-type"><a href="#" class="date">Sort by newest first</a></div>
        <ul class="content-types">
            <li><a href="#" class="date">Sort by newest first</a></li>
            <li><a href="#" class="relevance">Sort by relevance</a></li>
        </ul>
    </div>';
}

```

Here's the rendered source:

```
<form action="/"  accept-charset="UTF-8" method="post" id="search-block-form">
    <div id="search-box" style="margin-top: 10px; margin-bottom: 0px;">
   <div class="form-item form-text" id="edit-search-block-form-1-wrapper">
      <input type="text" maxlength="128" name="search_block_form" id="edit-search-block-form-1" size="15" value="Search mysite.org" title="Enter the terms you wish to search for." class="form-text" />
   </div>

   <input type="image" name="submit" value="Search the Site" src="/icons/search.png" alt="Search the Site" />
   <input type="hidden" name="form_build_id" id="form-17ad7cfea143f9acf10cca6602a02df0" value="form-17ad7cfea143f9acf10cca6602a02df0"  />
   <input type="hidden" name="form_token" id="edit-search-block-form-form-token" value="65a199ea9da3f7a52ed4c2693012997b"  />
   <input type="hidden" name="form_id" id="edit-search-block-form" value="search_block_form"  />

   <br />
   <span style="color:#fff"> <label>Image Switch Radios</label>
     <div class="form-radios"></div>
   </span>
        <div id="search-loading"></div>
        <div id="current-type"><a href="#" class="date">Sort by newest first</a></div>
        <ul class="content-types">
            <li><a href="#" class="date">Sort by newest first</a></li>
            <li><a href="#" class="relevance">Sort by relevance</a></li>
        </ul>
    </div>
</form>

```

Any ideas? Is it because the field is being added after the submit? The reason for that is because the submit is a graphic (the magnifying glass) at the end of the search box; we want the radio buttons to be positioned below that.

# Answer
> 2 votes
Form builder functions must return a form array, not a string, otherwise they won't work with `drupal_get_form()`. If you need to add markup before and after the form you you should use the `#prefix` and `#suffix` properties, or do it outside of the form function altogether.

Also the function signature for Drupal 6 should not contain the `$form` variable as an argument, but the `$form_state` variable instead. And you're currently setting the value (text) of the submit button to the HTML representation of a an `<input>` field which will never do what you want.

Try using code like this instead:

```
function ismiv3point1_search_block_form($form_state) {
  $form['search_block_form']['#title'] = '';
  $form['search_block_form']['#value'] = 'Search mysite.org';

  $form['submit']['#type'] = 'markup';
  $form['submit']['#value'] = 'Search the Site';
  $form['submit']['#weight'] = 2;

  // this is the new field I'm trying to add
  $form['image_switch'] = array(
      '#type' => 'radios',
      '#title' => t('Image Switch Radios'),
      '#prefix' => '<br /><span style="color:#fff">',
      '#suffix'   => '</span>',
      '#weight' => '3',
      '#options' => array(
          1 => t('Images'),
          2 => t('All'),
      ),
      '#default_value' => 1
  );

  $form['#prefix'] = '<div id="search-box" style="margin-top: 10px; margin-bottom: 0px;">';
  $form['#suffix'] = '
      <div id="search-loading"></div>
      <div id="current-type"><a href="#" class="date">Sort by newest first</a></div>
      <ul class="content-types">
          <li><a href="#" class="date">Sort by newest first</a></li>
          <li><a href="#" class="relevance">Sort by relevance</a></li>
      </ul>
  </div>';

  return $form;
}

```

**EDIT**

Just a bit of extra info on how to do this with a form alter hook:

```
function ismiv3point1_form_search_form_alter(&$form, &$form_state, $form_id) {
  $form['image_switch'] = array(
    '#type' => 'radios',
    '#title' => t('Image Switch Radios'),
    '#prefix' => '<br /><span style="color:#fff">',
    '#suffix'   => '</span>',
    '#weight' => '3',
    '#options' => array(
        1 => t('Images'),
        2 => t('All'),
    ),
    '#default_value' => 1
  );
}

```

---
Tags: 6, forms
---


# Question
Title: How do I find (or create) a File Template override in Panels 3?
So I'm using Panels 3 and Drupal 7 and it makes it damn easy to override the default templates for a taxonomy term template, a node template, even the front page template. However, I don't see anything on the default panel page admin list that allows me to override the default FILE template. When I try to Add a New Page and use the file/%file path, the system forbids it, as this URL structure already exists. How do I harness the power of Panels for other page templates that the Panels module does not offer an override out-of-the-box?

# Answer
As Adam Friedman points out, there is Page manager existing pages, which can do part of what "real" Page manager support can do, but it will not have the same capabilities as say the node/%node template has.

There are two issues that work on "full" support for this. First, and Second.
> 0 votes

---
Tags: 7, theming, panels, files
---


# Question
Title: What is the best way to show custom field information in node.tpl.php in Drupal 7
Hi I want to show in node.tpl.php this information about a custom filefield : File name , File type , file weight and link to download

# Answer
Something like this might demonstrate the fields available

```
<?php
$file = $node->field_yourfieldname[ $node->language ][0];
$mime = $file['filemime'];
$size = round($file['filesize'] / 1024 / 1024,1); // in MB
$description = $file['description']; // optional
$filename = $file['filename'];
$link = file_create_url($file['uri']);
?>

```

Hmmm, if $node's not available try something like this at the start

```
$file = $content['field_yourfieldname']['und'][0];

```
> 1 votes

---
Tags: 7, theming
---


title: Alt attribute inserted as empty

text:
# Question
Title: Alt attribute inserted as empty
When coding my formatter, I give user an option to provide alt, title and classes attributes for an image. All render beautifully, except for the alt title, which is output as flag-type, empty "alt" attribute (meaning: no equal sign or quotes), regardless of what I try to insert there.

Could the Media module be the reason - such as overriding the alt value with some hooks? If not, any ideas on what could be causing that?

# Answer
> 1 votes
Media module is almost certainly the reason.

There are patches in both http://drupal.org/node/1307054 and http://drupal.org/node/1343022 that you may find useful.

---
Tags: media, entities
---


# Question
Title: How to link to last comment on a node page?
I have some nodes with lots of comments that use a pager. I want to link from the top of the node page to the last comment.

Is there a simpler way than building the link like this (source):

1. Get number of (published) comments for a certain node;
2. Get number of comments per page (it can differ from on content type to another);
3. 1+2 = number of pages;
4. Get cid of the last comment;
5. Create a link like /node/\[nid\]?page=\[page\]#comment-\[cid\]

# Answer
I don't think there's a simpler way than that, but you can combine two of those steps into one so you at least only need to make a single database call:

```
function node_last_comment_link($node, $link_text) {
  // Get the num active comments and most recent comment id
  $data = db_query('SELECT MAX(cid) AS cid, COUNT(cid) AS cnt FROM {comment} WHERE nid = :nid AND status = 1', array(':nid' => $node->nid))->fetchObject();

  // No comments, no link
  if ($data->cnt == 0) {
    return FALSE;
  }

  // Get the num comments per page
  $var_name = 'comment_default_per_page_' . $node->type;
  $sensible_default = 50;
  $num_per_page = variable_get($var_name, $sensible_default);
  $page_num = floor($data->cnt / $num_per_page);

  //Build and return a URL
  $query = array();

  // No point adding ?page=0
  if ($page_num > 0) {
    $query['page'] = $page_num;
  }

  $fragment = 'comment-' . $data->cid;
  return l($link_text, 'node/' . $node->nid, array('query' => $query, 'fragment' => $fragment));
}

```

I've given that a quick test and it seems to work but it might need a bit of massaging, especially if you have threading turned on :)
> 2 votes

---
Tags: comments
---


title: Where should hooks go? Only in modules?

text:
# Question
Title: Where should hooks go? Only in modules?
I need to use 1 hook from webforms. Where does this belong? Do I have to make a custom module just to implement 1 hook or is there a more appropriate place?

# Answer
> 2 votes
A custom module is the most appropriate, probably only, place for your hook(s).

Most hooks only get run for modules; there are exceptions such as `hook_form_alter()`, `hook_theme()` etc. which are also called for themes, but generally speaking you'll need to write a custom module for any hooks you want to implement.

In case you're not familiar with building modules take a look at the Module Developer's Guide.

---
Tags: 7, hooks
---


title: How to theme 3rd party modules?

text:
# Question
Title: How to theme 3rd party modules?
I've added the "rate" module to my project. I've added multiple axes to rate but they display below my node content. How would I be able to style this? I know how to create a custom .tpl file for my content type but the module adds code AFTER my template. How I can fix this?

# Answer
Best answer on how to theme 3rd party modules is always to check their local documentation first, as most of the top-tier modules have very specific hooks, documentation, guidance for how you can theme their results. In the case of the Rate module, check the README.txt file for some guidance on what theme variables are able to be used in your node templates.

It looks like the best answer would then be to make a copy of the rate template into your theme folder and add your styling there:

```
* rate-widget.tpl.php
  This is the default template for all custom widgets.
* rate-widget--NAME.tpl.php
  This is a widget specific template. Use the machine name for NAME. Replace
  underscores by dashes in this name. This template is only available for custom
  widgets.

```

This does depend on exactly what it is your trying to theme in the emotion widget.
> 0 votes

---
Tags: theming, entities
---


# Question
Title: Dynamic Content Type? (field appears based on previous taxonomy choice)
I want to show/hide a field based on a taxonomy choice (in the content admin side of things).

Though having this field attached to every item of this content type does add overhead; I suspect it contributes to the easiest solution for a dynamic field.

I like the idea of dynamic fields, where only certain instances of an entity would have/need them, however, this seems like it could be quite an undertaking. (or my Drupal imagination is lacking today)

# Answer
Try out the Conditional Fields module.

> Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.
>
> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: How to add an icon before (or after) the node title if a field is filled?
I'm a newbie in Drupal and I want to add an icon before (or after) the node title, if the node have a 'field\_fav' filled. I know it can be done using preprocess functions, but I don't know how to append the title's with the class I desired. Any how to?

Found this : Optionally add image/icon after node title based on boolean content type field? but it only for boolean type value.

# Answer
I found your answer on drupal.org.

```
function mytheme_preprocess_page(&$variables) {
  $titleFile = 'myicon.png';
  $titleImage = base_path() . path_to_theme() . "/images/titles/" . $titleFile;

  $newTitle = $variables['title'].' <img alt="' . $variables['title'] .'" src="' . $titleImage.'" />';
  $variables['title'] = $newTitle;
}

```
> 1 votes

# Answer
This is my solution. Note that I am using an Omega sub theme.

```
function fourlegged_omega_alpha_preprocess_page(&$variables) {
  if (isset($variables['node']->type) && $variables['node']->type == 'entry') {
    if(!empty($variables['node']->field_entry_fav)) {
      $titleFile = 'ic-favourite.png';
      $titleImage = base_path() . "sites/all/themes/fourlegged_omega/images/" . $titleFile;

      $newTitle = $variables['node']->title . '<i class="icon-love" /></i>';
      $variables['title'] = $newTitle;
    }
  }
}

```
> 1 votes

---
Tags: 7, nodes, theming
---


# Question
Title: How do I rename Company field and remove Address2 field in a multiple value field in Addressfield module
I was able to remove the Address field with hook alter when it's single value field but don't know how to do it when it's a multiple value field. Same with renaming the fields. Thanks.

# Answer
> 1 votes
There's a patch for this in the Addressfield issues queue but it's still under discussion and doesn't work with the latest dev. You could look at the code in the patch though; it may provide you with insight on how to do what you want.

---
Tags: 7, entities
---


title: Adding Calendar page to another page?

text:
# Question
Title: Adding Calendar page to another page?
I am using the Calendar module. I was asked if it was possible to take the calendar page and put it inside of another. I'm not so sure about this. How would I add this to be inside the Content region of the other page? I see how it is possible to add the Calendar block to the Content region of the page but that is not what these people want...they want the full Calendar view inside of another page! Any ideas how I would go about doing this?

This is the Calendar module installed in Drupal 6.

# Answer
> 0 votes
If I am understanding you correctly, all you should need to do is go into the View UI and click on the clone link of the existing calendar view and then enter the new path in the page display and appropriate date field to use.

ADDITION:

based upon your comment below, you could set a variable in a preprocess hook to the output of this view, eg:

```
$vars['cal']=views_embed_view('calendar','calendar_1');

```

and then you would have $cal inside your template to use however you wanted. If you needed this information inside of a node, eg in a text field that would be displayed between those paragraphs of other text, you could probably hook into nodeapi() and set it there on display of the node. If you need it embeddable inside a field amongst other text, that gets trickier, but doable with a custom filter of your own (or http://drupal.org/project/customfilter might be able to do it with their php filter but I've not used it personally) but then you'd have something along the lines of \[calendar\] that your users could have inside of a text field that would be transformed into the calendar view output on view.

Regardless of any of the above, I have no idea what CSS style issues you would have to fiddle with, if any, or what to do with the previous and next links of the calendar and if they would also work or not as expected on this new page.

---
Tags: 7, datetime
---