Answer the question
In order to leave comments, you need to log in
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();
}
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,
]);
}
}
/**
* @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,
));
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question