# Question
Title: Drupal 7 Custom Content form_alter validation
Hi I was wondering if anyone could give me some advice on this. Basically what I have is a custom content type created by the content creator GUI, I am writing a custom module to alter the appearance and values of the content form.

like so:

```
function sswap_content_validation_form_alter(&$form, $form_state, $form_id)
{
if (isset($form['type']) && isset($form['#node']))
{

if ($form_id == 'advertise_node_form')
{

  // Unset the options we don't want user to see.
  unset($form['menu']);
  unset($form['comment_settings']);
  unset($form['revision_information']);
  unset($form['author']);
  unset($form['options']);
  unset($form['path']);

  $form['#after_build'][] = '_surplus_cck_form_alter';

  // we need to tell the form to follow a validation function
  $form['#validate'][] = '_surplus_cck_validation';
  $form['#submit'][] = '_surplus_cck_submit';
    }
  }
}

```

This all works fine and I am able to alter values in the form\_alter section as expected, however once I get to the \_surplus\_cck\_validation custom function I am unable to change values, basically what I am doing is checking if a value is X if not I'll replace it with something more suitable after some processing. At this point I can't even change X to a static string though.

To alter my form content I am using:

```
$form['field_adpostcode']['und'][0]['value']['#value'] = 'TESTING';
$form['field_adpostcode']['und'][0]['#value']['value'] = 'TESTING';

```

These lines do actually work in the form\_alter part as mentioned. I should also note the function for surplus\_cck\_validation is being called I have experimented with a few echos and notices, and the $form and &$form\_state are being passed to it also.

Any help on this would be greatly appreciated I've spent the last few hours trying different things and digging down into the form structure with dsm and debug, but can't seem to find what I need.

# Answer
Perhaps try **$form\_state**.

```
$form_state['field_adpostcode']['und'][0]['value']['#value'] = 'TESTING';
$form_state['field_adpostcode']['und'][0]['#value']['value'] = 'TESTING';

```

I suspect the array structure is different but you get the idea.
> 1 votes

---
Tags: nodes, forms
---


# Question
Title: remove node options from admin area when creating nodes
where creating nodes (node/add/content-type) bellow body box there are some options related to comments, author, menu and ..

How can I hide those options?

# Answer
> 1 votes
You need to create a module and implement **hook\_form\_alter**.

Then, in the **$form** array, **unset** the array index(es) containing the parts you don't want your users to see and configure.

ps: I advice you do the above by permissions. So, those array indexes are unset for specific roles not all roles which would include user#1

---
Tags: theming, 6
---


# Question
Title: Using Fivestar to list items that are 'trending' (highly rated in the last week)
I would like to create a list of items that are 'trending'. By 'trending' I mean nodes (in my case, Watches) that have been highly rated within the last several days. Right now I have a block that displays the 4 highest rated Watches, and would like to create a similar block that displays the 4 highest rated Watches, but only using votes that have been cast within the last 3 days.

For the trending block, I have the following filter criteria (the content type for a watch is Watch Detail):

* Content: Published (Yes)
* Content: Type (= Watch Detail)
* (Vote results) Vote results: Timestamp (\>= -3 days)

The watches are sorted by highest rated using the following sort critera:

* (Vote results) Vote results: Value (desc)

It's a fairly standard view, and I used the Relationship Content: Vote results to access the voting results for sorting and filtering.

The problem with what I've done is that while it is filtering by watches that have received votes within the last 3 days, it is not calculating the average value of the rating on votes that have been cast in the last 3 days. It is using the rating of the watch since the watch node was created. Hence, the Trending block and the Top Rated block essentially are identical, since the rating isn't limited to the last 3 days.

If anyone has done something like this I would very much appreciate some tips for how to limit the calculation the the average vote value to only votes cast within the last 3 days.

See http://ratemytimepiece.com/ for the exact website I'm working on if that helps you visualize this a little better.

# Answer
> 3 votes
Fivestar uses voting API. Voting API stores the individual votes and the total aggregates. You'll either have to create your own aggregates or calculate it "on the fly".

If you have lots of ratings in a week you'll be better off calculating your own aggregates. I would take a look how voting API does the calculation and copy that to your own module. Then modify it to only aggregate votes in the last week.

If you don't have a lot of ratings you can do it in views. Create a view of your type "watch detail". Add relationship "content: votes", require relationship, value type "percent", vote tag (whatever vote tag you are using for those fivestar ratings). Then add filter "votes: value" \>= 80 (gives you all 4 + 5 star ratings), "votes: timestamp" \> "-1 week". Check to make sure you'll see the correct ratings show up.

Now turn on aggregation, add "nid" and use "count distinct" to show the number of ratings for each node. Then sort by that value.

Turn on query caching to make sure the view renders quickly for future requests.

---
Tags: rating
---


# Question
Title: Calendar View of a Field Collections and Contextual Filters
I've clicked my way into a corner. So I have a Field Collection called Performance Dates that is embedded to a Content Type of Performance that looks like this:

I would like to put this into a calendar view, listing all dates (the field collection) from a single performance (the Performance content type).

Since Entity Host ID is not offered as a contextual filter, I was thinking to create a contextual filter on the Field Collection's ID.

My question: If I am going about this the right way, is there a way to return an array of IDs here much like using SQL `where id in (x, y, z)`?

# Answer
Got it. I started out creating a View from a Template.

Then, I decided to use a module called FullCalendar which is super easy to configure.

And here we go!

There is still some configurations to set in place but for the most part, this issue has been solved.
> 0 votes

---
Tags: views
---


# Question
Title: How to easily find whether the contibuted modules have been updated or not?
I am trying to upgrade my project form D6 to D7. I have used several contributed modules in my porject.

I am aware that I should check availability of all the contributed modules in version 7 before starting upgrade process.

In this case I need to check every independent contributed modules seperately whether it is available or not..

My question is:

> Is there any other easy way to check availability of all the contributed modules via programatically or any other modules to do this...

BTW : **Not using drush...**

# Answer
> 1 votes
You could write a web-crawler script which loops through the list of modules and scans the HTML to determine if a 7.x release of the module exist.

But a faster solution would probably be to do the manual check by looking up the module at d.o.

If you don't know if the module has a d7 release or not, you probably want to do a more thorough checkup anyways.

* Is the module stable (is it an alpha, beta, rc or point release)
* is the module used by others
* is the module actively maintained

These questions are very important and would be hard to check for programmatically - so even though a manual look at modules can be a bit tedious it is probably the best solution.

# Answer
> 2 votes
If you are going to attempt an upgrade from D6 to D7, you really should consider using Drush. Really strongly. The Drush Site Upgrade command will save you a lot of time, and as a bonus, it will tell you the upgrade status of your D6 modules, and will recommend alternate modules for some modules with no upgrade path, but for which alternatives exist.

If you really don't want to use Drush, you can use the Upgrade Status module. It also has an upgrade assist block that will help you walk through the upgrade process manually.

---
Tags: updating
---


# Question
Title: altering css / asset weight after it's been added?
I'm using context add assets to add a stylesheet.

It's currently being loaded correctly based on a context; but now it's loading before my global.css stylesheet. I would like blog to load after global.css.

Is it possible to alter the weight of the blog.css stylesheet via preprocessing? If so could you provide an example?

# Answer
> 3 votes
Take a look at `hook_css_alter()`:

```
/**
 * Implements hook_css_alter().
 */
function MYMODULE_css_alter(&$css) {
  $css['sites/all/themes/FUZZYGREYEDOUT/css/blog.css']['weight'] = 10;
}

```

---
Tags: 7
---


# Question
Title: installed memcache, no noticeable improvements
I just installed varnish and memcache on my server. Varnish works great but I don't really know how memcache should perform. I can't see any improvements for authenticated users.

I turned on memcache statistics and saw that it is working but I can't see a noticeable improvements in the page loading time.

Any ideas on how I can improve performance for authenticated users for an existing website?

Thanks, M.

# Answer
I recommend you to try/use Authcache module

http://drupal.org/project/authcache

Make sure to configure it with memcache by adding the following line in your settings file

```
$conf['cache_inc'] = './modules/authcache/api/authcache.inc';

```
> 1 votes

---
Tags: 6, caching
---


title: Add/hide blocks on user page

text:
# Question
Title: Add/hide blocks on user page
I have some blocks for navigation and side bars that are appearing all over the site.

I want to hide the navigation and sidebars on the following urls:

```
node/78
node/19
user
messages

```

For some reason, drupal will hide the nav and side bars on node/78 and node/19 but not the user and messages pages. How do I make it disappear from the user and messages page as well?

What I've done so far was click on Structure\>Block, then go to the block I want, configure it, and list the paths for the blocks I want to hide.

# Answer
I think your solution here is to also include `user/*` and `messages/*` in your list.

So the whole list would read:

```
node/78
node/19
user
user/*
messages
messages/*

```
> 3 votes

---
Tags: blocks
---


# Question
Title: How do I exclude a bunch of nodes from being indexed by Solr?
I want to remove unused nodes from indexing in solr and also I need to make sure that they are not indexed again. I will fetch the list of the unused node IDs using a query.

If any of the nodes is getting updated, then I need to index that node again.

How can I achieve this?

# Answer
For d7 you are looking for the hook: `hook_apachesolr_exclude`

Example from the apachesolr.api.php

```
/**
 * This is the place to look for the replacement to hook_apachesolr_node_exclude
 * You should define a replacement for the status callback and return
 * FALSE for entities which you do not want to appear in the index and TRUE for
 * those that you want to include
 */

/**
 * This is invoked for each entity that is being inspected to be added to the
 * index. if any module returns TRUE, the entity is skipped for indexing.
 *
 * @param integer $entity_id
 * @param string $entity_type
 * @param integer $row
 *   A complete set of data from the indexing table.
 * @param string $env_id
 * @return boolean
 */
function hook_apachesolr_exclude($entity_id, $entity_type, $row, $env_id) {
  // Never index media entities to core_1
  if ($entity_type == 'media' && $env_id == 'core_1') {
    return TRUE;
  }
  return FALSE;
}

```

See here: http://drupalcontrib.org/api/drupal/contributions%21apachesolr%21apachesolr.api.php/7

**UPDATE**

For deleting certain nodes (entities) you can use `apachesolr_remove_entity`.
> 6 votes

