Symfony Upload File in Embedded Form Is Null
196 votes
1 answers
php - Symfony : how to set a file type in an edit form?
Get the solution ↓↓↓
I take this error when I desire to edit an "effect" in my grade with symfony :
"The course's view data is expected to exist a "Symfony\Component\HttpFoundation\File\File", simply information technology is a "string". You can avoid this fault by setting the "data_class" selection to null or by adding a view transformer that transforms "string" to an instance of "Symfony\Component\HttpFoundation\File\File"."
I follow the documentation and adding this in my controller :
$event->setEventImage( new File($this->getParameter('images_dir').'/'.$result->getEventImage()) );
Simply it does not change anything I don't understand why.
So in that location is my entity :
/** * * @ORM\Column (type="string") * @Assert\NotBlank(message="Merci de charger un fichier au format image.") * @Assert\File(mimeTypes={ "image/*" }) */ private $eventImage; public function getEventImage(): ?string { return $this->eventImage; } public function setEventImage(string $eventImage): self { $this->eventImage = $eventImage; return $this; }
And my Controller :
#[Route('/{id}/edit', proper name: 'events_edit', methods: ['Go','Mail service'])] public function edit(Asking $asking, Events $event, SluggerInterface $slugger): Response { $event->setEventImage( new File($this->getParameter('images_dir').'/'.$consequence->getEventImage()) ); $form = $this->createForm(EventsType::class, $effect); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { /** @var UploadedFile $eventImage */ $eventImage = $form->get('eventImage')->getData(); // this condition is needed because the 'eventImage' field is non required // so the Image file must be processed just when a file is uploaded if ($eventImage) { $originalFilename = pathinfo($eventImage->getClientOriginalName(), PATHINFO_FILENAME); // this is needed to safely include the file name as office of the URL $safeFilename = $slugger->slug($originalFilename); $newFilename = $safeFilename . '-' . uniqid() . '.' . $eventImage->guessExtension(); // Move the file to the directory where images are stored attempt { $eventImage->movement( $this->getParameter('images_dir'), $newFilename ); } take hold of (FileException $due east) { // ... handle exception if something happens during file upload } // updates the 'eventImage' property to shop the image file name // instead of its contents $event->setEventImage($newFilename); } $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('events_index', [], Response::HTTP_SEE_OTHER); } return $this->renderForm('events/edit.html.twig', [ 'event' => $result, 'form' => $form, ]); }
And my EventsType :
public function buildForm(FormBuilderInterface $builder, array $options): void { $architect ->add('title') ->add('subtitle') ->add('content', CKEditorType::class, [ 'label' => 'content', 'required' => false, ]) ->add('dateEvent', DateTimeType::grade, [ 'widget' => 'single_text', 'label' => 'Date d\'arrivée : ' ]) ->add together('place') ->add('dateDead', DateType::class, [ 'widget' => 'single_text', 'label' => 'Appointment limite d\'inscription : ' ]) ->add('numberPersonRestricted') ->add together('eventImage', FileType::class, [ 'label' => 'Image (fichier image)', 'required' => false, 'constraints' => [ new File([ 'maxSize' => '1024k', 'mimeTypes' => [ 'image/*', ], 'mimeTypesMessage' => 'Please upload a valid image', ]) ] ]) ; } public role configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => Events::class, ]); }
Undefined asked
44
votes
Answer
Solution:
->add('eventImage', FileType::grade, [ 'label' => 'Image (fichier epitome)', 'required' => false, 'constraints' => [ new File([ 'maxSize' => '1024k', 'mimeTypes' => [ 'image/*', ], 'mimeTypesMessage' => 'Delight upload a valid image', ]) ] 'data_class' => null ])
in your formtype, you lot can add together the parameter 'data_class' => null (like the example to a higher place) to eventImage will remove warning and work if y'all add together new file but for edit if you don't add new file it should persist null in your bd.
To overcome this trouble in social club to be able to pre-fill the file field if a file exists is to practise something like pointing to the location of the file. i.eastward. the path of the file that is saved in your database.
So what y'all're doing is checking your view to see if a file exists for the file path that exists in the database and and so pre-filling it by doing something like this (don't forget to change with your upload path):
{% if class.eventImage.vars.data %} <img src="{{ asset('/uploads/directory/' ~ form.eventImage.vars.data.filename) }}"/>{% endif %}
Undefined answered
Link to answer
Source
Share
Didn't detect the reply?
Our customs is visited by hundreds of spider web development professionals every day. Inquire your question and go a quick answer for free.
Like questions
Find the answer in like questions on our website.
Write quick reply
Do you know the answer to this question? Write a quick response to it. With your help, nosotros volition make our community stronger.
About the technologies asked in this question
PHP
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported past most hosting providers, it is i of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cantankerous-platform, functionality and distribution of source codes under its own license.
https://www.php.cyberspace/
Symfony
Symfony compares favorably with other PHP frameworks in terms of reliability and maturity. This framework appeared a long time agone, in 2005, that is, it has existed much longer than most of the other tools we are because. It is popular for its spider web standards compliance and PHP blueprint patterns.
https://symfony.com/
Foundation
Foundation, similar to Bootstrap, has become very popular as a more complex framework with some advanced simply easy-to-implement CSS components. It is built with Sass, and so just similar Bootstrap, information technology is customizable. In addition to this, it besides boasts some features that assistance make the design mobile responsive.
https://go.foundation/
HTML
HTML (English "hyper text markup language" - hypertext markup linguistic communication) is a special markup language that is used to create sites on the Internet. Browsers understand html perfectly and tin translate it in an understandable fashion. In general, whatsoever page on the site is html-code, which the browser translates into a user-friendly course. Past the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to programmierfrage.com
programmierfrage.com is a question and reply site for professional web developers, programming enthusiasts and website builders. Site created and operated past the community. Together with you lot, nosotros create a gratuitous library of detailed answers to any question on programming, web development, website creation and website administration.
Become answers to specific questions
Ask near the real problem y'all are facing. Describe in particular what you are doing and what you lot want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you lot find a question and know the answer to it, aid others with your knowledge.
Source: https://programmierfrage.com/items/symfony-how-to-set-a-file-type-in-an-edit-form
0 Response to "Symfony Upload File in Embedded Form Is Null"
Postar um comentário