2

In this project I'm building, I have many forms to add data to the database that the site uses. 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

2 Answers 2

3

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!

Sign up to request clarification or add additional context in comments.

1 Comment

That has helped a lot. However, it doesn't edit the record. It instead retrieves the record, then adds it as a new record after I submit it. What is causing that?
1

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.

4 Comments

What will this do exactly? I have written code that persists data to the database which works fine. Will this command overwrite this code?
Good question... I don't know. Use version control to avoid surprises.
Why does this command feel like the big red button your not supposed to press. I will get back to you when I try it.
Do not live in fear. Use version control. A DCVS like git will perfectly do the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.