# Answer
If you're comfortable writing your own modules, there's a hook that can help you exclude certain nodes from the index: **hook\_apachesolr\_node\_exclude($node, $namespace)**.

This is invoked by the apachesolr module for each node that qualifies to be added to the index. If the function returns TRUE, the node is **skipped** for indexing. However, nodes which are already index will not just be removed because of the TRUE return value. That only prevents nodes from being added. You'll have to clean up your index by calling **apachesolr\_delete\_node\_from\_index()**.

See the here for additional information: http://api.drupalhelp.net/api/apachesolr/apachesolr.api.php/function/hook\_apachesolr\_node\_exclude/7

Hope this is enough to get you started!

There were some modules in Drupal 6 to help with this, such as http://drupal.org/project/apachesolr\_exclude, but I don't know of any good ones for Drupal 7.
> 2 votes

# Answer
In Solr configuration at "admin/settings/apachesolr/content-bias" you can set the content types to exclude from the search index.
> -1 votes

---
Tags: 7, nodes, search
---


title: Allow a role to create users

text:
# Question
Title: Allow a role to create users
I'm looking for a way in which we can assign a select role, the ability to create, edit, and delete users within another role. While its possible to use the "Administer Users" permission for this, it opens up the parties who will be assigned with this role to do all sorts of bad things. Ideally, we would like to limit to what role of user this faux administrator is able to excise.

We've explored using some of the options here, such as Administer Users By Role with some patches to the core User module (I know, but it was outside of my decision) with no success.

# Answer
Use the Subuser module. This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created.
> 0 votes

---
Tags: users
---


title: Disable user_node_load

text:
# Question
Title: Disable user_node_load
Is there a way to disable user\_node\_load on non-admin pages without hacking core modules? My theme doesn't use user data so this function results in needless database queries.

# Answer
### Disclamer

I am using a hook in a way that is different from the usage that is documented on Drupal.org API. See the notes at the end of the question.

You could achieve what you want by implementing two hooks:

* hook\_module\_implements\_alter()

```
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_load') {
    unset($implementations['user']);

    // Put mymodule_node_load() to the beginning of the list.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations = array('mymodule' => $group) + $implementations;
  }
}

```
* `hook_node_load()`

```
function mymodule_node_load($nodes, $types) {
  if (path_is_admin($_GET['q'])) {
    $uids = array();
    foreach ($nodes as $nid => $node) {
      $uids[$nid] = $node->uid;
    }

    $user_fields = db_query("SELECT uid, name, picture, data FROM {users} WHERE uid IN (:uids)", array(':uids' => $uids))->fetchAllAssoc('uid');

    // Add these values back into the node objects.
    foreach ($uids as $nid => $uid) {
      $nodes[$nid]->name = $user_fields[$uid]->name;
      $nodes[$nid]->picture = $user_fields[$uid]->picture;
      $nodes[$nid]->data = $user_fields[$uid]->data;
    }
  }
}

```

The code I used for `hook_module_implements_alter()` is different from the example code shown in the documentation, which just alters the order in which different implementations of the same hook are invoked.

```
function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'rdf_mapping') {
    // Move my_module_rdf_mapping() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

```

In general, it is not a good idea to avoid a hook implemented from another module is invoked. Modules that change their behavior because a hook implemented from another module is invoked normally use module\_exists(), rather than module\_implements(), which means those modules normally make the assumption that the module being enabled is sufficient for that specific hook to be invoked.
Generally speaking, there could be modules that depend from the data injected from the hook you are trying to block. It is not said that avoiding `user_node_load()` executes its SQL queries would avoid another module executes its own SQL queries with a decrement of performance even worse.

If you are sure that none of conditions I described are verified, you could implement the code I shown, at your own risk. Be prepared to verify there aren't any unwanted consequences, and check what the code used by the modules you use in the site is doing.
> 5 votes

# Answer
I think you're out of luck here (I'd love to be proven wrong though).

You can stop the hook from running with `hook_module_implements_alter()`, but the only way I can think of making that happen only on non-admin pages would incur quite a performance hit.

The return from that hook is cached so you'd pretty much have to flush the caches on every page to make that method work (so the cache could be regenerated and your implementation of the hook could check the current path).

Either way a code example for this would be something like:

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_load') {
    unset($implementations['user']);
  }
}

```

You'd need to add your condition in there, but that's the basic code. The proof that this works is in the following error message that appears on all node pages, as my theme has a requirement for the data added by `user_node_load()`:

Commenting out the `unset()` line and clearing the caches removes the error message, confirming the function's success.

There are some awful methods I can think of involving subclassing the `NodeController` class and overriding its `attachLoad()` method to become path aware...but you really don't want to go down that path.
> 2 votes

---
Tags: performance
---


title: views field php condition

text:
# Question
Title: views field php condition
I use drupal6 and UC2. I am working on a view which exports order details into an excel file such as - address and total order amount. Total amount field is crucial for me - Would it be possible to use views php and check if payment method is COD then get total amount. If payment method is different than COD then result would be nothing or 0?

Thank you

# Answer
You can certainly do that. If you setup a view and tell it to grab Ubercart Order data it will allow you to access information on orders such as the payment type, amount, order id, etc.

So if you grab the following information you'll be set to feed it into the Views PHP field.

1. Payment Method
2. Order Total (Exclude this from the display)

Then if you add the Global: PHP field you need to put the following into the Value code field:

```
if ($data->uc_orders_payment_method == "cod") {
  return number_format($data->uc_orders_order_total, 2, '.', ',');
} else {
  return number_format(0, 2, '.', ',');
}

```

And this in the output code field:

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

```
> 1 votes

---
Tags: views, entities
---


# Question
Title: How to wrap a custom content page with HTML tags?
I have a mini-panel in which I add custom content panes. I would like to turn these content panes into buttons. I am able to apply some CSS to turn them into a block, by adding a css class via the "CSS properties" option in each pane's settings. But how can I make a link out of them?

There is no option to add HTML around a pane. And I really want the entire pane to be a link, not just the stuff in it. I could artificially insert HTML into the pane to create a link-block that would fill up all the space, but then I'd have to create other CSS properties to apply to this element, it would just be cumbersome.

I'm still on Drupal 6. Any help would be appreciated.

# Answer
> 0 votes
Could you put an `<a>` tag inside the pane, and then with CSS give it a `width: 100%` and `height: 100%`, effectively filling the mini-pane?

To be specific, your html inside the pane would look like:

```
<a class="mini-pane-link" href="#">This Is A Link</a>

```

And your CSS would look like:

```
a.mini-pane-link {
    display:block;
    width: 100%;
    height: 100%;
}

```

(You might want/need to put a few extra selectors in front of the `a.mini-pane-link`)

---
Tags: panels, theming
---


title: From where d7 render comment_form

text:
# Question
Title: From where d7 render comment_form
Can i know from where drupal core render `comment_form`
Actually what i mean is what is the location of file which bear `comment_form` ..In my d7 folder , i am now testing it on localhost win7.
I want to know it so that i can easily do change in comment form texts, do change in comment buttons, is this possible?

# Answer
@rakibtg, To change the comment button text you are not supposed to change any comment module which is available in the core. Simply Never hack Core!!!

For your question, to change the comment button text,

1.You need to write up a custom module with hook\_form\_alter,

```
  function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id) {
     $form['actions']['submit']['#value'] => t('Post Comments');
 }

```
> 1 votes

# Answer
you have to use hook\_form\_alter() for altering your `comment_form`.

If you are altering the comment\_form only use below mentioned code in you own custom module.

```
 function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'comment_form'){
     $form['actions']['submit']['#value'] => t('Post Comments');
   }
 }

```
> 1 votes

---
Tags: 7, comments
---


title: Save comment dynamically

text:
# Question
Title: Save comment dynamically
I've made my own module to add commenting to a node (it opens modally in a colorbox - really nice). The form works great, but how do I save the comment?

I know it's got to be done using comment\_save. But, as usual, drupal.org is great at showing the code for the function without giving an example...

Has anyone done this before?

I'm guessing it's something like:

```
$comment = new stdClass();

$comment->nid = $the_node_the_comment_is_for;
$comment->title = $my_comment_title;
$comment->body = $my_comment_body;

comment_save($comment);

```

# Answer
Yes you can save comment dynamically using comment\_save() function, a working example is given below

```
<?php

$comment = new stdClass();

$comment->nid = 28; // nid of a node you want to attach a comment to
$comment->cid = 0; // leave it as is
$comment->pid = 0; // parent comment id, 0 if none
$comment->uid = 1; // user's id, who left the comment
$comment->mail = 'email@example.com'; // user's email
$comment->name = 'User name'; // If user is authenticated you can omit this field, it will be auto-populated, if the user is anonymous and you want to name him somehow, input his name here
$comment->thread = '01/'; // OPTIONAL. If you need comments to be threaded you can fill this value. Otherwise omit it.
$comment->hostname = '127.0.01' ;// OPTIONAL. You can log poster's ip here
$comment->created = time(); // OPTIONAL. You can set any time you want here. Useful for backdated comments creation.
$comment->is_anonymous = 0; // leave it as is
$comment->homepage = ''; // you can add homepage URL here
$comment->status = COMMENT_PUBLISHED; // We auto-publish this comment
$comment->language = LANGUAGE_NONE; // The same as for a node
$comment->subject = 'Comment subject';
$comment->comment_body[$comment->language][0]['value'] = 'Comment body text'; // Everything here is pretty much like with a node
$comment->comment_body[$comment->language][0]['format'] = 'filtered_html';
$comment->field_custom_field_name[LANGUAGE_NONE][0]['value'] = 'Some value'; // OPTIONAL. If your comment has a custom field attached it can added as simple as this // preparing a comment for a save

comment_submit($comment); // saving a comment
comment_save($comment);
?>

```
> 5 votes

---
Tags: 7, comments
---


# Question
Title: Using views how to display taxonomy term description in D6?
How can I display taxonomy term description next to taxonomy term in a views field?

# Answer
Create a new view of the type 'Term'. (D6: Select Term radio button while adding new view, D7: Choose Taxononomy Terms in 'Show' select box)

Then choose the fields

```
Taxonomy: Term Term
Taxonomy: Term description

```

that's it, and you can choose a suitable Style for the display
> 1 votes

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


