Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation UNIQUE field in Codeigniter with 2 index

In the Codeigniter Framework, I can validate an Unique field in the MYSQL Database using the "Form Validation Class". Exemple:

$this->form_validation->set_rules('form_field', 'form_label', 'is_unique[table.field]');

Work perfectly, but, I need validate a field from a table with 2 index. Exemple:

UNIQUE INDEX `id_aluno` (`id_aluno`, `ano`),

The Codeigniter Framework can do it natively?

like image 656
user875690 Avatar asked Jan 29 '13 03:01

user875690


3 Answers

I don't think that CI has built-in case for combined PK but I would use callback_ like this: but note that you have to send the second PK as extra and the rule should be applied on the first $PK see callbacks for more info about that

$this->form_validation->set_rules('form_field', 'form_label', 'callback_combpk[$pk2]');
    public function combpk($pk1, $pk2)
        {
               $this->db->where('field1', $pk1);
               $this->db->where('field2', $pk2);
               $result = $this->db->get('table');
               if($result->num_rows() > 0)
               {
                  $this->form_validation->set_message('combpk','something'); // set your message
                  return false;
               }
               else{ return true;}

        }
like image 85
mamdouh alramadan Avatar answered Nov 20 '22 00:11

mamdouh alramadan


$this->form_validation->set_rules(
    'form_field', 
    'form_label', 
    'trima|is_unique[table1.field1],trim|required|is_unique[table.field2]');

use

'trima|is_unique[table1.field1],trim|required|is_unique[table.field2]' 

in single code

like image 2
sajid saleem Avatar answered Nov 19 '22 22:11

sajid saleem


Did not find the description of native support for this functionality in CodeIgniter. You can check after INSERT query the database error number. For example:

$last_id = $this->model->set();
if ($last_id === FALSE)
    if ($this->db->_error_number() == 1062)
        $this->data['message_error'] = 'Not unique.';
    else
        $this->data['message_error'] = 'Database error.';

This method has disadvantages, but certainly has an advantage - do not use additional SELECT query.

P.S. If several different composite unique indexes, then of course you can use preg_match(<pattern_with_index_name>, $this->db->_error_message());.

like image 1
Apostle Avatar answered Nov 19 '22 22:11

Apostle