2012-09-24 113 views
0

我有兩個表,有一對多的主add.ctp關係, ,允許用戶上傳0〜5個文件(文件路徑信息存儲在信息表)CakePHP的主/詳細信息添加

我想在主/ add.ctp

1動態顯示附件(細節)的形式,用戶選擇文件的數目希望從下拉列表上傳,

echo $this->Form->input('attachments', array('options' => array(1, 2, 3, 4, 5),'empty' => '(choose one)', 'onchange' => 'showNumber(this.value)')); 

然後for循環

{ 
     echo $this->Form->input('attachment_path', array('type'=>'file','label' =>'Attachment, Maximum size: 10M'));  
} 

//但我不知道如何捕獲this.value,我知道Javascript無法將值傳遞給php。

或用戶點擊'添加另一個附件'鏈接,然後顯示詳細的表單。

如何實現這個功能,任何幫助,將不勝感激。

我讀這篇文章: Assign Javascript variable to PHP with AJAX ,並得到同樣的錯誤:變量未定義

編輯: http://cakephp.1045679.n5.nabble.com/Adding-fields-to-a-form-dynamically-a-complex-case-td3386365.html

'For each field use a default name with [] at the end (which will make it stack like a array) example: data[][book_id] after the fields have been submitted'

我應該在哪裏放置[]?

回答

0

我認爲你應該爲此使用Ajax。

只需在select.change()上創建一個ajax調用,然後在控制器中創建一個返回必要信息的方法。

您可以直接在您的控制器(或更好的自定義視圖)和訪問它使用JavaScript對返回使用echo json_encode(array('key' => 'value'))一組數據:

success: function(data) { 
    alert(data.key); 
} 

編輯...

在JavaScript中使用像...

$('select').change(function(e) { 
    var select = $(this); 
    $.ajax({ 
     type: "POST", 
     dataType: "json", 
     url: "/attachments/youraction", 
     data: { data: { id: select.find(":selected").val() } }, 
     success: function(data) { 
      for (i in data) { 
       var input = $('<input>', {type: "file", label: data[i].Attachment.label}) 
       $('form.your-form').append(input); 
      } 
     } 
    }) 
}); 

然後在 「Yourcontroller」 創造 「youraction」 的方法:

<?php 
class AttachmentsController extends AppController 
{ 
    public function youraction() 
    { 
     if (!$this->RequestHandler->isAjax() || !$this->RequestHandler->isPost() || empty($this->data['id'])) 
     { 
      $this->cakeError('404'); 
     } 

     // Do your logic with $this->data['id'] as the select value... 
     $data = $this->Attachment->find('all', array('conditions' => array('id' => $this->data['id']))); 
     // .... 


     // then output it... 
     echo json_encode($data); 

     // This should be done creating a view, for example one named "json" where you can have there the above echo json_encode($data); 
     // Then.. 
     // $this->set(compact('data')); 
     // $this->render('json'); 
    } 
} 

現在更清楚了??如果你對ajax + cakephp有疑問,你應該在網上進行搜索,在那裏你會找到很多教程。

+0

我對ajax知之甚少......你能否詳細解釋一下?我試圖做到這一點,但沒有奏效。 user1606032

+0

好的,讓我用更好的例子展開我的迴應 – elboletaire

+0

I'已經編輯過帖子..我期待它現在更清楚了 – elboletaire