如何在活动记录中使用唯一规则yii2

azi*_*mad 7 validation unique yii2

我想将我的表列设置的值设置为唯一值,如果在插入表单中我可以用来设置错误,我在数据库中插入与数据相同的值?

这是真的吗?

    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']
    ];
}
Run Code Online (Sandbox Code Playgroud)

Die*_*tto 10

记住:模型,视图,控制器.

模型 在模型规则中添加唯一验证器

...
 [['nama_barang'], 'unique'],
...
Run Code Online (Sandbox Code Playgroud)

视图

在表单视图中启用ajax验证

...
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true]); ?>
...
Run Code Online (Sandbox Code Playgroud)

调节器

在控制器"创建操作"中添加ajax验证

...
    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())) {
...
Run Code Online (Sandbox Code Playgroud)

和更新行动

...
    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())) {
...
Run Code Online (Sandbox Code Playgroud)

PS:如果不存在,请在控制器中添加所需的类.

use yii\web\Response;
use yii\widgets\ActiveForm;
Run Code Online (Sandbox Code Playgroud)


Ins*_*ull 5

试试这种方式

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']
  ];
}
Run Code Online (Sandbox Code Playgroud)