简体   繁体   中英

Phalcon\Mvc\Model\Validator\Uniqueness in “standalone” mode

I'd like to use Phalcon\\Mvc\\Model\\Validator when validating my Model before save. The problem, however, is that I'd like to check for field's uniqueness in some OTHER model, and not the one I am currently validating.

For example, there's a form that allows you to send email invitations to new users. I would like to ensure that my Invitation model fails validation if someone tries to reuse an email address of existing User model (you should not be allowed to invite an existing user).

How can do this in my Invitation Model:

public function validation()
{
    $this->validate(new Uniqueness(array(
        'field' => 'email'
    )));
}

How can I tell Uniqueness that it should check 'email' field in User model, as opposed to Invitation model?

Thanks!

One way I can think of achieving this would be to use custom validations,

Check following code for reference

class UniqueValidatorUser extends Validator implements ValidatorInterface
{
    public function validate($record)
    {
        $field = $this->getOption('field');
        $value = $record->readAttribute($field);
        $users = Users::find(array(
                                "conditions" => array("name" => $value)
                            ));

        if(count($users) == 1)
        {
            $this->appendMessage("The Name is already in use", $field, "Unique");
            return false;
        }
        return true;
    }
}

Within your invitation model you will have to put following code,

public function validation()
        {

            $this->validate(new UniqueValidatorUser(array(
                                    "field"  => "email",
                                )));
         }

Refer http://docs.phalconphp.com/en/latest/reference/validation.html for more!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM