2013-12-16 30 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

相关问题