Question

I have been using Silex for my latest project and I was trying to follow along with the "How to Dynamically Modify Forms Using Form Events" in the Symfony cookbook. I got to the part that uses the entity field type and realized it is not available in Silex.

It looks like the symfony/doctrine-bridge can be added to my composer.json which contains the "EntityType". Has anyone successfully got entity type to work in Silex or run into this issue and found a workaround?

I was thinking something like this might work:

    $builder
        ->add('myentity', new EntityType($objectManager, $queryBuilder, 'Path\To\Entity'), array(
    ))
    ;

I also found this answer which looks like it might do the trick by extending the form.factory but haven't attempted yet.

Was it helpful?

Solution

I use this Gist to add EntityType field in Silex.

But the trick is register the DoctrineOrmExtension form extension by extending form.extensions like FormServiceProvider doc says.

DoctrineOrmExtension expects an ManagerRegistry interface in its constructor, that can be implemented extending Doctrine\Common\Persistence\AbstractManagerRegistry as the follow:

<?php
namespace MyNamespace\Form\Extensions\Doctrine\Bridge;

use Doctrine\Common\Persistence\AbstractManagerRegistry;
use Silex\Application;

/**
 * References Doctrine connections and entity/document managers.
 *
 * @author Саша Стаменковић <umpirsky@gmail.com>
 */
class ManagerRegistry extends AbstractManagerRegistry
{

    /**
     * @var Application
     */
    protected $container;

    protected function getService($name)
    {
        return $this->container[$name];

    }

    protected function resetService($name)
    {
        unset($this->container[$name]);

    }

    public function getAliasNamespace($alias)
    {
        throw new \BadMethodCallException('Namespace aliases not supported.');

    }

    public function setContainer(Application $container)
    {
        $this->container = $container['orm.ems'];

    }

}

So, to register the form extension i use:

// Doctrine Brigde for form extension
$app['form.extensions'] = $app->share($app->extend('form.extensions', function ($extensions) use ($app) {
    $manager = new MyNamespace\Form\Extensions\Doctrine\Bridge\ManagerRegistry(
        null, array(), array('default'), null, null, '\Doctrine\ORM\Proxy\Proxy'
    );
    $manager->setContainer($app);
    $extensions[] = new Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension($manager);

    return $extensions;
}));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top