I have a little problem with a Controller method AJAX call in Yii. The thing is that I'm trying to filter the data of one dropDownList based in the value of a previous selected item.
In the view file, where I figured out is the source of the problem, I have this piece of code:
<?php echo $form->labelEx($model,'Estado'); ?>
<?php echo $form->dropDownList($model,'estado',CHtml::listData(Estado::model()->findAll(),'id','nombre'),array(
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createAbsoluteUrl('buscar/select'),
'update'=>'#'.CHtml::activeId($model,'tbl_municipio_id'),
),
'class'=>'form-control'
));
?>
<?php echo $form->error($model,'Estado'); ?>
On the Controller side, I got this:
public function actionSelect(){
echo "Hello world";
$data = Municipio::model()->findAll('tbl_estado_id=:tbl_estado_id',
array(':tbl_estado_id'=>(int) $_POST['Consultorio_estado']));
$data = CHtml::listData($data,'id','name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
The ajax call to the Select method isn't triggered when the dropDownList is clicked. I tracked the request using Firebug and no error nor fail message is dropped.
Anyone knows what can I do?.
Thanks in advance.
With my knowledge in Yii 1.1.13, there is no such option for ajax for form->dropDownList, just Chtml::dropDownList does.
Therefore you have option to manually custom event change of form->dropDownList or add more jQuery script to handle it by yourself, or simply switch to use Chtml::dropDownList like below example
<?php
echo CHtml::dropDownList('inst_province','',
array(1=>'A',2=>'B',3=>'C', 4=>'D'),
array(
'prompt'=>'Select City',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('city/selectAll'),
'update'=>'#city_area',
'data'=>array('city_param'=>'js:this.value'),
)));
?>
http://www.yiiframework.com/wiki/429/an-easy-solution-for-dependent-dropdownlist-using-ajax/
Related
I came across this problem when I used CHtml::ajaxSubmitButton to submit some of the data as a GET method. No Matter what i try, It always submits data as a POST method.
Anything that I might be doing wrong? Here's my code.
echo CHtml::beginForm(array('shoppingCart/addItem','GET'));
echo CHtml::textField('qty', 1, array('size' => 3));
echo CHtml::hiddenField('product_id', $model->product_id); echo CHtml::ajaxSubmitButton('submit',
array('shoppingCart/addItem'),
array(
'type'=>'GET',
//'data' => array()),
));
echo CHtml::endForm();
Regarding to this document the value of type will be overwritten.
public static function ajaxSubmitButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
{
$ajaxOptions['type']='POST';
$htmlOptions['type']='submit';
return self::ajaxButton($label,$url,$ajaxOptions,$htmlOptions);
}
So there is no way to use GET as long as you do not touch the core function.
That is by design. You can use CHtml::ajaxButton instead:
CHtml::ajaxButton('My Label','controller/action',array(
'type'=>'GET',
), array(
'type'=>'submit',
);
i am new to php,jquery and to programming itself.I have a model called Appoinments .I am calling an ajax query from a text field to a controller action 'appoinments/loaddates'.The ajax query executed correctly. But from the ajax action i want to get some array of variables to the view.Can somebody help me please how to do it?
my view
echo CHtml::activehiddenField($model,'doctor',array(
'onchange'=>CHtml::ajax(array(
'type'=>'POST',
'url'=> CController::createUrl('loadDates'),
'update'=>'#nick_result',
'dataType'=>'json' ,
'select'=>"js:function(event, ui) {
$('#nick_result').val(ui.item.x);
}"
))
));
<div id="nick_result">
</div>
my controller
$arr[] = array(
'x'=>$x, //this I need in view
'y'=>$y,
'z'=>$z,
'p'=>$q,
);
echo CJSON::encode($arr);
how to get the $x value as a variable in php as it is used by the datepicker in my form. Any help appreciated.One thing to notice is that I just need a variable to get updated, not a model attribute. I just want to get that outside of the javascript. Thanks in advance.
To achieve this you need to use ajax callback in your view. For example:
echo CHtml::activehiddenField($model, 'doctor', array(
'onchange'=>CHtml::ajax(array(
'type'=>'POST',
'url'=> CController::createUrl('loadDates'),
'update'=>'#nick_result',
'dataType'=>'json',
'select'=>"js:function(event, ui) { $('#nick_result').val(ui.item.x); }"
'success'=>'js:function(data){
//do here what you want to do. Your json encoded array will be passed as data
}'
))
));
I recommend to use firebug for this, in console you can see what you send to ajax action in your post/get and your ajax callback (data).
Q1 : How to call a function of component from view?
one of my function is using most of the controllers.
public function actionDynamicdepartment()
{
//Department
$data = Department::model()->findAll('p_id=0 AND company_id=:company_id', array(':company_id'=>(int) $_POST['company_id']));
$data = CHtml::listData($data,'id','name');
$dddepatment = "<option value=''>Please select a department</option>";
foreach($data as $value=>$name)
$dddepatment .= CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);
//Section and Team
$ddsection = "<option value=''>Please select a section</option>";
$ddteam = "<option value=''>Please select a team</option>";
// return data (JSON formatted)
echo CJSON::encode(array(
'dddepartment'=>$dddepatment,
'ddsection'=>$ddsection,
'ddteam'=>$ddteam
));
}
I want to put it into component or some place.
And I want to call those function from my views. e.g
<div class="row">
<?php echo $form->labelEx($model,'company_id'); ?>
<?php
$records = Company::model()->findAll();
$company = CHtml::listData($records, 'id', 'name');
echo $form->dropDownList($model,'company_id', $company, array('prompt'=>'Please select a company',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('department/dynamicdepartment'), //url to call.
'dataType'=>'json',
'data'=>array('company_id'=>'js:this.value'),
'success'=>'function(data) {
$("#FaMovehistory_department_id").html(data.dddepartment);
$("#FaMovehistory_section_id").html(data.ddsection);
$("#FaMovehistory_team_id").html(data.ddteam);
}',
)
)
);
?>
</div>
Or
Q2 : put those function at one of the controller (department.php). And can I call those function from different view?
Q3 : if do as Q2, is there any traffic?
What I use to do is to define a CWidget (like Dmitry said) and then I create some functions (I tend to make them static, as if it was a library), so if, for instance, your Widget is called "Departments", you could do something like this:
Yii::import("application.components.Departments");
Departments::actionDynamicdepartment();
Pretty straightforward. You could, for this situation, return that CJson instead of echoing. However, you may not be interested in having a static response from this method.
For your last questions, I tend to approach the population of dropdowns in a more classic manner, having an ajax call (I use jquery) requesting a central controller and passing some variables to it. That, of course, generates traffic.
So, to sum up, if you want to recieve a list of departments and avoid changing it during the current page, you could go for a widget/component. If, on the other side, your dropdown needs to be responsive along with the rest of the items in a form, a controller's action is your best (and probably unique) option.
You need to create a widget instead of component.
Each widget has its own view, and you will be able to describe in its class logic of his behaviour (move the code from the controller) Then call it in the main view:
<?php $this->widget('path.to.your.widget') ?>
Read more: http://www.yiiframework.com/doc/api/1.1/CWidget and http://www.yiiframework.com/doc/guide/1.1/en/basics.view#widget
I have a form that works perfectly. Now, when i add the following code, it throws the jQuery("body").undelegate is not a function error.
<?php
echo CHtml::dropDownList(
'country_id',
'',
array('0'=>'Choice One',
'1'=>'USA',
'2'=>'France',
'3'=>'Japan',),
array(
'ajax'=>array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('users/aTest'),
'success'=>'function(data){alert(data)}',
)));
?>
In UsersController, I have the following action (and it is also included in the accessRules)
public function actionATest()
{
echo "this is a test";
}
When i expand the error, a specific line of code is highlighted (the second one)
jQuery(function($) {
$(".errorDisplay").animate({opacity: 1.0}, 3000).fadeOut("slow");
jQuery('body').undelegate('#country_id','change').delegate('#country_id','change',function(){jQuery.ajax({'type':'POST','url':'/index.php/users/unaPrueba','success':function(data){alert(data)},'cache':false,'data':jQuery(this).parents("form").serialize()});return false;});
Any ideas??? Anybody had this problem? Couldn't find it anywhere!
Check that your jQuery includes aren't conflicting. If you're adding jQuery with your own tag, Yii might still be automatically adding another jQuery file you weren't expecting, as part of its built-in assets (see this question). You can disable Yii's jQuery:
'components'=>array(
'clientScript'=>array(
'scriptMap'=>array(
'jquery.js'=>false,
),
),
)
I created a function in my controller called addToPlaylist($songName). I wanted to add these song names to an array and then a session variable using an Ajax call. The first time i did this i got an error saying i do not have a template file to display in the chosen div ("add_to_playlist.ctp was missing"). I created this file and everything seemed to be working correctly. Basically I went to bed woke up and it is broken (it is possible I changed something before I went to bed). The problem now is that it does not show anything when i click the ajax link. when i click on the ajax link it seems to call the function but nothing displays in the view (except debug info) even when i delete the view (add_to_playlist.ctp) i get no errors, I just see debug info now.
Ajax Link in the View:
echo '<div class="albumName">'. $ajax->link(
'+ add song',
array( 'controller' => 'songs', 'action' => 'addToPlaylist', $song['Song']['name'] ),
array( 'update' => 'playlistInfo')
).'</div></div>';
controller function:
function addToPlaylist($songName = null){
$this->set('name', $songName);
}
Ajax view file:
<html>
<body>
<?php echo name; ?>
</body>
</htmml>
Try echoing the actual variable:
<?php echo $name; ?>