2012-09-15 3 views
1

DB 테이블의 열 이름을 사용하여 양식 중 하나에 목록을 채워야합니다.CakePHP에서 DB 열 이름으로 목록 채우기

Account Name 
Account Owner 

내가이 사용 CakePHP의 기능을 얻을 것이다 할 수있는 :처럼 표시됩니다 양식 목록에서

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

: 나는 계정 테이블에서 제출 한 이름을 당길 때 옵션 목록은 다음과 같이됩니다 컬럼 명. 또는 이것을 구현하기 위해 컬럼 설명과 함 2 DB 테이블의 메타 데이터를 보존해야합니다.

저는 CakePHP에 익숙하지 않습니다.

모든 아이디어/대답을 부탁드립니다.

감사합니다.

답변

0

다음과 같이 할 수 있습니다. 컨트롤러 동작에서 목록을 설정하고,보기에서 사용하고, Model :: schema() 메서드에서 목록을 가져 와서 각 값을 "humanize"합니다. B : 할 수있는 도우미 메서드를 작성합니다. 지금 모든 헬퍼가 getHumanFieldNames 방법이

<?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; 

} 
} 
?> 

을 : 당신은

이 그 일을 더 나은 방법이 될,하지만 난 그것을 찾을 때까지, 내 ​​AppHelper 코드의 당신에게 노래를 할 수 있습니다에 대한 보기에서 사용하려면 다음과 같이 사용하십시오.

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