Feedback: I added a member function to CActiveRecord

I found myself writing a number of forms that needed a basic dropDownList populated with data from a table. Just a simple array of id=>name. So, I created a member function of CActiveRecord that takes in two attribute names and returns an array of pairs of those attribute names for every record in the table.

I’m not a seasoned / experience developer, so I’d love to get some feedback on this implementation. Here are my questions (code below):

  1. Best practices: Should this be a static function? It seems like it should to me, but within Yii it there is the static model instatiation (ClassName::model()) so I’m not sure if this is necessary. However, there may be a memory/performance-related requirement for this.

  2. Is a CdB Exception the proper one to throw?

  3. Any other tips you can see from my code?

Thanks!


public function getAttributePairs($attribute1, $attribute2)

        {

            $returnArray = array();

            $modelArray = array();

            $modelAttributes = array_keys($this->getAttributes());




            // Ensure attributes are in class:

            if(in_array($attribute1,$modelAttributes) && in_array($attribute2, $modelAttributes))

            {

                $modelArray = $this->findAll();


                foreach($modelArray as $model)

                {

                    $returnArray[$model->getAttribute($attribute1)] = $model->getAttribute($attribute2);

                }


            }

            else

                throw new CDbException(Yii::t('yii','{class} does not have attribute "{name1}" or "{name2}".',

				array('{class}'=>get_class($this), '{name1}'=>$attribute1,'{name2}'=>$attribute2)));


            return $returnArray;

        }

By the way, this is how it is used:


<div class="row">

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

		<?php echo $form->dropDownList($model,'country_id',Country::model()->getAttributePairs('id','name')); ?>

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

	</div>

Hi,

There is already a function for this scenario: http://www.yiiframework.com/doc/api/1.1/CHtml#listData-detail

Used like this:




<div class="row">

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

            <?php echo $form->dropDownList($model, 'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?>

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

        </div>



Cheers,

Matt

Hah! Thanks! Oh, well, it was fun to try and extend CActiveRecord anyway.

Yeah, you had the right idea though: static function that returns an associative array.