[eluser]ururk[/eluser]
There is a way to extend this to also serve as a one-stop database table editor, using a single view for the form. I've made tweaks to the standard 'form' generated like so:
In my model:
Code:
function SaveForm($form_data)
function UpdateForm($form_data, $id)
function DeleteForm($id)
function GetForm($id)
function GetForms()
In my View:
Code:
echo form_open('myform/add', $attributes); ?>
Example form element ($var instead of set_value):
Code:
<p>
<label for="role_name">Role Name <span class="required">*</span></label>
<?php echo form_error('role_name'); ?>
<br /><input id="role_name" type="text" name="role_name" value="<?php echo $role_name; ?>" />
</p>
<input type="hidden" name="id" value="<php echo $id; ?>" />
<input type="hidden" name="operation" value="<?php echo $operation ?>" />
In my controller:
Code:
function index() - generalized for loop using a table generated via GetForms
function add() - handles UPDATES and INSERTS
$this->_validate(); // moved to separate function just to tidy the code up a bit
$validate_fields = $this->form_validation->run();
$form_data = array(
'myform_name' => set_value('myform_name'),
'myform_level' => set_value('myform_level')
);
if ($validate_fields == FALSE) // validation hasn't been passed
{
$form_data['role_id'] = set_value('role_id');
$form_data['operation'] = set_value('operation');
$data['content'] = $this->load->view('admin/roles_view', $form_data, true);
}
else // passed validation proceed to post success logic
{
if (set_value('operation') == 'edit') {
// run update model to write data to db
if ($this->myform_model->UpdateForm($form_data, set_value('role_id')) == TRUE) {
redirect('myform');
} else {
$data['content'] = 'An error occurred updating the data.';
}
} else {
// run insert model to write data to db
if ($this-> myform_model->SaveForm($form_data) == TRUE) {
redirect('myform');
} else {
$data['content'] = 'An error occurred adding the data.';
}
}
}
function edit($row_id) {
if ($this->myform_model->GetForm($row_id) == TRUE) {
$data = $this->myform_model->GetForm($row_id);
$data['operation'] = 'edit';
$data['content'] = $this->load->view('admin/roles_view', $data, true);
} else {
$data['content'] = 'Could not find the requested record.';
}
$this->load->view('myform', $data);
}
function delete($row_id) - deletes a single record
I could post my full code, but it is pretty basic stuff - the code above is chopped up to make it a bit more compact, and I got a little lazy in changing the names I used
. The trouble occurs when you go to use the form helpers that set values - some require POST values, such that I had to rewrite the cb, rb, and select setters. There may be unintended consequences to this, but they seem to work.