首页 文章

symfony 4表单集合实体,文件类型为create

提问于
浏览
1

如何使用通过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" .

下面是我的 Invoice entity

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;
    }

Attachment entity

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;
    }

Attachment form type

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,
        ]);
    }
}

Invoice form type

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

1 回答

  • 0

    在您的情况下属性 $path 类型 UploadedFilenot $invoice->getAttachments() . 尝试在没有doctrine映射的名为 $file 的Attachement类中添加属性,生成它的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));
        }
    

    请使您的fileUploader服务独立负责上传文件,无需使用 $file->move() .

相关问题