annotate includes/form.inc @ 10:6f15c9d74937

Added tag 6.4 for changeset acef7ccb09b5
author Franck Deroche <webmaster@defr.org>
date Tue, 23 Dec 2008 14:32:08 +0100
parents acef7ccb09b5
children 589fb7c02327
rev   line source
webmaster@1 1 <?php
webmaster@9 2 // $Id: form.inc,v 1.265.2.10 2008/08/13 23:59:12 drumm Exp $
webmaster@1 3
webmaster@1 4 /**
webmaster@1 5 * @defgroup forms Form builder functions
webmaster@1 6 * @{
webmaster@1 7 * Functions that build an abstract representation of a HTML form.
webmaster@1 8 *
webmaster@1 9 * All modules should declare their form builder functions to be in this
webmaster@1 10 * group and each builder function should reference its validate and submit
webmaster@1 11 * functions using \@see. Conversely, validate and submit functions should
webmaster@1 12 * reference the form builder function using \@see. For examples, of this see
webmaster@1 13 * system_modules_uninstall() or user_pass(), the latter of which has the
webmaster@1 14 * following in its doxygen documentation:
webmaster@1 15 *
webmaster@1 16 * \@ingroup forms
webmaster@1 17 * \@see user_pass_validate().
webmaster@1 18 * \@see user_pass_submit().
webmaster@1 19 *
webmaster@1 20 * @} End of "defgroup forms".
webmaster@1 21 */
webmaster@1 22
webmaster@1 23 /**
webmaster@1 24 * @defgroup form_api Form generation
webmaster@1 25 * @{
webmaster@1 26 * Functions to enable the processing and display of HTML forms.
webmaster@1 27 *
webmaster@1 28 * Drupal uses these functions to achieve consistency in its form processing and
webmaster@1 29 * presentation, while simplifying code and reducing the amount of HTML that
webmaster@1 30 * must be explicitly generated by modules.
webmaster@1 31 *
webmaster@1 32 * The drupal_get_form() function handles retrieving, processing, and
webmaster@1 33 * displaying a rendered HTML form for modules automatically. For example:
webmaster@1 34 *
webmaster@1 35 * @code
webmaster@1 36 * // Display the user registration form.
webmaster@1 37 * $output = drupal_get_form('user_register');
webmaster@1 38 * @endcode
webmaster@1 39 *
webmaster@1 40 * Forms can also be built and submitted programmatically without any user input
webmaster@1 41 * using the drupal_execute() function.
webmaster@1 42 *
webmaster@1 43 * For information on the format of the structured arrays used to define forms,
webmaster@1 44 * and more detailed explanations of the Form API workflow, see the
webmaster@1 45 * @link http://api.drupal.org/api/file/developer/topics/forms_api_reference.html reference @endlink
webmaster@1 46 * and the @link http://api.drupal.org/api/file/developer/topics/forms_api.html quickstart guide. @endlink
webmaster@1 47 */
webmaster@1 48
webmaster@1 49 /**
webmaster@1 50 * Retrieves a form from a constructor function, or from the cache if
webmaster@1 51 * the form was built in a previous page-load. The form is then passesed
webmaster@1 52 * on for processing, after and rendered for display if necessary.
webmaster@1 53 *
webmaster@1 54 * @param $form_id
webmaster@1 55 * The unique string identifying the desired form. If a function
webmaster@1 56 * with that name exists, it is called to build the form array.
webmaster@1 57 * Modules that need to generate the same form (or very similar forms)
webmaster@1 58 * using different $form_ids can implement hook_forms(), which maps
webmaster@1 59 * different $form_id values to the proper form constructor function. Examples
webmaster@1 60 * may be found in node_forms(), search_forms(), and user_forms().
webmaster@1 61 * @param ...
webmaster@1 62 * Any additional arguments are passed on to the functions called by
webmaster@1 63 * drupal_get_form(), including the unique form constructor function.
webmaster@1 64 * For example, the node_edit form requires that a node object be passed
webmaster@1 65 * in here when it is called.
webmaster@1 66 * @return
webmaster@1 67 * The rendered form.
webmaster@1 68 */
webmaster@1 69 function drupal_get_form($form_id) {
webmaster@1 70 $form_state = array('storage' => NULL, 'submitted' => FALSE);
webmaster@1 71
webmaster@1 72 $args = func_get_args();
webmaster@1 73 $cacheable = FALSE;
webmaster@1 74
webmaster@1 75 if (isset($_SESSION['batch_form_state'])) {
webmaster@1 76 // We've been redirected here after a batch processing : the form has
webmaster@1 77 // already been processed, so we grab the post-process $form_state value
webmaster@1 78 // and move on to form display. See _batch_finished() function.
webmaster@1 79 $form_state = $_SESSION['batch_form_state'];
webmaster@1 80 unset($_SESSION['batch_form_state']);
webmaster@1 81 }
webmaster@1 82 else {
webmaster@1 83 // If the incoming $_POST contains a form_build_id, we'll check the
webmaster@1 84 // cache for a copy of the form in question. If it's there, we don't
webmaster@1 85 // have to rebuild the form to proceed. In addition, if there is stored
webmaster@1 86 // form_state data from a previous step, we'll retrieve it so it can
webmaster@1 87 // be passed on to the form processing code.
webmaster@1 88 if (isset($_POST['form_id']) && $_POST['form_id'] == $form_id && !empty($_POST['form_build_id'])) {
webmaster@1 89 $form = form_get_cache($_POST['form_build_id'], $form_state);
webmaster@1 90 }
webmaster@1 91
webmaster@1 92 // If the previous bit of code didn't result in a populated $form
webmaster@1 93 // object, we're hitting the form for the first time and we need
webmaster@1 94 // to build it from scratch.
webmaster@1 95 if (!isset($form)) {
webmaster@1 96 $form_state['post'] = $_POST;
webmaster@1 97 // Use a copy of the function's arguments for manipulation
webmaster@1 98 $args_temp = $args;
webmaster@1 99 $args_temp[0] = &$form_state;
webmaster@1 100 array_unshift($args_temp, $form_id);
webmaster@1 101
webmaster@1 102 $form = call_user_func_array('drupal_retrieve_form', $args_temp);
webmaster@9 103 $form_build_id = 'form-'. md5(uniqid(mt_rand(), true));
webmaster@1 104 $form['#build_id'] = $form_build_id;
webmaster@1 105 drupal_prepare_form($form_id, $form, $form_state);
webmaster@1 106 // Store a copy of the unprocessed form for caching and indicate that it
webmaster@1 107 // is cacheable if #cache will be set.
webmaster@1 108 $original_form = $form;
webmaster@1 109 $cacheable = TRUE;
webmaster@1 110 unset($form_state['post']);
webmaster@1 111 }
webmaster@1 112 $form['#post'] = $_POST;
webmaster@1 113
webmaster@1 114 // Now that we know we have a form, we'll process it (validating,
webmaster@1 115 // submitting, and handling the results returned by its submission
webmaster@1 116 // handlers. Submit handlers accumulate data in the form_state by
webmaster@1 117 // altering the $form_state variable, which is passed into them by
webmaster@1 118 // reference.
webmaster@1 119 drupal_process_form($form_id, $form, $form_state);
webmaster@1 120 if ($cacheable && !empty($form['#cache'])) {
webmaster@1 121 // Caching is done past drupal_process_form so #process callbacks can
webmaster@1 122 // set #cache. By not sending the form state, we avoid storing
webmaster@1 123 // $form_state['storage'].
webmaster@1 124 form_set_cache($form_build_id, $original_form, NULL);
webmaster@1 125 }
webmaster@1 126 }
webmaster@1 127
webmaster@1 128 // Most simple, single-step forms will be finished by this point --
webmaster@1 129 // drupal_process_form() usually redirects to another page (or to
webmaster@1 130 // a 'fresh' copy of the form) once processing is complete. If one
webmaster@1 131 // of the form's handlers has set $form_state['redirect'] to FALSE,
webmaster@1 132 // the form will simply be re-rendered with the values still in its
webmaster@1 133 // fields.
webmaster@1 134 //
webmaster@1 135 // If $form_state['storage'] or $form_state['rebuild'] have been
webmaster@1 136 // set by any submit or validate handlers, however, we know that
webmaster@1 137 // we're in a complex multi-part process of some sort and the form's
webmaster@1 138 // workflow is NOT complete. We need to construct a fresh copy of
webmaster@1 139 // the form, passing in the latest $form_state in addition to any
webmaster@1 140 // other variables passed into drupal_get_form().
webmaster@1 141
webmaster@1 142 if (!empty($form_state['rebuild']) || !empty($form_state['storage'])) {
webmaster@1 143 $form = drupal_rebuild_form($form_id, $form_state, $args);
webmaster@1 144 }
webmaster@1 145
webmaster@1 146 // If we haven't redirected to a new location by now, we want to
webmaster@1 147 // render whatever form array is currently in hand.
webmaster@1 148 return drupal_render_form($form_id, $form);
webmaster@1 149 }
webmaster@1 150
webmaster@1 151 /**
webmaster@1 152 * Retrieves a form, caches it and processes it with an empty $_POST.
webmaster@1 153 *
webmaster@1 154 * This function clears $_POST and passes the empty $_POST to the form_builder.
webmaster@1 155 * To preserve some parts from $_POST, pass them in $form_state.
webmaster@1 156 *
webmaster@1 157 * If your AHAH callback simulates the pressing of a button, then your AHAH
webmaster@1 158 * callback will need to do the same as what drupal_get_form would do when the
webmaster@1 159 * button is pressed: get the form from the cache, run drupal_process_form over
webmaster@1 160 * it and then if it needs rebuild, run drupal_rebuild_form over it. Then send
webmaster@1 161 * back a part of the returned form.
webmaster@1 162 * $form_state['clicked_button']['#array_parents'] will help you to find which
webmaster@1 163 * part.
webmaster@1 164 *
webmaster@1 165 * @param $form_id
webmaster@1 166 * The unique string identifying the desired form. If a function
webmaster@1 167 * with that name exists, it is called to build the form array.
webmaster@1 168 * Modules that need to generate the same form (or very similar forms)
webmaster@1 169 * using different $form_ids can implement hook_forms(), which maps
webmaster@1 170 * different $form_id values to the proper form constructor function. Examples
webmaster@1 171 * may be found in node_forms(), search_forms(), and user_forms().
webmaster@1 172 * @param $form_state
webmaster@1 173 * A keyed array containing the current state of the form. Most
webmaster@1 174 * important is the $form_state['storage'] collection.
webmaster@1 175 * @param $args
webmaster@1 176 * Any additional arguments are passed on to the functions called by
webmaster@1 177 * drupal_get_form(), plus the original form_state in the beginning. If you
webmaster@1 178 * are getting a form from the cache, use $form['#parameters'] to shift off
webmaster@1 179 * the $form_id from its beginning then the resulting array can be used as
webmaster@1 180 * $arg here.
webmaster@1 181 * @param $form_build_id
webmaster@1 182 * If the AHAH callback calling this function only alters part of the form,
webmaster@1 183 * then pass in the existing form_build_id so we can re-cache with the same
webmaster@1 184 * csid.
webmaster@1 185 * @return
webmaster@1 186 * The newly built form.
webmaster@1 187 */
webmaster@1 188 function drupal_rebuild_form($form_id, &$form_state, $args, $form_build_id = NULL) {
webmaster@1 189 // Remove the first argument. This is $form_id.when called from
webmaster@1 190 // drupal_get_form and the original $form_state when called from some AHAH
webmaster@1 191 // callback. Neither is needed. After that, put in the current state.
webmaster@1 192 $args[0] = &$form_state;
webmaster@1 193 // And the form_id.
webmaster@1 194 array_unshift($args, $form_id);
webmaster@1 195 $form = call_user_func_array('drupal_retrieve_form', $args);
webmaster@1 196
webmaster@1 197 if (!isset($form_build_id)) {
webmaster@1 198 // We need a new build_id for the new version of the form.
webmaster@1 199 $form_build_id = 'form-'. md5(mt_rand());
webmaster@1 200 }
webmaster@1 201 $form['#build_id'] = $form_build_id;
webmaster@1 202 drupal_prepare_form($form_id, $form, $form_state);
webmaster@1 203
webmaster@1 204 // Now, we cache the form structure so it can be retrieved later for
webmaster@1 205 // validation. If $form_state['storage'] is populated, we'll also cache
webmaster@1 206 // it so that it can be used to resume complex multi-step processes.
webmaster@1 207 form_set_cache($form_build_id, $form, $form_state);
webmaster@1 208
webmaster@1 209 // Clear out all post data, as we don't want the previous step's
webmaster@1 210 // data to pollute this one and trigger validate/submit handling,
webmaster@1 211 // then process the form for rendering.
webmaster@1 212 $_POST = array();
webmaster@1 213 $form['#post'] = array();
webmaster@1 214 drupal_process_form($form_id, $form, $form_state);
webmaster@1 215 return $form;
webmaster@1 216 }
webmaster@1 217
webmaster@1 218 /**
webmaster@9 219 * Store a form in the cache.
webmaster@1 220 */
webmaster@9 221 function form_set_cache($form_build_id, $form, $form_state) {
webmaster@9 222 global $user;
webmaster@9 223 // 6 hours cache life time for forms should be plenty.
webmaster@9 224 $expire = 21600;
webmaster@9 225
webmaster@9 226 if ($user->uid) {
webmaster@9 227 $form['#cache_token'] = drupal_get_token();
webmaster@9 228 }
webmaster@9 229 cache_set('form_'. $form_build_id, $form, 'cache_form', time() + $expire);
webmaster@9 230 if (!empty($form_state['storage'])) {
webmaster@9 231 cache_set('storage_'. $form_build_id, $form_state['storage'], 'cache_form', time() + $expire);
webmaster@1 232 }
webmaster@1 233 }
webmaster@1 234
webmaster@1 235 /**
webmaster@9 236 * Fetch a form from cache.
webmaster@1 237 */
webmaster@9 238 function form_get_cache($form_build_id, &$form_state) {
webmaster@9 239 global $user;
webmaster@9 240 if ($cached = cache_get('form_'. $form_build_id, 'cache_form')) {
webmaster@9 241 $form = $cached->data;
webmaster@9 242 if ((isset($form['#cache_token']) && drupal_valid_token($form['#cache_token'])) || (!isset($form['#cache_token']) && !$user->uid)) {
webmaster@9 243 if ($cached = cache_get('storage_'. $form_build_id, 'cache_form')) {
webmaster@9 244 $form_state['storage'] = $cached->data;
webmaster@9 245 }
webmaster@9 246 return $form;
webmaster@9 247 }
webmaster@1 248 }
webmaster@1 249 }
webmaster@1 250
webmaster@1 251 /**
webmaster@1 252 * Retrieves a form using a form_id, populates it with $form_state['values'],
webmaster@1 253 * processes it, and returns any validation errors encountered. This
webmaster@1 254 * function is the programmatic counterpart to drupal_get_form().
webmaster@1 255 *
webmaster@1 256 * @param $form_id
webmaster@1 257 * The unique string identifying the desired form. If a function
webmaster@1 258 * with that name exists, it is called to build the form array.
webmaster@1 259 * Modules that need to generate the same form (or very similar forms)
webmaster@1 260 * using different $form_ids can implement hook_forms(), which maps
webmaster@1 261 * different $form_id values to the proper form constructor function. Examples
webmaster@1 262 * may be found in node_forms(), search_forms(), and user_forms().
webmaster@1 263 * @param $form_state
webmaster@1 264 * A keyed array containing the current state of the form. Most
webmaster@1 265 * important is the $form_state['values'] collection, a tree of data
webmaster@1 266 * used to simulate the incoming $_POST information from a user's
webmaster@1 267 * form submission.
webmaster@1 268 * @param ...
webmaster@1 269 * Any additional arguments are passed on to the functions called by
webmaster@1 270 * drupal_execute(), including the unique form constructor function.
webmaster@1 271 * For example, the node_edit form requires that a node object be passed
webmaster@1 272 * in here when it is called.
webmaster@1 273 * For example:
webmaster@1 274 *
webmaster@1 275 * // register a new user
webmaster@1 276 * $form_state = array();
webmaster@1 277 * $form_state['values']['name'] = 'robo-user';
webmaster@1 278 * $form_state['values']['mail'] = 'robouser@example.com';
webmaster@1 279 * $form_state['values']['pass'] = 'password';
webmaster@1 280 * $form_state['values']['op'] = t('Create new account');
webmaster@1 281 * drupal_execute('user_register', $form_state);
webmaster@1 282 *
webmaster@1 283 * // Create a new node
webmaster@1 284 * $form_state = array();
webmaster@1 285 * module_load_include('inc', 'node', 'node.pages');
webmaster@1 286 * $node = array('type' => 'story');
webmaster@1 287 * $form_state['values']['title'] = 'My node';
webmaster@1 288 * $form_state['values']['body'] = 'This is the body text!';
webmaster@1 289 * $form_state['values']['name'] = 'robo-user';
webmaster@1 290 * $form_state['values']['op'] = t('Save');
webmaster@1 291 * drupal_execute('story_node_form', $form_state, (object)$node);
webmaster@1 292 */
webmaster@1 293 function drupal_execute($form_id, &$form_state) {
webmaster@1 294 $args = func_get_args();
webmaster@1 295 $form = call_user_func_array('drupal_retrieve_form', $args);
webmaster@1 296 $form['#post'] = $form_state['values'];
webmaster@1 297 drupal_prepare_form($form_id, $form, $form_state);
webmaster@1 298 drupal_process_form($form_id, $form, $form_state);
webmaster@1 299 }
webmaster@1 300
webmaster@1 301 /**
webmaster@1 302 * Retrieves the structured array that defines a given form.
webmaster@1 303 *
webmaster@1 304 * @param $form_id
webmaster@1 305 * The unique string identifying the desired form. If a function
webmaster@1 306 * with that name exists, it is called to build the form array.
webmaster@1 307 * Modules that need to generate the same form (or very similar forms)
webmaster@1 308 * using different $form_ids can implement hook_forms(), which maps
webmaster@1 309 * different $form_id values to the proper form constructor function.
webmaster@1 310 * @param $form_state
webmaster@1 311 * A keyed array containing the current state of the form.
webmaster@1 312 * @param ...
webmaster@1 313 * Any additional arguments needed by the unique form constructor
webmaster@1 314 * function. Generally, these are any arguments passed into the
webmaster@1 315 * drupal_get_form() or drupal_execute() functions after the first
webmaster@1 316 * argument. If a module implements hook_forms(), it can examine
webmaster@1 317 * these additional arguments and conditionally return different
webmaster@1 318 * builder functions as well.
webmaster@1 319 */
webmaster@1 320 function drupal_retrieve_form($form_id, &$form_state) {
webmaster@1 321 static $forms;
webmaster@1 322
webmaster@1 323 // We save two copies of the incoming arguments: one for modules to use
webmaster@1 324 // when mapping form ids to constructor functions, and another to pass to
webmaster@1 325 // the constructor function itself. We shift out the first argument -- the
webmaster@1 326 // $form_id itself -- from the list to pass into the constructor function,
webmaster@1 327 // since it's already known.
webmaster@1 328 $args = func_get_args();
webmaster@1 329 $saved_args = $args;
webmaster@1 330 array_shift($args);
webmaster@1 331 if (isset($form_state)) {
webmaster@1 332 array_shift($args);
webmaster@1 333 }
webmaster@1 334
webmaster@1 335 // We first check to see if there's a function named after the $form_id.
webmaster@1 336 // If there is, we simply pass the arguments on to it to get the form.
webmaster@1 337 if (!function_exists($form_id)) {
webmaster@1 338 // In cases where many form_ids need to share a central constructor function,
webmaster@1 339 // such as the node editing form, modules can implement hook_forms(). It
webmaster@1 340 // maps one or more form_ids to the correct constructor functions.
webmaster@1 341 //
webmaster@1 342 // We cache the results of that hook to save time, but that only works
webmaster@1 343 // for modules that know all their form_ids in advance. (A module that
webmaster@1 344 // adds a small 'rate this comment' form to each comment in a list
webmaster@1 345 // would need a unique form_id for each one, for example.)
webmaster@1 346 //
webmaster@1 347 // So, we call the hook if $forms isn't yet populated, OR if it doesn't
webmaster@1 348 // yet have an entry for the requested form_id.
webmaster@1 349 if (!isset($forms) || !isset($forms[$form_id])) {
webmaster@1 350 $forms = module_invoke_all('forms', $form_id, $args);
webmaster@1 351 }
webmaster@1 352 $form_definition = $forms[$form_id];
webmaster@1 353 if (isset($form_definition['callback arguments'])) {
webmaster@1 354 $args = array_merge($form_definition['callback arguments'], $args);
webmaster@1 355 }
webmaster@1 356 if (isset($form_definition['callback'])) {
webmaster@1 357 $callback = $form_definition['callback'];
webmaster@1 358 }
webmaster@1 359 }
webmaster@1 360
webmaster@1 361 array_unshift($args, NULL);
webmaster@1 362 $args[0] = &$form_state;
webmaster@1 363
webmaster@1 364 // If $callback was returned by a hook_forms() implementation, call it.
webmaster@1 365 // Otherwise, call the function named after the form id.
webmaster@1 366 $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
webmaster@1 367
webmaster@1 368 // We store the original function arguments, rather than the final $arg
webmaster@1 369 // value, so that form_alter functions can see what was originally
webmaster@1 370 // passed to drupal_retrieve_form(). This allows the contents of #parameters
webmaster@1 371 // to be saved and passed in at a later date to recreate the form.
webmaster@1 372 $form['#parameters'] = $saved_args;
webmaster@1 373 return $form;
webmaster@1 374 }
webmaster@1 375
webmaster@1 376 /**
webmaster@1 377 * This function is the heart of form API. The form gets built, validated and in
webmaster@1 378 * appropriate cases, submitted.
webmaster@1 379 *
webmaster@1 380 * @param $form_id
webmaster@1 381 * The unique string identifying the current form.
webmaster@1 382 * @param $form
webmaster@1 383 * An associative array containing the structure of the form.
webmaster@1 384 * @param $form_state
webmaster@1 385 * A keyed array containing the current state of the form. This
webmaster@1 386 * includes the current persistent storage data for the form, and
webmaster@1 387 * any data passed along by earlier steps when displaying a
webmaster@1 388 * multi-step form. Additional information, like the sanitized $_POST
webmaster@1 389 * data, is also accumulated here.
webmaster@1 390 */
webmaster@1 391 function drupal_process_form($form_id, &$form, &$form_state) {
webmaster@1 392 $form_state['values'] = array();
webmaster@1 393
webmaster@1 394 $form = form_builder($form_id, $form, $form_state);
webmaster@1 395 // Only process the form if it is programmed or the form_id coming
webmaster@1 396 // from the POST data is set and matches the current form_id.
webmaster@1 397 if ((!empty($form['#programmed'])) || (!empty($form['#post']) && (isset($form['#post']['form_id']) && ($form['#post']['form_id'] == $form_id)))) {
webmaster@1 398 drupal_validate_form($form_id, $form, $form_state);
webmaster@1 399
webmaster@1 400 // form_clean_id() maintains a cache of element IDs it has seen,
webmaster@1 401 // so it can prevent duplicates. We want to be sure we reset that
webmaster@1 402 // cache when a form is processed, so scenerios that result in
webmaster@1 403 // the form being built behind the scenes and again for the
webmaster@1 404 // browser don't increment all the element IDs needlessly.
webmaster@1 405 form_clean_id(NULL, TRUE);
webmaster@1 406
webmaster@1 407 if ((!empty($form_state['submitted'])) && !form_get_errors() && empty($form_state['rebuild'])) {
webmaster@1 408 $form_state['redirect'] = NULL;
webmaster@1 409 form_execute_handlers('submit', $form, $form_state);
webmaster@1 410
webmaster@1 411 // We'll clear out the cached copies of the form and its stored data
webmaster@1 412 // here, as we've finished with them. The in-memory copies are still
webmaster@1 413 // here, though.
webmaster@1 414 if (variable_get('cache', CACHE_DISABLED) == CACHE_DISABLED && !empty($form_state['values']['form_build_id'])) {
webmaster@1 415 cache_clear_all('form_'. $form_state['values']['form_build_id'], 'cache_form');
webmaster@1 416 cache_clear_all('storage_'. $form_state['values']['form_build_id'], 'cache_form');
webmaster@1 417 }
webmaster@1 418
webmaster@1 419 // If batches were set in the submit handlers, we process them now,
webmaster@1 420 // possibly ending execution. We make sure we do not react to the batch
webmaster@1 421 // that is already being processed (if a batch operation performs a
webmaster@1 422 // drupal_execute).
webmaster@1 423 if ($batch =& batch_get() && !isset($batch['current_set'])) {
webmaster@1 424 // The batch uses its own copies of $form and $form_state for
webmaster@1 425 // late execution of submit handers and post-batch redirection.
webmaster@1 426 $batch['form'] = $form;
webmaster@1 427 $batch['form_state'] = $form_state;
webmaster@1 428 $batch['progressive'] = !$form['#programmed'];
webmaster@1 429 batch_process();
webmaster@1 430 // Execution continues only for programmatic forms.
webmaster@1 431 // For 'regular' forms, we get redirected to the batch processing
webmaster@1 432 // page. Form redirection will be handled in _batch_finished(),
webmaster@1 433 // after the batch is processed.
webmaster@1 434 }
webmaster@1 435
webmaster@1 436 // If no submit handlers have populated the $form_state['storage']
webmaster@1 437 // bundle, and the $form_state['rebuild'] flag has not been set,
webmaster@1 438 // we're finished and should redirect to a new destination page
webmaster@1 439 // if one has been set (and a fresh, unpopulated copy of the form
webmaster@1 440 // if one hasn't). If the form was called by drupal_execute(),
webmaster@1 441 // however, we'll skip this and let the calling function examine
webmaster@1 442 // the resulting $form_state bundle itself.
webmaster@1 443 if (!$form['#programmed'] && empty($form_state['rebuild']) && empty($form_state['storage'])) {
webmaster@1 444 drupal_redirect_form($form, $form_state['redirect']);
webmaster@1 445 }
webmaster@1 446 }
webmaster@1 447 }
webmaster@1 448 }
webmaster@1 449
webmaster@1 450 /**
webmaster@1 451 * Prepares a structured form array by adding required elements,
webmaster@1 452 * executing any hook_form_alter functions, and optionally inserting
webmaster@1 453 * a validation token to prevent tampering.
webmaster@1 454 *
webmaster@1 455 * @param $form_id
webmaster@1 456 * A unique string identifying the form for validation, submission,
webmaster@1 457 * theming, and hook_form_alter functions.
webmaster@1 458 * @param $form
webmaster@1 459 * An associative array containing the structure of the form.
webmaster@1 460 * @param $form_state
webmaster@1 461 * A keyed array containing the current state of the form. Passed
webmaster@1 462 * in here so that hook_form_alter() calls can use it, as well.
webmaster@1 463 */
webmaster@1 464 function drupal_prepare_form($form_id, &$form, &$form_state) {
webmaster@1 465 global $user;
webmaster@1 466
webmaster@1 467 $form['#type'] = 'form';
webmaster@1 468 $form['#programmed'] = isset($form['#post']);
webmaster@1 469
webmaster@1 470 if (isset($form['#build_id'])) {
webmaster@1 471 $form['form_build_id'] = array(
webmaster@1 472 '#type' => 'hidden',
webmaster@1 473 '#value' => $form['#build_id'],
webmaster@1 474 '#id' => $form['#build_id'],
webmaster@1 475 '#name' => 'form_build_id',
webmaster@1 476 );
webmaster@1 477 }
webmaster@1 478
webmaster@1 479 // Add a token, based on either #token or form_id, to any form displayed to
webmaster@1 480 // authenticated users. This ensures that any submitted form was actually
webmaster@1 481 // requested previously by the user and protects against cross site request
webmaster@1 482 // forgeries.
webmaster@1 483 if (isset($form['#token'])) {
webmaster@1 484 if ($form['#token'] === FALSE || $user->uid == 0 || $form['#programmed']) {
webmaster@1 485 unset($form['#token']);
webmaster@1 486 }
webmaster@1 487 else {
webmaster@1 488 $form['form_token'] = array('#type' => 'token', '#default_value' => drupal_get_token($form['#token']));
webmaster@1 489 }
webmaster@1 490 }
webmaster@1 491 else if (isset($user->uid) && $user->uid && !$form['#programmed']) {
webmaster@1 492 $form['#token'] = $form_id;
webmaster@1 493 $form['form_token'] = array(
webmaster@1 494 '#id' => form_clean_id('edit-'. $form_id .'-form-token'),
webmaster@1 495 '#type' => 'token',
webmaster@1 496 '#default_value' => drupal_get_token($form['#token']),
webmaster@1 497 );
webmaster@1 498 }
webmaster@1 499
webmaster@1 500 if (isset($form_id)) {
webmaster@1 501 $form['form_id'] = array(
webmaster@1 502 '#type' => 'hidden',
webmaster@1 503 '#value' => $form_id,
webmaster@1 504 '#id' => form_clean_id("edit-$form_id"),
webmaster@1 505 );
webmaster@1 506 }
webmaster@1 507 if (!isset($form['#id'])) {
webmaster@1 508 $form['#id'] = form_clean_id($form_id);
webmaster@1 509 }
webmaster@1 510
webmaster@1 511 $form += _element_info('form');
webmaster@1 512
webmaster@1 513 if (!isset($form['#validate'])) {
webmaster@1 514 if (function_exists($form_id .'_validate')) {
webmaster@1 515 $form['#validate'] = array($form_id .'_validate');
webmaster@1 516 }
webmaster@1 517 }
webmaster@1 518
webmaster@1 519 if (!isset($form['#submit'])) {
webmaster@1 520 if (function_exists($form_id .'_submit')) {
webmaster@1 521 // We set submit here so that it can be altered.
webmaster@1 522 $form['#submit'] = array($form_id .'_submit');
webmaster@1 523 }
webmaster@1 524 }
webmaster@1 525
webmaster@1 526 // Normally, we would call drupal_alter($form_id, $form, $form_state).
webmaster@1 527 // However, drupal_alter() normally supports just one byref parameter. Using
webmaster@1 528 // the __drupal_alter_by_ref key, we can store any additional parameters
webmaster@1 529 // that need to be altered, and they'll be split out into additional params
webmaster@1 530 // for the hook_form_alter() implementations.
webmaster@1 531 // @todo: Remove this in Drupal 7.
webmaster@1 532 $data = &$form;
webmaster@1 533 $data['__drupal_alter_by_ref'] = array(&$form_state);
webmaster@1 534 drupal_alter('form_'. $form_id, $data);
webmaster@1 535
webmaster@1 536 // __drupal_alter_by_ref is unset in the drupal_alter() function, we need
webmaster@1 537 // to repopulate it to ensure both calls get the data.
webmaster@1 538 $data['__drupal_alter_by_ref'] = array(&$form_state);
webmaster@1 539 drupal_alter('form', $data, $form_id);
webmaster@1 540 }
webmaster@1 541
webmaster@1 542
webmaster@1 543 /**
webmaster@1 544 * Validates user-submitted form data from the $form_state using
webmaster@1 545 * the validate functions defined in a structured form array.
webmaster@1 546 *
webmaster@1 547 * @param $form_id
webmaster@1 548 * A unique string identifying the form for validation, submission,
webmaster@1 549 * theming, and hook_form_alter functions.
webmaster@1 550 * @param $form
webmaster@1 551 * An associative array containing the structure of the form.
webmaster@1 552 * @param $form_state
webmaster@1 553 * A keyed array containing the current state of the form. The current
webmaster@1 554 * user-submitted data is stored in $form_state['values'], though
webmaster@1 555 * form validation functions are passed an explicit copy of the
webmaster@1 556 * values for the sake of simplicity. Validation handlers can also
webmaster@1 557 * $form_state to pass information on to submit handlers. For example:
webmaster@1 558 * $form_state['data_for_submision'] = $data;
webmaster@1 559 * This technique is useful when validation requires file parsing,
webmaster@1 560 * web service requests, or other expensive requests that should
webmaster@1 561 * not be repeated in the submission step.
webmaster@1 562 */
webmaster@1 563 function drupal_validate_form($form_id, $form, &$form_state) {
webmaster@1 564 static $validated_forms = array();
webmaster@1 565
webmaster@1 566 if (isset($validated_forms[$form_id])) {
webmaster@1 567 return;
webmaster@1 568 }
webmaster@1 569
webmaster@1 570 // If the session token was set by drupal_prepare_form(), ensure that it
webmaster@1 571 // matches the current user's session.
webmaster@1 572 if (isset($form['#token'])) {
webmaster@1 573 if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
webmaster@1 574 // Setting this error will cause the form to fail validation.
webmaster@1 575 form_set_error('form_token', t('Validation error, please try again. If this error persists, please contact the site administrator.'));
webmaster@1 576 }
webmaster@1 577 }
webmaster@1 578
webmaster@1 579 _form_validate($form, $form_state, $form_id);
webmaster@1 580 $validated_forms[$form_id] = TRUE;
webmaster@1 581 }
webmaster@1 582
webmaster@1 583 /**
webmaster@1 584 * Renders a structured form array into themed HTML.
webmaster@1 585 *
webmaster@1 586 * @param $form_id
webmaster@1 587 * A unique string identifying the form for validation, submission,
webmaster@1 588 * theming, and hook_form_alter functions.
webmaster@1 589 * @param $form
webmaster@1 590 * An associative array containing the structure of the form.
webmaster@1 591 * @return
webmaster@1 592 * A string containing the path of the page to display when processing
webmaster@1 593 * is complete.
webmaster@1 594 */
webmaster@1 595 function drupal_render_form($form_id, &$form) {
webmaster@1 596 // Don't override #theme if someone already set it.
webmaster@1 597 if (!isset($form['#theme'])) {
webmaster@1 598 init_theme();
webmaster@1 599 $registry = theme_get_registry();
webmaster@1 600 if (isset($registry[$form_id])) {
webmaster@1 601 $form['#theme'] = $form_id;
webmaster@1 602 }
webmaster@1 603 }
webmaster@1 604
webmaster@1 605 $output = drupal_render($form);
webmaster@1 606 return $output;
webmaster@1 607 }
webmaster@1 608
webmaster@1 609 /**
webmaster@1 610 * Redirect the user to a URL after a form has been processed.
webmaster@1 611 *
webmaster@1 612 * @param $form
webmaster@1 613 * An associative array containing the structure of the form.
webmaster@1 614 * @param $redirect
webmaster@1 615 * An optional value containing the destination path to redirect
webmaster@1 616 * to if none is specified by the form.
webmaster@1 617 */
webmaster@1 618 function drupal_redirect_form($form, $redirect = NULL) {
webmaster@1 619 $goto = NULL;
webmaster@1 620 if (isset($redirect)) {
webmaster@1 621 $goto = $redirect;
webmaster@1 622 }
webmaster@1 623 if ($goto !== FALSE && isset($form['#redirect'])) {
webmaster@1 624 $goto = $form['#redirect'];
webmaster@1 625 }
webmaster@1 626 if (!isset($goto) || ($goto !== FALSE)) {
webmaster@1 627 if (isset($goto)) {
webmaster@1 628 if (is_array($goto)) {
webmaster@1 629 call_user_func_array('drupal_goto', $goto);
webmaster@1 630 }
webmaster@1 631 else {
webmaster@1 632 drupal_goto($goto);
webmaster@1 633 }
webmaster@1 634 }
webmaster@1 635 drupal_goto($_GET['q']);
webmaster@1 636 }
webmaster@1 637 }
webmaster@1 638
webmaster@1 639 /**
webmaster@1 640 * Performs validation on form elements. First ensures required fields are
webmaster@1 641 * completed, #maxlength is not exceeded, and selected options were in the
webmaster@1 642 * list of options given to the user. Then calls user-defined validators.
webmaster@1 643 *
webmaster@1 644 * @param $elements
webmaster@1 645 * An associative array containing the structure of the form.
webmaster@1 646 * @param $form_state
webmaster@1 647 * A keyed array containing the current state of the form. The current
webmaster@1 648 * user-submitted data is stored in $form_state['values'], though
webmaster@1 649 * form validation functions are passed an explicit copy of the
webmaster@1 650 * values for the sake of simplicity. Validation handlers can also
webmaster@1 651 * $form_state to pass information on to submit handlers. For example:
webmaster@1 652 * $form_state['data_for_submision'] = $data;
webmaster@1 653 * This technique is useful when validation requires file parsing,
webmaster@1 654 * web service requests, or other expensive requests that should
webmaster@1 655 * not be repeated in the submission step.
webmaster@1 656 * @param $form_id
webmaster@1 657 * A unique string identifying the form for validation, submission,
webmaster@1 658 * theming, and hook_form_alter functions.
webmaster@1 659 */
webmaster@1 660 function _form_validate($elements, &$form_state, $form_id = NULL) {
webmaster@1 661 static $complete_form;
webmaster@1 662
webmaster@1 663 // Also used in the installer, pre-database setup.
webmaster@1 664 $t = get_t();
webmaster@1 665
webmaster@1 666 // Recurse through all children.
webmaster@1 667 foreach (element_children($elements) as $key) {
webmaster@1 668 if (isset($elements[$key]) && $elements[$key]) {
webmaster@1 669 _form_validate($elements[$key], $form_state);
webmaster@1 670 }
webmaster@1 671 }
webmaster@1 672 // Validate the current input.
webmaster@1 673 if (!isset($elements['#validated']) || !$elements['#validated']) {
webmaster@1 674 if (isset($elements['#needs_validation'])) {
webmaster@1 675 // Make sure a value is passed when the field is required.
webmaster@1 676 // A simple call to empty() will not cut it here as some fields, like
webmaster@1 677 // checkboxes, can return a valid value of '0'. Instead, check the
webmaster@1 678 // length if it's a string, and the item count if it's an array.
webmaster@1 679 if ($elements['#required'] && (!count($elements['#value']) || (is_string($elements['#value']) && strlen(trim($elements['#value'])) == 0))) {
webmaster@1 680 form_error($elements, $t('!name field is required.', array('!name' => $elements['#title'])));
webmaster@1 681 }
webmaster@1 682
webmaster@1 683 // Verify that the value is not longer than #maxlength.
webmaster@1 684 if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
webmaster@1 685 form_error($elements, $t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => drupal_strlen($elements['#value']))));
webmaster@1 686 }
webmaster@1 687
webmaster@1 688 if (isset($elements['#options']) && isset($elements['#value'])) {
webmaster@1 689 if ($elements['#type'] == 'select') {
webmaster@1 690 $options = form_options_flatten($elements['#options']);
webmaster@1 691 }
webmaster@1 692 else {
webmaster@1 693 $options = $elements['#options'];
webmaster@1 694 }
webmaster@1 695 if (is_array($elements['#value'])) {
webmaster@1 696 $value = $elements['#type'] == 'checkboxes' ? array_keys(array_filter($elements['#value'])) : $elements['#value'];
webmaster@1 697 foreach ($value as $v) {
webmaster@1 698 if (!isset($options[$v])) {
webmaster@1 699 form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
webmaster@1 700 watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
webmaster@1 701 }
webmaster@1 702 }
webmaster@1 703 }
webmaster@1 704 elseif (!isset($options[$elements['#value']])) {
webmaster@1 705 form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
webmaster@1 706 watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
webmaster@1 707 }
webmaster@1 708 }
webmaster@1 709 }
webmaster@1 710
webmaster@1 711 // Call user-defined form level validators and store a copy of the full
webmaster@1 712 // form so that element-specific validators can examine the entire structure
webmaster@1 713 // if necessary.
webmaster@1 714 if (isset($form_id)) {
webmaster@1 715 form_execute_handlers('validate', $elements, $form_state);
webmaster@1 716 $complete_form = $elements;
webmaster@1 717 }
webmaster@1 718 // Call any element-specific validators. These must act on the element
webmaster@1 719 // #value data.
webmaster@1 720 elseif (isset($elements['#element_validate'])) {
webmaster@1 721 foreach ($elements['#element_validate'] as $function) {
webmaster@1 722 if (function_exists($function)) {
webmaster@1 723 $function($elements, $form_state, $complete_form);
webmaster@1 724 }
webmaster@1 725 }
webmaster@1 726 }
webmaster@1 727 $elements['#validated'] = TRUE;
webmaster@1 728 }
webmaster@1 729 }
webmaster@1 730
webmaster@1 731 /**
webmaster@1 732 * A helper function used to execute custom validation and submission
webmaster@1 733 * handlers for a given form. Button-specific handlers are checked
webmaster@1 734 * first. If none exist, the function falls back to form-level handlers.
webmaster@1 735 *
webmaster@1 736 * @param $type
webmaster@1 737 * The type of handler to execute. 'validate' or 'submit' are the
webmaster@1 738 * defaults used by Form API.
webmaster@1 739 * @param $form
webmaster@1 740 * An associative array containing the structure of the form.
webmaster@1 741 * @param $form_state
webmaster@1 742 * A keyed array containing the current state of the form. If the user
webmaster@1 743 * submitted the form by clicking a button with custom handler functions
webmaster@1 744 * defined, those handlers will be stored here.
webmaster@1 745 */
webmaster@1 746 function form_execute_handlers($type, &$form, &$form_state) {
webmaster@1 747 $return = FALSE;
webmaster@1 748 if (isset($form_state[$type .'_handlers'])) {
webmaster@1 749 $handlers = $form_state[$type .'_handlers'];
webmaster@1 750 }
webmaster@1 751 elseif (isset($form['#'. $type])) {
webmaster@1 752 $handlers = $form['#'. $type];
webmaster@1 753 }
webmaster@1 754 else {
webmaster@1 755 $handlers = array();
webmaster@1 756 }
webmaster@1 757
webmaster@1 758 foreach ($handlers as $function) {
webmaster@1 759 if (function_exists($function)) {
webmaster@1 760 if ($type == 'submit' && ($batch =& batch_get())) {
webmaster@1 761 // Some previous _submit handler has set a batch. We store the call
webmaster@1 762 // in a special 'control' batch set, for execution at the correct
webmaster@1 763 // time during the batch processing workflow.
webmaster@1 764 $batch['sets'][] = array('form_submit' => $function);
webmaster@1 765 }
webmaster@1 766 else {
webmaster@1 767 $function($form, $form_state);
webmaster@1 768 }
webmaster@1 769 $return = TRUE;
webmaster@1 770 }
webmaster@1 771 }
webmaster@1 772 return $return;
webmaster@1 773 }
webmaster@1 774
webmaster@1 775 /**
webmaster@1 776 * File an error against a form element.
webmaster@1 777 *
webmaster@1 778 * @param $name
webmaster@1 779 * The name of the form element. If the #parents property of your form
webmaster@1 780 * element is array('foo', 'bar', 'baz') then you may set an error on 'foo'
webmaster@1 781 * or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every
webmaster@1 782 * element where the #parents array starts with 'foo'.
webmaster@1 783 * @param $message
webmaster@1 784 * The error message to present to the user.
webmaster@1 785 * @return
webmaster@1 786 * Never use the return value of this function, use form_get_errors and
webmaster@1 787 * form_get_error instead.
webmaster@1 788 */
webmaster@1 789 function form_set_error($name = NULL, $message = '') {
webmaster@1 790 static $form = array();
webmaster@1 791 if (isset($name) && !isset($form[$name])) {
webmaster@1 792 $form[$name] = $message;
webmaster@1 793 if ($message) {
webmaster@1 794 drupal_set_message($message, 'error');
webmaster@1 795 }
webmaster@1 796 }
webmaster@1 797 return $form;
webmaster@1 798 }
webmaster@1 799
webmaster@1 800 /**
webmaster@1 801 * Return an associative array of all errors.
webmaster@1 802 */
webmaster@1 803 function form_get_errors() {
webmaster@1 804 $form = form_set_error();
webmaster@1 805 if (!empty($form)) {
webmaster@1 806 return $form;
webmaster@1 807 }
webmaster@1 808 }
webmaster@1 809
webmaster@1 810 /**
webmaster@1 811 * Return the error message filed against the form with the specified name.
webmaster@1 812 */
webmaster@1 813 function form_get_error($element) {
webmaster@1 814 $form = form_set_error();
webmaster@1 815 $key = $element['#parents'][0];
webmaster@1 816 if (isset($form[$key])) {
webmaster@1 817 return $form[$key];
webmaster@1 818 }
webmaster@1 819 $key = implode('][', $element['#parents']);
webmaster@1 820 if (isset($form[$key])) {
webmaster@1 821 return $form[$key];
webmaster@1 822 }
webmaster@1 823 }
webmaster@1 824
webmaster@1 825 /**
webmaster@1 826 * Flag an element as having an error.
webmaster@1 827 */
webmaster@1 828 function form_error(&$element, $message = '') {
webmaster@1 829 form_set_error(implode('][', $element['#parents']), $message);
webmaster@1 830 }
webmaster@1 831
webmaster@1 832 /**
webmaster@1 833 * Walk through the structured form array, adding any required
webmaster@1 834 * properties to each element and mapping the incoming $_POST
webmaster@1 835 * data to the proper elements.
webmaster@1 836 *
webmaster@1 837 * @param $form_id
webmaster@1 838 * A unique string identifying the form for validation, submission,
webmaster@1 839 * theming, and hook_form_alter functions.
webmaster@1 840 * @param $form
webmaster@1 841 * An associative array containing the structure of the form.
webmaster@1 842 * @param $form_state
webmaster@1 843 * A keyed array containing the current state of the form. In this
webmaster@1 844 * context, it is used to accumulate information about which button
webmaster@1 845 * was clicked when the form was submitted, as well as the sanitized
webmaster@1 846 * $_POST data.
webmaster@1 847 */
webmaster@1 848 function form_builder($form_id, $form, &$form_state) {
webmaster@1 849 static $complete_form, $cache;
webmaster@1 850
webmaster@1 851 // Initialize as unprocessed.
webmaster@1 852 $form['#processed'] = FALSE;
webmaster@1 853
webmaster@1 854 // Use element defaults.
webmaster@1 855 if ((!empty($form['#type'])) && ($info = _element_info($form['#type']))) {
webmaster@1 856 // Overlay $info onto $form, retaining preexisting keys in $form.
webmaster@1 857 $form += $info;
webmaster@1 858 }
webmaster@1 859
webmaster@1 860 if (isset($form['#type']) && $form['#type'] == 'form') {
webmaster@1 861 $cache = NULL;
webmaster@1 862 $complete_form = $form;
webmaster@1 863 if (!empty($form['#programmed'])) {
webmaster@1 864 $form_state['submitted'] = TRUE;
webmaster@1 865 }
webmaster@1 866 }
webmaster@1 867
webmaster@1 868 if (isset($form['#input']) && $form['#input']) {
webmaster@1 869 _form_builder_handle_input_element($form_id, $form, $form_state, $complete_form);
webmaster@1 870 }
webmaster@1 871 $form['#defaults_loaded'] = TRUE;
webmaster@1 872
webmaster@1 873 // We start off assuming all form elements are in the correct order.
webmaster@1 874 $form['#sorted'] = TRUE;
webmaster@1 875
webmaster@1 876 // Recurse through all child elements.
webmaster@1 877 $count = 0;
webmaster@1 878 foreach (element_children($form) as $key) {
webmaster@1 879 $form[$key]['#post'] = $form['#post'];
webmaster@1 880 $form[$key]['#programmed'] = $form['#programmed'];
webmaster@1 881 // Don't squash an existing tree value.
webmaster@1 882 if (!isset($form[$key]['#tree'])) {
webmaster@1 883 $form[$key]['#tree'] = $form['#tree'];
webmaster@1 884 }
webmaster@1 885
webmaster@1 886 // Deny access to child elements if parent is denied.
webmaster@1 887 if (isset($form['#access']) && !$form['#access']) {
webmaster@1 888 $form[$key]['#access'] = FALSE;
webmaster@1 889 }
webmaster@1 890
webmaster@1 891 // Don't squash existing parents value.
webmaster@1 892 if (!isset($form[$key]['#parents'])) {
webmaster@1 893 // Check to see if a tree of child elements is present. If so,
webmaster@1 894 // continue down the tree if required.
webmaster@1 895 $form[$key]['#parents'] = $form[$key]['#tree'] && $form['#tree'] ? array_merge($form['#parents'], array($key)) : array($key);
webmaster@1 896 $array_parents = isset($form['#array_parents']) ? $form['#array_parents'] : array();
webmaster@1 897 $array_parents[] = $key;
webmaster@1 898 $form[$key]['#array_parents'] = $array_parents;
webmaster@1 899 }
webmaster@1 900
webmaster@1 901 // Assign a decimal placeholder weight to preserve original array order.
webmaster@1 902 if (!isset($form[$key]['#weight'])) {
webmaster@1 903 $form[$key]['#weight'] = $count/1000;
webmaster@1 904 }
webmaster@1 905 else {
webmaster@1 906 // If one of the child elements has a weight then we will need to sort
webmaster@1 907 // later.
webmaster@1 908 unset($form['#sorted']);
webmaster@1 909 }
webmaster@1 910 $form[$key] = form_builder($form_id, $form[$key], $form_state);
webmaster@1 911 $count++;
webmaster@1 912 }
webmaster@1 913
webmaster@1 914 // The #after_build flag allows any piece of a form to be altered
webmaster@1 915 // after normal input parsing has been completed.
webmaster@1 916 if (isset($form['#after_build']) && !isset($form['#after_build_done'])) {
webmaster@1 917 foreach ($form['#after_build'] as $function) {
webmaster@1 918 $form = $function($form, $form_state);
webmaster@1 919 $form['#after_build_done'] = TRUE;
webmaster@1 920 }
webmaster@1 921 }
webmaster@1 922
webmaster@1 923 // Now that we've processed everything, we can go back to handle the funky
webmaster@1 924 // Internet Explorer button-click scenario.
webmaster@1 925 _form_builder_ie_cleanup($form, $form_state);
webmaster@1 926
webmaster@1 927 // We shoud keep the buttons array until the IE clean up function
webmaster@1 928 // has recognized the submit button so the form has been marked
webmaster@1 929 // as submitted. If we already know which button was submitted,
webmaster@1 930 // we don't need the array.
webmaster@1 931 if (!empty($form_state['submitted'])) {
webmaster@1 932 unset($form_state['buttons']);
webmaster@1 933 }
webmaster@1 934
webmaster@1 935 // If some callback set #cache, we need to flip a static flag so later it
webmaster@1 936 // can be found.
webmaster@1 937 if (isset($form['#cache'])) {
webmaster@1 938 $cache = $form['#cache'];
webmaster@1 939 }
webmaster@1 940 // We are on the top form, we can copy back #cache if it's set.
webmaster@1 941 if (isset($form['#type']) && $form['#type'] == 'form' && isset($cache)) {
webmaster@1 942 $form['#cache'] = TRUE;
webmaster@1 943 }
webmaster@1 944 return $form;
webmaster@1 945 }
webmaster@1 946
webmaster@1 947 /**
webmaster@1 948 * Populate the #value and #name properties of input elements so they
webmaster@1 949 * can be processed and rendered. Also, execute any #process handlers
webmaster@1 950 * attached to a specific element.
webmaster@1 951 */
webmaster@1 952 function _form_builder_handle_input_element($form_id, &$form, &$form_state, $complete_form) {
webmaster@1 953 if (!isset($form['#name'])) {
webmaster@1 954 $name = array_shift($form['#parents']);
webmaster@1 955 $form['#name'] = $name;
webmaster@1 956 if ($form['#type'] == 'file') {
webmaster@1 957 // To make it easier to handle $_FILES in file.inc, we place all
webmaster@1 958 // file fields in the 'files' array. Also, we do not support
webmaster@1 959 // nested file names.
webmaster@1 960 $form['#name'] = 'files['. $form['#name'] .']';
webmaster@1 961 }
webmaster@1 962 elseif (count($form['#parents'])) {
webmaster@1 963 $form['#name'] .= '['. implode('][', $form['#parents']) .']';
webmaster@1 964 }
webmaster@1 965 array_unshift($form['#parents'], $name);
webmaster@1 966 }
webmaster@1 967 if (!isset($form['#id'])) {
webmaster@1 968 $form['#id'] = form_clean_id('edit-'. implode('-', $form['#parents']));
webmaster@1 969 }
webmaster@1 970
webmaster@1 971 unset($edit);
webmaster@1 972 if (!empty($form['#disabled'])) {
webmaster@1 973 $form['#attributes']['disabled'] = 'disabled';
webmaster@1 974 }
webmaster@1 975
webmaster@1 976 if (!isset($form['#value']) && !array_key_exists('#value', $form)) {
webmaster@1 977 $function = !empty($form['#value_callback']) ? $form['#value_callback'] : 'form_type_'. $form['#type'] .'_value';
webmaster@1 978 if (($form['#programmed']) || ((!isset($form['#access']) || $form['#access']) && isset($form['#post']) && (isset($form['#post']['form_id']) && $form['#post']['form_id'] == $form_id))) {
webmaster@1 979 $edit = $form['#post'];
webmaster@1 980 foreach ($form['#parents'] as $parent) {
webmaster@1 981 $edit = isset($edit[$parent]) ? $edit[$parent] : NULL;
webmaster@1 982 }
webmaster@1 983 if (!$form['#programmed'] || isset($edit)) {
webmaster@1 984 // Call #type_value to set the form value;
webmaster@1 985 if (function_exists($function)) {
webmaster@1 986 $form['#value'] = $function($form, $edit);
webmaster@1 987 }
webmaster@1 988 if (!isset($form['#value']) && isset($edit)) {
webmaster@1 989 $form['#value'] = $edit;
webmaster@1 990 }
webmaster@1 991 }
webmaster@1 992 // Mark all posted values for validation.
webmaster@1 993 if (isset($form['#value']) || (isset($form['#required']) && $form['#required'])) {
webmaster@1 994 $form['#needs_validation'] = TRUE;
webmaster@1 995 }
webmaster@1 996 }
webmaster@1 997 // Load defaults.
webmaster@1 998 if (!isset($form['#value'])) {
webmaster@1 999 // Call #type_value without a second argument to request default_value handling.
webmaster@1 1000 if (function_exists($function)) {
webmaster@1 1001 $form['#value'] = $function($form);
webmaster@1 1002 }
webmaster@1 1003 // Final catch. If we haven't set a value yet, use the explicit default value.
webmaster@1 1004 // Avoid image buttons (which come with garbage value), so we only get value
webmaster@1 1005 // for the button actually clicked.
webmaster@1 1006 if (!isset($form['#value']) && empty($form['#has_garbage_value'])) {
webmaster@1 1007 $form['#value'] = isset($form['#default_value']) ? $form['#default_value'] : '';
webmaster@1 1008 }
webmaster@1 1009 }
webmaster@1 1010 }
webmaster@1 1011
webmaster@1 1012 // Determine which button (if any) was clicked to submit the form.
webmaster@1 1013 // We compare the incoming values with the buttons defined in the form,
webmaster@1 1014 // and flag the one that matches. We have to do some funky tricks to
webmaster@1 1015 // deal with Internet Explorer's handling of single-button forms, though.
webmaster@1 1016 if (!empty($form['#post']) && isset($form['#executes_submit_callback'])) {
webmaster@1 1017 // First, accumulate a collection of buttons, divided into two bins:
webmaster@1 1018 // those that execute full submit callbacks and those that only validate.
webmaster@1 1019 $button_type = $form['#executes_submit_callback'] ? 'submit' : 'button';
webmaster@1 1020 $form_state['buttons'][$button_type][] = $form;
webmaster@1 1021
webmaster@1 1022 if (_form_button_was_clicked($form)) {
webmaster@1 1023 $form_state['submitted'] = $form_state['submitted'] || $form['#executes_submit_callback'];
webmaster@1 1024
webmaster@1 1025 // In most cases, we want to use form_set_value() to manipulate
webmaster@1 1026 // the global variables. In this special case, we want to make sure that
webmaster@1 1027 // the value of this element is listed in $form_variables under 'op'.
webmaster@1 1028 $form_state['values'][$form['#name']] = $form['#value'];
webmaster@1 1029 $form_state['clicked_button'] = $form;
webmaster@1 1030
webmaster@1 1031 if (isset($form['#validate'])) {
webmaster@1 1032 $form_state['validate_handlers'] = $form['#validate'];
webmaster@1 1033 }
webmaster@1 1034 if (isset($form['#submit'])) {
webmaster@1 1035 $form_state['submit_handlers'] = $form['#submit'];
webmaster@1 1036 }
webmaster@1 1037 }
webmaster@1 1038 }
webmaster@1 1039 // Allow for elements to expand to multiple elements, e.g., radios,
webmaster@1 1040 // checkboxes and files.
webmaster@1 1041 if (isset($form['#process']) && !$form['#processed']) {
webmaster@1 1042 foreach ($form['#process'] as $process) {
webmaster@1 1043 if (function_exists($process)) {
webmaster@1 1044 $form = $process($form, isset($edit) ? $edit : NULL, $form_state, $complete_form);
webmaster@1 1045 }
webmaster@1 1046 }
webmaster@1 1047 $form['#processed'] = TRUE;
webmaster@1 1048 }
webmaster@1 1049 form_set_value($form, $form['#value'], $form_state);
webmaster@1 1050 }
webmaster@1 1051
webmaster@1 1052 /**
webmaster@1 1053 * Helper function to handle the sometimes-convoluted logic of button
webmaster@1 1054 * click detection.
webmaster@1 1055 *
webmaster@1 1056 * In Internet Explorer, if ONLY one submit button is present, AND the
webmaster@1 1057 * enter key is used to submit the form, no form value is sent for it
webmaster@1 1058 * and we'll never detect a match. That special case is handled by
webmaster@1 1059 * _form_builder_ie_cleanup().
webmaster@1 1060 */
webmaster@1 1061 function _form_button_was_clicked($form) {
webmaster@1 1062 // First detect normal 'vanilla' button clicks. Traditionally, all
webmaster@1 1063 // standard buttons on a form share the same name (usually 'op'),
webmaster@1 1064 // and the specific return value is used to determine which was
webmaster@1 1065 // clicked. This ONLY works as long as $form['#name'] puts the
webmaster@1 1066 // value at the top level of the tree of $_POST data.
webmaster@1 1067 if (isset($form['#post'][$form['#name']]) && $form['#post'][$form['#name']] == $form['#value']) {
webmaster@1 1068 return TRUE;
webmaster@1 1069 }
webmaster@1 1070 // When image buttons are clicked, browsers do NOT pass the form element
webmaster@1 1071 // value in $_POST. Instead they pass an integer representing the
webmaster@1 1072 // coordinates of the click on the button image. This means that image
webmaster@1 1073 // buttons MUST have unique $form['#name'] values, but the details of
webmaster@1 1074 // their $_POST data should be ignored.
webmaster@1 1075 elseif (!empty($form['#has_garbage_value']) && isset($form['#value']) && $form['#value'] !== '') {
webmaster@1 1076 return TRUE;
webmaster@1 1077 }
webmaster@1 1078 return FALSE;
webmaster@1 1079 }
webmaster@1 1080
webmaster@1 1081 /**
webmaster@1 1082 * In IE, if only one submit button is present, AND the enter key is
webmaster@1 1083 * used to submit the form, no form value is sent for it and our normal
webmaster@1 1084 * button detection code will never detect a match. We call this
webmaster@1 1085 * function after all other button-detection is complete to check
webmaster@1 1086 * for the proper conditions, and treat the single button on the form
webmaster@1 1087 * as 'clicked' if they are met.
webmaster@1 1088 */
webmaster@1 1089 function _form_builder_ie_cleanup($form, &$form_state) {
webmaster@1 1090 // Quick check to make sure we're always looking at the full form
webmaster@1 1091 // and not a sub-element.
webmaster@1 1092 if (!empty($form['#type']) && $form['#type'] == 'form') {
webmaster@1 1093 // If we haven't recognized a submission yet, and there's a single
webmaster@1 1094 // submit button, we know that we've hit the right conditions. Grab
webmaster@1 1095 // the first one and treat it as the clicked button.
webmaster@1 1096 if (empty($form_state['submitted']) && !empty($form_state['buttons']['submit']) && empty($form_state['buttons']['button'])) {
webmaster@1 1097 $button = $form_state['buttons']['submit'][0];
webmaster@1 1098
webmaster@1 1099 // Set up all the $form_state information that would have been
webmaster@1 1100 // populated had the button been recognized earlier.
webmaster@1 1101 $form_state['submitted'] = TRUE;
webmaster@1 1102 $form_state['submit_handlers'] = empty($button['#submit']) ? NULL : $button['#submit'];
webmaster@1 1103 $form_state['validate_handlers'] = empty($button['#validate']) ? NULL : $button['#validate'];
webmaster@1 1104 $form_state['values'][$button['#name']] = $button['#value'];
webmaster@1 1105 $form_state['clicked_button'] = $button;
webmaster@1 1106 }
webmaster@1 1107 }
webmaster@1 1108 }
webmaster@1 1109
webmaster@1 1110 /**
webmaster@1 1111 * Helper function to determine the value for an image button form element.
webmaster@1 1112 *
webmaster@1 1113 * @param $form
webmaster@1 1114 * The form element whose value is being populated.
webmaster@1 1115 * @param $edit
webmaster@1 1116 * The incoming POST data to populate the form element. If this is FALSE,
webmaster@1 1117 * the element's default value should be returned.
webmaster@1 1118 * @return
webmaster@1 1119 * The data that will appear in the $form_state['values'] collection
webmaster@1 1120 * for this element. Return nothing to use the default.
webmaster@1 1121 */
webmaster@1 1122 function form_type_image_button_value($form, $edit = FALSE) {
webmaster@1 1123 if ($edit !== FALSE) {
webmaster@1 1124 if (!empty($edit)) {
webmaster@1 1125 // If we're dealing with Mozilla or Opera, we're lucky. It will
webmaster@1 1126 // return a proper value, and we can get on with things.
webmaster@1 1127 return $form['#return_value'];
webmaster@1 1128 }
webmaster@1 1129 else {
webmaster@1 1130 // Unfortunately, in IE we never get back a proper value for THIS
webmaster@1 1131 // form element. Instead, we get back two split values: one for the
webmaster@1 1132 // X and one for the Y coordinates on which the user clicked the
webmaster@1 1133 // button. We'll find this element in the #post data, and search
webmaster@1 1134 // in the same spot for its name, with '_x'.
webmaster@1 1135 $post = $form['#post'];
webmaster@1 1136 foreach (split('\[', $form['#name']) as $element_name) {
webmaster@1 1137 // chop off the ] that may exist.
webmaster@1 1138 if (substr($element_name, -1) == ']') {
webmaster@1 1139 $element_name = substr($element_name, 0, -1);
webmaster@1 1140 }
webmaster@1 1141
webmaster@1 1142 if (!isset($post[$element_name])) {
webmaster@1 1143 if (isset($post[$element_name .'_x'])) {
webmaster@1 1144 return $form['#return_value'];
webmaster@1 1145 }
webmaster@1 1146 return NULL;
webmaster@1 1147 }
webmaster@1 1148 $post = $post[$element_name];
webmaster@1 1149 }
webmaster@1 1150 return $form['#return_value'];
webmaster@1 1151 }
webmaster@1 1152 }
webmaster@1 1153 }
webmaster@1 1154
webmaster@1 1155 /**
webmaster@1 1156 * Helper function to determine the value for a checkbox form element.
webmaster@1 1157 *
webmaster@1 1158 * @param $form
webmaster@1 1159 * The form element whose value is being populated.
webmaster@1 1160 * @param $edit
webmaster@1 1161 * The incoming POST data to populate the form element. If this is FALSE,
webmaster@1 1162 * the element's default value should be returned.
webmaster@1 1163 * @return
webmaster@1 1164 * The data that will appear in the $form_state['values'] collection
webmaster@1 1165 * for this element. Return nothing to use the default.
webmaster@1 1166 */
webmaster@1 1167 function form_type_checkbox_value($form, $edit = FALSE) {
webmaster@1 1168 if ($edit !== FALSE) {
webmaster@1 1169 return !empty($edit) ? $form['#return_value'] : 0;
webmaster@1 1170 }
webmaster@1 1171 }
webmaster@1 1172
webmaster@1 1173 /**
webmaster@1 1174 * Helper function to determine the value for a checkboxes form element.
webmaster@1 1175 *
webmaster@1 1176 * @param $form
webmaster@1 1177 * The form element whose value is being populated.
webmaster@1 1178 * @param $edit
webmaster@1 1179 * The incoming POST data to populate the form element. If this is FALSE,
webmaster@1 1180 * the element's default value should be returned.
webmaster@1 1181 * @return
webmaster@1 1182 * The data that will appear in the $form_state['values'] collection
webmaster@1 1183 * for this element. Return nothing to use the default.
webmaster@1 1184 */
webmaster@1 1185 function form_type_checkboxes_value($form, $edit = FALSE) {
webmaster@1 1186 if ($edit === FALSE) {
webmaster@1 1187 $value = array();
webmaster@1 1188 $form += array('#default_value' => array());
webmaster@1 1189 foreach ($form['#default_value'] as $key) {
webmaster@1 1190 $value[$key] = 1;
webmaster@1 1191 }
webmaster@1 1192 return $value;
webmaster@1 1193 }
webmaster@1 1194 elseif (!isset($edit)) {
webmaster@1 1195 return array();
webmaster@1 1196 }
webmaster@1 1197 }
webmaster@1 1198
webmaster@1 1199 /**
webmaster@1 1200 * Helper function to determine the value for a password_confirm form
webmaster@1 1201 * element.
webmaster@1 1202 *
webmaster@1 1203 * @param $form
webmaster@1 1204 * The form element whose value is being populated.
webmaster@1 1205 * @param $edit
webmaster@1 1206 * The incoming POST data to populate the form element. If this is FALSE,
webmaster@1 1207 * the element's default value should be returned.
webmaster@1 1208 * @return
webmaster@1 1209 * The data that will appear in the $form_state['values'] collection
webmaster@1 1210 * for this element. Return nothing to use the default.
webmaster@1 1211 */
webmaster@1 1212 function form_type_password_confirm_value($form, $edit = FALSE) {
webmaster@1 1213 if ($edit === FALSE) {
webmaster@1 1214 $form += array('#default_value' => array());
webmaster@1 1215 return $form['#default_value'] + array('pass1' => '', 'pass2' => '');
webmaster@1 1216 }
webmaster@1 1217 }
webmaster@1 1218
webmaster@1 1219 /**
webmaster@1 1220 * Helper function to determine the value for a select form element.
webmaster@1 1221 *
webmaster@1 1222 * @param $form
webmaster@1 1223 * The form element whose value is being populated.
webmaster@1 1224 * @param $edit
webmaster@1 1225 * The incoming POST data to populate the form element. If this is FALSE,
webmaster@1 1226 * the element's default value should be returned.
webmaster@1 1227 * @return
webmaster@1 1228 * The data that will appear in the $form_state['values'] collection
webmaster@1 1229 * for this element. Return nothing to use the default.
webmaster@1 1230 */
webmaster@1 1231 function form_type_select_value($form, $edit = FALSE) {
webmaster@1 1232 if ($edit !== FALSE) {
webmaster@1 1233 if (isset($form['#multiple']) && $form['#multiple']) {
webmaster@1 1234 return (is_array($edit)) ? drupal_map_assoc($edit) : array();
webmaster@1 1235 }
webmaster@1 1236 else {
webmaster@1 1237 return $edit;
webmaster@1 1238 }
webmaster@1 1239 }
webmaster@1 1240 }
webmaster@1 1241
webmaster@1 1242 /**
webmaster@1 1243 * Helper function to determine the value for a textfield form element.
webmaster@1 1244 *
webmaster@1 1245 * @param $form
webmaster@1 1246 * The form element whose value is being populated.
webmaster@1 1247 * @param $edit
webmaster@1 1248 * The incoming POST data to populate the form element. If this is FALSE,
webmaster@1 1249 * the element's default value should be returned.
webmaster@1 1250 * @return
webmaster@1 1251 * The data that will appear in the $form_state['values'] collection
webmaster@1 1252 * for this element. Return nothing to use the default.
webmaster@1 1253 */
webmaster@1 1254 function form_type_textfield_value($form, $edit = FALSE) {
webmaster@1 1255 if ($edit !== FALSE) {
webmaster@1 1256 // Equate $edit to the form value to ensure it's marked for
webmaster@1 1257 // validation.
webmaster@1 1258 return str_replace(array("\r", "\n"), '', $edit);
webmaster@1 1259 }
webmaster@1 1260 }
webmaster@1 1261
webmaster@1 1262 /**
webmaster@1 1263 * Helper function to determine the value for form's token value.
webmaster@1 1264 *
webmaster@1 1265 * @param $form
webmaster@1 1266 * The form element whose value is being populated.
webmaster@1 1267 * @param $edit
webmaster@1 1268 * The incoming POST data to populate the form element. If this is FALSE,
webmaster@1 1269 * the element's default value should be returned.
webmaster@1 1270 * @return
webmaster@1 1271 * The data that will appear in the $form_state['values'] collection
webmaster@1 1272 * for this element. Return nothing to use the default.
webmaster@1 1273 */
webmaster@1 1274 function form_type_token_value($form, $edit = FALSE) {
webmaster@1 1275 if ($edit !== FALSE) {
webmaster@1 1276 return (string)$edit;
webmaster@1 1277 }
webmaster@1 1278 }
webmaster@1 1279
webmaster@1 1280 /**
webmaster@7 1281 * Change submitted form values during the form processing cycle.
webmaster@1 1282 *
webmaster@7 1283 * Use this function to change the submitted value of a form item in the
webmaster@7 1284 * validation phase so that it persists in $form_state through to the
webmaster@7 1285 * submission handlers in the submission phase.
webmaster@1 1286 *
webmaster@7 1287 * Since $form_state['values'] can either be a flat array of values, or a tree
webmaster@7 1288 * of nested values, some care must be taken when using this function.
webmaster@7 1289 * Specifically, $form_item['#parents'] is an array that describes the branch of
webmaster@7 1290 * the tree whose value should be updated. For example, if we wanted to update
webmaster@7 1291 * $form_state['values']['one']['two'] to 'new value', we'd pass in
webmaster@7 1292 * $form_item['#parents'] = array('one', 'two') and $value = 'new value'.
webmaster@7 1293 *
webmaster@7 1294 * @param $form_item
webmaster@7 1295 * The form item that should have its value updated. Keys used: #parents,
webmaster@7 1296 * #value. In most cases you can just pass in the right element from the $form
webmaster@7 1297 * array.
webmaster@1 1298 * @param $value
webmaster@7 1299 * The new value for the form item.
webmaster@7 1300 * @param $form_state
webmaster@7 1301 * The array where the value change should be recorded.
webmaster@1 1302 */
webmaster@7 1303 function form_set_value($form_item, $value, &$form_state) {
webmaster@7 1304 _form_set_value($form_state['values'], $form_item, $form_item['#parents'], $value);
webmaster@1 1305 }
webmaster@1 1306
webmaster@1 1307 /**
webmaster@1 1308 * Helper function for form_set_value().
webmaster@1 1309 *
webmaster@1 1310 * We iterate over $parents and create nested arrays for them
webmaster@1 1311 * in $form_state['values'] if needed. Then we insert the value into
webmaster@1 1312 * the right array.
webmaster@1 1313 */
webmaster@7 1314 function _form_set_value(&$form_values, $form_item, $parents, $value) {
webmaster@1 1315 $parent = array_shift($parents);
webmaster@1 1316 if (empty($parents)) {
webmaster@1 1317 $form_values[$parent] = $value;
webmaster@1 1318 }
webmaster@1 1319 else {
webmaster@1 1320 if (!isset($form_values[$parent])) {
webmaster@1 1321 $form_values[$parent] = array();
webmaster@1 1322 }
webmaster@7 1323 _form_set_value($form_values[$parent], $form_item, $parents, $value);
webmaster@1 1324 }
webmaster@1 1325 }
webmaster@1 1326
webmaster@1 1327 /**
webmaster@1 1328 * Retrieve the default properties for the defined element type.
webmaster@1 1329 */
webmaster@1 1330 function _element_info($type, $refresh = NULL) {
webmaster@1 1331 static $cache;
webmaster@1 1332
webmaster@1 1333 $basic_defaults = array(
webmaster@1 1334 '#description' => NULL,
webmaster@1 1335 '#attributes' => array(),
webmaster@1 1336 '#required' => FALSE,
webmaster@1 1337 '#tree' => FALSE,
webmaster@1 1338 '#parents' => array()
webmaster@1 1339 );
webmaster@1 1340 if (!isset($cache) || $refresh) {
webmaster@1 1341 $cache = array();
webmaster@1 1342 foreach (module_implements('elements') as $module) {
webmaster@1 1343 $elements = module_invoke($module, 'elements');
webmaster@1 1344 if (isset($elements) && is_array($elements)) {
webmaster@1 1345 $cache = array_merge_recursive($cache, $elements);
webmaster@1 1346 }
webmaster@1 1347 }
webmaster@1 1348 if (sizeof($cache)) {
webmaster@1 1349 foreach ($cache as $element_type => $info) {
webmaster@1 1350 $cache[$element_type] = array_merge_recursive($basic_defaults, $info);
webmaster@1 1351 }
webmaster@1 1352 }
webmaster@1 1353 }
webmaster@1 1354
webmaster@1 1355 return $cache[$type];
webmaster@1 1356 }
webmaster@1 1357
webmaster@1 1358 function form_options_flatten($array, $reset = TRUE) {
webmaster@1 1359 static $return;
webmaster@1 1360
webmaster@1 1361 if ($reset) {
webmaster@1 1362 $return = array();
webmaster@1 1363 }
webmaster@1 1364
webmaster@1 1365 foreach ($array as $key => $value) {
webmaster@1 1366 if (is_object($value)) {
webmaster@1 1367 form_options_flatten($value->option, FALSE);
webmaster@1 1368 }
webmaster@1 1369 else if (is_array($value)) {
webmaster@1 1370 form_options_flatten($value, FALSE);
webmaster@1 1371 }
webmaster@1 1372 else {
webmaster@1 1373 $return[$key] = 1;
webmaster@1 1374 }
webmaster@1 1375 }
webmaster@1 1376
webmaster@1 1377 return $return;
webmaster@1 1378 }
webmaster@1 1379
webmaster@1 1380 /**
webmaster@1 1381 * Format a dropdown menu or scrolling selection box.
webmaster@1 1382 *
webmaster@1 1383 * @param $element
webmaster@1 1384 * An associative array containing the properties of the element.
webmaster@1 1385 * Properties used: title, value, options, description, extra, multiple, required
webmaster@1 1386 * @return
webmaster@1 1387 * A themed HTML string representing the form element.
webmaster@1 1388 *
webmaster@1 1389 * @ingroup themeable
webmaster@1 1390 *
webmaster@1 1391 * It is possible to group options together; to do this, change the format of
webmaster@1 1392 * $options to an associative array in which the keys are group labels, and the
webmaster@1 1393 * values are associative arrays in the normal $options format.
webmaster@1 1394 */
webmaster@1 1395 function theme_select($element) {
webmaster@1 1396 $select = '';
webmaster@1 1397 $size = $element['#size'] ? ' size="'. $element['#size'] .'"' : '';
webmaster@1 1398 _form_set_class($element, array('form-select'));
webmaster@1 1399 $multiple = $element['#multiple'];
webmaster@1 1400 return theme('form_element', $element, '<select name="'. $element['#name'] .''. ($multiple ? '[]' : '') .'"'. ($multiple ? ' multiple="multiple" ' : '') . drupal_attributes($element['#attributes']) .' id="'. $element['#id'] .'" '. $size .'>'. form_select_options($element) .'</select>');
webmaster@1 1401 }
webmaster@1 1402
webmaster@1 1403 function form_select_options($element, $choices = NULL) {
webmaster@1 1404 if (!isset($choices)) {
webmaster@1 1405 $choices = $element['#options'];
webmaster@1 1406 }
webmaster@1 1407 // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
webmaster@1 1408 // isset() fails in this situation.
webmaster@1 1409 $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
webmaster@1 1410 $value_is_array = is_array($element['#value']);
webmaster@1 1411 $options = '';
webmaster@1 1412 foreach ($choices as $key => $choice) {
webmaster@1 1413 if (is_array($choice)) {
webmaster@1 1414 $options .= '<optgroup label="'. $key .'">';
webmaster@1 1415 $options .= form_select_options($element, $choice);
webmaster@1 1416 $options .= '</optgroup>';
webmaster@1 1417 }
webmaster@1 1418 elseif (is_object($choice)) {
webmaster@1 1419 $options .= form_select_options($element, $choice->option);
webmaster@1 1420 }
webmaster@1 1421 else {
webmaster@1 1422 $key = (string)$key;
webmaster@1 1423 if ($value_valid && (!$value_is_array && (string)$element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
webmaster@1 1424 $selected = ' selected="selected"';
webmaster@1 1425 }
webmaster@1 1426 else {
webmaster@1 1427 $selected = '';
webmaster@1 1428 }
webmaster@1 1429 $options .= '<option value="'. check_plain($key) .'"'. $selected .'>'. check_plain($choice) .'</option>';
webmaster@1 1430 }
webmaster@1 1431 }
webmaster@1 1432 return $options;
webmaster@1 1433 }
webmaster@1 1434
webmaster@1 1435 /**
webmaster@1 1436 * Traverses a select element's #option array looking for any values
webmaster@1 1437 * that hold the given key. Returns an array of indexes that match.
webmaster@1 1438 *
webmaster@1 1439 * This function is useful if you need to modify the options that are
webmaster@1 1440 * already in a form element; for example, to remove choices which are
webmaster@1 1441 * not valid because of additional filters imposed by another module.
webmaster@1 1442 * One example might be altering the choices in a taxonomy selector.
webmaster@1 1443 * To correctly handle the case of a multiple hierarchy taxonomy,
webmaster@1 1444 * #options arrays can now hold an array of objects, instead of a
webmaster@1 1445 * direct mapping of keys to labels, so that multiple choices in the
webmaster@1 1446 * selector can have the same key (and label). This makes it difficult
webmaster@1 1447 * to manipulate directly, which is why this helper function exists.
webmaster@1 1448 *
webmaster@1 1449 * This function does not support optgroups (when the elements of the
webmaster@1 1450 * #options array are themselves arrays), and will return FALSE if
webmaster@1 1451 * arrays are found. The caller must either flatten/restore or
webmaster@1 1452 * manually do their manipulations in this case, since returning the
webmaster@1 1453 * index is not sufficient, and supporting this would make the
webmaster@1 1454 * "helper" too complicated and cumbersome to be of any help.
webmaster@1 1455 *
webmaster@1 1456 * As usual with functions that can return array() or FALSE, do not
webmaster@1 1457 * forget to use === and !== if needed.
webmaster@1 1458 *
webmaster@1 1459 * @param $element
webmaster@1 1460 * The select element to search.
webmaster@1 1461 * @param $key
webmaster@1 1462 * The key to look for.
webmaster@1 1463 * @return
webmaster@1 1464 * An array of indexes that match the given $key. Array will be
webmaster@1 1465 * empty if no elements were found. FALSE if optgroups were found.
webmaster@1 1466 */
webmaster@1 1467 function form_get_options($element, $key) {
webmaster@1 1468 $keys = array();
webmaster@1 1469 foreach ($element['#options'] as $index => $choice) {
webmaster@1 1470 if (is_array($choice)) {
webmaster@1 1471 return FALSE;
webmaster@1 1472 }
webmaster@1 1473 else if (is_object($choice)) {
webmaster@1 1474 if (isset($choice->option[$key])) {
webmaster@1 1475 $keys[] = $index;
webmaster@1 1476 }
webmaster@1 1477 }
webmaster@1 1478 else if ($index == $key) {
webmaster@1 1479 $keys[] = $index;
webmaster@1 1480 }
webmaster@1 1481 }
webmaster@1 1482 return $keys;
webmaster@1 1483 }
webmaster@1 1484
webmaster@1 1485 /**
webmaster@1 1486 * Format a group of form items.
webmaster@1 1487 *
webmaster@1 1488 * @param $element
webmaster@1 1489 * An associative array containing the properties of the element.
webmaster@1 1490 * Properties used: attributes, title, value, description, children, collapsible, collapsed
webmaster@1 1491 * @return
webmaster@1 1492 * A themed HTML string representing the form item group.
webmaster@1 1493 *
webmaster@1 1494 * @ingroup themeable
webmaster@1 1495 */
webmaster@1 1496 function theme_fieldset($element) {
webmaster@1 1497 if ($element['#collapsible']) {
webmaster@1 1498 drupal_add_js('misc/collapse.js');
webmaster@1 1499
webmaster@1 1500 if (!isset($element['#attributes']['class'])) {
webmaster@1 1501 $element['#attributes']['class'] = '';
webmaster@1 1502 }
webmaster@1 1503
webmaster@1 1504 $element['#attributes']['class'] .= ' collapsible';
webmaster@1 1505 if ($element['#collapsed']) {
webmaster@1 1506 $element['#attributes']['class'] .= ' collapsed';
webmaster@1 1507 }
webmaster@1 1508 }
webmaster@1 1509
webmaster@7 1510 return '<fieldset'. drupal_attributes($element['#attributes']) .'>'. ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '') . (isset($element['#description']) && $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . (!empty($element['#children']) ? $element['#children'] : '') . (isset($element['#value']) ? $element['#value'] : '') ."</fieldset>\n";
webmaster@1 1511 }
webmaster@1 1512
webmaster@1 1513 /**
webmaster@1 1514 * Format a radio button.
webmaster@1 1515 *
webmaster@1 1516 * @param $element
webmaster@1 1517 * An associative array containing the properties of the element.
webmaster@1 1518 * Properties used: required, return_value, value, attributes, title, description
webmaster@1 1519 * @return
webmaster@1 1520 * A themed HTML string representing the form item group.
webmaster@1 1521 *
webmaster@1 1522 * @ingroup themeable
webmaster@1 1523 */
webmaster@1 1524 function theme_radio($element) {
webmaster@1 1525 _form_set_class($element, array('form-radio'));
webmaster@1 1526 $output = '<input type="radio" ';
webmaster@9 1527 $output .= 'id="'. $element['#id'] .'" ';
webmaster@1 1528 $output .= 'name="'. $element['#name'] .'" ';
webmaster@1 1529 $output .= 'value="'. $element['#return_value'] .'" ';
webmaster@1 1530 $output .= (check_plain($element['#value']) == $element['#return_value']) ? ' checked="checked" ' : ' ';
webmaster@1 1531 $output .= drupal_attributes($element['#attributes']) .' />';
webmaster@1 1532 if (!is_null($element['#title'])) {
webmaster@1 1533 $output = '<label class="option">'. $output .' '. $element['#title'] .'</label>';
webmaster@1 1534 }
webmaster@1 1535
webmaster@1 1536 unset($element['#title']);
webmaster@1 1537 return theme('form_element', $element, $output);
webmaster@1 1538 }
webmaster@1 1539
webmaster@1 1540 /**
webmaster@1 1541 * Format a set of radio buttons.
webmaster@1 1542 *
webmaster@1 1543 * @param $element
webmaster@1 1544 * An associative array containing the properties of the element.
webmaster@1 1545 * Properties used: title, value, options, description, required and attributes.
webmaster@1 1546 * @return
webmaster@1 1547 * A themed HTML string representing the radio button set.
webmaster@1 1548 *
webmaster@1 1549 * @ingroup themeable
webmaster@1 1550 */
webmaster@1 1551 function theme_radios($element) {
webmaster@1 1552 $class = 'form-radios';
webmaster@1 1553 if (isset($element['#attributes']['class'])) {
webmaster@1 1554 $class .= ' '. $element['#attributes']['class'];
webmaster@1 1555 }
webmaster@1 1556 $element['#children'] = '<div class="'. $class .'">'. (!empty($element['#children']) ? $element['#children'] : '') .'</div>';
webmaster@1 1557 if ($element['#title'] || $element['#description']) {
webmaster@1 1558 unset($element['#id']);
webmaster@1 1559 return theme('form_element', $element, $element['#children']);
webmaster@1 1560 }
webmaster@1 1561 else {
webmaster@1 1562 return $element['#children'];
webmaster@1 1563 }
webmaster@1 1564 }
webmaster@1 1565
webmaster@1 1566 /**
webmaster@1 1567 * Format a password_confirm item.
webmaster@1 1568 *
webmaster@1 1569 * @param $element
webmaster@1 1570 * An associative array containing the properties of the element.
webmaster@1 1571 * Properties used: title, value, id, required, error.
webmaster@1 1572 * @return
webmaster@1 1573 * A themed HTML string representing the form item.
webmaster@1 1574 *
webmaster@1 1575 * @ingroup themeable
webmaster@1 1576 */
webmaster@1 1577 function theme_password_confirm($element) {
webmaster@1 1578 return theme('form_element', $element, $element['#children']);
webmaster@1 1579 }
webmaster@1 1580
webmaster@1 1581 /**
webmaster@1 1582 * Expand a password_confirm field into two text boxes.
webmaster@1 1583 */
webmaster@1 1584 function expand_password_confirm($element) {
webmaster@1 1585 $element['pass1'] = array(
webmaster@1 1586 '#type' => 'password',
webmaster@1 1587 '#title' => t('Password'),
webmaster@1 1588 '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
webmaster@1 1589 '#required' => $element['#required'],
webmaster@1 1590 '#attributes' => array('class' => 'password-field'),
webmaster@1 1591 );
webmaster@1 1592 $element['pass2'] = array(
webmaster@1 1593 '#type' => 'password',
webmaster@1 1594 '#title' => t('Confirm password'),
webmaster@1 1595 '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
webmaster@1 1596 '#required' => $element['#required'],
webmaster@1 1597 '#attributes' => array('class' => 'password-confirm'),
webmaster@1 1598 );
webmaster@1 1599 $element['#element_validate'] = array('password_confirm_validate');
webmaster@1 1600 $element['#tree'] = TRUE;
webmaster@1 1601
webmaster@1 1602 if (isset($element['#size'])) {
webmaster@1 1603 $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
webmaster@1 1604 }
webmaster@1 1605
webmaster@1 1606 return $element;
webmaster@1 1607 }
webmaster@1 1608
webmaster@1 1609 /**
webmaster@1 1610 * Validate password_confirm element.
webmaster@1 1611 */
webmaster@1 1612 function password_confirm_validate($form, &$form_state) {
webmaster@1 1613 $pass1 = trim($form['pass1']['#value']);
webmaster@1 1614 if (!empty($pass1)) {
webmaster@1 1615 $pass2 = trim($form['pass2']['#value']);
webmaster@1 1616 if ($pass1 != $pass2) {
webmaster@1 1617 form_error($form, t('The specified passwords do not match.'));
webmaster@1 1618 }
webmaster@1 1619 }
webmaster@1 1620 elseif ($form['#required'] && !empty($form['#post'])) {
webmaster@1 1621 form_error($form, t('Password field is required.'));
webmaster@1 1622 }
webmaster@1 1623
webmaster@1 1624 // Password field must be converted from a two-element array into a single
webmaster@1 1625 // string regardless of validation results.
webmaster@1 1626 form_set_value($form['pass1'], NULL, $form_state);
webmaster@1 1627 form_set_value($form['pass2'], NULL, $form_state);
webmaster@1 1628 form_set_value($form, $pass1, $form_state);
webmaster@1 1629
webmaster@1 1630 return $form;
webmaster@1 1631
webmaster@1 1632 }
webmaster@1 1633
webmaster@1 1634 /**
webmaster@1 1635 * Format a date selection element.
webmaster@1 1636 *
webmaster@1 1637 * @param $element
webmaster@1 1638 * An associative array containing the properties of the element.
webmaster@1 1639 * Properties used: title, value, options, description, required and attributes.
webmaster@1 1640 * @return
webmaster@1 1641 * A themed HTML string representing the date selection boxes.
webmaster@1 1642 *
webmaster@1 1643 * @ingroup themeable
webmaster@1 1644 */
webmaster@1 1645 function theme_date($element) {
webmaster@1 1646 return theme('form_element', $element, '<div class="container-inline">'. $element['#children'] .'</div>');
webmaster@1 1647 }
webmaster@1 1648
webmaster@1 1649 /**
webmaster@1 1650 * Roll out a single date element.
webmaster@1 1651 */
webmaster@1 1652 function expand_date($element) {
webmaster@1 1653 // Default to current date
webmaster@1 1654 if (empty($element['#value'])) {
webmaster@1 1655 $element['#value'] = array('day' => format_date(time(), 'custom', 'j'),
webmaster@1 1656 'month' => format_date(time(), 'custom', 'n'),
webmaster@1 1657 'year' => format_date(time(), 'custom', 'Y'));
webmaster@1 1658 }
webmaster@1 1659
webmaster@1 1660 $element['#tree'] = TRUE;
webmaster@1 1661
webmaster@1 1662 // Determine the order of day, month, year in the site's chosen date format.
webmaster@1 1663 $format = variable_get('date_format_short', 'm/d/Y - H:i');
webmaster@1 1664 $sort = array();
webmaster@1 1665 $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
webmaster@1 1666 $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
webmaster@1 1667 $sort['year'] = strpos($format, 'Y');
webmaster@1 1668 asort($sort);
webmaster@1 1669 $order = array_keys($sort);
webmaster@1 1670
webmaster@1 1671 // Output multi-selector for date.
webmaster@1 1672 foreach ($order as $type) {
webmaster@1 1673 switch ($type) {
webmaster@1 1674 case 'day':
webmaster@1 1675 $options = drupal_map_assoc(range(1, 31));
webmaster@1 1676 break;
webmaster@1 1677 case 'month':
webmaster@1 1678 $options = drupal_map_assoc(range(1, 12), 'map_month');
webmaster@1 1679 break;
webmaster@1 1680 case 'year':
webmaster@1 1681 $options = drupal_map_assoc(range(1900, 2050));
webmaster@1 1682 break;
webmaster@1 1683 }
webmaster@1 1684 $parents = $element['#parents'];
webmaster@1 1685 $parents[] = $type;
webmaster@1 1686 $element[$type] = array(
webmaster@1 1687 '#type' => 'select',
webmaster@1 1688 '#value' => $element['#value'][$type],
webmaster@1 1689 '#attributes' => $element['#attributes'],
webmaster@1 1690 '#options' => $options,
webmaster@1 1691 );
webmaster@1 1692 }
webmaster@1 1693
webmaster@1 1694 return $element;
webmaster@1 1695 }
webmaster@1 1696
webmaster@1 1697 /**
webmaster@1 1698 * Validates the date type to stop dates like February 30, 2006.
webmaster@1 1699 */
webmaster@1 1700 function date_validate($form) {
webmaster@1 1701 if (!checkdate($form['#value']['month'], $form['#value']['day'], $form['#value']['year'])) {
webmaster@1 1702 form_error($form, t('The specified date is invalid.'));
webmaster@1 1703 }
webmaster@1 1704 }
webmaster@1 1705
webmaster@1 1706 /**
webmaster@1 1707 * Helper function for usage with drupal_map_assoc to display month names.
webmaster@1 1708 */
webmaster@1 1709 function map_month($month) {
webmaster@1 1710 return format_date(gmmktime(0, 0, 0, $month, 2, 1970), 'custom', 'M', 0);
webmaster@1 1711 }
webmaster@1 1712
webmaster@1 1713 /**
webmaster@1 1714 * If no default value is set for weight select boxes, use 0.
webmaster@1 1715 */
webmaster@1 1716 function weight_value(&$form) {
webmaster@1 1717 if (isset($form['#default_value'])) {
webmaster@1 1718 $form['#value'] = $form['#default_value'];
webmaster@1 1719 }
webmaster@1 1720 else {
webmaster@1 1721 $form['#value'] = 0;
webmaster@1 1722 }
webmaster@1 1723 }
webmaster@1 1724
webmaster@1 1725 /**
webmaster@1 1726 * Roll out a single radios element to a list of radios,
webmaster@1 1727 * using the options array as index.
webmaster@1 1728 */
webmaster@1 1729 function expand_radios($element) {
webmaster@1 1730 if (count($element['#options']) > 0) {
webmaster@1 1731 foreach ($element['#options'] as $key => $choice) {
webmaster@1 1732 if (!isset($element[$key])) {
webmaster@1 1733 // Generate the parents as the autogenerator does, so we will have a
webmaster@1 1734 // unique id for each radio button.
webmaster@1 1735 $parents_for_id = array_merge($element['#parents'], array($key));
webmaster@1 1736 $element[$key] = array(
webmaster@1 1737 '#type' => 'radio',
webmaster@1 1738 '#title' => $choice,
webmaster@1 1739 '#return_value' => check_plain($key),
webmaster@1 1740 '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : NULL,
webmaster@1 1741 '#attributes' => $element['#attributes'],
webmaster@1 1742 '#parents' => $element['#parents'],
webmaster@1 1743 '#id' => form_clean_id('edit-'. implode('-', $parents_for_id)),
webmaster@9 1744 '#ahah' => isset($element['#ahah']) ? $element['#ahah'] : NULL,
webmaster@1 1745 );
webmaster@1 1746 }
webmaster@1 1747 }
webmaster@1 1748 }
webmaster@1 1749 return $element;
webmaster@1 1750 }
webmaster@1 1751
webmaster@1 1752 /**
webmaster@1 1753 * Add AHAH information about a form element to the page to communicate with
webmaster@1 1754 * javascript. If #ahah[path] is set on an element, this additional javascript is
webmaster@1 1755 * added to the page header to attach the AHAH behaviors. See ahah.js for more
webmaster@1 1756 * information.
webmaster@1 1757 *
webmaster@1 1758 * @param $element
webmaster@1 1759 * An associative array containing the properties of the element.
webmaster@1 1760 * Properties used: ahah_event, ahah_path, ahah_wrapper, ahah_parameters,
webmaster@1 1761 * ahah_effect.
webmaster@1 1762 * @return
webmaster@1 1763 * None. Additional code is added to the header of the page using
webmaster@1 1764 * drupal_add_js.
webmaster@1 1765 */
webmaster@1 1766 function form_expand_ahah($element) {
webmaster@1 1767 static $js_added = array();
webmaster@1 1768 // Add a reasonable default event handler if none specified.
webmaster@1 1769 if (isset($element['#ahah']['path']) && !isset($element['#ahah']['event'])) {
webmaster@1 1770 switch ($element['#type']) {
webmaster@1 1771 case 'submit':
webmaster@1 1772 case 'button':
webmaster@1 1773 case 'image_button':
webmaster@1 1774 // Use the mousedown instead of the click event because form
webmaster@1 1775 // submission via pressing the enter key triggers a click event on
webmaster@1 1776 // submit inputs, inappropriately triggering AHAH behaviors.
webmaster@1 1777 $element['#ahah']['event'] = 'mousedown';
webmaster@1 1778 // Attach an additional event handler so that AHAH behaviours
webmaster@1 1779 // can be triggered still via keyboard input.
webmaster@1 1780 $element['#ahah']['keypress'] = TRUE;
webmaster@1 1781 break;
webmaster@1 1782 case 'password':
webmaster@1 1783 case 'textfield':
webmaster@1 1784 case 'textarea':
webmaster@1 1785 $element['#ahah']['event'] = 'blur';
webmaster@1 1786 break;
webmaster@1 1787 case 'radio':
webmaster@1 1788 case 'checkbox':
webmaster@1 1789 case 'select':
webmaster@1 1790 $element['#ahah']['event'] = 'change';
webmaster@1 1791 break;
webmaster@1 1792 }
webmaster@1 1793 }
webmaster@1 1794
webmaster@1 1795 // Adding the same javascript settings twice will cause a recursion error,
webmaster@1 1796 // we avoid the problem by checking if the javascript has already been added.
webmaster@1 1797 if (isset($element['#ahah']['path']) && isset($element['#ahah']['event']) && !isset($js_added[$element['#id']])) {
webmaster@1 1798 drupal_add_js('misc/jquery.form.js');
webmaster@1 1799 drupal_add_js('misc/ahah.js');
webmaster@1 1800
webmaster@1 1801 $ahah_binding = array(
webmaster@1 1802 'url' => url($element['#ahah']['path']),
webmaster@1 1803 'event' => $element['#ahah']['event'],
webmaster@1 1804 'keypress' => empty($element['#ahah']['keypress']) ? NULL : $element['#ahah']['keypress'],
webmaster@1 1805 'wrapper' => empty($element['#ahah']['wrapper']) ? NULL : $element['#ahah']['wrapper'],
webmaster@1 1806 'selector' => empty($element['#ahah']['selector']) ? '#'. $element['#id'] : $element['#ahah']['selector'],
webmaster@1 1807 'effect' => empty($element['#ahah']['effect']) ? 'none' : $element['#ahah']['effect'],
webmaster@1 1808 'method' => empty($element['#ahah']['method']) ? 'replace' : $element['#ahah']['method'],
webmaster@1 1809 'progress' => empty($element['#ahah']['progress']) ? array('type' => 'throbber') : $element['#ahah']['progress'],
webmaster@1 1810 'button' => isset($element['#executes_submit_callback']) ? array($element['#name'] => $element['#value']) : FALSE,
webmaster@1 1811 );
webmaster@1 1812
webmaster@1 1813 // Convert a simple #ahah[progress] type string into an array.
webmaster@1 1814 if (is_string($ahah_binding['progress'])) {
webmaster@1 1815 $ahah_binding['progress'] = array('type' => $ahah_binding['progress']);
webmaster@1 1816 }
webmaster@1 1817 // Change progress path to a full url.
webmaster@1 1818 if (isset($ahah_binding['progress']['path'])) {
webmaster@1 1819 $ahah_binding['progress']['url'] = url($ahah_binding['progress']['path']);
webmaster@1 1820 }
webmaster@1 1821
webmaster@1 1822 // Add progress.js if we're doing a bar display.
webmaster@1 1823 if ($ahah_binding['progress']['type'] == 'bar') {
webmaster@1 1824 drupal_add_js('misc/progress.js');
webmaster@1 1825 }
webmaster@1 1826
webmaster@1 1827 drupal_add_js(array('ahah' => array($element['#id'] => $ahah_binding)), 'setting');
webmaster@1 1828
webmaster@1 1829 $js_added[$element['#id']] = TRUE;
webmaster@1 1830 $element['#cache'] = TRUE;
webmaster@1 1831 }
webmaster@1 1832 return $element;
webmaster@1 1833 }
webmaster@1 1834
webmaster@1 1835 /**
webmaster@1 1836 * Format a form item.
webmaster@1 1837 *
webmaster@1 1838 * @param $element
webmaster@1 1839 * An associative array containing the properties of the element.
webmaster@1 1840 * Properties used: title, value, description, required, error
webmaster@1 1841 * @return
webmaster@1 1842 * A themed HTML string representing the form item.
webmaster@1 1843 *
webmaster@1 1844 * @ingroup themeable
webmaster@1 1845 */
webmaster@1 1846 function theme_item($element) {
webmaster@1 1847 return theme('form_element', $element, $element['#value'] . (!empty($element['#children']) ? $element['#children'] : ''));
webmaster@1 1848 }
webmaster@1 1849
webmaster@1 1850 /**
webmaster@1 1851 * Format a checkbox.
webmaster@1 1852 *
webmaster@1 1853 * @param $element
webmaster@1 1854 * An associative array containing the properties of the element.
webmaster@1 1855 * Properties used: title, value, return_value, description, required
webmaster@1 1856 * @return
webmaster@1 1857 * A themed HTML string representing the checkbox.
webmaster@1 1858 *
webmaster@1 1859 * @ingroup themeable
webmaster@1 1860 */
webmaster@1 1861 function theme_checkbox($element) {
webmaster@1 1862 _form_set_class($element, array('form-checkbox'));
webmaster@1 1863 $checkbox = '<input ';
webmaster@1 1864 $checkbox .= 'type="checkbox" ';
webmaster@1 1865 $checkbox .= 'name="'. $element['#name'] .'" ';
webmaster@1 1866 $checkbox .= 'id="'. $element['#id'] .'" ' ;
webmaster@1 1867 $checkbox .= 'value="'. $element['#return_value'] .'" ';
webmaster@1 1868 $checkbox .= $element['#value'] ? ' checked="checked" ' : ' ';
webmaster@1 1869 $checkbox .= drupal_attributes($element['#attributes']) .' />';
webmaster@1 1870
webmaster@1 1871 if (!is_null($element['#title'])) {
webmaster@1 1872 $checkbox = '<label class="option">'. $checkbox .' '. $element['#title'] .'</label>';
webmaster@1 1873 }
webmaster@1 1874
webmaster@1 1875 unset($element['#title']);
webmaster@1 1876 return theme('form_element', $element, $checkbox);
webmaster@1 1877 }
webmaster@1 1878
webmaster@1 1879 /**
webmaster@1 1880 * Format a set of checkboxes.
webmaster@1 1881 *
webmaster@1 1882 * @param $element
webmaster@1 1883 * An associative array containing the properties of the element.
webmaster@1 1884 * @return
webmaster@1 1885 * A themed HTML string representing the checkbox set.
webmaster@1 1886 *
webmaster@1 1887 * @ingroup themeable
webmaster@1 1888 */
webmaster@1 1889 function theme_checkboxes($element) {
webmaster@1 1890 $class = 'form-checkboxes';
webmaster@1 1891 if (isset($element['#attributes']['class'])) {
webmaster@1 1892 $class .= ' '. $element['#attributes']['class'];
webmaster@1 1893 }
webmaster@1 1894 $element['#children'] = '<div class="'. $class .'">'. (!empty($element['#children']) ? $element['#children'] : '') .'</div>';
webmaster@1 1895 if ($element['#title'] || $element['#description']) {
webmaster@1 1896 unset($element['#id']);
webmaster@1 1897 return theme('form_element', $element, $element['#children']);
webmaster@1 1898 }
webmaster@1 1899 else {
webmaster@1 1900 return $element['#children'];
webmaster@1 1901 }
webmaster@1 1902 }
webmaster@1 1903
webmaster@1 1904 function expand_checkboxes($element) {
webmaster@1 1905 $value = is_array($element['#value']) ? $element['#value'] : array();
webmaster@1 1906 $element['#tree'] = TRUE;
webmaster@1 1907 if (count($element['#options']) > 0) {
webmaster@1 1908 if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
webmaster@1 1909 $element['#default_value'] = array();
webmaster@1 1910 }
webmaster@1 1911 foreach ($element['#options'] as $key => $choice) {
webmaster@1 1912 if (!isset($element[$key])) {
webmaster@1 1913 $element[$key] = array('#type' => 'checkbox', '#processed' => TRUE, '#title' => $choice, '#return_value' => $key, '#default_value' => isset($value[$key]), '#attributes' => $element['#attributes']);
webmaster@1 1914 }
webmaster@1 1915 }
webmaster@1 1916 }
webmaster@1 1917 return $element;
webmaster@1 1918 }
webmaster@1 1919
webmaster@1 1920 /**
webmaster@1 1921 * Theme a form submit button.
webmaster@1 1922 *
webmaster@1 1923 * @ingroup themeable
webmaster@1 1924 */
webmaster@1 1925 function theme_submit($element) {
webmaster@1 1926 return theme('button', $element);
webmaster@1 1927 }
webmaster@1 1928
webmaster@1 1929 /**
webmaster@1 1930 * Theme a form button.
webmaster@1 1931 *
webmaster@1 1932 * @ingroup themeable
webmaster@1 1933 */
webmaster@1 1934 function theme_button($element) {
webmaster@1 1935 // Make sure not to overwrite classes.
webmaster@1 1936 if (isset($element['#attributes']['class'])) {
webmaster@1 1937 $element['#attributes']['class'] = 'form-'. $element['#button_type'] .' '. $element['#attributes']['class'];
webmaster@1 1938 }
webmaster@1 1939 else {
webmaster@1 1940 $element['#attributes']['class'] = 'form-'. $element['#button_type'];
webmaster@1 1941 }
webmaster@1 1942
webmaster@1 1943 return '<input type="submit" '. (empty($element['#name']) ? '' : 'name="'. $element['#name'] .'" ') .'id="'. $element['#id'] .'" value="'. check_plain($element['#value']) .'" '. drupal_attributes($element['#attributes']) ." />\n";
webmaster@1 1944 }
webmaster@1 1945
webmaster@1 1946 /**
webmaster@1 1947 * Theme a form image button.
webmaster@1 1948 *
webmaster@1 1949 * @ingroup themeable
webmaster@1 1950 */
webmaster@1 1951 function theme_image_button($element) {
webmaster@1 1952 // Make sure not to overwrite classes.
webmaster@1 1953 if (isset($element['#attributes']['class'])) {
webmaster@1 1954 $element['#attributes']['class'] = 'form-'. $element['#button_type'] .' '. $element['#attributes']['class'];
webmaster@1 1955 }
webmaster@1 1956 else {
webmaster@1 1957 $element['#attributes']['class'] = 'form-'. $element['#button_type'];
webmaster@1 1958 }
webmaster@1 1959
webmaster@1 1960 return '<input type="image" name="'. $element['#name'] .'" '.
webmaster@1 1961 (!empty($element['#value']) ? ('value="'. check_plain($element['#value']) .'" ') : '') .
webmaster@1 1962 'id="'. $element['#id'] .'" '.
webmaster@1 1963 drupal_attributes($element['#attributes']) .
webmaster@1 1964 ' src="'. base_path() . $element['#src'] .'" '.
webmaster@1 1965 (!empty($element['#title']) ? 'alt="'. check_plain($element['#title']) .'" title="'. check_plain($element['#title']) .'" ' : '' ) .
webmaster@1 1966 "/>\n";
webmaster@1 1967 }
webmaster@1 1968
webmaster@1 1969 /**
webmaster@1 1970 * Format a hidden form field.
webmaster@1 1971 *
webmaster@1 1972 * @param $element
webmaster@1 1973 * An associative array containing the properties of the element.
webmaster@1 1974 * Properties used: value, edit
webmaster@1 1975 * @return
webmaster@1 1976 * A themed HTML string representing the hidden form field.
webmaster@1 1977 *
webmaster@1 1978 * @ingroup themeable
webmaster@1 1979 */
webmaster@1 1980 function theme_hidden($element) {
webmaster@1 1981 return '<input type="hidden" name="'. $element['#name'] .'" id="'. $element['#id'] .'" value="'. check_plain($element['#value']) ."\" ". drupal_attributes($element['#attributes']) ." />\n";
webmaster@1 1982 }
webmaster@1 1983
webmaster@1 1984 /**
webmaster@1 1985 * Format a form token.
webmaster@1 1986 *
webmaster@1 1987 * @ingroup themeable
webmaster@1 1988 */
webmaster@1 1989 function theme_token($element) {
webmaster@1 1990 return theme('hidden', $element);
webmaster@1 1991 }
webmaster@1 1992
webmaster@1 1993 /**
webmaster@1 1994 * Format a textfield.
webmaster@1 1995 *
webmaster@1 1996 * @param $element
webmaster@1 1997 * An associative array containing the properties of the element.
webmaster@1 1998 * Properties used: title, value, description, size, maxlength, required, attributes autocomplete_path
webmaster@1 1999 * @return
webmaster@1 2000 * A themed HTML string representing the textfield.
webmaster@1 2001 *
webmaster@1 2002 * @ingroup themeable
webmaster@1 2003 */
webmaster@1 2004 function theme_textfield($element) {
webmaster@1 2005 $size = empty($element['#size']) ? '' : ' size="'. $element['#size'] .'"';
webmaster@1 2006 $maxlength = empty($element['#maxlength']) ? '' : ' maxlength="'. $element['#maxlength'] .'"';
webmaster@1 2007 $class = array('form-text');
webmaster@1 2008 $extra = '';
webmaster@1 2009 $output = '';
webmaster@1 2010
webmaster@1 2011 if ($element['#autocomplete_path']) {
webmaster@1 2012 drupal_add_js('misc/autocomplete.js');
webmaster@1 2013 $class[] = 'form-autocomplete';
webmaster@1 2014 $extra = '<input class="autocomplete" type="hidden" id="'. $element['#id'] .'-autocomplete" value="'. check_url(url($element['#autocomplete_path'], array('absolute' => TRUE))) .'" disabled="disabled" />';
webmaster@1 2015 }
webmaster@1 2016 _form_set_class($element, $class);
webmaster@1 2017
webmaster@1 2018 if (isset($element['#field_prefix'])) {
webmaster@1 2019 $output .= '<span class="field-prefix">'. $element['#field_prefix'] .'</span> ';
webmaster@1 2020 }
webmaster@1 2021
webmaster@1 2022 $output .= '<input type="text"'. $maxlength .' name="'. $element['#name'] .'" id="'. $element['#id'] .'"'. $size .' value="'. check_plain($element['#value']) .'"'. drupal_attributes($element['#attributes']) .' />';
webmaster@1 2023
webmaster@1 2024 if (isset($element['#field_suffix'])) {
webmaster@1 2025 $output .= ' <span class="field-suffix">'. $element['#field_suffix'] .'</span>';
webmaster@1 2026 }
webmaster@1 2027
webmaster@1 2028 return theme('form_element', $element, $output) . $extra;
webmaster@1 2029 }
webmaster@1 2030
webmaster@1 2031 /**
webmaster@1 2032 * Format a form.
webmaster@1 2033 *
webmaster@1 2034 * @param $element
webmaster@1 2035 * An associative array containing the properties of the element.
webmaster@1 2036 * Properties used: action, method, attributes, children
webmaster@1 2037 * @return
webmaster@1 2038 * A themed HTML string representing the form.
webmaster@1 2039 *
webmaster@1 2040 * @ingroup themeable
webmaster@1 2041 */
webmaster@1 2042 function theme_form($element) {
webmaster@1 2043 // Anonymous div to satisfy XHTML compliance.
webmaster@1 2044 $action = $element['#action'] ? 'action="'. check_url($element['#action']) .'" ' : '';
webmaster@1 2045 return '<form '. $action .' accept-charset="UTF-8" method="'. $element['#method'] .'" id="'. $element['#id'] .'"'. drupal_attributes($element['#attributes']) .">\n<div>". $element['#children'] ."\n</div></form>\n";
webmaster@1 2046 }
webmaster@1 2047
webmaster@1 2048 /**
webmaster@1 2049 * Format a textarea.
webmaster@1 2050 *
webmaster@1 2051 * @param $element
webmaster@1 2052 * An associative array containing the properties of the element.
webmaster@1 2053 * Properties used: title, value, description, rows, cols, required, attributes
webmaster@1 2054 * @return
webmaster@1 2055 * A themed HTML string representing the textarea.
webmaster@1 2056 *
webmaster@1 2057 * @ingroup themeable
webmaster@1 2058 */
webmaster@1 2059 function theme_textarea($element) {
webmaster@1 2060 $class = array('form-textarea');
webmaster@1 2061
webmaster@1 2062 // Add teaser behavior (must come before resizable)
webmaster@1 2063 if (!empty($element['#teaser'])) {
webmaster@1 2064 drupal_add_js('misc/teaser.js');
webmaster@1 2065 // Note: arrays are merged in drupal_get_js().
webmaster@1 2066 drupal_add_js(array('teaserCheckbox' => array($element['#id'] => $element['#teaser_checkbox'])), 'setting');
webmaster@1 2067 drupal_add_js(array('teaser' => array($element['#id'] => $element['#teaser'])), 'setting');
webmaster@1 2068 $class[] = 'teaser';
webmaster@1 2069 }
webmaster@1 2070
webmaster@1 2071 // Add resizable behavior
webmaster@1 2072 if ($element['#resizable'] !== FALSE) {
webmaster@1 2073 drupal_add_js('misc/textarea.js');
webmaster@1 2074 $class[] = 'resizable';
webmaster@1 2075 }
webmaster@1 2076
webmaster@1 2077 _form_set_class($element, $class);
webmaster@1 2078 return theme('form_element', $element, '<textarea cols="'. $element['#cols'] .'" rows="'. $element['#rows'] .'" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. drupal_attributes($element['#attributes']) .'>'. check_plain($element['#value']) .'</textarea>');
webmaster@1 2079 }
webmaster@1 2080
webmaster@1 2081 /**
webmaster@1 2082 * Format HTML markup for use in forms.
webmaster@1 2083 *
webmaster@1 2084 * This is used in more advanced forms, such as theme selection and filter format.
webmaster@1 2085 *
webmaster@1 2086 * @param $element
webmaster@1 2087 * An associative array containing the properties of the element.
webmaster@1 2088 * Properties used: value, children.
webmaster@1 2089 * @return
webmaster@1 2090 * A themed HTML string representing the HTML markup.
webmaster@1 2091 *
webmaster@1 2092 * @ingroup themeable
webmaster@1 2093 */
webmaster@1 2094
webmaster@1 2095 function theme_markup($element) {
webmaster@1 2096 return (isset($element['#value']) ? $element['#value'] : '') . (isset($element['#children']) ? $element['#children'] : '');
webmaster@1 2097 }
webmaster@1 2098
webmaster@1 2099 /**
webmaster@1 2100 * Format a password field.
webmaster@1 2101 *
webmaster@1 2102 * @param $element
webmaster@1 2103 * An associative array containing the properties of the element.
webmaster@1 2104 * Properties used: title, value, description, size, maxlength, required, attributes
webmaster@1 2105 * @return
webmaster@1 2106 * A themed HTML string representing the form.
webmaster@1 2107 *
webmaster@1 2108 * @ingroup themeable
webmaster@1 2109 */
webmaster@1 2110 function theme_password($element) {
webmaster@1 2111 $size = $element['#size'] ? ' size="'. $element['#size'] .'" ' : '';
webmaster@1 2112 $maxlength = $element['#maxlength'] ? ' maxlength="'. $element['#maxlength'] .'" ' : '';
webmaster@1 2113
webmaster@1 2114 _form_set_class($element, array('form-text'));
webmaster@1 2115 $output = '<input type="password" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. $maxlength . $size . drupal_attributes($element['#attributes']) .' />';
webmaster@1 2116 return theme('form_element', $element, $output);
webmaster@1 2117 }
webmaster@1 2118
webmaster@1 2119 /**
webmaster@1 2120 * Expand weight elements into selects.
webmaster@1 2121 */
webmaster@1 2122 function process_weight($element) {
webmaster@1 2123 for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
webmaster@1 2124 $weights[$n] = $n;
webmaster@1 2125 }
webmaster@1 2126 $element['#options'] = $weights;
webmaster@1 2127 $element['#type'] = 'select';
webmaster@1 2128 $element['#is_weight'] = TRUE;
webmaster@1 2129 $element += _element_info('select');
webmaster@1 2130 return $element;
webmaster@1 2131 }
webmaster@1 2132
webmaster@1 2133 /**
webmaster@1 2134 * Format a file upload field.
webmaster@1 2135 *
webmaster@1 2136 * @param $title
webmaster@1 2137 * The label for the file upload field.
webmaster@1 2138 * @param $name
webmaster@1 2139 * The internal name used to refer to the field.
webmaster@1 2140 * @param $size
webmaster@1 2141 * A measure of the visible size of the field (passed directly to HTML).
webmaster@1 2142 * @param $description
webmaster@1 2143 * Explanatory text to display after the form item.
webmaster@1 2144 * @param $required
webmaster@1 2145 * Whether the user must upload a file to the field.
webmaster@1 2146 * @return
webmaster@1 2147 * A themed HTML string representing the field.
webmaster@1 2148 *
webmaster@1 2149 * @ingroup themeable
webmaster@1 2150 *
webmaster@1 2151 * For assistance with handling the uploaded file correctly, see the API
webmaster@1 2152 * provided by file.inc.
webmaster@1 2153 */
webmaster@1 2154 function theme_file($element) {
webmaster@1 2155 _form_set_class($element, array('form-file'));
webmaster@1 2156 return theme('form_element', $element, '<input type="file" name="'. $element['#name'] .'"'. ($element['#attributes'] ? ' '. drupal_attributes($element['#attributes']) : '') .' id="'. $element['#id'] .'" size="'. $element['#size'] ."\" />\n");
webmaster@1 2157 }
webmaster@1 2158
webmaster@1 2159 /**
webmaster@1 2160 * Return a themed form element.
webmaster@1 2161 *
webmaster@1 2162 * @param element
webmaster@1 2163 * An associative array containing the properties of the element.
webmaster@1 2164 * Properties used: title, description, id, required
webmaster@1 2165 * @param $value
webmaster@1 2166 * The form element's data.
webmaster@1 2167 * @return
webmaster@1 2168 * A string representing the form element.
webmaster@1 2169 *
webmaster@1 2170 * @ingroup themeable
webmaster@1 2171 */
webmaster@1 2172 function theme_form_element($element, $value) {
webmaster@1 2173 // This is also used in the installer, pre-database setup.
webmaster@1 2174 $t = get_t();
webmaster@1 2175
webmaster@1 2176 $output = '<div class="form-item"';
webmaster@1 2177 if (!empty($element['#id'])) {
webmaster@1 2178 $output .= ' id="'. $element['#id'] .'-wrapper"';
webmaster@1 2179 }
webmaster@1 2180 $output .= ">\n";
webmaster@1 2181 $required = !empty($element['#required']) ? '<span class="form-required" title="'. $t('This field is required.') .'">*</span>' : '';
webmaster@1 2182
webmaster@1 2183 if (!empty($element['#title'])) {
webmaster@1 2184 $title = $element['#title'];
webmaster@1 2185 if (!empty($element['#id'])) {
webmaster@1 2186 $output .= ' <label for="'. $element['#id'] .'">'. $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
webmaster@1 2187 }
webmaster@1 2188 else {
webmaster@1 2189 $output .= ' <label>'. $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
webmaster@1 2190 }
webmaster@1 2191 }
webmaster@1 2192
webmaster@1 2193 $output .= " $value\n";
webmaster@1 2194
webmaster@1 2195 if (!empty($element['#description'])) {
webmaster@1 2196 $output .= ' <div class="description">'. $element['#description'] ."</div>\n";
webmaster@1 2197 }
webmaster@1 2198
webmaster@1 2199 $output .= "</div>\n";
webmaster@1 2200
webmaster@1 2201 return $output;
webmaster@1 2202 }
webmaster@1 2203
webmaster@1 2204 /**
webmaster@1 2205 * Sets a form element's class attribute.
webmaster@1 2206 *
webmaster@1 2207 * Adds 'required' and 'error' classes as needed.
webmaster@1 2208 *
webmaster@1 2209 * @param &$element
webmaster@1 2210 * The form element.
webmaster@1 2211 * @param $name
webmaster@1 2212 * Array of new class names to be added.
webmaster@1 2213 */
webmaster@1 2214 function _form_set_class(&$element, $class = array()) {
webmaster@1 2215 if ($element['#required']) {
webmaster@1 2216 $class[] = 'required';
webmaster@1 2217 }
webmaster@1 2218 if (form_get_error($element)) {
webmaster@1 2219 $class[] = 'error';
webmaster@1 2220 }
webmaster@1 2221 if (isset($element['#attributes']['class'])) {
webmaster@1 2222 $class[] = $element['#attributes']['class'];
webmaster@1 2223 }
webmaster@1 2224 $element['#attributes']['class'] = implode(' ', $class);
webmaster@1 2225 }
webmaster@1 2226
webmaster@1 2227 /**
webmaster@1 2228 * Prepare an HTML ID attribute string for a form item.
webmaster@1 2229 *
webmaster@1 2230 * Remove invalid characters and guarantee uniqueness.
webmaster@1 2231 *
webmaster@1 2232 * @param $id
webmaster@1 2233 * The ID to clean.
webmaster@1 2234 * @param $flush
webmaster@1 2235 * If set to TRUE, the function will flush and reset the static array
webmaster@1 2236 * which is built to test the uniqueness of element IDs. This is only
webmaster@1 2237 * used if a form has completed the validation process. This parameter
webmaster@1 2238 * should never be set to TRUE if this function is being called to
webmaster@1 2239 * assign an ID to the #ID element.
webmaster@1 2240 * @return
webmaster@1 2241 * The cleaned ID.
webmaster@1 2242 */
webmaster@1 2243 function form_clean_id($id = NULL, $flush = FALSE) {
webmaster@1 2244 static $seen_ids = array();
webmaster@1 2245
webmaster@1 2246 if ($flush) {
webmaster@1 2247 $seen_ids = array();
webmaster@1 2248 return;
webmaster@1 2249 }
webmaster@1 2250 $id = str_replace(array('][', '_', ' '), '-', $id);
webmaster@1 2251
webmaster@1 2252 // Ensure IDs are unique. The first occurrence is held but left alone.
webmaster@1 2253 // Subsequent occurrences get a number appended to them. This incrementing
webmaster@1 2254 // will almost certainly break code that relies on explicit HTML IDs in
webmaster@1 2255 // forms that appear more than once on the page, but the alternative is
webmaster@1 2256 // outputting duplicate IDs, which would break JS code and XHTML
webmaster@1 2257 // validity anyways. For now, it's an acceptable stopgap solution.
webmaster@1 2258 if (isset($seen_ids[$id])) {
webmaster@1 2259 $id = $id .'-'. $seen_ids[$id]++;
webmaster@1 2260 }
webmaster@1 2261 else {
webmaster@1 2262 $seen_ids[$id] = 1;
webmaster@1 2263 }
webmaster@1 2264
webmaster@1 2265 return $id;
webmaster@1 2266 }
webmaster@1 2267
webmaster@1 2268 /**
webmaster@1 2269 * @} End of "defgroup form_api".
webmaster@1 2270 */
webmaster@1 2271
webmaster@1 2272 /**
webmaster@1 2273 * @defgroup batch Batch operations
webmaster@1 2274 * @{
webmaster@1 2275 * Functions allowing forms processing to be spread out over several page
webmaster@1 2276 * requests, thus ensuring that the processing does not get interrupted
webmaster@1 2277 * because of a PHP timeout, while allowing the user to receive feedback
webmaster@1 2278 * on the progress of the ongoing operations.
webmaster@1 2279 *
webmaster@1 2280 * The API is primarily designed to integrate nicely with the Form API
webmaster@1 2281 * workflow, but can also be used by non-FAPI scripts (like update.php)
webmaster@1 2282 * or even simple page callbacks (which should probably be used sparingly).
webmaster@1 2283 *
webmaster@1 2284 * Example:
webmaster@1 2285 * @code
webmaster@1 2286 * $batch = array(
webmaster@1 2287 * 'title' => t('Exporting'),
webmaster@1 2288 * 'operations' => array(
webmaster@1 2289 * array('my_function_1', array($account->uid, 'story')),
webmaster@1 2290 * array('my_function_2', array()),
webmaster@1 2291 * ),
webmaster@1 2292 * 'finished' => 'my_finished_callback',
webmaster@1 2293 * );
webmaster@1 2294 * batch_set($batch);
webmaster@1 2295 * // only needed if not inside a form _submit handler :
webmaster@1 2296 * batch_process();
webmaster@1 2297 * @endcode
webmaster@1 2298 *
webmaster@1 2299 * Sample batch operations:
webmaster@1 2300 * @code
webmaster@1 2301 * // Simple and artificial: load a node of a given type for a given user
webmaster@1 2302 * function my_function_1($uid, $type, &$context) {
webmaster@1 2303 * // The $context array gathers batch context information about the execution (read),
webmaster@1 2304 * // as well as 'return values' for the current operation (write)
webmaster@1 2305 * // The following keys are provided :
webmaster@1 2306 * // 'results' (read / write): The array of results gathered so far by
webmaster@1 2307 * // the batch processing, for the current operation to append its own.
webmaster@1 2308 * // 'message' (write): A text message displayed in the progress page.
webmaster@1 2309 * // The following keys allow for multi-step operations :
webmaster@1 2310 * // 'sandbox' (read / write): An array that can be freely used to
webmaster@1 2311 * // store persistent data between iterations. It is recommended to
webmaster@1 2312 * // use this instead of $_SESSION, which is unsafe if the user
webmaster@1 2313 * // continues browsing in a separate window while the batch is processing.
webmaster@1 2314 * // 'finished' (write): A float number between 0 and 1 informing
webmaster@1 2315 * // the processing engine of the completion level for the operation.
webmaster@1 2316 * // 1 (or no value explicitly set) means the operation is finished
webmaster@1 2317 * // and the batch processing can continue to the next operation.
webmaster@1 2318 *
webmaster@1 2319 * $node = node_load(array('uid' => $uid, 'type' => $type));
webmaster@1 2320 * $context['results'][] = $node->nid .' : '. $node->title;
webmaster@1 2321 * $context['message'] = $node->title;
webmaster@1 2322 * }
webmaster@1 2323 *
webmaster@1 2324 * // More advanced example: multi-step operation - load all nodes, five by five
webmaster@1 2325 * function my_function_2(&$context) {
webmaster@1 2326 * if (empty($context['sandbox'])) {
webmaster@1 2327 * $context['sandbox']['progress'] = 0;
webmaster@1 2328 * $context['sandbox']['current_node'] = 0;
webmaster@1 2329 * $context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT nid) FROM {node}'));
webmaster@1 2330 * }
webmaster@1 2331 * $limit = 5;
webmaster@1 2332 * $result = db_query_range("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC", $context['sandbox']['current_node'], 0, $limit);
webmaster@1 2333 * while ($row = db_fetch_array($result)) {
webmaster@1 2334 * $node = node_load($row['nid'], NULL, TRUE);
webmaster@1 2335 * $context['results'][] = $node->nid .' : '. $node->title;
webmaster@1 2336 * $context['sandbox']['progress']++;
webmaster@1 2337 * $context['sandbox']['current_node'] = $node->nid;
webmaster@1 2338 * $context['message'] = $node->title;
webmaster@1 2339 * }
webmaster@1 2340 * if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
webmaster@1 2341 * $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
webmaster@1 2342 * }
webmaster@1 2343 * }
webmaster@1 2344 * @endcode
webmaster@1 2345 *
webmaster@1 2346 * Sample 'finished' callback:
webmaster@1 2347 * @code
webmaster@1 2348 * function batch_test_finished($success, $results, $operations) {
webmaster@1 2349 * if ($success) {
webmaster@1 2350 * $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
webmaster@1 2351 * }
webmaster@1 2352 * else {
webmaster@1 2353 * $message = t('Finished with an error.');
webmaster@1 2354 * }
webmaster@1 2355 * drupal_set_message($message);
webmaster@1 2356 * // Providing data for the redirected page is done through $_SESSION.
webmaster@1 2357 * foreach ($results as $result) {
webmaster@1 2358 * $items[] = t('Loaded node %title.', array('%title' => $result));
webmaster@1 2359 * }
webmaster@1 2360 * $_SESSION['my_batch_results'] = $items;
webmaster@1 2361 * }
webmaster@1 2362 * @endcode
webmaster@1 2363 */
webmaster@1 2364
webmaster@1 2365 /**
webmaster@1 2366 * Open a new batch.
webmaster@1 2367 *
webmaster@1 2368 * @param $batch
webmaster@1 2369 * An array defining the batch. The following keys can be used:
webmaster@1 2370 * 'operations': an array of function calls to be performed.
webmaster@1 2371 * Example:
webmaster@1 2372 * @code
webmaster@1 2373 * array(
webmaster@1 2374 * array('my_function_1', array($arg1)),
webmaster@1 2375 * array('my_function_2', array($arg2_1, $arg2_2)),
webmaster@1 2376 * )
webmaster@1 2377 * @endcode
webmaster@1 2378 * All the other values below are optional.
webmaster@1 2379 * batch_init() provides default values for the messages.
webmaster@1 2380 * 'title': title for the progress page.
webmaster@1 2381 * Defaults to t('Processing').
webmaster@1 2382 * 'init_message': message displayed while the processing is initialized.
webmaster@1 2383 * Defaults to t('Initializing.').
webmaster@1 2384 * 'progress_message': message displayed while processing the batch.
webmaster@1 2385 * Available placeholders are @current, @remaining, @total and @percent.
webmaster@1 2386 * Defaults to t('Remaining @remaining of @total.').
webmaster@1 2387 * 'error_message': message displayed if an error occurred while processing
webmaster@1 2388 * the batch.
webmaster@1 2389 * Defaults to t('An error has occurred.').
webmaster@1 2390 * 'finished': the name of a function to be executed after the batch has
webmaster@1 2391 * completed. This should be used to perform any result massaging that
webmaster@1 2392 * may be needed, and possibly save data in $_SESSION for display after
webmaster@1 2393 * final page redirection.
webmaster@1 2394 * 'file': the path to the file containing the definitions of the
webmaster@1 2395 * 'operations' and 'finished' functions, for instance if they don't
webmaster@1 2396 * reside in the original '.module' file. The path should be relative to
webmaster@1 2397 * the base_path(), and thus should be built using drupal_get_path().
webmaster@1 2398 *
webmaster@1 2399 * Operations are added as new batch sets. Batch sets are used to ensure
webmaster@1 2400 * clean code independence, ensuring that several batches submitted by
webmaster@1 2401 * different parts of the code (core / contrib modules) can be processed
webmaster@1 2402 * correctly while not interfering or having to cope with each other. Each
webmaster@1 2403 * batch set gets to specify his own UI messages, operates on its own set
webmaster@1 2404 * of operations and results, and triggers its own 'finished' callback.
webmaster@1 2405 * Batch sets are processed sequentially, with the progress bar starting
webmaster@1 2406 * fresh for every new set.
webmaster@1 2407 */
webmaster@1 2408 function batch_set($batch_definition) {
webmaster@1 2409 if ($batch_definition) {
webmaster@1 2410 $batch =& batch_get();
webmaster@1 2411 // Initialize the batch
webmaster@1 2412 if (empty($batch)) {
webmaster@1 2413 $batch = array(
webmaster@1 2414 'sets' => array(),
webmaster@1 2415 );
webmaster@1 2416 }
webmaster@1 2417
webmaster@1 2418 $init = array(
webmaster@1 2419 'sandbox' => array(),
webmaster@1 2420 'results' => array(),
webmaster@1 2421 'success' => FALSE,
webmaster@1 2422 );
webmaster@1 2423 // Use get_t() to allow batches at install time.
webmaster@1 2424 $t = get_t();
webmaster@1 2425 $defaults = array(
webmaster@1 2426 'title' => $t('Processing'),
webmaster@1 2427 'init_message' => $t('Initializing.'),
webmaster@1 2428 'progress_message' => $t('Remaining @remaining of @total.'),
webmaster@1 2429 'error_message' => $t('An error has occurred.'),
webmaster@1 2430 );
webmaster@1 2431 $batch_set = $init + $batch_definition + $defaults;
webmaster@1 2432
webmaster@1 2433 // Tweak init_message to avoid the bottom of the page flickering down after init phase.
webmaster@1 2434 $batch_set['init_message'] .= '<br/>&nbsp;';
webmaster@1 2435 $batch_set['total'] = count($batch_set['operations']);
webmaster@1 2436
webmaster@1 2437 // If the batch is being processed (meaning we are executing a stored submit handler),
webmaster@1 2438 // insert the new set after the current one.
webmaster@1 2439 if (isset($batch['current_set'])) {
webmaster@1 2440 // array_insert does not exist...
webmaster@1 2441 $slice1 = array_slice($batch['sets'], 0, $batch['current_set'] + 1);
webmaster@1 2442 $slice2 = array_slice($batch['sets'], $batch['current_set'] + 1);
webmaster@1 2443 $batch['sets'] = array_merge($slice1, array($batch_set), $slice2);
webmaster@1 2444 }
webmaster@1 2445 else {
webmaster@1 2446 $batch['sets'][] = $batch_set;
webmaster@1 2447 }
webmaster@1 2448 }
webmaster@1 2449 }
webmaster@1 2450
webmaster@1 2451 /**
webmaster@1 2452 * Process the batch.
webmaster@1 2453 *
webmaster@1 2454 * Unless the batch has been marked with 'progressive' = FALSE, the function
webmaster@1 2455 * issues a drupal_goto and thus ends page execution.
webmaster@1 2456 *
webmaster@1 2457 * This function is not needed in form submit handlers; Form API takes care
webmaster@1 2458 * of batches that were set during form submission.
webmaster@1 2459 *
webmaster@1 2460 * @param $redirect
webmaster@1 2461 * (optional) Path to redirect to when the batch has finished processing.
webmaster@1 2462 * @param $url
webmaster@1 2463 * (optional - should only be used for separate scripts like update.php)
webmaster@1 2464 * URL of the batch processing page.
webmaster@1 2465 */
webmaster@1 2466 function batch_process($redirect = NULL, $url = NULL) {
webmaster@1 2467 $batch =& batch_get();
webmaster@1 2468
webmaster@1 2469 if (isset($batch)) {
webmaster@1 2470 // Add process information
webmaster@1 2471 $url = isset($url) ? $url : 'batch';
webmaster@1 2472 $process_info = array(
webmaster@1 2473 'current_set' => 0,
webmaster@1 2474 'progressive' => TRUE,
webmaster@1 2475 'url' => isset($url) ? $url : 'batch',
webmaster@1 2476 'source_page' => $_GET['q'],
webmaster@1 2477 'redirect' => $redirect,
webmaster@1 2478 );
webmaster@1 2479 $batch += $process_info;
webmaster@1 2480
webmaster@1 2481 if ($batch['progressive']) {
webmaster@1 2482 // Clear the way for the drupal_goto redirection to the batch processing
webmaster@1 2483 // page, by saving and unsetting the 'destination' if any, on both places
webmaster@1 2484 // drupal_goto looks for it.
webmaster@1 2485 if (isset($_REQUEST['destination'])) {
webmaster@1 2486 $batch['destination'] = $_REQUEST['destination'];
webmaster@1 2487 unset($_REQUEST['destination']);
webmaster@1 2488 }
webmaster@1 2489 elseif (isset($_REQUEST['edit']['destination'])) {
webmaster@1 2490 $batch['destination'] = $_REQUEST['edit']['destination'];
webmaster@1 2491 unset($_REQUEST['edit']['destination']);
webmaster@1 2492 }
webmaster@1 2493
webmaster@1 2494 // Initiate db storage in order to get a batch id. We have to provide
webmaster@1 2495 // at least an empty string for the (not null) 'token' column.
webmaster@1 2496 db_query("INSERT INTO {batch} (token, timestamp) VALUES ('', %d)", time());
webmaster@1 2497 $batch['id'] = db_last_insert_id('batch', 'bid');
webmaster@1 2498
webmaster@1 2499 // Now that we have a batch id, we can generate the redirection link in
webmaster@1 2500 // the generic error message.
webmaster@1 2501 $t = get_t();
webmaster@1 2502 $batch['error_message'] = $t('Please continue to <a href="@error_url">the error page</a>', array('@error_url' => url($url, array('query' => array('id' => $batch['id'], 'op' => 'finished')))));
webmaster@1 2503
webmaster@1 2504 // Actually store the batch data and the token generated form the batch id.
webmaster@1 2505 db_query("UPDATE {batch} SET token = '%s', batch = '%s' WHERE bid = %d", drupal_get_token($batch['id']), serialize($batch), $batch['id']);
webmaster@1 2506
webmaster@1 2507 drupal_goto($batch['url'], 'op=start&id='. $batch['id']);
webmaster@1 2508 }
webmaster@1 2509 else {
webmaster@1 2510 // Non-progressive execution: bypass the whole progressbar workflow
webmaster@1 2511 // and execute the batch in one pass.
webmaster@1 2512 require_once './includes/batch.inc';
webmaster@1 2513 _batch_process();
webmaster@1 2514 }
webmaster@1 2515 }
webmaster@1 2516 }
webmaster@1 2517
webmaster@1 2518 /**
webmaster@1 2519 * Retrieve the current batch.
webmaster@1 2520 */
webmaster@1 2521 function &batch_get() {
webmaster@1 2522 static $batch = array();
webmaster@1 2523 return $batch;
webmaster@1 2524 }
webmaster@1 2525
webmaster@1 2526 /**
webmaster@1 2527 * @} End of "defgroup batch".
webmaster@1 2528 */