Optgroup Label from Relation

Hi Guys,

I have a table like so:

Products




++++++++++++++++++++++++++++++++++++++++++++

|     id       |       name     |  type    |

++++++++++++++++++++++++++++++++++++++++++++

|       1      |     Mars       |     1    |

++++++++++++++++++++++++++++++++++++++++++++

|       2      |     Snickers   |     1    |

++++++++++++++++++++++++++++++++++++++++++++

|       3      |     Cola       |     2    |

++++++++++++++++++++++++++++++++++++++++++++



I have another table like so:

Types




+++++++++++++++++++++++++++++++++

|     id       |       name     |

+++++++++++++++++++++++++++++++++

|       1      |     Sweet      |

+++++++++++++++++++++++++++++++++

|       2      |     Drinks     |

+++++++++++++++++++++++++++++++++



I am using the following code to generate a dropdown list with grouping.


CHtml::listData(Products::model()->findAll(array('condition'=>'stock_method<>3')), 'id', 'name','type')

The issue is that the options are grouped by a number rather than the type name. Is it possible to use a relationship or another find in order to show the name from the type table rather than the number in the products table?

One option is to add a property to the Products model:




public function getTypeName()

{

    return $this->type !== null ? $this->type->name : '';

}



then your code would become:




CHtml::listData(Products::model()->findAll(array('condition'=>'stock_method<>3')), 'id', 'name','typeName')



Actually, you can now use anonymous functions according to the docs, so if you’re using PHP 5.3+ and Yii 1.1.13+, instead of adding an extra property, you should be able to just do this:




CHtml::listData(Products::model()->findAll(array('condition'=>'stock_method<>3')), 'id', 'name', function($model){

    return $model->type !== null ? $model->type->name : '';

})



Works like a dream. Many thanks for taking them time to respond, it is much appreciated.