Welcome back! In the previous lesson, we set up the foundation of our MVC ToDo App in Symfony. We created a Todo entity, set up a TodoService to manage our todos, and defined a TodoController to handle requests and render a list of todos using Twig.
Today, we're going to add a critical feature: the ability to add new ToDo items to our list. By the end of this lesson, you will be able to create new tasks and see them displayed in the list.
Now, let's update our Twig template to include a form that allows users to add new ToDo items. Here is the updated list.html.twig template:
In this template, the form's action points to the todo_create route, which we defined in the controller. The form uses the POST method to send data to the server and contains two input fields: one for the title (required) and one for the description (optional). A submit button is included to add a new ToDo item when clicked.
Let's walk through an example of adding a new ToDo item.
-
Fill the Form: Enter a
titleand an optionaldescriptionin the form fields. -
Submit the Form: Click the
Add To Dobutton. -
Form Submission: The form data is sent to the
/todos/createendpoint as a POST request. -
Controller Handling: The
TodoControllerextracts the form data and calls thecreatemethod of theTodoService. -
Service Handling: The
TodoServicecreates a newTodoitem and stores it in the session. -
Redirection: The controller redirects back to the list view, where the new ToDo item is now visible.
In this lesson, we expanded our ToDo app by adding the functionality to create new ToDo items. Here is a summary of what we've covered:
-
Updated the TodoService: We added a
createmethod to handle the creation of new ToDo items and save them in the session. -
Configured the Controller: We modified the
TodoControllerto process form submissions and call the service method to create new ToDo items. -
Modified the Template: We updated the
list.html.twigtemplate to include a form for adding new ToDo items.
Now it's your turn to practice what you've learned. Head over to the practice exercises and try adding new ToDo items to your list. Remember, practice makes perfect!
