2012-10-19 88 views
0

用户sumbits这是构建使用symfony的2框架与抽象类型的一种形式:获取AbstractType从请求

<?php 
$form = $this->createForm(new MyAbstractType(), new MyEntity()); 

我接收在动作此篇请求:

public function receiveFormRequestAction(Request $request){ 
    //How do I get the abstract type from the request? 
} 

我需要能够仅使用请求中的信息创建表单上使用的AbstractType。

  1. 这可能吗?
  2. 你怎么做到的?

谢谢。

编辑:

对不起,如果我不够清楚。在“recieveFormRequestAction”方法中,我不知道我将得到什么抽象类型,所以我不能直接将表单绑定到MyAbstractType。

理论上,此操作可以接收任何AbastractType并将其绑定。

回答

0

我落得这样做:

  1. 的getName()方法在我的形式返回完全相同的名称作为窗体类的名称现在

    Class MyAbstractType extends AbstractType 
        [...] 
        public function getName(){ 
        return "MyAbstractType"; 
    } 
    
  2. 我可以用得到的类型在参数键的哈希

    public function myAction(Request $request){ 
    $parameterKeys = $request->request->keys(); 
    $formName = $parameterKeys[0]; 
    

丑陋地狱,但我需要一个快速解决方案。直到有一个更干净的,我接受这一点。

1
  1. 像这样:

    // first, create the very same form 
    $form = $this->createForm(new MyAbstractType(), new MyEntity()); 
    // bind the form with your request 
    $form->bind($request); 
    // Optional step : validate the form 
    if ($form->isValid()) { 
        // your object is ready, get it like this: 
        $object = $form->getData(); 
    } else { 
        // handle the validation errors. 
    } 
    
0

您需要Request对象绑定到窗体。

$form->bind($request); 

然后你就可以像$form->isValid()$form->getData()运行的东西。