symfony 4 具有文件类型的表单集合实体创建 [英] symfony 4 form collection entity with file type create

查看:24
本文介绍了symfony 4 具有文件类型的表单集合实体创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to create and upload the document using entity where fileType field is embedded in parent form via collectionType. I did read the documentation Symfony Upload. But didn't manage to accomplish this. Always get this error "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 实例获取?

I think the problem is the FileType field return attachment entity instance while it should return File instance. the question is how do i get the value as File instance?

推荐答案

在您的情况下,UploadedFilenot $invoice-> 的属性 $path 类型;getAttachments().尝试在没有学说映射的情况下向名为 $file 的 Attachement 类添加一个属性,生成它的 getter 和 setter 方法.

In your case the property $path type of UploadedFile and not $invoice->getAttachments(). Try to add a property to your Attachement class called $file without doctrine mapping, generate it's getter and setter methods.

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

在您的 AttachmentType 类中更改 'path' => 'file'.现在,尝试在您的控制器中更新此部分:

In your AttachmentType class change 'path' => 'file'. Now, try to update this part in your 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().

Please, make your fileUploader service the unique responsible for uploading file, no need to use $file->move().

这篇关于symfony 4 具有文件类型的表单集合实体创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