/[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.2 - (show annotations) (download) (as text)
Thu Mar 30 00:17:47 2006 UTC (3 years, 8 months ago) by drumm
Branch: MAIN
Changes since 1.1: +96 -44 lines
File MIME type: text/x-php
Using more helper functions for simpler code.
1 <?php
2
3 // $Id: multipage_form_example.module,v 1.1 2006/03/22 19:16:41 jvandyk 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
72
73 // Helper for our multipage - does field switching, sets options
74 // based on validated $form_values instead of $_POST, and so forth.
75 $form['#pre_render'] = array('multipage_form_example_pre_render');
76
77 // Title and body, page 1
78 $form['title'] = array(
79 '#type' => 'textfield',
80 '#title' => t('Title'),
81 '#default_value' => isset($node->title) ? $node->title : NULL,
82 '#description' => t("Enter a title for your favorites section."),
83 '#size' => 60,
84 '#maxlength' => 128,
85 '#required' => TRUE,
86 );
87 $form['body'] = array(
88 '#type' => 'textarea',
89 '#title' => t('Description'),
90 '#default_value' => isset($node->body) ? $node->body : NULL,
91 '#description' => t('Add any additional info about your favorites.'),
92 '#rows' => 20,
93 );
94
95 // Person, page 2
96 $form['person'] = array(
97 '#type' => 'fieldset',
98 '#title' => t('Your favorite person'),
99 );
100 $form['person']['fav_person'] = array(
101 '#type' => 'textfield',
102 '#title' => t('Name'),
103 '#default_value' => isset($node->fav_person) ? $node->fav_person : NULL,
104 '#description' => t('Enter their real name, or their code name if they like to fly stealth.'),
105 '#required' => TRUE,
106 );
107 $form['person']['fav_person_desc'] = array(
108 '#type' => 'textarea',
109 '#title' => t('Description'),
110 '#default_value' => isset($node->fav_person_desc) ? $node->fav_person_desc : NULL,
111 '#description' => t('Juicy details go here...'),
112 '#required' => TRUE,
113 );
114 $form['person']['fav_gummi'] = array(
115 '#type' => 'checkbox',
116 '#default_value' => isset($node->fav_gummi) ? $node->fav_gummi : 0,
117 '#title' => t('Do they like gummi bears?'),
118 );
119
120 // Color and number, page 3
121 $form['fav_color'] = array(
122 '#type' => 'select',
123 '#title' => t('Favorite color'),
124 '#default_value' => isset($node->fav_color) ? $node->fav_color : 'red',
125 '#options' => array('red' => t('Red'), 'green' => t('Green'), 'blue' => t('Blue'), 'yellow' => t('Yellow')),
126 '#required' => TRUE,
127 );
128 $form['fav_number'] = array(
129 '#type' => 'textfield',
130 '#title' => t('Favorite number'),
131 '#default_value' => isset($node->fav_number) ? $node->fav_number : NULL,
132 '#required' => TRUE,
133 );
134
135 // Movie and tv show, page 4
136 $form['fav_movie'] = array(
137 '#type' => 'textfield',
138 '#title' => t('Favorite movie'),
139 '#default_value' => isset($node->fav_movie) ? $node->fav_movie : NULL,
140 '#required' => TRUE,
141 );
142 $form['fav_tv'] = array(
143 '#type' => 'radios',
144 '#title' => t('How often do you watch your favorite tv show?'),
145 '#default_value' => isset($node->fav_tv) ? $node->fav_tv : 'daily',
146 '#options' => array('daily' => t('Daily'), 'weekly' => t('Weekly'), 'monthly' => t('Monthly'),),
147 '#required' => TRUE,
148 );
149
150 // Some markup elements to help the user see what they've already
151 // entered. Since the data won't be available until after the form
152 // is submitted, we'll only build the basic element here, and then
153 // we'll populate it in #pre_render
154 $form['person_display'] = array(
155 '#type' => 'markup',
156 );
157 $form['color_number_display'] = array(
158 '#type' => 'markup',
159 );
160
161 // Add a back button
162 $form['back'] = array(
163 '#type' => 'button',
164 '#value' => t('Back'),
165 '#weight' => 35,
166 );
167
168 return $form;
169 }
170
171 /**
172 * Implementation of hook_form_alter(). Here, we set up the 'page' field,
173 * which keeps track of what stage the form is in.
174 */
175 function multipage_form_example_form_alter($form_id, &$form) {
176 // Make sure it's our multipage form.
177 if ($form_id == 'multipage_form_example_node_form') {
178
179 // Determine which page of the multipage form we're on. We don't do
180 // any incrementing here - that's something that our #pre_render'er
181 // will do when this page of the form has successfully validated.
182 $form['page'] = array('#type' => 'hidden', '#value' =>
183 isset($_POST['edit']['page']) ? $_POST['edit']['page'] : 1);
184
185 // If back button is pressed, back up the form stage, Also, if preview
186 // is hit we need to decrement the counter here to keep us on the same page.
187 if ($_POST['op'] == t('Back') || $_POST['op'] == t('Preview')) {$form['page']['#value']--;}
188
189 // This modifies the form for validation purposes. once validation is
190 // completed, it'll be called one more time (through Drupal's Form API)
191 // at which point it'll advance the form to the next page.
192 multipage_form_example_pre_render($form_id, $form, FALSE);
193
194 // Here we're augmenting the regular node form validation/submission with
195 // some of our own. Note that these are inside the conditional check for
196 // this particular form.
197 $form['#validate'] = array_merge($form['#validate'], array('multipage_form_example_validate' => array()));
198 $form['#submit'] = array_merge($form['#submit'], array('multipage_form_example_submit' => array()));
199 }
200
201 return $form;
202 }
203
204 /**
205 * Validate our form.
206 */
207 function multipage_form_example_validate() {
208 global $form_values;
209 // validate our number, but don't bother if the back button was hit
210 if (($form_values['page'] == 3 ) && !is_numeric($form_values['fav_number']) && ($_POST['op'] != t('Back'))) {
211 form_set_error('fav_number', t('Favorite number is a <em>number</em>, dummy!'));
212 }
213 }
214
215 /**
216 * The #pre_render of a form allows us to make changes AFTER validation (unlike
217 * hook_form_alter()), but BEFORE the form has actually been displayed. We use
218 * it to control which form elements are shown, which are hidden, and which values
219 * to set based on validate elements, not $_POST. This is a necessity for our
220 * complicated multipage example form.
221 */
222 function multipage_form_example_pre_render($form_id, &$form, $next_page = TRUE) {
223 global $form_values;
224
225 // Make sure it's our multipage form.
226 if ($form_id == 'multipage_form_example_node_form') {
227 // Are we ready for the next page in our form?
228 if ($next_page && isset($_POST['edit']['page']) && ($_POST['op'] != t('Back'))) {
229 $form['page']['#value'] = $form['page']['#value'] + 1;
230 }
231
232 // Validation errors? Show previous page for correcting.
233 if (form_get_errors()) {
234 $form['page']['#value']--;
235 }
236
237 // Modify the #required/#type values depending on our current page.
238 // The arrays tell us the pages the changes should take place in.
239
240 // Title/body, stage 1
241 multipage_form_set_element_visibility($form['title'], in_array($form['page']['#value'], array(1)));
242 multipage_form_set_element_visibility($form['body'], in_array($form['page']['#value'], array(1)));
243
244 // Person, stage 2
245 multipage_form_set_element_visibility($form['person'], in_array($form['page']['#value'], array(2)));
246 multipage_form_set_element_visibility($form['person']['fav_person'], in_array($form['page']['#value'], array(2)));
247 multipage_form_set_element_visibility($form['person']['fav_person_desc'], in_array($form['page']['#value'], array(2)));
248 multipage_form_set_element_visibility($form['person']['fav_gummi'], in_array($form['page']['#value'], array(2)));
249
250 // Color and number, page 3
251 multipage_form_set_element_visibility($form['fav_color'], in_array($form['page']['#value'], array(3)));
252 multipage_form_set_element_visibility($form['fav_number'], in_array($form['page']['#value'], array(3)));
253
254 // Movie and tv show, page 4
255 multipage_form_set_element_visibility($form['fav_movie'], in_array($form['page']['#value'], array(4)));
256 // This bit of trickery is because radios is a bit of a special case --
257 // it's an 'expanding' form element, which means that the multiple buttons
258 // get built by form_builder. Because the building for display actually
259 // happens when the form is still set to stage 3, we have to build it as a
260 // radios type in stage 3, or nothing will display on stage 4!
261 // form_hide_elements is a little helper function that recurses through and
262 // hides all of the buttons we built if we don't actually happen to be
263 // displaying stage 4. whew!
264 if ($next_page) {
265 multipage_form_set_element_visibility($form['fav_tv'], in_array($form['page']['#value'], array(4)));
266 }
267
268 // The progress display for stuff we've already entered
269 $person_display = t('Your favorite person is %person, and they %like gummi bears.<br \>', array('%person' => check_plain($form_values['fav_person']), '%like' => ($form_values['fav_gummi'] ? t('like') : t('don\'t like'))));
270 $color_number_display = t('Your favorite color is %color, and your favorite number is %number.', array('%color' => check_plain($form_values['fav_color']), '%number' => check_plain($form_values['fav_number'])));
271
272 $form['person_display']['#value'] = in_array($form['page']['#value'], array(3,4)) ? $person_display : '';
273 $form['color_number_display']['#value'] = in_array($form['page']['#value'], array(4)) ? $color_number_display : '';
274
275 // Buttons -- like radios, they need to be properly built in the previous stage, so here we also do the switches at
276 // the last chance we have. Notice that the type gets set to 'value' and not 'hidden', b/c hidden will screw w/
277 // $_POST['op']
278 if ($next_page) {
279 multipage_form_set_element_visibility($form['back'], in_array($form['page']['#value'], array(2, 3, 4)));
280 multipage_form_set_element_visibility($form['preview'], in_array($form['page']['#value'], array(4)));
281 multipage_form_set_element_visibility($form['submit'], in_array($form['page']['#value'], array(4)));
282 $submit_text = array(NULL, t('Next (person)'), t('Next (color/number)'), t('Next (tv/movie)'), t('Submit'));
283 $form['submit']['#value'] = $submit_text[$form['page']['#value']];
284 }
285 }
286 }
287
288 // Handles form submission. We're just throwing our data into the variable
289 // table to keep things simple
290 function multipage_form_example_submit() {
291 global $form_values;
292 foreach ($form_values as $key => $value) {
293 if (in_array($key, array('fav_person', 'fav_person_desc', 'fav_gummi', 'fav_color', 'fav_number', 'fav_movie', 'fav_tv',))) {
294 $array[$key] = $value;
295 }
296 }
297 variable_set('multipage_form_example_'. $form_values['nid'], $array);
298 }
299
300 /**
301 * Implementation of hook_load().
302 *
303 * Now that we've defined how to manage the node data in the database, We
304 * need to tell Drupal how to get the node back out. This hook is called
305 * every time a node is loaded, and allows us to do some loading of our own.
306 */
307 function multipage_form_example_load($node) {
308 $additions = variable_get('multipage_form_example_'. $node->nid, NULL);
309 $additions = (object) $additions;
310 return $additions;
311 }
312
313 /**
314 * Implementation of hook_delete().
315 *
316 * Clean up our data in variable table.
317 */
318 function multipage_form_example_delete($node) {
319 // Notice that we're matching all revision, by using the node's nid.
320 variable_del('multipage_form_example_'. $node->nid);
321 }
322
323 /**
324 * Implementation of hook_view().
325 *
326 * This is a typical implementation that simply runs the node text through
327 * the output filters.
328 */
329 function multipage_form_example_view(&$node, $teaser = FALSE, $page = FALSE) {
330 $node = node_prepare($node, $teaser);
331 $favorites = theme('multipage_form_example', $node);
332 $node->body .= $favorites;
333 $node->teaser .= $favorites;
334 }
335
336 /**
337 * A custom theme function.
338 *
339 * By using this function to format our node-specific information, themes
340 * can override this presentation if they wish. We also wrap the default
341 * presentation in a CSS class that is prefixed by the module name. This
342 * way, style sheets can modify the output without requiring theme code.
343 */
344 function theme_multipage_form_example($node) {
345 $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'))));
346 $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)));
347 $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)));
348
349 $output = '<div class="multipage_form_example">';
350 $output .= $person_display . $color_number_display . $tv_movie_display;
351 $output .= '</div>';
352
353 return $output;
354 }
355
356 /**
357 * A little helper function to hide the child elements of 'radios'.
358 */
359 function multipage_form_set_element_visibility(&$element, $visible) {
360 multipage_form_restore_attributes($element);
361 if (!$visible) {
362 switch ($element['#type']) {
363 case 'textfield':
364 case 'textarea':
365 case 'radios':
366 case 'select':
367 multipage_form_set_attribute($element, '#type', 'hidden');
368 multipage_form_set_attribute($element, '#required', FALSE);
369 break;
370
371 case 'radio':
372 case 'checkbox':
373 multipage_form_set_attribute($element, '#type', 'hidden');
374 break;
375
376 case 'fieldset':
377 multipage_form_set_attribute($element, '#type', NULL);
378 break;
379
380 case 'button':
381 multipage_form_set_attribute($element, '#type', 'value');
382 break;
383
384 case 'submit':
385 multipage_form_set_attribute($element, '#type', 'button');
386 break;
387 }
388 }
389
390 foreach (element_children($element) as $key) {
391 multipage_form_set_element_visibility($element[$key], $visible);
392 }
393 }
394
395 /**
396 * Set an attribute on an element array with storing the previous value or
397 * restore to a previous value.
398 *
399 * @param $element
400 * The form element to modify.
401 * @param $attribute
402 * An attribute of the form element.
403 * @param $new_value
404 * The new value for the attribute to be set with; NULL to restore a previous
405 * value.
406 */
407 function multipage_form_set_attribute(&$element, $key, $new_value) {
408 $element['#multipage_form_original_'. $key] = $element[$key];
409 $element[$key] = $new_value;
410 }
411
412 function multipage_form_restore_attributes(&$element) {
413 foreach (array_filter(array_keys($element), create_function('$key', 'return (strpos($key, "#multipage_form_original_") === 0);')) as $key) {
414 $element[str_replace('#multipage_form_original_', '', $key)] = $element[$key];
415 }
416 }
417
418 /**
419 * Playing around here with a new form element to enable storing hidden values in an array fashion.
420 * Seems to work fine. Check out $form['test_hidden_array'] above for how to structure the form
421 * element
422 */
423 function multipage_form_example_elements() {
424 $type['hidden_array'] = array('#input' => TRUE, '#process' => array('expand_hidden_array' => array()), '#tree' => TRUE);
425 return $type;
426 }
427
428 function expand_hidden_array($element) {
429 $values = is_array($element['#values']) ? $element['#values'] : array();
430 $element['#tree'] = TRUE;
431 foreach ($values as $key => $value) {
432 $element[$key] = array('#type' => 'hidden', '#processed' => TRUE, '#value' => $value);
433 }
434 return $element;
435 }
436
437 function theme_hidden_array($element) {
438 return $element['#children'];
439 }

  ViewVC Help
Powered by ViewVC 1.1.2