Now, what might the best approach to mapping these to a dropdown box?
Write an array that uses the keys as the constants referencing the String representation? Or replace the constants with something different altogether such as external class?
I usually write something like the following for that kind of attribute:
class Os extends \yii\db\ActiveRecord
{
/**
* constants for $type attribute
*/
const TYPE_WINDOWS = 1;
const TYPE_WIN_SVR = 2;
const TYPE_LINUX = 3;
const TYPE_OTHER = 9;
/**
* types of the OS and their labels
*/
public static $typeLabels = [
self::TYPE_WINDOWS => 'Windows',
self::TYPE_WIN_SVR => 'Windows Server',
self::TYPE_LINUX => 'LINUX',
self::TYPE_OTHER => 'Other',
];
/**
* @return string the label of the OS type of the current instance
* Use $this->typeLabel in place of $this->type,
* then you'll get 'Windows' when $this->type is 1.
*/
public function getTypeLabel()
{
return ArrayHelper::getValue(self::$typeLabels, $this->type, 'undefined');
}
...
/**
* @inheritdoc
*/
public function rules()
{
return [
...
['type', 'in', 'range' => array_keys(self::$typeLabels)],
...
];
// 'type' should be found in the keys of self::$typeLabels
}
...
}
Maybe I could have created an external class for this attribute, but the idea looked a bit of an overkill to me. Or, I couldn’t think of a simple way to do it.