在 Symfony2 中创建表单作为服务 [英] Create a form as a service in Symfony2

查看:23
本文介绍了在 Symfony2 中创建表单作为服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从任何控制器执行的是:

What I'd like to be able to do from any controller is:

$register = $this->get('register_manager');
return $this->render(
    'AcmeUserBundle:Account:register.html.twig',
     array(
         'form' => $register->getRegistrationForm(),
         )
 );

在我的模板中

<form>
    {{ form_widget(form) }}
</form>

这是我目前设置的方式

在我的 Acme/UserBundle/Resources/config/services.yml 我有

parameters:
    register_manager.class: AcmeUserBundleManagerRegisterManager

services:
    register_manager:
        class:     %register_manager.class%
        arguments: [@form.factory]

RegisterManager.php我有

namespace AcmeUserBundleManager;

use AcmeUserBundleFormTypeRegistrationType;
use SymfonyComponentFormFormFactoryInterface;

class RegisterManager
{

    protected $formFactory;

    public function __construct(FormFactoryInterface $formFactory)
    {
        $this->formFactory = $formFactory;
    }


    public function getRegistrationForm()
    {
        return $this->formFactory->createBuilder(new RegistrationType());
    }
}

AcmeUserBundleFormTypeRegistrationType 中,我有:

namespace AcmeUserBundleFormType;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilder;

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('username','text');
        $builder->add('email','email');
        $builder->add('password','password');
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'AcmeUserBundleEntityUser',
        );
    }

    public function getName()
    {
        return 'registration';
    }
}

我知道 RegistrationType() 的工作原理就像我在控制器中一样.我的问题是将 RegisterManager 设置为服务,我无法在其中获取正确的组件,而且我不知道去哪里寻找.

I know the RegistrationType() works as I've had it in a controller. My problem is with setting up RegisterManager as a service, I can't get the right components in there and I'm not sure where to look.

推荐答案

您似乎快到了.要从您的服务中获取 Form 对象,您应该使用 FormFactoryInterface::create() 而不是 FormFactoryInterface::createBuilder()

You're almost there, it seems. To get a Form object from your service, you should use FormFactoryInterface::create() instead of FormFactoryInterface::createBuilder()

$this->createForm() 在控制器中工作的原因是因为每个控制器都扩展了 基础控制器,正好实现了这个方法.

The reason why $this->createForm() works in controllers is because every controller is extending the base controller, which happens to implement this method.

我发现我的 IDE 能够链接到特定的 Symfony 文件非常有用,如果您还没有,我建议您使用一个.还有一个 git 存储库,您可以在此处找到.

I have found my IDE's ability to link to specific Symfony files highly helpful and I suggest you use one, if you already aren't. There's also a git repository, which you can find here.

这篇关于在 Symfony2 中创建表单作为服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