0

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

1 回答 1

0

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

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

读书

$form->add($this->factory->createNamed('sex', 'choice', null, array(...
于 2012-12-29T17:36:12.837 回答