Code snippet: current OG context to node creation links

Simple use case of the day : when you deal with Organic Groups in Drupal, you might want your users to be able to create nodes in their groups without dealing with the infamous audience checkboxes.

A simple solution is to use the links from the Navigation menu. In order for OG to be able to add a node as post in a group, it needs to find the gids[] GET parameter.

An ugly, but really efficient solution is to use the custom_url_rewrite_outbound() function to alter node/add/* links and enforce the gids[] parameter if the user is currently is in a group context.

Solution :

<?php
// Define the custom_url_rewrite_outbound() function if not already defined.
if (!function_exists('custom_url_rewrite_outbound')) {
  function
custom_url_rewrite_outbound(&$path, &$options, $original_path) {
   
my_module_url_outbound_alter($path, $options, $original_path);
  }
}

/**
* Implementation of hook_url_outbound_alter().
*/
function my_module_url_outbound_alter(&$path, &$options, $original_path) {
  if ((
$group = og_get_group_context()) && preg_match('/^node\/add\/([^\/]+)/', $path, $matches)) {
    if (
og_is_group_post_type($matches[1])) {
     
$options['query'] .= (empty($options['query']) ? 'gids[]=' : '&gids[]=') . $group->nid;
    }
  }
}
?>

Et voilà :)

Notice that this code also add implicit compatibilty with the url_alter module, which can be really usefull when more than one module needs to do this kind of URL rewriting.

Votre notation : Aucun Moyenne : 5 (2 votes)
Étiquettes: