How to upload file with cjuidialog widget? - php

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.

Related

Error when trying to store the id of the multiple checkbox in database in yii

I had multiple check box to view the Hobby names from database, and it's working. But i need to store the selected id of the hobby names in the database. But when i select any hobby name it stores only 0 in my database table.
I had one Hobbies table and i created one model for that also. Please anybody help.
This is in views/sample/register.php file
<?php
/* #var $this SampleController */
/* #var $model Sample */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'sample-register-form',
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
'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,'username');
echo $form->textField($model,'username');
echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email');
echo $form->textField($model,'email');
echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password');
echo $form->passwordField($model,'password');
echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'confirm password');
echo $form->passwordField($model,'password');
echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'address');
echo $form->textArea($model,'address',array('rows'=>6, 'cols'=>22));
echo $form->error($model,'address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'country');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('Sample/Substate'),
'update'=>'#state_name',
'data'=>array('country_id'=>'js:this.value'),
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_name','', array('prompt'=>'Select Country First'),
array(
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createUrl('Sample/Subcity'),
'update'=>'#city_name',
'data'=>array('state_id'=>'js:this.value' ))));
echo $form->error($model,'state_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'city_id');
echo CHtml::dropDownList('city_name','', array('prompt'=>'Select State First'));
echo $form->error($model,'city_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'url');
echo CHtml::activeFileField($model, 'url'); // by this we can upload image
echo $form->error($model,'url'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'hobby');
//echo $form->checkBoxList($model,'hobby',CHtml::listData(Hobbies::model()->findAll(),'hobby_id','hobby_name'));
$data = Hobbies::model()->findAll();
foreach($data as $button)
{
//echo $button->course_name;
echo $form->checkBox($model,'hobby');
echo $button->hobby_name .'<br>';
}
echo $form->error($model,'hobby'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'gender');
echo $form->radioButtonList($model,'gender',array('Male'=>'Male','Female'=>'Female'),array('labelOptions'=>array('style'=>'display:inline'), // add this code
'separator'=>' ',
) );
echo $form->error($model,'gender'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'dob');
$form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'dob',
'name'=>$model->dob,
'value'=>$model->dob,
'options'=>array('dateFormat'=>'yy-mm-dd',
'altFormat'=>'yy-mm-dd',
'changeMonth'=>'true',
'changeYear'=>'true',
'yearRange'=>'1600:3000',
// which shows for both textfield and button
//'showOn'=>'both',
// 'buttonText'=>'choose date'
),
'htmlOptions'=>array('size'=>'10')
));
echo $form->error($model,'dob');
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Register'); ?>
</div>
<?php $this->endWidget(); ?>
This is in controller/SampleController.php file
public function actionRegister()
{
$model=new Sample;
if(isset($_POST['Sample']))
{
$model->attributes=$_POST['Sample'];
if($model->validate())
{
$model->hobby = implode(",",$model->hobby);
if($model->save())
{
$this->redirect(array('site/login'));
}
return;
}
}
$this->render('register',array('model'=>$model));
}
If you view the html generated by your foreach loop you will see that all your checkboxes have the same name and id. As such only one of them will be present in the $_POST array since the name is used as the key.
To fix this change the name to an array:
echo $form->checkBox($model, 'hobby[]');
Alternatively you can use CActiveForm::checkBoxList as in your commented code and use template to style it:
template: string, specifies how each checkbox is rendered. Defaults to "{input} {label}", where "{input}" will be replaced by the generated check box input tag while "{label}" will be replaced by the corresponding check box label.
echo $form->checkBoxList(
$model,
'hobby',
CHtml::listData(Hobbies::model()->findAll(), 'hobby_id', 'hobby_name'),
array('template' => '{input}{label}<br/>')
);

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

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));
}

How to Update a field based on the submit button - Yii

I'm new to Yii framework. I have to create three buttons in my form (update.php). i.e. (Save, Approve, Reject). I'm using the following fields in my form.
<?php
/* #var $this MessageTemplateController */
/* #var $model MessageTemplate */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'message-template-form',
'enableAjaxValidation'=>false,
)); ?>
<?php
echo $form->errorSummary($model);
?>
<div class="row">
<?php //$model->ReviewedDate=date('Y-m-d H:i:s');?>
<?php echo $form->labelEx($model,'ReviewedDate'); ?>
<?php echo $form->textField($model,'ReviewedDate',array('value'=>'0000-00-00 00:00:00','readonly' => true)); ?>
<?php echo $form->error($model,'ReviewedDate'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'SmsText'); ?>
<?php echo $form->textArea($model,'SmsText',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'SmsText'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'UpdatedDate'); ?>
<?php echo $form->textField($model,'UpdatedDate'); ?>
<?php echo $form->error($model,'UpdatedDate',array('value'=>date('Y-m-d H:i:s'),'readonly' => true)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Approved'); ?>
<?php echo $form->hiddenField($model, 'Approved'); ?>
<?php echo $form->error($model,'Approved'); ?>
</div>
<div class="row">
<div class="row">
<?php echo $form->labelEx($model_al, 'username'); ?>
<?php $identity=Yii::app()->user->name;?>
<?php echo $form->textField($model_al, 'username',array('value'=>$identity,'readonly' => true), array('size' => 60, 'maxlength' => 250)); ?>
<?php echo $form->error($model_al, 'username'); ?>
<div>
<div class="row">
<?php echo $form->labelEx($model_al, 'updatedtime'); ?>
<?php echo $form->textField($model_al, 'updatedtime',array('value'=>date('Y-m-d H:i:s'),'readonly' => true), array('size' => 60, 'maxlength' => 250)); ?>
<?php echo $form->error($model_al, 'updatedtime'); ?>
<div>
<div class="row">
<?php echo $form->labelEx($model_al, 'comments on approval/rejection'); ?>
<?php echo $form->textField($model_al, 'comments',array('size' => 60, 'maxlength' => 250)); ?>
<?php echo $form->error($model_al, 'comments'); ?>
<div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save', array('name' => 'save')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Accept', array('name' => 'accept')); ?>
<? echo ' '; ?>
<?php echo CHtml::submitButton('Reject', array('name' => 'reject')); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Now I have created three buttons.There is a field called approved in the above form.
I want this actions to happen when i click on the following buttons :
1. Save - All fields have to be saved but not approved(keep it as default).
2. Accept - All fields have to be saved with Approved changing to 1 in database.
3. Reject - All fields have to be saved with Approved changing to 0 in database.
How can I do this.
EDit
I have added the following in my controller.
public function actionUpdate($id)
{
$model_mt=new Messagesintable;
$model_al=new AuditLogin;
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['MessageTemplate']) && isset($_POST['AuditLogin']))
{
$model->attributes=$_POST['MessageTemplate'];
list($name,$mobile,$email)=retrieve_persondetails($id);
if($model->save())
{
$model_al->attributes=$_POST['AuditLogin'];
if ($model_al->save())
$this->redirect(array('admin','id'=>$model->Id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
You can check whether which submit button is clicked with these conditions and write your action inside.
if($_POST) {
if (isset($_POST['Save'])) {
// your code here
}
if (isset($_POST['Accept'])) {
// your code here
}
if (isset($_POST['Reject'])) {
// your code here
}
}

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.

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