2010-07-09 97 views
2

我想在驗證後重新填充(即重新填充)從選擇表單域中發佈的值。我知道使用set_select()函數提出的codeigniter用戶指南,但他們的指南中的示例假定您已對HTML代碼中的「select」表單元素進行了硬編碼(以HTML爲單位)。在我來說,我使用的形式助手和我的選擇字段值從一個數組(),像這樣拉:重新填充CodeIgniter中的選擇表單域


$allstates = array('blah','blah2','blah3','blah4','blah5'); 
echo form_label('Select State Affiliate', 'state'); 
echo form_dropdown('state', $allstates); 

不用說,$ allstates陣列是動態的,隨時間的變化。那麼,如何編碼,以便我的選擇字段可以用用戶選擇的值重新填充?

回答

4

您可以通過form_dropdown的第三個參數設置應該預先選擇的值。用戶在上一步中選擇的值在$ this-> input-> post('state')中。所以,你可以使用:

echo form_dropdown('state', $allstates, $this->input->post('state')); 

從用戶指南:

第一個參數包含字段的名稱,第二個參數將包含選項的關聯數組,第三個參數會包含您想要的值來選擇

$options = array(
       'small' => 'Small Shirt', 
       'med' => 'Medium Shirt', 
       'large' => 'Large Shirt', 
       'xlarge' => 'Extra Large Shirt', 
      ); 

$shirts_on_sale = array('small', 'large'); 

echo form_dropdown('shirts', $options, 'large'); 

// Would produce: 

<select name="shirts"> 
<option value="small">Small Shirt</option> 
<option value="med">Medium Shirt</option> 
<option value="large" selected="selected">Large Shirt</option> 
<option value="xlarge">Extra Large Shirt</option> 
</select> 
+0

糟糕!爲什麼我不想那個?只需使用函數:$ this-> input-> post('name_of_field'))來返回字段的值。非常感謝的人!完美工作,我喜歡這個解決方案,因爲它簡單直接。 – dtechplus 2010-07-10 12:10:53

2

有時,特別是使用對象的時候,它可能是更容易做到這一點沒有形式幫手:

<select name="my_select> 
    <?php foreach ($my_object_with_data as $row): ?> 
    <option value="" <?php if (isset($current_item->title) AND $row->title == $current_item->title) { echo 'selected="selected"';} ?> > 
     <?php echo $row->title; ?> 
    </option> 
    <?php endforeach; ?> 
</select> 

我知道這是很醜陋,但在很多情況下,這是有對象,而不是一個關聯數組工作時做的最簡單的方法。

+0

這種代碼在控制器中比在視圖中更好。這是使用表單助手創建下拉列表的好例子,它更乾淨。 – stef 2010-07-10 21:08:00

+0

表單助手需要一個關聯數組,一個對象會導致字符串轉換錯誤。 – 2010-07-10 23:09:04

相關問題