Twig CRUD - Update (Edit)


We now have 50 fake BlogPost entities in the database, a way to view them (via listAction), and a way to create more new BlogPost entities (via the createAction).

In order to be able to create new BlogPost entities we had to create a simple Symfony form which allowed us to post in new data.

To edit data, the good news is that we can re-use the existing form. All we need to do this time is pass in an existing BlogPost entity whilst creating the form, and Symfony's form component will re-populate the form with our existing data.

We can simplify things even further by allowing Symfony to inspect the URL, grab the passed in id, query for a BlogPost with that ID, and then make the resulting BlogPost entity available for us through dependency injection.

It all sounds quite complicated when written like this, so let's quickly see that in action:

// /src/AppBundle/Controller/BlogPostsController.php

    /**
     * @param Request  $request
     * @param BlogPost $blogPost
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     *
     * @Route("/edit/{blogPost}", name="edit")
     */
    public function editAction(Request $request, BlogPost $blogPost)
    {
        $form = $this->createForm(BlogPostType::class, $blogPost);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // * etc *
        }

        return $this->render('BlogPosts/edit.html.twig', [
            'form' => $form->createView()
        ]);
    }

In the Route we can see the {blogPost} parameter.

To call this route, we could make a request in our browser to GET http://our-symfony-3-site.dev/app_dev.php/edit/16.

In this example, Symfony would see that we passed in 16 as our {blogPost} parameter.

Before the editAction would be called, an event listener would hear of this request, and then query Doctrine for the BlogPost entity that matches id: 16.

Then, it would pass the resulting entity on to our editAction, injecting it for us directly in to the method. Pretty awesome. We don't need to do anything to make this work, other than follow this convention.

Also, because Doctrine is already managing this entity, we do not need to call persist when later wanting to save changes to the entity. We only need to call flush.

If any of this is new to you, or you don't feel entirely comfortable with it, then be sure to watch this series where creating, saving, updating, and deleting inside Doctrine are all covered in more depth.

Code For This Video

Get the code for this video.

Episodes