1

我需要使用数据库表的列名以我的一种形式填充列表。当我从帐户表中提取归档名称时,选项列表将如下所示:

<option value="NAME">Account Name</option>
<option value="OWNER">Account Owner</option>

在表单列表中将显示如下:

Account Name 
Account Owner

我可以使用直接获取列名的 CakePHP 函数来做到这一点吗?或者我是否需要保留数据库表的元数据及其列描述来实现这一点。

我对 CakePHP 很陌生。

任何想法/答案表示赞赏。

谢谢。

4

1 回答 1

0

您可以: 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')
?>
于 2012-10-11T20:46:32.407 回答