[eluser]WanWizard[/eluser]
I have a sort of standard flow for a method that displays and processes a form.
In pseudo code:
Code:
// initialize the view data array
$data = array( 'messages' => "" );
// returns an array, filled if record is found, or with default values (and id=0) if not.
if ( $record = $this->model->load_record_from_url() )
{
// record not found, URI info bogus, etc. handle it here
}
// check if the form was posted
if ( form_posted('my_form_page') )
{
// define all form validation rules (or load them from a config file)
// run the form validation
$validated = $this->form_validation->run();
// update the record array from the post
// ( requires form field names to be identical to column names )
// or make a manual mapping using the second parameter
$record = update_from_post($record, array('extra_field' => 'db_column') );
}
else
{
// no form to validate
$validated = FALSE;
}
// was the form posted and did it validate?
if ( $validated )
{
if ( $record['id'] )
{
// update the record here
// inform the user
$data['messages'] = "Record updated.";
}
else
{
// insert a new record here
// update the record with the new record id
$record['id'] = $this->db->insert_id();
// inform the user
$data['messages'] = "Record inserted.";
}
}
else
{
// fetch the validation errors
$data['messages'] = validation_errors();
}
// add the record to the view data array
$data['record'] = $record;
// load the form
$this->load->view('my_form_page');
This does everything in one go:
- load the record to edit, or initializes one if a new record is being added
- validates the form
- updates the record data with the posted form data
- updates or inserts the record, based on the presence of the record's ID
- load the form, and display messages (if any)
I use form_posted() and update_from_post() (they are actually methods in my form_validation extension) to check if the form I'm interested in is posted (via a hidden field in the form), and to copy data from form fields back to the record after validation.