Symfony2:EventSubscriber产生日期错误

时间:2012-12-27 21:52:15

标签: forms events symfony

我已将一个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 %}

1 个答案:

答案 0 :(得分:0)

同样,答案是要注意createNamed()函数的第三个参数。在这种情况下,我不得不修改

$form->add($this->factory->createNamed('sex', 'choice', array(...

阅读

$form->add($this->factory->createNamed('sex', 'choice', null, array(...