Symfony3:将值传递给Form EntityType是默认选择的值

时间:2016-07-13 01:39:21

标签: forms symfony

我有一个表单,应该允许将项目(设备)添加到类别(品牌)。下面是创建表单的控制器的一部分($ brand的东西不起作用,但我稍后会想到)。下面是创建表单的代码。

我希望我的选择框(品牌的实体类型,并显示所有可能的品牌)也会根据传递的变量显示默认的选定的值由控制器。

两个问题:

  1. 我可以在哪里传递此值?
  2. 如何为EntityType选择框设置默认选项?我希望它是'数据',但即使对数字进行硬编码也行不通。
  3. 这是控制器位:

    public function createDevice(Request $request, $brand) {
        $device = new Device();
        $form = $this->createForm(DeviceType::class, $device); // where do I pass the value of the default option?
        $form->handleRequest($request);
    

    类型

    class DeviceType extends AbstractType {
    
        public function buildForm(FormBuilderInterface $builder, array $options) {
    
            $builder
                ->add('brand', EntityType::class, array(
                    'class' => 'AppBundle:Brand',
                    'choice_label' => 'name',
                    'choice_value' => 'id',
                    'data' => '2' // does not set default value to second item!
    

1 个答案:

答案 0 :(得分:1)

只需将品牌设置为设备。

$em = $this->getDoctrine()->getManager();
$brand = $em->getRepository('AppBundle:Brand')->find(2);
$device = new Device();
$device->setBrand($brand);
相关问题