/[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.3 - (hide annotations) (download) (as text)
Thu Mar 30 01:54:00 2006 UTC (3 years, 7 months ago) by drumm
Branch: MAIN
Changes since 1.2: +24 -10 lines
File MIME type: text/x-php
Putting the themeing in a themeable function.
1 jvandyk 1.1 <?php
2    
3 drumm 1.2 // $Id: multipage_form_example.module,v 1.1 2006/03/22 19:16:41 jvandyk 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 drumm 1.3 if ($_POST['op'] == t('Back') || $_POST['op'] == t('Preview')) {
207     $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     $form['#validate'] = array_merge($form['#validate'], array('multipage_form_example_validate' => array()));
219     $form['#submit'] = array_merge($form['#submit'], array('multipage_form_example_submit' => array()));
220     }
221    
222     return $form;
223     }
224    
225     /**
226     * Validate our form.
227     */
228     function multipage_form_example_validate() {
229     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     if ($next_page && isset($_POST['edit']['page']) && ($_POST['op'] != t('Back'))) {
250     $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     multipage_form_set_element_visibility($form['person']['fav_gummi'], in_array($form['page']['#value'], array(2)));
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     function multipage_form_example_submit() {
305     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     variable_set('multipage_form_example_'. $form_values['nid'], $array);
312     }
313    
314     /**
315     * Implementation of hook_load().
316     *
317     * Now that we've defined how to manage the node data in the database, We
318     * need to tell Drupal how to get the node back out. This hook is called
319     * every time a node is loaded, and allows us to do some loading of our own.
320     */
321     function multipage_form_example_load($node) {
322     $additions = variable_get('multipage_form_example_'. $node->nid, NULL);
323     $additions = (object) $additions;
324     return $additions;
325     }
326    
327     /**
328     * Implementation of hook_delete().
329     *
330     * Clean up our data in variable table.
331     */
332     function multipage_form_example_delete($node) {
333     // Notice that we're matching all revision, by using the node's nid.
334     variable_del('multipage_form_example_'. $node->nid);
335     }
336    
337     /**
338     * Implementation of hook_view().
339     *
340     * This is a typical implementation that simply runs the node text through
341     * the output filters.
342     */
343     function multipage_form_example_view(&$node, $teaser = FALSE, $page = FALSE) {
344     $node = node_prepare($node, $teaser);
345     $favorites = theme('multipage_form_example', $node);
346     $node->body .= $favorites;
347     $node->teaser .= $favorites;
348     }
349    
350     /**
351     * A custom theme function.
352     *
353     * By using this function to format our node-specific information, themes
354     * can override this presentation if they wish. We also wrap the default
355     * presentation in a CSS class that is prefixed by the module name. This
356     * way, style sheets can modify the output without requiring theme code.
357     */
358     function theme_multipage_form_example($node) {
359     $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'))));
360     $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)));
361     $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)));
362    
363     $output = '<div class="multipage_form_example">';
364     $output .= $person_display . $color_number_display . $tv_movie_display;
365     $output .= '</div>';
366 drumm 1.2
367 jvandyk 1.1 return $output;
368     }
369    
370     /**
371     * A little helper function to hide the child elements of 'radios'.
372     */
373 drumm 1.2 function multipage_form_set_element_visibility(&$element, $visible) {
374     multipage_form_restore_attributes($element);
375     if (!$visible) {
376     switch ($element['#type']) {
377     case 'textfield':
378     case 'textarea':
379     case 'radios':
380     case 'select':
381     multipage_form_set_attribute($element, '#type', 'hidden');
382     multipage_form_set_attribute($element, '#required', FALSE);
383     break;
384    
385     case 'radio':
386     case 'checkbox':
387     multipage_form_set_attribute($element, '#type', 'hidden');
388     break;
389    
390     case 'fieldset':
391     multipage_form_set_attribute($element, '#type', NULL);
392     break;
393    
394     case 'button':
395     multipage_form_set_attribute($element, '#type', 'value');
396     break;
397    
398     case 'submit':
399     multipage_form_set_attribute($element, '#type', 'button');
400     break;
401     }
402     }
403    
404 jvandyk 1.1 foreach (element_children($element) as $key) {
405 drumm 1.2 multipage_form_set_element_visibility($element[$key], $visible);
406     }
407     }
408    
409     /**
410     * Set an attribute on an element array with storing the previous value or
411     * restore to a previous value.
412     *
413     * @param $element
414     * The form element to modify.
415     * @param $attribute
416     * An attribute of the form element.
417     * @param $new_value
418     * The new value for the attribute to be set with; NULL to restore a previous
419     * value.
420     */
421     function multipage_form_set_attribute(&$element, $key, $new_value) {
422     $element['#multipage_form_original_'. $key] = $element[$key];
423     $element[$key] = $new_value;
424     }
425    
426     function multipage_form_restore_attributes(&$element) {
427     foreach (array_filter(array_keys($element), create_function('$key', 'return (strpos($key, "#multipage_form_original_") === 0);')) as $key) {
428     $element[str_replace('#multipage_form_original_', '', $key)] = $element[$key];
429 jvandyk 1.1 }
430     }
431    
432     /**
433     * Playing around here with a new form element to enable storing hidden values in an array fashion.
434     * Seems to work fine. Check out $form['test_hidden_array'] above for how to structure the form
435     * element
436     */
437     function multipage_form_example_elements() {
438     $type['hidden_array'] = array('#input' => TRUE, '#process' => array('expand_hidden_array' => array()), '#tree' => TRUE);
439     return $type;
440     }
441    
442     function expand_hidden_array($element) {
443     $values = is_array($element['#values']) ? $element['#values'] : array();
444     $element['#tree'] = TRUE;
445     foreach ($values as $key => $value) {
446     $element[$key] = array('#type' => 'hidden', '#processed' => TRUE, '#value' => $value);
447     }
448     return $element;
449     }
450    
451 drumm 1.2 function theme_hidden_array($element) {
452 jvandyk 1.1 return $element['#children'];
453     }

  ViewVC Help
Powered by ViewVC 1.1.2