2013-05-01 72 views
3

我有一種形式是這樣的:笨表單驗證,重新填充動態添加字段

<form action="" method="post"> 
    <input type="text" name="name[]"> 
    <input type="text" name="name[]"> 
</form> 
<button id="add">Add extra field</button> 

而且還有一個可能性,即我已經使用Javascript/jQuery的處理多個輸入:

$('#add').click(function(){ 
    $('form').append('<input type="text" name="name[]">'); 
} 

這裏的一切工作正常。當我提交表格時,我回復echo '<pre>'.print_r($this->input->post(),TRUE).'</pre>';的數據,我收到了一切。

而我正在使用表單驗證類,所以如果失敗了,我想通過使用set_value函數來保存這些值。然後,窗體如下所示:

<form action="" method="post"> 
    <input type="text" name="name[]" value="<?=set_value('name[]');?>"> 
    <input type="text" name="name[]" value="<?=set_value('name[]');?>"> 
</form> 
<button id="add">Add extra field</button> 

但是...動態添加的輸入不存在,因爲它們是通過Javascript添加的。問題是:如何在代碼驗證失敗後「保留」動態添加的輸入和CodeIgniter的值?

四處搜尋,但沒有找到任何東西:(

+0

你可以回顯提交給控制器的表單數據,檢查是否存在添加到視圖中的所有動態字段。 – MaNKuR 2013-05-01 09:31:14

+0

是的,當我運行'回聲'

'.print_r($this->input->post(),TRUE).'
';'我得到的一切。 – Roy 2013-05-01 10:49:11

+0

還有一件事是這(動態)字段在服務器端進行驗證?你可以嘗試像這樣'value =「<?php echo set_value('name []',$ _ POST ['name []']);?>」' – MaNKuR 2013-05-01 11:18:55

回答

2

讓您的每個表單元素的規定指標。

<form action="" method="post"> 
    <input type="text" name="name[1]"> 
    <input type="text" name="name[2]"> 
</form> 

所以,你的JS變得像,

counter = 3; 
$('#add').click(function(){ 
    $('form').append('<input type="text" name="name['+counter+']">'); 
    counter++; 
} 

現在,如果您的驗證失敗,則必須添加如下條件:

<form action="" method="post"> 
<?php 
    if ($this->form_validation->run() == FALSE) 
    { 
     foreach($this->input->post('name') as $ind=>$item) 
     { 
    ?> 
     <input type="text" name="name[<?php echo $ind ?>]" 
         value="<?=set_value('name[".$ind ."]');?>"> 
    <?php 
     } 
    } 
    else 
    { 
    ?> 
     <input type="text" name="name[1]"> 
     <input type="text" name="name[2]"> 
    <?php 
    } 
?> 
</form> 
+0

我更新了我的問題,我想你誤解了我。但是,謝謝你的回覆! – Roy 2013-05-01 11:04:14

+1

看到我更新的答案,我希望你能找到答案。 – hsuk 2013-05-01 11:12:39

+0

有點哈克,但我認爲這是一個工作!謝謝!我會深入研究它,並且會在我的案例中發佈解決方案。如果我看看這個,我不認爲我必須在數組名稱中指定一個索引。 – Roy 2013-05-01 14:34:07

0

好吧,我是怎麼做的:

的控制器

<?php 
$data['some_data'] = ''; // Some data from the database to send to the view 
if($this->form_validation->run() == FALSE) 
{ 
    // Posted? 
    if($this->input->post()) 
    { 
     // Merge the submitted data with the current data 
     $data = array_merge($this->input->post(),$data); 
    } 

    // Load the view 
    $this->load->view('view',$data); 
} 
else 
{ 
    // Code after validation was successfull 
} 

視圖

<? if(isset($name)): // Name set? ?> 
    <? foreach($name as $item): // Loop through all previous posted items ?> 
     <input type="text" name="name[]" value="<?=set_value('name[]'); // Set it's value with the regular set_value function ?>"> 
    <? endforeach; ?> 
<? else: ?> 
    <input type="text" name="name[]"> 
<? endif; ?> 

這樣,它是不是在視圖哈克與控制器的東西,它完美的作品!

@hsuk,謝謝!