Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use unique rules in active record yii2

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']
    ];
}
like image 640
aziz akhmad Avatar asked Oct 12 '15 08:10

aziz akhmad


2 Answers

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;
like image 65
Diego Betto Avatar answered Nov 06 '22 04:11

Diego Betto


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']
  ];
}
like image 45
Insane Skull Avatar answered Nov 06 '22 04:11

Insane Skull