A
A
Andrey Ryazantsev2019-12-29 12:05:40
symfony
Andrey Ryazantsev, 2019-12-29 12:05:40

How to edit an entity with a field of type File?

There is a Project entity, it is connected to the Document entity through the documentation field with the OneToMany connection.

/**
     * @ORM\OneToMany(targetEntity="App\Entity\Document", mappedBy="project")
     */
    private $documentation;

    public function __construct()
    {
        $this->documentation = new ArrayCollection();
    }

Document is just a storage for uploaded files, this table shows the path to the file, who uploaded it, type, etc. The form for Project looks like this:
class ProjectType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('name')
            ->add('documentation', FileType::class, [
                'data_class' => null,
                'mapped'     => false,
            ]);
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults([
            'data_class' => Project::class,
        ]);
    }
}

I process the result of the form like this:
/**
     * @Route("/new", name="project_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $project = new Project();

        $form = $this->createForm(ProjectType::class, $project);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $document = new Document();
            $uploadedFile = $form['documentation']->getData();
            $document->setFile($uploadedFile);
            $document->setUploadDir($this->getParameter('kernel.root_dir') . $this->getParameter('upload_directory'));
            $document->setPath($this->getParameter('upload_directory'));
            $document->upload();
            $project->addDocumentation($document);
            $em = $this->getDoctrine()->getManager();
            $em->persist($project);
            $em->persist($document);
            $em->flush();

            return $this->redirect($this->generateUrl('project_index'));
        }
        $user = $this->getUser();
        return $this->render('project/new.html.twig', array(
            'form' => $form->createView(),
            'user' => $user,
        ));
    }

Question:
1. How to edit Project? The file is not showing up right now. I cannot replace or remove it.
2. How to do multiple file uploads?
Please do not use different bundles, I would like to understand the process in pure Symfony.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question