在symfony2 sonata admin bundle中设置默认值

时间:2012-05-11 06:00:14

标签: symfony symfony-sonata

如何在sonata admin bundle中设置默认值 configureFormFields方法

中缺少data选项
protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('name', null, array('required' => true, 'data' => "my default value"))
    ;
}

如何使用data属性在字段???中设置默认值

4 个答案:

答案 0 :(得分:47)

我认为你现在可能已经解决了这个问题,但是作为对其他任何人的引用,你可以覆盖getNewInstance()方法并在对象上设置默认值:

public function getNewInstance()
{
    $instance = parent::getNewInstance();
    $instance->setName('my default value');

    return $instance;
}

答案 1 :(得分:7)

您也可以直接将默认值分配给实体的属性:

class TheEntity
{
    private $name = 'default name';
}

答案 2 :(得分:5)

除了@RobMasters解决方案:

如果要设置关系,可以从entitymanager(而不是完整对象)获取引用:

public function getNewInstance()
{
    $instance = parent::getNewInstance();

    if ($this->hasRequest()) {
        $branch = $this->getRequest()->get('branch', null);

        if ($branch !== null) {
            $entityManager = $this->getModelManager()->getEntityManager('MyBundle\Entity\Branch');
            $branchReference = $entityManager->getReference('MyBundle\Entity\Branch', $branch);

            $instance->setBranch($branchReference);
        }
    }
    return $instance;
}

我在我的博客中添加了示例: http://blog.webdevilopers.net/populate-resp-set-default-values-on-form-resp-object-or-instance-in-sonataadminbundle/

答案 3 :(得分:0)

对于布尔值,另一种选择是在传递给data方法的第一个数组中设置add值,configureFormFields

所以经过一些记忆之后,我的代码(对于我希望默认选中的复选框)最终看起来像这样:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('name')
        ->add('visible', null, ['label'=>'Visibility', 'data' => true ])
    ;
}

...在我的文件顶部保存了几行,因为我可以摆脱getNewInstance()定义。