1
votes

I have ajax validation on unique on create it work fine but when I want to update i cant becouse this show message that this name is already used but i not owerwrite this name it is name from database on update click. Its does not matter whcich record i want to update it always show me message that name is already used. Whan can i do to disable message when i not change my input to name which is in base. Now it is so update action automatically filed my inputs but when i not change anythink i have this error on save

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'], 'id'=>$model->formName(), 'enableAjaxValidation'=>true, 'validationUrl'=>Url::toRoute('category/validation')]) ?>

My controller:

 public function actionValidation(){
        $model= new SmCategory;
        if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
        {
            Yii::$app->response->format='json';
            return ActiveForm::validate($model);
        }
    }

my rules:

public function rules()
    {
        return [
            [['Name'], 'required'],
            ['Name', 'unique', 'targetClass' => 'common\models\Smcategory', 'message' => 'This name has already been taken.'],
            [['Rel_Category', 'IsDeleted'], 'integer'],
            [['File'],'file'],
            [['Name', 'Label'], 'string', 'max' => 45],
            [['Picture'], 'string', 'max' => 255]
        ];
    }
1
i tried to do scenarios but i want to make this unique on create and update actions - qwerty
can u show me example plis i new in Yii and i dont have idea how to do this i tried with this scenarios but it still not work for me - qwerty
add ['Name', 'unique', 'targetClass' => 'common\models\Smcategory', 'message' => 'This name has already been taken.', 'on' => 'create'], and in controller add $model->scenario = 'create'; - Insane Skull
but then on update it not work i want to have this rule on update too - qwerty

1 Answers

2
votes

The problem is here :

$model= new SmCategory;

This code is ok for create, not for update since it will not use the existing model for validation, it could be (just an example and assuming id is the primary key) :

public function actionValidation($id = null)
{
    $model = $id===null ? new SmCategory : SmCategory::findOne($id);
    if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
    {
        Yii::$app->response->format='json';
        return ActiveForm::validate($model);
    }
}

And you could update validationUrl in your view :

$validationUrl = ['category/validation'];
if (!$model->isNewRecord)
    $validationUrl['id'] = $model->id;

$form = ActiveForm::begin([
    'options' => ['enctype' => 'multipart/form-data'],
    'id' => $model->formName(),
    'enableAjaxValidation' => true,
    'validationUrl' => $validationUrl,
]);