Baked enum fields reloaded

By gino pilotino (gunzip)
I had the need to convert (mysql) enum fields into form selects once baked with the cake console. This method worked for me with minimal changes to the infrastructure.
Place this into your app/app_controller.php and you will notice that all the enum(s) are converted into select fields in baked views.

Controller Class:

Download code <?php 
class AppController extends Controller {

  function 
beforeRender() {
    foreach(
$this->modelNames as $model) {
      foreach(
$this->$model->_schema as $var => $field) {
        if(
strpos($field['type'], 'enum') === FALSE)
          continue;

        
preg_match_all("/\'([^\']+)\'/"$field['type'], $strEnum);

        if(
is_array($strEnum[1])) {
          
$varName Inflector::camelize(Inflector::pluralize($var));
          
$varName[0] = strtolower($varName[0]);
          
$this->set($varNamearray_combine($strEnum[1], $strEnum[1]));
        }
      }
    }
  }

}

?>


This works for mysql (don't know about other dbms) and it's based on the assumption that
setting a variable array with the same name of the enum field in the view will convert the free text
input into a select.

 

Comments 767

CakePHP Team Comments Author Comments
 

Comment

1 great

Simple and definitly useful.
I'm an old enum-fan because it makes life easier if you skimm tables ;-)
Posted Sep 2, 2008 by Klaus Brantl
 

Comment

2 Release RC3 issue

Seems like the latest release (RC3) breaks this fine piece of code if you have the same field name in several tables. Ex. I have the "status" field in both accounts and logs, if I include logs in $uses the status field on accounts is overwritten by the status field on logs.

Hope one of you clever guys can fix the code :)

Thumbs up !
Posted Nov 2, 2008 by Mikey
 

Comment

3 you're right

You're right, you cannot use this if you have two fields with the same name and i don't think there's a simple solution to this (one would be to use a variable name like Model.names but this doesn't work in the core so i see no way, sorry :)

Seems like the latest release (RC3) breaks this fine piece of code if you have the same field name in several tables. Ex. I have the "status" field in both accounts and logs, if I include logs in $uses the status field on accounts is overwritten by the status field on logs.

Hope one of you clever guys can fix the code :)

Thumbs up !
Posted Nov 4, 2008 by gino pilotino