简体   繁体   English

Symfony 4-无法转换属性路径“ [myDateTime]”的值:预期为\\ DateTimeInterface

[英]Symfony 4 - Unable to transform value for property path “[myDateTime]”: Expected a \DateTimeInterface

I want to render a datetime picker using Symfony forms. 我想使用Symfony表单呈现日期时间选择器。

Since the datetime picker requires just an input text (because it returns a simple string) I've decided to use the form DataTransformers to transform data from datetime to string and viceversa. 由于datetime选择器仅需要输入文本(因为它返回一个简单的字符串),因此我决定使用DataTransformers形式将数据从datetime转换为string,反之亦然。 But when I try to render my page I get the following error message: 但是,当我尝试呈现我的页面时,出现以下错误消息:

Unable to transform value for property path "[myDateTime]": Expected a \\DateTimeInterface. 无法转换属性路径“ [myDateTime]”的值:预期为\\ DateTimeInterface。

My Controller class is the following: 我的Controller类如下:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class HomeController
 * @package App\Controller
 */
class HomeController extends Controller
{    
    /**
     * @Route("/test", name="form_test")
     */
    public function testForm(Request $request)
    {
        $data = ['myDateTime' => new \DateTime()];
        $builder = $this->createFormBuilder($data)
            ->add('myDateTime', DateTimeType::class, ['label' => 'My datetime']);

        $builder
            ->get('myDateTime')
            ->addModelTransformer(new DateTimeToStringTransformer(null, null, 'd/m/Y H:i'));

        $form = $builder->getForm();
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            dump($form->getData());
        }

        return $this->render('test.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}

My view template is so simple: 我的视图模板非常简单:

{% extends 'base.html.twig' %}

{% block body %}
    {{ form_start(form) }}
        {{ form_widget(form) }}
        <button class="btn btn-success">{{ button_label|default('Send') }}</button>
    {{ form_end(form) }}
{% endblock %}

To render my datetime picker I've used form themes stored in form/fields.html.twig: 为了渲染我的日期时间选择器,我使用了存储在form / fields.html.twig中的表单主题:

{% use "bootstrap_4_layout.html.twig" %}

{% block datetime_row %}
    <div class="form-group">
        {{ form_label(form) }}
        {{ form_errors(form) }}
        {{ form_widget(form) }}
        {{ form_help(form) }}
    </div>
{% endblock %}

{% block datetime_widget %}
    <div class="input-group date" id="{{ id }}" data-target-input="nearest">
        <input type="text" class="form-control datetimepicker-input" data-toggle="datetimepicker" data-target="#{{ id }}" {% if value %}value="{{ value|e('html_attr') }}"{% endif %}/>
        <div class="input-group-append" data-target="#{{ id }}" data-toggle="datetimepicker">
            <div class="input-group-text"><i class="fa fa-calendar"></i></div>
        </div>
    </div>
{% endblock datetime_widget %}

And added this theme into twig.yaml config file: 并将此主题添加到twig.yaml配置文件中:

twig:
    paths: ['%kernel.project_dir%/templates']
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    form_themes:
        - 'bootstrap_4_layout.html.twig'
        - 'form/fields.html.twig'

Does anyone help me to understand why that does not work or what am I doing wrong? 有人帮助我了解为什么这不起作用或我在做什么错吗?

In order to have your form working properly you have to use TextType instead of DateTimeType for your myDateTime field: 为了使您的表单正常工作,您必须在myDateTime字段中使用TextType而不是DateTimeType

$builder = $this->createFormBuilder($data)
        ->add('myDateTime', TextType::class, ['label' => 'My datetime']);

Explanation: 说明:

Symfony by default adds a ViewTransformer of type DataTransformerChain for DateTimeType fields. 默认情况下,Symfony为DateTimeType字段添加一个DataTransformerChain类型的ViewTransformer This transformer is called inside normToView function in Form class and expects an argument of \\DateTime class. 此转换器在Form类的normToView函数内部被调用,并且需要\\DateTime类的参数。 However by adding the ModelTransformer of type DateTimeToStringTransformer you have already changed the normalized value of myDateTime field to a string and that's why you get the error. 但是,通过添加类型为DateTimeToStringTransformer的ModelTransformer,您已经将myDateTime字段的规范化值更改为字符串,这就是为什么会出现错误。

Furthermore, your code won't work even if you use 此外,即使您使用,您的代码也不起作用

->addViewTransformer(new DateTimeToStringTransformer(null, null, 'd/m/YH:i'));

instead of 代替

->addModelTransformer(new DateTimeToStringTransformer(null, null, 'd/m/YH:i'));

because in this case the DataTransformerChain transformer is called before the transformer you added and you will get the same error, this time from the DateTimeToStringTransformer . 因为在这种情况下, DataTransformerChain转换程序在添加的转换程序之前被调用,并且这次您将从DateTimeToStringTransformer得到相同的错误。

You don't need the DateTimeToStringTransformer . 您不需要DateTimeToStringTransformer Remove this Transformer. 删除此变压器。 By default the Symfony DateTimeType expects a \\DateTime object. 默认情况下,Symfony DateTimeType需要一个\\DateTime对象。

So what's happening is your transformer is transforming it to a string and then the DateTimeType is expecting a DateTime but it is getting a string so it's causing this error. 因此,正在发生的情况是您的转换器将其转换为字符串,然后DateTimeType期望有DateTime但它正在获取字符串,因此导致此错误。

You can read more here: https://symfony.com/doc/current/reference/forms/types/datetime.html#input 您可以在此处阅读更多信息: https : //symfony.com/doc/current/reference/forms/types/datetime.html#input

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Symfony-无法转换属性路径启动日期的值:预期为\\ DateTimeInterface - Symfony - Unable to transform value for property path launchdate: Expected a \DateTimeInterface 无法转换属性路径的值:预期\\ DateTime或\\ DateTimeInterface - Unable to transform value for property path : Expected a \DateTime or \DateTimeInterface "Symfony 选择类型数组错误:无法转换属性路径的值:需要一个数组" - Symfony choice type array error: Unable to transform value for property path: Expected an array EasyAdmin:“无法转换属性路径XY的值:需要一个字符串。” - EasyAdmin: “Unable to transform value for property path XY: Expected a string.” 无法转换属性路径“fechaReclamacion”的值:datefmt_format:string''不是数字 - Unable to transform value for property path “fechaReclamacion”: datefmt_format: string '' is not numeric Symfony 5:在属性路径“myEntity”中给出的“字符串”、“对象”类型的预期参数 - Symfony 5: Expected argument of type “string”, “object” given at property path “myEntity” empty_data:无法反转属性路径“ countryOfOrigin”的值:预期为字符串或空 - empty_data: Unable to reverse value for property path “countryOfOrigin”: Expected a string or null 如何设置 `DateTimeInterface` 默认值 - How to set the `DateTimeInterface` default value Symfony 不允许实现 DateTimeInterface - Symfony doesn't allowing to implement DateTimeInterface Symfony:属性路径中给出的“?Doctrine\Common\Collections\Collection”类型的预期参数,“array” - Symfony: Expected argument of type "?Doctrine\Common\Collections\Collection", "array" given at property path
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM