Created
February 19, 2015 18:19
-
-
Save amcgowanca/16fa6104b3db764dfbac to your computer and use it in GitHub Desktop.
Drupal 7: Path argument mapping to $form_state['values'] default
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Retrieves a single form by the $form_id and maps path arguments to values. | |
* | |
* This function mimics the behaviour of drupal_get_form() however it also | |
* provides a mechanism to map path arguments to the default values provided | |
* to the form via $form_state['values']. This solves a massive problem with | |
* the Drupal core ability to correctly handle forms with that have methods of | |
* type "GET" (<form method="get">) correctly. | |
* | |
* For example, if the requested path is /path/to/form/abc123 where `abc123` is | |
* a value that should be mapped to $form_state['values'], the | |
* $path_arg_value_map should be an associative array where the key represents | |
* the element name within $form_state['values'] and the value should represent | |
* the integer position value to retrieve `abc123` from the path using arg(). | |
* Therefore, this function call should look like: | |
* | |
* MY_MODULE_get_form('my_module_form_id', array( | |
* 'first_value' => 3, | |
* )); | |
* | |
* @param string $form_id | |
* The form id. | |
* @param array $path_arg_value_map | |
* An associative array of path segment arguments to map to the form's | |
* $form_state['values'] array. | |
* | |
* @return array|mixed | |
* Returns the retrieved and built form. | |
*/ | |
function MY_MODULE_get_form($form_id, array $path_arg_value_map = array()) { | |
$form_state = array(); | |
if (!empty($path_arg_value_map)) { | |
$values = array(); | |
foreach ($path_arg_value_map as $element_id => $position) { | |
$value = arg($position); | |
if (!empty($value)) { | |
// TODO: Determine how to best sanitize this data; for now this suffices. | |
$values[$element_id] = check_plain($value); | |
} | |
} | |
if (!empty($values)) { | |
$form_state['values'] = $values; | |
} | |
} | |
$args = func_get_args(); | |
// Remove the $form_id from the argument list. | |
array_shift($args); | |
// Remove the $path_arg_value_map from the argument list. | |
array_shift($args); | |
$form_state['build_info']['args'] = $args; | |
return drupal_build_form($form_id, $form_state); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment