代码之家  ›  专栏  ›  技术社区  ›  Marleen

Symfony 4 forms CollectionType:仅使新行需要FileType元素

  •  3
  • Marleen  · 技术社区  · 8 年前

    我有一个图像数组,我想能够添加/更新/删除在symfony4的形式。

    public function buildForm(FormBuilderInterface $builder, array $options) {
    
        $builder
            ->add('image', FileType::class, array(
                'data_class' => null
            ))
        ;
    
    }
    

    然后,我使用一个CollectionType填充上述表单的实例来为数组中的每个图像呈现一个表单,使用'allow\u add'和'allow\u delete'这样我就可以通过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元素不应该是必需的,它应该只对新行是必需的。

    问题:

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

    1 回复  |  直到 8 年前
        1
  •  2
  •   cezaryta    8 年前

    你应该加一个 EventListener 必修的

    $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,
            ))
             ;
        });
    }
    
    推荐文章