Error Handling

Good Day Yii Masters,

Im working on my register page and I want to know, Is their a way on how I can show an error message when i Click the submit button if the input in a text field has a duplicate record on my database?

my model function

public function checkusername(){

if($this->username == $email){

//Then show Error Message and failed to register a record

}

}

Assuming that you’re using either a CActiveForm or the CHtml::active*() methods to build your form, you can add a unique validation rule in your model.




    array('username', 'unique'),



This will automatically ensure that the field is unique in the database table.

If you’re using a CFormModel rather than CActiveRecord, you’ll need some additional configuration in the rule:




    array('username', 'unique', 'className'=>'YourUserARClass', 'attributeName'=>'username'),



Im using CFormModel

when u say className, is this the name of your model class??

Yes, it’s the name of the active record class that represents the table containing the unique field.