【问题标题】:Symfony: form doesn't submit data to compound fieldSymfony:表单不向复合字段提交数据
【发布时间】:2020-05-09 10:51:53
【问题描述】:

我正在尝试将数据提交到表单,但提交后我的复合字段有空值。 问题出在propertyValues 字段上。

我的表格:

class PropertyForm extends FormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder
            ->add('name', TextType::class)
            ->add('propertyValues', CollectionType::class, [
                'entry_type' => PropertyValueDTO::class,
                'required' => true,
                'constraints' => [
                    Count::class, ['min' => 1]
                ]
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        return $resolver
            ->setDefaults([
                'data_class' => PropertyDTO::class
            ])
        ;
    }
}

提交数据:

Array
(
    [propertyValues] => Array
        (
            [0] => Array
                (
                    [id] => 15
                    [value] => Ikea
                    [propertyId] => 7
                    [productsCount] => 4
                )

        )

    [id] => 7
    [name] => Manufacturer
    [description] => 
)

生成的表单数据:

App\DTO\Api\PropertyDTO Object
(
    [id:App\DTO\Api\PropertyDTO:private] => 
    [name:App\DTO\Api\PropertyDTO:private] => Manufacturer
    [description:App\DTO\Api\PropertyDTO:private] => 
    [propertyValues:App\DTO\Api\PropertyDTO:private] => Array
        (
        )

)

并且表单已提交且有效。 如您所见,propertyValues 是一个空数组

我的控制器代码:

public function update(Property $property, Request $request)
{
    $form = $this->createForm(PropertyForm::class);
    $data = json_decode($request->getContent(), true);
    $form->submit($data);
    if (!$form->isValid()) {
        return $this->jsonFormFailed($form);
    }

    return $this->jsonResponse($form->getData());
}

我曾尝试跟踪函数 submit() 并偶然发现了这样的代码:

$viewData = $this->config->getCompound() ? $this->viewData : $submittedData;

由于我的领域是复合 symfony 使用空的 $this->viewData 而不是 $submittedData

【问题讨论】:

    标签: php forms symfony


    【解决方案1】:

    我忘记添加选项allow_add。现在一切正常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-21
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      相关资源
      最近更新 更多