How to show CActiveForm::errorSummary() on ajax requests? (Yii) - php

On Post requests <?php echo $form->errorSummary($model) ?> automatically appears on the page after submitting form and show summary of form errors. How can make it appear on Ajax requests?
Edit:
Following is my view file:
<div class="form" >
<?php
$form = $this->beginWidget('CActiveForm',array(
'id'=>'change-profile-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'action' => Yii::app()->createUrl('upanel/user/CProfile'),
'method' => 'POST',
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
'validateOnType'=>false,
),
));
?>
.
.
.
<div class="row">
<?php
echo CHtml::ajaxSubmitButton(
'update',
Yii::app()->createUrl('upanel/user/CProfile'),
array(
'type'=>'POST',
'data'=>"js:$('#change-profile-form').serialize()",
'success'=>'callback',
'beforeSend'=>'before',
),
array(
'id'=>'update-button'.uniqid(),
'class'=>'submit-button',
)
);
?>
</div>
<?php $this->endWidget() ?>
</div> <!-- End The Profile Form -->
<?php echo $form->errorSummary($model,'Please solve these errors:') ?>

clientOptions can also accept:
'afterValidate' => 'js:function(form, data, hasError){
if(hasError){
// do something with: data
}
}'
What i do is something like this http://phpfiddle.org/lite/code/4j3-6rx then on the server side, i just return a json message that gets parsed on the ajax success callback, pretty simple.

Related

Creating a dependent dropdown in yii

i am trying this sample about Creating a dependent dropdown i created form in provinceCity/_form and copy actionDynamiccities to ProvinceCityController.php but when i change dropDown list i have not any change ?
i think i must to enable ajax but i do not how i do it?
<?php echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('ProvinceController/dynamiccities'), //url to call.
//Style: CController::createUrl('ProvinceCity/methodToCall')
'update'=>'#city_id', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
)));
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array()); ?>
Here is what you will do in _form
<?php echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('ProvinceController/dynamiccities'), //url to call.
'update'=>'#city_name', //selector to update
'data'=>array('country_id' => 'js:this.value'),
)));
?>
</div>
<div id=city_name>
<?php echo $form->dropDownList($model, 'city_id', array()); ?>
</div>
Hopefully, it would help you.
It should be,
<?php
$countryAry=array(1=>'USA',2=>'France',3=>'Japan');
echo CHtml::dropDownList('country_id','', $countryAry,
array
(
'ajax' => array
(
'type'=>'POST',
'url'=>CController::createUrl('Controller/action'),
'dataType'=>'JSON',
'success'=>'js:function(data)'
. '{'
. ' var opt="<option value=>-----Select city-----</option>";'
. ' $.each(data,function(i,obj)'
. ' {'
. ' opt+="<option value=\'"+obj.id+"\'>"+obj.name+"</option>";'
. ' });'
. ' $("#city_id").html(opt);'
. '}'
)
));
echo CHtml::dropDownList('city_id','', array());
?>
But, I suggest you to implement this task as showing bellow.
<?php
$countryAry=array(1=>'USA',2=>'France',3=>'Japan');
echo CHtml::dropDownList('country_id','', $countryAry,array('onchange'=>'js:getCities()'));
echo CHtml::dropDownList('city_id','', array());
?>
<script type="text/javascript">
function getCities()
{
$.ajax
({
type:'POST',
url:'Controller/action',
dataType:'JSON',
success:function(data)
{
var opt="<option value=>-----Select city-----</option>";
$.each(data,function(i,obj)
{
opt+="<option value='"+obj.id+"'>"+obj.name+"</option>";
});
$("#city_id").html(opt);
}
});
}
</script>
I found the solution here Dependent dropdown list in yii
<?php
$model=new ModelClass; // initilize it in controller
$form=$this->beginWidget('CActiveForm', array(
'id'=>'dependent-form',
'enableClientValidation'=>true,
'htmlOptions' => array('enctype' => 'multipart/form-data','autocomplete'=>'off'),
'clientOptions'=>array(
'validateOnSubmit'=>true,
)
));
?>
<div class="row">
<?php
echo $form->dropDownList($model,'country_id',
CHtml::listData(Countries::model()->findAll(), 'id', 'title'),
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('YourController/loadstates'), // get states list
'update'=>'#ModelClass_state_id', // add the state dropdown id
'data'=>array('country_id'=>'js:this.value'),
)));
?>
</div>
<div class="row">
<?php
echo $form->dropDownList($model,'state_id',
array(),
array(
'prompt'=>'Select State',
'ajax' => array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('YourController/loadcities'), // get states list
'update'=>'#ModelClass_city_id', // add the state dropdown id
'data'=>array('state_id'=>'js:this.value'),
)));
?>
</div>
<div class="row">
<?php
echo $form->dropDownList($model,'city_id',array(),array('empty'=>'-choose city-'));
?>
</div>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Add' : 'Update',array('class'=>'btn btn-primary')); ?>
<?php $this->endWidget(); ?>

