2013-07-05 34 views
3

我正在學習使用Symfony2,並且在我已閱讀的文檔中,與Symfony窗​​體一起使用的所有實體都有空構造函數,或者根本沒有。 (實施例)Symfony2 Forms - 如何在表單構建器中使用參數化構造函數

http://symfony.com/doc/current/book/index.html第12章
http://symfony.com/doc/current/cookbook/doctrine/registration_form.html

我人爲了參數化構造函數來需要在創建時間某些信息。看起來Symfony的方法是將執行留給驗證過程,主要依靠元數據斷言和數據庫約束來確保對象被正確初始化,不需要構造器約束來確保狀態。

考慮:

Class Employee { 
    private $id; 
    private $first; 
    private $last; 

    public function __construct($first, $last) 
    { .... } 
} 

... 
class DefaultController extends Controller 
{ 
    public function newAction(Request $request) 
    { 
     $employee = new Employee(); // Obviously not going to work, KABOOM! 

     $form = $this->createFormBuilder($employee) 
      ->add('last', 'text') 
      ->add('first', 'text') 
      ->add('save', 'submit') 
      ->getForm(); 

     return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
      'form' => $form->createView(), 
     )); 
    } 
} 

如果我無法使用構造函數的參數來做到這一點?

感謝

編輯:回答下面

回答

5

找到了解決辦法:

展望爲控制器的API「的CreateForm()」方法,我發現的東西是不是顯而易見的例子。看來,第二個參數是不一定的對象:

**Parameters** 
    string|FormTypeInterface  $type The built type of the form 
    mixed      $data The initial data for the form 
    array      $options Options for the form 

因此,而不是通過在實體的實例,你可以在一個陣列簡單地通過與相應的字段值:

$data = array(
    'first' => 'John', 
    'last' => 'Doe', 
); 
$form = $this->createFormBuilder($data) 
    ->add('first','text') 
    ->add('last', 'text') 
    ->getForm(); 

另一種選擇(可能更好)是創建一個empty data set作爲表單類中的默認選項。 說明herehere

class EmployeeType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder->add('first'); 
     $builder->add('last'); 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'empty_data' => new Employee('John', 'Doe'), 
     )); 
    } 
    //...... 
} 

class EmployeeFormController extends Controller 
{ 
    public function newAction(Request $request) 
    { 
     $form = $this->createForm(new EmployeeType()); 
    } 
    //......... 
} 

希望這樣可以節省別人的頭劃傷。

+0

只需傳遞靜態字符串很簡單。如何將變量傳遞給Employee的構造函數? –

相關問題