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.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Finalizing A To-Do App Using Symfony 3.1

Updated on April 8, 2021

5 Min Read

In the second installment of this series, I introduced a to-do app that I built to demonstrate the capabilities of Symfony  3.1 and covered the following topics:

  1. Directory Structure
  2. Creating first Controller
  3. Creating a Database entity with Doctrine
  4. Adding Bootstrap
  5. Create new Templates

finalize to-do app in symfony 3.1

I hope you are up to speed with these parts of the app. Let’s get started with the rest of the app. The main focus of this piece is TodoController.php and the template files present in Views/todo folder. Follow the steps below:

Step 6 : Create List Method and Route

To show a list of all to-do items we first need to make a method and route in our parent controller which is TodoController. Go to src/AppBundle/Controller and open TodoController.php. Now add the following code in between the braces of the class. In fact, all methods and routes will be defined in this class.

You might be interested in: How to Install Symfony 3 on Cloud

/**
     * @Route(/todolist/web, name=todo_list)
*/

    public function listAction(Request $request)
    {
        $todos = $this->getDoctrine()
        ->getRepository('AppBundle:Todo')
        ->findAll();
        
        return $this->render('todos/index.html.twig', array(
            'todos' => $todos
            
        ));
    }

First, we made a route call when the user hits the URL /todolist/web.  It will be redirected to index.html.twig, that will display the list of all to-do items. Next, we send a request to the entity made by Doctrine to fetch all to-do items from the database. Once all to-do items have been properly fetched, they are stored in a variable named $todos.
Now open index.html.twig and add the following code:

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

{% block body %}
</br></br></br></br>
   <table class=table table-bordered>
    <thead>
      <tr>
        <th>#</th>
        <th>Todo</th>
         <th>Assigned Date</th>
        <th>Due Date</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
    {% for todo in todos %}
      <tr>
        <td scope=row>{{todo.id}}</td>
        <td>{{todo.name}}</td>
        <td>{{todo.createDate | date('F j, Y, g:i a')}}</td>
        <td>{{todo.duedate | date('F j, Y, g:i a')}}</td>
        <td>
        <a href=todos/details/{{todo.id}} class=btn btn-success>View</a>
        <a href=todos/edit/{{todo.id}} class=btn btn-default>Edit</a>
        <a href=todos/delete/{{todo.id}} class=btn btn-danger>Delete</a>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
{% endblock %}

Related:

Look at line 1. This is how the base template could be easily extended.

Todo

Step 7: Create To-dos using Form Builder

The next step is to create the to-dos. Symfony provides a great form builder method that creates the form and then insert records in the database.

First we will make a route call and then a form. This form makes a request to Doctrine for get/set records according to the entity. Data will now be saved to a variable $todo. Finally the doctrine manager will save records to the database and resets the form.

If the record was saved successfully, a flash message will appear and the page redirects to home route.

