PDF文档创建 EasyAdmin symfony 5

PDF document creation EasyAdmin symfony 5

我有这个配置允许我在 CRUD 中创建一个 pdf 文档,有没有办法在 CRUD easyAdmin 中添加这个代码或者 link 我的 EasyAdmin documentos 的 CRUD 到 symfony 的 CRUD . 我在 EasyAdmin table

中创建文档时遇到问题

DocumentController.php

<?php

namespace App\Controller;

use App\Entity\Document;
use App\Form\DocumentType;
use App\Repository\DocumentRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Service\FileUploader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

/**
 * @IsGranted("ROLE_USER")
 * @Route("/documents")
 */
class DocumentController extends AbstractController
{
    /**
     * @Route("/", name="document_index", methods={"GET"})
     */
    public function index(DocumentRepository $documentRepository): Response
    {
        return $this->render('document/index.html.twig', [
            'documents' => $documentRepository->findAll([], ['created_at' => 'desc']),
        ]);
    }

    /**
     * @Route("/new", name="document_new", methods={"GET","POST"})
     */
    public function new(Request $request, FileUploader $fileUploader): Response
    {
        $document = new Document();
        $document->setCreatedAt(new \DateTime('now'));
        $form = $this->createForm(DocumentType::class, $document);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $file = $form['fileDocument']->getData();

            $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $fileName = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
            $fileName = md5(uniqid()) . '.' . $file->guessExtension();
            $file->move(
                $this->getParameter('brochures_directory'),
                $fileName
            );

            $document->setFileDocument($fileName);
            $entityManager->persist($document);
            $entityManager->flush();

            return $this->redirectToRoute('document_index', array('id' => $document->getId()));
        }

        return $this->render('document/new.html.twig', [
            // 'document' => $document,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="document_show",  methods={"GET"})
     */
    public function show(Document $document): Response
    {
        return $this->render('document/show.html.twig', [
            'document' => $document,
        ]);
    }

    /**
     * @Route("/{id}/edit", name="document_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Document $document): Response
    {
        $form = $this->createForm(DocumentType::class, $document);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $file = $form['fileDocument']->getData();


            $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
            // this is needed to safely include the file name as part of the URL
            $fileName = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
            $fileName = md5(uniqid()) . '.' . $file->guessExtension();
            $file->move(
                $this->getParameter('brochures_directory'),
                $fileName
            );

            $document->setFileDocument($fileName);

            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('document_index');
        }

        return $this->render('document/edit.html.twig', [
            'document' => $document,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="document_delete", methods={"DELETE"})
     */
    public function delete(Request $request, Document $document): Response
    {
        if ($this->isCsrfTokenValid('delete' . $document->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($document);
            $entityManager->flush();
        }

        return $this->redirectToRoute('document_index');
    }
}

DocumentCrudController 轻松管理

<?php

namespace App\Controller\Admin;

use App\Entity\Document;
use App\Entity\Publication;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Validator\Constraints\File;

class DocumentCrudController extends AbstractCrudController
{
    public static function getEntityFqcn(): string
    {
        return Document::class;
    }

    
    public function configureCrud(Crud $crud): Crud
    {
        return $crud
                ->setPageTitle(Crud::PAGE_INDEX, 'Liste de Documents')
        ;
          
    }
    
    public function configureFields(string $pageName): iterable
    {

        ImageField::new('fileDocument', 'Document PDF')->setFormType(FileType::class)
        ->setBasePath('docs');

        return [
            IdField::new('id')->onlyOnIndex(),
            TextField::new('nomDocument', 'Titre'),
            DateTimeField::new('created_at', 'Date de création'),
            TextField::new('fileDocument', 'Document PDF')                       
            ->hideOnIndex()
            ->setFormType(FileType::class, [
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'application/pdf',
                            'application/x-pdf',
                        ],
                        'mimeTypesMessage' => 'Veuillez télécharger un document PDF valide',
                    ])
                ],
            ]),

            
        ];
    }
     
      
    public function configureActions(Actions $actions): Actions
    {
        return $actions
            ->add(Crud::PAGE_INDEX, Action::DETAIL);
    }
}

我不知道如何在 easy admin 中实现相同的配置。 Look Here 这是我从 table EasyAdmin 创建文档时发生的情况。 谢谢。

这有点奇怪,但您需要使用 ImageField (https://symfony.com/bundles/EasyAdminBundle/current/fields/ImageField.html)

在你的 CrudController 中:

public function configureFields(string $pageName): iterable{
    return [
        
        ImageField::new('pdf', 'Your PDF')
                    ->setFormType(FileUploadType::class)
                    ->setBasePath('documents/') //see documentation about ImageField to understand the difference beetwen setBasePath and setUploadDir
                    ->setUploadDir('public/documents/')
                    ->setColumns(6)
                    ->hideOnIndex()
                    ->setFormTypeOptions(['attr' => [
                            'accept' => 'application/pdf'
                        ]
                    ]),
        
    ];
}

查看有关 ImageField 的文档以了解 setBasePath 和 setUploadDir 之间的区别

----- 编辑 ----

在您的 CRUD 索引页面中,您可以像这样为您的文件创建一个 link:

public function configureFields(string $pageName): iterable{
    return [
        
        ImageField::new('pdf', 'Your PDF')
                    ->setFormType(FileUploadType::class)
                    ->setBasePath('documents/') //see documentation about ImageField to understand the difference beetwen setBasePath and setUploadDir
                    ->setUploadDir('public/documents/')
                    ->setColumns(6)
                    ->hideOnIndex()
                    ->setFormTypeOptions(['attr' => [
                            'accept' => 'application/pdf'
                        ]
                    ]),
        TextField::new('pdf')->setTemplatePath('admin/fields/document_link.html.twig')->onlyOnIndex(),
        
    ];
}

你的 templates/admin/fields/document_link.html.twig :

{% if field.value %}
    <a href="{{ field.value }}" target="_blank">Download file</a>
{% else %}
    --
{% endif %}