2016-09-14 149 views
0

我有一個ChoiceType :: Type字段,顯示一些選擇,並且我想爲每個選項添加一個輸入以在其上添加一個價格。我這樣做是這樣的:Symfony - 添加並保留額外的字段

->add('product_price', ChoiceType::class, array(
    'choices' => array(
     "Product 1", 
     "Product 2", 
    ), 
) 

是添加輸入每個選擇的JS:

var productBoxes = $("[id^=product_]"); 
// Listen the checkbox to display or hide the prices inputs 
productBoxes.each(function (index) { 
    var priceField = '<label class="control-label required" for="product_price_' + index + '">Capacité</label>' + 
     '<input type="text" id="product_price_' + index + '" name="product[price][]" class="form-control">'; 
    $(this).click(function() { 
     if ($(this).is(':checked')) { 
      $(this).parent().append(priceField); 
     } 
    }) 
}) 

JavaScript的作品,其追加旁邊的每個選擇字段。現在我想發送一個數組中的數據,如下所示: [「Product 1」=>「附加字段的值」]

但我不知道如何獲取額外的數據並將其保存到數據庫。

有人知道該怎麼做嗎?

編輯1 我試圖用CollectionType做,但沒有找到如何呈現每個CollectionType元素作爲複選框。有沒有辦法這樣做?

感謝您的幫助!

回答

1

我認爲更好的方法是創建自定義類型並在其中設置附加字段。

例如:

您主要形式類型:

$builder->add('product_price', CollectionType::class, array(
    'label' => 'Prices', 
    'entry_type' => ProductPriceType::class 
)); 

而且ProductPriceType:

/** 
* @param FormBuilderInterface $builder 
* @param array $options 
*/ 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('product', TextType::class, array()) 
     ->add('price', NumericType::class, array()); 
} 


/** 
* @param OptionsResolver @resolver 
*/ 
public function configureOptions(OptionsResolver $resolver) 
{ 
    $resolver->setDefaults(array(
     'data_class' => 'AppBundle\Entity\SomeEntity' 
    )); 
} 

我認爲你從基地獲得產品數據。 在這種情況下,你得到的數組包含2個值 - 產品和價格

+0

是的,我嘗試過,但沒有找到如何1. Render CollectionType作爲複選框。 2.在產品選擇上附加價格輸入。有沒有辦法做到這一點? – Boulboulouboule

+1

您可以在ProductPriceType中添加複選框字段。它看起來像每個產品條目的複選框。然後保存已選中的數組項目複選框 – Victor

1

在您的示例中,最簡單的方法是將兩個更多的字段添加到您的表單。讓他們隱藏的CSS(顯示:無),並且只顯示他們與JS(切換級「隱藏」在選擇時被un /選擇)

->add('product_one_price', NumberType::class, array(
    'attr' => array('class' => 'hidden') 
)) 
->add('product_two_price', NumberType::class, array(
    'attr' => array('class' => 'hidden') 
)) 

另一種方法是有嵌套的表格,或建動態的形式可能會或可能不會矯枉過正,這取決於你實際在做什麼

+0

感謝您的回答!但通過這種方式,我需要每個產品1個字段,並且我的表中每個價格需要1個字段。我不要那個。嵌套表單是一個解決方案,但我真的每個產品1複選框,每個複選框1個字段..!使用CollectionType可以這樣做嗎? – Boulboulouboule

0

也許我錯了,但我認爲你應該挖掘ChoiceType類。

當使用基本ChoiceType,Symfony的文檔說:

的選擇選項是一個數組,數組鍵是項目的標籤和數組值是項目的價值

如果我正確地理解你的情況,你想要一些非常具體的像這樣的選擇:

$choices = [ 
    'item_label' => [ 
      'value' => 'item_value', 
      'price' => 'item_price' 
    ], 
    'item_label2' => [ 
      'value' => 'item_value2', 
      'price' => 'item_price2' 
    ], 
    ... 
] 

我不能準確地告訴你哪個類o verride但你最好的選擇將是看一看:

  • ChoiceListFactory類
  • 選擇列表類(ChoiceType使用子類SimpleChoiceList)
  • ChoiceToValuesTransformer

我有兩個問題:

  • 什麼是數據模型來存儲標籤和價格?

  • 這是什麼名單?如果它太複雜,你在表單組件挖,也許你應該一分爲二步你的過程:

    1. 一種形式來定義你的價格爲您的產品
    2. 一種形式來選擇您感興趣的產品在
相關問題