Problem Dependent Dropdown

Hello everyone,

I’ve been struggling with the implementation of the dependent dropdown solution and alto I have been following the wiki article and various forum posts, I don’t seem to be able to create the desired result.

The code that i have at the moment.

SystemControllers.php


<?php


class SystemPermissionsController extends SystemController {


    public function actionIndex() {

        $data['permissions'] = SystemPermissions::model()->findAll();

        $this->render('index', $data);

    }


    public function actionView($id) {

        $this->render('view', array(

            'model' => $this->loadModel($id),

        ));

    }


    public function actionCreate() {

        $data['model'] = new SystemPermissions;

        // adding data to view -----------------------------------------------//

        $data['status'] = array(SystemPermissions::ACTIVE => Yii::t('gui', 'active'), SystemPermissions::INACTIVE => Yii::t('gui', 'inactive'));

        $data['roles'] = SystemRoles::model()->findAll();

        $data['modules'] = SystemModules::model()->findAll();

        // if post is used ---------------------------------------------------//

        if (isset($_POST['SystemPermissions'])) {

            // transfer attributes -------------------------------------------//

            $data['model']->attributes = $_POST['SystemPermissions'];

            // validate ------------------------------------------------------//

            if ($data['model']->validate()) {

                try {

                    // Save --------------------------------------------------//

                    $data['model']->save();

                    // setFlash ----------------------------------------------//

                    Yii::app()->user->setFlash('success', Yii::t('gui', 'successPermissionCreate'));

                    // redirect to dashboard, dash can handle it further -----//

                    $this->redirect('/' . $this->getModule()->getId() . '/' . $this->getId() . '/index');

                } catch (Exception $e) {

                    // setFlash ----------------------------------------------//

                    Yii::app()->user->setFlash('error', Yii::t('gui', 'errorFailedSavePermission'));

                }

            } else {

                // setFlash --------------------------------------------------//

                Yii::app()->user->setFlash('error', Yii::t('gui', 'errorValidationPermission'));

            }

        }

        // render ------------------------------------------------------------//

        $this->render('create', $data);

    }


    public function actionUpdate($id) {

        $data['model'] = $this->loadModel($id);

        // adding data to view -----------------------------------------------//

        $data['status'] = array(SystemPermissions::ACTIVE => Yii::t('gui', 'active'), SystemPermissions::INACTIVE => Yii::t('gui', 'inactive'));

        $data['roles'] = SystemRoles::model()->findAll();

        $data['modules'] = SystemModules::model()->findAll();

        // restructure companies and roles so checkboxes love ----------------//

        $temp = array();

        foreach ($data['model']->systemRoles as $r) {

            $temp[$r['roleId']] = $r['roleId'];

        }

        $data['model']->systemRoles = $temp;

        // if post is used ---------------------------------------------------//

        if (isset($_POST['SystemPermissions'])) {

            // transfer attributes -------------------------------------------//

            $data['model']->attributes = $_POST['SystemPermissions'];

            // validate ------------------------------------------------------//

            if ($data['model']->validate()) {

                try {

                    // Save --------------------------------------------------//

                    $data['model']->save();

                    // tabular input -----------------------------------------//

                    if (isset($_POST['SystemPermissions']['systemRoles'])) {

                        // dump post to var ----------------------------------//

                        $items = $_POST['SystemPermissions']['systemRoles'];

                        // fetching all the related companies from linktable -//

                        $relatedRoles = SystemRolePermission::model()->findAll('roleIdFk=:rId', array(':rId'=>$data['model']['roleId']));

                        //delete all easy way out unfortunantly --------------//

                        foreach($relatedRoles as $c){

                            // try catch to prevent errors -------------------//

                            try {

                                $c->delete(false);

                            } catch (Exception $e){}

                        }

                        // recreate links where needed -----------------------//

                        if($items){

                            foreach($items as $key => $value){

                                // try catch to prevent errors ---------------//

                                try {

                                    // new model -----------------------------//

                                    $r = new SystemRolePermission;

                                    $r['roleIdFk'] = $value;

                                    $r['permissionIdFk'] = $data['model']['accountId'];

                                    $r->save(false);


                                } catch (Exception $e){}

                            }

                        }

                        

                    }

                    // setFlash ----------------------------------------------//

                    Yii::app()->user->setFlash('success', Yii::t('gui', 'successPermissionUpdate'));

                    // redirect to dashboard, dash can handle it further -----//

                    $this->redirect('/' . $this->getModule()->getId() . '/' . $this->getId() . '/index');

                } catch (Exception $e) {

                    // setFlash ----------------------------------------------//

                    Yii::app()->user->setFlash('error', Yii::t('gui', 'errorFailedSavePermission'));

                }

            } else {

                // setFlash --------------------------------------------------//

                Yii::app()->user->setFlash('error', Yii::t('gui', 'errorValidationPermission'));

            }

        }

        // render ------------------------------------------------------------//

        $this->render('update', $data);

    }


