2012-09-24 30 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