动态字段是额外的?

时间:2012-12-29 22:03:23

标签: php forms symfony

我已经定义了一个有两种可能性的EventSubscriber,其中一种可能会添加一个带有可变数量按钮的单选按钮。除非选中其中一个单选按钮,否则所有表现都符合预期。选中后,我会得到

  

此表单不应包含额外字段。

错误。

如何避免这种情况?

一些代码:

订户

class AddV2FieldsSubscriber implements EventSubscriberInterface {

    private $factory;

    public function __construct(FormFactoryInterface $factory) {
        $this->factory = $factory;
    }

    public static function getSubscribedEvents() {
        return array(FormEvents::PRE_SET_DATA => 'preSetData');
    }

    public function preSetData(DataEvent $event) {
        $data = $event->getData();
        $form = $event->getForm();
        if (null === $data) {
            return;
        }
        // check if the client object is v1: id exists, dateAdded is null
        $n = $data->getMembers()->count();
        if (!$data->getId() || $data->getDateAdded()) {
            $date = new \DateTime();
            $form->add($this->factory->createNamed('dateAdded', 'date', $date, array(
                    'widget' => 'choice',
                    'format' => 'MM/dd/yyyy',
                    'pattern' => '{{ year }}-{{ month }}-{{ day }}',
                    'years' => range(Date('Y'), Date('Y') - 5),
                    'required' => false,
                    'input' => 'datetime',
                ))
                    );
            $form->add($this->factory->createNamed('active', 'hidden', 'Yes')
                    );
            $form->add($this->factory->createNamed('updated', 'hidden', 'No')
                    );
            $form->add($this->factory->createNamed('sex', 'choice', null, array(
                    'choices' => array('Male' => 'Male', 'Female' => 'Female'),
                    'empty_value' => "Select a gender",
                    'required' => false))
                    );
            $form->add($this->factory->createNamed('dob', 'dob_age', null)
                    );
        } 
        elseif ($n && !$data->getDateAdded())
        {
            $members = $data->getMembers();
            // build choices array with member ids
            $choices = array();
            foreach ($members as $member) {
                $choices[$member->getId()] = 'Yes';
            }
            $form->add($this->factory->createNamed('isClient', 'choice', null, array(
                        'choices' => $choices,
                        'empty_value' => false,
                        'required' => false,
                        'mapped' => false,
                        'expanded' => true,
                        'label' => 'isClient',
                    )));
        }
   }
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,答案是使用调试器找出Symfony确定的额外字段。原来,模板中有一些需要删除的硬连线隐藏字段。卫生署!