    public function loadModel($id) {

        $model = SystemPermissions::model()->findByPk($id);

        if ($model === null)

            throw new CHttpException(404, 'The requested page does not exist.');

        return $model;

    }

    

    public function actionTestLoad(){

        $data = SystemControllers::model()->active()->findAll('moduleIdFk=:mId', array(':mId' => (int) $_POST['moduleIdFk']));

        

        $data = CHtml::listData($data, 'controllerId', 'controllerName');

        foreach ($data as $value => $name) {

            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);

        }

    }



partials/form.php


<?php

$form = $this->beginWidget('CActiveForm', array(

    'id' => 'system-permissions-form',

    'htmlOptions' => array('class' => 'form-horizontal'),

    'enableAjaxValidation' => true,

        ));

?>


<div class="control-group ">

    <label class="control-label equired" ><?php echo Yii::t('models', 'permissionName'); ?> <span class="required">*</span></label>

    <div class="controls">

        <?php echo CHtml::activeTextField($model, 'permissionName', array('class' => 'span5', 'maxlength' => 128)); ?>

        <span class="help-inline">.</span>

    </div>

</div>


<div class="control-group ">

    <label class="control-label required"> <?php echo Yii::t('models', 'permissionStatus'); ?>  <span class="required">*</span></label>

    <div class="controls">

        <?php echo CHtml::activeDropDownList($model, 'permissionStatus', $status, array('class' => 'span5')); ?>

        <span class="help-inline">.</span>

    </div>

</div>


<div class="control-group ">

    <label class="control-label required"> <?php echo Yii::t('models', 'moduleName'); ?>  <span class="required">*</span></label>

    <div class="controls">

        <?php

        echo CHtml::activeDropDownList($model, 'moduleIdFk', CHtml::listData($modules, 'moduleId', 'moduleName'), array(

            'ajax' => array(

                'type' => 'POST', //request type

                'url' => CController::createUrl('testLoad'),

                'update' => CHtml::activeId($model, 'controllerIdFk'), //selector to update

        )));

        ?>

        <span class="help-inline">.</span>

    </div>

</div>


<div class="control-group ">

    <label class="control-label required"> <?php echo Yii::t('models', 'controllerName'); ?>  <span class="required">*</span></label>

    <div class="controls">

        <?php echo CHtml::activeDropDownList($model, 'controllerIdFk', array(), array('class' => 'span5')); ?>

        <span class="help-inline">.</span>

    </div>

</div>


<div class="control-group ">

    <label class="control-label required"> <?php echo Yii::t('models', 'actionName'); ?>  <span class="required">*</span></label>

    <div class="controls">

        <?php echo CHtml::activeDropDownList($model, 'actionIdFk', array(), array('class' => 'span5')); ?>

        <span class="help-inline">.</span>

    </div>

</div>


<div class="control-group ">

    <label class="control-label required"> <?php echo Yii::t('gui', 'rolesWithPermission'); ?></label>

    <div class="controls">

        <label class="checkbox">

            <?php echo CHtml::activeCheckboxList($model, 'systemRoles', CHtml::listData($roles, 'roleId', 'roleName')); ?>

        </label>

    </div>

</div> 


<div class="form-actions">

    <?php echo CHtml::submitButton(Yii::t('gui', 'save'), array('class' => 'btn btn-primary')); ?>

</div>


<?php $this->endWidget(); ?>

The form.php is a general form for both the update and the create functions as followed:


<?php $this->widget('application.widgets.TitleWidget', array('title' => Yii::t('gui', 'titlePermissions'))); ?>