# Question
Title: Context.module fires blocks on access denied pages. How do I stop this?
The context.module fires block regions on the access denied page if the condition for the context is path. I don't have much of a choice in triggers other than path for these pages. How to do I disable the side blocks? Is doing a page redirect to a custom 403 page a better idea?

# Answer
Use Context Error, and set the proper condition.
> 0 votes

---
Tags: 7
---


# Question
Title: Require visitor to fill a form to view contents
How can I require visitors to fill in a form if they want to view certain pages?

# Answer
> 1 votes
I don't have experience with the Webform module, but I think that you could create a rule to grant access to a referenced node when the user submits the form.

Basically, you need to add an entity reference field to the webform content type, reference the webform with the particular node, and create a rule that on the form submission event grants the current user access to the referenced node. In Content Access and ACL, you should set the access per-node and per-user.

You'll need Entity reference, Webform, Rules, Webform Rules, Content Access and ACL modules.

---
Tags: 7, forms
---


title: Views get OG mixed information

text:
# Question
Title: Views get OG mixed information
Im trying to create a view that will get the following:

```
Organic group: Name.
Organic group: Members.
Organic group: Number of published nodes.

```

Its sounds like an easy task but really it isnt. I got really confused with the type of view, and theres much relationships to be done, And after adding aggregation the view gets huge and frustrating.

I was thinking about creating each one as a separated view and embedding them on a page, but that might sound bad.

**UPDATE** here is whats expected of the view to produce.

```
Organic group: Group A.
Organic group: X, Y, Z.
Organic group: 3 open tasks.

Organic group: Group Alpha.
Organic group: Alpha, Beta, Gamma.
Organic group: 0 Open tasks.

Organic group: Power rangers.
Organic group: Green dude, White dude.
Organic group: 15 open tasks.

```

Tasks being the content type that belongs to an OG. Any help is greatly appreciated.

# Answer
You are using Organic group module. So this module also provides two views called **Og members** and **Og Content**. Now download the module Views Field View which allows you to embed views as field in other view. See the Readme.txt file for more detail.

Create a new view and embed other two views **Og members** and **Og Content** in new view.
> 1 votes

---
Tags: 7, views, organic-groups
---


title: db_update doesn't work with my code

text:
# Question
Title: db_update doesn't work with my code
Whith a custom module, I'd like to update some nodes uid whenever a content type is updated. I triple checked, and my database update function is called, as "changed" field is updated each time, and I send myself a mail to check that the data passed is correct.

I don't know how to call the equivalent of `mysql_query() or die()`, and don't manage to debug that.

I have only a notice:

> Undefined index: #language dans `locale_field_node_form_submit()`.

```
function zen_custom_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  switch($form_id){
    case 'lieux_de_pratique_node_form':
      if (in_array('Admin dojos', array_values($user->roles))) {
        // some stuff
        $form['#submit'][]='set_dojos_manager';
        // ...
      }
      // ...
  }
  // ...
}

function set_dojos_manager($form, &$form_state) {
  $dojo_editeur = $form['field_dojo_editeur_web']['und'][0]['uid']['#default_value'];
  $dojo = $form['nid']['#value'];
  $uid_updated = db_update('node')
    ->fields(array(
      'uid' => $dojo_editeur,
    ))
    ->condition('nid', $dojo)
    ->execute();

    mail('my_email', 'test', $dojo_editeur . ' / ' . $dojo);
  }
}

```

# Answer
So this is the way I solved it. I had to deactivate the *uid content type* synchronize. I added **hook\_node\_presave()** for insert nodes cases. I also assigned a role to the new user *uid* :

```
function zen_custom_node_update($node){
  switch($node->type){
    case 'lieux_de_pratique':
      global $user;
      if (in_array('Admin dojos', array_values($user->roles)) || in_array('administrator', array_values($user->roles))) {
        $dojo = $node -> nid ;
        $dojo_editeur = $node -> field_dojo_editeur['und'][0]['uid'] ;
        db_update('node')
          ->fields(array(
            'uid' => $dojo_editeur,
          ))
          ->condition('tnid', $node->nid) //update all translations
          ->execute();
        //drupal_set_message($node->nid . ' node_update case:translated');
        $recipient = user_load($dojo_editeur);
        user_multiple_role_edit(array($recipient -> uid), 'add_role', 11);
        drupal_set_message( 'Le compte <em>'. $recipient-> name . '</em> est éditeur de <em>' . $node -> title .'</em>');
      }
      break;
  }
}

function zen_custom_node_presave($node){//necessary for creating the first node of the translation set
  switch($node->type){
    case 'lieux_de_pratique':
      global $user;
      if (in_array('Admin dojos', array_values($user->roles)) || in_array('administrator', array_values($user->roles))) {
        $dojo_editeur = $node -> field_dojo_editeur['und'][0]['uid'] ;
        $node -> uid = $dojo_editeur;
        $recipient = user_load($dojo_editeur);
        user_multiple_role_edit(array($recipient->uid ), 'add_role', 11);
      }
  break;
  }
}

```
> 0 votes

# Answer
Your form submission handler should take the submitted values from `$form_state['values']`, not `$form`. The node object is then available in `$form_state['node']`.

For such task it would be better to implement hook\_node\_presave(), which is called right before a node is saved.
> 4 votes

---
Tags: database
---


# Question
Title: Bulk opening of several node edit screens
is there a way to open up several nodes to edit at once? At `/admin/content` I can mark all of the nodes that I want to edit, but I still have to click each edit link individually.

Is this something that I could do by adding an action to the "Update Options" dropdown?

**Edit**
The reason for the mass editing is that I have added a new field to a content type. I would like to add unique values to that field for preexisting nodes.

# Answer
> 3 votes
As far as I am aware, no module will do this out of the box. However in saying that there is a potential solution in:

1. Installing Views Bulk Operations (VBO)
2. Writing a custom action that happens on each selected node

From the VBO page:

**How can I write an action that performs a function on all selected nodes AT ONCE?**

You need to write a node operation instead of an action. Whereas actions get called *once for every selected node*, node operations are called once only, and they are passed an array of selected nodes. Check out sirkitree's article for the same concept applied to user operations. Note: If you use Batch API to execute your actions, VBO will revert to calling the action once per node instead. This is because it doesn't make sense to batch one single action.

# Answer
> 1 votes
Edit view used to allow you to do this, although it hasn't officially been ported to D7 yet, although I believe work has started on that.

Essentially it allows you to build a view which exposed fields of your choice which you can edit all at once.

---
Tags: 7
---


# Question
Title: How to set the default language in code?
I want to set the default language during install to something other than English. How?

# Answer
A profile install hook that enables and sets Swedish.

```
/**
 * Implements hook_install().
 */
function hook_install() {
  // Enable swedish.
  locale_add_language('sv');
  $languages = language_list();
  variable_set('language_default', $languages['sv']);
}

```

Since `language_default` is a variable, it could also be Strongarm managed.
> 2 votes

---
Tags: i18n-l10n
---


title: Entity Filtering mechanism

text:
# Question
Title: Entity Filtering mechanism
I've come to face this issue time and again and I haven't yet found a solution without having to compromise something.

This scenario applies both to admin and front end.

There seems to be a lack of an efficient way to filter Entities according to some of their properties and/or fields.

In my example I'll use Users as my entity.

In multiple occasions I've had to filter users. Either to reference them to a node (entity reference), or to perform a bulk operation (front end - invite them to something or send them an email, doesn't really matter). The requirement would be pretty much the same: A view-like presentation with exposed filters that would allow for an operation to be performed to the selected Entities.

I am aware of Views Bulk Operations but even that lacks flexibility in this aspect, as it "resets" the form in each trigger of the exposed form.

If, I wanted to send an email to all the "Johns" and "Marys" on my user base, I'd have to filter against "John", select the users that are presented to me, and then filter against "Mary", select all the users that are presented to me, again, and then, either press the submit button or reset the filter to preview my selection.

Thing is that after the (ajax or not) exposed filter submission, the "John" checkmarks are lost, and if I Clear the exposed form, so are the "Mary" checkmarks.

The exposed form submission simply fetches a "fresh" view-form with it's rows filtered accordingly.

On the backend (entity reference) there seems to be some work by the entityrefence\_view\_widget module but it's still in the makings.

My question would be: How do you tackle such an issue when you face it in your projects? Is there a way I am not aware of?

# Answer
> 0 votes
Customized as it may be, it worked:

Using VBO and performing a `hook_form_alter` onto the exposed filter form I was able to add a hidden field.

Using javascript, I store the values of the selected entities (derived from the checkboxes attributes) into the hidden field. If the user triggers the exposed form submission, the values remain and on the new page load I use the same values to recheck the checkboxes thus providing the illusion that the values got preserved.

Downside is the unavoidable use of javascript and the possible huge URL.

If anyone has anything better to propose or make the exposed form NOT place it's parameters as $\_GET parameters in the url I'd be glad :)

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


title: Administration theme for certain roles

text:
# Question
Title: Administration theme for certain roles
How do I force certain roles to use exclusively administration theme? These roles are only allowed to add content in administration and there is no problem for that. But some pages, like the user profil page, still use the front office theme and I need them to always use the administration theme. Any good solution for that?

Thanks

# Answer
> 1 votes
You might want to look into the hook\_admin\_paths function where You can define the pages that should use the administration theme.

For this to work on specific roles just use something like:

```
function mymodule_admin_paths() {
  global $user;
  if(in_array('administrator', $user->roles)) {
    //Make the changes for the administrator
  }
}

```

---
Tags: 7, users
---


# Question
Title: How to attach username at the end of url?
Suppose I have a site www.example.com with many users in it. Now user "abc" is logged in, then the username should be attached at the end of that URL, like: www.example.com/abc

Also I have fix content on my website e.g. about us , contact us etc. Now if I go to the "about us" content then the link should be : www.example.com/abc/contact-us

# Answer
> 1 votes
Try this:

go here: admin/config/search/path/patterns

and add: /\[user:name\]

to your replacement patterns.

---
Tags: uri
---


# Question
Title: How to manage translations when a site is being re-installed frequently?
Sites built on a profile, will, during it's early development experience frequent re-installs.

If a translator makes changes to a site, these will get lost when the database is dropped.