php YII Cgridview & Checkbox + Different Model

I'm very new in YII and sorry if it's a silly question.
in the view (_form) I'm displayng 2 different tables: billing & cost
they are connected trough colums IDCLIENT & IDBILLING
When I create a new billing I would like to select (with checkboxes) which cost insert in it, and the cost.IDBILLING must be update with the IDBILLING just created.
I've underline the unknow part.
Here _form Code:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'billing-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,'IDCLIENT'); ?>
<h2><?php echo $client->IDCLIENT; ?></h2>
<?php echo $form->error($model,'IDCLIENT'); ?> <br>
<h3><?php
echo $client->name." ".$client->surname."<br>".$client->document;
?></h3>
</div>
<div class="row">
<?php echo $form->labelEx($model,'datefrom'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>"Billing[datefrom]", // the name of the field
'value'=>$model->datefrom, // pre-fill the value
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd', // optional Date formatting
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'datefrom'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'dateto'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>"Billing[dateto]", // the name of the field
'value'=>$model->dateto, // pre-fill the value
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd', // optional Date formatting
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'dateto'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>"Billing[date]", // the name of the field
'value'=>$model->date, // pre-fill the value
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd', // optional Date formatting
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state'); ?>
<?php echo $form->textField($model,'state',array('size'=>16,'maxlength'=>16)); ?>
<?php echo $form->error($model,'state'); ?>
</div>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'cost-grid',
'dataProvider'=>new CActiveDataProvider('Cost',array(
'criteria' => $criteria,
'pagination' => array('pageSize' => 10),
)),
'selectableRows' => 2,
//'filter'=>$model,
'columns'=>array(
array('class'=>'CCheckBoxColumn','value'=>'$data->IDCOST/*??????IS THIS CORRET????*/',),
'IDCOST',
'advance',
'spent',
'date',
'type',
'scope',
/*
'note',
'IDCLIENT',
*/
),
)); ?>
here the controller:
public function actionCreate($IDCLIENT)
{
$model=new Billing;
$client = new Client;
$criteria=new CDbCriteria;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
//$this->IDCLIENT= $IDCLIENT;
$client = Client::model()->findByPk((int)$IDCLIENT);
$criteria->condition = "IDCLIENT = ".$client->IDCLIENT." AND (IDBILLING IS NULL OR IDBILLING = 0)";
$criteria->order = "date DESC";
if(isset($_POST['Billing']))
{
$model->attributes=$_POST['Billing'];
$model->IDCLIENT=$client->IDCLIENT;
if($model->save()){
$cost= new Cost;
if($cost=Cost::model()->updateAll(array( 'IDBILLING' => $model->IDBILLING ), 'IDCOST = '.#########WHAT I HAVE TO INSERT HERE???########))
$this->redirect(array('view','id'=>$model->IDBILLING));
}
}
$this->render('create',array(
'model'=>$model,
'client'=>$client,
'criteria'=>$criteria,
));
}
Thanks in advance for any reply
you can refresh your grids like this (in javascript):
$.fn.yiiGridView.update("your-grid-name");
submit the data you want by ajax to another controller and save it or whatever you want, and then refresh your grid and display your new result!
cheers

Yii. How to add css "error" class to input on form submit?

I have Yii form. Some fields are required. When form is submitted i need that CSS class "error" would be added to the text input. My Code:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<ul class="contact_form">
<li class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name', array('class'=>'input')); ?>
<?php echo $form->error($model,'name'); ?>
</li>
...
Now i just get div with error message:
<div class="errorMessage" id="ContactForm_name_em_" style="">Laukelis „Vardas, pavardė“ negali būti tuščias.</div>
How to add "error" class to input field?
<?php echo $form->textField($model,'name', array('class'=>'input' . ( $model->getError('name') ? ' error' : ''))); ?>
To have AJAX validation also, you should add something more or less like this:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'afterValidate' => 'js:function(form, data, hasError) {
if(hasError) {
for(var i in data) $("#"+i).addClass("error_input");
return false;
}
else {
form.children().removeClass("error_input");
return true;
}
}',
'afterValidateAttribute' => 'js:function(form, attribute, data, hasError) {
if(hasError) $("#"+attribute.id).addClass("error_input");
else $("#"+attribute.id).removeClass("error_input");
}'
),
)); ?>

Auto complete fields of a previous values

