Form doesn't validate and submit in yii - php

I try load form via ajax in CJuiDialog. The form was success loaded but when I submitted form or write text, form not validate and not submit.I tried set "true" fourth parameter in renderPartialbut after then dialog window didn't open. In console, I got error
$(...).dialog is not a function
In view I have this:
Yii::app()->clientScript->registerScript(
"test",
"jQuery.ajax({
type: 'POST',
url: '".$this->createUrl("/Site/ShowForm")."',
success: function(html){
$('#form-test').html(html);
});
",
CClientScript::POS_READY); ?>
<div id="form-test"></div>
<?php $this->endWidget('zii.widgets.jui.CJuiDialog');
My actions in controller:
public function actionShowForm()
{
$model = new RegistrationForm;
if(Yii::app()->request->isAjaxRequest )
return $this->renderPartial('register', array('model' => $model),false,false);
}
public function actionRegister()
{
$model = new RegistrationForm;
$this->ajaxValidate($model);
$model->attributes =$_POST['RegistrationForm'];
if($model->validate())
{
$user = new User;
$user->attributes = $model->attributes;
if($user->save())
echo 1;
}
}
and my form (register.php)
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'register-form',
//'enableClientValidation'=>true,
'enableAjaxValidation' => true,
'clientOptions' => array(
//'validateOnSubmit' => true,
'validateOnChange' => true
),
'action' => array('site/Register'),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model, 'first_name'); ?>
<?php echo $form->textField($model, 'first_name'); ?>
<?php echo $form->error($model, 'first_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'last_name'); ?>
<?php echo $form->textField($model, 'last_name'); ?>
<?php echo $form->error($model, 'last_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'email'); ?>
<?php echo $form->emailField($model, 'email'); ?>
<?php echo $form->error($model, 'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'password'); ?>
<?php echo $form->textField($model, 'password'); ?>
<?php echo $form->error($model, 'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'Repeat password'); ?>
<?php echo $form->textField($model, 'repeat_password'); ?>
<?php echo $form->error($model, 'repeat_password'); ?>
</div>
<div>
<?php echo $form->textField($model, 'verifyCode'); ?>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->error($model, 'verifyCode'); ?>
</div>
<div class="row buttons">
<?php
echo CHtml::ajaxSubmitButton('Register', $this->createUrl("/Site/Register"), array(
'type' => 'POST',
'dataType' => 'json',
'success' => 'js:function(data){
if(data == 1){
window.location ="' . $this->createUrl('site/index') . '"
}
}',
));
?>
</div>
<?php $this->endWidget(); ?>
How Can I fix this problem?

In your controller, where you check if the request is Ajax, you should be doing the Ajax validation in there.

I found solution! I added
Yii::app()->clientScript->scriptMap = array(
'jquery.js' => false,
'jquery.ui.js' => false,
'jquery.yiiactiveform.js' => false,
);
in my actionShowForm.

Related

yii - insert data into two tables via single form

I am very much a novice with PHP and the Yii framework.
Click here to see a sample of my SQL database setup http://i.stack.imgur.com/W6qQj.png
I have set up controllers and models for all three tables and have set up CRUD views from Gii for the Users table. I have read through this -> http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models/ and tried multiple sets of code examples etc... and failed. The best I can do is get the create form to insert all the data into the users table but not the email table. I believe my short coming is in my UsersController.php -> public function actionCreate() section. Can someone help me out with a sample piece of code to make the information post into the email table?
---EDIT---
As requested below is the requested info...
UsersController.php
public function actionCreate()
{
$model = new Users;
if (isset($_POST['Users'])) {
$model->attributes = $_POST['Users'];
$model->password=crypt($model->password,'salt');
$model->datecreated = new CDbExpression('NOW()');
if ($model->save()) {
$modelEmail = new Email;
$modelEmail->attributes = $_POST['Email'];
$modelEmail->fer_users_id = $model->id;
if ($modelEmail->save())
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
This is the users/_form.php view file:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-form',
'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,'username'); ?>
<?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'firstname'); ?>
<?php echo $form->textField($model,'firstname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'firstname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'lastname'); ?>
<?php echo $form->textField($model,'lastname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'lastname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx(Email::model(),'emailaddress'); ?>
<?php echo $form->textField(Email::model(),'emailaddress',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error(Email::model(),'emailaddress'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'fer_roles_id'); ?>
<?php
echo $form->dropDownList($model, 'fer_roles_id',
CHtml::listData(Roles::model()->findAll(), 'id', 'description'),
array('class' => 'my-drop-down', 'options' => array('2' => array('selected' => "selected")
)
)
);
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
you could do this:
Controller:
<?php
public function actionCreate()
{
$model = new Users;
$model1 = new Email;
$roles = Roles::model()->findAll();
if(isset($_POST['Users']))
{
$model->attributes = $_POST['Users'];
$model->password = crypt($model->password, 'salt');
$model->datecreated = new CDbExpression('NOW()');
$model->save();
$model1->attributes = $_POST['Users']['emailaddress'];
$model1->fer_users_id = $model->id;
$model1->save();
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('create', array(
'user'=>$model,
'email'=>$model1,
'roles'=> $roles
));
}
?>
your view:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($user); ?>
<div class="row">
<?php echo $form->labelEx($user,'username'); ?>
<?php echo $form->textField($user,'username',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'password'); ?>
<?php echo $form->passwordField($user,'password',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'firstname'); ?>
<?php echo $form->textField($user,'firstname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'firstname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'lastname'); ?>
<?php echo $form->textField($user,'lastname',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($user,'lastname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($email,'emailaddress'); ?>
<?php echo $form->textField($email,'emailaddress',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($email,'emailaddress'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($user,'fer_roles_id'); ?>
<?php
echo $form->dropDownList($user, 'fer_roles_id',
CHtml::listData($roles, 'id', 'description'),
array('class' => 'my-drop-down', 'options' => array('2' => array('selected' => "selected")
)
)
);
?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($user->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
if you get any error with this, let me know..

Updating Fields on a form with ajax and json

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.

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

internal server Error when load ajax in yii

I had problem in loading Ajax , I knew that by got screanshot of request by
Tamper Data :
http://up.arabseyes.com/uploads/02_12_1213544389861.jpg
result was : internal server Error .
What is the problem in my code ?
View :
<?php
/* #var $this UsersController */
/* #var $model Users */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-index-form',
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'الأسم الأول'); ?>
<?php echo $form->textField($model,'first_name'); ?>
<?php echo $form->error($model,'الأسم الاول'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'العائلة'); ?>
<?php echo $form->textField($model,'last_name'); ?>
<?php echo $form->error($model,'العائلة'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'كلمة المرور'); ?>
<?php echo $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'تأكيد كلمة المرور'); ?>
<?php echo $form->passwordField($model,'passwordconfirm'); ?>
<?php echo $form->error($model,'passwordconfirm'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'البريد الإلكتروني '); ?>
<?php echo $form->textField($model,'email'); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'تأكيد البريد الإلكتروني'); ?>
<?php echo $form->textField($model,'emailconfirm'); ?>
<?php echo $form->error($model,'emailconfirm'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'تاريخ الميلاد'); ?>
<?php
$this->widget(
'ext.jui.EJuiDateTimePicker',
array(
'model' => $model,
'attribute' => 'birth_date',
'language'=> 'en',//default Yii::app()->language
'mode' => 'date',//'datetime' or 'time' ('datetime' default)
'options' => array(
'dateFormat' => 'yy-mm-dd',
//'timeFormat' => '',//'hh:mm tt' default
),
)
);
?>
<?php echo $form->error($model,'birth_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'الجنس'); ?>
<?php echo chtml::activeDropDownList($model,'gender',$model->getStatusOption(),array('prompt'=>'أختر جنسك')
); ?>
<?php echo $form->error($model,'gender'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'البلد'); ?>
<?php
/*
echo chtml::activeDropDownList($model,'country',$model->getcountry(),array('prompt'=>'اختر بلدك ') ,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('current/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
))
);
*/
echo CHtml::activedropDownList($model,'country',$model->getcountry(),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('Register/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
))
);
?>
<?php echo $form->error($model,'country'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'المدينة'); ?>
<?php
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city','', array());
?>
<?php echo $form->error($model,'city'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'رمز الاتصال'); ?>
<?php echo $form->textField($model,'mobile_code'); ?>
<?php echo $form->error($model,'mobile_code'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'رقم الجوال'); ?>
<?php echo $form->textField($model,'mobile_number'); ?>
<?php echo $form->error($model,'mobile_number'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('تسجيــــــــــــل'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Controller :
....
public function actionDynamiccities() /// call Ajax
{
$data=Cities::model()->findAll('country=:country_id',
array(':country_id'=>(int) $_POST['country']));
$data=CHtml::listData($data,'id','city_name_e');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
};
}
....
Thanks in Advance .

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.

Categories