在Symfony 2.3中通过服务创建表单时出错

时间:2014-05-26 02:48:43

标签: symfony symfony-2.3

我想通过表格工厂通过Symfony 2.3中的服务创建表单,但我无法重现它。

我的services.yml看起来像这样:

user.form.myservice:
    factory_method: createNamed
    factory_service: form.factory
    class: Symfony\Component\Form\Form
    arguments: [my_form_type_name]
user.form.myservice.type:
    class: XxX\MyBundle\Form\Type\myEntityType
    arguments: [null]
    tags:
      - { name: form.type, alias: my_form_type_name }

这是我的表单类型定义(myEntityType)

class MyEntityType extends AbstractType
{
    private $class;

    public function __construct($class = null)
    {
        $this->class = (isset($class)) ? $class : 'XxX\MyBundle\Entity\myEntity';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('first_name', 'text')
            ->add('last_name', 'text');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => $this->class
        ));
    }

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

在我的控制器中,当我尝试创建表单时:

$formFactory = $this->container->get('user.form.myservice');
$myForm = $formFactory->createForm();

它说:

FatalErrorException: Error: Call to undefined method Symfony\Component\Form\Form::createForm() in ...\proj1\src\XxX\MyBundle\Controller\ProfileController.php line 134

请帮忙吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

首先,你没有将任何参数传递给MyEntityType的构造函数。您还以错误的方式使用了createForm方法。它需要以下参数:$type$data = null,array $ options = array()`。

要使此功能正常,您应指定type

$form = $this->createForm($this->get('user.form.myservice'), new YourEntity());

答案 1 :(得分:0)

您的工厂服务user.form.myservice已返回FormInterface个实例(Symfony\Component\Form\FormFactory::createNamed),您可以从createForm个实例调用方法Form

你的创作形式的逻辑错误。 工厂方法必须返回完成的对象以供下次工作,但您需要预期的工厂。

工厂为您的例子:

public function createForm()
{
  $form = $this->formFactory->createForm('....');
  return $form;
}

答案 2 :(得分:0)

好吧,我终于解决了通过以下方式创建表单的问题:

$myForm = $this->container->get('form.factory')->create(new myEntityType(), new myEntity());

感谢您的帮助!