如何防止CodeIgniter表单验证的代码重复?

时间:2012-03-26 01:50:21

标签: codeigniter validation dry

这是此问题的Staff控制器中的函数示例

function newStaff()
{
    $data = array();

    $data['departmentList'] = $this->department_model->list_department();
    $data['branchList'] = $this->branch_model->list_branch();
    $data['companyList'] = $this->company_model->list_company();

    $this->load->view('staff/newstaff', $data);

}

function add_newStaff()
{
    //when user submit the form, it will call this function
    //if form validation false

    if ($this->validation->run() == FALSE)
    {
        $data = array();

        $data['departmentList'] = $this->department_model->list_department();
        $data['branchList'] = $this->branch_model->list_branch();
        $data['companyList'] = $this->company_model->list_company();

        $this->load->view('staff/newstaff', $data);
    }
    else
    {
        //submit data into DB
    }

}

从函数add_newStaff(),如果表单验证返回false,我需要从数据库加载回所有数据。这可能很麻烦,因为我需要保留两份代码。我可以用什么提示来防止这种情况?

感谢。

2 个答案:

答案 0 :(得分:1)

阻止您执行以下操作

  function newStaff()
    {
        $data = $this->_getData();

        $this->load->view('staff/newstaff', $data);

    }

    function add_newStaff()
    {
        //when user submit the form, it will call this function
        //if form validation false

        if ($this->validation->run() == FALSE)
        {
            $data = $this->_getData();

            $this->load->view('staff/newstaff', $data);
        }
        else
        {
            //submit data into DB
        }

    }

    private function _getData()
    {
        $data = array();

        $data['departmentList'] = $this->department_model->list_department();
        $data['branchList'] = $this->branch_model->list_branch();
        $data['companyList'] = $this->company_model->list_company();

        return $data;
    }

答案 1 :(得分:1)

或者,您可以更改表单提交的操作,以便它指向您用于初始表单请求的相同服务,如下所示。如果您想保留表单中的任何提交值,这也意味着您可以在页面加载之间保留POST值。

function newStaff()
{
    // validation rules

    if ($this->validation->run() == TRUE)
    {
        //submit data into DB
    }
    else
    {
         $data = array();
         $data['departmentList'] = $this->department_model->list_department();
         $data['branchList'] = $this->branch_model->list_branch();
         $data['companyList'] = $this->company_model->list_company();

         $this->load->view('staff/newstaff', $data);
    }
}