Symfony 3.3从数据库表中填充ChoiceType下拉列表

时间:2017-06-13 10:30:02

标签: forms symfony doctrine

我正在尝试从数据库填充表单上的下拉菜单,选择标签很好但我无法在下拉列表中针对这些选项返回正确的值(Ids),如何为'选择编写代码& #39;在下面?

public function newModelAction(Request $request)
    {
        $product = $this->getDoctrine()
        ->getRepository('coreBundle:brand')
        ->findAll();


        if (!$product) {
            throw $this->createNotFoundException(
                'No product found for id '.$productId
                );
        }

        $model = new model();
        $form = $this->createFormBuilder($model)
        ->add('brand_id',ChoiceType::class,array(
            'label'=>'Brand Name',
            'choices'=>array($product),
            'choice_label' => function($product, $key, $index) {
            return strtoupper($product->getName());
            },
            ))
        ->add('name',TextType::class,array('label'=>'Model Name'))
        ->add('comment',TextType::class,array('label'=>'Comments'))
        ->add('save',SubmitType::class, array('label'=>'Add Model'))
        ->getForm();


        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            $em->persist($model);
            $em->flush();
            return $this->render('coreBundle:layouts:newItem.html.twig',
                array('form'=>$form->createView(),));
        }


        // ... do something, like pass the $product object into a template
        return $this->render('coreBundle:layouts:newModel.html.twig',
            array('form'=>$form->createView(),));

    }

表单图片,选项从Db填充,但在提交时不返回ID

enter image description here

我得到以下异常:

  
    
      

执行' INSERT INTO模型(brand_id,name,image_url,comment)VALUES(?,?,?,?)'使用params [null," ABC",null," XYZ"]:       SQLSTATE [23000]:完整性约束违规:1048列' brand_id'不能为空

    
  

忽略Image_url为空,

1 个答案:

答案 0 :(得分:1)

第一个解决方案:按EntityType更改ChoiceType并将模型实体传递给表单,以便symfony可以单独执行映射

第二个解决方案:使用form-> getData()获取brand_id并将其设置为您的模型实体