Tuesday, September 18, 2012

YII: How to create a dropdown list with database information

I need to create a dropdown list from a database table data.

Here is an example that I created for displaying school quarter information.

You can use this in the /view folder _form.php file.
e.g. /view/season/_form.php 

<div class="row">
        <?php  /*  Display label */ 

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

                        /* Retrieve data - select QuarterID, Year, Season; ordered by QuarterID DESC */
                        $Qmodels = Quarter::model()->findAll(array('select'=>'QuarterID, Year, Season','order'=>'QuarterID DESC'));
                        $data = array();

                        /* Used array to rename the season name to something more clear */
                        $season    = array(1=>'Winter','Fall','Summer','Spring');
                       
                        foreach ($Qmodels as $Qmodel)
                            $data[$Qmodel->QuarterID] = $Qmodel->Year . ' '. $season[$Qmodel->Season];   ?>
                <?php 

                      /* Display "Select Quarter" by default */
                      echo $form->dropDownList($model,'QuarterID',$data, array('empty'=>'Select Quarter')) ;?>
        <?php echo $form->error($model,'QuarterID'); ?>
    </div>



Here is an another example from yiiframework.com.  It is a simple and good example.
http://www.yiiframework.com/forum/index.php/topic/601-how-to-populate-a-dropdown-list-with-database-data/

 $qAlbums=Album::model()->findAll($criteria);

                

                $albums = array();

                foreach($qAlbums as $p)

                {

                        $albums[$p->AlId] = $p->AlDescr;

                }

                return $albums;



and then give $albums as parameter to 
 
$form->dropDownList($model, 'attribute', $albums); 
 

No comments: