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

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

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

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

Legend:
Removed from v.1.8.2.1  
changed lines
  Added in v.1.8.2.2

  ViewVC Help
Powered by ViewVC 1.1.2