开发者

Display data from database to forms in Symfony2

开发者 https://www.devze.com 2023-04-12 23:18 出处:网络
In this project I\'m building, I have many forms to add data to the database that the site u开发者_如何学运维ses. Obviously, if a user add\'s data they must be able to edit this data (or delete it).

In this project I'm building, I have many forms to add data to the database that the site u开发者_如何学运维ses. Obviously, if a user add's data they must be able to edit this data (or delete it).

I've looked through the book and it talks at length about using a form to add data. However, it doesn't seem to mention how forms can be used to edit data.

How can this be achieved?

Cheers


If you want, it's quite easy to write your edit action without doctrine, you should do something like this:

public function editAction( $id ) {
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('YourBundle:YourEntity');
$element = $repository->find( $id );
if ( false !== is_null( $element ) ) {
    throw $this->createNotFoundException( 'Couldn\'t find element ' . $id . '!');
}
$form = $this->createForm( new YourFormType(), $element );
$request = $this->getRequest();
if ( $request->getMethod() == 'POST' ) {
    $form->bindRequest( $request );
    if ( $form->isValid() ) {
        $em->persist( $element );
        $em->flush();
        $this->get( 'session' )->setFlash( 'system-message', 'Element Updated!' );
        return $this->redirect( $this->generateUrl( 'Your_route' ) );
    }
}
return $this->render('YourBundle:YourView:your_template.html.twig', array( 'element' => $element, 'form' => $form->createView() ) );}

The only different thing of the edit action with the new action is that, instead of creating a new "element" instance, you get it from the entity manager, you could even set any arbitrary values to your element before attaching it to the form.

I hope it helps!


Use the generate:doctrine:crud task to generate code for editing/updating users. You'll see that the newAction and the editAction are very similar.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号