Search code examples
phpsymfonysonata-admin

Getting empty_data to work in a Symfony 2 application


I am adding fields to a project based on a project based on Symfony 2 and Sonata. I am trying to follow the instructions from this answer. In one of my admin classes, I have inserted the following code:

   $default = 'Germany';
   if (!$this->getUser()->hasRole(User::CONTENT_SUPPLIER)) {
        $formMapper
            ->tab('Distribution')
                ->with('Distribution')
                    ->add(
                        'module',
                        null,
                        [
                            'empty_data' => $default,
                        ]
                    )
                    ->add(
                        'distributions',
                        'distribution_list',
                        [
                            'label'    => false,
                            'required' => 'false',
                            'disabled' => true
                        ]
                    )
                    ->add('plannedDistributions')
                ->end()
            ->end()
        ;
    }

... and while I expect to see a reference to the "Germany" object by default in my form, I instead see an empty field. Should I be passing in an object rather than a string? Is what I'm trying to do even possible? What am I doing incorrectly here?


Solution

  • I think you missed a crucial bit in the documentation regarding empty_data:

    This option determines what value the field will return when the submitted value is empty (or missing). It does not set an initial value if none is provided when the form is rendered in a view.

    This means it helps you handling form submission with blank fields.

    That means empty_data will populate your model with the data when the form was submitted without a default value.

    I'm not familiar with the $formMapper used in your snippet, but in a typical Symfony-Controller you could create your form like this:

    $form = $this->createForm(MyForm::class, $initialData);
    

    In this case $initialData contains a property Distribution with the value Germany. Alternatively you could try providing the value in your frontend.