1

DB テーブルの列名を使用して、フォームの 1 つにリストを作成する必要があります。アカウント テーブルからファイル名を取得すると、オプション リストは次のようになります。

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

フォーム リストでは次のように表示されます。

Account Name 
Account Owner

列名を直接取得するCakePHP関数を使用してこれを行うことはできますか? または、これを実装するために、列の説明とともに DB テーブルのメタデータを保持する必要がありますか。

私は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
?>

便宜上、ブール値フラグを 2 番目のパラメーターとして追加しました。

<?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 に答える