I am doing a small application in Yii Framework for that my database is something like this
=== Invoices ===
id (PK)
customer_id
invoice_title
order_no
invoice_issue_date
due_date
description
=== Customers ===
id (PK)
email_address
customer_name
address
city
state
postal_code
description
I have rendered the Customer model in Invoice model so that I can enter all the values for both models in a single Invoice form.But there is one problem,let us assume that I have a customer name xyz which I had saved before.Now when I am going to again fill the Customer name with xyz,it should show all the fields of both models like invoice_title,order_no,invoice_issue_date,due_date,description,email_address,customer_name,address etc. in that input fields of the form so that I don't have to re-enter all the fields again.So how this can be achive in Yii framework.Any help and suggestions will be highly appreciable.More clarification on codes that I have done can be shared if needed.
Please help me out.I am totally stuck here.
To do this as everyone has already mentioned you need ajax, and some javascript. The logic is something like this:
When a value is selected in the dropdown for customer name, trigger an ajax call to retrieve the information about that user. This can be easily done with the ajax option, which is available as an additional htmlOption for some html element helpers in CHtml, as part of clientChange.
echo $form->dropDownList($model,'customer_name',CHtml::listData(Customers::model()->findAll(),'id','customer_name'),
array(// htmlOptions
'ajax'=>array(// special htmlOption through clientChange, for ajax
'type'=>'GET',
'url'=>$this->createUrl('controllername/customerdetails'),// action that will generate the data
'data'=>'js:"id="+$(this).val()',// this is the data that we are sending to the action in the controller
'dataType'=>'json',// type of data we expect back from the server
'success'=>'js:updateFields'// a javascript function that will execute when the request completes successfully
)
)
);
The documentation for the above options for ajax can be seen in jquery's ajax documentation.
Then in the server side find the particular customer, and send a response to the browser. Example:
// in the controllername code an action that will return the values as json
public function actionCustomerdetails($id){
$var=Customers::model()->findByPk($id);
echo CJSON::encode($var);
}
When you receive the server response populate the respective fields. This can be done in the success function callback for ajax, in the above code it was updateFields:
Yii::app()->clientScript->registerScript('update','
function updateFields(data, textStatus, jqXHR){
// select each input field by id, and update its value
$("#Customers_postal_code").val(data.postal_code);
$("#Customers_city").val(data.city);
$("#Customers_address").val(data.address);
// similarly update the fields for the other inputs
}
');
Notes:
Your customer can have many invoices, so the question will be which invoice to select given a customer name. That's something you'll have to handle, i think my answer has enough code to get you going.
To know the input field ids, you can simply check the generated html.
You could do this in two stages, so that:
When the view is initially displayed, the customer is asked for their email address or customer_name.
The Controller Action that the form is submitted to then retrieves data from the Customer model for the submitted email address or customer_name (I'll use email_address in my example below). Once retrieved, you can display your Single Invoice Form View with the data pre-populated for the customer if available.
This concept could then be implemented as follows:
<?php
// file: controllers/InvoiceController.php
class InvoiceController extends CController
{
// ... other controller functions
public function actionCreate($step = null)
{
$invoice = new Invoice;
$customer = new Customer;
# Form has been submitted:
if ( isset($_POST['Customer']) )
{
# The submitted form was Step 1:
if ( $step == 1 )
{
# make sure the submitted email address is valid
$customer->setAttributes($_POST['Customer']);
if ( $customer->validate(array('email_address')) )
{
# retrieve the customer by email_address
$customer = Customer::model()->findByAttributes(array('email_address' => $_POST['Customer']['email_address']));
}
$this->render('createstep2', array('invoice' => $invoice, 'customer' => $customer));
}
# The submitted form was Step 2:
elseif ( $step == 2 )
{
$income->setAttributes($_POST['Invoice']);
$customer->setAttributes($_POST['Customer']);
# save the data
if ( $customer->save() )
{
$invoice->customer_id = $customer->id;
if ( $invoice->save() )
{
$this->redirect(array('view', 'id' => $invoice->id));
}
}
# display any errors
$this->render('createstep2', array('invoice' => $invoice, 'customer' => $customer));
}
}
$this->render('createstep1', array('invoice' => $invoice, 'customer' => $customer));
}
// ... other controller functions
}
?>
You could split that to two separate Controller Actions if you wish.
For Step 1 View, you could then have the following:
<!-- file: views/invoice/createstep1.php -->
<h1>Create Invoice: Step 1</h1>
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'invoice-form',
'enableAjaxValidation'=>false,
'action'=>array('invoice/create','step' => 1)
));
?>
<?php echo $form->errorSummary($customer); ?>
<div class="row">
<?php echo $form->labelEx($customer,'email_address'); ?>
<?php echo $form->textField($customer,'email_address', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'email_address'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Next'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Step 2 view, you could then look like what you already have. Maybe something like:
<!-- file: views/invoice/createstep2.php -->
<h1>Create Invoice: Step 2</h1>
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'invoice-form',
'enableAjaxValidation'=>false,
'action'=>array('invoice/create','step' => 2)
));
?>
<?php echo $form->errorSummary($invoce); ?>
<?php echo $form->errorSummary($customer); ?>
<h2>Customer Details</h2>
<div class="row">
<?php echo $form->labelEx($customer,'email_address'); ?>
<?php echo $form->textField($customer,'email_address', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'email_address'); ?>
</div>
<!-- If the customer already exists, these field should be pre-populated: -->
<div class="row">
<?php echo $form->labelEx($customer,'customer_name'); ?>
<?php echo $form->textField($customer,'customer_name', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'customer_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'address'); ?>
<?php echo $form->textField($customer,'address', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'city'); ?>
<?php echo $form->textField($customer,'city', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'city'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'state'); ?>
<?php echo $form->textField($customer,'state', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'state'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'postal_code'); ?>
<?php echo $form->textField($customer,'postal_code', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'postal_code'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'description'); ?>
<?php echo $form->textField($customer,'description', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'description'); ?>
</div>
<h2>Order Details</h2>
<div class="row">
<?php echo $form->labelEx($invoice,'invoice_title'); ?>
<?php echo $form->textField($invoice,'invoice_title', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($invoice,'invoice_title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'order_no'); ?>
<?php echo $form->textField($invoice,'order_no', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($invoice,'order_no'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'invoice_issue_date'); ?>
<?php $form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $invoice,
'attribute' => 'invoice_issue_date',
'value' => $invoice->invoice_issue_date,
'options' => array(
'showButtonPanel' => false,
'changeYear' => true,
'dateFormat' => 'yy-mm-dd',
),
)); ?>
<?php echo $form->error($invoice,'invoice_issue_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'due_date'); ?>
<?php $form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $invoice,
'attribute' => 'due_date',
'value' => $invoice->due_date,
'options' => array(
'showButtonPanel' => false,
'changeYear' => true,
'dateFormat' => 'yy-mm-dd',
),
)); ?>
<?php echo $form->error($invoice,'due_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'description'); ?>
<?php echo $form->textField($invoice,'description', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($invoice,'description'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Create'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Have you checked the Yii Autocomplete widget? And you wouldn't have to worry about AJAX implementation. It does it for you.
Yii Framework: CJui AutoComplete
A more customized autocomplete solution in this link.
Yii Framework: custom-autocomplete-display-and-value-submission

Php form ajax request not working , yii framework

I am doing a yii web application
i have a drop down list that should be dependent on another , i use ajax however it doesnt work.
ive seen the yii tutorial for dependent drop downs and searched everywhere.
http://www.yiiframework.com/wiki/24
this is my main drop down list:
<div class="row">
<?php echo $form->labelEx($model, 'sourceID'); ?>
<?php
echo $form->dropDownList($model, 'sourceID', CHtml::listData(Sources::model()->findAll(), 'sourceID', 'name'), array('empty' => 'select source'), array(
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('reservations/atest'),
'update' => '#meal'
)
)
);
?>
<?php echo $form->error($model, 'sourceID'); ?>
</div>
this is the dependent drop down list :
<div class="row">
<?php echo $form->labelEx($model, 'meal'); ?>
<?php echo $form->dropDownList($model, 'meal', array()); ?>
<?php echo $form->error($model, 'meal'); ?>
</div>
this is my controller action:
public function actionAtest() {
$data = Sources::model()->findAll();
$data = CHtml::listData($data, 'sourceID', 'name');
foreach ($data as $value => $name) {
echo CHtml::tag('option', array('value' => $value), CHtml::encode($name),true);
} }
also, i added the action to the access rules.
any help is appreciated ,
thank you in advance.
You placed the ajax option after the htmlOptions. Here is the modified code
<div class="row">
<?php echo $form->labelEx($model, 'sourceID'); ?>
<?php
echo $form->dropDownList($model, 'sourceID', CHtml::listData(Sources::model()->findAll(), 'sourceID', 'name'), array('empty' => 'select source','ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('reservations/atest'),
'update' => '#meal'
)
)
);
?>
<?php echo $form->error($model, 'sourceID'); ?>
</div>
And instead of using forms dropdownlist use CHtml::dropDownList for the dependent drop-down.
echo CHtml::dropDownList('meal','', array());
You can also use CActiveForm::dropDownList but in that case you have to use CHtml::resolveNameId in the update option of ajax

Categories