如何传递变量以在表单上添加if条件

时间:2012-07-07 11:27:23

标签: php symfony twig symfony-forms

我正在使用Symfony2。 我有一个EMPLOYEE实体(其中包含字符串字段'category')和CONTRACT实体。

所以,这是我的问题:

编辑员工后,我可以为他编辑合同。

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

这是我的ContractType:

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));

        }
    }
}

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"

我遇到了这个错误,我不明白我的代码中有什么问题

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:0)

您必须实现buildView并在FormView对象上设置变量。以下是从CollectionType开始如何完成的示例。

答案 1 :(得分:0)

您要做的是根据您的员工实体动态构建合同表单。 IMO,您应该使用解决此用例的表单事件。

http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html