unique Validator Issue

Hi,

I am trying to update a form record, and certain attributes are required to be unique. Validators on record creation works just fine. But, when I try to update a record it doesn’t work, error message “Field A has already been taken.”

When I comment out unique validation rule, the record get updated nicely.

Model:




    public function updateUser()

    {

        if(!$this->validate()) {

            return false;

        }


        $user = self::findOne($this->user_id);

        $user->nicename = $this->nicename;

        $user->status = $this->status;


        return $user->update() ? $user : null;

    }



Rule:




    public function rules()

    {

        return [

            [['user_id', 'nicename'], 'required', 'on' => self::SCENARIO_UPDATE],

            [['nicename'], 'unique', 'on' => self::SCENARIO_UPDATE]

        ];

    }



Controller:




    public function actionUserPost()

    {

        $userModel = new User();

        $userModel->scenario = User::SCENARIO_UPDATE;

        if($userModel->load(Yii::$app->request->post())) {

            if(!$userModel->updateUser()) {

                return $this->render('update', ['model' => $countryModel]);

            }

            echo 'Updated';

        } else {

            echo 'Not Updated';

        }

    }



Am I missing anything here?

Thanks,

Hi clonex1,

You don’t need to create “updateUser” method to update the user model. You just need to “save” the model. The save method will automatically call “insert” or “update” depending on whether it is just newly created or populated with an existing data.

And the unique validator is also clever enough to distinguish the scenarios automatically between inserting and updating.

Rule:




    public function rules()

    {

        return [

            [['nicename'], 'required'],

            [['nicename'], 'unique']

        ];

    }



Controller:




    public function actionUserPost()

    {

        $userModel = new User();

        // $userModel->scenario = User::SCENARIO_UPDATE;

        if($userModel->load(Yii::$app->request->post())) {

            if(!$userModel->save()) {

                return $this->render('update', ['model' => $userModel]);

            }

            echo 'Updated';

        } else {

            echo 'Not Updated';

        }

    }



Check some CRUD codes that Gii has generated for you.

I applied your proposed changes to the code. Still, it didn’t work.

Actually, I don’t know how to get beyond this issue…

Try using Gii’s CRUD generator. It will show the basic approach you should follow to “insert” and “update” a model.