Drupal: Load a Function Based on URL (wildcard loaders)

Drupal sites often use wildcards in their URL. In Drupal, this is accomplished in the hook_menu() function. In the hook_menu() function, the URL is defined as the key of the $item array. The wildcard value is represented by the token, % (percent sign). But did you know the % can proceed the name of a callback function? Drupal automatically “knows” to look for the callback function you call out. There is a bit of a trick to it, though. Note in the example that there is ‘my_function’ immediately after the wildcard (%). That would be the call to the callback function. The little trickiness is that you need to define the function in your module suffixed with the word ‘_load’. The function you define as my_function_load( $nid ), also needs to have an argument of $nid. Pretty easy, huh? Drupal will “know” that the wildcard (%) is a token representing the parameter ($nid) for the function.

 'My Ttitle',
	'page callback' => 'mymodule_page',
	'page arguments' => array(1),
	);
  ... some code ...
  
/**
 * Menu loader callback. Load a webform node if the given nid is a webform.
 */
function my_function_load($nid) {
  .... do some stuff here ...
  return $node;
}
?>

Leave a Reply

Your email address will not be published.