Symfony2 - use Sonata field type outside the bundle

1.8k views Asked by At

I would like to have good looking EntityType for multiple selection as Sonata does with sonata_type_model (ModelType).

The question would be, how can I use sonata_type_model outside SonataAdminBundle on my custom form?

I tried:

->add('countries', 'sonata_type_model', array(
    'label' => 'Countries',
    'property' => 'name',
    'multiple' => true
))

Also I tried:

use Sonata\AdminBundle\Form\Type\ModelType;

...

->add('countries', ModelType::class, array(
    'label' => 'Countries',
    'property' => 'name',
    'multiple' => true
))

But unfortunately I am getting an error:

Catchable Fatal Error: Argument 1 passed to Sonata\AdminBundle\Form\ChoiceList\ModelChoiceLoader::__construct() must implement interface Sonata\AdminBundle\Model\ModelManagerInterface, null given, called in C:\xampp\htdocs\trainingexperience_symfony\app\cache\dev\classes.php on line 18005 and defined

UPDATE

I followed an advice to define model_manager property inside form type options:

protected $modelManager;

function __construct(ModelManager $modelManager)
{
    $this->modelManager = $modelManager;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('preferredCountries', ModelType::class, array(
            'label' => 'Countries',
            'property' => 'name',
            'multiple' => true,
            'model_manager' => $this->modelManager
        ));

    ...
}

I pass it from controller like:

/** @var ModelManager $modelManager */
$modelManager = $this->get('sonata.media.admin.media.manager');
$formType = new FormType($modelManager);

...

But now I get an error:

Class does not exist

500 Internal Server Error - ReflectionException

Stack Trace

in vendor\doctrine\common\lib\Doctrine\Common\Persistence\AbstractManagerRegistry.php at line 197   -

   $class = $this->getAliasNamespace($namespaceAlias) . '\\' . $simpleClassName; 
        } 
        $proxyClass = new \ReflectionClass($class); 
        if ($proxyClass->implementsInterface($this->proxyInterfaceName)) { 
            if (! $parentClass = $proxyClass->getParentClass()) { 

at ReflectionClass ->__construct ('') 
in vendor\doctrine\common\lib\Doctrine\Common\Persistence\AbstractManagerRegistry.php at line 197   + 
at AbstractManagerRegistry ->getManagerForClass (null) 
in vendor\sonata-project\doctrine-orm-admin-bundle\Model\ModelManager.php at line 272   + 
at ModelManager ->getEntityManager (null) 
in vendor\sonata-project\doctrine-orm-admin-bundle\Model\ModelManager.php at line 64   + 
at ModelManager ->getMetadata (null) 
in vendor\sonata-project\doctrine-orm-admin-bundle\Model\ModelManager.php at line 377   + 
at ModelManager ->getIdentifierFieldNames (null) 
in vendor\sonata-project\admin-bundle\Form\ChoiceList\ModelChoiceLoader.php at line 75   + 
at ModelChoiceLoader ->__construct (object(ModelManager), null, 'name', null, array(), object(PropertyAccessor)) 
in vendor\sonata-project\admin-bundle\Form\Type\ModelType.php at line 113   + 
at ModelType ->Sonata\AdminBundle\Form\Type\{closure} (object(OptionsResolver), null) 
in vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php at line 859   + 
at OptionsResolver ->offsetGet ('choice_loader') 
in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\Type\ChoiceType.php at line 320   + 
at ChoiceType ->Symfony\Component\Form\Extension\Core\Type\{closure} (object(OptionsResolver), null) 
in vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php at line 965   + 
at OptionsResolver ->offsetGet ('choice_list') 
in vendor\symfony\symfony\src\Symfony\Component\OptionsResolver\OptionsResolver.php at line 791   + 
at OptionsResolver ->resolve (array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager))) 
in vendor\symfony\symfony\src\Symfony\Component\Form\ResolvedFormType.php at line 156   + 
at ResolvedFormType ->createBuilder (object(FormFactory), 'preferredCountries', array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager))) 
in vendor\symfony\symfony\src\Symfony\Component\Form\Extension\DataCollector\Proxy\ResolvedTypeDataCollectorProxy.php at line 89  + 
at ResolvedTypeDataCollectorProxy ->createBuilder (object(FormFactory), 'preferredCountries', array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager))) 
in vendor\symfony\symfony\src\Symfony\Component\Form\FormFactory.php at line 114   + 
at FormFactory ->createNamedBuilder ('preferredCountries', 'Sonata\AdminBundle\Form\Type\ModelType', null, array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager))) 
in vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php at line 106   + 
at FormBuilder ->create ('preferredCountries', 'Sonata\AdminBundle\Form\Type\ModelType', array('label' => 'Countries', 'property' => 'name', 'multiple' => true, 'model_manager' => object(ModelManager))) 
in vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php at line 269   + 
at FormBuilder ->resolveChildren () 
in vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php at line 215   + 
at FormBuilder ->getForm () 
in vendor\symfony\symfony\src\Symfony\Component\Form\FormFactory.php at line 40   + 
at FormFactory ->create (object(InternshipType), object(Internship), array()) 
in vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller\Controller.php at line 282   + 
at Controller ->createForm (object(InternshipType), object(Internship)) 
in src\IndexBundle\Controller\TraineeController.php at line 194   + 
at TraineeController ->internshipsAction (object(Request)) 
at call_user_func_array (array(object(TraineeController), 'internshipsAction'), array(object(Request))) 
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 144   + 
at HttpKernel ->handleRaw (object(Request), '1') 
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php at line 64   + 
at HttpKernel ->handle (object(Request), '1', true) 
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel.php at line 69   + 
at ContainerAwareHttpKernel ->handle (object(Request), '1', true) 
in vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php at line 185   + 
at Kernel ->handle (object(Request)) 
in web\app_dev.php at line 30   + 
3

