Building A Basic To-Do Application With Symfony 3- Part 2
In this tutorial, we will building on what we started in the first part of the tutorial. So, I will be explaining some concepts in Symfony while I build the Todo-Application. Some of these concepts include bundle , configurations , entity to mention but a few. So, let us continue.
Create New Bundle
In symfony, a notable term in Symfony is bundle
and as the name implies, it is a collection that includes folders like Controller , Entity , DependencyInjections , Form , Resource and so on. So, we have to create a bundle for our To-Do Application with the commands below
php bin/console generate:bundle
Once you do that, you will have to interact with your terminal by answering the question that comes out. Let your answer follow the image below.
Check the src
folder and you will see our new bundle named TodoBundle
. You can check for the folders in the the bundle and check the files there. Before we proceed, you need to do 4 things
- Delete
AppBundle
in the thesrc
folder - Go to
/app/AppKernel.php
then removenew AppBundle\AppBundle(),
from the file so as not to cause any issue later on. TheAppKernel.php
file registers the bundles used in the application. - Go to
app/config
folder. This is where all configuration files of the application are stored. Then, go to therouting.yml
file , clear everything in the file and make it look like the below.
todo: resource: "@TodoBundle/Controller/" type: annotation prefix: /
Run php bin/console server:run
in your console, if your server is not up and then, fire up your browser. You should see this
Setting Up Database
To be able to save our todo list, we need to setup our database and to do this, you have to go to parameters.yml
file in app/config/
folder and adjust the settings of your database.
database_host: 127.0.0.1 database_port: 3306 database_name: todo-app database_user: root database_password: null
Once you put the correct details, your database configuration will be fully set but if you are a badass developer and you want to use another database engine, you can change that in the app/config/config.php
file.
Create Entity
In symfony, instead of having models like in Laravel or other frameworks, we have entity and it is very important when building web applications that involve saving and reading of data with Symfony. So, we will create an entity called Todo
and to keep this tutorial simple, this entity will contain a column called title
. Creating entities in Symfony is super amazing as you can do that with just the simple command below and it will create getter
and setter
methods for you. Answer the interactive questions after running the command
php bin/console generate:doctrine:entity
So, once that is done check your TodoBundle
folder and you will see 2 new folders created: Entity
and Repository
.
Using the Database
Now, we want to create a new database and update the database. This can be done with simple commands in Symfony.
php bin/console doctrine:database:create
This command will create a database with the name set in your parameters.yml
file
php bin/console doctrine:schema:update --force
While this command will update the database with enities created.
Creating Form For Todo App
One unique feature of symfony is that you don't need to manually create forms. Forms get created with only one terminal command and few codes. Let us create a form for our application. Note that the last arguement in the command is the bundle name followed by the entity nam e you want to create a form from
php bin/console generate:doctrine:form TodoBundle:Todo
Check your src/TodoBundle
. You will see a folder called Form
with a file TodoType.php
in it. That shows the command worked.
Setting Up The View
Yippy!!! we have been writing codes and running commands in terminals but we have not touched the view of the application. We are going to do that in some minutes. Symfony uses a template engine called Twig and it is very powerfull. So we will be seeing it in action in our code.
- First, go to
app/Resources/views/base.html.twig
file. That is the the layout we will be working with in the tutorial. It should look like this.
<!DOCTYPE html>
<html>
<head> <meta charset="UTF-8" /> <title>{% block title %}My To-do Application{% endblock %}</title> {% block stylesheets %}{% endblock %} <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
{% block body %}{% endblock %}
{% block javascripts %}{% endblock %}
</body>
</html>
- Go to
src/TodoBundle/Resources/views/Default/index.html.twig
and make the file have the following inside.
{% extends 'base.html.twig' %}
{% form_theme form 'bootstrap_3_layout.html.twig' %}
{% block body %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-2"> <h1 class="text-center">Add to my To-Do List</h1> {{ form(form) }} </div> </div> </div>
{% endblock %}
The statement {{ form(form) }}
above renders the form on the browser after the form must have been initialized in the controller. {% form_theme form 'bootstrap_3_layout.html.twig' %}
statement is just to tell our form to make use of bootstrap theme.
Update Controller
So, after setting up the view, we cannot run our application until we have the controller method fully setup. So in the controller we are working with, we want to initialize the form to be displayed in the view and also handle the form request. We will do this by going to /src/TodoBundle/Controller/DefaultController.php
file and then updating the code with the below.
<?php namespace TodoBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use TodoBundle\Entity\Todo;
use TodoBundle\Form\TodoType; class DefaultController extends Controller
{ /** * @Route("/", name="todo_create") */ public function indexAction(Request $request) { $todo = new Todo(); $form = $this->createForm(TodoType::class,$todo); $form->add('submit', SubmitType::class, array( 'label' => 'Add To-Do', 'attr' => array('class' => 'btn btn-primary pull-right') )); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($todo); $em->flush(); return $this->redirect($this->generateUrl( 'todo_list' )); } return $this->render('TodoBundle:Default:index.html.twig',['form' => $form->createView()]); }
}
Before we run the application we need to create a page where we will be redirected to after submitting the form. We will do this by doing the following below:
- Create a file with the name
list.html.twig
in/src/TodoBundle/Resources/views/Default
folder - Go to controller and make sure your controller looks like the below.
<?php namespace TodoBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use TodoBundle\Entity\Todo;
use TodoBundle\Form\TodoType; class DefaultController extends Controller
{ /*** @Route("/", name="todo_create") */ public function indexAction(Request $request) { $todo = new Todo(); $form = $this->createForm(TodoType::class,$todo); $form->add('submit', SubmitType::class, array( 'label' => 'Add To-Do', 'attr' => array('class' => 'btn btn-primary pull-right') )); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($todo); $em->flush(); return $this->redirect($this->generateUrl( 'todo_list' )); } return $this->render('TodoBundle:Default:index.html.twig',['form' => $form->createView()]); } /** * @Route("/my/todos", name="todo_list") */ public function listAction() { return $this->render('TodoBundle:Default:list.html.twig'); }
}
- Add to
list.html.twig
in/src/TodoBundle/Resources/views/Default
folder the below:
{% extends 'base.html.twig' %}
{% block body %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-2"> <h1 class="text-center">To do list created successfully</h1> </div> </div> <div class="row"> <div class="col-md-6 col-md-offset-2"> <h3 class="text-center">List To-do Here</h3> </div> </div> </div>
{% endblock %}
Run The App
We can now go to our browser to test the application and Yipee!!! You should see the below.
Don't Miss Out On The Other Parts Of The Tutorial
Building A Basic To-Do Application With Symfony 3- Part 1
Building A Basic To-Do Application With Symfony 3- Part 3
Like this article? Follow @goodnesskayode on Twitter