I have a 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 function for submitting:
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 create controller:
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
));
}
Filed name is required and that is only validation for now. When I try to submit form without field name inputted, validation messages appear as they supposed to do in Yii. But when I fill form correctly, my model is inputted twice in database. If I remove following property:
'clientOptions'=>array('validateOnSubmit'=>true)
model gets saved correctly (only one time), but no validation messages appear.
How can I get default validation messages in Yii to appear, when I submit my form via ajax and model not to be saved twice. I need to submit form this way, because I will return model id in Ajax response for processing in JavaScript.
I searched the web for this and tried all suggestions, but none of them work.
Thank you all!
'afterValidate'=>'js:function(form,data,hasError){ send(form,data,hasError);
and removing'onsubmit'=>"return send();"
line. Now it shows validation errors and only saves model once. Check yiiframework.com/forum/index.php/topic/… this post for more info. – user3691678