How to enable query builder for is_unique form validation in CodeIgniter? How to enable query builder for is_unique form validation in CodeIgniter? codeigniter codeigniter

How to enable query builder for is_unique form validation in CodeIgniter?


I have just gone through the link you posted, There are 2 ways to use such validation. If you have set in your configuration files.

With that you can use the code as is is_unique[TABLE_NAME.FIELD] and it will work automatically. But at times this logic might not necessarily meet your need and you will need something more complex.

For example lets say you have a members registration that requires you to check if the email already exists, you can run is_unique and it will work perfectly. Now let's say you want to edit the same member, running is_unique on an edit function will render the user unable to save the data if no data is edited. WHY? because is_unique would determine that the email is already registered although it belongs to the current user that is being edited.

How do we fix this? We run our own callback in which we specify the logic.

You do it by specifying a method within the controller (or a model -- slightly different) but you prefix the method name with callback_ so that it is detected.

$this->form_validation->set_rules('username', 'Username', 'callback_username_check');

This will then look for a method in your controller called 'username_check'

public function username_check($str){        if ($str == 'test')        {                $this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');                return FALSE;        }        else        {                return TRUE;        }}

Of course you can use a query within the callback to check against the db rather than check for just a string as it shows in the example.

more information can be found on Ci3 documentation.LINK

Use CTRL + F and search for callback or is_unique


You might have missed this?

$this->load->library('database');

works instantly after adding database lib.