Rendering Yii's Flash message inside the partial view with ajax call - php

I have a problem displaying Flash messages in Yii. Inside my view I have an ajax button, calling method update of my controller. Inside the update method I want to set a Flash message and display it inside my view when it's updated with new data.
*update.php :*
<?php
<h1>Update Campaign <?php echo $campaign->id; ?></h1>
<?php
$tabList = array();
//FORM IS DISPLAYED INSIDE A JUI TAB:
$tabList['General'] = $this->renderPartial('_form', array('campaign'=>$campaign),true);*
...
$this->widget('zii.widgets.jui.CJuiTabs',array(
'tabs'=>$tabList,
'options'=>array(
'collapsible'=>false,
),
));
?>
*_form.php:*
//HERE I WANT TO DISPLAY A FLASH MESSAGE WHEN _form IS RENDERED:
<?php foreach(Yii::app()->user->getFlashes() as $key => $message) : ?>
<div class="flash-<?php echo $key; ?>"><?php echo $message; ?></div>
<?php endforeach; ?>
<?php
Yii::app()->clientScript->registerScript(
'myHideEffect',
'$(".flash-success").animate({opacity: 1.0}, 1000).fadeOut("slow");',
CClientScript::POS_READY
);
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'campaign-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($campaign); ?>
<div class="row">
<div class="span2">
<?php echo $form->labelEx($campaign,'campaign_mode_id'); ?>
</div>
<div class="span2">
<?php echo $form->dropDownList($campaign,'campaign_mode_id', CampaignMode::model()->getModes());?>
<?php echo $form->error($campaign,'campaign_mode_id'); ?>
</div>
</div>
...
<div class="row buttons">
<div class="span2">
<?php
if($campaign->isNewRecord){
echo CHtml::submitButton( 'Create');
}else{
//THIS IS MY AJAX-SUBMIT BUTTON, IT CALL CONTROLLER'S UPDATE METHOD AND UPDATE JUI TAB (DIV WITH ID '#yw0_tab0')
echo CHtml::ajaxSubmitButton(
'Save',
Yii::app()->createUrl("//campaign/update/{$campaign->id}"),
array('beforeSend' => 'function(){
$("#surveyquestions").addClass("ajaxloading");}',
'complete' => 'function(){
$("#surveyquestions").removeClass("ajaxloading");}','update' => "#yw0_tab0"),
array('id' => 'send-link-'.uniqid()));
}
?>
</div>
</div>
<?php $this->endWidget(); ?>
*Contorller:*
public function actionUpdate($id)
{
$campaign=$this->loadModel($id);
if(isset($_POST['Campaign']))
{
$campaign->attributes=$_POST['Campaign'];
if($campaign->save())
{
//HERE I'M SETTING THE FLASH MSG
Yii::app()->user->setFlash('success','Campaign is updated');
if(Yii::app()->request->isAjaxRequest){
//AND UPDATING MY VIEW
$this->renderPartial('_form', array('campaign'=>$campaign), true,true);
}else{
$this->redirect(array('update','id'=>$campaign->id));
}
}
}
$this->render('update',array('campaign'=>$campaign));
}

Actually you are rendering _form view, but without sending it to output (take a look at third param), and then you are rendering update view... The flash message has been rendered once in _form, so it won't be rendered again.
You should simply try this :
if(Yii::app()->request->isAjaxRequest) {
$this->renderPartial('_form', array('campaign'=>$campaign), false, true);
Yii::app()->end();
} else {
$this->redirect(array('update','id'=>$campaign->id));
}

Related

Data from a form don't register in a database (Yii framework)

I have view:
...
<div class="row">
<?php echo $form->labelEx($model,'content'); ?>
<?php $this->widget('application.extensions.ckeditor.CKEditor',array(
'model'=>$model,
'attribute'=>'content',
'language'=>'en',
'editorTemplate'=>'full',));
?>
<?php echo $form->error($model,'content'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->dropDownList($model,'status', array('0' => 'Not published', '1' => 'Published')); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row">
<?php
echo $form->labelEx($model,'category_id');
echo CHtml::dropDownList('category_id','', Category::allCategory(),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('subcategory/dynamicSubCategories'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#subcategory_id', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
)));
echo $form->error($model,'category_id');
?>
</div>
<div class="row">
<?php
echo $form->labelEx($model,'subcategory_id');
echo CHtml::dropDownList('subcategory_id','', array());
echo $form->error($model,'subcategory_id');
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
...
Data from the fields 'category_id' and 'subcategory_id' don't write in a database. All other fields successfully register. Prompt as me to tie this field to a form and to solve the matter?
Use this method for dropDownLists
echo CHtml::activeDropDownList($model, 'category_id',Category::allCategory()
....
Or better use form method
echo $form->dropDownList($model, 'category_id', Category::allCategory()
....
this is because the data that is saved, should be part of the models array data, so change your new field name to reflect MODELNAME[ATTRIBUTENAME]
echo CHtml::dropDownList('MODELNAME[category_id]', ...
or simply change to activeDropdownList

issues validation using render partial yii framework

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.

Validating a Form without redirect

I created app with yii and I need to load a view form in Fancy-box.
I did that but my problem is when I click on the submit button the form redirects me to the controller action without validating the form.
How to validate the form without the redirect inside Fancy-box?
My view:
<?php
$config = array(
);
$this->widget('application.extensions.fancybox.EFancyBox', array(
'target'=>'#getaction',
'config'=>$config,));
echo CHtml::link('Add Section',array('section/create'),array('id'=>'getaction'));
?>
FormView _from from call from another view
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'section-form',
'enableAjaxValidation'=>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,'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>
<?php $this->endWidget(); ?>
</div><!-- form -->
Controller :
public function actionCreate()
{
$model=new Section;
if(isset($_POST['Section']))
{
$model->attributes=$_POST['Section'];
if($model->validate())
//// Do Som code here
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
the problem was fixed by my bro seenivasan on Yii Forum , so I will share the code here
_form.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'section-form',
'enableAjaxValidation'=>true,
//'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true), //This is very important
)); ?>
<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->textField($model,'name',array('size'=>60,'maxlength'=>64)); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
In controller
public function actionCreate()
{
$model=new Section;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);//You have enabled ajax validation. You have to uncomment this line.
if(isset($_POST['Section']))
{
$model->attributes=$_POST['Section'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
if(Yii::app()->request->getIsAjaxRequest())
echo $this->renderPartial('_form',array('model'=>$model),true,true);//This will bring out the view along with its script.
else $this->render('create',array(
'model'=>$model,
));
}
Reference link :
Yii Forum
Just add 'enableClientValidation'=>true, in the array inside the beginwidget.

How to upload file with cjuidialog widget?

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.

ajax request in CActiveForm

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')
); ?>

Categories