2012-07-07 45 views
2

我正在使用Symfony2。 我有一个EMPLOYEE实体(其中有一个字符串字段'category')和一个CONTRACT实体。如何通过变量在表单上添加if条件

所以,这里是我的问题:

编辑雇员后,我可以编辑他的合同。

如果员工属于=='worker'类别,并且如果category ='CEO',我想在合同表单中添加字段“salary”,但我不想显示该字段。

这里是我的合约类型:

class ContractType extends AbstractType 
{ 
    protected $employee; 

    function __construct(MyBundle\Entity\Employee $employee = null) { 
    $this->employee = $employee; 
    } 


    public function buildForm(FormBuilder $builder, array $options) { 
    $builder 
     ->add('startDate'); 

     if ($this->employee !== null && $this->employee->getCategory() == 'worker') 
     { 
      $builder 
      ->add('salary', 'money', array('currency' => 'USD', 'required' =>false));        
     } 

     elseif ($this->employee !== null && $this->employee->getCategory() == 'CEO') 
     { 
      $builder->add('salary', 'hidden', array('required' => false)); 

     } 
    } 
} 

这里是我的contract_form.html.twig:

{% if employee.category == 'worker'%} 
    <tr> 
    <td>{{ form_label(form.salary, "Salary : ") }}</td> 
    <td>{{ form_widget(form.salary) }}</td> 
    </tr> 
{% endif %} 


After editing a employee and setting him category=='worker', when I want to edit him a contract, I have the error :

 Method "salary" for object "Symfony\Component\Form\FormView" does not exist in MyBundle:Contract:contract_form.html.twig" 

我坚持这个错误,我不明白什么是错的在我的代码

非常感谢您的帮助!

回答

0

您必须执行buildView并在FormView对象上设置变量。这是一个关于CollectionType如何完成的例子。