Duplicate entries added after activating client side validation and form submission in Yii
I have the following simple form in Yii that is submitted by AJAX:
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'application-form',
'enableAjaxValidation' => true,
'enableClientValidation' => true,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
'onsubmit'=>"return send();"
),
'clientOptions'=>array('validateOnSubmit'=>true)
)); ?>
<div class="row">
<?php echo $form->labelEx($model, 'name'); ?>
<?php echo $form->textField($model, 'name', array('size' => 60,'maxlength' => 255)); ?>
<?php echo $form->error($model, 'name'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
And the function to send:
function send (){
var data_form=$("#application-form").serialize();
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->createUrl('admin/application/create') ?>",
dataType:'json',
data: data_form,
success: function (data, textStatus, jqXHR) {
console.log(data);
alert("success",textStatus);
},
error: function (jqXHR, textStatus, errorThrown) {
// console.log( errorThrown);
}
});
return false;
}
My creator:
public function actionCreate()
{
$model = new Application;
$model->setScenario('create');
$this->performAjaxValidation($model);
if (isset($_POST['Application'])) {
if ( $model->save()){
echo CJSON::encode(array('success' => 'true','id'=>$model->id));
Yii::app()->end();
}
}
$this->render('create', array(
'model' => $model
));
}
A name is required and this is only a test. When I try to submit the form without entering the field name, validation messages appear as they should have done in Yii. But when I fill out the form correctly, my model is entered into the database twice. If I remove the following property:
'clientOptions'=>array('validateOnSubmit'=>true)
the model is saved correctly (only once), but validation messages are not displayed.
How can I get default validation messages in Yii when I submit my form via ajax and the model will not be saved twice. I need to submit the form this way because I will return the model ID in the Ajax response for processing in JavaScript.
I've searched the internet for this and tried all the suggestions, but none of them work.
Thanks everyone!
source to share