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(){
},
});
});
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 created model view and controller for advertise.
i want a date in add table as current date.
in view generated by gii it displays text input field.
how can i make it hidden so that it can get current date without taking input from user??
what should I change?
help me please. this is not a complex but i getting confused.. thanks
view/_form.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'add-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'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'addname'); ?>
<?php echo $form->textField($model,'addname',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'addname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'category'); ?>
<?php echo $form->textField($model,'category',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'category'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description',array('size'=>60,'maxlength'=>1000)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'city'); ?>
<?php echo $form->textField($model,'city',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'city'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'address'); ?>
<?php echo $form->textField($model,'address',array('size'=>60,'maxlength'=>500)); ?>
<?php echo $form->error($model,'address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'mobile'); ?>
<?php echo $form->textField($model,'mobile',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'mobile'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'image'); ?>
<?php echo $form->textField($model,'image',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'image'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'price'); ?>
<?php echo $form->textField($model,'price',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($model,'price'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'createtime'); ?>
<?php echo $form->textField($model,'createtime'); ?>
<?php echo $form->error($model,'createtime'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
You can do that in Your controller. For example in yuor Controller` create action
public function actionCreate()
{
$model=new Product;
$model->createtime = strtotime('Now');
if(isset($_POST['Product']))
{........}
.......
}
And remove from _from.php
<div class="row">
<?php echo $form->labelEx($model,'createtime'); ?>
<?php echo $form->textField($model,'createtime'); ?>
<?php echo $form->error($model,'createtime'); ?>
</div>
Instead of
<?php echo $form->textField($model,'createtime'); ?>
Use
<?php echo $form->hiddenField($model,'createtime'); ?>
Alternatively in your model, you can set default values in afterConstruct():
protected function afterConstruct() {
parent::afterConstruct();
if($this->hasAttribute('createtime') && empty($this->createtime))
$this->createtime = new Date();
Another way to do it is set the default value in the database to CURRENT_TIMESTAMP.
Use simply:
date('Y-m-d H:i:s')
You can simply CURRENT_TIMESTAMP in your database, but unfortunately it only works for 1 row in a table
I think better put assign value on Model.
you can use beforeSave() to assign value into 'createtime' before model saved.
on # protected/models/YourModel.php add method like this :
public function beforeSave(){
if($this->isNewRecord){
$this->createtime = date('Y-m-d H:i:s');
}else{
$this->modifiedtime = date('Y-m-d H:i:s');
//just case if you have modifiedtime field
}
return parent::beforeSave();
}
after that, just removed this code from view form.
<div class="row">
<?php echo $form->labelEx($model,'createtime'); ?>
<?php echo $form->textField($model,'createtime'); ?>
<?php echo $form->error($model,'createtime'); ?>
</div>
I have a model website and a model url.
Each url data is attached to a website data. A url is related to a website via a website_id.
On my web app, I need to check the data before accepting it.
I want to see on screen the entire data regarding a url data and I managed to do this.
Now, I also want to update the entire data that is listed on screen.
On screen I have the entire url data and website data, but when I try to save the data, the website data is empty.
My logic was to add to the url model a property: public $website;
And within the url model, a method aftersave:
protected function afterSave() {
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
//echo '<pre>';
//print_r($w);
print_r($this->website);
$w->link = $this->website['link'];
$w->domain = $this->website['domain'];
$w->description = $this->website['description'];
$w->save(false);
die;
return parent::afterSave();
}
and here is the important code from the _form file:
<div class="row">
<?php echo $form->labelEx($model,'will_expire'); ?>
<?php echo $form->dropDownList($model,'will_expire',array(0=>'No',1=>'Yes')); ?>
<?php echo $form->error($model,'will_expire'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'link'); ?>
<?php echo $form->textField($model_website,'link'); ?>
<?php echo $form->error($model_website,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'domain'); ?>
<?php echo $form->textField($model_website,'domain'); ?>
<?php echo $form->error($model_website,'domain'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'description'); ?>
<?php echo $form->textField($model_website,'description'); ?>
<?php echo $form->error($model_website,'description'); ?>
</div>
There are few questions:
Is the relation url and website being defined in the model such that $url->website of a existing url gives you valid website record?
You form shows, you are not using any website_id, means that you are creating a new website record for every URL, means $w = Website::model()->findByAttributes(array('id' => $this->website_id)); will always return NULL
I assume you have defined a relation of website within your URL model.
Suggested function from my understanding:
protected function afterSave() {
//data is already assigned by the caller
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
if($w)
{
Yii::log("updating existing website data","info");
$this->website->save();
}
else
{
Yii::log("creating new website data","info");
$this->website->save();
$this->website_id = $this->website->website_id;
$this->update(array('website_id')); //save the relation
Yii::log("created new website {$this->website_id}","info");
}
return parent::afterSave();
}
It turned out to be small mistakes like w instead of W, object property instead of array;
Ok, so let me teach you how to do this;
I have 2 models: Url and Website.
Url model has a foreign key website_id and a relation to model Website;
Within the Url model I have a property called website and i declared it like: public $website = array();;
The data gets added thru a bookmarklet that uses a API so the data will be there when the admin comes to update/check it;
In the Url model i have a method afterSave:
protected function afterSave() {
$w = null;
$w = Website::model()->findByAttributes(array('id' => $this->website_id));
if($w)
{
$w->link = $this->website['link'];
$w->domain = $this->website['domain'];
$w->description = $this->website['description'];
$w->save();
}
return parent::afterSave();
}
where $this->website gets populated in the UrlController on actionUpdate like:
public function actionUpdate($id, $type = 'update') {
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Url'])) {
$model->attributes = $_POST['Url'];
$model->website = $_POST['Website'];
if ($model->save())
if ($type == 'update')
$this->redirect(array('view', 'id' => $model->id));
else
$this->redirect(array('/admin/url/approvePublicLink'));
}
$model_website = Website::model()->findByAttributes(array('id'=>$model->website_id));
$this->render('update', array(
'model' => $model,
'model_website' => $model_website,
));
}
and gets passed to the afterSave method later;
this is the _update view:
<div style="padding:20px 20px;">
<h1>Update Url, Website, Keywords ...</h1>
<?php echo $this->renderPartial('_form', array(
'model'=>$model,
'model_website' => $model_website,
)); ?>
</div>
and this is the _form view that gets rendered partial:
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'url-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,'website_id'); ?>
<?php echo CHtml::link($model->relation_website->domain,$model->relation_website->domain,array('class'=>'avia','target'=>'_blank')); ?>
<?php echo $form->error($model,'website_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'link'); ?>
<?php echo $form->textField($model,'link',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'important'); ?>
<?php echo $form->dropDownList($model,'important',array(0=>'Normal',1=>'Important')); ?>
<?php echo $form->error($model,'important'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'views'); ?>
<?php echo $form->textField($model,'views'); ?>
<?php echo $form->error($model,'views'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'created'); ?>
<?php echo $model->created; ?>
<?php echo $form->error($model,'created'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'updated'); ?>
<?php echo $model->updated; ?>
<?php echo $form->error($model,'updated'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'will_expire'); ?>
<?php echo $form->dropDownList($model,'will_expire',array(0=>'No',1=>'Yes')); ?>
<?php echo $form->error($model,'will_expire'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'link'); ?>
<?php echo $form->textField($model_website,'link'); ?>
<?php echo $form->error($model_website,'link'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'domain'); ?>
<?php echo $form->textField($model_website,'domain'); ?>
<?php echo $form->error($model_website,'domain'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model_website,'description'); ?>
<?php echo $form->textField($model_website,'description'); ?>
<?php echo $form->error($model_website,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'status'); ?>
<?php echo $form->dropDownList($model,'status',array(-1=>'Banned',0=>'Normal',1=>'Active')); ?>
<?php echo $form->error($model,'status'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I hope it helps.
I have the following form which is being used to create new records
<?php
/* #var $this ComponentsController */
/* #var $model Components */
/* #var $form CActiveForm */
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'components-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,'component_id'); ?>
<?php echo $form->textField($model,'component_id'); ?>
<?php echo $form->error($model,'component_id'); ?>
</div>
<div class="row">
<label class="required" for="FixedAsset_original_asset_number">
Asset Number
</label>
<input id="Components_original_asset_number" type="text" name="Components[original_asset_number]">
<?php //echo Chtml::textField('fixed_asset_id', FixedAsset::model()->FindByPk($model2->fixed_asset_id)->fixed_asset_id); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?>
<?php echo $form->textField($model,'description',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'manufacturer'); ?>
<?php //echo $form->textField($model,'manufacturer'); ?>
<?php $manufacturer = Manufacturers::model()->findAll(array("order"=>"name"));
$list = CHtml::listData($manufacturer, 'manufacturer_id', 'name');
echo $form->dropDownList($model,'manufacturer', $list,array());
?>
<?php echo $form->error($model,'manufacturer'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'medium'); ?>
<?php //echo $form->textField($model,'medium'); ?>
<?php $medium = Medium::model()->findAll();
$list = CHtml::listData($medium, 'medium_id', 'type');
echo $form->dropDownList($model,'medium', $list,array());
?>
<?php echo $form->error($model,'medium'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'version'); ?>
<?php echo $form->textField($model,'version',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'version'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'serial_no'); ?>
<?php echo $form->textField($model,'serial_no',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'serial_no'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'purchase_date'); ?>
<?php //echo $form->textField($model,'purchase_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'id'=>'Components_purchase_date',
'name'=>'Components[purchase_date]',
//'value'=>CTimestamp::formatDate('d/m/Y',$item->validFrom),
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'purchase_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'disposal_date'); ?>
<?php //echo $form->textField($model,'disposal_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'id'=>'Components_disposal_date',
'name'=>'Components[disposal_date]',
//'value'=>CTimestamp::formatDate('d/m/Y',$item->validFrom),
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'disposal_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'model'); ?>
<?php echo $form->textField($model,'model',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'model'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nol'); ?>
<?php echo $form->textField($model,'nol'); ?>
<?php echo $form->error($model,'nol'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I want to send an error to the field Components_original_asset_number on the form. How would I achieve this. In the controller function I am checking to see if it exists if not I want to display error on form or message. original asset number is part of a separate model which I am displaying on this form.
public function actionCreate()
{
$model = new Components;
$model_fixedAsset = new FixedAsset;
$model_comAsset = new ComAsset;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Components']))
{
$model->attributes=$_POST['Components'];
$fixedAssetId = null;
// Check if asset exist and get PK
if( $_POST['Components']['original_asset_number'] != "" ){
//print_r($_POST['Components']);
$criteria = new CDbCriteria;
$criteria->condition = "(original_asset_number = :original_asset_number)";
$criteria->params = array(":original_asset_number" => $_POST['Components']['original_asset_number'] );
$fixedAssetRow = FixedAsset::model()->find($criteria);
//print_r($fixedAssetRow);
if($fixedAssetRow){
$fixedAssetId = $fixedAssetRow->fixed_asset_id;
}
//echo $fixedAssetId;
}
if($fixedAssetId){
/*if($model->save())
$this->redirect(array('view','id'=>$model->component_id));*/
// Create com_asset record
}else{
//no asset found return error message to input corect asset number or create asset in navision and run php script to update mysql db
}
}
$this->render('create',array(
'model'=>$model,
'model_fixedAsset'=>$model_fixedAsset,
'model_comAsset'=>$model_comAsset,
));
}
You should add the 'original_asset_number' in your model as variable and set required validation rule. Then you can use the following line to set error
$model->addError('original_asset_number', " no asset found return error message to input corect asset number or create asset in navision and run php script to update mysql ");
Also, you use the following way to display the field and error.
<?php echo $form->errorSummary($model); ?>
or
<div class="row">
<?php echo $form->labelEx($model,'original_asset_number'); ?>
<?php echo $form->textField($model,'original_asset_number',array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'original_asset_number'); ?>
</div>
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')
); ?>