我已将 EventSubscriber 添加到表单类中,以便可以使用单个模板来添加和编辑实体。在添加订阅者之前,表单不会为添加或编辑抛出错误。添加订阅者后,当满足添加dateAdded字段的条件时,编辑出现如下错误:
给定类型“\DateTime”、“array”的预期参数
否则,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
if (!$data->getId() || $data->getDateAdded()) {
$date = new \DateTime();
$form->add($this->factory->createNamed('dateAdded', 'date', $date, array(
'widget' => 'single_text',
'format' => 'MM/dd/yyyy',
'pattern' => '{{ year }}-{{ month }}-{{ day }}',
'years' => range(Date('Y'), Date('Y') - 5),
'required' => false,
'data' => date_create(),))
);
$form->add($this->factory->createNamed('dob', 'dob_age')
);
$form->add($this->factory->createNamed('sex', 'choice', array(
'choices' => array('Male' => 'Male', 'Female' => 'Female'),
'empty_value' => "Select a gender",
'required' => false))
);
}
}
}
其实体中的 dateAdded 字段:
/**
* @var \DateTime $dateAdded
*
* @ORM\Column(name="date_added", type="date", nullable=true)
*/
private $dateAdded;
模板片段
{% if form.dateAdded is defined %}
{% include 'ManaClientBundle:Client:v2.html.twig' %}
{% endif %}