How to Use unique rules in active record yii2

20,469

Solution 1

Remember: model, view, controller.

Model add unique validator in your model rules like

...
 [['nama_barang'], 'unique'],
...

View

Enable ajax validation in your form view

...
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true]); ?>
...

Controller

Add ajax validation in your controller Create Action

...
    public function actionCreate()
    {
        $model = new Product();
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(Yii::$app->request->post())) {
...

and Update Action

...
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(Yii::$app->request->post())) {
...

PS: if not present, add required classes in your controller.

use yii\web\Response;
use yii\widgets\ActiveForm;

Solution 2

Try this way

public function rules()
{
return [
    [['nama_barang', 'harga', 'stok', 'id_satuan'], 'required'],
    [['harga', 'stok', 'id_satuan'], 'integer'],
    ['nama_barang', 'unique', 'targetAttribute' => ['nama_barang'], 'message' => 'Username must be unique.'],
    [['foto'], 'safe']
  ];
}
Share:
20,469
aziz akhmad
Author by

aziz akhmad

Updated on July 09, 2022

Comments

  • aziz akhmad
    aziz akhmad almost 2 years

    I want to set the values of my table column set as unique value, how i can use to set error if in insert form, I insert the same value as data in my database?

    Is it true?

        public function rules()
    {
        return [
            [['nama_barang', 'harga', 'stok', 'id_satuan'], 'required'],
            [['harga', 'stok', 'id_satuan'], 'integer'],
            ['nama_barang', 'unique', 'targetAttribute' => ['nama_barang' => 'nama_barang']],
            [['foto'], 'safe']
        ];
    }