Validation 如何在活动记录yii2中使用唯一规则
我想将我的表列集合的值设置为唯一值,如果在insert表单中,我在数据库中插入与数据相同的值,如何使用设置错误?Validation 如何在活动记录yii2中使用唯一规则,validation,yii2,unique,Validation,Yii2,Unique,我想将我的表列集合的值设置为唯一值,如果在insert表单中,我在数据库中插入与数据相同的值,如何使用设置错误? 这是真的吗 public function rules() { return [ [['nama_barang', 'harga', 'stok', 'id_satuan'], 'required'], [['harga', 'stok', 'id_satuan'], 'integer'], ['nama_barang
这是真的吗
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']
];
}
这样试试
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']
];
}
记住:模型、视图、控制器
use yii\web\Response;
use yii\widgets\ActiveForm;
型号
在模型规则中添加唯一的验证器,如
...
[['nama_barang'], 'unique'],
...
查看
在表单视图中启用ajax验证
...
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true]); ?>
...
和更新操作
...
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())) {
...
...
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:如果不存在,请在控制器中添加所需的类
use yii\web\Response;
use yii\widgets\ActiveForm;
只需在规则
[['name'],'unique'],
下面是完整的函数
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']],
];
}
我遇到了一个类似的问题,即当我插入一个带有现有唯一字段的记录时,框架保持沉默,返回我的视图时没有任何错误。
因此,解决这个问题的诀窍是仅当$model->save()的布尔值为true时才执行成功重定向,否则通过view.php返回_form.php是否尝试插入相同的值?是的,我尝试插入相同的值,如果插入相同的值,我希望显示eror。我如何做到这一点?您是否试图让唯一的验证器纯粹在前端工作?因为只有后端可以执行实际的数据库查找。这意味着该验证器仅用于ajax和后端验证,而不用于前端验证。另外,看看属性,默认情况下只显示第一个错误。那么,它只是在后端?它不能在前端使用?谢谢匿名,但是表单中没有显示表单错误。如何显示表单错误?这对我来说是可行的,但我有一个问题。我有另一个列名为
证据
,我将其设置为必需
。在我遵循您的建议之后,表单中的证据字段始终标记为空,表示显示错误,尽管我输入了值。谢谢