/[drupal]/contributions/docs/developer/examples/multipage_form_example.module
ViewVC logotype

Contents of /contributions/docs/developer/examples/multipage_form_example.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.10 - (show annotations) (download) (as text)
Sun Oct 12 08:52:36 2008 UTC (13 months, 2 weeks ago) by davereid
Branch: MAIN
Changes since 1.9: +7 -9 lines
File MIME type: text/x-php
- Fix coding standards
1 <?php
2
3 // $Id: multipage_form_example.module,v 1.9 2008/10/12 01:39:48 davereid Exp $
4
5 /**
6 * Implementation of hook_help().
7 */
8 function multipage_form_example_help($section) {
9 switch ($section) {
10 case 'admin/modules#description':
11 return t('An example module showing how to handle multipage forms in FAPI.');
12 case 'node/add#multipage_form_example':
13 return t('This will show you an example multipage form submission.');
14 }
15 }
16
17 /**
18 * Implementation of hook_menu().
19 */
20 function multipage_form_example_menu($may_cache) {
21 $items = array();
22
23 if (!$may_cache) {
24
25 $items[] = array('title' => t('multipage form example'),
26 'path' => 'node/add/multipage_form_example',
27 'access' => TRUE,
28 );
29 }
30
31 return $items;
32 }
33
34 /**
35 * Implementation of hook_access().
36 */
37 function multipage_form_example_access($op, $node) {
38 return TRUE;
39 }
40
41 /**
42 * Implementation of hook_node_info().
43 */
44 function multipage_form_example_node_info() {
45 return array('multipage_form_example' => array('name' => t('multipage form example'), 'base' => 'multipage_form_example'));
46 }
47
48 /**
49 * Implementation of hook_form() for multipage_form_example. We don't set ANY
50 * #required attributes here - we leave that up to multipage_form_example_pre_render().
51 */
52 function multipage_form_example_form(&$node) {
53 $form = array();
54
55 // 'checkboxes' elements are just ridiculously hard--i recommend just
56 // using a bunch of individual checkbox elements instead.
57 // I suspect that multiselects would also be pretty difficult...
58
59 // Here's a new form element, which enables you to store hidden values
60 // in an array. Check out the element definition functions at the bottom
61 // if you want to use this in a module. Keys show up in the
62 // $_POST/$form_values like:
63 // $_POST['edit']['test_hidden_array']['n'] = 'north'
64 // $form_values['test_hidden_array']['n'] = 'north'
65
66 $form['test_hidden_array'] = array(
67 '#type' => 'hidden_array',
68 '#values' => array('n' => 'north', 'e' => 'east', 'w' => 'west', 's' => 'south', ),
69 );
70
71 // Helper for our multipage - does field switching, sets options
72 // based on validated $form_values instead of $_POST, and so forth.
73 $form['#pre_render'] = array('multipage_form_example_pre_render');
74
75 // Title and body, page 1
76 $form['title'] = array(
77 '#type' => 'textfield',
78 '#title' => t('Title'),
79 '#default_value' => isset($node->title) ? $node->title : NULL,
80 '#description' => t("Enter a title for your favorites section."),
81 '#size' => 60,
82 '#maxlength' => 128,
83 '#required' => TRUE,
84 );
85 $form['body'] = array(
86 '#type' => 'textarea',
87 '#title' => t('Description'),
88 '#default_value' => isset($node->body) ? $node->body : NULL,
89 '#description' => t('Add any additional info about your favorites.'),
90 '#rows' => 20,
91 );
92
93 // Person, page 2
94 $form['person'] = array(
95 '#type' => 'fieldset',
96 '#title' => t('Your favorite person'),
97 );
98 $form['person']['fav_person'] = array(
99 '#type' => 'textfield',
100 '#title' => t('Name'),
101 '#default_value' => isset($node->fav_person) ? $node->fav_person : NULL,
102 '#description' => t('Enter their real name, or their code name if they like to fly stealth.'),
103 '#required' => TRUE,
104 );
105 $form['person']['fav_person_desc'] = array(
106 '#type' => 'textarea',
107 '#title' => t('Description'),
108 '#default_value' => isset($node->fav_person_desc) ? $node->fav_person_desc : NULL,
109 '#description' => t('Juicy details go here...'),
110 '#required' => TRUE,
111 );
112 $form['person']['fav_gummi'] = array(
113 '#type' => 'checkbox',
114 '#default_value' => isset($node->fav_gummi) ? $node->fav_gummi : 0,
115 '#title' => t('Do they like gummi bears?'),
116 );
117
118 // Color and number, page 3
119 $form['fav_color'] = array(
120 '#type' => 'select',
121 '#title' => t('Favorite color'),
122 '#default_value' => isset($node->fav_color) ? $node->fav_color : 'red',
123 '#options' => array('red' => t('Red'), 'green' => t('Green'), 'blue' => t('Blue'), 'yellow' => t('Yellow')),
124 '#required' => TRUE,
125 );
126 $form['fav_number'] = array(
127 '#type' => 'textfield',
128 '#title' => t('Favorite number'),
129 '#default_value' => isset($node->fav_number) ? $node->fav_number : NULL,
130 '#required' => TRUE,
131 );
132
133 // Movie and tv show, page 4
134 $form['fav_movie'] = array(
135 '#type' => 'textfield',
136 '#title' => t('Favorite movie'),
137 '#default_value' => isset($node->fav_movie) ? $node->fav_movie : NULL,
138 '#required' => TRUE,
139 );
140 $form['fav_tv'] = array(
141 '#type' => 'radios',
142 '#title' => t('How often do you watch your favorite tv show?'),
143 '#default_value' => isset($node->fav_tv) ? $node->fav_tv : 'daily',
144 '#options' => array('daily' => t('Daily'), 'weekly' => t('Weekly'), 'monthly' => t('Monthly'),),
145 '#required' => TRUE,
146 );
147
148 // Add a back button
149 $form['back'] = array(
150 '#type' => 'button',
151 '#value' => t('Back'),
152 '#weight' => 35,
153 );
154
155 return $form;
156 }
157
158 function theme_multipage_form_example_node_form($form) {
159 $content = '';
160
161 if (in_array($form['page']['#value'], array(3,4))) {
162 $content .= '<p>' . t('Your favorite person is %person, and they %like gummi bears.', array('%person' => check_plain($form['person']['fav_person']['#value']), '%like' => ($form['person']['fav_gummi']['#value'] ? t('like') : t('don\'t like')))) . '</p>';
163 }
164
165 if (in_array($form['page']['#value'], array(4))) {
166 $content .= '<p>' . t('Your favorite color is %color, and your favorite number is %number.', array('%color' => check_plain($form['fav_color']['#value']), '%number' => check_plain($form['fav_number']['#value'])));
167 }
168
169 foreach (element_children($form) as $key) {
170 $content .= form_render($form[$key]);
171 }
172 return $content;
173 }
174
175 /**
176 * Implementation of hook_form_alter(). Here, we set up the 'page' field,
177 * which keeps track of what stage the form is in.
178 */
179 function multipage_form_example_form_alter($form_id, &$form) {
180 // Make sure it's our multipage form.
181 if ($form_id == 'multipage_form_example_node_form') {
182
183 // Determine which page of the multipage form we're on. We don't do
184 // any incrementing here - that's something that our #pre_render'er
185 // will do when this page of the form has successfully validated.
186 $form['page'] = array(
187 '#type' => 'hidden',
188 '#value' => isset($_POST['edit']['page']) ? $_POST['edit']['page'] : 1,
189 );
190
191 // If back button is pressed, back up the form stage, Also, if preview
192 // is hit we need to decrement the counter here to keep us on the same page.
193 if ($_POST['op'] == t('Back')) {
194 $form['page']['#value']--;
195 }
196
197 // This modifies the form for validation purposes. once validation is
198 // completed, it'll be called one more time (through Drupal's Form API)
199 // at which point it'll advance the form to the next page.
200 multipage_form_example_pre_render($form_id, $form, FALSE);
201
202 // Here we're augmenting the regular node form validation/submission with
203 // some of our own. Note that these are inside the conditional check for
204 // this particular form.
205 $form['#validate'] = array_merge($form['#validate'], array('multipage_form_example_custom_validate' => array()));
206 $form['#submit'] = array_merge($form['#submit'], array('multipage_form_example_custom_submit' => array()));
207 }
208
209 return $form;
210 }
211
212 /**
213 * Validate our form.
214 */
215 function multipage_form_example_custom_validate() {
216 global $form_values;
217 // validate our number, but don't bother if the back button was hit
218 if (($form_values['page'] == 3 ) && !is_numeric($form_values['fav_number']) && ($_POST['op'] != t('Back'))) {
219 form_set_error('fav_number', t('Favorite number is a <em>number</em>, dummy!'));
220 }
221 }
222
223 /**
224 * The #pre_render of a form allows us to make changes AFTER validation (unlike
225 * hook_form_alter()), but BEFORE the form has actually been displayed. We use
226 * it to control which form elements are shown, which are hidden, and which values
227 * to set based on validate elements, not $_POST. This is a necessity for our
228 * complicated multipage example form.
229 */
230 function multipage_form_example_pre_render($form_id, &$form, $next_page = TRUE) {
231 global $form_values;
232
233 // Make sure it's our multipage form.
234 if ($form_id == 'multipage_form_example_node_form') {
235 // Are we ready for the next page in our form?
236 if ($next_page && isset($_POST['edit']['page']) && ($_POST['op'] != t('Back')) && ($_POST['op'] != t('Preview'))) {
237 $form['page']['#value'] = $form['page']['#value'] + 1;
238 }
239
240 // Validation errors? Show previous page for correcting.
241 if (form_get_errors()) {
242 $form['page']['#value']--;
243 }
244
245 // Modify the #required/#type values depending on our current page.
246 // The arrays tell us the pages the changes should take place in.
247
248 // Title/body, stage 1
249 multipage_form_set_element_visibility($form['title'], in_array($form['page']['#value'], array(1)));
250 multipage_form_set_element_visibility($form['body'], in_array($form['page']['#value'], array(1)));
251
252 // Person, stage 2
253 multipage_form_set_element_visibility($form['person'], in_array($form['page']['#value'], array(2)));
254 multipage_form_set_element_visibility($form['person']['fav_person'], in_array($form['page']['#value'], array(2)));
255 multipage_form_set_element_visibility($form['person']['fav_person_desc'], in_array($form['page']['#value'], array(2)));
256 multipage_form_set_element_visibility($form['person']['fav_gummi'], in_array($form['page']['#value'], array(2)), $next_page);
257
258 // Color and number, page 3
259 multipage_form_set_element_visibility($form['fav_color'], in_array($form['page']['#value'], array(3)));
260 multipage_form_set_element_visibility($form['fav_number'], in_array($form['page']['#value'], array(3)));
261
262 // Movie and tv show, page 4
263 multipage_form_set_element_visibility($form['fav_movie'], in_array($form['page']['#value'], array(4)));
264 multipage_form_set_element_visibility($form['fav_tv'], in_array($form['page']['#value'], array(4)), $next_page);
265
266 // Buttons
267 multipage_form_set_element_visibility($form['back'], in_array($form['page']['#value'], array(2, 3, 4)), $next_page);
268 multipage_form_set_element_visibility($form['preview'], in_array($form['page']['#value'], array(4)), $next_page);
269 multipage_form_set_element_visibility($form['submit'], in_array($form['page']['#value'], array(4)), $next_page);
270
271 // The button text actually helps determine if a form has actually been
272 // submitted because the name is also the value of a clicked button. By
273 // changing it for building, but not rendering, the form is not fully
274 // sumbitted until we name it 'Submit', the usual value.
275 if ($next_page) {
276 $submit_text = array(NULL, t('Next (person)'), t('Next (color/number)'), t('Next (tv/movie)'), t('Submit'));
277 $form['submit']['#value'] = $submit_text[$form['page']['#value']];
278 }
279 }
280 }
281
282 // Handles form submission. We're just throwing our data into the variable
283 // table to keep things simple
284 function multipage_form_example_custom_submit() {
285 global $form_values;
286 foreach ($form_values as $key => $value) {
287 if (in_array($key, array('fav_person', 'fav_person_desc', 'fav_gummi', 'fav_color', 'fav_number', 'fav_movie', 'fav_tv',))) {
288 $array[$key] = $value;
289 }
290 }
291
292 // A little hack so we can save new node info properly to the variable table
293 if (isset($form_values['nid'])) {
294 $nid = $form_values['nid'];
295 }
296 else {
297 $nid = db_result(db_query("SELECT id FROM {sequences} WHERE name = 'node_nid'"));
298 }
299
300 variable_set('multipage_form_example_' . $nid, $array);
301 }
302
303 /**
304 * Implementation of hook_load().
305 *
306 * Now that we've defined how to manage the node data in the database, We
307 * need to tell Drupal how to get the node back out. This hook is called
308 * every time a node is loaded, and allows us to do some loading of our own.
309 */
310 function multipage_form_example_load($node) {
311 $additions = variable_get('multipage_form_example_' . $node->nid, NULL);
312 $additions = (object) $additions;
313 return $additions;
314 }
315
316 /**
317 * Implementation of hook_delete().
318 *
319 * Clean up our data in variable table.
320 */
321 function multipage_form_example_delete($node) {
322 // Notice that we're matching all revision, by using the node's nid.
323 variable_del('multipage_form_example_' . $node->nid);
324 }
325
326 /**
327 * Implementation of hook_view().
328 *
329 * This is a typical implementation that simply runs the node text through
330 * the output filters.
331 */
332 function multipage_form_example_view(&$node, $teaser = FALSE, $page = FALSE) {
333 $node = node_prepare($node, $teaser);
334 $favorites = theme('multipage_form_example', $node);
335 $node->body .= $favorites;
336 $node->teaser .= $favorites;
337 }
338
339 /**
340 * A custom theme function.
341 *
342 * By using this function to format our node-specific information, themes
343 * can override this presentation if they wish. We also wrap the default
344 * presentation in a CSS class that is prefixed by the module name. This
345 * way, style sheets can modify the output without requiring theme code.
346 */
347 function theme_multipage_form_example($node) {
348 $person_display = t('Your favorite person is %person, and they %like gummi bears. <br \>', array('%person' => check_plain($node->fav_person), '%like' => ($node->fav_gummi ? t('like') : t('don\'t like'))));
349 $color_number_display = t('Your favorite color is %color, and your favorite number is %number. <br \>', array('%color' => check_plain($node->fav_color), '%number' => check_plain($node->fav_number)));
350 $tv_movie_display = t('Your favorite movie is %movie, and you watch your favorite tv show %watch.', array('%movie' => check_plain($node->fav_movie), '%watch' => check_plain($node->fav_tv)));
351
352 $output = '<div class="multipage_form_example">';
353 $output .= $person_display . $color_number_display . $tv_movie_display;
354 $output .= '</div>';
355
356 return $output;
357 }
358
359 /**
360 * Set an element's visibility. Elements are gnerally changed to hidden
361 * elements. Visibility may be set and reset any number of times.
362 *
363 * @param $element
364 * The form element array to modify.
365 * @param $visible
366 * The desired visibity of the form element.
367 * @param $next_page
368 * Boolean value, TRUE if the next page is about to be rendered, FALSE otherwise.
369 */
370 function multipage_form_set_element_visibility(&$element, $visible, $next_page = TRUE) {
371 multipage_form_restore_attributes($element);
372 if (!$visible) {
373 switch ($element['#type']) {
374 case 'textfield':
375 case 'textarea':
376 case 'select':
377 multipage_form_set_attribute($element, '#type', 'hidden');
378 multipage_form_set_attribute($element, '#required', FALSE);
379 break;
380
381 case 'radios':
382 // Radios elements cannot be hidden unless they have been processed.
383 if ($next_page) {
384 multipage_form_set_attribute($element, '#type', 'hidden');
385 multipage_form_set_attribute($element, '#required', FALSE);
386 }
387 break;
388
389 case 'radio':
390 case 'checkbox':
391 // We can't change these to hidden until right before the next page is rendered, otherwise
392 // the value is lost sometimes.
393 if ($next_page) {
394 multipage_form_set_attribute($element, '#type', 'hidden');
395 }
396 break;
397
398 case 'fieldset':
399 multipage_form_set_attribute($element, '#type', NULL);
400 break;
401
402 case 'button':
403 if ($next_page) {
404 multipage_form_set_attribute($element, '#type', 'value');
405 }
406 break;
407
408 case 'submit':
409 if ($next_page) {
410 multipage_form_set_attribute($element, '#type', 'button');
411 }
412 break;
413 }
414 }
415
416 foreach (element_children($element) as $key) {
417 multipage_form_set_element_visibility($element[$key], $visible, $next_page);
418 }
419 }
420
421 /**
422 * Set an attribute on an element array with storing the previous value which
423 * may be reverted to using multipage_form_restore_attributes().
424 *
425 * @param $element
426 * The form element array to modify.
427 * @param $key
428 * A key of the form element array.
429 * @param $new_value
430 * The new value for the attribute.
431 */
432 function multipage_form_set_attribute(&$element, $key, $new_value) {
433 $element['#multipage_form_original_' . $key] = $element[$key];
434 $element[$key] = $new_value;
435 }
436
437 /**
438 * Restore any form attributes which have been set using
439 * multipage_form_set_attribute().
440 *
441 * @param $element
442 * The form element array to restore.
443 */
444 function multipage_form_restore_attributes(&$element) {
445 foreach (array_filter(array_keys($element), create_function('$key', 'return (strpos($key, "#multipage_form_original_") === 0);')) as $key) {
446 $element[str_replace('#multipage_form_original_', '', $key)] = $element[$key];
447 }
448 }
449
450 /**
451 * Playing around here with a new form element to enable storing hidden values in an array fashion.
452 * Seems to work fine. Check out $form['test_hidden_array'] above for how to structure the form
453 * element
454 */
455 function multipage_form_example_elements() {
456 $type['hidden_array'] = array('#input' => TRUE, '#process' => array('expand_hidden_array' => array()), '#tree' => TRUE);
457 return $type;
458 }
459
460 function expand_hidden_array($element) {
461 $values = is_array($element['#values']) ? $element['#values'] : array();
462 $element['#tree'] = TRUE;
463 foreach ($values as $key => $value) {
464 $element[$key] = array('#type' => 'hidden', '#processed' => TRUE, '#value' => $value);
465 }
466 return $element;
467 }
468
469 function theme_hidden_array($element) {
470 return $element['#children'];
471 }

  ViewVC Help
Powered by ViewVC 1.1.2