How to use unique rules in active yii2 record

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

It's 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'] ]; } 
+6
source share
3 answers

Remember: model, view, controller.

Model add a unique validator to your model rules, for example

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

View

Enable form ajax validation

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

controller

Add ajax check in 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, add the necessary classes to your controller.

 use yii\web\Response; use yii\widgets\ActiveForm; 
+8
source

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'] ]; } 
+5
source

Just set the unique in the rules [['name'], 'unique'],

Below is the full function.

 public function rules() { return [ [['name', 'description', 'comp_id'], 'required'], [['description'], 'string'], [['comp_id'], 'integer'], [['name'], 'string', 'max' => 100,], [['name'], 'unique'], [['comp_id'], 'exist', 'skipOnError' => true, 'targetClass' => Company::className(), 'targetAttribute' => ['comp_id' => 'comp_id']], ]; } 
0
source

All Articles