Welcome Guest, Not a member yet? Register   Sign In
Form Validation | Custom Callback | With additional posted form variable.
#1

[eluser]porangi[/eluser]
Hi,

I'm in the process of writing a simple pages system for basic websites. Each record has a url field which holds a SEO friendly version of the title. I'd like to check that during create/update actions that the url value is not already in use.

Code:
//Validate the posted variables.
    $this->load->library('form_validation');
    if ($this->form_validation->run($this->model) == FALSE) {

        //Validation failed so return to update view
        $this->detail($this->input->post('id'));

    //Validated OK so -> update record into the database
    } else {

I'm using the config/form_validation.php array system. Part of the pages_model array is shown below with the problematic post->id variable:

Code:
'pages_model' => array(
        
        array('field' => 'id', 'label' => 'lang:id',
            'rules' => 'trim|xss_clean'),

        array('field' => 'title', 'label' => 'lang:title',
            'rules' => 'trim|xss_clean|required|max_length[100]'
             ),

        array('field' => 'url', 'label' => 'lang:url',
            'rules' => 'trim|xss_clean|required|max_length[100]|callback_url_check['.$this->input->post('id').']'
             ),

And have written a callback function for the test which works fine except it disallows the current url field for the record. What I need to do is pass the id field for the current record to the callback function so it can be excluded from the database call.

Code:
function url_check($str,$id=null) {
    $this->load->model($this->model);
    $where = array('url' => $str, 'id !=' => $id);
    $query = $this->pages_model->findby($where);
    if ($query->num_rows()>=1) {
            $this->form_validation->set_message('url_check', $str.' has already been used as an %s.');
            return FALSE;
    } else {
            return TRUE;
    }
}

In a recent project I did this within the controller by just using the
Code:
$this->input->post('id')
variable but this fails when the placed into the form_validation array.

What are my options? I'm looking for a neat solution that will make the package easy to adapt for other objects/projects. By the way - Codeigniter rocks.

Thanks in advance

Chris


Messages In This Thread
Form Validation | Custom Callback | With additional posted form variable. - by El Forum - 05-19-2011, 07:36 AM



Theme © iAndrew 2016 - Forum software by © MyBB