0

How to inherit FormType in Sonata Admin?

For example in src/AppBundle/Form/CityType.php:

class SmsType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('recommend', ChoiceType::class, array(
                'choices'  => array(
                    'Maybe' => 0,
                    'Yes' => 1,
                    'No' => 2,
                ),
            ))
            // ...
        ;
    }
}

src/AppBundle/Admin/CityAdmin.php:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('name')
        ->name('recommend')
        // ...
    ;
}

And in my admin field recommend is text input instead of select.

I can:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('name')
        ->name('recommend', ChoiceType::class, array(
            'choices'  => array(
                'Maybe' => 0,
                'Yes' => 1,
                'No' =>   2,
             )
        ))
        // ...
    ;
}

But then in two places I have the same code.

How is best way to refactor this?

Jason Roman
  • 8,146
  • 10
  • 35
  • 40
yeveb
  • 1
  • 1

1 Answers1

0

You can find the answer in the docs https://symfony.com/doc/current/form/inherit_data_option.html. All you have to do, is add your FormType to the FormMapper and set the inherit_data option. The name of the field does not matter.

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('sms', SmsType::class, array(
            'inherit_data' => true,
            'label' => false,
        ))
        // ...
    ;
}
Jason Roman
  • 8,146
  • 10
  • 35
  • 40
jag0
  • 1