What options are there for handling this, in a way that survives re-installs?

# Answer
> 0 votes
The only way is to make a copy of the translation options.

I'm not sure if a hook\_cron or a drush can donwload the files, if not the only way is to donwload and them copy into ../profiles/myprofile/translations/\*.po

---
Tags: i18n-l10n
---


title: Hierarchical Taxonomy list pages

text:
# Question
Title: Hierarchical Taxonomy list pages
I'm developing a site which has 3 levels of taxonomy terms, something like:

Products -\> Subcat1 -\> Subcat2 -\> Item

I've created a view with a page for the taxonomy vocabulary which has a contextual filter configured when a filter value is not in the URL to use the fixed value ''. This page displays the first level of taxonomy terms as expected which is great, however I would like to link the first level to the next level of terms but after 3 days of trying I'm still no closer to figuring it out.

Can anyone shed any light on how this can be achieved? I'm still learning Drupal so it's more than possible I've missed something obvious.

So essentially what I'm after is this:

Top-level page:

```
Fruits
Nuts
Sweets

```

Clicking on fruits shows:

```
Citrus
Non-citrus

```

Clicking on Citrus shows:

```
Lemon
Lime

```

The final page above is a list of actual content items, not taxonomy terms. I hope that makes sense.

# Answer
So i have similar issue, and i solve this by creating 2 views. First view show taxonomy terms and i group them by theirs parents (add relationship Taxonomy term: Parent) Second View is override on taxonomy/term/% and i add more Context (Arguments) for each level add an argument, and finally i add into header another view, who shows only children terms of current term.

You can view my work at http://www.attorney-directory.net/practice-areas
> 2 votes

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


