dependent dropdown

I have removed one parameter from dropdown list and seen firebug html source it doesnt show javascript code that is making ajax call.some more suggestions.I have removed the parameter array(prompt=>select).

Please post here the complete view file… and use the code tags ( <> in the editor toolbar) so that the code is more readable…

I cannot help u much, here is the code of my dependent’s dropdowns, this work perfectly




 <div class="row">

		<?php

		echo CHtml::label('Pais:','paises');

        echo CHtml::dropDownList('paises','', CHtml::listData(Pais::model()->findAll(),'id','nom'),

        array(

        'ajax' => array(

        'type'=>'POST',

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

        'update'=>'#provincias', 

        )));

        ?>

    </div>

 	<div class="row">

        <?php

		echo CHtml::label('Provincia:','provincias'); 

		echo CHtml::dropDownList('provincias','',CHtml::listData(Provincia::model()->findAll(),'id','nom'),

		array(

		'ajax' => array(

		'type' => 'POST',

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

		'update' => '#Persona_poblacio',

		)));

        ?>        

    </div>

    <div class="row">

    	<?php echo $form->labelEx($model,'poblacio'); ?>

        <?php echo $form->dropDownList($model,'poblacio',CHtml::listData(Poblacio::model()->findAll(),'id','nom'));?>

    </div>



Grettings,

s0mk3t

view file




<div class="form">


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

	'id'=>'productsubsubcategory-form',

	'enableAjaxValidation'=>true,

)); ?>


	<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,'category'); ?>

                <?php

                  $productCategoriesArray = CHtml::listData(Productcategory::model()->findAll(),'id','category');

                   echo $form->DropDownList($model,'cat_id',$productCategoriesArray,

                            array(

                                'ajax' => array(

                                'type' => 'POST',

                                'url' => CController::createUrl('productsubsubcategory/DynamicSubcategory'),

                                'update' => '#'.CHtml::activeId($model,'subcat2_id'))));




            ?>


              <?php echo $form->error($model,'cat_id'); ?>

        </div>

              <div class="row">


               <?php echo $form->labelEx($model,'subcategory'); ?>




       <?php  echo $form->dropDownList($model,'subcat2_id',CHtml::listData(Productsubcategory::model()->findAll(),'subcategory','subcategory'),array('prompt'=>'--select--') );	 ?>




              <?php echo $form->error($model,'subcat2_id'); ?>

        </div>




	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


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


</div><!-- form -->



controller code:




<?php


class ProductsubsubcategoryController extends Controller

{

        /**

         * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

         * using two-column layout. See 'protected/views/layouts/column2.php'.

         */

        public $layout='//layouts/column2';


        /**

         * @var CActiveRecord the currently loaded data model instance.

         */

        private $_model;


        /**

         * @return array action filters

         */

        public function filters()

        {

                return array(

                        'accessControl', // perform access control for CRUD operations

                );

        }


        public function accessRules()

        {





                return array(

                        array('allow',  // allow admin users to perform 'index' and 'view' actions

                                'actions'=>array('index','view'),


                        ),

                        array('allow', // allow super users to perform 'create' and 'update' actions

                                'actions'=>array('create','update','dynamicSubcategory'),


                        ),

                        array('allow', // allow super user to perform 'admin' and 'delete' actions

                                'actions'=>array('admin','delete'),


                        ),

                        array('deny',  // deny all users

                                'users'=>array('*'),

                        ),

                );

        }


         public function actionDynamicSubcategory()

          {

            $cat_id = $_POST['Productsubsubcategory']['cat_id'];

            $data=Productsubcategory::model()->findAll('cat_id=:cat_id',

                    array(':cat_id'=> $cat_id));


            $data=CHtml::listData($data,'id','subcategory');

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

                echo CHtml::tag('option',

                   array('value'=>$value),CHtml::encode($subcategory),true);

            }

        }


        /**

         * Displays a particular model.

         */

        public function actionView()

        {

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

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

                ));

        }


        /**

         * Creates a new model.

         * If creation is successful, the browser will be redirected to the 'view' page.

         */

        public function actionCreate()

        {

                $model=new Productsubsubcategory;


                // Uncomment the following line if AJAX validation is needed

                $this->performAjaxValidation($model);




                if(isset($_POST['Productsubsubcategory']))

                {

                        $model->attributes=$_POST['Productsubsubcategory'];




                        if($model->save())

                                $this->redirect(array('view','id'=>$model->id));

                }




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

                        'model'=>$model,

                ));

        }


        /**

         * Updates a particular model.

         * If update is successful, the browser will be redirected to the 'view' page.

         */

        public function actionUpdate()

        {

                $model=$this->loadModel();


                // Uncomment the following line if AJAX validation is needed

                $this->performAjaxValidation($model);


                if(isset($_POST['Productsubsubcategory']))

                {

                        $model->attributes=$_POST['Productsubsubcategory'];

                        if($model->save())

                                $this->redirect(array('view','id'=>$model->id));

                }


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

                        'model'=>$model,

                ));

        }


        /**

         * Lists all models.

         */

        public function actionIndex()

        {

                $dataProvider=new CActiveDataProvider('Productsubsubcategory');

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

                        'dataProvider'=>$dataProvider,

                ));

        }


        /**

         * Manages all models.

         */

        public function actionAdmin()

        {

                $model=new Productsubsubcategory('search');

                $model->unsetAttributes();  // clear any default values

                if(isset($_GET['Productsubsubcategory']))

                        $model->attributes=$_GET['Productsubsubcategory'];


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

                        'model'=>$model,

                ));

        }


        /**

         * Returns the data model based on the primary key given in the GET variable.

         * If the data model is not found, an HTTP exception will be raised.

         */

        public function loadModel()

        {

                if($this->_model===null)

                {

                        if(isset($_GET['id']))

                                $this->_model=Productsubsubcategory::model()->findbyPk($_GET['id']);

                        if($this->_model===null)

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

                }

                return $this->_model;

        }


        /**

         * Performs the AJAX validation.

         * @param CModel the model to be validated

         */

        protected function performAjaxValidation($model)

        {

                if(isset($_POST['ajax']) && $_POST['ajax']==='productsubsubcategory-form')

                {

                      //$model->selected_catID = $model->cat_id;

                        echo CActiveForm::validate($model);

                        Yii::app()->end();

                }

        }

}



