2013-12-16 31 views
4

我正在尋找一種方法來訪問symfony2表單構建器類中的數據類實體。在symfony2表單構建器中訪問底層實體

我需要這個的原因是因爲提交按鈕上的文本應根據此實體的值(用戶無法在表單中更改的值)更改。

所以基本上我想做的事:

if ($this->entity->getVariable() == xxx) { 
// do something 
} else { 
// do something else 
} 

表單生成器類中

回答

3

praxmatig我指出了正確的方向,解決的辦法是更容易:

底層的實體是自動提供的名爲「數據」選項,這樣你就可以這樣做:

public function buildForm(FormBuilderInterface $builder, array $options) { 
    // whatever 

    if (isset($options['data'])) { 
     switch ($options['data']->getSomeVariable()) { 
     // whatever 
     } 
    } 

    // whatever 
} 
1

如果您從控制器的形式,你可以通過任何你想要的選項

// AcmeType.php 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $entity = $options['entity']; 
} 

// AcmeController.php 
$form = $this->createForm(new AcmeType(), $entity, array('entity' => $entity)); 

或者更好但更難的方法是使用form event

相關問題