Yii ajaxvalidation为true时重复插入
我有一个奇怪的问题,当我的表单启用ajaxvalidation时,我的模型会双重插入数据库。我不明白为什么会发生这种情况,但这一直与我的自定义验证冲突,我无法继续。有人能在这个问题上启发我吗 型号:Yii ajaxvalidation为true时重复插入,yii,Yii,我有一个奇怪的问题,当我的表单启用ajaxvalidation时,我的模型会双重插入数据库。我不明白为什么会发生这种情况,但这一直与我的自定义验证冲突,我无法继续。有人能在这个问题上启发我吗 型号: public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array(
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('category, ppmp_id', 'numerical', 'integerOnly'=>true),
array('category','required'),
array('q1, q2, q3, q4', 'numerical'),
array('category', 'myTestUniqueMethod'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('item_id, category, q1, q2, q3, q4, ppmp_id', 'safe', 'on'=>'search'),
);
}
public function myTestUniqueMethod($attribute,$params)
{
$sql = 'SELECT *
FROM ppmp_item
WHERE ppmp_id='.$this->ppmp_id.'and category='.$this->category;
$unique = Yii::app()->db->createCommand($sql)->queryRow();
if ($unique)
{
$this->addError('category', "Category already added to PPMP");
}
}
视图:
问题是在验证时不应该执行save()方法,因为它在执行ajax验证和通过表单发送数据时会保存,因此,您应该执行以下操作:
...
...
if(isset($_POST['ajax']) && $_POST['ajax']==='ppmp-item-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
$valid=$model->validate();
if($valid)
if($model->save())
...
...
这与使用ajax进行验证时使用的gii相同。Oh。我想$valid可以处理这个问题。因此,如果无效,则模型将自动不保存。此外,编程中还有另一个问题,在验证函数处,不要连接变量的值,只需使用如下参数:公共函数myTestUniqueMethod($attribute,$params){$sql='从ppmp_项中选择*,其中ppmp_id=:ppmp_id,category=:category';然后使用$unique=Yii::app()->db->createCommand($sql)->->->bindParam(“:ppmp_id”,$this->ppmp_id,PDO::PARAM_STR)->bindParam(:category“,$this->category,PDO::PARAM_STR)->query query queryRow();注意。感谢您的帮助。另外,将以下代码移动到控制器:$data=philgepscegory::model()->findAll();并将其传递给视图,因为视图不应访问数据。仅此而已。
public function actionCreate($ppmp,$bal)
{
$model=new PpmpItem;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PpmpItem']))
{
$model->attributes=$_POST['PpmpItem'];
$model->ppmp_id = $ppmp;
$valid=$model->validate();
if($valid)
if($model->save())
$this->redirect(array('ppmp/view','id'=>$ppmp));
}
$this->render('create',array(
'model'=>$model,
'ppmp'=>$ppmp,
'bal'=>$bal,
));
}
...
...
if(isset($_POST['ajax']) && $_POST['ajax']==='ppmp-item-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
$valid=$model->validate();
if($valid)
if($model->save())
...
...