# Question
Title: How to make a parent - child taxonomy list
How can I make a category page displaying all my 100+ taxonomy terms in a parent/child way (something just like http://www.dmoz.org/)?

```
-parent
--child
--child
-parent
...

```

# Answer
> 2 votes
Yes above answer works, but parent terms are showed at top of view, so it's nice to remove them. I use Views Hacks module , and only check Selective Exposed Filters. For filter select Taxonomy term: Parent (selective) and choose is not one of all You can view my view at http://www.attorney-directory.net/practice-areas

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


title: How to get database credentials

text:
# Question
Title: How to get database credentials
I am integrating code that implements its own extension of PHP's PDO class, in the same way that Drupal's DatabaseConnection does. So this code (which is various data models) needs to use this non-drupal PDO object.

This code needs DSN, username and password to access the default drupal database. I noted that `$databases`, defined in `settings.php` is not available: `global $databases` does not work to give me access to that data.

Is there a way to ask Drupal for this info or extract it from the default connection object?

# Answer
The following works perfectly for me in *devel/php*

```
global $databases;

dpm($databases);

```

It should return the full array of database information:
> 11 votes

# Answer
As shown by Chapabu `global $databases` does work but it wont work if you are using a separate PHP file (not related to Drupal Codebase), if you want to use it like that you need to `include settings.php` file before.
> 3 votes

---
Tags: 7, database
---


# Question
Title: Set the custom initial date on FullCalendar based on a field in the current node
I would like to populate the *custom initial date* based on a field in the current node. Is this possible?

(bigger)

## Update after looking at the module code

I snooped around the module code and noticed the line below.

```
if (!empty($settings['times']['default_date'])) {
    $settings['date'] = $settings['times']['date'];
}

```

(bigger)

## Update 2: Hard coded test

Well this looks possible, I hard coded a test and it appears to have worked. The next step is to pull this value from a Node Field.

```
 // First, use the default date if set.
  dsm($settings['times']);
  if (!empty($settings['times']['default_date'])) {
    //$settings['date'] = $settings['times']['date'];
    $settings['date'] = array(
      'year'=>2012,
      'month'=>1,
      'day'=>2
    );
  }

```

*Edit from file ./includes/fullcalendar.fullcalendar.inc near line 629*

# Answer
> 0 votes
So this and two additional Content Node Fields edit worked for me. Starting around line 629 in `includes/views/fullcalendar.fullcalendar.inc`, I changed to the following. Don't forget to add two additional fields to your Content Type with machine names **`field_default_calendar_year`** and **`field_default_calendar_month`**.

Update on project's issues list: Patch Submitted, Requested Review

See Patch code: http://drupal.org/files/fullcalendar-7.x-2.x-custom\_init\_date\_1.patch

---
Tags: javascript
---


title: Results of a Views display as an array

text:
# Question
Title: Results of a Views display as an array
With Views in D6, I was able to get the results of a Views display as an array and work with it using php code embedded in a node.

For example, using this code snippet:

```
$view = views_get_view('view_name', 1);
$view->set_display('block_1');
$view->preview();
$MyArray = $view->result;

```

This allowed me to get the results of the 'block\_1' view display into the $MyArray array.

However, I'm trying to do the same thing in D7 and all I'm getting is a list of all the nodes in the view I'm calling, and not the results of the view display.

How do I get the results of a view display in code for D7??

# Answer
I think it has been replaced by the `views_get_view_result()` function. It returns:

> An array containing an object for each view item.

e.g.

```
$result = views_get_view_result('view_name', 'block_1');

```
> 5 votes

---
Tags: 7, views
---


# Question
Title: Why does using '#type' => 'text_format' change the position of the field's description?
I have a form with a text field which looks like this:

```
$form['myTextField'] = array(
    '#title' => 'Write here',
    '#type' => 'text_format',
    '#format' => 'filtered_html',
    '#description' => "Description goes here")
);

```

Now I would like the description to appear bewteen the title and the field, so I tried the technique described here. It works for all the other fields, but not for this one. I can make it work by changing the above code to this:

```
$form['myTextField'] = array(
    '#title' => 'Write here',
    '#type' => 'textarea',
    '#description' => "Description goes here")
);

```

The downside of this approach is that I end up with a plain old textarea instead of a `text_format`, which is what I need.

Any ideas as to why the description appears below the field rather than above it when I use `'#type' => 'text_format'` as opposed to `'#type' => 'textarea'`?

# Answer
`text_format` is not a single form element that is rendered like textarea, textfield checkbox etc. Instead, it is several form elements (you get two form elements, one to select the filter, and a textarea to enter the actual text).

What you need to do is use the `#after_build` property to define a function that will enable you to alter the element after it has been built (the two form elements has been created). You can define custom theme function here and move data around in order to output the description and other data exactly how you want to.

Look at the FAPI documentation for more info.

### Update

The `#after_build` on text\_formats works a bit differently than expected, as it gets called twice. What you could is:

```
$form['text_format'] = array(
  '#type' => 'text_format',
  '#title' => t('Body'),
  '#my_description' => t('The text you enter here appears on the page.'),
  '#after_build' => array('after_build'),
);

```

And then

```
function after_build($element) {
  if ($element['#type'] == 'textarea') {
    $element['#description'] = $element['#my_description'];
  }
  return $element;
}

```

The idea is that you create a value for the fake description and convert it to the real description on the text area. What will happen with the normal description value is that is will be added to the filter form element only which is why your theme overrides doesn't work.
> 3 votes

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


# Question
Title: listing users filtered by whether they have posted content or not
I've been fiddling with the filters in views but none of the filters seem to work on if they posted content or not.

Is custom code necessary for this?

# Answer
> 1 votes
Have you tried using Relationships instead? **User:Nodes authored** might be what you are looking for.

---
Tags: 6, views
---


title: Problem with adding content

text:
# Question
Title: Problem with adding content
I allow my administators to add panels, articles, blog posts, forum topics, etc but it only shows the default set that regular users get which is blog posts and forum topics. Ive checked and all the people are set to admin. How do i fix this?

# Answer
You need to go into People -\> Permissions -\> Roles. Find the administrator role and click on 'Edit Permissions'.

Then, go down to the Node section, and check off the appropriate permissions for viewing, creating, editing, deleting, etc.. that particular content type. The permissions actually look like this:

```
Article: Create new content [ ]
Article: Edit own content   [ ]
Article: Edit any content   [ ]
Article: Delete own content [ ]
Article: Delete any content [ ]

```

You'll of course want to check off probably all of those if the role is an administrator, as typically they'll have absolutely power over your application. That is, if it's what you intend. The power of Drupal is yours :)
> 1 votes

---
Tags: nodes
---


# Question
Title: 'Create new book' in Drupal 6 won't create, only shows loading icon
Through the admin, Anytime I try to create a new book in Drupal via 'Create Content' \> Book page and select '', the loading icon hangs there. When I save the entire page, it creates the page but it doesn't add it to the new book. Going to the list of books does not show the new book either. So, the object isn't being created.

I have feeling this could be a frontend error, but I'm not really sure where to start. I checked the Javascript error console and no errors there, so...

I've attached a screenshot for more context.

I am not going to upgrade to Drupal 7, if someone suggests this.

Maybe there is a way to programmatically create a new book until I figure out what the problem is.

# Answer
> 0 votes
I found the problem. We had to disable the jQuery update module, but it breaks stuff on the frontpage.

---
Tags: 6, nodes
---


# Question
Title: Automatically backing up uploaded files?
One of the news sites I'm developing is heavily reliant on its image database, which has been migrated from the old site and is ~15-20gb at this point.

It's dawned on me that it would be really bad if there was some sort of server malfunction and all of the images in that directory were lost -- they're generally created on-the-fly by one person every week from much higher-resolution versions that have been pushed so far back into a totally-disorganized archive that it would take ages to resize and upload them all again (Which isn't even going into the awful process that would be re-adding them to the site's ~15,000 article nodes).

To this end, I'm looking for a way of backing up the uploaded images folder in sites/default/files. One thought I've had is to use Subversion's WebDAV Autoversioning capability, though I'm not overly sure how I'd get the Drupal 7 filefields to use this.

I could also just write a script to rsync files between two servers once a night -- the newspaper's office has a few servers for that sort of thing.

Any thoughts what a good backup solution would be for this particular situation?

Thanks!

# Answer
I have not been in the situation before, if I were in your shoes I would take a look at the CDN module.

In **File Conveyor mode** (ie, a push model), it will automagically copy files up to your CDN of choice. A side effect of this is the fact that the files will now live in two places. You can go with one of the commercial CDNs, or you can set up your own with another server.
> 1 votes

# Answer
> > I could also just write a script to rsync files between two servers once a night -- the newspaper's office has a few servers for that sort of thing.

I'd suggest this option, as it seems you have thousands image files, so any php/drupal solution will be slow and may affect your server's performance. Rsync is pretty fast after the initial copy, so you can just run it every 10 minutes. Also, you can should copy to more than one server - minimum two other backup servers.
> 0 votes

---
Tags: backups, version-control
---


# Question
Title: Drupal 7 html.tpl.php vs page.tpl.php variables questions/thoughts
First off I am very new to Drupal but not very new to other frameworks and CMS's (symfony, cake, codeigniter, wordpress)

So I am trying to make a theme and it seems like I want to put a lot more stuff in html.tpl.php then drupal wants me to?

Like for example $logo, why is that not available in html.tpl.php, I don't want to include that in every variation of the page template, do I?

Or should I be thinking of page.tpl.php more as the wrapper than html.tpl.php.

I basically think the page template should only display content for that page, anything around that (ie, nav, logo, footer) should be in html.tpl.php. but drupal seems to be set up opposite? Why does this feel wrong to me?

# Answer
> 3 votes
Something to keep in mind is that Drupal doesn't work with templates the way a traditional MVC framework will. Ideally you want to have as few templates as possible in your theme, i.e having only one page.tpl.php with some conditionals would be best. If you do need to split things up you can define additional templates with hook\_theme() in your theme's template.php and move your header/footer section into there, but in general you'll have better results by not having lots of template variations.

---
Tags: theming
---


# Question
Title: Inserting additional AJAX using hook_flag
I'm trying to insert additional AJAX commands when a Flag link is toggled. The flags link type is 'JavaScript toggle'.

Hooking into the Flag callback seems simple enough using hook\_flag.

```
function hook_flag($op, $flag, $content_id, $account, $fcid) {

    if ($flag->name == 'flag_name') {
        // Additional Ajax Commands
    }

}

```

The AJAX command I'm looking to include is:

```
ajax_command_replace("#div_id_to_replace", 'New content');

```

Is it possible to insert AJAX using hook\_flag? If not, what would be the most appropriate way to swap out div content (in addition to the actual Flag AJAX) without a page reload when a Flag link is toggled?

Update: Found the Flag API (JavaScript) page while crawling through the docs. Hopefully will have an answer to add shortly.

# Answer
I'm certain there is a better way to do this, but rather than using hook\_flag use JavaScript.

The trick seems to be to use `bind('flagGlobalAfterLinkUpdate', function(event, data)`

And then catch the specific flag you're using with `data.contentId;`

```
(function ($) {
    $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
        var fsrnid=data.contentId;
        var fsrpostcard = $(".postcard-" + fsrnid).text();
        var fsrpostcardset = fsrpostcard.indexOf('Yes') >= 0;
        var fsrcalled = $(".flag-customer-called-" + fsrnid).text();
        var fsrcalledset = fsrcalled.indexOf('Yes') >= 0;
        var fsremail = $(".flag-email-sent-" + fsrnid).text();
        var fsremailset = fsremail.indexOf('Yes') >= 0;

        if (fsrpostcardset || fsrcalledset || fsremailset) {
            $(".completed-" + fsrnid).text('Yes');
        } else {
            $(".completed-" + fsrnid).text('No');
        }

    });
}(jQuery));

```

The Flag API (JavaScript) documentation is a bit dated and doesn't necessarily apply directly to Drupal 7. It is still very useful in figuring out how the Flag module uses JavaScript though.
> 2 votes

---
Tags: ajax, flags
---


# Question
Title: Using hook_form_alter in overlay admin theme
I am using hook\_form\_alter in a custom module to remove some fields from the block edit screen to clean up the ui for users of a certain role

```
function module_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (in_array('staff member', $user->roles)) {
    $form['visibility_title']['#access'] = FALSE;
    $form['visibility']['#access'] = FALSE;
    return $form;
  }
}

```

It works great. However, when the form appears in Drupal's admin overlay using the site's admin theme, Seven, the above code is not applied.

Is this because it's in an overlay? Or because it's a different theme? How can I get the hook\_form\_alter to apply globally?

FWIW, adding

```
function module_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

```

doesn't print anything above the form in the overlay. But when I switch the admin theme to the site's theme, it properly dpm's the form.

Note: The custom module and the site's custom theme have the same name. Is this the problem?

# Answer
> 3 votes
Thanks to Clive's tip I realized that because my module and theme had the same name, the hook was being applied at the theme level. I renamed my module and now it works!

---
Tags: 7, forms
---


# Question
Title: Pressflow 6 forms creating session cookies
We have a Pressflow 6 website behind a Varnish cache but our cache hit-rate is awfully low. I've recently found that stripping the "Cookie" header from requests completely increases the hit-rate to 97-98%.

The vast majority of our users are anonymous, so Pressflow shouldn't be setting a session cookie, however we do have a number of forms on the site and it seems that when someone uses a form a session cookie is set in their browser. The forms aren't fancy, the page they submit to just says "thanks for your comment" so there's no need for a session as POST requests aren't cached anyway. The cookie's lifetime is about a month and a half too.

I was considering stripping the cookies when there's no "DRUPAL\_UID" cookie, however I'm loath to remove them all in case there's a legitimate reason for them being set.

So, two questions:

1. Is there a legitimate reason for these cookies being set?
2. If not is my best option to get Varnish to strip them out or is there a way to prevent them from being set or to remove them within Pressflow?

# Answer
```
// Default backend definition.  Set this to point to your content
// server.
//
backend default {
  .host = "127.0.0.1";
.port = "81";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
// enable to use status script for health of backend
//  .probe = { .url = "/status.php"; .interval = 5s; .timeout = 1s; .window = 5;.threshold = 3; }
}

//
// BOOSTED VARNISH - by Trellon, LLC
//
// - Based on a configuration by Lullabot and VCL examples for Varnish Wiki.
//
// Logic is:
//
// * Assume: A cookie is set (we add __varnish=1 to client request to make this always true)
// * If boosted URL -> unset cookie
// * If backend not healthy -> unset cookie
// * If graphic or CSS file -> unset cookie
//
// Backend response:
//
// * If no (SESSION) cookie was send in, don't allow a cookie to go out, because
//   this would overwrite the current SESSION.

// Respond to incoming requests.
sub vcl_recv {

////// START BOOST Logic (Prerequisite)
  // We always send a cookie, so that empty requests are
  // handled by below boost logic, too.
  set req.http.Cookie = ";__varnish=1;" req.http.Cookie;
////// END BOOST Logic (Prerequisite)

// Enable to disable varnish
//      return (pipe);

////// START DEFAULT RULES
 // -------- CloudFlare ----------
  remove req.http.X-Forwarded-For;
  if (req.http.CF-Connecting-IP) {
    set req.http.X-Forwarded-For = req.http.CF-Connecting-IP;
  } else {
    set req.http.X-Forwarded-For = client.ip;
  }

  // Remove a ";" prefix, if present.
  set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
  set req.http.Cookie = regsub(req.http.Cookie, "^__\s*", "");
  set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|cfduid)=[^;]*","");
  // -------- CloudFlare ----------

 if (req.request != "GET" &&
    req.request != "HEAD" &&
    req.request != "PUT" &&
    req.request != "POST" &&
    req.request != "TRACE" &&
    req.request != "OPTIONS" &&
    req.request != "DELETE") {
      // Non-RFC2616 or CONNECT which is weird.
      return (pipe);
  }
  if (req.request != "GET" && req.request != "HEAD") {
    // We only deal with GET and HEAD by default
    return (pass);
  }

////// END DEFAULT RULES

  // Allow the backend to serve up stale content if it is responding slowly.
  set req.grace = 1h;

  // Do not cache these paths.
  if (req.url ~ "^/status\.php$" ||
      req.url ~ "^/sitemap\.xml$" ||
      req.url ~ "^/update\.php$" ||
      req.url ~ "^/jstats\.php$" ||
      req.url ~ "^/boost_stats\.php$" ||
      req.url ~ "^/cron\.php$" ||
      req.url ~ "^/ooyala/ping$" ||
      req.url ~ "^/admin/" ||
      req.url ~ "^/info/.*$" ||
      req.url ~ "^/flag/.*$" ||
      req.url ~ "^.*/ajax/.*$" ||
      req.url ~ "^.*/ahah/.*$") {
       return (pass);
  }

  // Pipe these paths directly to Apache for streaming.
  if (req.url ~ "^/admin/") {
    return (pipe);
  }

  // Do not allow outside access to cron.php or install.php.
  if (req.url ~ "^/(install)\.php$" && !client.ip ~ internal) {
    // Have Varnish throw the error directly.
    error 404 "Page not found.";
    // Use a custom error page that you've defined in Drupal at the path "404".
    // set req.url = "/404";
  }

  // Handle compression correctly. Different browsers send different
  // "Accept-Encoding" headers, even though they mostly all support the same
  // compression mechanisms. By consolidating these compression headers into
  // a consistent format, we can reduce the size of the cache and get more hits.=
  // @see: http:// varnish.projects.linpro.no/wiki/FAQ/Compression
  if (req.http.Accept-Encoding) {
    if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v)$") {
      // No point in compressing these
      remove req.http.Accept-Encoding;
    }
    else if (req.http.Accept-Encoding ~ "gzip") {
      // If the browser supports it, we'll use gzip.
      set req.http.Accept-Encoding = "gzip";
    }
    else {
      // Unknown or deflate algorithm. Remove it and send unencoded.
      unset req.http.Accept-Encoding;
    }
  }

////// START .htaccess rewrite rules

// Strip out Google Analytics campaign variables. They are only needed
// by the javascript running on the page
// utm_source, utm_medium, utm_campaign, gclid
  if(req.url ~ "(\?|&)(gclid|utm_[a-z]+)=") {
    set req.url = regsuball(req.url, "(gclid|utm_[a-z]+)=[^\&]+&?", "");
    set req.url = regsub(req.url, "(\?|&)$", "");
  }

////// END .htaccess rewrite rules

////// START BOOST Logic

  // This is no pressflow, so we always have a SESSION

  // but boost will always set the DRUPAL_UID cookie
  // when the user is logged in.
  //
  // So it is safe to remove all cookies for the boosted paths.
  if (!(req.http.Cookie ~ "DRUPAL_UID=")) {
     // User is anonymous

     // Boost rules from .htaccess
     if (!(req.url ~ "(^/(admin|cache|misc|modules|sites|system|openid|themes|node/add))|(/(comment/reply|edit|user|user/(login|password|register))$)")) {

////////// BOOST CONFIG: Change this to your needs
       // Boost rules from boost configuration
       if (!(req.url ~ "/(excluded-url-to-be-configured)")) {
         unset req.http.Cookie;
       }
////////// END BOOST CONFIG: Change this to your needs
    }
  }

////// END BOOST LOGIC

////// Cookie removal logic

  // Always cache the following file types for all users.
  if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v|pdf)(\?[a-z0-9]+)?$") {
    unset req.http.Cookie;
  }

  // Use anonymous, cached pages if all backends are down.
  if (!req.backend.healthy) {
    unset req.http.Cookie;
  }

}

// Routine used to determine the cache key if storing/retrieving a cached page.
sub vcl_hash {
  // Include cookie in cache hash.
  // This check is unnecessary because we already pass on all cookies.
  // if (req.http.Cookie) {
  //   set req.hash += req.http.Cookie;
  // }
}

// Code determining what to do when serving items from the Apache servers.
sub vcl_fetch {

////// START BOOST Logic

  // This is no pressflow, so we always have a SESSION
  // but we only set SESSION if we actually send cookies
  //
  // So logic is: If we did not send a cookie in,
  // we do not allow a cookie out.

  if (!req.http.Cookie) {
    unset beresp.http.set-cookie;
  }

////// END BOOST LOGIC

  // Don't allow static files to set cookies.
  if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v|pdf)(\?[a-z0-9]+)?$") {
    // beresp == Back-end response from the web server.
    unset beresp.http.set-cookie;
  }

  // Allow items to be stale if needed.
  set beresp.grace = 1h;

  // Serve the good page from the cache and re-check in one minute

  if (beresp.status == 503 || beresp.status == 501 || beresp.status == 500) {
    set beresp.grace = 60s;
    restart;
  }

  // Anything that is cacheable, but has expiration date too low
  // which prevents caching gets cached by varnish to take the
  // load off apache.

  if (beresp.cacheable && beresp.ttl < 1h) {

////////// MINIMUM CACHE LIFETIME: Change this to your needs
    // Set how long Varnish will keep it
    set beresp.ttl = 1h;
////////// END MINIMUM CACHE LIFETIME: Change this to your needs

    // marker for vcl_deliver to reset Age:
    set beresp.http.magicmarker = "1";
  }

}

sub vcl_deliver {
////// START DEBUG
  if (obj.hits > 0) {
    set resp.http.X-Varnish-Cache = "HIT Varnish (" obj.hits ")";
  }
  else {
    set resp.http.X-Varnish-Cache = "MISS";
  }
////// END DEBUG

  // The magic marker is used to reset the age to 0
  // as else the object is older than its ttl.

  if (resp.http.magicmarker) {
    // Remove the magic marker
    unset resp.http.magicmarker;

    // By definition we have a fresh object
    set resp.http.Age = "0";
  }
}

// In the event of an error, show friendlier messages.
sub vcl_error {
  // Redirect to some other URL in the case of a homepage failure.
  //if (req.url ~ "^/?$") {
  //  set obj.status = 302;
  //  set obj.http.Location = "http://www.megaleecher.net";
  //}

  // Otherwise redirect to the homepage, which will likely be in the cache.
  set obj.http.Content-Type = "text/html; charset=utf-8";
  synthetic {"
<html>
<head>
  <title>"} obj.status " " obj.response {"</title>
  <style>
    //page {width: 400px; padding: 10px; margin: 20px auto; border: 1px solid black; background-color: //FFF;}
    p {margin-left:20px;}
    body {background-color: //DDD; margin: auto;}
    .error { margin-left: 20px; color: //222; }
  </style>
</head>
<body onload="setTimeout(function() { window.location = '/' }, 5000)">
  <div id="page">
    <h1 class="title">Page Could Not Be Loaded</h1>
    <p>The page you requested is temporarily unavailable.</p>
    <p>We're very sorry, but the page could not be loaded properly. This should be fixed very soon, and we apologize for any inconvenience.</p>
    <hr />
    <p>We're redirecting you to the <a href="http://www.megaleecher.net">Tech Blogs Homepage</a> in 5 seconds.</p>
    <div class="error">(Error: "} obj.status " " obj.response {")</div>
  </div>
</body>
</html>
"};
  return (deliver);
}

```

**The above worked for me, if you are not using Cloudflare make sure to remove that section.**
> -1 votes

---
Tags: forms, 6, cookies, proxies
---


# Question
Title: How to change "Image style" of an Image field in a given view mode programmatically (as on "Manage display" tab after clicking the gear)?
**I would like to change the *"Image style"* of some Image fields** in some given view modes, which are attached to particular content types; I would like to do this **programmatically**.

This is what I would like to change:

How should I do this?

# Answer
Something like this should do it:

```
$entity_type = 'node';
$bundle = 'article';
$field_name = 'field_image';
$view_mode = 'default';

// Get the instance info
$instance_info = field_info_instance($entity_type, $field_name, $bundle);

// Change the image style
$instance_info['display'][$view_mode]['settings']['image_style'] = 'new_image_style';

// Save it
field_update_instance($instance_info);

```
> 2 votes

---
Tags: 7, media
---


# Question
Title: Can you link an image field to a link field by 'Manage display'?
I have a content type with two fields: image and link. I'd like the image to display linked to the link field. I'm happy to do that myself programmatically, I'm just wondering if there's a module that lets you do this directly from the *Manage display* screen (ie zero code).

# Answer
Using Linked Field and Token module, you can easily do this by checking ***"Link this field"***, and entering the appropriate token of your Link field.

Here is an example:

**Destination:**

```
[node:field-test-link:url]

```

**Title:**

```
[node:field-test-link:title]

```
> 3 votes

---
Tags: 7, entities, media, navigation
---


# Question
Title: how to convert node_uri (array) to url string
I used a function node\_uri($node) get an url array. how to change it to a string?

# Answer
> 1 votes
The path string is contained inside the `path` element of that array, so

```
$node = node_load(1);
$uri_array = node_uri($node);

$url = url($uri_array['path']);

```

should get you what you're looking for

---
Tags: nodes, uri
---


# Question
Title: How to group node comments using parent comment in views
I have a content type that student users can comment on. Tutors can go to each comment and respond with an answer.

On each node, I want to display the comments a user makes ONLY. Each comment should be a thread though, showing the responses from tutors.

Right now I have tried views and seen the potential to use a parent comment as relationship then filtering on the parent comment's uid. This however, doesn't bring out the needed functionality.

How do you think I can accomplish this. Any pointers appreciated.

# Answer
Hmmm, maybe this way:

1. Create Views that view only comments. and filter from all comments only those, that was made by the users with role "student".
2. With Display Suite module mark-up displaying of your content type - "screw" this view to your content type.
3. Edit what view that is checked id of this node and show comments only for this node
> 1 votes

---
Tags: comments, views
---


# Question
Title: How to display nodes only after certain dates? (An Advent calendar is in progress)
I'd like to build an Advent calendar with Drupal 7 as a warm-up exercise.

What would be the recommended way to protect future calendar entries from being accessed before their time?

I have 3–5 different content types to be used as calendar entries.

Everything should be accessible to anonymous users as well, so I only need to check the current date.

# Answer
> 2 votes
We have a client who uses the Scheduler module for their blog. They write a backlog of posts, and then post date them for when they want them to appear. You should be able to use this. Make nodes for all of the days, and date them for when you want them to appear. As long as you have cron workng properly, nodes should appear when they should.

Another option is to use the Date module along with Views. Make a content type with a date field. Set the date field to the day you want it to appear. Then make a view over that content type, and add a filter to compare the date field against the current day.

Of the choices, I would go with Scheduler.

# Answer
> 1 votes
Try the Calendar module. Crete in each of your five content types fields for date and type and Calendar should automatically hitch data from this fields and show it on calendar. Think that this is the pimpliest way to create references between own content type and events.

---
Tags: nodes, users, datetime
---


title: Shared hosting behind Cloudflare

text:
# Question
Title: Shared hosting behind Cloudflare
I use Drupal 7 at a share hosting account (with apache server) and I use Cloudflare.com CDN. Cloudflare ip token (at webform etc) shows cloudflare IP instead of visitor's original IP.

At settings.php I put

```
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_header'] = 'HTTP_CF_CONNECTING_IP';

```

These did not seem to work.

What seems to work was: the instructions given by cloudflare for PHP

```
if ($_SERVER["HTTP_CF_CONNECTING_IP"]) {$_SERVER["REMOTE_ADDR"] = $_SERVER["HTTP_CF_CONNECTING_IP"]; }

```

or alternatively what was written at drupal cloudflare module (which is only for drupal 6 and not 7)

```
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"] ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];

```

The questions are

* why the typical drupal settings ($conf\['reverse\_proxy\_header) did not work, and how can I make them work?
* If not, then which of the 2 solutions that worked for me is more secure or better?
* Should I setup $conf\['reverse\_proxy\_addresses'\] with cloudflare ips, or it's useless since $conf\['reverse\_proxy\_header'\] does not work anyway?

# Answer
Why don't you install the CloudFlare - Free Reverse Proxy, Firewall, and Global CDN module? The module comes with instructions on how to solve this problem:

**Installation Instructions:**

> Install and Enable this module. Add one line of code at the end of your settings.php file:
>
> ```
> $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"] ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
>
> ```
>
> Save your email address and CloudFlare API key to the CloudFlare administration screen on your Drupal web site (admin/settings/cloudflare).
> 2 votes

---
Tags: 7, configuration
---


# Question
Title: How to expose to users filter for changing views items limit for pagination?
As in question, is this possible via UI or only custom form must be created?

# Answer
> 0 votes
I have done this manually. I typically edit views-view.tpl.php file to build up a "items per page" list w/ links and tack on a `perpage=` GET argument. You can do the same with a preprocess for the view, but I am spacing on what it is called.

I then implement a hook\_views\_pre\_build:

```
function mymodule_views_pre_build (&$view)
{
  if ($_GET["perpage"]) {
    $perpage = check_plain($_GET["perpage"]);

    if (is_numeric($perpage) && (int) $perpage > 1) {
      $view->pager["items_per_page"] = (int) $perpage;
    } else if ($perpage == "all") {
      $view->pager["use_pager"] = false;
      $view->pager["items_per_page"] = 0;
    }
  }
}

```

The last time I remember doing this was with Drupal 6 and Views 2, so you may need to adjust the hook for Views 3.

---
Tags: 7, views, paging
---


# Question
Title: How to find out which cron jobs are currently running?
Is this possible to find out which cron jobs are currently running?

# Answer
The answer can be found in drupal\_cron\_run. While it is the case that you can tell if Cron is currently running by calling `lock_acquire('cron', ...))`, just as Drupal does (don't forget to call lock\_release too), Drupal does not in any way set any information about the individual cron hooks that it executes during a cron job.

If you need more control over cron job execution, you could always copy the drupal\_cron\_run function into your own module and modify it to suit. drush\_core\_cron() does nothing other than call drupal\_cron\_run, so you could call your own cron function via drush ev 'mymodule\_cron\_run();' from your crontab. If you did this, you would need to review the implementation of drupal\_cron\_run on every update of Drupal core, and check for any significant alterations in behavior, so you should only customize cron if it's really important that you do so.
> 4 votes

---
Tags: 7, cron
---


# Question
Title: Most appropriate simple IP direct for Drupal 7
Having looked at the descriptions provided for the following modules

* ip2cc
* ip2country
* geoip
* smart\_ip

I'm having trouble identifying which module would be the simple solution to my scenario.

I have established 'Landing Pages' which represent the different countries for my website. (initially)

e.g: \- www.example.com/au (Australia) \- www.example.com/us (United States) \- www.example.com/uk (United Kingdom)

If a user lands at the www.example.com url and they are from IP addresses in Australia, United States or the UK, I'd want it to direct them to the appropriate landing page.

I'm not sure which module is the most appropriate for this scenario and how it would be applied.

Many thanks for your help.

# Answer
> 2 votes
All of the modules you have listed only provide APIs, choose one for which you need least maintanence. For geoIp you need to keep updating County List DAT file manually once in 3~4 months, I am not sure about others. Once you choose your module you have to write logic for your scenario, something like this

```
$cc = geoip_country_code();
if($cc == "AU"){
  drupal_goto(MY_AUSTRALIAN_SITE_URL);
}

```

You can use page--front.tpl.php or make use of drupal\_is\_front\_page() in page.tpl.php to write your own logic.

---
Tags: 7, redirection, location
---


# Question
Title: View comments in admin area before approval
How can I view posted comments in admin area before approval?

I mean previewing comment INSIDE admin area not node's page.

# Answer
Default comment administration page does not show you the entire comment. But it shows author and some other helpful information that should be helpful for most users to decide anther delete it or not.

You can replicate this form using Views and Views Bulk Operations module.

Just install both modules and create a new View on comment entity. You can add a new page with a path like admin/content/comment2 (so you are not overriding the default page - if you want to do so, enter same path as core comment admin page).

Add necessary fields and set style as table. You can add a VBO checkbox and actions by adding a checkbox field.

There is an action "delete comment" that you can use to delete comments via VBO. hooks will work without a problem.
> 1 votes

---
Tags: 6, comments, theming
---


# Question
Title: Use the full name instead of the user name as author of articles
I'm coming to Drupal from Joomla. To be honest, Drupal is a little more daunting.

I simply wish to have the author's name appear in the articles (ie, written by RealName) instead of the default (written by username).

I already have the real name field created, and can display the real name if I click on user info.

Any idea how I can have "written by realname" on articles?

# Answer
> 5 votes
There's a module for that - RealName

> The RealName module allows the administrator to choose fields from the user profile that will be used to add a "real name" element (method) to a user object. Hook\_user is used to automatically add this to any user object that is loaded. It will also optionally set all nodes and comments to show this name.

EDIT - since your new to Drupal you might want to checkout - http://drupalmodules.com/ \- great way of finding modules that you might need.

# Answer
> 0 votes
First of all, there is nothing preventing you for using usernames as realnames, as you can use spaces by default in username, but you got some options tho.

You could create a author field your self on the node type, however this forces you to type it in manualy.

You could make a template for the nodetype, printing the profile field yourself.

I will thought encourage you to have a look at either views (http://drupal.org/project/views) or panels (http://drupal.org/project/panels), which gives you a lot of control of the output.

If you are new to drupal, start with Views, this will solve your problem almost out of the box by override the node/% page.

With panelizer (http://drupal.org/project/panelizer) you can define default layouts for each nodetypes, using fields of choice.

---
Tags: nodes, users
---


# Question
Title: Send email on comment to users depending on Taxonomy term selection in node
I need to send notification on new comment to users. But not based on node ownership, but based on what Taxonomy term is selected in node. It might be good task to accomplish with Rules module.

So i knwo to set event - after saving a new content and Action - send e-mail

but for condition, i should somehow get the Commented node taxonomy term value. But cannot find selector: Taxonomy term to do data comparison, or way to get taxonmy data for given commented node. Is this possible ?

Can the commented node object be checked - if custom PHP is selected for condition - so i can check selected taxonomy term value ?

Thanks!

# Answer
You should Load the Entity (node) from the comment's data.

Then pass that node to a component rule, which actually checks the taxonomy of the node and sends the appropriate email.

Here's a step by step.

First create a component: 1) Go to Rules -\> Components -\> Add new component 2) Select Rule 3) Name and Tag the component 4) In variables select 'Entity Node' and give it a label and a machine name. Example 'comment\_node' 5) Add your conditions. Probably good idea to check node type and of course the taxonomy term you were looking for. 6) Add an Action. Here you should send an email.

Now go to your rule: 1) In actions add 'Fetch entity by Id'. Select 'node'. Use data selector and put 'comment:node:nid' in the id. 2) Then add a Loop 3) In the loop add an action. That action should be your component you created previously. 4) Pass the fetched entity into the component and you should be done
> 3 votes

---
Tags: rules, comments
---


# Question
Title: how to create new image size with new image style with php code in drupal 7?
I want to create a new image style in Drupal 7, with a name like front\_video\_thumbnail. I want to use this size image on front page. I wrote code in template.php preprocess\_page(), like the following one.

```
$img = theme('image_style', array('style_name' => 'front_video_thumnail', 'path' => $value['uri']));
$content =l($img, $node_url, array('html' => TRUE));

```

No image is showing, because no image has been created in the new style folder.

How can I make this new image style created in the style folder?

# Answer
You have to go to Configuration =\> Image Styles. Create the Image Style with the name front\_video\_thumnail and once it's configuration is saved your code should work.
> 1 votes

---
Tags: 7, media
---


# Question
Title: Store age from Date of birth when use registration
I am having a date of birth field in my registration form.

* I want to add the age in user data when the reregistration form is submitted.
* How can I update the age in the field when crone is run.

# Answer
> 1 votes
Computed Field Module will do the job:

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

