2016-09-20 124 views
0

我有一個簡單的按鈕$builder->add('language_switcher', ButtonType::class);的形式,它應該只是,如果按下,添加另一個字段。要做到這一點,我用的Symfony的食譜http://symfony.com/doc/current/form/dynamic_form_modification.html按下按鈕後添加一個動態的表單字段

$builder 
    ->get('language_switcher') 
    ->addEventListener(
     FormEvents::POST_SUBMIT, 
     function() use ($builder, $options) { 
      $preparedOptions = $this->prepareOptions($options['data']['productCustomizations']); 
      $builder->add('lang_switcher'), ChoiceType::class, $preparedOptions); 

     } 
    ); 

現在,當通過AJAX

在提交
<script> 
    var $button = $('#xyz'); 

    $button.click(function() { 
     var $form = $(this).closest('form'); 
     $.ajax({ 
      url: $form.attr('action'), 
      type: $form.attr('method'), 
      success: function(html) { 
       console.log(html); 
       $('#xyz').replaceWith($(html).find('#lang_switcher')); 
      } 
     }); 
    }); 
</script> 

,我發現了錯誤Buttons do not support event listeners.於是,我嘗試過了一個隱藏字段。我加入了隱藏字段的形式設置EventListener它,並添加這個dataAJAX要求

data[$('#id_of_hidden_field').attr('name')] = 1;

然而,這也沒做。該書中的例子是在提交選擇字段之後,因此我不知道如何使其適應我的需求。我無法使用SubmitType,因爲它會提交表單,對吧?我只想用一個簡單的按鈕。

問題是,當我做一個console.log(html)我看不到新的html元素,所以看起來好像我沒有去EventListener這很奇怪,因爲如果我在監聽器I內部轉儲內容正在獲取一些數據。它只是好像我沒有得到它的迴應

+0

有關事件偵聽器安裝到什麼(父)形式呢?這實際上觸發了這個事件。 – Rvanlaak

回答

2

好吧,明白了。問題在於我在POST_SUBMIT事件中使用了builder,但我必須使用FormInterface。因爲我無法添加它提交後,我不得不買同樣的回調函數中的Symfony的食譜

$formModifier = function (FormInterface $form, $preparedOptions) { 
    $form->add($this->childIdentifier, ChoiceType::class, $preparedOptions); 
}; 

然後聽衆建立這樣

$builder 
    ->get('lang_switcher') 
    ->addEventListener(
     FormEvents::POST_SUBMIT, 
     function (FormEvent $event) use ($formModifier, $options) { 
      $preparedOptions = $this->prepareOptions($options); 
      $formModifier($event->getForm()->getParent(), $preparedOptions); 
     } 
    ); 
-2
<script type="text/javascript"> 
    function inputBtn(){ 
    var input=document.createElement('input'); 
    input.type="file"; 
    input.name="img[]"; 
    input.multiple="multiple"; 
    //without this next line, you'll get nuthin' on the display 
    document.getElementById('target_div').appendChild(input); 
} 
</script> 

<button id="ifile" onclick="inputBtn();">create</button> 
<form action="test.php" method="post" enctype="multipart/form-data"> 
<div id="target_div"></div> 
<input type="submit"> 
</form> 
+0

JavaScript不是問題。當我將ajax請求的輸出記錄到控制檯時,新的表單元素不存在。這是symfony中的東西。 – Musterknabe