[eluser]boldyellow[/eluser]
I cobbled together a shared add/edit functionality in my controller and view.
It works fine for me, but maybe can be improved (since I'm still learning CI).
The key parts are:
View
Start by checking if an id is passed to the view (since we need an id in order to edit). If so, we're in edit mode, otherwise we're in add mode.
Code:
<? $ae = (isset($row->id)) ? 'edit' : 'add'; ?>
After form open, add a hidden field for the id, if we're in edit mode
Code:
<?=form_open('instructor_form'); ?>
<? if($ae == 'edit'): ?>
<?=form_hidden('id', $row->id); ?>
<? endif; ?>
All form fields are theoretically identical for add and edit.
Code:
<fieldset>
<label>Instructor Name</label>
<?=form_input('instructor_name', set_value('instructor_name')); ?>
</fieldset>
...
Then at the form end, the submit button is named according to add or edit mode
Code:
<button type="submit" name="<? echo ($ae == 'edit' ? 'editsubmit' : 'addsubmit'); ?>">...
Controller
Set variable of db table name and check if posted submit button was to edit or to add. If no submit posted, then load the form filled in for updating or empty for inserting.
Code:
function instructor_add_edit()
{
// db table name we'll need to insert or update
$table = 'course_instructors';
// check if submit posted was for edit or for add
if ($this->input->post('editsubmit') OR $this->input->post('addsubmit'))
{
// load the validation (same for edit and add)
$this->_instructor_validation();
// deal with validation errors
// when validation passes will need posted id to update, but not to insert
if ($this->input->post('editsubmit'))
{
$id = $this->input->post('id'); //
}
$data = array(
'instructor_name' => $this->input->post('instructor_name'),
'instructor_bio' => $this->input->post('instructor_bio')
);
// if edit mode, pass data to model's edit function
if ($this->input->post('editsubmit'))
{
$this->courses_model->edit_item($data, $id, $table);
}
// if add mode, pass data to model's add function
elseif ($this->input->post('addsubmit'))
{
$this->courses_model->add_item($data, $table);
}
else
{
// put in error handling if update or insert fails
}
}
// if form not submitted, load the edit form or the add form
// need an id to edit, so if an id is in the url, it's edit mode -- load filled in fields
elseif(is_numeric($this->uri->segment(4)))
{
$id = $this->uri->segment(4);
$data['row'] = $this->courses_model->get_item($id, $table);
$this->load->view('form_view', $data);
}
else // otherwise it's add mode so display empty fields
{
$this->load->view('form_view', $data);
}
}