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

标签 php symfony symfony-forms symfony4

如何使用实体创建和上传文档,其中 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/

相关文章:

Symfony2 : displaying form entity field type as radio buttons

php - Laravel 5 函数名必须是字符串错误

php - Magento 无法使用正确的用户名和密码登录管理员

PHP 从数组创建正确的字符串

apache - 在没有 mod_deflate 的情况下在 Symfony 2 中使用 gzip/compression

php - Symfony 表单与 RESTful API 的序列化程序

PHP 删除按钮

apache - 设置 Symfony2 以使用 apache + php-fpm

php - 如何在 Symfony 2.7 中关闭用户的所有 session ?

symfony - 在 symfony2 表单中使用 isValid() 不验证子类型