为buildForm设置可选参数

时间:2014-09-19 01:35:12

标签: php symfony symfony-forms

我正在使用OptionsResolverInterface将一些额外的参数传递给我的表单。这是表单的代码:

class OrdersType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ($options['curr_action'] !== NULL)
        {
            $builder
                    ->add('status', 'choice', array(
                        'choices' => array("Pendiente", "Leido"),
                        'required' => TRUE,
                        'label' => FALSE,
                        'mapped' => FALSE
                    ))
                    ->add('invoice_no', 'text', array(
                        'required' => TRUE,
                        'label' => FALSE,
                        'trim' => TRUE
                    ))
                    ->add('shipment_no', 'text', array(
                        'required' => TRUE,
                        'label' => FALSE,
                        'trim' => TRUE
            ));
        }

        if ($options['register_type'] == "natural")
        {
            $builder->add('person', new NaturalPersonType(), array('label' => FALSE));
        }
        elseif ($options['register_type'] == "legal")
        {
            $builder->add('person', new LegalPersonType(), array('label' => FALSE));
        }
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired(array(
            'register_type'
        ));

        $resolver->setOptional(array(
            'curr_action'
        ));

        $resolver->setDefaults(array(
            'data_class' => 'Tanane\FrontendBundle\Entity\Orders',
            'render_fieldset' => FALSE,
            'show_legend' => FALSE,
            'intention' => 'orders_form'
        ));
    }

    public function getName()
    {
        return 'orders';
    }

}

这就是我在控制器上构建表单的方式:

$order = new Orders();
$orderForm = $this->createForm(new OrdersType(), $order, array('action' => $this->generateUrl('save_order'), 'register_type' => $type));

但是我收到了这个错误:

  

注意:未定义的索引:curr_action in   /var/www/html/tanane/src/Tanane/FrontendBundle/Form/Type/OrdersType.php   第95行

为什么呢? {i} curr_action形式的$options是否可选,因为此代码设置了?

$resolver->setOptional(array(
   'curr_action'
));

1 个答案:

答案 0 :(得分:1)

完全。访问未知数组密钥时,PHP会激活NOTICE

要正确处理此问题,您有两种解决方案:

** 1)替换:if ($options['curr_action'] !== NULL)

if (array_key_exists('curr_action', $options) && $options['curr_action'] !== NULL)

有点麻烦,但它有效...

2)另一种解决方案是定义默认值:

$resolver->setDefaults(array(
        'data_class' => 'Tanane\FrontendBundle\Entity\Orders',
        'render_fieldset' => FALSE,
        'show_legend' => FALSE,
        'intention' => 'orders_form',
        'curr_action' => NULL // <--- THIS
    ));