在ChoiceType Symfony2中的IF语句

时间:2016-01-27 09:28:31

标签: php forms symfony

如何在ChoiceType中放置IF语句以添加其他选项?

这是代码:

        $form = $this->createFormBuilder()
        ->add('Name', ChoiceType::class, array(
            'choices' => array(
                'Server' => 'Server',
                'APC' => 'APC',
                'Switch' => 'Switch',
                'APC Small' => 'APC Small'
            ),

首先需要检查选择APC以查看它是否存在。如果它不存在,则必须包括在内,否则排除。

检查准备好了true和false但是如何在表单add array中放置if语句。或者还有其他方法可以做到吗?

if语句是这样的:

if($APCDisable == false){}

2 个答案:

答案 0 :(得分:2)

我不确定我是否理解您的问题,但您可以在将数组内容添加到表单之前简单地确定/计算数组内容,例如像

// initially w/out APC
$choices = [
    'Server' => 'Server',
    'Switch' => 'Switch',
    'APC Small' => 'APC Small'
];
if($APCDisable == false) {
    // add APC choice, since it's available
    $choices['APC'] = 'APC';
}
$form->add('Name', ChoiceType::class, [
    'choices' => $choices,
]);

如果您可以根据表单数据计算$APCDisable ,那么您可以使用http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html中所述的表单事件。

答案 1 :(得分:0)

您可以创建一个返回选择数组的方法。

 $form = $this->createFormBuilder()
        ->add('Name', ChoiceType::class, array(
            'choices' => methodToRetrieveTheChoices(),
            ),

在这种方法中,你可以提出你提出的逻辑。