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):
-
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.
-
Is a CdB Exception the proper one to throw?
-
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;
}