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;
source share