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

查看:86
本文介绍了在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: Acme\UserBundle\Manager\RegisterManager

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

RegisterManager.php我有

namespace Acme\UserBundle\Manager;

use Acme\UserBundle\Form\Type\RegistrationType;
use Symfony\Component\Form\FormFactoryInterface;

class RegisterManager
{

    protected $formFactory;

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


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

Acme\UserBundle\Form\Type\RegistrationType中,我有:

namespace Acme\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

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' => 'Acme\UserBundle\Entity\User',
        );
    }

    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对象,您应该使用

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天全站免登陆