background image

Content tagged with: hook_menu

Eric's picture

For some time now I've wanted to write a blog entry about using AHAH to create dynamically generated form elements. After a recent conversation at work regarding usability, I now had a real world example to create: how to use tiered taxonomy to dynamically generate a form. This code snippet will show you how to create a form that creates child select dropdowns based on the parent taxonomy term the user selects.

First I established a multi-tier taxonomy called "AHAH":

For this example I created a menu callback to display my initial form:

<?php
function helper_menu() {
 
 
$items = array();
 
 
$items['ahah-form'] = array(
   
'title' => 'AHAH Form',
   
'page callback' => 'drupal_get_form',
   
'page arguments' => array('_helper_callback_ahah_form'),
   
'type' => MENU_CALLBACK,
   
'access callback' => 'user_access',
   
'access arguments' => array('access content'),
  );
 
  return
$items;
 
}
?>

I then defined the page callback to show the initial form:

<?php
function _helper_callback_ahah_form() {

 
// define an array to contain form elements
 
$form = array();
 
 
// define the top level vid
 
$vid = 2;
 
 
// fetch a tree of taxonomy elements
 
$tree = taxonomy_get_tree($vid, 0, -1, 1);
 
 
// loop though taxonomy and collect elements
 
$options = array();
  foreach (
$tree as $key => $value) {
   
$options[$value->tid] = $value->name;
  }
 
 
// create the first select dropdown input
 
$form['select_1'] = array(
   
'#type' => 'select',
   
'#options' => $options,
   
'#title' => t('Select 1'),
   
'#size' => 5,
   
'#multiple' => false,
   
'#ahah' => array(
     
'event' => 'change',
     
'path' => 'ahah-form-callback',
     
'wrapper' => 'wrapper-1',
     
'method' => 'replace',
    ),
  );
 
 
// pass the top level vid in the form
 
$form['ahah_vid'] = array(
   
'#type' => 'hidden',
   
'#value' => $vid,
  );
 
 
// create an empty form element to contain the second taxonomy dropdown
 
$form['wrapper_1'] = array(
   
'#prefix' => '<div id="wrapper-1">',
   
'#suffix' => '</div>',
   
'#value' => '&nbsp;',
  );
 
 
// add a form submit button
 
$form['submit'] = array(
   
'#value' => 'Submit',
   
'#type' => 'submit'
 
);
 
  return
$form;
 
}
?>

The above form callback produces the following:

Next, I defined a callback to handle the AHAH page request:

<?php
// new menu item:
function helper_menu() {
 
 
// ...
 
 
$items['ahah-form-callback'] = array(
   
'title' => 'AHAH Form Callback',
   
'page callback' => '_helper_callback_ahah_form_callback',
   
'type' => MENU_CALLBACK,
   
'access callback' => 'user_access',
   
'access arguments' => array('access content'),
  );
 
 
// ...

 
return $items;
 
}

// and, here's the AHAH callback used to create the new form elements:
function _helper_callback_ahah_form_callback() {
 
 
// define a string variable to contain callback output
 
$output = "";
 
 
// pull the top level vid from the $_POST data
 
$vid = $_POST['ahah_vid'];
 
 
// pull the selected dropdown from the $_PODT data
 
$parentVid = $_POST['select_1'];
 
 
// loop through the taxonomy tree and fetch child taxonomies
 
$options = array();
 
$tree = taxonomy_get_tree($vid, $parentVid, -1, 1);  
  foreach (
$tree as $key => $value) {
   
$options[$value->tid] = $value->name;
  }
 
 
// define the second tier select dropdown element
 
$form['select_2'] = array(
   
'#type' => 'select',
   
'#options' => $options,
   
'#title' => t('Select 2'),
   
'#size' => 5,
   
'#multiple' => false,
  );
 
 
// rebuild form object and output new form elements
 
$output .= ahah_render($form, 'select_2');
 
 
// render form output as JSON
 
print drupal_to_js(array('data' => $output, 'status' => true));
 
 
// exit to avoid rendering the theme layer
 
exit();
 
}

// Lastly, here's a help function pulled from Nick Lewis's blog to alter the form
// see: http://www.nicklewis.org/node/967
// NOTE: based on poll module, see: poll_choice_js() function in poll.module
function ahah_render($fields, $name) {
 
$form_state = array('submitted' => FALSE);
 
$form_build_id = $_POST['form_build_id'];
 
// Add the new element to the stored form. Without adding the element to the
  // form, Drupal is not aware of this new elements existence and will not
  // process it. We retreive the cached form, add the element, and resave.
 
$form = form_get_cache($form_build_id, $form_state);
 
$form[$name] = $fields;
 
form_set_cache($form_build_id, $form, $form_state);
 
$form += array(
   
'#post' => $_POST,
   
'#programmed' => FALSE,
  );
 
// Rebuild the form.
 
$form = form_builder($_POST['form_id'], $form, $form_state);

 
// Render the new output.
 
$new_form = $form[$name];
  return
drupal_render($new_form);
}
?>

The above code allows the user to select an option from the top level tier of taxonomy and the AHAH callback will generate the a select dropdown of the child taxonomies as shown below:

On form submission, you'll see that the options the user selected as stored in $form_state['values']['select_1'] and $form_state['values']['select_2']

Eric's picture

In this blog entry, I'll show you how you can add some module code to allow users to select different themes for their profile page. I decided to use the standard user-profile.tpl.php as the base template. I copied this file into my theme folder and replicated it a few times. I named the files:

user-profile-version-1.tpl.php
user-profile-version-2.tpl.php

For my example, I simply added the text "Version 1" and "Version 2" to the top of these files to show it's working, but you could revise the layout, add CSS, etc.

Next, I created a module to contain all the following code. I defined a hook_perm() and hook_menu() function to add a menu local task (tab) to the user page.

<?php
function MYMODULE_perm() {
  return array(
   
'choose profile theme'
 
);
}

function
MYMODULE_menu() {
 
 
$items = array();
 
 
$items['user/%user/choose-profile-them'] = array(
   
'title' => 'Choose Profile Theme',
   
'page callback' => '_MYMODULE_callback_choose_profile_theme',
   
'page arguments' => array(1),
   
'access callback' => 'user_access',
   
'access arguments' => array('choose profile theme'),
   
'type' => MENU_LOCAL_TASK,
  );
 
  return
$items;
 
}
?>

user profile tab

Next, I defined the page callback to create a list of available templates for the user to choose from.

<?php
function _MYMODULE_callback_choose_profile_theme($user) {

 
// create an empty strong variable for page html
 
$html = "";

 
// define a list of available profile templates
 
$profileTemplates = array(
   
'user-profile-version-1' => 'Version 1',
   
'user-profile-version-2' => 'Version 2'
 
);
 
 
// loop through templates and ensure they exist
 
foreach ($profileTemplates as $template => $name) {
    if (!
file_exists(path_to_theme() . '/' . $template . '.tpl.php')) {
      unset(
$profileTemplates[$name]); 
    }
  }
 
  if (
count($profileTemplates)) {
   
$html .= drupal_get_form('_MYMODULE_callback_choose_profile_theme_form', $user, $profileTemplates);
  } else {
   
$html .= "No profile themes currently exist.";
  }
 
  return
$html;
 
}
?>

The following functions define the form array, and validation and submit handlers. When the form is submitted, the template option is saved to the user account variables using the user_save() function.

<?php
function _MYMODULE_callback_choose_profile_theme_form($form_state, $user, $profileTemplates) {

 
$form = array();
 
 
// add a select input element
 
$form['profileTemplate'] = array(
   
'#type' => 'select',
   
'#title' => t('Profile Template'),
   
'#options' => $profileTemplates,
   
'#default_value' => $GLOBALS['user']->profileTemplate
 
);
 
 
// add a submit button
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('Submit')
  );
 
 
// add hidden element for userID
 
$form['userID'] = array(
   
'#type' => 'hidden',
   
'#value' => $user->uid
 
);
 
  return
$form;
}

function
_MYMODULE_callback_choose_profile_theme_form_validate($form, &$form_state) {
 
// TODO: add your additional form validation here
 
  // ensure userID submitted matches current user
 
if ($form_state['values']['userID']!=$GLOBALS['user']->uid) {
   
form_set_error('', t('Error processing form.')); 
  }
 
}

function
_MYMODULE_callback_choose_profile_theme_form_submit($form, &$form_state) {

 
// load user object
 
$user = user_load($form_state['values']['userID']);
 
 
// save profile template to user variables
 
user_save($user, array('profileTemplate' => $form_state['values']['profileTemplate']));
 
 
// set a message
 
drupal_set_message('Your profile template has been set.');
 
}
?>

user profile form

Last, I defined the preprocess function to see if a template has been set in the user variables, and add the templates suggestion to change the user profile template.

<?php
function MYMODULE_preprocess_user_profile(&$variables) {

 
// ensure the template file exists, and is set in the user object
 
if (file_exists(path_to_theme() . '/' . $variables['user']->profileTemplate . '.tpl.php') && $variables['user']->profileTemplate) {

   
// set a templates suggestion
   
$variables['template_files'][] = $variables['user']->profileTemplate;
  }
 
}
?>

As you can see below, when I choose the "Version 2" template option, the file "user-profile-version-2.tpl.php" is being loaded, and the text "Version 2" is displayed at the top of the page.

user profile selected

Eric's picture

In this tutorial, I'll show you how you can expose your search form on another site using jQuery. At first, I thought about scraping the form's html using AJAX.. and quickly remembered you cannot easily do that. Which lead me to review the AJAX functionality included in jQuery. Bingo, one of my favorites: jQuery.getJSON. To summarize this code, I create a callback function to display the form's json-ified html which can then be easily embedded on another site.

First I defined the menu hook:

<?php
function MYMODULE_menu() {

 
$items = array();

 
// add a page callback for the url: "external-search.js"
 
$items['external-search.js'] = array(
   
'page callback' => '_MYMODULE_external_search',
   
'type' => MENU_CALLBACK,
   
'access arguments' => array('search content'),
  );
   
  return
$items;
   
}
?>

Then I created the callback function for the menu callback:

<?php
function _MYMODULE_external_search() {

 
// create a json string of the search form html
 
$json = drupal_to_js(drupal_get_form('search_form'));
   
 
// format the json as a callback function
  // see: http://docs.jquery.com/Ajax/jQuery.getJSON for more information
 
if ($_GET['jsoncallback']) {
   
$json = $_GET['jsoncallback'] . "(" . $json . ");";
  }
   
 
// output the json
 
print $json;

 
// stop the script, so the theme layer is not applied
 
die;
}
?>

One problem though, the form submits locally. That can be fixed using a form_alter function:

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
   
 
// check for external search form and set form action to be full path
 
if ($form_id == 'search_form' && arg(0)=='external-search.js') {
   
// change the form action to be the full path
   
$form['#action'] = 'http://' . $_SERVER['HTTP_HOST'] . $form['#action'];
  }
}
?>

Now, if you clear your cache and go to http://YOURSITE/external-search.js, you should see the JSON (and nothing else).

Lastly, you can embed the code on another site using a few lines of jQuery. You can even pull the jQuery from your site if the external site does not have jQuery included.

<!-- Include jQuery (as necessary) -->
<script type='text/javascript' src='http://YOURSITE/misc/jquery.js' ></script>

<!-- create a div container to contain the search form -->
<div id='embedded_search'></div>

<!-- add the jQuery to embed the form -->
<script type='text/javascript'>
$(document).ready(function(){
  // make the ajax request
  $.getJSON("http://YOURSITE/external-search.js?jsoncallback=?",
    function(data){
      // append the form to the container
      $('#embedded_search').append(data);           
    }
  );
});
</script>

Now people should be able to access your site's search form from another site!

Eric's picture

I've been working on an intranet site that needed to have typical intranet permissions: unauthenticated users can see a handful of pages and the rest of the nodes are only visible to authenticated users. Instead of having the user specify permissions for every page, I figured it would be more usable to have them specify a list of pages available to unauth users.

I created an admin settings page callback to generate the form with a single textarea input. Users will enter a list of URLs in the textarea, one per line:

<?php
function MYMODULE_menu() {
 
$items = array();

 
$items['admin/settings/MYMODULE'] = array(
   
'title' => 'MYMODULE Settings',
   
'page callback' => 'drupal_get_form',
   
'page arguments' => array('_MYMODULE_callback_admin_settings'),
   
'type' => MENU_NORMAL_ITEM,
   
'access arguments' => array('administer site configuration'),
  );

  return
$items;
}

function
_MYMODULE_callback_admin_settings() {
 
$form = array();

 
$form['MYMODULE_unauth_pages'] = array(
   
'#type' => 'textarea',
   
'#title' => 'Unauth Pages',
   
'#default_value' => variable_get('MYMODULE_unauth_pages',''),
  );
   
  return
system_settings_form($form);
}
?>

For this example, I entered the following URLs in the textarea:

<front>
about-us
contact-us

I then added a menu_alter hook function to override the access control for viewing nodes:

<?php
function MYMODULE_menu_alter(&$items) {
 
// per unauth pages, replace the callback function
 
if (function_exists('_MYMODULE_node_access')) {
   
// note: access callback function was previously: node_access
   
$items['node/%node']['access callback'] = '_MYMODULE_node_access';
  }
}
?>

And, then added a new access control function:

<?php
function _MYMODULE_node_access($op, $node) {

 
// check if user is unauth
 
if (in_array('anonymous user', array_values($GLOBALS['user']->roles))) {

   
// get a list of unauth pages
   
$unauth = variable_get('MYMODULE_unauth_pages','');
   
$unauth = explode("\r\n", trim($unauth));
       
   
// replace <front> with empty string
   
if (in_array('<front>', $unauth)) {
     
$unauth[array_search('<front>',$unauth)] = '';
    }
       
   
// check for unauth entries
   
if (is_array($unauth) && count($unauth)) {
     
// check if current url is allowed
     
if (!in_array($_REQUEST['q'], $unauth)) {
        return
false;
      }           
    }
  }
   
 
// default to node_access function result
 
return node_access($op, $node);
   
}
?>

Now, unauth users have access ONLY to the pages you define and the rest of the node viewing permissions default to the node_access function.

Eric's picture

When I'm coding modules, I rely heavily on the information found here: http://api.drupal.org/api/functions. Searching for functions can show you what already exists and how to use them in your code. Before you code something from scratch (or start to write your own SQL statement), you should start with the API. To be honest, I can't say that I've never coding something from scratch.

Another way to figure out how Drupal functionality is generated is to check out the menu hook in the module. A lot of helpful information resides here. For instance, you might want to embed a forum in a block or a custom module. If the functionality you're trying to recreate is found on your site at http://YOURSITE/forum, look for the menu_hook entry for "forum". Open /modules/forum/forum.module, locate the forum_menu() function, and look in the associative array for the "forum" entry:

// it starts with:
$items['forum'] = array(

In this case, the "page callback" property of the array tells you which callback function is being used. If you search the forum.module file, you notice that this function does not exist. The "file" property of the array tells you that this function requires an additional file to function properly, in this case "forum.pages.inc". At this point, it's helpful to review the code in the page callback function and use the online API documentation as a reference. NOTE: more information about hook_menu() can be found here: http://api.drupal.org/api/function/hook_menu/6.

For this example, I decided to use the forum_get_forum() function in my code. Before I can simply call this function, I must include the same file defined in the "file" property of the menu_hook entry:

<?php
require_once(drupal_get_path('module','forum') . '/forum.pages.inc');
$forums = forum_get_forums(0);
?>

Now, I have the html generated from the forum module. You could use this same process to recreate functionality from other modules as well.