2012-10-19 87 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()運行的東西。