表单字段值而不是其索引



这是我的FormBuilder:

         // EditUserFormType.php
         $builder
                ->add('eduStartYear', 'choice', array(
                    'label' => false,
                    'choices' => range(date('Y'),1956)
                ))
                ->add('eduEndYear', 'choice', array(
                    'label' => false,
                    'choices' => range(date('Y'),1957),
                ))
                ->add('save', 'submit');

这是来自Entity:

    /**
     * @ORMColumn(type="date", nullable=true)
     */
    protected $eduStartYear;
    /**
     * @ORMColumn(type="date", nullable=true)
     */
    protected $eduEndYear;

是控制器的一部分:

    $user = $this->getUser();
    $form = $this->createForm(new EditUserFormType(), $user);
    $form->handleRequest($request);
    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();
    }

我得到这个错误在保存:

datettype .php第53行:

错误:调用非对象的成员函数format()

在我用调试器检查了所有过程后,我注意到值传递给

public function convertToDatabaseValue($value, AbstractPlatform $platform)

实际上是整数,这个整数是形式值的索引(例如0 = 2015,1 = 2014等)

我如何从表单字段获取值,而不是它的索引?

为什么不按照文档中的数组key == value创建一个选择列表呢?

$builder->add('eduStartYear', 'choice', array(
    'choices' => array(
        '1990'   => '1990',
        '1991'   => '1991',
        '1992'   => '1992', // of course you have to generate this array - just an example
    ),
));

Doctrine仍然会期望日期字段有一个DateTime对象,尽管这会导致->format错误。您可以查看数据转换器,将YYYY值转换为DateTime对象,然后再转换回来。

我没有语法检查,但它应该工作或接近工作。

class YearToDateTransformer implements DataTransformerInterface
{
    private $manager;
    public function __construct(ObjectManager $manager)
    {
        $this->manager = $manager;
    }
    /**
     * Transforms an object (DateTime) to a string (year).
     *
     * @param  DateTime|null $date
     * @return string
     */
    public function transform($date)
    {
        if (null === $date) {
            return '';
        }
        return $date->format('Y');
    }
    /**
     * Transforms a year to a DateTime
     *
     * @param  string $year
     * @return DateTime|null
     * @throws TransformationFailedException if object (DateTime) is not found.
     */
    public function reverseTransform($year)
    {
        if (!$year) {
            return;
        }
        $date = DateTime::createFromFormat('Y', $year);
        if (!$date instanceof DateTime) {
            throw new TransformationFailedException(sprintf(
                'Coul not convert year %s to DateTime',
                $year
            ));
        }
        return $date;
    }
}

然后你可以把它附加到你的表单字段,像这样:

  $builder->get('eduStartYear')
            ->addModelTransformer(new YearToDateTransformer());