gpt4 book ai didi

php - 文件类型为 create 的 symfony 4 表单集合实体

转载 作者:行者123 更新时间:2023-12-05 05:16:36 25 4
gpt4 key购买 nike

如何使用实体创建和上传文档,其中 fileType 字段通过 collectionType 嵌入到父表单中。我确实阅读了文档 Symfony Upload .但是没有设法做到这一点。总是收到此错误“类型错误:传递给 App\Service\FileUploader::upload() 的参数 1 必须是 Symfony\Component\HttpFoundation\File\UploadedFile 的实例,给定的 App\Entity\Attachment 实例”。

下面是我的发票实体

class Invoice
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;

/**
* @ORM\OneToMany(targetEntity="App\Entity\Attachment", mappedBy="invoiceId", cascade={"persist"})
*/
private $attachments;


public function __construct()
{
$this->attachments = new ArrayCollection();
}

/**
* @return Collection|Attachment[]
*/
public function getAttachments(): Collection
{
return $this->attachments;
}

public function addAttachment(Attachment $attachment): self
{
if (!$this->attachments->contains($attachment)) {
$this->attachments[] = $attachment;
$attachment->setInvoiceId($this);
}

return $this;
}

附件实体

class Attachment
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;

/**
* @ORM\Column(type="string", length=255)
*/
private $path;

/**
* @ORM\ManyToOne(targetEntity="App\Entity\Invoice", inversedBy="attachments")
*/
private $invoiceId;

public function getId()
{
return $this->id;
}

public function getPath(): ?string
{
return $this->path;
}

public function setPath(string $path): self
{
$this->path = $path;

return $this;
}


public function getInvoiceId(): ?Invoice
{
return $this->invoiceId;
}

public function setInvoiceId(?Invoice $invoiceId): self
{
$this->invoiceId = $invoiceId;

return $this;
}

附件表单类型

namespace App\Form;

use App\Entity\Attachment;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;

class AttachmentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('path',FileType::class, array(
'label' => false,
));
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Attachment::class,
]);
}
}

发票表格类型

namespace App\Form;

use App\Entity\Invoice;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class InvoiceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('attachments', CollectionType::class, array(
'entry_type' => AttachmentType::class,
'entry_options' => array('label' => false),
'allow_add' => true
))
->add('submit', SubmitType::class, array(
'label' => $options['set_button_label']
));
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Invoice::class,
'set_button_label' => "Create Invoice",
]);
}
}

Controller

namespace App\Controller;

use App\Entity\Invoice;
use App\Form\InvoiceType;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Service\FileUploader;
use Symfony\Component\HttpFoundation\File\UploadedFile;


class InvoiceController extends Controller
{
/**
* @Route("/invoice/create", name="createInvoice")
* @param Request $request
* @param UserInterface $user
* @param FileUploader $fileUploader
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function createInvoice( Request $request, UserInterface $user, FileUploader $fileUploader)
{
Debug::enable();
$invoice = new Invoice();

$form = $this->createForm(InvoiceType::class,$invoice);

$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
// Prepare upload file
/** @var UploadedFile $files */
$files = $invoice->getAttachments();
foreach($files as $file){
$fileName = $fileUploader->upload($file);
}
$file->move(
$this->getParameter('attachment_directory'),
$fileName
);

$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($invoice);
$entityManager->flush();

return $this->redirectToRoute('user');
}
return $this->render('invoice/createInvoice.html.twig', [
'controller_name' => 'UserController',
'form' => $form->createView()
]);
}

我认为问题是 FileType 字段返回附件实体实例,而它应该返回文件实例。问题是如何获取文件实例的值?

最佳答案

在您的情况下,属性 $path 类型为 UploadedFile 并且 不是 $invoice->getAttachments()。尝试在没有原则映射的情况下向名为 $file 的附件类添加一个属性,生成它的 getter 和 setter 方法。

/**
* @var UploadedFile
*/
protected $file;

在您的 AttachmentType 类中更改 'path' => 'file'。现在,尝试在您的 Controller 中更新此部分:

    $attachements = $invoice->getAttachments();
foreach($attachements as $attachement){
/** @var UploadedFile $file */
$file = $attachement->getFile(); // This is the file
$attachement->setPath($this->fileUploader->upload($file));
}

请让您的 fileUploader 服务成为唯一负责上传文件的服务,无需使用 $file->move()

关于php - 文件类型为 create 的 symfony 4 表单集合实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50233669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com