There are 3 answers

4
greg0ire On

You should try providing the model_manager option to the type. It might be a service, so have a look at debug:container and try to spot it.

1
Mawcel On

You are getting this error because sonata_type_model needs the modelmanager of the targeted admin to manipulate the entities.

Bottom line: you can not use sonata_type_model on entities that do not have an admin service defined

Here is a workaround i used :

Form type:

<?php

namespace Blast\BaseEntitiesBundle\Form\Type;

use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\Options;
use Blast\CoreBundle\Form\AbstractType;

class NestedTreeableType extends AbstractType
{   
    public function configureOptions(OptionsResolver $resolver)
    {
        $queryBuilder = function (Options $options) 
        {
            return $options['em']
                ->getRepository($options['class'])
                ->getNodesHierarchyQueryBuilder();
        };

    $choiceLabel = function($choice)
    {
         return str_repeat(' - ', $choice->getTreeLvl()) . (string) $choice;
    };

    $resolver->setDefaults([
        'query_builder' => $queryBuilder,
        'choice_label'  => $choiceLabel,
        'btn_add' => 'link_add',
        'btn_list' => 'link_list',
        'btn_delete' => 'link_delete',
        'btn_catalogue' => 'SonataAdminBundle',
    ]);
}

public function buildView(FormView $view, FormInterface $form, array $options)
{
    parent::buildView($view, $form, $options);

    $object_id = ($view->vars['name'] == 'treeParent') ? $form->getParent()->getData()->getId() : null;

    $choices = [];

    foreach ($view->vars['choices'] as $choice) {
            if ( $object_id && $choice->data->getId() == $object_id )
                $choice->attr['disabled'] = 'disabled';

        $choices[] = $choice;
    }

    $view->vars['choices'] = $choices;
    $view->vars['btn_add'] = $options['btn_add'];
    $view->vars['btn_list'] = $options['btn_list'];
    $view->vars['btn_delete'] = $options['btn_delete'];
    $view->vars['btn_catalogue'] = $options['btn_catalogue'];
}

public function getParent()
{
    return 'entity';
}

public function getBlockPrefix()
{
    return 'blast_nested_treeable';
}

}

as you can see i am defining the options and view variables that sonata_type_model needs and now the template for the form type

{% extends 'SonataDoctrineORMAdminBundle:Form:form_admin_fields.html.twig' %}

{% block blast_nested_treeable_widget %}
    {{ block('sonata_type_model_widget') }}
{% endblock %}

Just render a sonata_type_model block and your good to go. if you want to take a look at the real example : https://github.com/blast-project/BaseEntitiesBundle

Hope that helps

0
Mix Kira On

I don't know if someone is still searching that, but, I've found that you need this to have the modelManager (at least in 2.7 version of symfony):

/** @var ModelManager $modelManager */
$modelManager = $this->get('sonata.admin.manager.orm');
$formType = new FormType($modelManager);

...

byez