我是codeigniter的新手,并尝试使用相同的方法添加和编辑类别。
这是我的添加方法:
public function add($category_id = FALSE)
{
$this->load->helper('form');
$this->load->library('form_validation');
if($category_id === FALSE)
{
$this->data['mode'] = 'insert';
$this->data['hidden_fields'] = array('mode' => $this->data['mode']);
}
else
{
$this->data['mode'] = 'update';
$this->data['category_details'] = $this->category_model->get_category_details($category_id);
$this->data['category_id'] = isset($this->data['category_details'][0]['category_id']) ? $this->data['category_details'][0]['category_id'] : '';
$this->data['hidden_fields'] = array('category_id' => $this->data['category_id'], 'mode' => $this->data['mode']);
}
// Fill the form data for edit.
$this->data['name'] = isset($this->data['category_details'][0]['name']) ? $this->data['category_details'][0]['name'] : set_value('name');
$this->data['description'] = isset($this->data['exam_category_details'][0]['description']) ? $this->data['category_details'][0]['description'] : set_value('description');
$this->data['status_y'] = (isset($this->data['category_details'][0]['status']) && $this->data['category_details'][0]['status'] === 'Y') ? 'checked="checked"' : set_radio('status', 'Y', TRUE);
$this->data['status_n'] = (isset($this->data['category_details'][0]['status']) && $this->data['category_details'][0]['status'] === 'N') ? 'checked="checked"' : set_radio('status', 'Y');
// set the validation rules
$validation_rules = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|min_length[5]|max_length[20]|xss_clean'
),
array(
'field' => 'description',
'label' => 'Description',
'rules' => 'trim|min_length[5]|max_length[256]|xss_clean'
)
);
$this->form_validation->set_rules($validation_rules);
// check if validation fails or upload logo fails
if ($this->form_validation->run() === FALSE)
{
$this->data['validation_errors'] = validation_errors();
$this->load->view($this->config->item('templates_path').'header', $this->data);
$this->load->view($this->config->item('templates_path').'sidebar_content', $this->data);
$this->load->view($this->config->item('templates_path').'navigation', $this->data);
$this->load->view('add_category', $this->data);
$this->load->view($this->config->item('templates_path').'footer');
}
else
{
$id = $this->category_model->update_category();
if($id !== FALSE && is_numeric($id))
{
$this->session->set_flashdata('msg_success', 'Operation Successful');
redirect('/exams/exam_category/');
}
else
{
// update exam category failed some where
log_message('error', 'Update exam category failed', TRUE);
show_error("Unable to Update exam category : ".$id);
}
}
}
上述方法适用于添加和编辑类别,但如果表单验证失败,我在添加和编辑的情况下都会丢失表单默认值。我使用了codeignitor的set_value方法。如果验证失败,我如何保留表单输入值?