2012-09-15 67 views
1

我需要使用數據庫表的列名填充我的一個表單中的列表。當我拉從帳戶表中的申請名稱的選項列表將如下所示:在CakePHP中填充具有數據庫列名稱的列表

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

在表單列表將顯示,如:

Account Name 
Account Owner 

我能做到這一點使用CakePHP的功能,這將得到列名直接。或者,我是否需要保留數據庫表的元數據以及其列描述來執行此操作。

我很喜歡CakePHP。

任何想法/答案表示讚賞。

謝謝。

回答

0

您可以: 答:設置從控制器動作列表,在視圖中使用,從模型獲取列表::模式()方法和「人性化」的每個值 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') 
?>