将对象绑定到Symfony表单

时间:2019-03-05 14:55:48

标签: symfony

我有一个预填充了一些数据的实体,我想在表格上显示它们:这里的状态为ACTIVEcustomerId = 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());
}

看来submit不是正确的绑定函数。我希望相应地预先填写表单,并且在POST请求之后,我有一个更新的BenFile实体。

1 个答案:

答案 0 :(得分:1)

您可以在createForm方法中轻松完成操作:

// 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());
}