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" => "value of the attached field"]

但我不知道如何获取额外的数据并将其保存到数据库中。

有人知道怎么做吗?

编辑 1 我尝试使用 CollectionType 来完成它,但没有找到如何将每个 CollectionType 元素呈现为复选框。有没有办法这样做?

感谢您的帮助!

在您的示例中,最简单的方法是在表单中再添加两个字段。将它们隐藏在CSS(display:none)中,只需用js(toggle class "hidden"选择时un/selected)[= 11)[= 11) =]

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

另一种方法是使用嵌套表单,或者动态构建表单,这可能会或可能不会过度杀伤,具体取决于您实际在做什么

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

例如:

您的主表单类型:

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

和产品价格类型:

/**
 * @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'
    ));
}

我想你是从 base 获取产品数据的。 在这种情况下,您将获得包含 2 个值的数组 - 产品和价格

也许我错了,但我认为你应该深入了解 ChoiceType class。

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

The choices option is an array, where the array key is the item's label and the array value is the item's value

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

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

我无法准确告诉您要覆盖哪个 class,但您最好看一下:

  • ChoiceListFactory class
  • ChoiceList class(ChoiceType 使用子 class SimpleChoiceList)
  • ChoiceToValuesTransformer

我有两个问题:

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

  • 这个列表有什么用?如果您无法深入挖掘表单组件,也许您应该将流程分为两步:

    1. 定义产品价格的表格
    2. 一张表格select您感兴趣的产品