2

我想创建一个 html 选择字段,其中包含上次编辑的日期时间条目。当采用数据库中的任何其他字段时,这有效,而日期时间则无效。

在我的表单类型中

class MemberlistType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('CreatedAt', 'entity', array(
                'mapped' => false,
                'class' => 'TestProject\TestBundle\Entity\Memberlist',
                'property' => 'created_at'
                ))

`

在我看来

{{form_label(form.children.memberlists[0].children.CreatedAt}}
{{form_widget(form.children.memberlists[0].children.CreatedAt}}
{{form_errors(form.children.memberlists[0].children.CreatedAt)}}

我得到:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object 
of class DateTime could not be converted to string in /var/www/symfony/vendor/symfony/symfony
/src/Symfony/Component/Translation/Translator.php line 188") in 
TestprojectTestBundle:Default:updateData.html.twig at line 77

如何以简单的方式将此日期时间转换为字符串?

4

2 回答 2

1

您可以将树枝过滤器称为“日期”:

{{form_label(form.children.memberlists[0].children.CreatedAt|date("m/d/Y")}}
{{form_widget(form.children.memberlists[0].children.CreatedAt|date("m/d/Y")}}
{{form_errors(form.children.memberlists[0].children.CreatedAt|date("m/d/Y"))}}

编辑,我误读了这个问题......就像ZhukV所说,你需要一个ViewTransformer:

namespace My\Bundle\Form\Transformers;

class DateToStringTransformer
{
    public function transform($dateObj)
    {
        if (null === $dateObj) {
            return "";
        }

        return $dateObj->format('m/d/Y');
    }

    public function reverseTransform($date)
    {
        if ($date === "") {
            return null;
        }
        $dateObj = new \DateTime($issue);

        return $dateObj;
    }
}

然后以您的形式调用它:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $transformer = new new DateToStringTransformer();
    $builder
        ->add(
            $builder->create('CreatedAt', 'entity', array(
                'mapped' => false,
                'class' => 'TestProject\TestBundle\Entity\Memberlist',
                'property' => 'created_at'
            ))->addViewTransformer($transformer)
        )

更多信息在这里:http ://symfony.com/fr/doc/current/cookbook/form/data_transformers.html

于 2013-09-08T13:46:11.363 回答
1

您有此错误,因为实体尝试将视图名称作为字符串,但对象 \DateTime 没有 __toString 方法。

最佳解决方案 - 创建自定义视图转换器。

于 2013-09-08T12:38:56.130 回答