Step 14: Accepting Feedback with Forms

Accepting Feedback with Forms

Time to let our attendees give feedback on conferences. They will contribute their comments through an HTML form.

Generating a Form Type

Use the Maker bundle to generate a form class:

  1. $ symfony console make:form CommentFormType Comment
  1. created: src/Form/CommentFormType.php
  2. Success!
  3. Next: Add fields to your form and start using it.
  4. Find the documentation at https://symfony.com/doc/current/forms.html

The App\Form\CommentFormType class defines a form for the App\Entity\Comment entity:

src/App/Form/CommentFormType.php

  1. namespace App\Form;
  2. use App\Entity\Comment;
  3. use Symfony\Component\Form\AbstractType;
  4. use Symfony\Component\Form\FormBuilderInterface;
  5. use Symfony\Component\OptionsResolver\OptionsResolver;
  6. class CommentFormType extends AbstractType
  7. {
  8. public function buildForm(FormBuilderInterface $builder, array $options)
  9. {
  10. $builder
  11. ->add('author')
  12. ->add('text')
  13. ->add('email')
  14. ->add('createdAt')
  15. ->add('photoFilename')
  16. ->add('conference')
  17. ;
  18. }
  19. public function configureOptions(OptionsResolver $resolver)
  20. {
  21. $resolver->setDefaults([
  22. 'data_class' => Comment::class,
  23. ]);
  24. }
  25. }

A form type describes the form fields bound to a model. It does the data conversion between submitted data and the model class properties. By default, Symfony uses metadata from the Comment entity - such as the Doctrine metadata - to guess configuration about each field. For example, the text field renders as a textarea because it uses a larger column in the database.

Displaying a Form

To display the form to the user, create the form in the controller and pass it to the template:

patch_file

  1. --- a/src/Controller/ConferenceController.php
  2. +++ b/src/Controller/ConferenceController.php
  3. @@ -2,7 +2,9 @@
  4. namespace App\Controller;
  5. +use App\Entity\Comment;
  6. use App\Entity\Conference;
  7. +use App\Form\CommentFormType;
  8. use App\Repository\CommentRepository;
  9. use App\Repository\ConferenceRepository;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. @@ -31,6 +33,9 @@ class ConferenceController extends AbstractController
  12. #[Route('/conference/{slug}', name: 'conference')]
  13. public function show(Request $request, Conference $conference, CommentRepository $commentRepository): Response
  14. {
  15. + $comment = new Comment();
  16. + $form = $this->createForm(CommentFormType::class, $comment);
  17. +
  18. $offset = max(0, $request->query->getInt('offset', 0));
  19. $paginator = $commentRepository->getCommentPaginator($conference, $offset);
  20. @@ -39,6 +44,7 @@ class ConferenceController extends AbstractController
  21. 'comments' => $paginator,
  22. 'previous' => $offset - CommentRepository::PAGINATOR_PER_PAGE,
  23. 'next' => min(count($paginator), $offset + CommentRepository::PAGINATOR_PER_PAGE),
  24. + 'comment_form' => $form->createView(),
  25. ]));
  26. }
  27. }

You should never instantiate the form type directly. Instead, use the createForm() method. This method is part of AbstractController and eases the creation of forms.

When passing a form to a template, use createView() to convert the data to a format suitable for templates.

Displaying the form in the template can be done via the form Twig function:

patch_file

  1. --- a/templates/conference/show.html.twig
  2. +++ b/templates/conference/show.html.twig
  3. @@ -30,4 +30,8 @@
  4. {% else %}
  5. <div>No comments have been posted yet for this conference.</div>
  6. {% endif %}
  7. +
  8. + <h2>Add your own feedback</h2>
  9. +
  10. + {{ form(comment_form) }}
  11. {% endblock %}

When refreshing a conference page in the browser, note that each form field shows the right HTML widget (the data type is derived from the model):

Step 14: Accepting Feedback with Forms - 图1

The form() function generates the HTML form based on all the information defined in the Form type. It also adds enctype=multipart/form-data on the <form> tag as required by the file upload input field. Moreover, it takes care of displaying error messages when the submission has some errors. Everything can be customized by overriding the default templates, but we won’t need it for this project.

Customizing a Form Type

Even if form fields are configured based on their model counterpart, you can customize the default configuration in the form type class directly:

patch_file

  1. --- a/src/Form/CommentFormType.php
  2. +++ b/src/Form/CommentFormType.php
  3. @@ -4,20 +4,31 @@ namespace App\Form;
  4. use App\Entity\Comment;
  5. use Symfony\Component\Form\AbstractType;
  6. +use Symfony\Component\Form\Extension\Core\Type\EmailType;
  7. +use Symfony\Component\Form\Extension\Core\Type\FileType;
  8. +use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  9. use Symfony\Component\Form\FormBuilderInterface;
  10. use Symfony\Component\OptionsResolver\OptionsResolver;
  11. +use Symfony\Component\Validator\Constraints\Image;
  12. class CommentFormType extends AbstractType
  13. {
  14. public function buildForm(FormBuilderInterface $builder, array $options)
  15. {
  16. $builder
  17. - ->add('author')
  18. + ->add('author', null, [
  19. + 'label' => 'Your name',
  20. + ])
  21. ->add('text')
  22. - ->add('email')
  23. - ->add('createdAt')
  24. - ->add('photoFilename')
  25. - ->add('conference')
  26. + ->add('email', EmailType::class)
  27. + ->add('photo', FileType::class, [
  28. + 'required' => false,
  29. + 'mapped' => false,
  30. + 'constraints' => [
  31. + new Image(['maxSize' => '1024k'])
  32. + ],
  33. + ])
  34. + ->add('submit', SubmitType::class)
  35. ;
  36. }

Note that we have added a submit button (that allows us to keep using the simple {{ form(comment_form) }} expression in the template).

Some fields cannot be auto-configured, like the photoFilename one. The Comment entity only needs to save the photo filename, but the form has to deal with the file upload itself. To handle this case, we have added a field called photo as un-mapped field: it won’t be mapped to any property on Comment. We will manage it manually to implement some specific logic (like storing the uploaded photo on the disk).

As an example of customization, we have also modified the default label for some fields.

The image constraint works by checking the mime type; require the Mime component to make it work:

  1. $ symfony composer req mime

Step 14: Accepting Feedback with Forms - 图2

Validating Models

The Form Type configures the frontend rendering of the form (via some HTML5 validation). Here is the generated HTML form:

  1. <form name="comment_form" method="post" enctype="multipart/form-data">
  2. <div id="comment_form">
  3. <div >
  4. <label for="comment_form_author" class="required">Your name</label>
  5. <input type="text" id="comment_form_author" name="comment_form[author]" required="required" maxlength="255" />
  6. </div>
  7. <div >
  8. <label for="comment_form_text" class="required">Text</label>
  9. <textarea id="comment_form_text" name="comment_form[text]" required="required"></textarea>
  10. </div>
  11. <div >
  12. <label for="comment_form_email" class="required">Email</label>
  13. <input type="email" id="comment_form_email" name="comment_form[email]" required="required" />
  14. </div>
  15. <div >
  16. <label for="comment_form_photo">Photo</label>
  17. <input type="file" id="comment_form_photo" name="comment_form[photo]" />
  18. </div>
  19. <div >
  20. <button type="submit" id="comment_form_submit" name="comment_form[submit]">Submit</button>
  21. </div>
  22. <input type="hidden" id="comment_form__token" name="comment_form[_token]" value="DwqsEanxc48jofxsqbGBVLQBqlVJ_Tg4u9-BL1Hjgac" />
  23. </div>
  24. </form>

The form uses the email input for the comment email and makes most of the fields required. Note that the form also contains a _token hidden field to protect the form from CSRF attacks.

But if the form submission bypasses the HTML validation (by using an HTTP client that does not enforce these validation rules like cURL), invalid data can hit the server.

We also need to add some validation constraints on the Comment data model:

patch_file

  1. --- a/src/Entity/Comment.php
  2. +++ b/src/Entity/Comment.php
  3. @@ -4,6 +4,7 @@ namespace App\Entity;
  4. use App\Repository\CommentRepository;
  5. use Doctrine\ORM\Mapping as ORM;
  6. +use Symfony\Component\Validator\Constraints as Assert;
  7. /**
  8. * @ORM\Entity(repositoryClass=CommentRepository::class)
  9. @@ -21,16 +22,20 @@ class Comment
  10. /**
  11. * @ORM\Column(type="string", length=255)
  12. */
  13. + #[Assert\NotBlank]
  14. private $author;
  15. /**
  16. * @ORM\Column(type="text")
  17. */
  18. + #[Assert\NotBlank]
  19. private $text;
  20. /**
  21. * @ORM\Column(type="string", length=255)
  22. */
  23. + #[Assert\NotBlank]
  24. + #[Assert\Email]
  25. private $email;
  26. /**

Handling a Form

The code we have written so far is enough to display the form.

We should now handle the form submission and the persistence of its information to the database in the controller:

patch_file

  1. --- a/src/Controller/ConferenceController.php
  2. +++ b/src/Controller/ConferenceController.php
  3. @@ -7,6 +7,7 @@ use App\Entity\Conference;
  4. use App\Form\CommentFormType;
  5. use App\Repository\CommentRepository;
  6. use App\Repository\ConferenceRepository;
  7. +use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\Response;
  11. @@ -16,10 +17,12 @@ use Twig\Environment;
  12. class ConferenceController extends AbstractController
  13. {
  14. private $twig;
  15. + private $entityManager;
  16. - public function __construct(Environment $twig)
  17. + public function __construct(Environment $twig, EntityManagerInterface $entityManager)
  18. {
  19. $this->twig = $twig;
  20. + $this->entityManager = $entityManager;
  21. }
  22. #[Route('/', name: 'homepage')]
  23. @@ -35,6 +38,15 @@ class ConferenceController extends AbstractController
  24. {
  25. $comment = new Comment();
  26. $form = $this->createForm(CommentFormType::class, $comment);
  27. + $form->handleRequest($request);
  28. + if ($form->isSubmitted() && $form->isValid()) {
  29. + $comment->setConference($conference);
  30. +
  31. + $this->entityManager->persist($comment);
  32. + $this->entityManager->flush();
  33. +
  34. + return $this->redirectToRoute('conference', ['slug' => $conference->getSlug()]);
  35. + }
  36. $offset = max(0, $request->query->getInt('offset', 0));
  37. $paginator = $commentRepository->getCommentPaginator($conference, $offset);

When the form is submitted, the Comment object is updated according to the submitted data.

The conference is forced to be the same as the one from the URL (we removed it from the form).

If the form is not valid, we display the page, but the form will now contain submitted values and error messages so that they can be displayed back to the user.

Try the form. It should work well and the data should be stored in the database (check it in the admin backend). There is one problem though: photos. They do not work as we have not handled them yet in the controller.

Uploading Files

Uploaded photos should be stored on the local disk, somewhere accessible by the frontend so that we can display them on the conference page. We will store them under the public/uploads/photos directory:

patch_file

  1. --- a/src/Controller/ConferenceController.php
  2. +++ b/src/Controller/ConferenceController.php
  3. @@ -9,6 +9,7 @@ use App\Repository\CommentRepository;
  4. use App\Repository\ConferenceRepository;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. +use Symfony\Component\HttpFoundation\File\Exception\FileException;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. @@ -34,13 +35,22 @@ class ConferenceController extends AbstractController
  12. }
  13. #[Route('/conference/{slug}', name: 'conference')]
  14. - public function show(Request $request, Conference $conference, CommentRepository $commentRepository): Response
  15. + public function show(Request $request, Conference $conference, CommentRepository $commentRepository, string $photoDir): Response
  16. {
  17. $comment = new Comment();
  18. $form = $this->createForm(CommentFormType::class, $comment);
  19. $form->handleRequest($request);
  20. if ($form->isSubmitted() && $form->isValid()) {
  21. $comment->setConference($conference);
  22. + if ($photo = $form['photo']->getData()) {
  23. + $filename = bin2hex(random_bytes(6)).'.'.$photo->guessExtension();
  24. + try {
  25. + $photo->move($photoDir, $filename);
  26. + } catch (FileException $e) {
  27. + // unable to upload the photo, give up
  28. + }
  29. + $comment->setPhotoFilename($filename);
  30. + }
  31. $this->entityManager->persist($comment);
  32. $this->entityManager->flush();

To manage photo uploads, we create a random name for the file. Then, we move the uploaded file to its final location (the photo directory). Finally, we store the filename in the Comment object.

Notice the new argument on the show() method? $photoDir is a string and not a service. How can Symfony know what to inject here? The Symfony Container is able to store parameters in addition to services. Parameters are scalars that help configure services. These parameters can be injected into services explicitly, or they can be bound by name:

patch_file

  1. --- a/config/services.yaml
  2. +++ b/config/services.yaml
  3. @@ -10,6 +10,8 @@ services:
  4. _defaults:
  5. autowire: true # Automatically injects dependencies in your services.
  6. autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
  7. + bind:
  8. + $photoDir: "%kernel.project_dir%/public/uploads/photos"
  9. # makes classes in src/ available to be used as services
  10. # this creates a service per class whose id is the fully-qualified class name

The bind setting allows Symfony to inject the value whenever a service has a $photoDir argument.

Try to upload a PDF file instead of a photo. You should see the error messages in action. The design is quite ugly at the moment, but don’t worry, everything will turn beautiful in a few steps when we will work on the design of the website. For the forms, we will change one line of configuration to style all form elements.

Debugging Forms

When a form is submitted and something does not work quite well, use the “Form” panel of the Symfony Profiler. It gives you information about the form, all its options, the submitted data and how they are converted internally. If the form contains any errors, they will be listed as well.

The typical form workflow goes like this:

  • The form is displayed on a page;
  • The user submits the form via a POST request;
  • The server redirects the user to another page or the same page.

But how can you access the profiler for a successful submit request? Because the page is immediately redirected, we never see the web debug toolbar for the POST request. No problem: on the redirected page, hover over the left “200” green part. You should see the “302” redirection with a link to the profile (in parenthesis).

Step 14: Accepting Feedback with Forms - 图3

Click on it to access the POST request profile, and go to the “Form” panel:

  1. $ rm -rf var/cache

Step 14: Accepting Feedback with Forms - 图4

Displaying Uploaded Photos in the Admin Backend

The admin backend is currently displaying the photo filename, but we want to see the actual photo:

patch_file

  1. --- a/src/Controller/Admin/CommentCrudController.php
  2. +++ b/src/Controller/Admin/CommentCrudController.php
  3. @@ -9,6 +9,7 @@ use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
  4. use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
  5. use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
  6. use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
  7. +use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
  8. use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
  9. use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  10. use EasyCorp\Bundle\EasyAdminBundle\Filter\EntityFilter;
  11. @@ -45,7 +46,9 @@ class CommentCrudController extends AbstractCrudController
  12. yield TextareaField::new('text')
  13. ->hideOnIndex()
  14. ;
  15. - yield TextField::new('photoFilename')
  16. + yield ImageField::new('photoFilename')
  17. + ->setBasePath('/uploads/photos')
  18. + ->setLabel('Photo')
  19. ->onlyOnIndex()
  20. ;

Excluding Uploaded Photos from Git

Don’t commit yet! We don’t want to store uploaded images in the Git repository. Add the /public/uploads directory to the .gitignore file:

patch_file

  1. --- a/.gitignore
  2. +++ b/.gitignore
  3. @@ -1,3 +1,4 @@
  4. +/public/uploads
  5. ###> symfony/framework-bundle ###
  6. /.env.local

Storing Uploaded Files on Production Servers

The last step is to store the uploaded files on production servers. Why would we have to do something special? Because most modern cloud platforms use read-only containers for various reasons. SymfonyCloud is no exception.

Not everything is read-only in a Symfony project. We try hard to generate as much cache as possible when building the container (during the cache warmup phase), but Symfony still needs to be able to write somewhere for the user cache, the logs, the sessions if they are stored on the filesystem, and more.

Have a look at .symfony.cloud.yaml, there is already a writeable mount for the var/ directory. The var/ directory is the only directory where Symfony writes (caches, logs, …).

Let’s create a new mount for uploaded photos:

patch_file

  1. --- a/.symfony.cloud.yaml
  2. +++ b/.symfony.cloud.yaml
  3. @@ -36,6 +36,7 @@ web:
  4. mounts:
  5. "/var": { source: local, source_path: var }
  6. + "/public/uploads": { source: local, source_path: uploads }
  7. hooks:
  8. build: |

You can now deploy the code and photos will be stored in the public/uploads/ directory like our local version.

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.