please help me

The code seems OK now… it should work… have you checked that javascript is enabled?

when you select a new value in the first dropdown (category) you should see in firebug the call to dynamicSubcategory

thanks mdomba its working for me now.

Could you post your code for ‘controller’ ? Thanks.

thanks mdomba for your valuable suggestions which made my code working.I tried that example with 3 tables.

If i have 2 tables called

tbl_country(id,name)

tbl_state(id,statename,countryid)

and i placed the below code in my state view and controller




 <div class="row">

                <?php echo $form->labelEx($model,'country'); ?>

                <?php

                  $countryArray = CHtml::listData(country::model()->findAll(),'id','name');

                   echo $form->DropDownList($model,'id',$countryArray,

                            array(

                                'ajax' => array(

                                'type' => 'POST',

                                'url' => CController::createUrl('state/DynamicStates'),

                                'update' => '#'.CHtml::activeId($model,'countryid'))));




            ?>


              <?php echo $form->error($model,'name'); ?>

        </div>

              <div class="row">


               <?php echo $form->labelEx($model,'statename'); ?>




       <?php  echo $form->dropDownList($model,'countryid',CHtml::listData(state::model()->findAll(),'statename','statename'),array('prompt'=>'--select--') );	 ?>




              <?php echo $form->error($model,'countryid'); ?>

        </div>






 public function actionDynamicStates()

          {

            $ct = $_POST['state']['id'];

            $data=state::model()->findAll('id=:id',

                    array(':id'=> $ct));


            $data=CHtml::listData($data,'id','statename');

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

                echo CHtml::tag('option',

                   array('value'=>$value),CHtml::encode($statename),true);

            }

        }



when i run the above and select a dropdown nothing is happening in the state dropdown.Is there any mistake in the code or i have to add another table for it to work as the previous example of categories.

This is stil 2 dropdowns… and the code is like the previous one… so it seems fine…

you need to degub a bit… check it with firebug to see if the ajax call is made… and what is returned…

my controller code




public function actionDProvincias()

    {

        $data = Provincia::model()->findAll('id_pais=:parent_id',

                        array(':parent_id'=>(int) $_POST['paises']));

 

 

        $data = CHtml::listData($data,'id','nom');

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

            {

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

            }

 

    }

 

    public function actionDPoblaciones()

    {

        $data = Poblacio::model()->findAll('id_provincia=:parent_id',

                        array(':parent_id'=>(int) $_POST['provincias']));

 

        $data = CHtml::listData($data,'id','nom');

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

            {

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

            }

    }



i made it run with firebug and it says 500 php error.It is showing undefined index in the controller code

$ct = $_POST[‘state’][‘id’];

so any modifications to be done here.

compared to previous example of mine i have used only two tables here so any changes to be done

thanks

i have two tables country(id,name) and state(id1,statename,countryid(foreignkey referring id of first table).

_form.php




 <div class="row">

                <?php echo $form->labelEx($model,'country'); ?>

                <?php

                  $countryArray = CHtml::listData(country::model()->findAll(),'id','name');

                   echo $form->DropDownList($model,'id1',$countryArray,

                            array(

                                'ajax' => array(

                                'type' => 'POST',

                                'url' => CController::createUrl('State/DynamicStates'),

                                'update' => '#'.CHtml::activeId($model,'countryid'))));




            ?>


              <?php echo $form->error($model,'name'); ?>

        </div>

              <div class="row">


               <?php echo $form->labelEx($model,'statename'); ?>




       <?php  echo $form->dropDownList($model,'countryid',CHtml::listData(state::model()->findAll(),'statename','statename'),array('prompt'=>'--select--') );	 ?>




              <?php echo $form->error($model,'countryid'); ?>

        </div>




controller code:




<?php


class StateController extends Controller

{

        /**

         * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

         * using two-column layout. See 'protected/views/layouts/column2.php'.

         */

        public $layout='//layouts/column2';


        /**

         * @var CActiveRecord the currently loaded data model instance.

         */

        private $_model;


        /**

         * @return array action filters

         */

        public function filters()

        {

                return array(

                        'accessControl', // perform access control for CRUD operations

                );

        }


        public function accessRules()

        {





                return array(

                        array('allow',  // allow admin users to perform 'index' and 'view' actions

                                'actions'=>array('index','view'),


                        ),

                        array('allow', // allow super users to perform 'create' and 'update' actions

                                'actions'=>array('create','update','DynamicStates'),


                        ),

                        array('allow', // allow super user to perform 'admin' and 'delete' actions

                                'actions'=>array('admin','delete'),


                        ),

                        array('deny',  // deny all users

                                'users'=>array('*'),

                        ),

                );

        }


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	 public function actionView()

        {

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

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

                ));

        }


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

        {

                $model=new State;


                // Uncomment the following line if AJAX validation is needed

                $this->performAjaxValidation($model);




                if(isset($_POST['state']))

                {

                        $model->attributes=$_POST['state'];




                        if($model->save())

                                $this->redirect(array('view','id1'=>$model->id1));

                }




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

                        'model'=>$model,

                ));

        }

          public function actionDynamicStates()

          {

            $ct = $_POST['state']['id1'];

            $data=state::model()->findAll('id=:id',

                    array(':id'=> $ct));


            $data=CHtml::listData($data,'id1','statename');

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

                echo CHtml::tag('option',

                   array('value'=>$value),CHtml::encode($statename),true);

            }

        }

	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 */

	 public function actionUpdate()

        {

                $model=$this->loadModel();


                // Uncomment the following line if AJAX validation is needed

                $this->performAjaxValidation($model);


                if(isset($_POST['State']))

                {

                        $model->attributes=$_POST['State'];

                        if($model->save())

                                $this->redirect(array('view','id1'=>$model->id1));

                }


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

                        'model'=>$model,

                ));

        }


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'index' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	/*public function actionDelete($id)

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

			$this->loadModel($id)->delete();


			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

			if(!isset($_GET['ajax']))

				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}

     */


	  /**

         * Lists all models.

         */

	 public function actionIndex()

        {

                $dataProvider=new CActiveDataProvider('State');

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

                        'dataProvider'=>$dataProvider,

                ));

        }


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

        {

                $model=new State('search');

                $model->unsetAttributes();  // clear any default values

                if(isset($_GET['State']))

                        $model->attributes=$_GET['State'];


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

                        'model'=>$model,

                ));

        }


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer the ID of the model to be loaded

	 */

	 public function loadModel()

        {

                if($this->_model===null)

                {

                        if(isset($_GET['id1']))

                                $this->_model=State::model()->findbyPk($_GET['id1']);

                        if($this->_model===null)

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

                }

                return $this->_model;

        }


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	 protected function performAjaxValidation($model)

        {

                if(isset($_POST['ajax']) && $_POST['ajax']==='state-form')

                {

                      //$model->selected_catID = $model->cat_id;

                        echo CActiveForm::validate($model);

                        Yii::app()->end();

                }

        }

}



when i run this code and select an item in first dropdown respective states are not populated and firebug console says 500 php error.in controller where i defined dynamicstates ’ $ct = $_POST[‘state’][‘id1’];’ it tells state is an undefined index.Anyone please help me

@nalaja… what is the point of your post #31… you quoted your post and wrote the exact same text ???

and again posting all your view and controller… you are abusing this thread…

I already wrote you once… if you have a problem… you can ask for help… but you cannot expect that someone will write the code instead of you…

you are posting here all your code so that someone can find your errors ???

You got all the help for the first example and made it working… so now study it… understand it… and there will be no problem to make a second example…

Both examples are the same to me… but you are confusing some points here

I don’t understand what you want to do here… but I think you too don’t understand that…

The first dropdown has the label “Country” and then you are entering the value to $model->id1, but that is the primary key of the state table ???

The second dropdown has the label “statename” but here you are entering $model->countrid ???

Again… don’t expect that anybody will degug your code… if you get the error “undefined index” and it gives you the line where that error is… you need to find out what is the problem… debug a bit… echo some value… find what is wrong and repair it… do not overuse the forum…

I agree. We want to help you, really. But it already seems that what you want is spoon-feeding, which is not very healthy. That’s just my impression, so I might be wrong.

At any rate, try to find some of the answers yourself. Somehow it’s a satisfying act :) If you’re out of resources and all that’s left to do is ask, then ask. Just don’t make us debug your codes. That’s too much.

Hi,

I have used the dependent dropdown and it is working fine. However, the value of the second dropdown is not preserved on page refresh. Any ideas, how to preserve the value of the second dropdown.

Thanks,