We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Uniqueness validator during update/edit

Hello

I have AddForm (it is to add new admin model) with such field:


        $username = new Text('username');
        $username->setLabel('Username');
        $username->setFilters(['striptags', 'string']);
        $username->addValidator(
                new Uniqueness([
                    'table' => 'admin',
                    'column' => 'username',
                    'message' => 'Is is rserved yet.',
                    'except'
                ])
         );

I use Uniqueness validator to check if there is such username in database. Next I have EditForm (it is to edit existing admin model) and there is also this same username field. And i got problem, because this validator activates during update admin model. I need solution to check Uniqueness of username except of updating model.

I know I can do this in controller with one sql query, but I prefer to do this in form class. Is it possible?

Phalcon 2.1 beta

edited Oct '15

maybe this will do the trick - u can skip the field on update. i also just started 2 days ago with phalcon so the code is not tested. but let me know if that worked or how you solved it

public function initialize(){//TODO create a if that is true when it is an update
$this->skipAttributesOnUpdate(array('firstname', 'lastname'));
}

You talk about model validation, I talk about form validation. Even If I skip username field, there could be user who wants to update this field.



20.4k
Accepted
answer
edited Oct '15

You could do it simply by using if by getting the current user name and comparing it to the submitted user name. You only need to do the validation if it is being changed.

if($NewUserName != $currentUserName){
    // then we do the validation
    $username->addValidator(
        new Uniqueness([
            'table' => 'admin',
            'column' => 'username',
            'message' => 'Is is rserved yet.'
        ])
     );
}