Symfony 2 Form collection field with type file

前端 未结 4 886
悲&欢浪女
悲&欢浪女 2021-02-19 09:49

I want to upload multiple files with POST request (without Ajax). Can I use Symfony 2\'s form collection field with type file like this:

Code in Entity:



        
4条回答
  •  清酒与你
    2021-02-19 10:24

    If you want to show multiple input fields, no, it won't work. A collection type requires you to supply some data before rendering the fields. I've already tried it, and came up creating a separate entity (e.g. File) and and adding relationship to my target entity.

    example:

    class File
    {
        // properties
    
        public $file; // this holds an UploadedFile object
    
        // getters, setters
    }
    

    FileType:

    ....
    
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('file', 'file', [
                'required' => false
            ])
        ;
    }
    

    Product:

    class Product
    {
        // properties
    
        private $images; // ManyToMany relationship
    
        // setters, getters
    }
    

    ProductType:

    ->add('images', 'collection', [
        'type' => 'YOUR_FILE_TYPE_NAME',
        'by_reference' => false,
        'required' => false
    ])
    

    Product contoller:

    public function someAction()
    {
        ...
    
        $image = new File();
        $product->addImage($image);
    
    }
    

    I know this solution can be overkill and creates extra tables, but it works.

提交回复
热议问题