Nicolas Zozol
Nicolas Zozol

Reputation: 7038

Bind an object to a Symfony form

I have a entity with some data prefilled, and I want to display them on the form : here state would be ACTIVE and customerId = 1;

// Form file (ben.file.create)
protected function buildForm()
{
    $this->formBuilder->add('name', 'text', ['label'=>'Nom du patient'])
        ->add('customerId', 'integer')
        ->add('state', 'choice', ['choices'=>['ACTIVE'=>'ACTIVE',
            'DONE'=>'DONE', 'CANCELLED'=>'CANCELLED']]);

}


// in the controller
public function index()
{
    $form = $this->createForm("ben-file-create");

    $file = new BenFile();
    $file->setCustomerId(1);
    $file->setState('ACTIVE');

    $form->getForm()->submit($file); // <--- Here the glue problem
    return $this->render('create-file', array());
}

It looks like submit is not the right bind function. I would expect that the form is pre-filled accordingly, and after the POST request, I have an updated BenFile entity.

Upvotes: 0

Views: 335

Answers (1)

Vincent Decaux
Vincent Decaux

Reputation: 10714

You can do easily in createForm method :

// in the controller
public function index(Request $request)
{
    $file = new BenFile();
    $file->setCustomerId(1);
    $file->setState('ACTIVE');

    $form = $this->createForm("ben-file-create", $file);

    // handle submit
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        // flush entity 
        $fileNew = $form->getData();

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($fileNew );
        $entityManager->flush();
    }

    return $this->render('create-file', array());
}

Upvotes: 1

Related Questions