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