How can I make the entity field type available in silex?

…衆ロ難τιáo~ 提交于 2019-12-07 04:15:27

问题


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.


回答1:


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;
}));


来源:https://stackoverflow.com/questions/23569901/how-can-i-make-the-entity-field-type-available-in-silex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!