Handling Drupal forms submission is dead simple. You basically write a three functions: a form generator, a form validator and a form submitter.
The form generator is called everytime the form needs to be built and it can be used to populate fields default values or the values previously entered by the user.
In the form generator you can specify the functions that should be called to validate the form and to submit it (to actually do something with the form values, like adding a new row to a table for instance):
$form[‘#validate’][] = ‘car_edit_validate’;
$form[‘#submit’][] = ‘car_edit_submit’;
Where car_edit_validate is the name of the function that will be called to do the validation and car_edit_submit is the function that will be called after the form validates.
Every time you submit the form the validate function is called first and if the validation does not encounter any errors the submit function is called.
The problem I had is that I wanted to return an error and keep the form values if an error occurred in my submit function. By default, after the submit function is called an empty form will be rendered and user entered values will be lost even if you add an error to the form with form_set_error. The error is displayed but this does not prevent the form values from being lost. If you want to keep the form values you must also add this line:
$form_state[‘redirect’] = FALSE;
Example:
function car_edit_submit($form, &$form_state) { global $user; $car = (object)$form_state['values']; $car->uid = $user->uid; if(car_save($car)) { drupal_set_message(t('car successfully saved'))); drupal_goto('car/'.$car->cid); } else { form_set_error('form', t('The car could not be saved, please try again')); $form_state['redirect'] = FALSE; //To prevent Drupal from cleaning the form } }