Symfony 4表单集合实体与文件类型创建。

3
如何使用实体创建并上传文档,在父表单中通过 collectionType 嵌入 fileType 字段。我已经阅读了文档 Symfony Upload,但没有成功完成。始终会出现此错误:“Type error: Argument 1 passed to App\Service\FileUploader::upload() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, instance of App\Entity\Attachment given”。
以下是我的发票实体
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",
        ]);
    }
}

以及控制器

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字段返回了附件实体实例,而应该返回File实例。问题是如何获取File实例的值?

1个回答

2
在您的情况下,$path属性类型为UploadedFile而不是$invoice->getAttachments()。尝试在Attachement类中添加一个名为$file的属性,不需要使用doctrine mapping,并生成它的getter和setter方法。
/**
 * @var UploadedFile
 */
protected $file;

在您的AttachmentType类中将'path'更改为'file'。 现在,请尝试更新您控制器中的此部分:
    $attachements = $invoice->getAttachments();
    foreach($attachements as $attachement){
        /** @var UploadedFile $file */
        $file = $attachement->getFile(); // This is the file
        $attachement->setPath($this->fileUploader->upload($file));
    }

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

谢谢,问题解决了!顺便说一下,$this-fileUploader->upload($file)在我的情况下不起作用,所以我将其更改为$fileUploader->upload($file)。 - Defrian Afdi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接