Sunday, September 27, 2009

Adding Enum support to CakePHP

CakePHP have been previously support Enum, but it was removed because Enum is actually MySQL specific datatype.

I really need this feature and so I decided to hack the form helper to support Enum type.
It is basically adding new Enum handler to the input() method of form helper which is used by scaffolding or user custom form.

Here is the patch of [CAKE_ROOT]/cake/libs/view/helpers/form.php file:
582c582
< 
---
>   
613a614,625
>     
>  // enum special handling
>  preg_match('/enum\((.*)\)/i', $type, $matches);
>  if(!empty($matches[1])) {
>    $options['type'] = 'select';
>    $enum_options = explode(',', $matches[1]);
>    $options['options'] = array();
>    foreach($enum_options as $_option) {
>      $option = trim($_option, "\"' ");
>      $options['options'][$option] = $option;
>    }
>  }
624c636
< 
---
>    

Once you patched the file, every Enum fields will be displayed as a HTML select instead of a normal text field. Goodluck!

1 comment: