This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Create A Contact Form in Symfony With SwiftMailer

Updated on March 12, 2022

7 Min Read
symfony form

So you have created the perfect Symfony powered website but how could people interact with you? How could they express interest in your products and services? For this, you need a contact form so the visitors could send you a direct message. According to many experts, the faster and easier the communication options, the greater the trust of the visitors and customers on the brand.

Symfony offers a mailer feature based on the popular Quick Mailer library through the SwiftMailerBundle. This mailer supports sending messages together with your own mail servers as well as utilizing well-known mail suppliers like Mandrill, SendGrid, and Amazon SES.

In this article, I will help you create a contact form in Symfony using Form Builder. The contact form will be connected to the SwiftMailer Bundle so that the visitor could receive an acknowledgment that the message has been successfully sent.

I will start with the development of the contact form. For the purpose of this article, I have assumed that you have already installed Symfony 3.x on Cloudways PHP hosting. If not, follow this simple guide to installing Symfony 3 on Cloud Server. You can download the framework from GitHub and check out the demo.

Get Code on Github

Create Contact Entity with Doctrine

I will not go into the details of the benefits of Doctrine ORM and how awesome it is.

The first step is to configure the database in Symfony. You can find database related information and credentials in Application Access details panel. Add these to the app/config/parameters.yml

parameters:

   database_host: localhost
   database_port: null
   database_name: xxxuzxxxxxx
   database_user: pyxxxxxxxmj
   database_password: Hdxxxxxxx38U

Now, the second step is to create a Contact entity with Doctrine (if you wish you could use any name for this entity). To use Doctrine, open SSH terminal and go to your Symfony project:

cd application/{your_app_folder}/public_html

Now run the following command to start the entity generator:

Php bin/console doctrine:generate:entity

Doctrine2

In other frameworks, it’s common to distinguish between “forms” and “frame fields”. In Symfony, all of them are “form types”: a single form field is a “form type”. A group of several HTML fields used to input a postal address could be a “form type”;

For the contact form I need four fields: name, email, subject, message. You can add more fields as per your requirements. The entity name will be Contact and the shortcut name will be AppBundle:Contact. Annotation will be Yaml, so just press the Enter key on this.

generate entity

Now go to src/AppBundle/Entity. You will see a Contact.php file in which Doctrine has created a new method for every field. I will use these methods to set values in the Controller:

<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM

/**
* Contact
*
* @ORM\Table(name="contact")
* @ORM\Entity(repositoryClass="AppBundle\Repository\ContactRepository")
*/

class Contact
{
   /**
    * @var int
    *
    * @ORM\Column(name="id", type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */

   private $id;

   /**
    * @var string
    *
    * @ORM\Column(name="name", type="string", length=255)
    */

   private $name;

   /**
    * @var string
    *
    * @ORM\Column(name="email", type="string", length=255)
    */

   private $email;

   /**
    * @var string
    *
    * @ORM\Column(name="subject", type="string", length=255)
    */

   private $subject;

   /**
    * @var string
    *
    * @ORM\Column(name="message", type="string", length=255)
    */

   private $message;

   /**
    * Get id
    *
    * @return int
    */

   public function getId()

   {
       return $this->id;
   }

   /**
    * Set name
    *
    * @param string $name
    *
    * @return Contact
    */

   public function setName($name)
   {
       $this->name = $name;
       return $this;
   }

   /**
    * Get name
    *
    * @return string
    */

   public function getName()
   {
       return $this->name;
   }

   /**
    * Set email
    *
    * @param string $email
    *
    * @return Contact
    */

   public function setEmail($email)
   {
       $this->email = $email;
       return $this;
   }

   /**
    * Get email
    *
    * @return string
    */

   public function getEmail()
   {
       return $this->email;
   }

   /**
    * Set subject
    *
    * @param string $subject
    *
    * @return Contact
    */

   public function setSubject($subject)
   {
       $this->subject = $subject;
       return $this;
   }

   /**
    * Get subject
    *
    * @return string
    */

   public function getSubject()
   {
       return $this->subject;
   }

   /**
    * Set message
    *
    * @param string $message
    *
    * @return Contact
    */

   public function setMessage($message)
   {
       $this->message = $message;
       return $this;
   }

   /**
    * Get message
    *
    * @return string
    */

   public function getMessage()

   {
       return $this->message;
   }

}

Next, I will work on the Controller and the form View.

Related: How to Upgrade From Symfony 2.x to 3.x

Create the Form in DefaultController.php

The next step is to create a form in the controller. You can also create a form in the Twig view. However, in this article, I will initialize the form fields using the Symfony’s form builder, and then show the form Widget in the View.

Open DefaultController.php and add the following namesapaces and the entity (created earlier):

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;

use AppBundle\Entity\Contact;

Now in the createAction() method, create an entity object and pass it to the form builder. The form contains the input fields (as discussed earlier).

class DefaultController extends Controller

{
    /**
    * @Route("/form", name="homepage")
    */

  public function createAction(Request $request)
   {
      $contact = new Contact;     

     # Add form fields
       $form = $this->createFormBuilder($contact)
       ->add('name', TextType::class, array('label'=> 'name', 'attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
       ->add('email', TextType::class, array('label'=> 'email','attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
       ->add('subject', TextType::class, array('label'=> 'subject','attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
       ->add('message', TextareaType::class, array('label'=> 'message','attr' => array('class' => 'form-control')))
       ->add('Save', SubmitType::class, array('label'=> 'submit', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-top:15px')))
       ->getForm();

     # Handle form response
       $form->handleRequest($request);

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Create View for the Contact Form

To view this form on the Twig template, create a file form.html.twig in app/Resources/views/default and add the form widget to it.

{% block body %}

<div class="container">
       <div class="row">
           <div class="col-sm-4">
               <h2 class=page-header>Contact Form in Symfony</h2>

                   {{form_start(form)}}
                   {{form_widget(form)}}
                   {{form_end(form)}}

           </div>
       </div>
</div>

{% endblock %}

What is Form_widget?

Renders the HTML widget of a given field. In case you apply this to a complete form or collection of fields, each fundamental form row will be rendered. The foremost common variable is attr , which is a cluster of HTML qualities to apply to the HTML widget.

I have added bootstrap classes to the code. I will now add the bootstrap CDN to base template to make the classes work.

Open the base.html.twig from app/Resources/views and add the CDN links to it.

<!DOCTYPE html>

<html>
   <head>
       <meta charset="UTF-8" />
       <title>{% block title %}Welcome!{% endblock %}</title>
       {% block stylesheets %}{% endblock %}
       <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
       <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
       <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
   </head>

   <body>
   <div class="alert alert-success">
   {% set flashbag_notices = app.session.flashbag.get('notice') %}
   {% if flashbag_notices is not empty %}
 
   <div class="flash-notice">
       {% for notice in flashbag_notices %}
       {{notice}}
       {% endfor %}
   </div>

{% endif %}
{% block body %}{% endblock %}

</div>
{% block javascripts %}{% endblock %}

   </body>

</html>

Now I need to extend form.html.twig with base.html.twig by simply adding the following line at the top.

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

At this point, if you hit the /form Route, you will get the following Form:

Related: How to Create Simple REST API in Symfony 3.1

Save Values in the Database

The form looks good!

Next, I will save the values in database. I have already created the form in the DefaultController class. I will continue and start saving the input records in the database. First, I will save the values in variables and then pass these variables to the related methods in the entity. Finally, I will save the variables through the persist() method.

# check if form is submitted 

       if($form->isSubmitted() &&  $form->isValid()){
           $name = $form['name']->getData();
           $email = $form['email']->getData();
           $subject = $form['subject']->getData();
           $message = $form['message']->getData(); 

     # set form data   

           $contact->setName($name);
           $contact->setEmail($email);          
           $contact->setSubject($subject);     
           $contact->setMessage($message);                

      # finally add data in database

           $sn = $this->getDoctrine()->getManager();      
           $sn -> persist($contact);
           $sn -> flush();

Now, when the form is submitted, the values will be available in the database.

Send Acknowledgement to the User

It is important to tell the user that their message has been successfully delivered to the website. Many websites send an email that provides all user-submitted data in a proper format.

What is SwiftMailer

I will use SwiftMailer, Swift Mailer is a component-based library for sending emails from PHP applications. It’s a bundle that comes preinstalled in Symfony 3. To use it, you just need to configure it. To do the necessary changes, open app/config/parameters.yml under parameters

   mailer_transport: gmail
   mailer_host: smtp.gmail.com
   mailer_user: [email protected]
   mailer_password: password
   secret: Iknowididstupidthings
   encryption: tls

Now in the config.yml, add the following code to get the values:

# Swiftmailer Configuration

swiftmailer:

      transport: "%mailer_transport%"
      host:      "%mailer_host%"
      username:  "%mailer_user%"
      password:  "%mailer_password%"
      spool:     { type: memory }

The configuration process is over. Now, open DefaultController.php and add the code for SwiftMailer. I will use the same data variables in this code:

$message = \Swift_Message::newInstance()

               ->setSubject($subject)
               ->setFrom('[email protected]')
               ->setTo($email)
               ->setBody($this->renderView('default/sendemail.html.twig',array('name' => $name)),'text/html');

$this->get('mailer')->send($message);

Notice that you can also send email templates. In this code snippet, I sent the email template I created (sendemail.html.twig) in the views/default. This template has a simple test message.

{# app/Resources/views/Emails/sendemail.html.twig #}

<h3>You did it</h3>
Hi {{ name }}! Your Message is successfully Submitted.
We will get back to you soon!
Thanks!

Now, when you submit the form, you will get an acknowledgment email in your inbox:

You Might Also Like: Creating Contact Form in HTML and PHP

Final Words

A contact form is still an essential component of any website. In this article, I created a contact form in Symfony and then added SwiftMailer for generating acknowledgment emails. You can also apply reCAPTCHA in the Contact form for avoiding spam messages. If you have a query or would like to contribute to the discussion, do leave a comment.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahzeb Ahmed

Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now