I am trying to display the price based on the selection of product from a drop down.
View contains:
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'plan-form',
'enableAjaxValidation'=>true,
)); ?>
<?php echo $form->dropDownListRow($model, 'plan_id',
$planList, array('id'=>'planid', 'prompt'=>'Select Plan',
'ajax' => array('type'=>'GET',
'url'=> Yii::app()->createUrl('mbr/plan/ajaxGetPrice'),
'update'=>'#price'))); ?>
<div id="price">0.00</div>
<?php $this->endWidget(); ?>
Action:
public function actionAjaxGetPrice()
{
Yii::log("Within AjaxGetPrice");
if (Yii::app()->request->isAjaxRequest)
Yii::log("ajax request");
else
Yii::log("regular request");
//$plan=Plan::model()->findByPk((int) $_GET['plan_id']);
//Yii::log(serializ($plan));
// echo $plan->price;
echo "10";
Yii::app()->end();
}
It is not updating the price. Its not calling the action at all. I looked at the suggestions found in Yiiframework and here and tried those and still no luck.
when I add this to the view
<?php
echo CHtml::ajaxLink(
"Get Price",
Yii::app()->createUrl('mbr/plan/ajaxgetprice'),
array( // ajaxOptions
'type' => 'GET',
'update' => '#price'),
array( //htmlOptions
'href' => Yii::app()->createUrl('mbr/plan/ajaxgetprice')
)
);
?>
I get the response when I click on the link, but it renders a separate page with value "10". I have URLFormat = Path.
What am I doing wrong? Any pointers?
You can also try this as shown
<?php echo CHtml::dropDownList('categories','',
$category,
array('ajax'=>array('type'=>'POST','url'=>CController::createUrl('yourController/GetId'),'update' =>'#data'))
);?>
yourController action
public function actionGetId(){
echo 10;
}
And the div
<div id="data">0.00</div>
I'm not really sure how to do this the Yii way but the following javascript should be useful.
$("#yourdropdownidhere").change(function(){
$.ajax({
url: 'your url here', //(dynamically generated by product item)
type: "get",
success: ajaxSuccessHandler
});
});
function ajaxSuccessHandler(obj) {
$('#price').html(obj);
}
I also suggest sending a JSON object as the response for AJAX requests, so it will have an actual structure. A great blog post on this to check out would be Fully ajax website with Yii
I had the same problem and solved it on the controller that renders the view. If you are using renderPartial assure that the processOutput() option is set to TRUE, otherwise Yii will not attach any Javascript.
If you use render instead of renderPartial it also works.
Related
How to show the validation errors in a form in a pop dialogue box?Instead of showing it in the top of the form as a separate div, i want to show those errors in a popup dialogue box so that user clicks okay and dismiss the box.How to do this in yii?
Register your own javascript function name to the afterValidate, which is one of the options in clientOptions property in CActiveForm form class.
Your form declaration should have
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate' => 'js:myFunc',
),
And Your form will appear like bellow
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'a-form',
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'errorMessageCssClass' => 'required',
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate' => 'js:myFunc',
),
));
?>
------Your form fields------------
------Your form fields------------
------Your form fields------------
<?php $this->endWidget(); ?>
Now, Your myFunc code:
<script type="text/javascript" charset="utf-8">
function myFunc(form, data, hasError)
{
if (hasError)
{
var errors='';
$.each(data, function(obj)
{
errors+=data[obj][0]+"\n";
});
alert(errors);
// Do what ever you want
return true;
}
}
</script>
If you enable client side validation, then you will get error message under textbox, dropdown. There is no in-built option for poping up error message.
still if you need popup error message display, then you have to do with jquery. Then add in Yii forum to help others as well :-)
Refer this link (Yii forum) for details about client side validation
You can build the HTML view yourself with a custom CFormModel and use getError() method in a modal popup.
See : http://www.yiiframework.com/doc/api/1.1/CModel#getError-detail
and : http://www.yiiframework.com/doc/api/1.1/CFormModel
I am using both the client validation and ajax validation for my CActiveForm but both the client and ajax validations are not performing if i remove ajaxvalidation means to false the client validation is happening. can any suggest for the solution here i am posting my code
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'useraccess-form',
'enableClientValidation'=>true,
'enableAjaxValidation'=> true,
'clientOptions' => array(
'validateOnSubmit' => true
),
)); ?>
I got the same problem when tried to set id for feilds via htmlOptions
Check source code of generated page. Compare ids of fields in javascript code with ids in html code
I am included JQuery twice. Need once and with framework.
<?php Yii::app()->getClientScript()->registerCoreScript('jquery'); ?>
I have a user registration form, in which I am trying to display a Captcha image by using Yii widget CCaptcha, however my image link appears broken,
Controller file:
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
Model File:
public function rules()
{
return array( array('verifyCode','captcha','allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'insert'),
);
}
And view file:
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as shown.
<br/>Letters are not case-sensitive.</div>
<?php echo $form->error($model,'verifyCode'); ?>
</div>
<?php endif; ?>
As a answer provided somewhere I also tried giving the access rules in my controller file as
public function accessRules()
{
return array(
array('allow',
'actions' => array('captcha'),
'users' => array('*'),
),
);
}
But nothing seems to be working.
The problem was with the controller file,it should have been,
public function accessRules()
{
return array(
array('allow',
'actions'=>array('create', 'captcha'),
'users'=>array('*'),
),
}
whereas I had mentioned the action for captcha at the end, which I figured out is not allowed in Yii. All the allow actions for * should be together.
Yii captcha will create a png image. A possible explanation for the broken image link would be a missing GD extension or imagick extension, which can be identified by the presence of the following text in your error.log:
call to undefined function imagecreatetruecolor
For details and fix see "call to undefined function imagecreatetruecolor" error in PHP & pChart
I'm a new to yii, so I was following this tutorial.
when I try to upload picture it reports empty field even if it is not.
my _form view:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'picture-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
...
<div class="row">
<?php echo $form->labelEx($model,'path_to'); ?>
<?php echo $form->fileField($model,'path_to'); ?>
<?php echo $form->error($model,'path_to'); ?>
</div>
...
<?php $this->endWidget(); ?>
</div><!-- form -->
and here is my action method:
public function actionCreate()
{
$model=new Picture;
if(isset($_POST['Picture']))
{
$model->attributes=$_POST['Picture'];
$model->picture=CUploadedFile::getInstance($model,'path_to');
if($model->save()){
$log->lwrite('in save'.$model->picture);
$model->picture->saveAs(Yii::app()->basePath.'/../images/'.$model->picture);
$this->redirect(array('view','id'=>$model->id));
$log->lclose();
}
}
$this->render('create',array('model'=>$model,));
}
when I print_r($_FILES) everything what should be there is there
when I print_r($_POST) the field 'path_to' is empty and the validator probably is picking that one.
I'm probably missing something here and I'm clueless.
update1:
I've noticed yii is using hidden field with the same name as file input, than attributes are read from $_POST, which is causing the engine reading empty hidden field.
I understand that the hidden field is there for update when user is not entering new picture.
Can anyone advice what is the best way of doing picture upload?
update2:
model code:
class Picture extends CActiveRecord
{
public $picture;
...
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('path_to, page_id', 'required'),
array('page_id', 'numerical', 'integerOnly'=>true),
array('alt_text', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, alt_text, path_to, page_id', 'safe', 'on'=>'search'),
//array('path_to', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
//array('path_to', 'length', 'max'=>255, 'on'=>'insert,update'),
array('path_to', 'unsafe'),
);
}
...
Best!
I think because you've declared 'path_to' to be unsafe in your rules, the massive assignment line:
$model->attributes=$_POST['Picture'];
Will fail, which will then cause the rule validation to fail. Change your rules to allow for path_to to be safe, and you should be good to go . . .
It also appears you're requiring a page_id, which I'm not seeing in your form.
_form code for file upload field :
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'post-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
<div class="row">
<?php echo $form->labelEx($model, 'image');?>
<?php echo $form->fileField($model, 'image'); ?>
<?php echo $form->error($model, 'image'); ?>
</div>
<?php $this->endWidget(); ?>
Controller Code:
public function actionCreate()
{
$model=new Post;
if(isset($_POST['Post']))
{
$model->attributes=$_POST['Post'];
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = $uploadedFile;
$model->image = $fileName;
if($model->save()){
$uploadedFile->saveAs('C:/Program Files/Apache Group/Apache2/htdocs'.Yii::app()->baseUrl.'/images/thumbnails/'.$fileName);
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
diplay view code :
<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'ajaxUpdate' => false,
'columns'=>array(
array(
'name'=>'Thumbnail',
'value'=>array($model,'showThumbnail'), // function in model
'type'=>'html',
'htmlOptions'=>array('class'=>'thumbnail'),
),
)
));
?>
model code :
place this function in ur model :
public function showThumbnail($data){
$path = $data->image;
return CHtml::image(Yii::app()->baseUrl.'/images/thumbnails/'.$path); // same path as ur uploaded file path
}
CGridView widget is already having view,update,dete option.But i am using CListView widget in my jquery mobile based project, but having problem in creating ajax link for delete option. Not getting idea how to create a ajax delete link in _view.php(view file) and its renderPartial() view file to disappear the bar after successfully deleted plz help thanks in advance. Here is the _view.php file link for edit and delete.
<?php
echo CHtml::link(CHtml::encode($data->id),
array('editmember1', 'id' => $data->id),
array('data-role' => 'button', 'data-icon' => 'star')
);
echo CHtml::link(CHtml::encode($data->id), $this->createUrl('customer/delete', array('id' => $data->id)),
array(
// for htmlOptions
'onclick' => ' {' . CHtml::ajax(array(
'beforeSend' => 'js:function(){if(confirm("Are you sure you want to delete?"))return true;else return false;}',
'success' => "js:function(html){ alert('removed'); }")) .
'return false;}', // returning false prevents the default navigation to another url on a new page
'class' => 'delete-icon',
'id' => 'x' . $data->id)
);
?>
This is happening because:
The correct action is not being called, because you have not set the url property of jQuery.ajax(). You should know that Yii's CHtml::ajax is built on top of jQuery's ajax. So you can add :
CHtml::ajax(array(
...
'url'=>$this->createUrl('customer/delete', array('id' => $data->id,'ajax'=>'delete')),
...
))
Also in the url i'm passing an ajax parameter so that the action knows that it's an ajax request explicitly.
Then the controller action by default(i.e Gii generated CRUD) expects the request to be of post type, you can see this in the customer/delete action line:if(Yii::app()->request->isPostRequest){...}. So you have to send a POST request, again modify the ajax options:
CHtml::ajax(array(
...
'type'=>'POST',
'url'=>'',// copy from point 1 above
...
))
Alternatively you can also use CHtml::ajaxLink().
To update the CListView after deletion, call $.fn.yiiListView.update("id_of_the_listview");. Something like:
CHtml::ajax(array(
...
'type'=>'POST',
'url'=>'',// copy from point 1 above
'complete'=>'js:function(jqXHR, textStatus){$.fn.yiiListView.update("mylistview");}'
...
))