i am trying ajax based form submission in yii framework here is my view code
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-form',
'enableAjaxValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true, 'validateOnType'=>false),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'user_username'); ?>
<?php echo $form->textField($model,'user_username',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'user_username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'user_password'); ?>
<?php echo $form->textField($model,'user_password',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'user_password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'user_role'); ?>
<?php echo $form->dropDownList($model,'user_role', CHtml::listData($dropDownData, 'role_id', 'role_title')); ?>
<?php echo $form->error($model,'user_role'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'user_company_id'); ?>
<?php echo $form->textField($model,'user_company_id'); ?>
<?php echo $form->error($model,'user_company_id'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::ajaxSubmitButton('Create User', CHtml::normalizeUrl(array(''),
array(
'beforeSend'=>'function() {
$(".createUser").attr("disabled","disabled");
}',
'success'=>'function(data) {
alert(data);
if( data == "sent" ) {
$(".ajaxMessage").text("User has been successfully created");
} else {
$(".ajaxMessage").text("Oops! It looks there is some error in your form");
}
$(".createUser").removeAttr("disabled");
}'
),
array('class'=>'createUser')
)); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<div class="ajaxMessage"></div>
I want to grab the ajax response in variable. Here is the controller code
if(isset($_POST['Users']))
{
if( Yii::app()->request->isAjaxRequest )
echo 'ajax get';
else
echo 'ajax not get';
}
In firebug i have seen that response is generated correctly but it is not stored in my variable. The view code is created with the help of this link:
http://www.yiiframework.com/forum/index.php/topic/8219-solved-ajax-form-submission/
The javascript data will be whatever you echo from controller. So if you want to check for data=="sent" in jquery's success callback, do echo 'sent'; from the action.
You have included the ajaxOptions inside the normalizeUrl function, change it to:
<div class="row buttons">
<?php echo CHtml::ajaxSubmitButton('Create User', CHtml::normalizeUrl(array('')),
array(
'beforeSend'=>'function() {
$(".createUser").attr("disabled","disabled");
}',
'success'=>'function(data) {
alert(data);
if( data == "sent" ) {
$(".ajaxMessage").text("User has been successfully created");
} else {
$(".ajaxMessage").text("Oops! It looks there is some error in your form");
}
$(".createUser").removeAttr("disabled");
}'
),
array('class'=>'createUser')
); ?>
Related
I created a ajax submit button to submit a form.
The form is working Good and all the functionalty which I need working perfectly.
I enabled Ajax validation and a success message also.
The problem occurs when I partial redirect the form.
The ajax function and validation is not working.
My Controller
public function actionCreate()
{
$model=new Comments;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Comments']))
{
$model->attributes=$_POST['Comments'];
// echo '<pre>';print_r($model->attributes);die();
$valid = $model->validate();
if($valid){
if($model->save()){
echo CJSON::encode(array('status'=>'success'
));
}
}else{
$error =CActiveForm::validate($model);
if($error != '[]')
echo $error;
Yii::app()->end();
}
}
}
View /_Form
<?php
$form = $this->beginWidget('CActiveForm',array('id'=>'comments-form',
'enableAjaxValidation'=>true,
'action'=>$this->createUrl('Comments/create'),
'enableClientValidation'=>true
));
?>
<div class="errorMessage" id="formResult"></div>
<div id="AjaxLoader" style="display:none" >
<img src="<?php echo Yii::app()->request->baseUrl;?>/theme/images/spinner.gif">
</div>
<div class="row-user-single-user-single" >
<?php echo $form->labelEx($model,'type'); ?>
<?php
echo $form->dropDownList($model,'type',
array(""=>"Select Type","0"=>"Offer","1"=>"Events"),
array('style' => 'width:220px;','class'=>'form-control','disabled'=>false,)); ?>
<?php echo $form->error($model,'type'); ?>
</div>
<div class="row-user-single-user-single" >
<?php echo $form->labelEx($model,'offereventid'); ?>
<?php echo $form->textField($model,'offereventid',array('style' => 'width:500px;','class'=>'form-control','disabled'=>false,)); ?>
<?php echo $form->error($model,'offereventid'); ?>
</div>
<div class="row-user-single-user-single">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name',array('style' => 'width:500px;','class'=>'form-control','disabled'=>false,)); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row-user-single">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('style' => 'width:500px;','class'=>'form-control','disabled'=>false,)); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row-user-single">
<?php echo $form->labelEx($model,'comment'); ?>
<?php echo $form->textArea($model,'comment',array('style' => 'width:500px;','class'=>'form-control','disabled'=>false,)); ?>
<?php echo $form->error($model,'comment'); ?>
</div>
<div class="row-user-single">
<?php //echo $form->labelEx($model,'createdby'); ?>
<?php //echo $form->textField($model,'createdby'); ?>
<?php //echo $form->error($model,'createdby'); ?>
</div>
<div class="row-user-single">
<?php //echo $form->labelEx($model,'createdon'); ?>
<?php //echo $form->textField($model,'createdon'); ?>
<?php //echo $form->error($model,'createdon'); ?>
</div>
<div class="row-user-single">
<?php //echo $form->labelEx($model,'status'); ?>
<?php //echo $form->textField($model,'status',array('size'=>1,'maxlength'=>1)); ?>
<?php //echo $form->error($model,'status'); ?>
</div>
<div class="buttons">
<?php
echo CHtml::ajaxSubmitButton('Submit',CHtml::normalizeUrl(array('Comments/create','render'=>true)),
array(
'dataType'=>'json',
'type'=>'post',
'success'=>'function(data){
$("#AjaxLoader").hide();
if(data.status == "success"){
$("#formResult").html("Comment Submitted");
$("#comments-form")[0].reset();
}else{
$each(data,function(key.val){
$("#comments-form #"+key+"_em_").text(val);
$("#comments-form #"+key+"_em_").show();
});
}
}',
'beforeSend'=>'function(){
$("#AjaxLoader").show();
}'
),array('id'=>'submit','class'=>'btn btn-success'));
?>
<?php $this->endWidget();?>
</div>
Please help me...
Make sure that all required scripts (jQuery etc.) are registered. Debug it in JS console. If you render this form by renderPartial method maybe you should set $processOutput=true param in this method.
I want to update some fields in my form, after retrieving data from a db using ajax & json.
This is the code:
In my form:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'anagrafica-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'codicefiscale'); ?>
<?php echo $form->textField($model,'codicefiscale',array('size'=>20,'maxlength'=>16)); ?>
<?php echo $form->error($model,'codicefiscale'); ?>
<div id="bottone_ricerca" style="display:inline;">
<?php
echo CHtml::ajaxButton( 'Ricerca',
$this->createUrl('anagrafica/popolaAnagrafica'),
array(
'type' => 'POST',
'datatype' => 'json',
'data' => array('codfisc' => 'js:$(\'#AnagraficaForm_codicefiscale\').val()'),
'success' => 'function(response){
$("#cand").html(response);
$("#'.CHTML::activeId($model,'cognome').'").val(response.cognome);
$("#'.CHTML::activeId($model,'nome').'").val(response.nome);
$("#'.CHTML::activeId($model,'email').'").val(response.email);
}'
),
array()
);
?>
</div>
<div id="cand">
</div>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cognome'); ?>
<?php echo $form->textField($model,'cognome',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'cognome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nome'); ?>
<?php echo $form->textField($model,'nome',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'nome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'indirizzo'); ?>
<?php echo $form->textField($model,'indirizzo',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'indirizzo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cap'); ?>
<?php echo $form->textField($model,'cap',array('size'=>10,'maxlength'=>5)); ?>
<?php echo $form->error($model,'cap'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'comune'); ?>
<?php echo $form->textField($model,'comune',array('size'=>25,'maxlength'=>20)); ?>
<?php echo $form->error($model,'comune'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'provincia'); ?>
<?php echo $form->textField($model,'provincia',array('size'=>5,'maxlength'=>2)); ?>
<?php echo $form->error($model,'provincia'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'telefono'); ?>
<?php echo $form->textField($model,'telefono',array('size'=>20,'maxlength'=>15)); ?>
<?php echo $form->error($model,'telefono'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Inserisci'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
In my controller:
public function actionPopolaAnagrafica()
{
$codfisc = Yii::app()->request->getParam('codfisc');
echo $codfisc;
if (Yii::app()->request->isAjaxRequest) {
if ($codfisc == '') {
echo CJSON::encode(array(
'error' => 'true',
'status' => 'Richiesta non valida.'
));
Yii::app()->end();
} else {
//$sql = "SELECT * FROM user WHERE username = ':codfisc'";
$sql = "SELECT * FROM user WHERE username = '".$codfisc . "'";
$cmd = Yii::app()->db->createCommand($sql);
//$cmd->bindParam(":codfisc", $codfisc, PDO::PARAM_STR);
$result = $cmd->queryRow();
$sql2 = $cmd->text;
if($result) {
echo CJSON::encode(array(
'error' => 'false',
'status' => 'Codice Fiscale esistente',
'username' => $result['username'],
'cognome' => $result['cognome'],
'nome' => $result['nome'],
'email' => $result['email']
)
);
Yii::app()->end();
} else {
echo CJSON::encode(array(
'error' => 'true',
'status' => 'Il codice fiscale ' . $codfisc . ' non esiste. SQL = ' . $sql2 . '.'
));
Yii::app()->end();
}
}
}
I can't update fields. The response is:
xxxyyyddxdd{"error":"false","status":"Codice Fiscale
esistente","username":"xxxyyyddxdd","cognome":"Cognome","nome":"Nome","email":"prova#email.it"}
but it should be:
{"error":"false","status":"Codice Fiscale
esistente","username":"xxxyyyddxdd","cognome":"Cognome","nome":"Nome","email":"prova#email.it"}
Where's my mistake?
Thanks
You need to remove the following line:
echo $codfisc;
(second line in function actionPopolaAnagrafica)
public function actionPopolaAnagrafica()
{
$codfisc = Yii::app()->request->getParam('codfisc');
//this LINE!!!!!!!!!!!!!!!!!!!!!!!
echo $codfisc;
Change :
'success' => 'function(response){
$("#cand").html(response);
$("#'.CHTML::activeId($model,'cognome').'").val(response.cognome);
With this :
'success' => 'function(response){
$("#cand").html(response);
var obj = jQuery.parseJSON( response );
console.log(obj.cognome);
$("#'.CHTML::activeId($model,'cognome').'").val(obj.cognome);
Parse JSON data before you put in HTML value.
Use console.log(obj.cognome); to debug value in chrome.
I have created a form which allows user to save tabular data. I have followed this tutorial . I have managed to add multiple instance for a Model and I am getting the data in the post and it is getting validate. The problem is with the error summary and the AJAX validation.
Below is my controller code, I have created an array for the second Model and passed it to the form.
$model = new UserAccountDetail;
$addresses = array();
array_push($addresses, new UserAddress);
array_push($addresses, new UserAddress);
$this->validateUserAccount($model,$addresses);
if(isset($_POST['UserAccountDetail']) && isset($_POST['UserAddress']))
{
$model->attributes = $_POST['UserAccountDetail'];
$model->validate();
$addresses = array();
for($i=0;$i<2;$i++)
{
if(isset($_POST['UserAddress'][$i]))
{
$address = new UserAddress;
$address->attributes = $_POST['UserAddress'][$i];
array_push($addresses, $address);
$address->validate();
}
}
}
$this->render('accountinformation',array('model'=>$model,'addresses'=>$addresses));
Below is my ajax validation function:
protected function validateUserAccount($model,$addresses)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='user-account-detail-form')
{
echo CActiveForm::validate($model).CActiveForm::validateTabular($addresses);
Yii::app()->end();
}
}
When I run this code the Ajax validation does not work. The onclick validation does work but for the tabular data the messages are not shown in the error summary but the fields are highlighted in red.
I any thing else is required then please let me know.
Thanks for your time. Cheers!!!!!
Update View File:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'user-account-detail-form',
'enableAjaxValidation'=>true,
)); ?>
<?php echo $form->errorSummary($model,$address); ?>
<h2> Account Details </h2>
<div class="row">
<?php echo $form->labelEx($model,'Title'); ?>
<?php echo $form->dropDownList($model,'Title', $model->getAllTitles()); ?>
<?php echo $form->error($model,'Title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'firstName'); ?>
<?php echo $form->textField($model,'firstName',array('size'=>50,'maxlength'=>100)); ?>
<?php echo $form->error($model,'firstName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'middleName'); ?>
<?php echo $form->textField($model,'middleName',array('size'=>50,'maxlength'=>100)); ?>
<?php echo $form->error($model,'middleName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastName'); ?>
<?php echo $form->textField($model,'lastName',array('size'=>50,'maxlength'=>100)); ?>
<?php echo $form->error($model,'lastName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'displayName'); ?>
<?php echo $form->textField($model,'displayName',array('size'=>50,'maxlength'=>200)); ?>
<?php echo $form->error($model,'displayName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'birthDate'); ?>
<?php echo $form->textField($model,'birthDate',array('size'=>50,'maxlength'=>15)); ?>
<?php echo $form->error($model,'birthDate'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lenderType'); ?>
<?php echo $form->textField($model,'lenderType',array('size'=>50,'maxlength'=>15)); ?>
<?php echo $form->error($model,'lenderType'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'businessName'); ?>
<?php echo $form->textField($model,'businessName',array('size'=>60,'maxlength'=>200)); ?>
<?php echo $form->error($model,'businessName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'hearAboutUs'); ?>
<?php echo $form->dropDownList($model,'hearAboutUs', $model->getAllHearAbout()); ?>
<?php echo $form->error($model,'hearAboutUs'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'promotionalCode'); ?>
<?php echo $form->textField($model,'promotionalCode',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'promotionalCode'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'mobileNumber'); ?>
<?php echo $form->textField($model,'mobileNumber',array('size'=>50,'maxlength'=>15)); ?>
<?php echo $form->error($model,'mobileNumber'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'workLandline'); ?>
<?php echo $form->textField($model,'workLandline',array('size'=>50,'maxlength'=>15)); ?>
<?php echo $form->error($model,'workLandline'); ?>
</div>
<?php echo $form->textField($model,'thirdAnswer',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'thirdAnswer'); ?>
</div>
<h2>Address </h2>
<?php foreach ($addresses as $i=>$address) { ?>
<div class="row">
<?php echo $form->labelEx($address,"[$i]Flat"); ?>
<?php echo $form->textField($address,"[$i]Flat",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]Flat"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]buildingName"); ?>
<?php echo $form->textField($address,"[$i]buildingName",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]buildingName"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]buildingNumber"); ?>
<?php echo $form->textField($address,"[$i]buildingNumber",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]buildingNumber"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]street"); ?>
<?php echo $form->textField($address,"[$i]street",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]street"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]district"); ?>
<?php echo $form->textField($address,"[$i]district",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]district"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]town"); ?>
<?php echo $form->textField($address,"[$i]town",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]town"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]county"); ?>
<?php echo $form->textField($address,"[$i]county",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]county"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]postCode"); ?>
<?php echo $form->textField($address,"[$i]postCode",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]postCode"); ?>
</div>
<div class="row">
<?php echo $form->labelEx($address,"[$i]isCorresppondence"); ?>
<?php echo $form->textField($address,"[$i]isCorresppondence",array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($address,"[$i]isCorresppondence"); ?>
</div>
<?php } ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Continue'); ?>
</div>
<?php $this->endWidget(); ?>
Update : I have checked the response from the server and it is giving the correct response. Below is the screen shot:
Update :: I have managed to correct the on click validation issue by passing the array of models to the errorSummary() function like:
<?php
$error = array();
array_push($error, $model);
foreach ($addresses as $address)
{
array_push($error, $address);
}
echo $form->errorSummary($error); ?>
But the AJAX validation is still not working. Can any one help me with that.
http://www.yiiframework.com/doc/api/1.1/CActiveForm
The AJAX-based validation has a few limitations. First, it does not
work with file upload fields. Second, it should not be used to perform
validations that may cause server-side state changes. Third, it is not
designed to work with tabular data input for the moment.
So, you need to write custom error handler for tabular data
//view
$form = $this->beginWidget('CActiveForm', array(
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnChange' => false,
'validateOnType' => false,
'validateOnSubmit' => true,
'beforeValidate' => 'js:formBeforeValidate',
'afterValidate' => 'js:formAfterValidate'
),
));
//some js
function formBeforeValidate (form) {
//clean errors
return true;
}
function formAfterValidate(form, data, hasError) {
if (hasError === true) {
//append errors to input
}
return !hasError;
}
There is no inbuilt mechanism in Yii to ajax validation for tabular data. I implemented custom validation using jquery for this purpose. Below is the code that I used to create a custom ajax validation for tabular data.
Controller: It assigns the value passed to the model attribute and returns any error for the attribute.
public function actionValidateData($value,$name)
{
$model = new BusinessPartner;
$model->setAttribute($name, $value);
$model->validate();
echo CHtml::error($model,$name);
Yii::app()->end();
}
Jquery function to make ajax call and show the messages. I have added class 'businessPartner' to all the fields of the model.
$(document).on('blur','.businessPartner',function(e){
e.preventDefault();
var id= $(this).attr('id');
var name= $(this).attr('rel');
$.ajax({
url:"<?php echo Yii::app()->createUrl('user/validatedata'); ?>",
type: "GET",
data: 'value='+$.trim($(this).val())+'&name='+ name,
success :function(data){
if($.trim(data))
{
if(!$('#'+id).hasClass('error'))
{
$('#'+id).addClass('error');
$('#'+id).prev().addClass('error');
$('#'+id).after(data);
}
}
else
{
if(!$('#'+id).parent().hasClass('success'))
{
$('#'+id).removeClass('error');
$('#'+id).prev().removeClass('error')
$('#'+id).next().remove()
$('#'+id).parent().addClass('success');
}
}
},
error:function(){
},
});
});
I am loading a view using renderpartial, but the validations not working and not show the error messages. I tried to resolve the problem actived processOUtput in renderpartial but isn´t work.
this is my index view where I load the form view
<?php echo CHtml::link('Crear Usuario', array('create'), array('id'=>'newUsuario')); ?>
<div id="modal" class="modal hide fade"></div>
<script>
$(document).ready(function() {
$("#newUsuario").click(function() {
event.preventDefault();
$("#modal").load($("#newUsuario").attr("href"));
$("#modal").modal({show:true});
});
});
</script>
This is my action that load the view
public function actionCreate() {
$model = new Usuarios;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Usuarios']))
{
$model->validate();
$model->attributes=$_POST['Usuarios'];
$_POST['Usuarios']['check_tipo'] == 1 ? $model->tipo = 'Administrador' : $model->tipo = 'Normal';
$model->pass_php = md5($model->pass);
$model->session = $model->generateSalt();
$model->pass_hash= $model->hashPassword($_POST['Usuarios']['pass'], $model->session);
$this->transaction = $model->dbConnection->beginTransaction();
try {
if($model->save()) {
$this->transaction->commit();
$this->actionIndex();
}
} catch(Exception $e) {
$this->transaction->rollBack();
}
}
$this->renderPartial('create', array('model'=>$model));
}
And this is the view with the form
<h4 align="center">Nuevo Usuario</h4>
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'usuarios-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>255, 'placeholder'=>'Escriba su email')); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'check_tipo'); ?>
<?php echo $form->checkBox($model,'check_tipo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nombre'); ?>
<?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>255, 'placeholder'=>'Escriba su nombre')); ?>
<?php echo $form->error($model,'nombre'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'pass'); ?>
<?php echo $form->passwordField($model,'pass',array('size'=>60,'maxlength'=>255, 'placeholder'=>'Escriba su contraseña')); ?>
<?php echo $form->error($model,'pass'); ?>
</div>
</div>
<center>
<?php echo CHtml::button('Close', array('class'=>'btn', 'data-dismiss'=>'modal', 'aria-hidden'=>true)); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save', array('class'=>'btn btn-primary')); ?>
</center>
<?php $this->endWidget(); ?>
When I used render the validations and error messages work, the problem is just with renderpartial.
Help me please and sorry if my english is bad.
Q : how to upload file with cjuidialog widget?
description : I want to upload a single file with popup box. So I select the cjuidialog box widget. And I followed from here. But I'm facing with saving and validation. After submitting, there is not saving the data and when validation failed, the popup box is re-showing again and again (duplicated).
this is views/aa/_form.php
<?php
echo CHtml::ajaxLink(Yii::t('attachment','Attachment'),$this->createUrl('attachmentform'),array(
'onclick'=>'$("#attachDialog").dialog("open"); return false;',
'update'=>'#attachDialog'
),array('id'=>'showattachDialog', 'class'=>'btn btn-info'));
?>
this is controller/aacontroller.php
public function actionAttachmentForm()
{
$media=new Media;
$this->performAjaxValidation($media);
$flag=true;
if(isset($_POST['Media']))
{
$flag=false;
$media->attributes=$_POST['Media'];
$media->name=CUploadedFile::getInstance($media,'name');
var_dump($media->attributes);
if($media->save()) {
//do something here and renderPartial to uploadedfile.php to show uploaded files.
$this->renderPartial('uploadedFile','',false,true);
}
}
if($flag == true) {
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
}
$this->renderPartial('uploadform',array('model'=>$media,),false,true);
}
this is views/aa/uploadform.php
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'attachDialog',
'options'=>array(
'title'=>Yii::t('attachment','Attachment Form'),
'autoOpen'=>true,
'modal'=>'true',
'width'=>'450',
'height'=>'300',
'draggable' => false,
'resizable'=> false,
),
));
echo $this->renderPartial('_formupload', array('model'=>$model)); ?>
<?php $this->endWidget('zii.widgets.jui.CJuiDialog');
this is views/aa/_formupload.php
<div class="form" id="attachDialogForm">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'attach-form',
'enableAjaxValidation'=>true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
//I have enableAjaxValidation set to true so i can validate on the fly the
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php //echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->fileField($model,'name'); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description'); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row buttons">
<?php
echo CHtml::ajaxSubmitButton(Yii::t('attachment','Upload'),
CHtml::normalizeUrl(array('attachmentform','render'=>false)),array(
//'beforeSend' => 'function(){$("#uploadedfile").addClass("loading");}',
//'complete' => 'function(){$("#uploadedfile").removeClass("loading"); $("#attachDialog").dialog("close");}',
'success'=>'js: function(data) {
//alert(data);
$("#attachDialog").dialog("close");
$("#uploadedfile").html(data);
}'),array('id'=>'closeattachDialog'));
?>
</div>
<?php $this->endWidget(); ?>
</div>
I recommend the 'EAjaxUpload' extension.
It is very easy to use and if you have any questions I can help, since I have it implemented.