在Symfony2 Sonata Admin Bundle中设置默认值

20

如何在Sonata Admin Bundle中设置默认值?
在configureFormFields方法中缺少数据选项。

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

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


名称的 fieldType 是什么? - Amit
4个回答

46

我想你可能已经解决了这个问题,但是作为参考,你可以重写getNewInstance()方法并在对象上设置默认值:

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

    return $instance;
}

正是我所需要的。谢谢! - Matheno
@RobMasters 如果我们需要显示的属性实际上是一个方法怎么办? - smarber
尝试使用以下方式设置日期时间时:$instance->setCloseTimeUTC((new \DateTime())->format('Y-m-d H:i:s')); 保存时会出现错误:“预期的类型之一:null,DateTime”。 - Darius.V

7
您还可以直接将默认值分配给实体属性:
class TheEntity
{
    private $name = 'default name';
}

2
为什么这个答案被投票否决了?它能够正常工作,并且涉及最少的供应商代码覆盖。在我看来,这是最佳答案。 - FallenSquirrel
@FallenSquirrel 这个方法可以工作,但我认为这不是期望的解决方案,因为 OP 可能希望在 Sonata 中完成解决方案,而不想触及类属性。 - GusDeCooL

6

除了@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/

标识符或者说“11”会从哪里来? - webDEVILopers
是的,这正是我的问题。 - aderuwe
我不确定你的意思。我的例子只是硬编码,因为我从一个测试用例中复制了它。只需用来自请求堆栈的$branch替换11即可。我认为这很明显。除此之外,我还会编辑我的示例。 - webDEVILopers
你的博客对我非常有帮助,谢谢 <3 - Paul Leclerc

0

对于布尔值,另一个选项是在传递给add方法的第一个数组中设置一个data值,在configureFormFields内部进行设置。

因此,在一些指导后,我的代码(用于默认选中复选框)最终看起来像这样:

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

...这样可以在文件顶部节省几行代码,因为我可以摆脱getNewInstance()的定义。


1
在编辑现有项目值时,来自“数据”的值将覆盖实体中的值。 - ariwez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接