2014-01-16 43 views
2

我有一個選擇框,其中充滿了我通過SOAP調用從CRM中檢索到的帳戶名稱。當我使用CakePHP FormHelper創建表單時,我只將名稱發送給我的視圖。我遇到的唯一問題是,雖然選擇填充正確,它會發回我選擇的索引,而不是我喜歡的文本。從選擇輸入提交文本,而不是ID - CakePHP

echo $this->Form->create(); 
    echo $this->Form->input('name'); 
    echo $this->Form->input('email'); 
    echo $this->Form->input('account'); 
    echo $this->Form->input('message'); 
    echo $this->Form->end(__('Submit')); 
echo $this->Form->end(); 

那麼有誰知道如何提交選定的帳戶值而不是ID? 預先感謝您。

回答

2

如果$帳戶是您正在使用的變量名,你可以嘗試

$accountValues = array(); 
foreach ($accounts as $key => $value) { 
    $accountValues[$value] = $value; 
} 
$accounts = $accountValues; 

產生一個陣列,將有兩個鍵和值相同。

0

考慮到你有一個數組

$account = array('1'=>'Account Name','2'=>'Account name2',etc); 

改變上述陣列分爲(值=>值對)

$account = array('Account Name'=>'Account Name', 
       'Account name2'=>'Account name2',etc); 

假設你知道如何$帳戶數組轉換成所希望的輸入: 然後只需在選項中傳遞該數組,您將獲得值而不是ID。

<?php echo $this->Form->input('account', 
        array('type'=>'select', 
         'options'=>$account, 
         'label'=>false, 
         'empty'=>'Account')); 
?> 
0

拓展更多蛋糕的方式來做到這一點是有一個ACCOUNT_ID表單字段

$this->Form->input('account_id');

,然後設置$帳戶從控制器到您的視圖。

0

在CakePHP 3.X,你可以做這樣的事情:

// somewhere inside your Controller 
$optionList = 
    $this->createOptionList(
     $this->Users, ['id', 'name'], 'id', 'name' 
    ); 

// a reusable function to create the array format that you needs for your select input 
private function createOptionArray($model, $fields, $arrayKey, $arrayValue, $limit = 200) { 
    $query = $model 
     ->find() 
     ->select($fields) 
     ->limit($limit); 

    $options = array(); 
    foreach ($query as $key => $value) { 
     $options[$value->$arrayKey] = $value->$arrayValue; 
    } 

    return $options; 
} 

功能createOptionArray,創建以下陣列格式:

[ 
    (int) 1 => 'Dennis', 
    (int) 2 => 'Frans' 
] 

現在,你可以簡單的添加這個陣列中的表格內 - 你的看法像這樣輸入:

<?= $this->Form->input('user_id', ['options' => $optionList, 'empty'=>'Choose']); ?> 
相關問題