在symfony2 sonata admin bundle中设置默认值

Ani*_*pta 19 symfony symfony-sonata

如何在sonata admin bundle中设置默认值,configureFormFields方法中缺少data选项

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('name', null, array('required' => true, 'data' => "my default value"))
    ;
}
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*ers 47

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

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

    return $instance;
}
Run Code Online (Sandbox Code Playgroud)


Jes*_*den 7

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

class TheEntity
{
    private $name = 'default name';
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么这个答案被否决?它起作用并涉及最少覆盖供应商代码.最佳答案imho. (2认同)

web*_*ers 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;
}
Run Code Online (Sandbox Code Playgroud)

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