我是Symfony的新手,我很难找到上传多个文件的方法。我正在尝试建立一个应用程序。有公寓,每个公寓可以有多个图像。
公寓(一对多(-图像(多对一(
所以我创建了两个实体,并在我的AppartmentTypeForm中添加了一个名为"image"的字段,它是我的ImageTypeForm中"name"的CollectionType::class,它是FileType::class
我添加了一些js,可以通过点击按钮添加多个输入文件
在我提交表格之前,一切都正常,如果我添加了3个图像并尝试,我就无法获得图像名称
$photo = $form->get('image')->getData();
我会看到我的3个数组,只有我公寓的id设置没有名称没有文件什么都没有。
我可能做错了什么,但我不知道在哪里。
控制器,正如您将看到的,iI尝试foreach我的图像数据,但我只能获得文件名的1,即使当我尝试flush((时,Symfony也会返回一个错误,因为它试图设置我的数据库列"name"为null。。。,
#[Route('/create_product', name: 'create_product', methods: ['GET', 'POST'])]
public function createProduct(EntityManagerInterface $em, Request $request, SluggerInterface $slugger): Response
{
$image = new Image;
$product = new Appartment;
$form = $this->createForm(AppartmentTypeFormType::class, $product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$product->setCreatedAt(new DateTime());
$product->setUpdatedAt(new DateTime());
$product->setCountry($form->get('country')->getData());
$image->setCreatedAt(new DateTime());
$image->setUpdatedAt(new DateTime());
foreach ($form->get('image') as $formChild) {
$uploadedImages = $formChild->get('name')->getData();
$uploadedImage = $uploadedImages[0];
$newFileName = $this->handleFile($slugger, $uploadedImage);
$image->setName($newFileName);
}
}
$em->persist($product);
$em->persist($image);
$em->flush();
$this->addFlash('success', "votre produit a bien était ajouté");
return $this->render('admin/create_product.html.twig', [
'form' => $form->createView(),
]);
}
public function handleFile($slugger, $image)
{
$extension = '.' . $image->guessExtension();
$originalFileName = $slugger->slug($image->getClientOriginalName());
$newFileName = $originalFileName . uniqid() . $extension;
try {
$image->move($this->getParameter('uploads_directory'), $newFileName);
} catch (FileException $fe) {
//throw $th;
}
return $newFileName;
}
公寓实体(一对多(
#[ORMManyToOne(inversedBy: 'appartments')]
#[ORMJoinColumn(nullable: false)]
private ?Country $country = null;
#[ORMOneToMany(mappedBy: 'image', targetEntity: Image::class, cascade:["persist"])]
private Collection $image;
public function __construct()
{
$this->image = new ArrayCollection();
}
/**
* @return Collection<int, Image>
*/
public function getImage(): Collection
{
return $this->image;
}
public function addImage(Image $image): self
{
if (!$this->image->contains($image)) {
$this->image->add($image);
$image->setImage($this);
}
return $this;
}
public function removeImage(Image $image): self
{
if ($this->image->removeElement($image)) {
// set the owning side to null (unless already changed)
if ($image->getImage() === $this) {
$image->setImage(null);
}
}
return $this;
}
图像实体(ManyToOne(
#[ORMEntity(repositoryClass: ImageRepository::class)]
class Image
{
use TimestampableEntity;
use SoftDeleteableEntity;
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn]
private ?int $id = null;
#[ORMManyToOne(inversedBy: 'image')]
private ?Appartment $image = null;
#[ORMColumn(length: 255)]
private ?string $name = null;
public function getId(): ?int
{
return $this->id;
}
public function getImage(): ?Appartment
{
return $this->image;
}
public function setImage(?Appartment $image): self
{
$this->image = $image;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
}
公寓类型表单
class AppartmentTypeFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('title')
->add('description')
->add('beds')
->add('price')
->add('city')
->add('address')
->add('postal_code')
->add('country',EntityType::class, [
'class' => Country::class,
'choice_label' => 'name'
])
->add('image', CollectionType::class, [
'entry_type' => ImageTypeFormType::class,
'constraints' => [
new Valid()
],
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false
])
->add('submit', SubmitType::class, [
'label' => 'envoyer',
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Appartment::class,
'allow_file_upload' => true
]);
}
}
ImageTypeForm
class ImageTypeFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', FileType::class, [
'label' => false,
'constraints' => [
new All([
new File(
[ "mimeTypes" => ["image/png",
"image/jpg",
"image/jpeg",
"image/gif"]]
)]),
new Valid(),
],
'multiple' => true,
'mapped' => false,
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Image::class,
'allow_file_upload' => true
]);
}
}
这是我时得到的
$image = form->get('image')->getData();
dd($image) return me this
AdminController.php on line 50:
DoctrineCommonCollectionsArrayCollection {#1191 ▼
-elements: array:3 [▼
0 => AppEntityImage {#1343 ▼
-id: null
-image: AppEntityAppartment {#526 ▶}
-name: null
#createdAt: null
#updatedAt: null
#deletedAt: null
}
1 => AppEntityImage {#1247 ▼
-id: null
-image: AppEntityAppartment {#526}
-name: null
#createdAt: null
#updatedAt: null
#deletedAt: null
}
2 => AppEntityImage {#1257 ▼
-id: null
-image: AppEntityAppartment {#526}
-name: null
#createdAt: null
#updatedAt: null
#deletedAt: null
}
]
}
这就是我为文件做这件事时得到的
$photo = $request->files;
dd($photo); return me this
AdminController.php on line 50:
SymfonyComponentHttpFoundationFileBag {#55 ▼
#parameters: array:1 [▼
"appartment_type_form" => array:1 [▼
"image" => array:3 [▼
0 => array:1 [▼
"name" => array:1 [▼
0 => SymfonyComponentHttpFoundationFileUploadedFile {#60 ▼
-test: false
-originalName: "FaYS3XxWQAAesmS.jpg"
-mimeType: "image/jpeg"
-error: 0
path: "C:xampptmp"
filename: "php6EE1.tmp"
basename: "php6EE1.tmp"
pathname: "C:xampptmpphp6EE1.tmp"
extension: "tmp"
realPath: "C:xampptmpphp6EE1.tmp"
aTime: 2022-09-18 08:43:33
mTime: 2022-09-18 08:43:32
cTime: 2022-09-18 08:43:32
inode: 2251799814701650
size: 129133
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:xampptmpphp6EE1.tmp"
}
]
]
1 => array:1 [▼
"name" => array:1 [▼
0 => SymfonyComponentHttpFoundationFileUploadedFile {#43 ▼
-test: false
-originalName: "FUR6LQ3X0AQxOIW.jpg"
-mimeType: "image/jpeg"
-error: 0
path: "C:xampptmp"
filename: "php6EE2.tmp"
basename: "php6EE2.tmp"
pathname: "C:xampptmpphp6EE2.tmp"
extension: "tmp"
realPath: "C:xampptmpphp6EE2.tmp"
aTime: 2022-09-18 08:43:33
mTime: 2022-09-18 08:43:32
cTime: 2022-09-18 08:43:32
inode: 1970324837991018
size: 69872
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:xampptmpphp6EE2.tmp"
}
]
]
2 => array:1 [▼
"name" => array:1 [▼
0 => SymfonyComponentHttpFoundationFileUploadedFile {#42 ▼
-test: false
-originalName: "8fecc63aa4d247d6895b0de17e38b858.jpg"
-mimeType: "image/jpeg"
-error: 0
path: "C:xampptmp"
filename: "php6EE3.tmp"
basename: "php6EE3.tmp"
pathname: "C:xampptmpphp6EE3.tmp"
extension: "tmp"
realPath: "C:xampptmpphp6EE3.tmp"
aTime: 2022-09-18 08:43:33
mTime: 2022-09-18 08:43:32
cTime: 2022-09-18 08:43:32
inode: 1688849861280373
size: 565083
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:xampptmpphp6EE3.tmp"
}
]
]
]
]
]
}
很抱歉有点长,但我试着到处搜索,找不到响应
谢谢。
所以很少编辑:
当我提交我的文件时,我的图像会被重命名并上传到我的uploads_directory中,我不知道如何或为什么。我什么都没改变,但是我怎样才能使我的数据库列名等于我的文件名。
第二次编辑:
我通过更改在数据库中上传了1张图像
$image->setName($newFileName);
$em->persist($image)
通过这个:
$em->persist($image->setName($newFileName));
但我仍然无法将我所有的图像都放入数据库。
将$image = new Image;
和$em->persist($image);
移动到的前一部分
...
foreach ($form->get('image') as $formChild) {
$image = new Image; // added
$image->setCreatedAt(new DateTime()); // added
$image->setUpdatedAt(new DateTime()); // added
$uploadedImages = $formChild->get('name')->getData();
$uploadedImage = $uploadedImages[0];
$newFileName = $this->handleFile($slugger, $uploadedImage);
$image->setName($newFileName);
$em->persist($image); // added
}
...