You can also google "Drupal Computed Field Age" for more information.

---
Tags: users, datetime, cron
---


# Question
Title: Creating Feature with content types imported by Feature
Exporting several content types (7) from old website and importing them to new one worked perfectly.

After that i have done some basic changes in imported content types (changed widgets in few text fields (all widgets are default type)).

Now i want to make fresh backup of content types. "Create feature" / Edit components - Content types: node Now i can only choose "Article" and "Basic page". Content types i imported are not visible as an option.

Any idea ?

# Answer
> 1 votes
Open exisitng feature that contains content types and choose "Recreate", then click "Download". You will get new version of feature that will include all your changes.

# Answer
> 1 votes
If your nodetype is already in a feature, they will not show up in the feature list. You can disable the feature containing the nodetypes, now the nodetypes should appear.

---
Tags: 7, features
---


# Question
Title: Create users to post unplublished nodes so admin could approve
How can I create some users in Drupal 6 to post unpublished nodes so that admin could approve those unpublished node?

# Answer
> 1 votes
There are multiple ways. (**Edit:**The workbench module is very popular, but is for Drupal 7 only). I have achieved good results using the revisioning module, which has a release for Drupal 6.

---
Tags: rules, users
---


# Question
Title: How to get attached files outputted by views for given node id (programatically)
I am working with a module. I have a node id. That node id is a page and it has 2 or more view blocks on it. The results of views are lists of nodes with file attachments.

I need to get all the files attached to the nodes outputted by the view on this particular page.

I work in a module file and I can supply the nid of type page where these views sit.

I could not find much help so I decided to ask for what would be the best way to approach this.

I am new to Drupal so I will appreciate a great explanation on how to approach this.

# Answer
I thought I'd come back and explain my solution. It involves a series of loops through the following: getting regions available for current nid, then the blocks displayed on that nid, then loading each view that has blocks on that nid to obtain access to the fields. I can't provide any code but in theory that's what it involves.
> 1 votes

# Answer
I had some fields for related documents, and so I added those in a custom field (HTML format to link to my already uploaded documents), and created a view block in the sidebar to grab these fields from the current node. I went here and did what this guy said:

That worked for me.
> 0 votes

---
Tags: views, files
---


# Question
Title: how to a translatable string in drupal theme?
I want to put a string as a signature in drupal theme I am working on. the website is multilingual and the string should be translated based on the current language of the website. I don't know how to do it.

my drupal version is 6.

Would you help me?

# Answer
> 4 votes
The first step to translate a string used from a module, or a theme is using t() for every string that needs to be translated. Remember that the first argument given to the function is a literal string containing a phrase in English. This means that the following calls to `t()` are not correct.

```
// The string is a concatenation of literal strings.
$error = t('This example, ' . "doesn't work.");

```

```
// Also in this case there is a concatenation of literal strings.
$errno = 15;
$error = t("Error number $errno received while translating a string.");

```

```
// This could work, provided that another function calls t() using a
// literal string that is equal to the string returned from the function.
$error = t(mymodule_get_error());

```

The second step is providing the translation of the string passed to `t()`. If the theme is hosted on Drupal.org, then the translation will be provided from translators on http://localize.drupal.org.
Otherwise, you need to translate the string on admin/build/translate/search.

You can look for the string to translate searching for untranslated strings, or entering a string.

