2010-04-29 79 views
10

我在codeigniter中有一個簡單的表單,希望用於編輯或記錄。 我處於顯示錶單並將值輸入到相應輸入框的階段。Codeigniter:如何構建使用表單驗證和重新填充的編輯表單?

<input type="text" value="<?php echo $article['short_desc'];?>" name="short_desc" /> 

但是,如果我想在笨使用form_validation那我也THOS代碼添加到:

這是通過將所述盒到任何他們需要在視圖中簡單地設定值來實現我的標記:

<input value="<?php echo set_value('short_desc')?>" type="text" name="short_desc" /> 

因此,不能使用set_value函數設置值,如果它需要從發佈數據錯誤地重新填充。

有沒有辦法將兩者結合起來,以便我的編輯窗體可以顯示要編輯的值,但也可以重新填充?

感謝

回答

19

set_value()實際上可以採取第二個參數的默認值,如果沒有要重新填充(至少看CI版本1.7.1和1.7.2)。請參閱從Form_validation.php庫中的以下(行710):

/** 
* Get the value from a form 
* 
* Permits you to repopulate a form field with the value it was submitted 
* with, or, if that value doesn't exist, with the default 
* 
* @access public 
* @param string the field name 
* @param string 
* @return void 
*/ 
function set_value($field = '', $default = '') 
{ 
    if (! isset($this->_field_data[$field])) 
     { 
      return $default; 
     } 

     return $this->_field_data[$field]['postdata']; 
} 

因此,考慮到這一點,你應該能夠簡單地通過你的默認值SET_VALUE這樣的:

<input value="<?php echo set_value('short_desc', $article['short_desc'])?>" type="text" name="short_desc" /> 

如果沒有價值重新填充,set_value()將默認爲$article['short_desc']

希望有所幫助。

+0

看起來很棒 - 歡呼! – Sergio 2010-04-29 12:58:21

+0

完美的解決方案。在測試此「set_value」時,請將「set_value()」函數應用於所有字段。在單個字段上測試它不會產生結果。 – Pravin 2017-07-25 08:40:15