Petra
Petra

Reputation: 575

Codeigniter - edit form (repopulating) with edit_unique

It seems that the edit_unique function, which is desribed here - Validating Uniqueness In CodeIgniter When Updating A Record, kills the set_value function.

All works fine, which something like this...

echo form_input('username', set_value('username',$user->username));

But when using the edit_unique validation, the value is empty after submitting the form. Post-Variables are ok and also the validation has no errors - but the value is not set.

Any idea how I can fix that?

Upvotes: 2

Views: 4898

Answers (2)

Rod911
Rod911

Reputation: 860

Petra's answer works well, if for some reason it doesn't work for you, check if your primary key is 'id', if not you'll need to make some changes.

Change

list($table, $field, $current_id) = explode(".", $params);

if ($query->row() && $query->row()->id != $current_id)

to

list($table, $field, $current_id, $key) = explode(".", $params);

if ($query->row() && $query->row()->$key != $current_id)

Then add the rule like:

$this->form_validation->set_rules(
    'form_field', 
    'Form Label', 
    'required|trim|edit_unique[table.column.' . $edit . '.unique]'
);

Where unique is your unique/primary key and $edit is it's value.

Upvotes: 0

Petra
Petra

Reputation: 575

Ok - found it myself. There was no return value in case of beeing true. Perhaps anyone faces the same problem... with this function, it works:

function edit_unique($value, $params)  {
    $CI =& get_instance();
    $CI->load->database();

    $CI->form_validation->set_message('edit_unique', "Sorry, that %s is already being used.");

    list($table, $field, $current_id) = explode(".", $params);

    $query = $CI->db->select()->from($table)->where($field, $value)->limit(1)->get();

    if ($query->row() && $query->row()->id != $current_id)
    {
        return FALSE;
    } else {
        return TRUE;
    }
}

Upvotes: 8

Related Questions