[英]Symfony 6: embedded form Collection with File upload in child form
我有一個實體ClientFileAction
,它是OneToMany
關系中實體Attachment
的父級。 Attachment
不僅包含文件路徑,還包含有關文件的信息,如標題、上傳日期等。
Attachment:
#[ORM\Column(type: 'string', length: 255)]
private $title;
#[ORM\Column(type: 'datetime')]
private $uploaded;
#[ORM\Column(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',
])
],
]);
在 controller 中,我剛剛使用$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
作為Collection嵌入到ClientFileActionType
中時,在 controller 中我找不到獲取上傳文件的方法:
$attachments = $form->get('attachments')->getData();
$attachments
是Attachment
的數組,並且由於attachmentFile
不是映射字段,它在$form->handleRequest($request);
.
我需要一種方法來獲取子 forms 的未映射的attachmentFile
字段,例如:
$attachmentFiles = $form->get('attachments.attachmentFile')->getData();
這會引發錯誤。 有正確的方法嗎?
我在輸入問題時找到了正確的方法。
上傳的文件在Request
object中,所以這種文件上傳管理的正確做法應該是:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.