/[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.7 - (hide annotations) (download) (as text)
Sun Apr 2 19:23:47 2006 UTC (3 years, 7 months ago) by thehunmonkgroup
Branch: MAIN
Changes since 1.6: +11 -4 lines
File MIME type: text/x-php
added an optional  parameter to multipage_form_set_element_visibility--this is necessary because changing the element type of checkbox/radio to hidden prior to form building causes the value to be lost sometimes.
1 jvandyk 1.1 <?php
2    
3 thehunmonkgroup 1.7 // $Id: multipage_form_example.module,v 1.6 2006/04/02 19:02:55 thehunmonkgroup Exp $
4 jvandyk 1.1
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 drumm 1.2 // Title and body, page 1
78 jvandyk 1.1 $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 drumm 1.2 '#required' => TRUE,
86 jvandyk 1.1 );
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 drumm 1.2 '#type' => 'fieldset',
98 jvandyk 1.1 '#title' => t('Your favorite person'),
99 drumm 1.2 );
100 jvandyk 1.1 $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 drumm 1.2 '#required' => TRUE,
106 jvandyk 1.1 );
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 drumm 1.2 '#required' => TRUE,
113 jvandyk 1.1 );
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 drumm 1.2 '#required' => TRUE,
127 jvandyk 1.1 );
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 drumm 1.2 '#required' => TRUE,
133 jvandyk 1.1 );
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 drumm 1.2 '#required' => TRUE,
141 jvandyk 1.1 );
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 drumm 1.2 '#required' => TRUE,
148 jvandyk 1.1 );
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 drumm 1.2 '#weight' => 35,
166 jvandyk 1.1 );
167    
168     return $form;
169     }
170    
171 drumm 1.3 function theme_multipage_form_example_node_form($form) {
172     $content = '';
173    
174     if (in_array($form['page']['#value'], array(3,4))) {
175     $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>';
176     }
177    
178     if (in_array($form['page']['#value'], array(4))) {
179     $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'])));
180     }
181    
182     foreach (element_children($form) as $key) {
183     $content .= form_render($form[$key]);
184     }
185     return $content;
186     }
187    
188 jvandyk 1.1 /**
189     * Implementation of hook_form_alter(). Here, we set up the 'page' field,
190     * which keeps track of what stage the form is in.
191     */
192     function multipage_form_example_form_alter($form_id, &$form) {
193     // Make sure it's our multipage form.
194     if ($form_id == 'multipage_form_example_node_form') {
195    
196     // Determine which page of the multipage form we're on. We don't do
197     // any incrementing here - that's something that our #pre_render'er
198     // will do when this page of the form has successfully validated.
199 drumm 1.3 $form['page'] = array(
200     '#type' => 'hidden',
201     '#value' => isset($_POST['edit']['page']) ? $_POST['edit']['page'] : 1,
202     );
203 jvandyk 1.1
204     // If back button is pressed, back up the form stage, Also, if preview
205     // is hit we need to decrement the counter here to keep us on the same page.
206 thehunmonkgroup 1.6 if ($_POST['op'] == t('Back')) {
207 drumm 1.3 $form['page']['#value']--;
208     }
209 jvandyk 1.1
210     // This modifies the form for validation purposes. once validation is
211     // completed, it'll be called one more time (through Drupal's Form API)
212     // at which point it'll advance the form to the next page.
213     multipage_form_example_pre_render($form_id, $form, FALSE);
214    
215     // Here we're augmenting the regular node form validation/submission with
216     // some of our own. Note that these are inside the conditional check for
217     // this particular form.
218 thehunmonkgroup 1.6 $form['#validate'] = array_merge($form['#validate'], array('multipage_form_example_custom_validate' => array()));
219     $form['#submit'] = array_merge($form['#submit'], array('multipage_form_example_custom_submit' => array()));
220 jvandyk 1.1 }
221    
222     return $form;
223     }
224    
225     /**
226     * Validate our form.
227     */
228 thehunmonkgroup 1.6 function multipage_form_example_custom_validate() {
229 jvandyk 1.1 global $form_values;
230     // validate our number, but don't bother if the back button was hit
231     if (($form_values['page'] == 3 ) && !is_numeric($form_values['fav_number']) && ($_POST['op'] != t('Back'))) {
232     form_set_error('fav_number', t('Favorite number is a <em>number</em>, dummy!'));
233     }
234     }
235    
236     /**
237     * The #pre_render of a form allows us to make changes AFTER validation (unlike
238     * hook_form_alter()), but BEFORE the form has actually been displayed. We use
239     * it to control which form elements are shown, which are hidden, and which values
240     * to set based on validate elements, not $_POST. This is a necessity for our
241     * complicated multipage example form.
242     */
243     function multipage_form_example_pre_render($form_id, &$form, $next_page = TRUE) {
244     global $form_values;
245    
246     // Make sure it's our multipage form.
247     if ($form_id == 'multipage_form_example_node_form') {
248     // Are we ready for the next page in our form?
249 thehunmonkgroup 1.6 if ($next_page && isset($_POST['edit']['page']) && ($_POST['op'] != t('Back')) && ($_POST['op'] != t('Preview'))) {
250 jvandyk 1.1 $form['page']['#value'] = $form['page']['#value'] + 1;
251     }
252    
253     // Validation errors? Show previous page for correcting.
254 drumm 1.2 if (form_get_errors()) {
255     $form['page']['#value']--;
256     }
257 jvandyk 1.1
258     // Modify the #required/#type values depending on our current page.
259     // The arrays tell us the pages the changes should take place in.
260    
261     // Title/body, stage 1
262 drumm 1.2 multipage_form_set_element_visibility($form['title'], in_array($form['page']['#value'], array(1)));
263     multipage_form_set_element_visibility($form['body'], in_array($form['page']['#value'], array(1)));
264 jvandyk 1.1
265     // Person, stage 2
266 drumm 1.2 multipage_form_set_element_visibility($form['person'], in_array($form['page']['#value'], array(2)));
267     multipage_form_set_element_visibility($form['person']['fav_person'], in_array($form['page']['#value'], array(2)));
268     multipage_form_set_element_visibility($form['person']['fav_person_desc'], in_array($form['page']['#value'], array(2)));
269 thehunmonkgroup 1.7 multipage_form_set_element_visibility($form['person']['fav_gummi'], in_array($form['page']['#value'], array(2)), $next_page);
270 jvandyk 1.1
271     // Color and number, page 3
272 drumm 1.2 multipage_form_set_element_visibility($form['fav_color'], in_array($form['page']['#value'], array(3)));
273     multipage_form_set_element_visibility($form['fav_number'], in_array($form['page']['#value'], array(3)));
274 jvandyk 1.1
275     // Movie and tv show, page 4
276 drumm 1.2 multipage_form_set_element_visibility($form['fav_movie'], in_array($form['page']['#value'], array(4)));
277     // This bit of trickery is because radios is a bit of a special case --
278     // it's an 'expanding' form element, which means that the multiple buttons
279     // get built by form_builder. Because the building for display actually
280     // happens when the form is still set to stage 3, we have to build it as a
281     // radios type in stage 3, or nothing will display on stage 4!
282     // form_hide_elements is a little helper function that recurses through and
283     // hides all of the buttons we built if we don't actually happen to be
284     // displaying stage 4. whew!
285     if ($next_page) {
286     multipage_form_set_element_visibility($form['fav_tv'], in_array($form['page']['#value'], array(4)));
287     }
288 jvandyk 1.1
289     // Buttons -- like radios, they need to be properly built in the previous stage, so here we also do the switches at
290     // the last chance we have. Notice that the type gets set to 'value' and not 'hidden', b/c hidden will screw w/
291     // $_POST['op']
292     if ($next_page) {
293 drumm 1.2 multipage_form_set_element_visibility($form['back'], in_array($form['page']['#value'], array(2, 3, 4)));
294     multipage_form_set_element_visibility($form['preview'], in_array($form['page']['#value'], array(4)));
295     multipage_form_set_element_visibility($form['submit'], in_array($form['page']['#value'], array(4)));
296 jvandyk 1.1 $submit_text = array(NULL, t('Next (person)'), t('Next (color/number)'), t('Next (tv/movie)'), t('Submit'));
297 drumm 1.2 $form['submit']['#value'] = $submit_text[$form['page']['#value']];
298 jvandyk 1.1 }
299     }
300     }
301    
302     // Handles form submission. We're just throwing our data into the variable
303     // table to keep things simple
304 thehunmonkgroup 1.6 function multipage_form_example_custom_submit() {
305 jvandyk 1.1 global $form_values;
306     foreach ($form_values as $key => $value) {
307     if (in_array($key, array('fav_person', 'fav_person_desc', 'fav_gummi', 'fav_color', 'fav_number', 'fav_movie', 'fav_tv',))) {
308     $array[$key] = $value;
309     }
310     }
311 thehunmonkgroup 1.6
312     // A little hack so we can save new node info properly to the variable table
313     if (isset($form_values['nid'])) {
314     $nid = $form_values['nid'];
315     }
316     else {
317     $nid = db_result(db_query("SELECT id FROM {sequences} WHERE name = 'node_nid'"));
318     }
319    
320     variable_set('multipage_form_example_'. $nid, $array);
321 jvandyk 1.1 }
322    
323     /**
324     * Implementation of hook_load().
325     *
326     * Now that we've defined how to manage the node data in the database, We
327     * need to tell Drupal how to get the node back out. This hook is called
328     * every time a node is loaded, and allows us to do some loading of our own.
329     */
330     function multipage_form_example_load($node) {
331     $additions = variable_get('multipage_form_example_'. $node->nid, NULL);
332     $additions = (object) $additions;
333     return $additions;
334     }
335    
336     /**
337     * Implementation of hook_delete().
338     *
339     * Clean up our data in variable table.
340     */
341     function multipage_form_example_delete($node) {
342     // Notice that we're matching all revision, by using the node's nid.
343     variable_del('multipage_form_example_'. $node->nid);
344     }
345    
346     /**
347     * Implementation of hook_view().
348     *
349     * This is a typical implementation that simply runs the node text through
350     * the output filters.
351     */
352     function multipage_form_example_view(&$node, $teaser = FALSE, $page = FALSE) {
353     $node = node_prepare($node, $teaser);
354     $favorites = theme('multipage_form_example', $node);
355     $node->body .= $favorites;
356     $node->teaser .= $favorites;
357     }
358    
359     /**
360     * A custom theme function.
361     *
362     * By using this function to format our node-specific information, themes
363     * can override this presentation if they wish. We also wrap the default
364     * presentation in a CSS class that is prefixed by the module name. This
365     * way, style sheets can modify the output without requiring theme code.
366     */
367     function theme_multipage_form_example($node) {
368     $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'))));
369     $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)));
370     $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)));
371    
372     $output = '<div class="multipage_form_example">';
373     $output .= $person_display . $color_number_display . $tv_movie_display;
374     $output .= '</div>';
375 drumm 1.2
376 jvandyk 1.1 return $output;
377     }
378    
379     /**
380 drumm 1.5 * Set an element's visibility. Elements are gnerally changed to hidden
381     * elements. Visibility may be set and reset any number of times.
382     *
383     * @param $element
384     * The form element array to modify.
385     * @param $visible
386     * The desired visibity of the form element.
387 thehunmonkgroup 1.7 * @param $next_page
388     * Boolean value, TRUE if the next page is about to be rendered, FALSE otherwise.
389 jvandyk 1.1 */
390 thehunmonkgroup 1.7 function multipage_form_set_element_visibility(&$element, $visible, $next_page = TRUE) {
391 drumm 1.2 multipage_form_restore_attributes($element);
392     if (!$visible) {
393     switch ($element['#type']) {
394     case 'textfield':
395     case 'textarea':
396     case 'radios':
397     case 'select':
398     multipage_form_set_attribute($element, '#type', 'hidden');
399     multipage_form_set_attribute($element, '#required', FALSE);
400     break;
401    
402     case 'radio':
403     case 'checkbox':
404 thehunmonkgroup 1.7
405     // We can't change these to hidden until right before the next page is rendered, otherwise
406     // the value is lost sometimes.
407     if ($next_page) {
408     multipage_form_set_attribute($element, '#type', 'hidden');
409     }
410 drumm 1.2 break;
411    
412     case 'fieldset':
413     multipage_form_set_attribute($element, '#type', NULL);
414     break;
415    
416     case 'button':
417     multipage_form_set_attribute($element, '#type', 'value');
418     break;
419    
420     case 'submit':
421     multipage_form_set_attribute($element, '#type', 'button');
422     break;
423     }
424     }
425    
426 jvandyk 1.1 foreach (element_children($element) as $key) {
427 drumm 1.2 multipage_form_set_element_visibility($element[$key], $visible);
428     }
429     }
430    
431     /**
432 drumm 1.4 * Set an attribute on an element array with storing the previous value which
433     * may be reverted to using multipage_form_restore_attributes().
434 drumm 1.2 *
435     * @param $element
436 drumm 1.4 * The form element array to modify.
437     * @param $key
438     * A key of the form element array.
439 drumm 1.2 * @param $new_value
440 drumm 1.4 * The new value for the attribute.
441 drumm 1.2 */
442     function multipage_form_set_attribute(&$element, $key, $new_value) {
443     $element['#multipage_form_original_'. $key] = $element[$key];
444     $element[$key] = $new_value;
445     }
446    
447 drumm 1.4 /**
448     * Restore any form attributes which have been set using
449     * multipage_form_set_attribute().
450     *
451     * @param $element
452     * The form element array to restore.
453     */
454 drumm 1.2 function multipage_form_restore_attributes(&$element) {
455     foreach (array_filter(array_keys($element), create_function('$key', 'return (strpos($key, "#multipage_form_original_") === 0);')) as $key) {
456     $element[str_replace('#multipage_form_original_', '', $key)] = $element[$key];
457 jvandyk 1.1 }
458     }
459    
460     /**
461     * Playing around here with a new form element to enable storing hidden values in an array fashion.
462     * Seems to work fine. Check out $form['test_hidden_array'] above for how to structure the form
463     * element
464     */
465     function multipage_form_example_elements() {
466     $type['hidden_array'] = array('#input' => TRUE, '#process' => array('expand_hidden_array' => array()), '#tree' => TRUE);
467     return $type;
468     }
469    
470     function expand_hidden_array($element) {
471     $values = is_array($element['#values']) ? $element['#values'] : array();
472     $element['#tree'] = TRUE;
473     foreach ($values as $key => $value) {
474     $element[$key] = array('#type' => 'hidden', '#processed' => TRUE, '#value' => $value);
475     }
476     return $element;
477     }
478    
479 drumm 1.2 function theme_hidden_array($element) {
480 jvandyk 1.1 return $element['#children'];
481     }

  ViewVC Help
Powered by ViewVC 1.1.2