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')
?>