Symfony2 非映射 collectionType 不工作

Symfony2 non mapped collectionType not working

我正在使用 here 中解释的方法来实现多文件上传,但找不到使其工作的方法。我知道已经有很多关于它的问题,但我找不到适合我的情况的答案。

请注意,由于具有名称、内容和类型属性的文件实体,我将文件的内容存储在数据库中。 但是,为了使其正常工作,我没有将表单映射到该实体。

所以,我的控制器看起来像这样:

    $files = [];

    $form = $this->createForm(MultipleFilesType::class, []);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $files = $form->getData();

        dump($files);

        foreach ($files as $file)
        {
            //code that stores the file in the database which works fine and is not relevant to my problems I think
        }
        return // redirect to some page
    }

    return //form to the view

我的 MultipleFilesType 是嵌入多个 addFileType 的集合:

class MultipleFilesType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('files', CollectionType::class, array (
            'entry_type' => addFileType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'label' => false,
            'mapped' => false,
            'data' => array(
               array ('file' => null)
            )
        ))
    ;
}
}

我的 addFileType 是这样的:

class AddFileType extends AbstractType
{


/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('file', FileType::class, array (
            'label' => false
        ))
    ;

}
}

在我看来,由于链接文档中解释的一些 JQuery,我可以添加/删除字段。 (代码与文档中的代码大致相同,除了我没有使用 Entites,所以我不在这里显示)。

我首先尝试进行单个文件上传,效果很好,然后我尝试了上面的代码,使用 collectionType 和 $files 数组将数据从表单检索到控制器,但我有这些问题:

当我提交表单时,显然第一个文件之后的文件值无效。

当我只提交一个文件(没有验证错误)时,控制器中的转储($files) 无论如何都会向我显示一个空数组。

如有任何帮助,我们将不胜感激 =) 如果您认为需要更多代码,请随时索取更多代码。

谢谢!

AddFileType 没有用,会破坏您的表单映射。在你的 MultipleFileType.

中直接使用 FileType

那么,你其他的错误,主要看你的JavaScript和你的实体。

客户端,您需要提交名称为"multiple_file_form[files][INDEX]"的每个文件,其中INDEX是列表中每个文件的索引。为此:

  • 如果您同步提交(使用提交按钮和 form 标签),请输入 <input type="file" name="multiple_files_form[files][INDEX]"> 个标签
  • 如果你的表单是异步提交的(通过AJAX),你的请求参数必须是这样的数组:

    {
         "multiple_files_form": {
             "files": [
                 // Your files here...
             ]
         }
     }
    

而不是

$files = $form->getData();

$files = $form->get("files")->getData();