Nov 27th, 2012
An example module which integrates the Flag module with a custom form.
rad_module.info
name = Rad Module description = Supplements the flag module to create a custom rad flag form core = 7.x package = Rad Modules php = 5.2.4 version = 7.x-1.0 dependencies[] = flag
rad_module.module
<?php /** * Implements hook_theme(); */ function rad_module_theme() { return array( 'rad_module_rad_flag_form' => array( 'render element' => 'form', 'template' => 'rad-module-rad-flag-form', ), ); } /** * Form to flag a node as rad */ function rad_module_rad_flag_form($form, &$form_state) { // get current node $node = menu_get_object(); // get the node id $nid = isset($node->nid) ? $node->nid : FALSE; // load the rad flag object $flag = flag_get_flag('rad'); $rad = 0; // check if the node is currently flagged if ($flag && $nid && $flag->is_flagged($nid)) { $rad = 1; } $form['rad'] = array( '#type' => 'checkbox', '#required' => FALSE, '#default_value' => $rad, // set our custom form_element wrapper '#theme_wrappers' => array('rad_module_rad_form_element'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Submit'), ); return $form; } /** * Submit handler for rad_module_rad_flag_form(). */ function rad_module_rad_flag_form_submit($form, &$form_state) { // load the current node $node = menu_get_object(); // check to see if this form was rendered on a node try { $nid = $node->nid; $type = $node->type; } catch (Exception $exc) { watchdog('rad_module', 'Only nodes can be rad' . $exc->getTraceAsString()); return; } // get a rad flag object $flag = flag_get_flag('rad'); // unflag or flag the node according to the state of the checkbox in the form if ($form_state['values']['rad'] == 0) { $flag->flag('unflag', $nid); drupal_set_message('You think this is rad'); } else { $flag->flag('flag', $nid); drupal_set_message('You do not think this is rad'); } } /** * Custom theme wrapper for the rad checkbox * @see theme_form_element(). */ function theme_rad_module_rad_form_element($variables) { $element = $variables['element']; $output = $element['#children'] . "\n"; return $output; } ?>
rad-module-rad-flag-form.tpl.php
<p class="checkbox"> <label for="rad"> <?php print render($form['rad']); ?>Recommend this paper </label> </p> <p class="buttons"> <?php print render($form['submit']); ?> </p> <?php print drupal_render_children($form); ?>