Here's a step-by-step implementation of a contact form with phone number and email validation in Symfony:
1. Create the Contact Entity
php
<?php
// src/Entity/Contact.php
namespace App\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Contact
{
#[Assert\NotBlank]
private ?string $name = null;
#[Assert\NotBlank]
#[Assert\Email(message: 'Please enter a valid email address.')]
private ?string $email = null;
#[Assert\PhoneNumber(message: 'Please enter a valid phone number.')]
private ?string $phone = null;
#[Assert\NotBlank]
private ?string $message = null;
// Getters and Setters
public function getName(): ?string { return $this->name; }
public function setName(string $name): self { $this->name = $name; return $this; }
public function getEmail(): ?string { return $this->email; }
public function setEmail(string $email): self { $this->email = $email; return $this; }
public function getPhone(): ?string { return $this->phone; }
public function setPhone(string $phone): self { $this->phone = $phone; return $this; }
public function getMessage(): ?string { return $this->message; }
public function setMessage(string $message): self { $this->message = $message; return $this; }
}
2. Create the Form Type
php
<?php
// src/Form/ContactType.php
namespace App\Form;
use App\Entity\Contact;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TelType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', TextType::class, [
'attr' => ['class' => 'form-control', 'placeholder' => 'John Doe']
])
->add('email', EmailType::class, [
'attr' => ['class' => 'form-control', 'placeholder' => 'john@example.com']
])
->add('phone', TelType::class, [
'required' => false,
'attr' => ['class' => 'form-control', 'placeholder' => '+1234567890']
])
->add('message', TextareaType::class, [
'attr' => ['class' => 'form-control', 'rows' => 5, 'placeholder' => 'Your message...']
])
->add('submit', SubmitType::class, [
'label' => 'Send Message',
'attr' => ['class' => 'btn btn-primary mt-3']
]);
}
}
3. Create the Controller
php
<?php
// src/Controller/ContactController.php
namespace App\Controller;
use App\Entity\Contact;
use App\Form\ContactType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class ContactController extends AbstractController
{
#[Route('/contact', name: 'app_contact')]
public function contact(Request $request): Response
{
$contact = new Contact();
$form = $this->createForm(ContactType::class, $contact);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Handle valid form submission (e.g., send email)
// $this->sendEmail($contact);
return $this->redirectToRoute('contact_success');
}
return $this->render('contact/index.html.twig', [
'form' => $form->createView(),
]);
}
#[Route('/contact/success', name: 'contact_success')]
public function success(): Response
{
return $this->render('contact/success.html.twig');
}
}
4. Create the Twig Template
twig
{# templates/contact/index.html.twig #}
{% extends 'base.html.twig' %}
{% block title %}Contact Us{% endblock %}
{% block body %}
<div class="container mt-5">
<h1 class="mb-4">Contact Form</h1>
{{ form_start(form, {'attr': {'class': 'needs-validation', 'novalidate': 'novalidate'}}) }}
<div class="mb-3">
{{ form_row(form.name) }}
</div>
<div class="mb-3">
{{ form_row(form.email) }}
</div>
<div class="mb-3">
{{ form_row(form.phone) }}
</div>
<div class="mb-3">
{{ form_row(form.message) }}
</div>
{{ form_row(form.submit) }}
{{ form_end(form) }}
</div>
{% endblock %}
5. Add CSS Styling (Optional)
twig
{# Add this to your base.html.twig or in a separate CSS file #}
<style>
.form-control {
border-radius: 8px;
padding: 12px;
border: 1px solid #ced4da;
transition: border-color 0.3s ease;
}
.form-control:focus {
border-color: #007bff;
box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
}
.btn-primary {
padding: 10px 20px;
border-radius: 5px;
background-color: #007bff;
border: none;
}
.invalid-feedback {
color: #dc3545;
font-size: 0.875em;
}
</style>
Key Features:
- Email Validation: Uses Symfony's built-in
Email constraint
- Phone Validation: Uses Symfony's
PhoneNumber constraint (requires symfony/validator and libphonenumber)
- Modern UI: Includes Bootstrap-compatible classes and custom CSS
- Server-Side Validation: All validation rules are enforced server-side
- Responsive Design: Works on mobile and desktop devices
To use this implementation:
- Install required dependencies:
composer require symfony/validator
- Create the necessary templates and routing configuration
- Add form handling logic in the controller to process valid submissions
The form will automatically validate:
- Email format
- Phone number format (international format)
- Required fields (name, email, and message)
- Proper HTML5 validation attributes will be added to the form fields