# Question
Title: Modify node in hook_node_view() for Drupal 7
I'm trying to modify the array of content, and add an extra link.

* I don't want to use the Link module; this link is going to be generated with other fields, it's something like Computed Field module (which is in developing stage for Drupal 7, and I'd rather not use it).
* I don't want to just add HTML/PHP to node.tpl.php. I want this to be nice solution.

I've been trying with adding new field to `$node->content`. I managed to copy another field and display it once again. I was able to change label of that field, but not the link itself.

Does anyone have any idea on how to proceed?

# Answer
You can do this by implementing hook\_node\_view.

For example:

```
function my_module_node_view($node, $view_mode, $langcode) {
  switch ($node->type) {
    case 'my_node_type':
      $node->content['extra_link'] = array(
          '#weight' => 10,
          '#theme' => 'link',
          '#path' => 'path_to_content',
          '#text' => t('An extra link'),
          '#options' => array(
              'attributes' => array(),
              'html' => FALSE
          ),
      );
      break;
  }
}

```
> 9 votes

# Answer
Whisky's answer will work most of the time, but didn't work if you're trying to **add query arguments** to the end of the URL. In my case, I'm prepopulating an Entity Reference field which needs a URL that looks like this:

```
node/add/er-engagement?field_er_cal_entity_reference=19

```

Whiskey's answer doesn't seem to allow this, whether 'html' is TRUE or FALSE.

The '#markup' attribute will work, however.

```
function hook_node_view($node, $view_mode, $langcode){
  switch ($node->type) {
      case 'er_event':
        $node->content['links']['extra_link'] = array(
            '#weight' => 100, // place it at the bottom
            '#markup' => l('Add attendee data', 'node/add/er-engagement', array('query' => array('field_er_cal_entity_reference' => $node->nid))),
        );
        break;
}

```

}

That works great if you need those arguments in there. The documentation is lacking, but thanks to this post, it helps to check out Drupal 7's blog.module, just search for '#links' to get a clue.
> 3 votes

# Answer
To add query fragment just put it inside the option array:

```
$node->content['links']['extra_link'] = array(
    '#weight' => 10,
    '#theme' => 'link',
    '#path' => 'node/add/er-engagement',
    '#text' => t('Add attendee data'),
    '#options' => array(
        'html' => FALSE,
        'query' => array('field_er_cal_entity_reference' => $node->nid)
    ),
);

```

This will return an URL like this: node/add/er-engagement?field\_er\_cal\_entity\_reference=13
> 1 votes

---
Tags: entities, hooks, nodes
---


# Question
Title: How to Identify Fields from Field Collection?
I have a Content Type, which has field collection and I need to load the fields present inside the field collection, Any idea on how to do this?

**Very Important Note:** There is no content created for this Content Type as yet.

# Answer
This'll do it:

```
$entity_type = 'field_collection_item';
$bundle_name = 'field_profile_address';

$info = field_info_instances($entity_type, $bundle_name);

// $info at this point is an array of fields attached to the queried bundle.

```

From your last 2 questions I think you'd be very interested in the Field Info API docs.
> 4 votes

---
Tags: entities
---


# Question
Title: Create View That Overlays The Theme When Field Clicked
Hello i like the feature that ive seen on a few themes where it lets you have an overlay button top left and when you click it it overlays the whole screen with a grid or in my case a picture. Here;s a video explaining more if you dont mind. Its just brief. http://www.youtube.com/watch?v=cwXV20VJAr8&feature=youtu.be

I would like to create a View and let the items on it have the same function as this overlay button. Im sure it would be possible. I could do most of it barr the action of clicking a view title (button) and making html overlay.

Actually there sounds like there will be a module to do this. I would rather avoid if i could. Maybe some jquery or something wuld be easier?

Thanks

# Answer
> 1 votes
You can achieve this effect like this for example:

* You put a view block on top (which will overlay the other content) and put the other content below, position them on top of each other with position: absolute.
* Then create a button and position it however you prefer.
* Use jQuery .click() with this button (http://api.jquery.com/click/) to hide and show your view block. One possible solution is that on click, you examine if the view block has a "hidden" CSS class (for example). If it has "hidden" on click, you remove the class with .removeClass("hidden"), if it doesn't have the class, you add it with .addClass("hidden").
* CSS styling should be like this: .hidden{ display: none; }

---
Tags: views, 6, javascript
---


title: Drupal Multilingual Home page

text:
# Question
Title: Drupal Multilingual Home page
I am having a problem with multilingual settings. Here is my site URL http://centriumcapital.com/centrium. Everything is working fine but I just want when someone requests http://centriumcapital.com/centrium the default language should be French and also content of the home page also should in French.

I added code in settings.php file to make French language as default language it selects the French language as default but content is still from English language.

# Answer
Finally I got the problem. in the languages setting Browser default language was enabled. so i just unchecked browser language and it is working fine now.

Thanks to mohit\_rocks
> 0 votes

# Answer
Check out this Page. You can set this using locale module and i18n translation module.
> 1 votes

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


# Question
Title: How to render random image on every refresh page
I have got a content type and an `image` field.

How can I render the field with a random image at every page refresh.

# Answer
Previously I write a small module for this purpose, named Many to one image

This is a small display formatter, Download and install then go to manage display and select it.
> 0 votes

---
Tags: entities, media
---


# Question
Title: Show news articles only by the year selected
I am working on porting a static site over to Drupal 7, and one of the pages I am porting is a Newsroom page that starts off by listing news articles (which are internal site pages, not links to other sites) and then below that are links to different years. The way the old site works is that when a year is clicked it hides the articles that are up and then shows the articles for that year. Is there a module/plugin that can do this or is there some other way than using javascript to hide and show the different articles?

# Answer
> 0 votes
You could create a view using Views and allowing an exposed filter on the year to the user to select the year or dates. That would then submit the request to the server and reload the page with only the selected year. It wouldn't be pretty like using Javascript, but it would do the job.

---
Tags: 7
---


# Question
Title: Using Drupal 7 hashing method in Drupal 6
I want to use Drupal 7 hashing method in Drupal 6 for generating hash(not for password). I will be using a key(say username) generate hash and store it in DB, later on when user provides username i will be generating hash for input and compare with the one that's stored in database.

```
include 'd7_modified_password.inc';
$key = "random_string";
print user_hash_password($key);

```

This generates a random string every time even though `$key` is unchanged. How can I use this so that I can use this method to compare two keys.

# Answer
> 0 votes
Need to use `user_check_password()` method to compare existing key. Guess I overlooked it earlier.

---
Tags: 6
---


title: Custom Form submit not saving

text:
# Question
Title: Custom Form submit not saving
I've created a custom module to add several submission buttons at the bottom of the form. One submit button should redirect users to their Profile2 profile. The other will send them to the user administration section.

The Profile2 page has a submit button to send them to the user account edit page, or to the user administration section. I was able to do this with rules, but the site admin didn't like that there weren't buttons.

So I've created a custom module to handle this, but the problem is that the data is not saved when one of the custom submission handlers is called.

```
//redirects to account and from profile are working but submissions not saving

function MY_MODULE_redirect_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    if (arg(3) == 'coach'){
        $form['actions']['profile'] = array(
        '#type' => 'submit',
        '#submit' => array('MY_MODULE_redirect_account'),
        '#value' => t('Save and go to Account'));
        $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#submit' => array('MY_MODULE_redirect_admin'),
        '#value' => t('Save and go to Administration'));
    }
    else {
    $form['actions']['profile'] = array(
      '#type' => 'submit',
      '#submit' => array('MY_MODULE_redirect_submit'),
      '#value' => t('Save and go to Profile'));
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#submit' => array('MY_MODULE_redirect_admin'),
      '#value' => t('Save and go to Administration'));
    }
  }
}

function MY_MODULE_redirect_submit(&$form, &$form_state) {
    $user = $form_state['user'];
    $form_state['redirect'] = 'user/' . $user->uid . '/edit/coach' ;
    drupal_set_message('The user account has been saved');
}

function MY_MODULE_redirect_admin(&$form, &$form_state) {
    $user = $form_state['user'];
    $form_state['redirect'] = 'admin/MY_MODULE-user';
    drupal_set_message('Your submission is complete');
}

function MY_MODULE_redirect_account(&$form, &$form_state) {
  $user = $form_state['user'];
  $form_state['redirect'] = 'user/' . $user->uid . '/edit';
  drupal_set_message('The coach profile has been saved');
}

```

# Answer
> 5 votes
You are altering user\_profile\_form. By doing this

```
$form['actions']['profile'] = array(
      '#type' => 'submit',
      '#submit' => array('MY_MODULE_redirect_submit'),
      '#value' => t('Save and go to Profile'));

```

you have dissconnected default submit handler which save the data.

```
// Add the final user profile form submit handler.
  $form['#submit'][] = 'user_profile_form_submit';

```

So you need to append your submit handler with default submit handler

# Answer
> 0 votes
I was able to figure it out thanks to Ankit's recommendation. I had to pass $form and $form\_state to the default submit handlers user\_profile\_form\_submit($form, $form\_state) for the user account and profile2\_form\_submit\_handler($form, $form\_state) for profile2. I also had to separate out the standard submission to save the proper form fields.

Here's the code that I used

```
//redirects to account and from profile are working but submissions not saving

function MY_MODULE_redirect_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    if (arg(3) == 'coach'){
        //handes profile2 submissions
        $form['actions']['profile'] = array(
        '#type' => 'submit',
        '#submit' => array('MY_MODULE_redirect_account'),
        '#value' => t('Save and go to Account'));
        $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#submit' => array('MY_MODULE_redirect_profile_admin'),
        '#value' => t('Save and go to Administration'));
    }
    else {
    //handles user account submissions
    $form['actions']['profile'] = array(
      '#type' => 'submit',
      '#submit' => array('MY_MODULE_redirect_submit'),
      '#value' => t('Save and go to Profile'));
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#submit' => array('MY_MODULE_redirect_user_admin'),
      '#value' => t('Save and go to Administration'));
    }
  }
}

//redirect from profile2 to custom URL

function MY_MODULE_redirect_profile_admin(&$form, &$form_state) {
    $user = $form_state['user'];
    profile2_form_submit_handler($form, $form_state);
    $form_state['redirect'] = 'admin/MY_CUSTOM_REDIRECT';
    drupal_set_message('Your submission is complete');
}

//redirect from profile2 to user account

function MY_MODULE_redirect_account(&$form, &$form_state) {
  $user = $form_state['user'];
  profile2_form_submit_handler($form, $form_state);
  $form_state['redirect'] = 'user/' . $user->uid . '/edit';
  drupal_set_message('The coach profile has been saved');

//redirect from account to profile2

function MY_MODULE_redirect_submit(&$form, &$form_state) {
    $user = $form_state['user'];
    user_profile_form_submit($form, $form_state);
    $form_state['redirect'] = 'user/' . $user->uid . '/edit/coach' ;
    drupal_set_message('The user account has been saved');
}

//redirect from account to custom URL

function MY_MODULE_redirect_user_admin(&$form, &$form_state) {
    $user = $form_state['user'];
    user_profile_form_submit($form, $form_state);
    $form_state['redirect'] = 'admin/MY_CUSTOM_REDIRECT';
    drupal_set_message('Your submission is complete');
}

```

---
Tags: forms
---


title: Are proprocess functions cached?

text:
# Question
Title: Are proprocess functions cached?
I'm using a MODULE\_preprocess\_node function to modify the node template and I'm experiencing strange things.

Basically my idea was to prevent anonymous users from commenting more than once. In the preprocess function, I check if the current hostname (if anonymous) has a previously submitted comment for the current NID and if it does, I empty the comment form array.

But the problem is that, even when caching is disabled, I'm experiencing strange behavior. I'm not quite sure whether it's because of caching. I checked my `db_select` call and it works.

Do you have any recommendation for me to prevent this from being happening ? May be I should ask if the output of `*_preprocess_*` functions are cached at first place.

I do not have (core) caching enabled and I'm planning to do so. No other modules installed yet.

Thanks in advance.

# Answer
Do not confuse the cache with the "theme registry".

If you're updating theme functions, flush the cache (which will also update the theme registry).

if you post code there could be other reasons it isn't working. if you're dealing with comments I would look at using comment specific hooks rather than node submission hooks.
> 1 votes

---
Tags: 7, comments, theming
---


# Question
Title: Setting the form value to an organic group gid from validation hook of custom field widget (Drupal 7)
I have a custom widget which can be used for a group audience field. Instead of being a dropdown like the OG\_AUDIENCE\_WIDGET it is made up of three multiple select list, and the group which is actually selected is the one which is picked in the third select list. I have the actual widget working but I am stuck on validation. I have been trying to set the gid in a couple of different ways which have failed in a couple different manors. First:

```
function multiselect_validate($element, &$form_state)
{
  if($form_state['submitted'])
  {
    $index = array_shift(array_values($element['wrapper']['dropdown_assignment']['#value']));
    $assignment_name = $element['wrapper']['dropdown_assignment']['#options'][$index];
    $query = new EntityFieldQuery();
    $result = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'assignment_group')
    ->propertyCondition('title',$assignment_name)
    ->execute();
    $node  = reset($result['node']);
    $assignment_gid = og_get_group("node", $node->nid)->gid;
    $value = $value[LANGUAGE_NONE][0]['gid'] = $assignment_gid;
    form_set_value($element,array('gid'=>198), $form_state);
  }
}

```

This kind of validation returns an error:

```
[11-Dec-2012 11:23:07] PHP Fatal error:  Cannot unset string offsets in /Applications/MAMP/htdocs/arcade/modules/field/field.default.inc on line 41

```

I also tried something like this for the final form\_set\_value:

```
form_set_value($element,array('gid'=>$assignment_gid), $form_state);

```

But when I do this and then look at the result nothing actually gets set into the field.

What is the proper way to set the gid for the field?

# Answer
I'm assuming the validate callback that you have mentioned in your question is the `#element_validate` callback for the field widget element.

In that case, `form_set_value` must be set to a *list* of items because a field is inherently *multi-valued*. Each item in this list must conform to the schema of the field.

So, in this case:

```
$items = array();
$delta = 0;
$gid = ...; // From somewhere
$items[$delta] = array(
  'gid' => $gid,
  'state' => OG_STATE_ACTIVE, // optional
  'created' => REQUEST_TIME - 3600 // optional (yesterday)
);
form_set_value($element, $items, $form_state);

```

To illustrate this better, I have a sandbox project up on drupal.org. It declares a new widget with hierarchical dropdowns just like you have described. You can check the code directly from http://drupalcode.org/sandbox/amarnus/1868742.git/tree/refs/heads/master or clone the project from http://drupal.org/sandbox/amarnus/1868742. Hope this helps!
> 2 votes

---
Tags: 7, entities, organic-groups
---


# Question
Title: login_destination module and link with anchor
I want to to use login\_destination module to have a link to login screen in comment-wrapper.tpl.php, so after the login, the user came back to write the comment.

I have installed and configured login\_destination and modified comment-wrapper.tpl.php.

The login\_destination documentation say that if I use my own links to the login screen, i have to use GET to supply "current" parameter.

So in my theme I've added to comment-wrapper.tpl.php:

```
$destino = drupal_get_destination();
$destino = $destino['destination'];

```

And changed the text to add the link to the login screen:

```
<?php if ($comment_form): ?>
<h2 class="title comment-form"><?php print t('<a href="@login">Login</a> or anonymous comment:', array('@login' => url('user', array('query' => array('current' => $destino), 'fragment' => 'comments')))) ?></h2>
<?php print $comment_form; ?>

```

Now, when I click on "Login" link, opens an url like:

```
SITE.com/user?current=node/3#comments

```

But after finish the login, I'm redirected to node/3 alias, without the anchor #comments.

If I type on the browser the url:

```
SITE.com/node/3#comments

```

It' works ok, it goes to the #comments anchor.

Any help or suggerence?

Thanks!

# Answer
> 0 votes
Try this.

```
<?php if ($comment_form): ?>
        <h2 class="title comment-form"><?php l('Login or anonymous comment', user, array('query' => 'current=node/3#comments')); ?></h2>
<?php print $comment_form; ?>

```

# Answer
> 0 votes
Update: after reading your quesiton again, it seems that redirecting to a fragment is not possible with destination or current parameters. See this Here is my previous answer where I assumed the problem was in the l() function.

Just have a look at

```
<?php if ($comment_form): ?>
<h2 class="title comment-form">
<?php print t('!login or anonymous comment:',
        array('!login' => l(t('Login'), 'user/login', array(
          'query' => array('current' => $destino),
          'fragment' => 'comments')))); ?></h2>
<?php print $comment_form; ?>

```

A few points: I have used !login in the t() function. if you use @login, it will not be parsed as HTML. Instead, you will see the a tag in plain text.

l() function accepts the actual text of the A tag. We need to use t() function here.

I just tested it myself and worked for me.

---
Tags: navigation
---


# Question
Title: Theming: Is this a valid way to go about it
Total newbie at Drupal. Is it valid to say that I could code a page in pure html/css and then start adding the php variables needed to eventually make the page.tpl.php?

Or should I go about it by creating the tpl.php file differently?

That feels possible but all the reading I've done hasn't explicitly said it that way.

# Answer
You certainly could do it that way, however, that would require you to know all of the php necessary to make a fully functional Drupal page.tpl. What I would recommend, and how I started themeing (outside of reading a bunch!) was taking a page.tpl.php from a theme similar to what I was looking for and modifying it until I was happy with it. After doing this several times and experimenting a lot (and reading!) I became quite familiar with the templating system used in Drupal and the php code needed in the most common template files.
> 0 votes

---
Tags: theming
---


# Question
Title: Reference start date and end date for date field
I'm trying show some text when it falls between a certain date, but I am having trouble referencing the start date and end date of the date field.

My code is:

```
$now = time();
$date1 = strtotime($date1);
$date2 = strtotime($date2);
  if ( $now >= $date1 && $now <= $date2) {
  echo 'This is a new video';

     } else {
  echo 'This is an OLD video';
     }

```

But it is not working because I do not think I am getting the value of the date in $date1 & $date2. My drupal field (named field\_time) is set up as a Date (UNIX timestamp). I used the Devel Module to see where the start and end dates are held and it told me "date1" and "date2".

But my code above isn't referencing the field, so im suspicious. Am I referencing the correct date strings above?

# Answer
> 0 votes
If that is a node field, then the values you are trying to use are accessible using the following code.

```
$items = field_get_items('node', $node, 'field_time');

$from = $items[0]['value'];
$to = $items[0]['value2'];

```

---
Tags: 7, datetime
---


# Question
Title: How can I display latest post in another menu tab?
I want my latest post to appear in another Menu tab. For example, in this website www.drupal.stackexchange.com, you have the following menus QUESTIONS, TAGS, USERS, BADGES, UNANSWERED, if I want my post to appear in BADGES, how can I archive this?

# Answer
> 1 votes
You could use taxonomies. First, navigate to *admin/structure/taxonomy* and create a taxonomy with the terms you want to have tabs for (e.g. QUESTIONS, TAGS, USERS, BADGES, UNANSWERED). Hover over each of the terms in the list terms to discover their default paths. Let's say you note that "BADGES" has been assigned the path "taxonomy/term/7"

Now, *all* you need to do is to create an item in your main menu to display tagged articles. So navigate to *admin/structure/menus* and add the following link to the main menu. Set *Menu link title* to "BADGES", and *Path* to "taxonomy/term/7". Repeat for other taxonomy terms you want to access via a main menu tab.

Now, you have tabs in your main menu called "BADGES", etc. Under each tab content tagged with its taxonomy term will appear automatically, so to make content show up under the BADGES tab, tag it with "BADGES". If you're using Drupal 7, the default article content type already has a taxonomy field. But you can add a taxonomy field to any content type if it is missing.

You can now refine this by customizing *how* things are listed using Views to create customized listings. You can also hide the numeric paths with the use of URL aliases if you want (so the path appear to the user as badges instead of taxonomy/term/7.)

---
Tags: views
---


# Question
Title: using drupal 7 functions in external files
I feel that the above title isn't very well worded since I can't figure how to state it properly using few words. Anyway, what I'd like to do is this:

```
$.post("foo.php", data, function(msg) {
   //the js part is easy enough to handle
});

```

This is simple enough but how do I get foo.php to use Drupal 7's functions? While it would probably make my life much easier to use ordinary php code to do all my database queries, I'd like to stick with Drupal functions to play it safe.

# Answer
Make a copy of the `index.php` file and rename it to `foo.php`. `index.php` ships by default with Drupal 7 and can be found in the root of the Drupal source.

Remove the last call to `menu_execute_active_handler()` from the new file. This is the router that calls an appropriate page handler based on the query string. You wouldn't need this.

This leaves:

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
/* Stub */

```

As you can see, Drupal is now bootstrapped fully. This makes the API methods of Drupal core and all other *enabled* core and contributed modules available for use in this script from the fourth line.
> 9 votes

---
Tags: 7
---


# Question
Title: Alter the exposed filter value on change of other exposed filter value
I wanted to do an interdependent select boxes using views exposed filters. So when i select the 1st exposed filter, the second once should filter itself based on first exposed filter value and this should happen dynamically. I tried a lot with form\_alter but did not work. Any example or any suggestion as to how to go about it.

# Answer
> 2 votes
The easiest way of solving this, would be to use JavaScript. You need to have all the options available, and with JavaScript you can alter the options based on what's selected. Something like this:

```
$("#field-1").change(function(){
  if ($(this).val() == 'option_1') {
    var options = '<option value="foo">bar</option>';
    $("#field-2).html(options);
  }
});

```

The above is merely example code but illustrates the approach. You might need to do some work, in order to get the different options that should be available.

# Answer
> 3 votes
The Views Dependent Filters module will solve your problem.

> Allows the presence of exposed filters on a view to be controlled by values in another exposed filter. Dependent filters are hidden when not relevant, and their values are not considered when the exposed form is submitted.
>
> The module is compatible with both the Views basic and the Better Exposed Filters form plugins.

---
Tags: 7, views
---


# Question
Title: How to store field data in a file instead of the db?
So far, I found two decent options for storing field in a file:

1. using node hooks to store data in a filefield, and process it on node view
2. theoretically, the best would be to use file storage as a backend, but is there a module for field file storage instead of field sql storage?

My use case is a field that does not change, but mysql backup is very slow because there are 600 000 nodes with it. I also do not need to query this field, just display it. With file storage I can do incremental backup which is lightyears more efficient.

# Answer
Your best bet's going to be using the MongoDB module, I think ... Here is a quote about it (from the module's project page):

> ... is a collection of several modules which allow sites to store different types of Drupal data in MongoDB.
>
> Views integration provided by EntityFieldQuery Views Backend.
> 2 votes

---
Tags: 7, entities, files
---


# Question
Title: Multiple webforms: Show list of those user has submitted?
Is there a way to list all webform submissions user has submitted using views?

I have a site where there is hundreds of webforms. I need to create a block that contains all webforms by title current user has submitted.

# Answer
> 1 votes
If you are using Drupal 6.Try this view export code

```
$view = new view;
$view->name = 'test_webform';
$view->description = '';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'webform_submissions';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('relationships', array(
  'nid' => array(
    'id' => 'nid',
    'table' => 'webform_submissions',
    'field' => 'nid',
  ),
  'uid' => array(
    'id' => 'uid',
    'table' => 'webform_submissions',
    'field' => 'uid',
  ),
));
$handler->override_option('fields', array(
  'title' => array(
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'relationship' => 'nid',
  ),
));
$handler->override_option('filters', array(
  'uid_current' => array(
    'id' => 'uid_current',
    'table' => 'users',
    'field' => 'uid_current',
    'relationship' => 'nid',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->override_option('relationships', array(
  'nid' => array(
    'label' => 'Node',
    'required' => 0,
    'id' => 'nid',
    'table' => 'webform_submissions',
    'field' => 'nid',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
  'uid' => array(
    'label' => 'User',
    'required' => 1,
    'id' => 'uid',
    'table' => 'webform_submissions',
    'field' => 'uid',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('fields', array(
  'title' => array(
    'label' => 'Title',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'link_to_node' => 0,
    'exclude' => 0,
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'relationship' => 'nid',
    'override' => array(
      'button' => 'Use default',
    ),
  ),
  'submitted' => array(
    'label' => 'Submitted',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'submitted',
    'table' => 'webform_submissions',
    'field' => 'submitted',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
  'sid' => array(
    'label' => 'Sid',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'link_class' => '',
      'alt' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'set_precision' => FALSE,
    'precision' => 0,
    'decimal' => '.',
    'separator' => ',',
    'prefix' => '',
    'suffix' => '',
    'exclude' => 0,
    'id' => 'sid',
    'table' => 'webform_submissions',
    'field' => 'sid',
    'override' => array(
      'button' => 'Use default',
    ),
    'relationship' => 'none',
  ),
));
$handler->override_option('filters', array(
  'uid_current' => array(
    'operator' => '=',
    'value' => '1',
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'uid_current',
    'table' => 'users',
    'field' => 'uid_current',
    'relationship' => 'uid',
    'override' => array(
      'button' => 'Use default',
    ),
  ),
));
$handler->override_option('block_description', '');
$handler->override_option('block_caching', -1);

```

---
Tags: views, webforms, database
---


# Question
Title: How to programmatically read the display name of a CCK field from the allowed list?
For example if a CCK text field is configured to have the following allowed values:

```
US|United States
UK|United Kingdom

```

The node has the corresponding field:

```
node->country

```

and its value can be found by accessing:

```
node->country[0]['value']

```

which will return 'US' or 'UK'. What is best way to return the display name which was specified in the allowed list (i.e "United States" or "United Kingdom")?

# Answer
You can use the following code.

```
$field = content_fields($field_name);
$function = $field['module'] . '_allowed_values';
$values = array_values(function_exists($function) ? $function($field) : (array) content_allowed_values($field));

```

This code is similar to the code used by optionwidgets\_options(); the difference is that `optionwidgets_options()` returns also the value for the empty choice.

The output of `content_allowed_values($field)` is an array that in your case is the following one.

```
array(
  'US' => 'United States',
  'UK' => 'United Kingdom',
);

```

As you are only interested to the options visible in the user interface, I passed the result of `content_allowed_values($field)` to `array_values()`.
> 1 votes

# Answer
Install the devel module and go to a node with this field and click the devel tab. If its available directly it will show in devel. If not you may have to do a custom db query.
> 0 votes

---
Tags: 6, entities
---


# Question
Title: htaccess 301 redirect everything except /admin
I have been scratching my head for almost half an hour already because of this. I don't know what I am doing wrong, might just be under my nose, but i just cant see it. Here's what I have on my .htaccess

```
  RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
  RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

  RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
  RewriteCond %{REQUEST_URI} !^/admin [NC]
  RewriteRule ^(.*)$ http://newsite.com/$1 [R=301,L]

```

When I access example.com/admin, i am still redirected to newsite.com/admin.
Can anyone please advise? Thanks!

# Answer
> 1 votes
It depends on `RewriteBase /`. I checked your code with this online tool and it was working fine. Toggling comment for rewritebase line will help but other rules might get affected. Instead, modify your condition and remove the slash. It should work.

```
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteCond %{REQUEST_URI} !^admin [NC]
RewriteRule ^(.*)$ http://newsite.com/$1 [R=301,L]

```

# Answer
> 0 votes
Try this:

```
RedirectMatch 302 /(?!admin)  http://www.newsite.com

```

---
Tags: redirection, users, .htaccess
---


# Question
Title: Node authors notified by email when a comment is added using trigger module - node token not getting
My goal is to send a notification email to the node author when a new comment is added. For this i am using trigger module. But didn't get the node author mail id.

Any one experienced in it?

# Answer
> 5 votes
Maybe you can try these module http://drupal.org/project/comment\_notify

Video tutorial http://drupalize.me/videos/notify-author-comments http://drupalize.me/videos/notify-comment-reply

# Answer
> 4 votes
I got the token for the question i posted here.

`[node:author:mail]` should be replaced with `[comment:node:author:mail]`

drupal.org link to refer

---
Tags: emails, tokens, rules
---


title: Sort nodes by latest comments on it

text:
# Question
Title: Sort nodes by latest comments on it
I am using D7. I want to sort the nodes by the comment post date on it.

**Like**

Node `a` created on Jan 03 Node `b` Created on Jan 05

Normally i can sort it either `asc` or `desc`.

What i want is a node with latest comment will be in top of my views.

I am looking for a views3 solution. Is it possible ?

# Answer
> 3 votes
"Last comment time" is sort.

Then use 'Sort descending'

# Answer
> 2 votes
Add the comment table in a relationship, "Last comment time" should just show up.

# Answer
> 2 votes
The first step would be to add the *Comments of the node* relationship. You can find this under the *Comment* section in the *Relationships* block in the Views UI (when the base table of your view is `{node}`). You will now be able to add the *Comment: Post date* as a filter and make it sort by *desc* which should do the trick for you.

Depending on your use-case, you can *then* consider doing the following:

* Making the relationship "required" if you wan't to exclude nodes that don't have comments on them as yet.
* Set `Use aggregation: Yes` if you'd like to just show only the most recent comment of a node and not any other i.e. nodes don't repeat themselves.

# Answer
> 2 votes
Import this view:

```
$view = new view;
$view->name = 'newcomments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'newcomments';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'newcomments';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['hide_empty'] = 0;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Field: Content: Updated/commented date */
$handler->display->display_options['fields']['last_updated']['id'] = 'last_updated';
$handler->display->display_options['fields']['last_updated']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['last_updated']['field'] = 'last_updated';
$handler->display->display_options['fields']['last_updated']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['external'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['trim'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['last_updated']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['last_updated']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['last_updated']['alter']['html'] = 0;
$handler->display->display_options['fields']['last_updated']['element_label_colon'] = 1;
$handler->display->display_options['fields']['last_updated']['element_default_classes'] = 1;
$handler->display->display_options['fields']['last_updated']['hide_empty'] = 0;
$handler->display->display_options['fields']['last_updated']['empty_zero'] = 0;
$handler->display->display_options['fields']['last_updated']['date_format'] = 'long';
/* Field: Content: Comment count */
$handler->display->display_options['fields']['comment_count']['id'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['external'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['trim'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['comment_count']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['comment_count']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['html'] = 0;
$handler->display->display_options['fields']['comment_count']['element_label_colon'] = 1;
$handler->display->display_options['fields']['comment_count']['element_default_classes'] = 1;
$handler->display->display_options['fields']['comment_count']['hide_empty'] = 0;
$handler->display->display_options['fields']['comment_count']['empty_zero'] = 0;
$handler->display->display_options['fields']['comment_count']['format_plural'] = 0;
/* Sort criterion: Content: Updated/commented date */
$handler->display->display_options['sorts']['last_updated']['id'] = 'last_updated';
$handler->display->display_options['sorts']['last_updated']['table'] = 'node_comment_statistics';
$handler->display->display_options['sorts']['last_updated']['field'] = 'last_updated';
$handler->display->display_options['sorts']['last_updated']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'newcomments';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$translatables['newcomments'] = array(
  t('Master'),
  t('newcomments'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('Updated/commented date'),
  t('Comment count'),
  t('.'),
  t(','),
  t('Page'),
  t('Block'),
);

```

---
Tags: 7, comments, views
---


title: Upload gallery by ftp

text:
# Question
Title: Upload gallery by ftp
Is there a module for drupal7 that can create galleries from ftp? basically I upload a bunch of folders containing images in them by ftp. I want drupal to auto populate from ftp to create galleries.

# Answer
> 1 votes
Have you tried himuesgallery module?

> It implements a new node-type to show all pictures in an specified directory. Descriptions will be automatically generated from the filenames, so there is no need to administer a seperate databse table, etc. My gallery works with automated generetated thumbnails so it seems to be fast. It can use Lightbox2 or colorbox to simply generate lightshows and naturally it makes use of user configurable css-files to style the gallery. Some styles will be delivered with the module, so users don't be worried about this.

# Answer
> 1 votes
There is Media Mover

> Media Mover is a set of modules which allows website administrators to easily create complex file conversion processes. The core of Media Mover is the media\_mover\_api module which creates a set of rules allowing multiple modules to interact with a file. Media Mover can take a file emailed to an email account, turn a file attachment into an FLV file, create a new node with the file data, and then save the file on an external file storage system like Amazon's S3 all at once. And that's just the start.

**What you can do**
The core set of Media Mover modules offers lots of options for someone manipulating rich media.

* get attachments from an email account
* get attached files from nodes of a specified type
* get files from previously harvested files
* get files from CCK filefield and imagefield fields
* get files from a FTP server, provide file tokens for user authentication as well
* create a thumbnail from a video file with ffmpeg
* transcode video files into web friendly (and other) formats
* compress a file with zip
* move a file to Amazon's S3 service
* attach file back to node
* save file and related data as a node
* add a file to a CCK filefield or imagefield
* save a file to YouTube

# Answer
> 0 votes
There is no module like this in my knowledge as I have also searched a lot for the same functionality which you want.

Though the near which I got is, I will upload the folder and all the images will be available to choose when I make gallery.

Thanks, RajeevK

---
Tags: views, media, files
---


# Question
Title: Programmatically add a file upload field to all webforms (+more file extensions)
I have a set of \>100 webforms in my projects.

I need to add an upload field to all webforms in my `hook_form_alter()`.

I guess I need to do something like the following.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'webform_client_form_') === 0) {
    $form['file'] = array(
      '#type' => 'file',
      '#title' => t('File'),
      '#weight' => 50,
    );
  }
}

```

I need to set as on certain attributes such as:

* fieldkey
* max upload size
* allowed file extensions

How can this be achieved?

# Answer
In this way (hook\_form\_alter) you will have this field in existing and next created webforms, and you must have own additional \_validate and \_submit function to process the $form\['file'\] field. Other way, the question is how to add programmatically file upload component to existing webform? To see structure of webform file component, add manually field file to one existing webform and make your setting from the picture, and see devel output tab (enable devel module). Also you may be interested to see http://api.drupalize.me/api/drupal/function/webform\_component\_insert/7. Then create update script to loop webforms.
> 2 votes

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


title: Creating output files from Drupal 6

text:
# Question
Title: Creating output files from Drupal 6
I need to produce PDF/HTML output from my Drupal 6 app; is there a "Drupal way" to create a template with variables and then substitute them when the output is rendered or do i have to realize it by hand?

**EDITED**

Data is not on a node, but need to select from a non-drupal table

# Answer
> 3 votes
If you're using Views, you could try the Views PDF module.

> With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

Or perhaps the Print module if you're just creating a PDF from a node.

> This module allows you to generate the following printer-friendly versions of any node:
>
> * Printer-friendly version (webpage format) (at www.example.com/print/nid)
> * PDF version (at www.example.com/printpdf/nid)
> * Send by email (at www.example.com/printmail/nid)

**Edit**:

If you're willing to do a little legwork, you can use the Data module to expose your non-Drupal table to Views, and then use the previously mentions Views PDF

# Answer
> 1 votes
Have you checked Print Email and PDF module ? This module allows you to generate the following printer-friendly versions of any node:

* Printer-friendly version (webpage format) (at www.example.com/print/nid)
* PDF version (at www.example.com/printpdf/nid)
* Send by email (at www.example.com/printmail/nid)

---
Tags: 6, files
---


# Question
Title: Best way to achieve the following layout
I am pretty new to Drupal, I have a Content Type with a "Field Collection" say like below..

1. Title
2. Banner Image
3. Details - Field Collection Type (Short Title, Description, Links)

I would like to achieve the following style of output, basically upon "User Selection" in the LHS the RHS side should refresh and show the selected Field Collection item's Description. What is the best possible way to achieve this in Drupal 7 (Views with Contextual Filters?, Cycle? or Rotator components etc). Please advice.

**Edit: It's only the Content area shown in the picture, there will be a Menu/navigation system wrapping this. Hence this actually becomes 2nd level navigation for that page/node.**

thanks, Vasanth.

# Answer
Sounds like some form of a slideshow you're after. If you're on D7, try the Field Slideshow module. You may need to do some preprocessing to get the Titles linked as Pagers to the slideshow (currently no option to specify a field collection field as a pager). The module comes with 3 template files for next/prev and pager and main slideshow which you can copy to your theme folder and override.

After you install the module, go to the Manage Display of your content type and set the Format of the field collection field to Slideshow and then click the gear icon to configure.

To use titles as pagers, first go to Manage Display of your content type and set the Pager type to "Image". Ignore the Pager image style configuration.

Then paste the following code to your theme's template.php file and replace THEMENAME with the name of your theme, and replace FIELDNAME with the machine name of your title field inside the field collection:

```
/**
 * Override template_preprocess_field_slideshow_pager
 * @param array $vars
 */
function THEMENAME_preprocess_field_slideshow_pager(&$vars) {
    $pager = $vars['pager'];

    if($pager == 'image') {
        $items = $vars['items'];

        $thumbnails = array();

        foreach($items as $item) {
            $thumbnails[] = '<a href="#">' . $item['FIELDNAME']['und'][0]['safe_value'] . '</a>';
        }

        $vars['thumbnails'] = theme('item_list', array(
          'items'       => $thumbnails,
              'attributes'  => array(
                'id'    => 'field-slideshow-' . $vars['slideshow_id'] . '-pager',
                'class' => 'field-slideshow-pager slides-' . count($vars['items']),
              ),
        ));
    }
}

```

Clear all caches.

To include any long text type fields in the slideshow that you couldn't select in the Manage Display gear icon configuration, simply print them inside the field\_slideshow.tpl.php, if you know a bit of PHP it should be easy. All the fields should be available to you inside the tpl file in `$items` array. Look for the line that reads `foreach($items as $num => $item)`
> 0 votes

# Answer
Try Single Page Website module. Its a good option for this kind of website. Just create menu and give proper link.

> This module provide the ability to display the content of all menu items of the menu that you indicate in settings on the Single Page Website module. On the page 'single\_page' the links in the menu will be replaced to the links to the correspondent anchors. You can set URL 'single\_page' as front page of your site, and your visitors will see the Single Page Website. But it will be the site managed by Drupal 7.
> 0 votes

---
Tags: views, theming
---


title: Write to Organic groups

text:
# Question
Title: Write to Organic groups
I need option like on Facebook groups to publish something in group, and then user comment that.

Now i have only comment form which users use to post in groups.

I need something like posting nodes, but in group.

Is this possible?

Thank you!

# Answer
> 1 votes
You can allow any content type as content in the group. So if you want to set post in group you can edit **post** content type and make as group content.

When you edit the **post** content type usign **admin\>structure\>content types\>post** you will find the following options to add this content type as group option.

After doing this when you visit post create page you will find group select box. From here you can select the group.

---
Tags: organic-groups
---


# Question
Title: Views 3: Getting related content from node ref field
Okay, i have the following node types:

Band Story

Every story content **links to a band** via the node reference module for Drupal 7, now i'd like to pull related story content thats linked to the band when i **view the current node** that links to band X.

To give you an beter example:

When the story, "helloween reveals new album" links to helloween, i'd like to display all the related story's about helloween in that view...

# Answer
Your question is not quite clear whether you want to show band information when viewing a band-story node or to show band stories when viewing a band node. I'm assuming it's the second one.

1. Create a View with "Content" under "Show", and choose "Band Story" as the node type.
2. Clear the check box to create a page or make a block if you want. That's up to you:
3. Save and continue to Views UI.
4. In the Views UI, make sure you have 2 filters added - Node is published, and the node's type is Band Story.
5. Default sort criteria would be "Newest first". Change it if you want.
6. Add a new contextual filter.
7. In the add contextual filter, choose the field that **refers to Band node**. This field should be **in the Band Story node type**.
8. Add the argument. You will get the argument's settings page.
9. Under "When the filter value is NOT available", choose "Provide default value". Under "Type" select list, choose "Content ID from URL".
10. You can optionally add a validation criteria if you allow the node reference field to refer other node types than "band" as follows.

11. That's it! Save the View and put the block (you have to give a name to it) in the sidebar (or anywhere else). it will inherit the current node's ID and will show Band Story nodes that have this node ID in its node reference field.
> 2 votes

# Answer
## **If you use Panels**

Simply don't use **nid** as contextual filter, but your **entity reference field** and send that field's value of your story node to the view. Don't use any relationship.

---

## **If you don't use Panels**

I expect the only thing you can send to your view is the story's nid.

Then the only way I see (I hope people can provide you with a simpler one) is with a **PhP filter** :

1. Contextual filter : **nid**, **exclude** (I guess you want all the *other* stories about your band)
2. Relationship : **your reference field**, **require this relationship**
3. Field : **Content title**, without relationship
4. Field : **nid**, **with relationship, and exclude it from display**
5. Filter criteria : **PhP** with the following code :

// In "**setup code**" we will set into $static the nid referenced by the story with the 'field\_reference' field

```
$node = node_load($view->args[0]);
$static = $node->'node_field_data_yourreferencefield'['und'][0]['target_id'];

```

// In "**filter code**", we will exclude the rows where field value is different from $static

```
if ($data->'yourreferencefield' == $static) {return FALSE;} else {return TRUE;}

```

If you don't know the names to use for your fields, don't hesitate to dpm($data) and / or dpm($view-\>args\[0\]) in your php filter.
> 0 votes

---
Tags: views, nodes
---


title: Theme a taxonomy terms page

text:
# Question
Title: Theme a taxonomy terms page
How do I theme the tag/taxonomyterm page on my site? Can I use a panels page for this?

# Answer
You could use panels. Heres a good guide to setting up page manager with panels.

http://drupal.org/node/1582906

or you could use templates...

> ```
> taxonomy-term--[vocabulary-machine-name|tid].tpl.php
> base template: taxonomy-term.tpl.php
>
> ```
>
> Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:
>
> ```
> taxonomy-term--tid.tpl.php
> taxonomy-term--vocabulary-machine-name.tpl.php
> taxonomy-term.tpl.php
>
> ```
>
> Note that underscores in a vocabulary's machine name are replaced by hyphens.

See: http://drupal.org/node/1089656
> 2 votes

---
Tags: taxonomy-terms, theming, panels
---


# Question
Title: How to output data from module to a page. What are my options?
I have some code in a module that returns some data. I want to output it in a particular place on the page: Would a block, ctools plugin for panels or a template file be the best option and how would I choose?.

# Answer
If you already use Panels, and/or if you have an argument to send to your code, i'd advise Panels, definitively...

Great caching powers, multi-instances and rules of access.

But if you don't use it, don't make your site heavier with it and keep it with Blocks.

What about tpl.php ?
> 0 votes

---
Tags: theming
---


title: Auto-populating Storm Invoice

text:
# Question
Title: Auto-populating Storm Invoice
I'm using Storm for a bunch of its varying functionality, and figure it thus makes sense to use its Invoice module as the final part of a multi-part project (see previous SO post).

Everything in Storm Invoice seems like it needs to be entered on the fly, all the time. What I need to have happen is for a computed field from another node or a view to provide a price to the Invoice module, autopopulating some fields. **Is this at all possible with Storm Invoice?**

**Addendum:** If Storm isn't the best way to create dynamically-generated invoices from node CCK fields, please suggest an alternative.

# Answer
I'm not sure but maybe the Computed Field can be used, you can even use it to fill another field.

If you are ready for some custom code (although Computed Field will probably require some code too), you can implement `hook_nodeapi()` when `$op == 'prepare'`(or `hook_prepare()` in Drupal 7). There you can pre-fill new Invoice node (when `$node->nid` is not set, the node is being created).
> 1 votes

# Answer
It isn't currently possible to auto-fill these fields in Storm Invoice.

If you're still looking to do this (realise this is an old question), then ask over at the issues queue and we can help find a solution.
> 1 votes

---
Tags: nodes
---


title: PHP code in menu links

text:
# Question
Title: PHP code in menu links
One of many things I want to do in Drupal is to have

```
Hi: "User name"

```

link for /users page. (In the future I also want to have a control over visibility of menu tabs and their links depending on the logged user.)

Currently I have a quick, easy and relaxing solution - hacked page.tpl.php which works perfectly. Unfortunately I it is not a perfect (nor profesional) solution because the website will brake down as soon as I update the drupal core.

Is there any way of injecting php code into menu link/title without messing up the core?

I've been thinking about using translation module, menu module, and others but so far I have not been successful. I know that menus in drupal are designed to be static, but there must be a walk-around.

I know that menu\_token can solve some of my problems but it does not work for me (when installed I have memory allocation issues in php server or crashing MYSQL).

# Answer
> 6 votes
I finally figured this out. YES it is possible to have dynamic menus in Drupal.

You start by enabling dynamic access to menu item with the \['alter'\] flag and hook\_menu\_link\_alter(&$item).

```
function mycode_menu_link_alter(&$item) {
    if($item['menu_name'] == 'user-menu'){
        $item['options']['alter'] = TRUE;
    }
}

```

Note that menu\_link\_alter works on a menu item (not the whole menu) and needs to be trigered by editing and saving that item (for example disable-\>save-\>enable-\>save-\>).

Once the menu item is activated, I can use hook\_translated\_menu\_link\_alter(&$item, $map)

```
function mycode_translated_menu_link_alter(&$item, $map){
    //drupal_set_message("Menu: ".$item['menu_name']." Item: ".$item['title']
    if($item['menu_name'] == 'user-menu'){
        global $user;
        $item['title'] = "Hi: $user->name";
    }
}

```

Other very useful thing you can do is to disable the menu link

```
$item['hidden'] = TRUE;

```

or (my favorite) change the links

```
[...];
if($item['menu_name'] == 'main-menu'){
   switch ($item['title']){
       case "Home":
            $item['href'] = 'not/home/page';
[...]

```

# Answer
> 1 votes
Have you hacked the page.tpl.php file which came installed with Drupal? I hope not. The way you do it (the Drupal way) is you place a copy of that file in your theme folder (`/sites/all/themes/YOURTHEME/templates`) instead, clear cache, and you're done - from now on Drupal will use your template. During any core upgrade you typically leave the `sites` folder in place and thus your hack, your theme, your everything stays intact.

As per PHP code in menu, I have seen that in OM Maximenu, but I haven't tested this particular feature.

As with any international site - it's advisable to first test any newly installed module against its i18n support before you test any other features.

# Answer
> 1 votes
There is Menu token

> Menu Token module provides tokens, that could be used in title or in path of menu items (links). For example, if you create a menu item with path: "user/\[current-user:uid\]", the url will be changed "on fly" to: "user/1" (assuming you are user 1).

---
Tags: theming, hooks
---


# Question
Title: How to limit access to a view based on the contextual filter
I have a view that uses a contextual filter and I want to limit access to that view based on the filter. To give it some context:

I have a content type that represents minutes from previous meetings. These minutes can belong to a handful of committees. The user selects which committee the minutes belong to when creating the node, and the view then uses that as a contextual filter.

I would like to know if there is something out there that would allow me to filter access to the view based on the contextual filter. So if someone tries to access minutes/mycommittee vs minutes/notmycommittee they would be allowed and denied respectively.

Thanks in advance.

# Answer
> 4 votes
If you are using Drupal 7 and Views 3.x, then for each contextual argument, you can specify a validation criteria from the Views UI. Look for this checkbox under the *When the filter value IS in the URL or a default is provided* section for a given contextual argument.

Suppose your committees are taxonomy terms in a vocabulary, say, *Committee*, then you can use the `Taxonomy term` validator. Otherwise, you can simply use the `PHP Code` validator and key in the custom logic that defines access to your view.

Think of this custom logic as a boolean method from which you can access the view object and the raw value of the argument and then based on this *context*, allow or deny the current user's access to your view accordingly.

---
Tags: views, users
---


# Question
Title: How can I add a search feature to my Drupal 7 Zen child theme frontpage?
I would like to add a search form to the front page. I've added this to my template.php:

```
function my_theme_preprocess_page(&$variables){
   $search_box = drupal_render(drupal_get_form('search_form'));
   $variables['search_box'] = $search_box;
}

```

I've added this to my page.tpl.php:

```
<?php print $search_box; ?>

```

After viewing my site I do see the search form but get this error:

> Strict warning: Only variables should be passed by reference in denta\_quest\_preprocess\_page() (line 142 of C:\xampp\htdocs\drupal\themes\my\_theme\template.php).

# Answer
Your probably getting the warning because the function takes its argument by reference and to pass a variable by reference it needs to be defined. You're passing a function call which isn't a variable.

Try the following...

```
$search_form = drupal_get_form('search_form');
$search_box = drupal_render($search_form);
$variables['search_box'] = $search_box;

```
> 1 votes

---
Tags: search, theming
---


# Question
Title: Display output from custom module in a panel
How would I output data from a custom module to be displayed in a panel pane?

# Answer
I would recommend using hook\_block\_info() and hook\_block\_view() to expose your custom content in a block. This gives you Panels support + contextual links should the need for a form arise, and you can set caching settings for the block.
> 2 votes

# Answer
For my part I create a function that prints or echoes what I want and I simply call it in a PhP block (by using "Add custom content" in Panels) and use PhP filter.

You can call any function defined in your module and send it args the normal way, like

`<?php myfunction(%node:nid); ?>`

Panels is very handy there, because it gives you all sorts of data to use as arguments. You can do the same with blocks and PhP filter, but without access to data.
> 0 votes

---
Tags: 7, panels
---


# Question
Title: Using taxonomies to enhance SEO: Hard Situation
I am working on a site that the client required a dynamic url creation for a huge number of keywords for each city (for example). So the result url would be like www.domain.com/city/citname/keyword.

And each URL shall direct to a page which has the same content except the city name and keyword.

So I directly thought of taxonomies, but when I reached the development stage ... it was very hard to apply this over Drupal. I think of making two vocabularies one for the cities and the other for keywords as keywords are repeated the same for each city.

**Summery: every city should have all the keywords connected to it**

So, If my approach is good, how to mix two vocabulary? and how to maintain one content for all resulted taxonomy terms.

I hope it is clear

best,

# Answer
> 1 votes
From an SEO perspective I'm not sure its a great idea, I have little experience optimizing for SEO. But....

If the `title` of your Node is the cityname. I would simply make its url path pattern in Pathauto as `city/[node:title]`.

That takes care of the url /city/cityname.

Then you can simply use the `Tagging` taxonomy installed by default to tag the city with relevant keywords.

Then install the 3rd party contributed module: view\_mode\_page

It allows you to define alternate pattern(s) to get to a piece of Node content.

Then use its API to create the alternate urls based on the tags.

Something like this example code in a custom module (untested, as I dont have your exact setup):

```
/**
 * Implementation of hook_view_mode_page_get_patterns() from module
 * view_mode_page.
 *
 * This lets me define additional node urls (per NID) with a custom
 * view mode.
 *
 * Creating a custom view mode, and using Display Suite for example could let
 * you customize these pages so they're slightly more unique in content layout
 * and values.
 */
function MYMODULE_view_mode_page_get_patterns($results, $content_type, $view_mode) {
  $results = array();
  $defaults = array('content_type' => 'CITY_CONTENT_TYPE', 'view_mode' => 'full' /* or a custom view mode */, 'show_title' => 0, 'title' => '');

  // Load the terms for keyword vocabulary by its vocabulary name.
  $keyword_terms = taxonomy_get_tree(taxonomy_vocabulary_machine_name_load('city_keywords')->vid);

  // Loop through the Term objects and build the sub-url using the nodes pathauto alias denoted by %.
  foreach ($keyword_terms as $pos => $Term) {
    $results[$pos] = (Object) array_merge($defaults, array('url_pattern' => '%/'.$Term->name));
  }
  return $results;
}

```

If every city is to have different keywords, this may not work. Or you may have to load all the city nodes and iterate through them to get the correct paths and attached keyword terms. This is just taking a generic keywords list and building additional urls for each city.

---
Tags: taxonomy-terms
---


# Question
Title: Auto-create Nodes based on Content in current node?
In Drupal 7, is there a way to auto-create a node of "Type B" whenever a node of "Type A" has been created? Ideally, certain info would be passed on to the new "Type B" content item as well. For instance...

Let's say I create a new Type A content item, and that the Type A content type has several CCK fields. One of those CCK fields is a Node Reference field, which refers to content items of "**Type C**". Another of the CCK fields in Type A is a basic integer/text field.

When I create that new Type A content item, I choose "Content Type C Content Item #1" from the Node Reference drop-down select list. I also add "100" to the integer/text field. I'd then like a new Type B content item to be auto-created, with the same node reference info in its own node ref CCK field and the same integer/text in its own integer/text CCK field.

The purpose of this is to track usages of parts in sort of a macro and micro situation... Type C is the macro/master, Type A is the sub-macro/sub-master (if that makes sense) and Type B is the micro/slave of Type A. There will be many Type B's associated with a single Type A, but there will likely only be a single Type A content item associated with any given Type C content item.

I'm open to any all all suggestions, including scrapping this implementation concept in favor of something else that might work better and might be easier to manage.

Thanks!

# Answer
> 0 votes
You can do this kind of stuff with Rules. You could also look into hook\_node\_presave() yourself and do logic when nodes of TypeA are being saved.

---
Tags: nodes, views
---


# Question
Title: Why is the drush views-list command complaining (incorrectly) that views is not enabled?
I am running drush version 5.3:

```
rob@drupaldev:/var/www/drupal$ sudo drush version
drush version 5.3

```

When I attempt to execute the views-list command it says that the views module is note enabled.

```
rob@drupaldev:/var/www/drupal$ sudo drush views-list
Command views-list needs the following module(s) enabled to run:     [error]
views.
The drush command 'views-list' could not be executed.                [error]

```

However, the module is already enabled:

```
rob@drupaldev:/var/www/drupal$ sudo drush pm-list|grep -i views
 Chaos tool   Views content panes              Module  Not installed  7.x-1.0
 suite        (views_content)
 Views        Views (views)                    Module  Enabled        7.x-3.3
 Views        Views UI (views_ui)              Module  Enabled        7.x-3.3

```

Any ideas what else could be causing this?

Greg suggested that it could be a permissions issue or an environment issue caused by the necessity of using sudo. After having fixed one of my permission issues, I can reliably run drush with or without sudo. In either case it returns true.

```
rob@drupaldev:/var/www/drupal$ sudo drush ev 'var_export(module_exists("views"));'
truerob@drupaldev:/var/www/drupal$ drush ev 'var_export(module_exists("views"));'
truerob@drupaldev:/var/www/drupal$

```

# Answer
As Greg already mentioned in a comment, you will likely find that

```
drush cache-clear drush

```

removes this error.
> 3 votes

# Answer
This is working just fine for me on a d7 site using Drush 5.4. You are getting that message because module\_exists("views") is returning false. Your next example shows that views is enabled, which implies that module\_exists("views") should be returning true. Perhaps your site is not always bootstrapping cleanly under Drush?

Try:

```
drush ev 'var_export(module_exists("views"));'

```

Add on the 'sudo' as you do above, if you really need it. The sudo does give me pause; I prefer to set up my permissions in such a way as to allow Drush to run without it. Sometimes sudo changes your environment subtly (e.g. your $PATH may change), although I cannot think of a reason why it would cause you trouble in this instance. In any event, if the test above returns 'true', then you've stumped me. If it returns 'false', it indicates that there is something inconsistent or incorrect about your environment. You'll have to dig deeper to find out what it is.

**Edit:** I'm wrong, there could be other reasons why you are getting that error, even if module\_exists("views") returns 'true'. It probably boils down to drush\_bootstrap\_to\_phase() failing when called from \_drush\_bootstrap\_and\_dispatch(); however, I can't imagine why this would fail for views-list, but work for pm-list. More data is needed.

**Edit 2:** Try again with Drush All-versions-5.x-dev (or check out head of master from git). This is usually the first thing I suggest, but I thought that none of this code had changed recently. Turns out that enabling / disabling a module now clears the cache, but this feature was added *after* Drush-5.4 went out. `drush cc drush` should do the trick in the interim, but you won't need to explicitly do this in the future.
> 3 votes

---
Tags: views, drush
---


title: Problems with workbench access

text:
# Question
Title: Problems with workbench access
I'm trying to configure Workbench Access.

I follow the guide, so I've two users of the same role that can add node to the "custom" content type, and they can edit own nodes.

Then I've added workbench access and add this two users to all sections. But if I try to edit, with the user "one" a node owned by the user "two" I obtain an Access denied error.

The system tells me that the node is assigned to "Section one", but also if the user "two" is assigned to the "Section one", he can't edit the node.

Why? Have I to set standard permissions to node in a particular way? I haven't set the permission "Custom: edit any content".

# Answer
> 1 votes
To make sure I completely understand your question, I am going to restate it:

User B has created a node from a custom content type and it is assigned to Section One via Workbench Access. User A, who is also assigned to Section One, needs to edit User B's node but is currently unable to.

You're right in that you need to give people in that role the permission to "Edit Any Content" for that custom Content Type. You can access the permission page at admin/people/permissions, scroll to the "Node" section, find the specific content type in the list and select the proper permissions.

I don't know about what specifically you're trying to develop but I do have a couple of notes for you if it's still applicable to your situation.

First, you might want to consider adding a second role that only has the power to edit content from content types you designate in the permissions page. Using your example, let's say User B is assigned the role of "Author", meaning he can create content and edit/delete his own content. User A is assigned the role of "Editor", meaning she can edit any content User B has created but she cannot create her own. If User A needs access to edit content as well as to create content, you can assign User A to both the "Author" role and the "Editor" role. This means that User B will not be able to edit any content generated from the content type except for his own (if he has the correct permission set for that).

Second, I would recommend taking some time to review the documentation for Workbench Access for more information on configuration and permissions.

# Answer
> 0 votes
This sounds like a permissions issue (and workbench moderation related if you're using that) ...

I recommend reviewing the permissions for instance on this page (regarding workbench moderation) but would still apply to sharing content in an Editorial Section. documenation on workbench moderation.

---
Tags: workbench
---


# Question
Title: Where should twitter embed javascript go in a ctools plugin
I have a ctools plugin with the twitter embed javasacript in there, but where should the javascript go? Should it be in the template file, or should be be outputted into the block in the plugin file?

# Answer
> 1 votes
There's nothing "special" either about "Twitter embed" or "javascript and plugins".

The solution is the same as for other javascript includes, put the javascript in `[module]/js/file_name.js`, and call drupal\_add\_js() on it.

---
Tags: chaos-tool-suite, social-network
---


# Question
Title: Create an author archive page with views
I have two content types: article and author. The author content type has a bio, links to facebook and twitter etc. This author content type is connected to the article content type with an entity reference. I want to create a page that displays the author content at the top and then below that, a list of all the authors most recent articles.

I am trying to make a view block with a contextual filter to drop into the author page, but I cannot get it to work. I dont really understand views that well. Can anyone give me some pointers on what I need to do to set this up?

# Answer
You'll want to create a view of articles and add a contextual filter for the node reference field.

How are you attaching the view to a node? Is it a views attachment? Is it a panel pane á la Page Manager? That will determine the specifics of how your view parses the argument out of the URL.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: Role that can set roles but not change its own
In our sites, I have an Admin role (me) and Staff roles. The Staff role needs to be able to create client user accounts and assign client specific roles to those accounts. How can I give my staff the permission to set other's roles but not their own? I don't want them changing themselves to an admin when they want to (and they have).

# Answer
> 2 votes
I have used this with some success in the past: http://drupal.org/project/role\_delegation

I believe I also ended up formatting some of the user profile edit forms to make it simpler for the end user, but I can't quite recall.

# Answer
> 2 votes
It really sounds like there should be a module that does this ... I'm not aware of 1 offhand.

You could use hook\_form\_alter on the user account form and simply check the role of the logged in user. If they are `Staff` allow them to set roles to all but the Admin role you've defined. You would simply `unset()` the admin value in the `$options` array for the Roles checkboxes.

For example:

```
function MYMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (array_search('Staff', $user->roles)) {
    // Any RIDs you want to remove.
    unset($form['account']['roles']['#options'][3]);
  }
}

```

You would also probably want to add a validator to this form to check that a Staff user does not try to get around this by setting this value for instance via Firefox's Firebug. I leave that exercise to you.

# Answer
> 2 votes
It sounds like you want Administer Users By Role:

> If the user-being-edited has multiple roles, the user-doing-the-editing must have permission to edit ALL of the user-being-edited's roles.

This seems like it would prevent users from administering themselves, if they were given a role they couldn't administer.

---
Tags: users
---


title: Mobile_Detect.php and Drupal

text:
# Question
Title: Mobile_Detect.php and Drupal
How might I make use of this Mobile Detect php class in a D7 site? Rather new to this so I'm really not sure where this can be implemented.

# Answer
I wrote a module to do just that, Mobile Detect:

> This is a lightweight mobile detection based on the Mobile\_Detect.php library, which can be obtained from the GitHub repository.
>
> This module is intended to aid developers utilizing mobile-first and responsive design techniques who also have a need for slight changes for mobile and tablet users. An example would be showing (or hiding) a block or content pane to a particular device.
>
> This module is not intended (and never will be enhanced) to provide theme switching or redirection; other modules already provide this functionality.

There is also Context Mobile Detect:

> This is a Context module which integrates Context and PHP Mobile Detect library Mobile\_Detect.
>
> Module preserve drupal page cache working.

And you can check out Mobile Switch:

> The Mobile Switch module provides a simple automatic theme switch functionality for mobile devices, detected by Browscap or Mobile Detect.

These all serve slightly different audiences. Pick the one that best fits your needs.
> 5 votes

---
Tags: theming
---


# Question
Title: Images loading fine on day 1, broken on day 2
Strange problem.

Images on my production site are 100% working at one point (right after getting a refresh from staging), and within a day or two, some images on some pages become broken links.

(Production is updated from staging through mysql database dump/restore).

As I continue to watch this over the course of subsequent days, more pages in production experience this symptom, but the images are always there in staging - never broken.

Here's some data... When viewing the content of a page in the staging environment, an inserted image looks like this (Admin UI - view Source).

```
...installed one of the Outlook toolbars.</p><p>
[[{\"type\":\"media\",\"view_mode\":\"media_large\",\"fid\":\"123\",\"attributes\":
{\"alt\":\"\",\"class\":\"media-image image-style-large image-style-large image-style-large\",
\"height\":\"298\",\"typeof\":\"foaf:Image\",\"width\":\"264\"}}]]
</p><p><strong>Who can ...

```

When the Staging content is pushed to Production, viewing the same page in the Admin UI on the production server, the content starts out exactly the same and the image renders fine.

Within a day or two, the Production page changes (presumably by something Drupal Cron is doing) to something like this:

```
...installed one of the Outlook toolbars.</p><p>
<img alt=\"\" class=\"media-image image-style-large image-style-large image-style-large image-style-large\"
height=\"298\" width=\"264\" typeof=\"foaf:Image\"
src=\"http://default/sites/default/files/styles/large/public/Send%20Securely%20and%20account%20selection.png\" />
</p><p><strong>Who can ...

```

The "img src" version that creeps in is a bad URL -

```
http://default/sites/default/....

```

I've grep'ed my daily mysqldumps for this bad URL string, and each day there are a different number that creep in.

```
    for file in /data/mysqldumps/*sql
    do
      echo -n $file
      echo -n ": "
      grep -o "http://default" $file | wc -l
    done

/data/mysqldumps/20121205-160101.sql: 0 (Zero occurrences on Dec 5 because I pushed
                                         on that date, & all images were known good)
/data/mysqldumps/20121206-160101.sql: 106
/data/mysqldumps/20121207-160102.sql: 130
/data/mysqldumps/20121208-000101.sql: 138
/data/mysqldumps/20121209-000101.sql: 157
/data/mysqldumps/20121210-000101.sql: 158

```

No local Admin changes have occurred on production, and nothing but cron is running there.

What can be causing this? It's only happening in production (which is totally awesome).

Any suggestions on troubleshooting?

Thanks, Mark

# Answer
There is a related issue for this here. http://drupal.org/node/1352182.

What's happening is that drupal is storing the URL that is created when the page is first viewed after the cache is cleared. Normally that would be your site url, but sometimes it's not.

In the issue linked you see that some people fixed this using the Pathologic module.
> 1 votes

---
Tags: media, cron
---


# Question
Title: Creating content regarding to node address arguments
Say it I have such node alias: **example.com/content/my-fancy-page/**

If user enters to node above, he will see default page content of my fancy page. After some process I will redirect him to this: **example.com/content/my-fancy-page/tt3741/** or this **example.com/content/my-fancy-page/tt3802/**

1. Regarding to user's selection he will see the "tt3741" or "tt3802" content that resides inside database. Is it possible to do this with hooking etc. When I try "example.com/content/some-old-page/foobar" in my old website I get 404 error. So is it nt possible?
2. Is it possible to cache these three addresses seperately with Boost module? Or Boost only caches "/my-fancy-page/"

# Answer
Path aliases must be exact, thus if you want `my-fancy-page/tt3741` to work you need to create an alias for it. If you link to the node path `node/6` then `node/6/tt341` will work. This has to do with how hook\_menu works vs how path aliases work.

If you wish to hack around how path aliases work you can try out the PURL's Path Extensions feature http://drupal.org/project/purl or use hook\_url\_inbound\_alter() to get the correct node given the unique alias.

Boost will work as long as each URL is unique (same as drupal's core cache). Good luck.
> 0 votes

---
Tags: nodes, caching, path-aliases, uri
---


# Question
Title: Drupal doesn't invoke a hook function until I don't clean the cache
I created a module, and implemented `hook_form_alter()` using the following code.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mymodule_form_id') {
    $form['#validate'] = array('mymodule_form_validate');
  }
}

```

Drupal can call the function correctly, and run well for several days.

But one day Drupal did not call the function anymore, until I cleared the cache. Why?

# Answer
The reason why clearing the caches fixed the issue is because all hooks are cached in Drupal 7 via module\_implements(). My guess is something odd happened to your cache and thus your hook went missing from the cache.
> 0 votes

---
Tags: 7, caching
---


title: link each active block to it's page url

text:
# Question
Title: link each active block to it's page url
I want to link availaible block bids with active url. Then i want to clear page cache by block. How to do that best way? I wanted to use

```
block_list($region)

```

But it's overhead.

# Answer
> 1 votes
Knowing where any block is displayed can be tricky; you would need to keep a nontrivial database table in order to do that (Boost 6.x does this with nodes that are in panels and views). A better option would be to output the block via AJAX or ESI.

http://drupal.org/project/esi/ (has ajax output option)
http://drupal.org/project/ajaxblocks/
http://drupal.org/project/ajaxify\_regions/

---
Tags: blocks, caching
---


# Question
Title: How do I create a view that displays the author information of the current node being viewed?
I need to show a view in the sidebar that shows information about the current node's author (Username, picture, email). How do I go about doing this?

# Answer
1. Create a view with selecting a type as user.
2. Add "User:Content authored" relationship.
3. IN Contextual filters add nid and select the option of "provide default value" and select content Id from URL.

.

That's it :)
> 4 votes

---
Tags: views
---


# Question
Title: I deleted my .htaccess. easy way to fix this?
I'm clueless enough that I managed to delete my .htaccess file from my drupal site (after some mistaked advice from my webhost tech support). Now, I can go to the home page, but links to all internal pages result in 404 not found. I'm using drupal 5 and my web host is dreamhost. I don't have a recent backup of my site. I did find a very old htaccess file, and uploaded it, but then it threw a login pass popup.

Is there an easy way to fix this? Must I have the htaccess file? How can I generate a new one that will work with my site?

any help much appreciated.

# Answer
> 4 votes
Here you go the . htaccess for drupal 5.x

http://drupalcode.org/project/drupal.git/blob/refs/heads/5.x:/.htaccess

# Answer
> 2 votes
If you don't have any modification from the original file then you're ok the just upload this `.htaccess` from Drupal 5 repository.

It throws 404 because there is something in your clean url settings that depends in `.htaccess`, thats the reason why your URL rewrite is not working.

I advice to always backup before touching anything in your production environment so you can roll it back when something goes wrong.

---
Tags: users, .htaccess
---


title: hook_menu alternative for custom themes

text:
# Question
Title: hook_menu alternative for custom themes
I can understand that hook\_menu is for modules only, not custom themes. But if I want to add custom paths/urls to my theme what should I do?

For example if I want some of the content to load by ajax, and I want to use custom urls, then a "hook\_menu" would be great for custom themes.

Surely there must be another solution than to write a small custom module?

Any suggestions and help is appreciated.

Raf

# Answer
As of Drupal 7, themes can implement alter hooks, so you can use hook\_menu\_alter() in template.php.
> 1 votes

---
Tags: 7, hooks, routes
---


# Question
Title: Restricting view of nodes on taxonomy aggregation pages?
I have a taxonomy vocabulary that I use in many different content types. I want to restrict, programmatically, access rights to specific content types. As in, a specific role is not able to view particular content types unless they directly authored the item. This includes any view of a particular node (full, teaser, etc.). I've implemented `hook_node_access` as follows:

```
function progress_reporting_node_access($node, $op, $account) {
  if ($account->uid == 0) {
    return NODE_ACCESS_IGNORE;
  }
  if (_is_tagged($node,$account) && $op == 'update') {
    return NODE_ACCESS_ALLOW;
  }

  $records = _non_viewable_records();
  if (is_object($node) && in_array($node->type,$records)) {
    if ($op == 'view' && $node->uid != $account->uid) {
      drupal_set_message('Sorry, you cannot access this page. <a href="/">Click here to get back home</a>.','error');
      return NODE_ACCESS_DENY;
    }
  }

  return NODE_ACCESS_IGNORE;
}

```

The only thing that I didn't realize is that this affects a user only when they try to ***view the full node***. So, when a user navigates to a taxonomy term's aggregation page, all the teasers of all the content that the term is referenced in shows up, regardless of the logic I applied in `hook_node_access`.

I need to somehow apply the same restrictions to all node views. In other words, when they navigate to the taxonomy term aggregation page, they don't see teasers that they're not supposed to see.

How can this be done, programmatically, exactly?

# Answer
You're looking for hook\_node\_access\_records:

http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_access\_records/7
> 1 votes

---
Tags: 7, hooks, users
---


title: Drupal Shurly before redirect

text:
# Question
Title: Drupal Shurly before redirect
I want create to something like adf.ly script with Drupal. I am using shurly (developed by Jeff Robins) for URL shortening, and it works fine, but I want to display an advertising page for 10 seconds before redirecting to the final URL, which is not a feature provided by this module.

It has a hook called `hook_shurly_redirect_before()` which may help me, but I don't have enough knowledge to use it.

Can anyone explain how I should use this hook?

# Answer
> 1 votes
With a quick glance at the shurly code, I'd think this should work:

```
function yourmodule_shurly_redirect_before(&$redirect) {
  $redirect->destination = 'path/to/advert?somevar='. $redirect->destination;
}

```

And then you need to set up your advertisement page as path/to/advert and have it redirect to `$_GET['somevar']` after the timeout.

---
Tags: hooks
---


# Question
Title: Problems in recovering the fields with php
1. How do I retrieve a field without first being written its title? Now I'm doing so: `print render ($ content ['field_text']);`
2. I tried to recall the title of a node: `print render ($ content ['title']);` but this is not the way

# Answer
In node.tpl.php, the title is available as $title.

http://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7

In the case of full-page view of nodes, the title may be printed via page.tpl.php, so you may also need to modify that template to get the desired behavior.

http://api.drupal.org/api/drupal/modules%21system%21page.tpl.php/7
> 1 votes

---
Tags: hooks, 7
---


# Question
Title: How to disable delete once the thread has been started in advanced forum module in drupal 7?
If there are no comments on the current topic then user can delete the post.

If there are one or more comments on the forum-topic then user will not be able to edit or delete forum-topic.

Which module should i use or which hook needs to be implemented?

# Answer
You're looking for hook\_node\_access() where $op == 'delete'.

http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_access/7
> 0 votes

---
Tags: 7, hooks, nodes
---


# Question
Title: I want to add an include_path but don't have access to php.ini
I was thinking I could use the php function `set_include_path()` to accomplish this, but I'm not sure which file I should include this in. `template.php` perhaps?

# Answer
> 3 votes
`settings.php` would probably be the safest bet.

The `template.php` file might well be included too late in the process to have the desired effect, but `settings.php` is included indirectly from `drupal_bootstrap()` so should take effect before any of your custom code has a chance to run.

If you don't want to alter `settings.php` in that way you could implement `hook_boot()` in a custom module which is also invoked very early on in the page build process.

---
Tags: 7
---


# Question
Title: How do I create a rule to display a system message to users that an event is now over?
I have an event content type with a date field. Is there a rule I can create that will display a system message to the user that "This event is now over." based on comparing the current date and the date in the date field?

EDIT:

# Answer
Rules can be used for this. Your message will be displayed using drupal\_set\_message()

Starting at the Admin screen;

1. Click through *Configuration \> Rules \> Add New Rule*
2. Give it a name and select *Content is viewed* in *React on event*. Click Save.
3. Under *Conditions* click *Add condition*
    1. Select *Data \> Data comparison*
    2. Select *node:type* and click Save
    3. Fill in for your content type and save
4. Under *Conditions* click *Add condition* (again)
    1. Select *Entities \> Entity has field*
    2. *Data Selector* should have *node*
    3. *Field* should have the field you're wanting to check. This should be a date field
5. Under *Conditions* click *Add condition* (again)
    1. Select *Data \> Data comparison*
    2. In *Data Selector* chose your field. Mine was node:field-end-date
    3. Click Continue.
    4. Under *Operator* select *is lower than*
    5. Under *Data value* select *site:current-date*
    6. Click Save
6. Under *Actions* click *Add action*
    1. Select the *System \> Show a message on the site* entry.
    2. Enter your *Message*, select the *Message type* (this is the drupal\_set\_message() status), untick *Repeat message* and click Save
7. Browse to your expired content to see your message.
> 3 votes

# Answer
Your question is vague. What is a "message" to the user, a pop-up window ? a fake field you display above the other fields if the date is passed ?

The easiest thing for you to do without coding a custom module is probably using Display Suite to create a custom\_field in your content type. Use PHP to set the string value of the message if the date has passed as the field body. Or if the date has passed then call `drupal_set_message('Event has already occurred');` Or else return an empty string.

If you want a popup-window you can probably find a suitable module that shows a popup window from this popup module comparison matrix.
> 0 votes

---
Tags: rules
---


# Question
Title: How to Migrate static html files to Book - Migrate Module
I have almost 5000 static html files which belongs to different books.Please give me some direction How to migrate this html files to book.

I am able to migrate html files to Drupal.

But how should i update this Nodes to particular Book during migration.

Thanks a lot for the help!!

# Answer
A full description of this process would fill a lecture series. However, the broad approach I would take follows. This approach also has some assumptions that need to be met.

1. You will need to be able to code
2. You will need to know, or learn (it's not hard) XPath
3. The files are in a structure that allows you to recognise where they live in a book (either by links from file to file or path/filename or a combination.

If these conditions are met then import\_html is where I'd start. This will require you have the ability to write a module (that will use this module) and there is a bit of a learning curve, but learning this is well worth it. If you're already able to import the files it sounds like you're up to speed with the skillset needed.

One of the things that import\_html will also allow you to do is update nodes if they're already present too. Although my experience with this has always been with blowing away the content and rerunning the import to see how any changes went.

I've been involved with a few projects that used this and imported many content types and media from static source dumps.
> 0 votes

---
Tags: migrations, nodes
---