php - Generating dynamic dropdown list in Yii? -
i need generate second dropdownlist based on choice of first.
view in _form.php:
<?php echo chtml::dropdownlist('category_id','', category::allcategory(), array( 'ajax' => array( 'type'=>'post', //request type 'url'=>ccontroller::createurl('subcategory/dynamicsubcategories'), //url call. //style: ccontroller::createurl('currentcontroller/methodtocall') 'update'=>'#subcategory_id', //selector update //'data'=>'js:javascript statement' //leave out data key pass form values through ))); //empty since filled other dropdown echo chtml::dropdownlist('subcategory_id','', array()); ?>
also created controler: subcategorycontroller.php
public function actiondynamicsubcategories() { $data = subcategory::model()->findall('category_id=:category_id', array(':category_id' => (int)$_post['category_id'])); $data = chtml::listdata($data, 'id', 'title'); foreach ($data $value => $name) { echo chtml::tag('option', array('value' => $value), chtml::encode($name), true); } }
i registered rules performance of action in same controler: function accessrules
array('allow', // deny users 'actions' => array('dynamicsubcategories'), 'users' => array('@'), ),
the table 'category' has structure: id, title, position , category::allcategory() return:
return chtml::listdata($models, 'id', 'title');
the table 'subcategory' has structure: id, title, category_id.
unfortunately, inquiry carried out in second dropdownlist displayed nothing, prompt made not correctly?
result:
look @ http://www.yiiframework.com/doc/api/1.1/chtml#dropdownlist-detail
, no ajax params, htmloptions. have organize ajax
on change event of select#category_id
:
like that:
<?php echo chtml::dropdownlist('category_id','', category::allcategory(), array('onchange' => 'getsubcategory(this.value)')); ?> <script>function getsubcategory(val) { $.ajax({ type :'post', //request type url : '<?php echo ccontroller::createurl('subcategory/dynamicsubcategories')?>', success : function(data) { $('#subcategory_id').html(data); } };</script>
Comments
Post a Comment