Symfony 6:嵌入表单Collection,并在子表单中上传文件



我有一个实体ClientFileAction,它是OneToMany关系中实体Attachment的父实体。Attachment不仅保存文件路径,还保存文件的信息,如标题、上传日期等。

Attachment:

#[ORMColumn(type: 'string', length: 255)]
private $title;
#[ORMColumn(type: 'datetime')]
private $uploaded;
#[ORMColumn(type: 'string', length: 255)]
private $filePath;

当涉及到创建表单类型AttachmentType和上传文件一对一,没有问题:

AttachmentType:

$builder
->add('title', null, ['label' => 'Title', 'required' => true])
->add('attachmentFile', FileType::class, [
'label' => 'File',
'mapped' => false,
'required' => true,
'constraints' => [
new File([
'maxSize' => '1024k',
])
],
]);

在控制器中,我只是上传文件与$attachmentFile = $form->get('attachmentFile')->getData();,然后继续到通常的UploadedFile::move()的东西。

问题:在父窗体中嵌入AttachmentType

但是当我尝试上传多个附件(不仅是文件,而是带有标题字段的附件)时,上传的文件字段似乎无法访问。

ClientFileActionType:

$builder
->add('description', null, ['label' => 'Description', 'required' => true])
->add('attachments', CollectionType::class, ['label' => false,
'allow_add' => true,
'by_reference' => false,
'entry_type' => AttachmentType::class,
'entry_options' => ['label' => false],
]);

当我嵌入AttachmentType作为集合ClientFileActionType,然后,在控制器我找不到一种方法来获得上传的文件:

$attachments = $form->get('attachments')->getData();

$attachmentsAttachment的数组,由于attachmentFile不是映射字段,所以在$form->handleRequest($request);上消失了。

我需要一种方法来获得未映射的attachmentFile字段的子形式的某种方式,如:

$attachmentFiles = $form->get('attachments.attachmentFile')->getData();

抛出错误。有正确的方法吗?

我在输入问题时找到了正确的方法。

上传的文件位于Request对象中,因此此文件上传管理场景的正确方法是:

if ($form->isSubmitted() && $form->isValid())
{
$i=0;
$files = $request->files->all('client_file_action')['attachments'];
foreach ($files as $file)
{
$attachmentFile = $file['attachmentFile'];
$originalFilename = pathinfo($attachmentFile->getClientOriginalName(), PATHINFO_FILENAME);

$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-' . uniqid() . '.' .$attachmentFile->guessExtension();
$attachmentFile->move('path/to/folder',$newFilename);
$attachment = $clientFileAction->findAttachment($i);
if ($attachment != null)
$attachment->setFilePath('path/to/folder/' . $newFilename);
$i++;
}
$clientFileActionRepository->add($clientFileAction, true);
}

相关内容

  • 没有找到相关文章

最新更新