# Answer
> -1 votes
you should use something like t('your string');

---
Tags: theming, 6, i18n-l10n
---


# Question
Title: Exportable and Fieldable Blocks in Drupal 7
I have a project where I have two competing requirements for blocks.

First, I'd like to have blocks be fieldable. There are blocks on the site that contain static content but should have the block title as a link, and have an icon associated with the block.

Secondly, although these blocks are not "configuration" per-se, the client would certainly say that their site was broken if they didn't exist. Because of this, I'd like to be able to export the blocks using Features so that they can be included in version control.

I've looked into both the Bean and Boxes modules. Bean supports making the blocks fieldable by defining new block types. Unfortunately, while the block type is exportable with Bean, the block itself isn't.

I've also looked into Boxes. Boxes supports exporting blocks, but isn't fieldable by itself. If I add the Entity Box module to Box, I get fieldable boxes, but those new boxes aren't exportable.

Help! Is it even possible to do what I'm trying to do here? Is there some way other than creating Features exportables to easily synchronize small pieces of content so that all of the developers are working on a consistent version of the site?

# Answer
The answer is simpler than you could possibly imagine: check out the Bean module, it does exactly what you want! :)
> 1 votes

# Answer
If you need custom blocks that need to be exportable, I would install the Panels module. First of all, all the custom content types in Panels (panel nodes, Pages, mini-panels) are all exported, and can be saved as a file, or bundled with Features. (To save as just a file, you just "export" the code for the piece of content.)

Also, the mini-panel content type that you can create in Panels functions essentially just like a block. So, it might meet your needs.
> 0 votes

# Answer
You want the Node Block module.

It's fieldable and node blocks created can be exported.

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.
> 0 votes

---
Tags: 7, entities, features, importing-exporting, blocks
---


# Question
Title: Commerce doesn't handle Sagepay Form Integration return
So I'm using SagePay Form Integration on my site, but it has ceased to function correctly.

So on the Payment Stage of Checkout it says 'Use the button below to proceed to the payment server.'. Now I successfully complete a payment on the Sage Pay Testing Server and it comes back to the site URL checkout/order\_id/payment/return attached with some GET vars.

The issue is that when it returns, checkout just displays 'Use the button below to proceed to the payment server.' again. The status of the order hasn't been updated and the user isn't ushered to the complete stage. Any idea why this is?

After further inspection it also seems that under Store \> Orders it isn't logging the payment as it had previous. The order just remains at the payment stage in 'Shopping Carts' tab of Admin \> Store \> Orders.

I'm having this exact same issue with all of the following versions:

* 7.x-1.0-beta2
* 7.x-1.0-beta1
* 7.x-1.x-dev

Your help would be greatly appreciated!

# Answer
> 0 votes
Turns out that Firebug Lite script in `html.tpl.php` was causing the issue:

```
<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script>

```

Swiftly removed.

---
Tags: 7, commerce
---


title: views query I can't workout

text:
# Question
Title: views query I can't workout
I know the query I am trying to achieve. But how to start create it in views using drupal 7 alludes me. This is what I am trying to achieve

SELECT * from Articles where Node IS NOT current Node.

# Answer
> 1 votes
You need to use views contextual filters. Add a contextual filter Content:Nid and provide default value as "Content Id from URL" and select Exclude checkbox in the settings. That's it !!

---
Tags: 7, views
---


title: Is "system_settings_form" voodoo?

text:
# Question
Title: Is "system_settings_form" voodoo?
A friend just showed me system\_settings\_form in action in a configuration file for a form.

The code in question looks like this (simplified).

```
function my_module_generateAdminForm($form){
  $form = array();
  $form['super_secret_password'] = array(
    '#type' => 'textfield',
    '#title' => t('Headline'),
    '#default_value' => variable_get('super_secret_password','password'),
  );
  system_settings_form($form);
}

```

system\_settings\_form adds in submit buttons and handles the form submission, saving the variables. It also adds a "Reset to default" button - that resets all the variable to the default.

I basically guessed what it does because there's not a whole lot of documentation out there and my friend doesn't know exactly what it does either. My question is how does it know the variables to save/reset? Aren't I just passing an array?

Also is there any other magic in system\_settings\_form that I should know about?

# Answer
> 14 votes
See system\_settings\_form and system\_settings\_form\_submit for implementation details. In Drupal 7 Reset to Default button is removed from System Settings form .

```
function system_settings_form($form) {
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save configuration'),
  );

  if (!empty($_POST) && form_get_errors()) {
    drupal_set_message(t('The settings have not been saved because of the errors.'), 'error');
  }
  $form['#submit'][] = 'system_settings_form_submit';
  // By default, render the form using theme_system_settings_form().
  if (!isset($form['#theme'])) {
    $form['#theme'] = 'system_settings_form';
  }
  return $form;
}

```

**System\_settings\_form :**

Add's save configuration Submit button and submit callback to system\_settings\_form\_submit function.

**system\_settings\_form\_submit:**

```
function system_settings_form_submit($form, &$form_state) {
  // Exclude unnecessary elements.
  form_state_values_clean($form_state);

  foreach ($form_state['values'] as $key => $value) {
    if (is_array($value) && isset($form_state['values']['array_filter'])) {
      $value = array_keys(array_filter($value));
    }
    variable_set($key, $value);
  }

  drupal_set_message(t('The configuration options have been saved.'));
}

```

Iterates through all form elements and sets variables for each form element with key as form element key and value as user submitted form element value read using $form\_state\['values'\]

So, it's just a form with submit handler that sets variables for all form values using variable\_set function.

---
Tags: 7
---


# Question
Title: Is there a way to add profile2 forms in multistep registration
Is there a way to add profile2 forms into a multistep registration form?... First of all I am a beginner I only know small tidbits on how to do multistep... What I need is step 1 to be basic user registration information, step 2 to be personal profile2 info and a conditional set up basically asking the viewer something in a radio or click box that should process if they need a second profile. If that conditional is met then they go to step 3 and fill out a second profile2 form.

I found out about multistep here

# Answer
> 2 votes
yes definately we can create profile2 field as a multistep form for this we can use Field Group By field group module you can include all fields in multipage group and after that create multipage group as per you need and include relevant fields in each break.

---
Tags: users, forms
---


title: Use custom profile field in Rules

text:
# Question
Title: Use custom profile field in Rules
I have a custom Boolean field in user profile called "social reading" in my drupal installation. I want to create an action using rules module which should check if this field is marked or not. But I am not able to find the option in rules.

# Answer
> 1 votes
Under the Rules module add the event that fires `After new user is created`, then under conditions add a `Data comparison`, on the first step you should select your checkbox field, on clicking continue you will be presented with the options of this field, that is checked or unchecked.

Now add your action/s under the actions section.

If you want to also check when a user is modified, you should add a rule for the event `Existing user is updated`.

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


title: Hide text field in hook_form_alter

text:
# Question
Title: Hide text field in hook_form_alter
I have a field field\_agent\_name. I want to hide this field in my custom module using hook\_form\_alter.

How to do this.

# Answer
> 18 votes
Using the hook\_form\_FORM\_ID\_alter format is ideal:

```
function MODULENAME_form_CONTENTTYPE_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_agent_name']['#access'] = FALSE;
}

```

More info on hook\_form\_FORM\_ID\_alter

# Answer
> 1 votes
Below code worked for me:

```
function modulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'contenttypename_node_form') {
    $form['field_agent_name']['#access'] = 0;
  }
}

```

---
Tags: 7, forms
---


title: How to do a redirection in drupal

text:
# Question
Title: How to do a redirection in drupal
I have a node page that should redirect to another node's page instead of displaying itself...

How can I do that ?

Many thanks !

# Answer
> 1 votes
Rather than using a node to redirect to another one, I would implement hook\_menu() to define a new menu callback that renders the other node, or redirect to the other node.
The alternative would be implementing hook\_node\_view() to add the other node to the node being viewed (when it is the correct one). For example, the following code would work.

```
function mymodule_node_view($node, $view_mode, $langcode) {
  if ($node->nid == $node_to_alter) {
    $node->content['my_module_additional_content'] = node_view($the_other_node);
  }
}

```

This is the approach followed by Drupal where, instead of using the PHP filter (which would make a node editable only from Drupal.org administrators), a custom module is used to add content to specific nodes.

A node that redirects to another node would create problems because:

* If you are doing the redirect when rendering the node, you would create problems with all the functions that render a node. The assumption is that a node is rendered when it is going to be visualized, but that is always true, as (for example) node\_search\_execute() renders the node while executing a search for a set of key words. There are other 10 functions that call node\_view(), including the one rendering multiple nodes; all of them would have a problem, if the user is redirected in the middle of what they are doing, which means PHP stops its execution as `exit()` is being executed.
If you are using the PHP filter to execute PHP as node content, that is not suggested to do. If you need to dynamically render a node content, you should implement a module which could be implement an input filter, or other hooks, depending from the needs.
* If you are using a custom module to redirect the users when the node is being loaded, or rendered (e.g. implementing hook\_node\_load(), or hook\_node\_view()), you would have the same problem I described first. Plus, as you are already using a custom module, then you can implement one of the solutions I have proposed.

As for other suggestions:

* `hook_menu_alter()` is used to alter the existing menus. For the nodes, the menu callback is the one associated to node/%node, which is invoked for every node. It is possible to use this hook to alter the page callback with a different one that first check which node is being viewed, and then redirect the users to the other node. In this case, there would not be problems, as the function is called when the node is being viewed, not when a node is being loaded, or being rendered in memory.
IMO, it would be a sub-optimal solution. I would rather implement `hook_menu()` to define a new menu callback.
* The Path redirect allows to set static redirects from the UI. This doesn't help if the intent is having a dynamic redirect, which seems the case here.
* The Rules module can be useful, but I would rather use it if you need it for more than what you are trying to achieve here. It is a better solution that enabling the PHP filter module to execute PHP code inside a node body, but it would probably require you to write PHP code that is executed through `eval()`, which should generally be avoided.

# Answer
> 0 votes
You have several ways of doing this, you could use Path Redirect module to redirect the first page to the second one or in the body of the node use the drupal\_goto() function (with PHP input filter enabled), although the first option is by far the best and more "clean".

---
Tags: redirection
---