如何在buildForm实体函数中设置存储值(symfony2)

时间:2016-04-30 00:53:32

标签: symfony

我在通过ArrayCollection使用的实体中有这段代码:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('imageFile',VichImageType::class, array(
            'label' => false,
            'required'      => false,
            'allow_delete'  => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ));
        $builder->add('weight','hidden',array(
            'attr' => array(
                //'value' =>'__name__',
                'class' => 'weight'
            )
        ));
    }

当为“新操作”调用buildForm时,我希望“默认值”设置为“ name ”。但是,如果我退出该行

//'value' =>'__name__',

此设置也适用于“编辑操作”。

如何访问此“条目”的“已存储”值以检查我是处于“新操作”还是“编辑操作”?

3 个答案:

答案 0 :(得分:1)

为实体/文档设置默认值的最简单方法是在实体类中:

/**
 * @ORM\Column(type="string")
 */
protected $weight = 'name';

empty_data应该适用于表单构建器:

$builder->add('weight','hidden',array(
        'empty_data' => 'name',
        'attr' => array(
            'class' => 'weight'
        )
    ));

答案 1 :(得分:0)

  

如何访问此“条目”的“已存储”值以检查我是否   在“新动作”或“编辑动作”中?

您应该分开操作以了解确切的上下文。

否则,您可以使用表单模型数据来检查实体的id属性以获取操作的上下文。然后,您可以使用表单事件修改表单。

<强>参考文献:

http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html http://symfony.com/doc/current/components/form/form_events.html

答案 2 :(得分:0)

你可以通过

设置默认值
  ->add('myfield', 'text', array(
  'label' => 'Field',
  'data' => 'Default value'
  ))

 ->add('myfield', 'text', array(
 'label' => 'Field',
 'choices' => array()

)) 传递一个数组(ex为下拉列表) ,一切顺利