在 Symfony2 中创建表单即服务
我希望能够从任何控制器上做的是:
$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