Checking uniqueness of other model in a form

Hi,

following problem: Users can register on my page. While registering, an account for this user is created (user is account owner). But Account is another model since this user can now invite other users to this model.

How can I check in the user registration form (where a user adds the desired name for his account) if the account name doesnt’t exist with the same ajax validator?

Thx for any help.

it is not clear what you are trying to achieve! Are you saying that you are saving the model User but while saving it you would like to check the uniqueness of an attribute from model Account before saving the User model? Can you please give an example of what you are trying to achieve.

Hi,

yeah it is pretty much that.

A User that registers directly on my site needs to provide the following data: Username, email, accountname, password. Username, email and password belong to the model User whereas accountname belongs to the model Account.

Then the User Model and the account model is created and the AccountId is saved in User as reference to the account. But I didn’t manage to check whether the accountname already exists or not.

In that case I guess one of the options would be before saving your User model to do the following:




$acc = Account::model()->exists('accountField=:name', array(':name'=>$_POST['accountField']));

if($acc)

   $model->addError('accountField', 'This account already exists...');




In the above scenario if the account already exists it should throw up an error message and the form won’t be saved. If this is not what you are trying to achieve then please provide an example

I would write a custom validation method/class instead of putting it into beforeSave().

…or at least in beforeValidation, not in beforeSave :) but custom validation rule is the best solution.

The beforeValidate - method made some problems when one of the models couldn’t be validated, but it brought me at the end to this: http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models/

Thanks for the help!