2010-11-04 44 views
3

嗨 我想添加一個禁用選項與窗體幫助器的選擇框我使用此代碼來生成一個額外的空字段,但我希望這字段禁用。添加禁用(和選擇)選項與表單助手

echo $this->Form->input('User.usertype_id',array('type'=>'select', 'empty'=>'usertype'); 

這會產生:

<div class="input select"> 
    <label for="UserUsertypeId">Usertype</label> 
    <select name="data[User][usertype_id]" id="UserUsertypeId"> 
     <option value="">usertype</option> 
     <option value="1">athlete</option> 
     <option value="2">trainer</option> 
    </select> 
</div> 

,但我想這一點:

<div class="input select"> 
    <label for="UserUsertypeId">Usertype</label> 
    <select name="data[User][usertype_id]" id="UserUsertypeId"> 
     <option value="" disabled="disabled" selected="selected">usertype</option> 
     <option value="1">athlete</option> 
     <option value="2">trainer</option> 
    </select> 
</div> 

有沒有辦法簡單地做到這一點,或者我應該只使用一些JS?

回答

9

如果您事先知道這些選項,則可以構建要在選擇菜單中使用的$options陣列。這應該給你你想要什麼:

$options = array(
      array(
       'name' => 'usertype', 
       'value' => '', 
       'disabled' => TRUE, 
       'selected' => TRUE 
      ), 
      'athlete', 
      'trainer' 
      ); 

echo $this->Form->input('User.usertype_id', array('type' => 'select', 'options' => $options)); 

或者,也許這可能工作,但我還沒有測試它要麼:

回聲$這個 - >形式 - >輸入(「用戶.usertype_id',array('type'=>'select','empty'=> array('text'=>'usertype','selected'=> TRUE,'disabled'=> FALSE)));

+0

看看我的答案... – Weptunus 2010-11-04 21:56:13

+0

做工精細..謝謝。 – 2016-04-27 11:48:10

1

MHMM看起來是不可能的一些代碼塊添加註釋 所以,無論你的選擇產生:

<select name="data[User][usertype_id]" id="UserUsertypeId"> 
    <option value="text">usertype</option> 
    <option value="selected">1</option> 
    <option value="disabled"></option> 
    <option value="1">athlete</option> 
    <option value="2">trainer</option> 
</select> 

所以這沒有工作,但我沒有這樣說:

echo $this->Form->input('User.usertype_id', array('type' => 'select', 'empty'=> array('text" disabled="disabled" selected="selected' => ''))); 

這產生具有值的選項:( 「禁用= 」禁用「 選擇=」 選中) 所以它成爲:

... 
<option value="" disabled="disabled" selected="selected"></option> 
... 

這是一個臨時解決方案,直到我找到更好的東西,歡迎提出建議!

+0

再次查看我的答案。我編輯了第一個選項,以便它能正常工作。 – stevelove 2010-11-05 00:37:45

0

我合併Weptunus和stevelove的解決方案。

在控制器:

$examples = $this->Test->Examples->find('list'); 
$this->set('examples', $examples); 

在視圖

echo $this->Form->input('example_id', array('empty' => array(
     '' => array(
      'name' => __('Select an Example'), 
      'value' => '', 
      'disabled' => TRUE, 
      'selected' => TRUE 
     ) 
    )) 
);