Search code examples
phpsymfonysymfony-sonatadbal

Symfony2 - Inject a service into SonataAdmin


I'd like to get a db connection from within a SonataAdmin class' configureFormFields()

For sure this doesn't work

protected function configureFormFields(FormMapper $formMapper)
{
    $mycnx = $this->get('doctrine.dbal.mycnx_connection');
//...

I need it for my extension of Sonata/UserBundle/Admin/Entity/UserAdmin

How can I call a service from this class ?


The context:

I need to have a choice field (company) whose choices come from an other connection (from a stored procedure).


Solution

  • What you have to do is:

    • create a service getting the connection injected to get companies from
    • create a custom field
    • register it as a service and inject the first service in constructor
    • supply the choices to the field

      public function setDefaultOptions(OptionsResolverInterface $resolver)
      {
          $resolver->setDefaults(array(
      #...
      

    Then you'll be able to simply use it from configureFormFields() with:

    ->add('company', 'company')