Summer Reading Registration... What's new!
by jaimonr
It's that time of the year when all flock to the library for Summer Reading sign-up. Last year we had over 8000 participants including youth, teens and adults.
This year we bring the sign-up form to you to sign-up from home. The Summer Reading form was build using drupal's new form API. If you want to get a jump start I would suggest the "quickstart guide", which is awesome with little code snippets and examples.
Here is how the form works. The name of the from is the $form_id and to build the form drupal looks for a function with the same name. In this case the $form id is sumreading_form. Here is an example:
function sumreading_form() { $form['last_name'] = array( '#type' => 'textfield', '#title' => t('Last name'), ); $form['first_name'] = array( '#type' => 'textfield', '#title' => t('First name'), ); $form['submit'] = array ( '#type' => 'submit', '#value' => t('Save Registration'), ); return drupal_get_form('sumreading_form', $form); }
There are two fields in the form that is required. The phone number and the game type. Drupal has a wonderful way of validating its forms. So we need two more functions to validate and submit. Don't forget the $form_id for the validating function...
function sumreading_form_validate($form_id, $form_values) { if ($form_values['phone'] == '') { form_set_error('', t('You must enter a phone number.')); } if ($form_values['type'] == '') { form_set_error('', t('Please specify a type of Youth Listeners, Youth Readers, Teen OR Adult')); } }
form_set_error(,) will display the form back with the user input that was just typed in and displays the specified error. So, if you forget to put a phone number on your form an error would show up with the words "You must enter a phone number".
Now we finally submit the form. The form will only submit if there are no errors returned.
function sumreading_form_submit($form_id, $form_values) { db_query("INSERT INTO {table} VALUES (last_name, first_name)", $form_values['last_name'], $form_values['first_name']); drupal_set_message(t('Your registration is successfully saved')); drupal_goto('services/read'); }
If there are no return values, the form refreshes and gives you a fresh form to fill in another participant.
Blog Post