Symfony 4 表单 CollectionType:仅新行需要 FileType 元素

Symfony 4 forms CollectionType: make FileType element required for new rows only

我有一组图像,我希望能够从 Symfony 4 表单中添加 to/update/delete。

要为这些图像创建一个表单,我使用了一个包含 FileType 的自定义表单:

public function buildForm(FormBuilderInterface $builder, array $options) {

    $builder
        ->add('image', FileType::class, array(
            'data_class' => null
        ))
    ;

}

然后我使用一个 CollectionType 填充了上述表单的实例来为数组中的每个图像呈现一个表单,使用 'allow_add' 和 'allow_delete' 这样我就可以 add/remove行通过JavaScript.

public function buildForm(FormBuilderInterface $builder, array $options) {

    $builder->add('imagesets', CollectionType::class, array(
        'entry_type' => ImageType::class,
        'entry_options' => array('label' => false),
        'allow_add' => true,
        'allow_delete' => true
    ));
}

这适用于添加新图像,但在更新现有图像时,不需要 FileType 元素,只有新行才需要它。

问题:如何使现有图像不需要 FileType,但所有新行都需要?

(注意,我会将普通数组传递给这些表单对象,而不是 Doctrine 实体。)

如果对象不是新的(或不为空),您应该将 EventListener 添加到 ImageType 表单并修改 required 属性。请记住,将与前一个同名的第二个元素添加到表单中,替换它。

$builder
    ->add('image', FileType::class, array(
        'data_class' => null,
        'required' => true,
    ))
    ;

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    // get the form object
    $form = $event->getForm();
    // get the entity/object data
    $image = $event->getData();
    // if it is new, it will be null
    if(null !== $image) {
        // modify the input
        $form->add('image', FileType::class, array(
            'data_class' => null,
            'required' => false,
        ))
         ;
    });
}