Model Field Names

Posted on 10/21/09 by Rob Conner
Sometimes I've needed to get a list of fields that a Model's table has. This is a little function that I have in my AppModel just to make getting the list of fields easy.

Dont forget, if you just want to know about one field, you can use the already builtin Model->hasField($name)
Code:
<?php class AppModel extends Model { /** * Get a list of all fields of a the table this model is associated with * @param bool, prefix all values with the name of this model eg: Model.fieldname * @return array non-associative array with field names as values * @author rtconner */ function fieldNames($prefix=false) { if (empty($this->_tableInfo)) { $this->loadInfo(); } $arr = array_keys($this->_tableInfo->combine('{n}.name')); if($prefix) { $func = create_function('&$a, $key, &$obj', '$a = $obj->escapeField($a);'); array_walk($arr, $func, $this); } return $arr; } }?>