0

我定义了一个具有两种可能性的 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',
                    )));
        }
   }
}
4

1 回答 1

0

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

于 2013-01-14T01:48:57.510 回答