We must initialize the createview() method in order to show the form on the page. Add the following code in the  TodoController class.

  /**
     * @Route(/todos/create, name=todo_create)
     */
    public function createAction(Request $request)
    {
        $todo = new Todo;
      
        $form = $this->createFormBuilder($todo)
        ->add('name', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        ->add('category', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        ->add('description', TextareaType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        // ->add('priority', ChoiceType::class, array('choices' => array('Low' => 'Low', 'Normal' => 'Normal', 'High'=>'High'), 'attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        ->add('due_date', DateTimeType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        ->add('Save', SubmitType::class, array('label'=> 'Create Todo', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))
        ->getForm();
        
        $form->handleRequest($request);
        if($form->isSubmitted() &&  $form->isValid()){
            $name = $form['name']->getData();
            $category = $form['category']->getData();
            $description = $form['description']->getData();
            $due_date = $form['due_date']->getData();
            $name = $form['name']->getData();
            
            $now = new\DateTime('now');  
            
            $todo->setName($name);
            $todo->setCategory($category);          
            $todo->setDescription($description);                  
            $todo->setDuedate($due_date);          
            $todo->setCreateDate($now);    
            
            $sn = $this->getDoctrine()->getManager();      
            $sn -> persist($todo);
            $sn -> flush();
            
            $this->addFlash(
                'notice',
                'Todo Added'
            );
            return $this->redirectToRoute('todo_list');            
           
        }
        
        return $this->render('todos/create.html.twig', array(
            'form' => $form->createView()
            
        ));
    }

Now open edit.html.twig and add the following code to call the form present in the controller method.

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

{% block body %}
<h2 class=page-header>Edit Todos</h2>
{{form_start(form)}}
{{form_widget(form)}}
{{form_end(form)}}
{% endblock %}

Add todo

Step 8: View Details of Todos

To view the details of any to-do item, add the following code in TodoController. This will take the id as parameter and show details of related to-do from the database.

 /**
     * @Route(/todos/details/{id}, name=todo_details)
     */
    public function detailsAction($id)
    {
         $todos = $this->getDoctrine()
        ->getRepository('AppBundle:Todo')
        ->find($id);
        
        return $this->render('todos/details.html.twig', array(
            'todo' => $todos
        ));
    }

Now open its template file which is detail.html.twig. Add the following code to it.

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

{% block body %}
</br></br></br>
<a href=/todolist/web class=btn btn-default>Back to Todos</a>
<h2 class=page-header>{{todo.name}}</h2>
<ul class=list-group>
<li class=list-group-item>Category : {{todo.category}}</li>
<li class=list-group-item>Description : {{todo.description}}</li>
<li class=list-group-item>Due: {{todo.duedate | date('F j, Y, g:i a')}}</li>
</ul>

{% endblock %}

Now click on the view button to show the details

Make a Blog

Step 9: Edit To-dos using Form Builder

Editing to-do items is similar to creating them. The only difference is that we first get the data in the $todo variable and then make a form through the createFormBuilder method. After altering records, the same process is performed. The request generated by the form is transferred to Doctrine, which saves data in the  database and redirects to the home page.

Add the following code to the TodoController class.

/**
     * @Route(/todos/edit/{id}, name=todo_edit)
     */
    public function editAction($id,Request $request)
    {
         $now = new\DateTime('now');  
         $todo = $this->getDoctrine()
        ->getRepository('AppBundle:Todo')
        ->find($id);
        
            $todo->setName($todo->getName());
            $todo->setCategory($todo->getCategory());          
            $todo->setDescription($todo->getDescription());                  
            $todo->setDuedate($todo->getDueDate());          
            $todo->setCreateDate($now);        
      
        $form = $this->createFormBuilder($todo)
        ->add('name', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        ->add('category', TextType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        ->add('description', TextareaType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        
        ->add('due_date', DateTimeType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
        ->add('Save', SubmitType::class, array('label'=> 'Update Todo', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))
        ->getForm();
        
        $form->handleRequest($request);
        if($form->isSubmitted() &&  $form->isValid()){
            $name = $form['name']->getData();
            $category = $form['category']->getData();
            $description = $form['description']->getData();
            $due_date = $form['due_date']->getData();
            $name = $form['name']->getData();
            
           
            $sn = $this->getDoctrine()->getManager();
            $todo = $sn->getRepository('AppBundle:Todo')->find($id);
            
            $todo->setName($name);
            $todo->setCategory($category);          
            $todo->setDescription($description);                  
            $todo->setDuedate($due_date);          
            $todo->setCreateDate($now);          
      
            $sn -> flush();
            
            $this->addFlash(
                'notice',
                'Todo Updated'
            );
            return $this->redirectToRoute('todo_list');            
           
        }
        
        return $this->render('todos/edit.html.twig', array(
            'todo' => $todo,
            'form' => $form->createView()
        ));
        
    }

Now open edit.html.twig file from the views folder and add the following code in it.

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

{% block body %}
<h2 class=page-header>Edit Todos</h2>
{{form_start(form)}}
{{form_widget(form)}}
{{form_end(form)}}
{% endblock %}

Update Todo

Step 10: Delete To-dos

Finally, to delete a to-do, add the following code. The id of a to-do item is passed as the method’s parameter:

 /**
     * @Route(/todos/delete/{id}, name=todo_delete)
     */ 
    public function deleteAction($id)
    {
        
         $sn = $this->getDoctrine()->getManager();
         $todo = $sn->getRepository('AppBundle:Todo')->find($id);
         
         $sn->remove($todo);
         $sn->flush();
        //  $todos = $this->getDoctrine()
        // ->getRepository('AppBundle:Todo')
        // ->find($id);
        
         $this->addFlash(
                'notice',
                'Todo Removed'
            );
          return $this->redirectToRoute('todo_list');             
    }

Final Words

In this series of  articles, i have shown how easy it is to create a simple to-do app in Symfony 3.1 using controllers, templates and some basic database configuration. You can also work independently without using Doctrine, but for Symfony 3.1, I consider it a best practice.

In the upcoming installment of this series, I will discuss how Symfony 3.1 managed user registration and login via FOSUserBundle. Here is a short introduction and list of major topics in this Symfony 3.1 series.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

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