Symfony 5 Créer un formulaire de Contact

Les composants Mailer & Mime de Symfony vous donne un puissant système pour la création et l’envoi d’e-mails – avec la prise en charge des messages en plusieurs parties, l’intégration Twig, l’insertion CSS, les pièces jointes et bien plus encore.

Commençons l’installation avec cette commande :

composer require symfony/mailer

Ajoutons ou modifions dans notre fichier .env

###> symfony/mailer ###
MAILER_DSN=smtp://YOUR@MAİL.com:PASSWORD@smtp.votreserveur.com:465?encryption=ssl&auth_mode=login
###< symfony/mailer ###

services.yaml

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    locale: 'en'
services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

Créons notre Controlleur avec cette commande :

php bin/console make:controller ContactController

Créer 3 champs : nom, email, et message

src/Controller/ContactController.php

<?php

namespace App\Controller;

use App\Form\ContactType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Mailer\MailerInterface;

class ContactController extends AbstractController
{
    /**
     * @Route("/contact", name="contact")
     */
    public function index(Request $request, MailerInterface $mailer)
    {
        $form = $this->createForm(ContactType::class);
        $form->handleRequest($request);


        if($form->isSubmitted() && $form->isValid()) {

            $contactFormData = $form->getData();
            
            $message = (new Email())
                ->from($contactFormData['email'])
                ->to('ton@gmail.com')
                ->subject('vous avez reçu unn email')
                ->text('Sender : '.$contactFormData['email'].\PHP_EOL.
                    $contactFormData['Message'],
                    'text/plain');
            $mailer->send($message);

            $this->addFlash('success', 'Vore message a été envoyé');

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

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

contact/index.html.twig;

{% extends 'base.html.twig' %}

{% block body %}
<div class="bg-white p-5 contact-form">
    <div class="form-group">
{{ form_start(our_form) }}
    {{ form_row(our_form.fullName, {'attr': {'class': 'form-control'}}) }}


</div>
<div class="form-group">
    {{ form_row(our_form.email, {'attr': {'class': 'form-control'}}) }}

</div>
<div class="form-group">
    {{ form_row(our_form.message, {'attr': {'class': 'form-control'}}) }}

</div>

<div class="form-group">
    <input type="submit" value="Send" class="btn btn-primary py-3 px-5">
</div>
{{ form_end(our_form) }}
</div>

</div>
{% endblock %}

ContactType;

<?php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nom',TextType::class, [
            ])
            ->add('email',EmailType::class, [
            ])
            ->add('message', TextareaType::class, [
                'attr' => ['rows' => 6],
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
        ]);
    }
}

contact/index.html.twig;

{% block body %}
<div class="col-sm-12">
    <div class="form-group">
{{ form_start(our_form) }}
    {{ form_row(our_form.fullName, {'attr': {'class': 'form-control'}}) }}


</div>
<div class="form-group">
    {{ form_row(our_form.email, {'attr': {'class': 'form-control'}}) }}

</div>
<div class="form-group">
    {{ form_row(our_form.message, {'attr': {'class': 'form-control'}}) }}

</div>

<div class="form-group">
    <input type="submit" value="Send" class="btn btn-primary py-3 px-5">
</div>
{{ form_end(our_form) }}
</div>

</div>
{% endblock %}