Search code examples
symfonysonata-adminsymfony-sonata

Set a field like choose in sonata Admin bundle


Hello I'm working with sonata admin bundle

So I've a form to create, in which I need to select a Facultad entity from a list of these, this is the method to create and edit a Proyecto record.

 protected function configureFormFields(FormMapper $formMapper)
 {
        $em = $this->getConfigurationPool()->getContainer()->get('doctrine.orm.entity_manager');
        $facultades = $em->getRepository('UIFIIntegrantesBundle:Facultad')->findAll();
        $formMapper
            ->add('nombre')
            ->add('facultad','choice',array('choices'=>$facultades))
        ;
 }

Before to it, I added the __toString() in the entity Facultdad

So when I try to add some register I get and error, apparently the Facultad entity retrieve a id value, not the entity.

Catchable Fatal Error: Argument 1 passed to UIFI\IntegrantesBundle\Entity
\Proyecto::setFacultad() must be an instance of UIFI\IntegrantesBundle\Entity
\Facultad, integer given, called in /Development/repositorios/uifi/vendor
/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on 
line 442 and defined 

So how is the best approach to set a choose, from list of entities in sonata admin class?


Solution

  • Instead of choice, you need to use "sonata_type_model" http://sonata-project.org/bundles/admin/master/doc/reference/form_types.html#sonata-type-model

    In this case your code will become:

    protected function configureFormFields(FormMapper $formMapper)
    {     
        $formMapper
            ->add('nombre')
            ->add('facultad','sonata_type_model')
        ;
    }