Symfony -添加和保存额外的字段


Symfony - Add and persist extra fields

我有一个显示一些选择的ChoiceType::Type字段,我想为每个选择添加一个输入以在其上添加价格。我是这样做的:

->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元素呈现为复选框。有办法这样做吗?

感谢您的帮助

我认为更好的方法是创建自定义类型并在那里设置额外的字段。

例如:

你的主表单类型:

$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个值的数组- product和price

在您的示例中,最简单的方法是在表单中再添加两个字段。用CSS (display: none)隐藏它们,用JS显示它们(当选项变为un/selected时切换class "hidden")

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

另一种选择是使用嵌套表单,或者动态构建表单,这可能会或不会过度,这取决于你实际在做什么

也许我错了,但我认为你应该在ChoiceType类中挖掘。

当使用基本的ChoiceType时,Symfony文档说:

choices选项是一个数组,其中数组键是项目的标签,数组值是项目的值

如果我正确理解了你的情况,你想要一些非常具体的选择,就像这样:

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

我不能确切地告诉你要重写哪个类,但你最好的选择是看一下:

    <
  • ChoiceListFactory类/gh>
  • 选择冰岛类(选择类型使用子类simplecho冰岛)
  • ChoiceToValuesTransformer

我有两个问题:

  • 存储标签和价格的数据模型是什么

  • 这个列表是干什么用的?如果对您来说挖掘表单组件太复杂,也许您应该将流程分成两步:

    1. 为您的产品定义价格的表单
    2. 一个选择您感兴趣的产品的表单