Search code examples
symfonysonata-adminsonata

How to access Sonata admin pool in form type


Use case

I' m trying to reuse sonata_type_model_list in the front admin of my website by defining this in my buildForm method of my Entity FormType :

[...]
->add('position', 'sonata_type_model_list', array(
      'model_manager' => $categoryManager,
))
[...]

However I can't use

$categoryAdmin = $this
    ->getConfigurationPool()
    ->getAdminByClass("\\Application\\Sonata\\ClassificationBundle\\Entity\\Category");

As I need to be in an AdminClass to use getConfigurationPool().

If anyone knows how to use getConfigurationPool() outside of an AdminClass or do you know how to declare sonata_type_model_list in order to use it outside of an admin class ?


Solution

  • Solution


    Thanks to @pbenard & @Mawcel for their answers, I combined them to achieve my goal as follow:


    In my controller I create my form and inject $this->container->get('sonata.admin.pool') to it like so :

    $form = $this->createForm(
        new FormType($this->container->get('sonata.admin.pool')), 
        $entity, 
        $options
    );
    

    In my formType, I added the property $adminPool && the __construct method:

    private $adminPool;
    
    public function __construct(Pool $adminPool) {
        $this->adminPool = $adminPool;
    }
    

    So I can now access the adminPool from the buildForm method:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        [...]
        $categoryAdmin = $this
            ->getConfigurationPool()
            ->getAdminByClass("\\Application\\Sonata\\ClassificationBundle\\Entity\\Category"        );
        [...]
    }