ByteHornet
ByteHornet

Reputation: 390

CakePhp: How to display specific enum values from a list of multiple ones

I want to fetch and display a dropdown of specific enum-values.

for example i have a column named status . with enum values:- 'Open','Read','Progress','Piece','Lift','Coordination','Done','Closed'

I want a method for selecting and showing only the enum value Closed in the dropdown.

I have written a main method to get enum values in App Model as follows.

public function getEnumValues($columnName=null, $respectDefault=false ,$blank =false){
        if ($columnName==null) { return array(); } //no field specified
        //Get the name of the table
        $db = ConnectionManager::getDataSource($this->useDbConfig);
        $tableName = $db->fullTableName($this, false);


        //Get the values for the specified column (database and version specific, needs testing)
        $result = $this->query("SHOW COLUMNS FROM {$tableName} LIKE '{$columnName}'");

        //figure out where in the result our Types are (this varies between mysql versions)
        $types = null;
        if     ( isset( $result[0]['COLUMNS']['Type'] ) ) { $types = $result[0]['COLUMNS']['Type']; $default = $result[0]['COLUMNS']['Default']; } //MySQL 5
        elseif ( isset( $result[0][0]['Type'] ) )         { $types = $result[0][0]['Type']; $default = $result[0][0]['Default']; } //MySQL 4
        else   { return array(); } //types return not accounted for

        //Get the values
        $values = explode("','", preg_replace("/(enum)\('(.+?)'\)/","\\2", $types) );

        if($respectDefault){
            $assoc_values = array("$default"=>Inflector::humanize($default));
            foreach ( $values as $value ) {
                if($value==$default){ 
                    continue; 
                }
                $assoc_values[$value] = __t(Inflector::humanize($value));
           }
        }else{
           $assoc_values = array();
            if($blank){
                $assoc_values[] = '-- انتخاب نشده --'; 
            }
           foreach ( $values as $value ) {
               $assoc_values[$value] = __t(Inflector::humanize($value));
           }
        }
        return $assoc_values;
    } //end getEnumValues

I will be obliged to get a solution for this problem

Upvotes: 0

Views: 3525

Answers (1)

mark
mark

Reputation: 21743

I try to prevent mysql enums as they are not natively supported in CakePHP.

Instead try to use an approach like http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/ using tinyint(2) and simple static model methods to emulate it. It is faster and more dynamic.

Upvotes: 1

Related Questions