ENUM DB type in Yii

If you use MySQL SETs, you might find setItem useful. It does require enumItem by Zaccaria, in the posts above.

Suggestions are welcome.




		public static function setItem($model, $attribute)

	{

    	$options = array_keys(self::enumItem($model, $attribute));


    	$values = array();

    	// $options has all possible values, but not yet the combinations.

    	$values[] = '';

    	for ($i = 0; $i < count($options); $i++)

    	{

        	$element = $options[$i];

        	$values[$element] = $element;

        	self::traverseItems($i + 1, $options, $element, $values);

    	}

    	$element = implode(",", $options);

    	$values[$element] = $element;

    	return $values;

	}


	private static function traverseItems($start, $options, &$element, array &$values)

	{

    	$copy = $element;

    	for ($j = $start; $j < count($options); $j++)

    	{

        	$element = $element . "," . $options[$j];

        	$values[$element] = $element;

        	self::traverseItems($j + 1, $options, $element, $values);

        	$element= $copy;

    	}

	}



enumItem in case you don’t want to scrollup (made by Zaccaria, not made by me)




	public static function enumItem($model, $attribute)

	{

    	$matches = $values = array();


    	$attr = $attribute;

    	CHtml::resolveName($model, $attr);

    	preg_match('/\((.*)\)/', $model->tableSchema->columns[$attr]->dbType, $matches);

    	foreach (explode(',', $matches[1]) as $value)

    	{

        	$value = str_replace("'", null, $value);

        	$values[$value] = Yii::t('enumItem', $value);

    	}


    	return $values;

	}

Has anyone worked out a way to return the results ordered alphabetically?

Cheers!

Sort the results:




  public static function enumItem($model, $attribute)

	{

    	$matches = $values = array();


    	$attr = $attribute;

    	CHtml::resolveName($model, $attr);

    	preg_match('/\((.*)\)/', $model->tableSchema->columns[$attr]->dbType, $matches);

    	foreach (explode(',', $matches[1]) as $value)

    	{

        	$value = str_replace("'", null, $value);

        	$values[$value] = Yii::t('enumItem', $value);

    	}


    	asort($values);


    	return $values;

	}



Haha, such a n00b i am… dont know why I didnt think of that.

thanks!

This discuss solved all enum data type issues I have.

Very helpful, thanks a lot. :)

Nice solution, Zaccaria! Thanks!