Arun
Arun

Reputation: 31

Unique validation on edit a form, in codeigniter

How can i write the code for unique check for a field on edit, in codeigniter. using codeigniter form validation.

Upvotes: 2

Views: 4500

Answers (3)

Ellix4u
Ellix4u

Reputation: 586

This solution allow you to declear your column name like columnID Create a custom validation class in application\libraries\MY_Form_validation.php

class MY_Form_validation extends CI_Form_validation
{
    public function __construct($rules = array())
    {
        $this->CI =& get_instance();
        parent::__construct($rules);
    }

    public function edit_unique($str, $field)
    {
        sscanf($field, '%[^.].%[^.].%[^.].%[^.]', $table, $field, $columnIdName, $id);
        return isset($this->CI->db)
            ? ($this->CI->db->limit(1)->get_where($table, array($field => $str, $columnIdName .'!=' => $id))->num_rows() === 0)
            : FALSE;
    }
}

Add this to system\language\english\form_validation_lang.php

$lang['form_validation_edit_unique']= 'The supplied value is already taken.';

To use in your controller

$id = $this->uri->segment(3);
'rules' => 'trim|required|max_length[50]|edit_unique[mytable.mycolumn.columnID.'.$id.']'

Upvotes: 0

bbosternak
bbosternak

Reputation: 357

You have to write a callback function for validation. Here is a possible solution:

class MY_Form_validation extends CI_Form_validation
{
    function edit_unique($value, $params)
    {
        $this->set_message('edit_unique', "This %s is already in use!");
        list($table, $field, $current_id) = explode(".", $params);
        $result = $this->CI->db->where($field, $value)->get($table)->row();
        return ($result && $result->id != $current_id) ? FALSE : TRUE;
    }
}

Example:

$this->form_validation->set_rules('username', 'Username', 'required|edit_unique[users.username.4]');

Upvotes: 3

Pupil
Pupil

Reputation: 23958

Using CodeIgniter's form validation rules:

$this->form_validation->set_rules('username', 'Username', 'required|is_unique[users.username]');

Where

username: Name of the field

Username: Label of the field.

required: Required field

is_unique: Check for uniqueness.

users : Database Table Name

username: Database field name.

Reference:

https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

Upvotes: 2

Related Questions