您可以: A:从控制器操作中设置一个列表,在视图中使用,从 Model::schema() 方法中获取一个列表并“人性化”每个值 B:编写一个辅助方法来为您完成
可能有更好的方法,但在我找到它之前,让我为你唱一首我的 AppHelper 代码的歌曲:
<?php
class AppHelper extends Helper {
/**
* Returns and array of 'column_name' => 'Column Name' values from a model
*
* @param string $modelName
* @param type $includeModelName If true, prepends the model name to the field value
* @return array Or false if Model is unavailable
*/
function getHumanFieldNames($modelName, $includeModelName = true){
$model = ClassRegistry::init($modelName, true);
if (!$model) return false;
$schema = $model->schema();
$return = array();
foreach($schema as $field => $meta){
$return[$field] =
($includeModelName) ?
Inflector::humanize($modelName) . ' ' .Inflector::humanize($field)
: Inflector::humanize($field);
}
return $return;
}
}
?>
现在您的所有助手都有一个 getHumanFieldNames 方法,因此要在您的视图中使用它,请使用以下内容:
<?php
$accountFieldNames = $this->Form->getHumanFieldNames('account');
// returns array('owner' => 'Account Owner', 'name' => 'Account Name', 'bank_code' => 'Account Bank code')
//you can use any helper instead of $this->Form
//or better yet, you could write your own "utility" helper
echo $this->Form->select('database_column', $accountFieldNames);
// renders a select element with all
// model column names as values and
// human readable names as labels
?>
为了您的方便,我添加了一个布尔标志作为第二个参数:
<?php
$this->Form->getHumanFieldNames('account', false);
//returns array('name' => 'Name', 'bank_code' => 'Bank Code')
$this->Form->getHumanFieldNames('account', true); // default is true
//returns array('name' => 'Account Name', 'bank_code' => 'Account Bank Code')
?>