Friday, April 6, 2012

Unique Validation

Grr.  I've spent two days trying to figure out how to do unique validation.

I have a form that a user fills out.  If it meets all of the validation rules then its submitted to the DB.  If it does not - if one of the fields is too long or short, not a proper email address, etc - the form is kicked back.  That all works.

I'm trying to get it to check to make sure that the email address is unique.  You cannot register an email address that is already in the system.  Now, I know how to do this old school, you query the db and look for the submitted email address, and if you get a return, you reject it.  However, I don't want to do it that way.

There are apparently functions in CodeIgniter/Doctrine for this very thing.

CodeIgniter has a form_validation function that works great for making sure that the passwords match, that length or complexity requirements are met... and has an is_unique feature, but I cannot seem to get it to work - that could be because I'm also using Doctrine, but I'm not certain.

The CodeIgniter userguide also suggests using a callback, but again - I just cannot seem to get it to work.  In this case, the code example seems incomplete.  Either it is, or I'm new enough that I'm not grasping some fundamental concept.

I've appealed to the internet for help, posting on stackoverflow and a couple PHP forums.  We'll see what I can find out.

Edit:

I discovered that if I add $autoload['libraries'] = array('database'); to autoload.php, it makes the form_validation work.

However, it seems to break the Doctrine part of this thing.
Fatal error: Class 'Entities\User' not found in /home/xxxjermxxx/dixieandtheninjas.net/hellounderscoreworld/applicationFolder/controllers/signup_form.php on line 30
After more trial and error, I find that I cannot apparently have both of those autoloaded libraries.  Hm.

Edit:  Solved.

This may not be the best or most elegant solution, but it works.
$this->form_validation->set_rules('email', 'E-mail', 'required|valid_email|callback_email_check');
 
public function email_check($str)
{
$user = $this->doctrine->em->getRepository('Entities\User')->findOneBy(array('email' => $str));
               if (isset($user)) {
                        $this->form_validation->set_message('email_check', 'This email address is already in use');
                        return FALSE;
                } else
{
return TRUE;
}
}
(Note to self,  code looks hideous on here.)

No comments:

Post a Comment