setting default value in symfony2 sonata admin bundle

时光毁灭记忆、已成空白 提交于 2019-11-30 03:45:53

I presume you've probably already solved this by now, but as a reference to anyone else you can override the getNewInstance() method and set the default value on the object:

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

    return $instance;
}

you can also assign the default value to the property of the entity directly:

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

In addition to @RobMasters solution:

If you want to set a relation you can get a reference from the entitymanager (instead of the complete object):

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;
}

I added the example to my blog: http://blog.webdevilopers.net/populate-resp-set-default-values-on-form-resp-object-or-instance-in-sonataadminbundle/

For booleans, another option is to set a data value within the first array passed to your add method, inside of configureFormFields

So after some memtoring, my code (for a checkbox that I wanted to have checked by default) ended up looking something like this:

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

... which saved a few lines at the top of my file, since I could then get rid of the getNewInstance() definition.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!