<div class="innerLR">

    <div class="widget">


        <!-- Widget heading -->

        <div class="widget-head">

    <h4 class="heading"><?php echo yii::t('gui', 'titleCreatePermission'); ?></h4>

        </div>

        <!-- // Widget heading END -->


        <div class="widget-body">


            <?php echo $this->renderPartial('partials/form', array('model' => $model, 'status'=>$status, 'roles'=>$roles, 'modules'=>$modules)); ?>


        </div>

        <div class="widget-footer">

        </div>

    </div>

</div>

I think it is because of the renderPartial that the dependent dropdown doesn’t preform as desired, whatever values I retrieve for the module, isn’t translated to the controller dropdown although i do have gotten values for both.

Any advice and help is much appreciated!

Hi,

Please follow the link … it should work

http://www.yiiframework.com/wiki/429/an-easy-solution-for-dependent-dropdownlist-using-ajax/

http://www.yiiframework.com/wiki/24/

If still not working just attach screenshot to show where u have stumped.

Thanks

chandran nepolean

I have tried both tutorials, even with exactly the same code it doesn’t work, even with a JSON encode approach I didn’t get any result the second dropdown stays empty upon the selection of a value in the first. $_post and others don’t return a single thing named like the thing I have.

Doesn anyone have the same problem? Or maybe a working exemple en code perhaps?

Thank

this is a screenshot of the page i’m trying to build with the dependent dropdownlist but to no avail. I starting to thing that the renderPartial doesn’t work right or that I have missed a configuration option of the form or the application or even that i forgot to include a script. It might also be the post value but when dumping the post i don’t see the specific variable so why isn’t ajax invoiking the code?

Working code:

_form.php:


<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(

	'id'=>'additem-form',

	'type'=>'horizontal',

));?>


<?php echo CHtml::dropDownList('service_id','', CHtml::listData($catlist,'id','name'),

	array(

		'prompt'=>'Service Category',

		'class'=>'input-medium',

		'ajax' => array(

			'type'=>'POST', //request type

			'url'=>CController::createUrl('controller-name/dynamicservices'), //url to call.

			'update'=>'#pricebookitem_id', //selector to update

			)

		));

	echo CHtml::dropDownList('pricebookitem_id','',array(),array('prompt'=>'Service','class'=>'input-medium',));

?>

<?php $this->endWidget(); ?>

Controller:


public function actiontest()

{

	$catlist=PricebookServicesTypes::model()->findAll(array('order'=>'name')); //service list details


	$this->render('_form',array(

		'catlist'=>$catlist,

	));

} 

public function actionDynamicServices()

{

	$data=PricebookItems::model()->findAll('service_type_id=:service_id',array(':service_id'=>$_POST['service_id']));

	$data=CHtml::listdata($data,'id','service');

	foreach($data as $value=>$name)

	{

		echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);

	}

}

Tables:


CREATE TABLE IF NOT EXISTS `pricebook_items` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `code` varchar(10) NOT NULL,

  `service` varchar(128) NOT NULL,

  `service_type_id` int(2) NOT NULL,

  PRIMARY KEY (`id`),

  KEY `service_type_id` (`service_type_id`),

) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=66 ;


INSERT INTO `pricebook_items` (`id`, `code`, `service`, `service_type_id`,) VALUES

(1, 'CS', 'Consultation - Specialist', 1),

(2, 'CSS', 'Consultation - Super Specialist', 1),

(3, 'BL', 'Braces Lingual', 2),

(4, 'BM', 'Braces Metallic', 2),

(5, 'FS', 'FollowUp - Specialist', 1),

(6, 'BC', 'Braces Ceramic', 2),

(7, 'RCT', 'Root Canal Treatment', 2),

(8, 'FSS', 'FollowUp - Super Specialist', 10),

(9, 'CSc', 'Citi Scan', 3),

(10,'TE', 'Tooth Extraction', 2),

(11,'RCT', 'Root Canal Treatment', 2),

(12,'MSc', 'MRI Scan', 3);

Create the model class for the table and use it.

Thank you for the code example it helped me to understand a some of the things but still the code refuses the request. Now I have been looking with firebug and firefox webdeveloper and the problem that seems to exist is that the POST operation isn’t triggered for some reason.

The code I used is slightly different meaning I tried it with the default widget Yii provides and even followed the code provided by chiragChetan and the wiki article but still I’m stuck:

the following video has a working code exemple which I also tried (watch out it’s in spanish) http://www.youtube.com/watch?v=NZDpTHtRp1s but it helped for a few things nicely.

So my question now remains why doesn’t ajax wants to execute a POST request and follow the provided url?

Thank