Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all articles
Browse latest Browse all 3924

Symfony 4: Use existing form type class in Sonata's configureFormFields method

$
0
0

I know I can pull individual form elements from the type's builder into the form mapper as described in the documentation:

You can add Symfony FormBuilderInterface instances to the FormMapper. This allows you to re-use a model form type. When adding a field using a FormBuilderInterface, the type is guessed.

Given you have a PostType like this:

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\AbstractType;

class PostType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('author', EntityType::class, [
                'class' => User::class
            ])
            ->add('title', TextType::class)
            ->add('body', TextareaType::class)
        ;
    }
}

you can reuse it like this:

use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use App\Form\PostType;

class Post extend AbstractAdmin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $builder = $formMapper->getFormBuilder()->getFormFactory()->createBuilder(PostType::class);

        $formMapper
            ->with('Post')
                ->add($builder->get('title'))
                ->add($builder->get('body'))
            ->end()
            ->with('Author')
                ->add($builder->get('author'))
            ->end()
        ;
    }
}

However, this feels clunky if all you want is for Sonata to use that exact type as is.

I was therefore wondering if there is a shorthand that tells sonata to simply use the entire form type as is.

Something like:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper->mapForm((new PostType()));
}

Viewing all articles
Browse latest Browse all 3924

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>