custom validate function

Hi,

In my app users can add many customers.

The name of customers must be unique But only for that particular user ,

I could not use [‘name’ , ‘unique’] in customer model ,then i prefer to have my own specific validate function.


['name', 'validatemyname']

    public function validatemyname($attribute, $params)

    {

        $identity = Yii::$app->user->identity;

        $login_id = $identity->id;

        $customer = (new \yii\db\Query())

            ->select(['id','name'])

            ->from('customer')

            ->where(['user_id'=>$login_id])

            ->all();

            $customer_temp=ArrayHelper::map($customer,'id','name');

            if (in_array($this->$attribute, $customer_temp)) {

                $this->addError($attribute, 'BEFORE USED');

            }

    }

As you know every things right when users add customer, but in update customer form this error will be always visible.

what’s the best solution?

Hi,

You can make use of the exists validator.

http://www.yiiframework.com/doc-2.0/yii-validators-existvalidator.html