无法转换属性路径的值:预期\ DateTime或\ DateTimeInterface

时间:2016-11-21 08:53:34

标签: php symfony datetime

首先:我对Symfony /编程很陌生,并且在找到我需要的解决方案时遇到了问题。

我在“事件”中有这些变量。具有标准getter和setter的实体。:

 /**
 * @var \DateTime
 *
 * @ORM\Column(name="startTime", type="time", nullable=true)
 *
 * @Assert\Expression(
 *     "this.getStartTime() <= this.getEndTime()",
 *     message="Start time should be less or equal to end date!"
 * )
 */
private $startTime;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="endTime", type="time", nullable=true)
 *
 * @Assert\Expression(
 *     "this.getEndTime() >= this.getStartTime()",
 *     message="End time should be greater or equal to start time!"
 * )
 */
private $endTime;

我的表格有这个控制器:

<?php


namespace AppBundle\Controller;


use AppBundle\Entity\Event;
use AppBundle\Form\EventCreateFormType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class EventController extends Controller {

/**
 * @Route("/eventmanager", name="event")
 */
public function eventsAction(Request $request)
{
    $events = $this->getDoctrine()// query database and get all events
    ->getRepository('AppBundle:Event')
        ->findAll();

    $event = new Event();

    $adminstatus = false;

    if (in_array('ROLE_ADMIN', $this->getUser()->getRoles())) {
        $adminstatus = true;
    }
    $event = $this->get('holiday.service')->createEventForm($request);
    $form = $this->createForm(EventCreateFormType::class, $event, array('rolestatus' => $adminstatus));


    if ($form->isValid()) {

        $em = $this->getDoctrine()->getManager();
        $em->persist($event);
        $em->flush();

        return $this->redirectToRoute('event'); // redirect to route: events
    }

    return $this->render('default/eventmanager.html.twig', array('events' => $events, 'form' => $form->createView()));
}

使用此类型:

<?php


namespace AppBundle\Form;


use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TimeType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class EventCreateFormType extends AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options)
{
    parent::buildForm($builder, $options);

    $builder
        ->add('title', TextType::class, array(
            'label' => 'event.form.title.label',
            'attr' => array(
                'maxlength' => 75,
                '' => '')
        ))
        ->add('dateOf', TextType::class, array(
            'label' => 'event.form.dateOf.label',
//                'widget' => 'single_text',
//                'html5' => false,
            'attr' => [
                'class' => 'js-datepicker',
//                    'format' => 'dd-MM-yyyy',
            ],
        ))
        ->add('startTime', TimeType::class, array(
            'label' => 'event.form.startTime.label',
        ))
        ->add('endTime', TimeType::class, array(
            'label' => 'event.form.endTime.label',
        ))
        ->add('notice', TextareaType::class, array(
            'label' => 'event.form.notice.label',
            'required' => false,
            'attr' => array('maxlength' => 2500)
        ));
    if ($options['rolestatus'] == true) {
        $builder->add('status', ChoiceType::class, array(
            'label' => 'event.form.status.label',
            'data' => $options['rolestatus'],
            'choices' => array(
                'event.form.status.public' => true,
                'event.form.status.private' => false
            ),
            'choices_as_values' => true
        ));
    }
    $builder->add('save', SubmitType::class, array(
        'label' => 'event.form.create.button'
    ));


}

public function configureOptions(OptionsResolver $resolver)
{
    $configs = $resolver->getDefinedOptions();
    $configs[] = 'rolestatus';
    $resolver->setDefined($configs);
}

}

这项服务:

<?php

namespace AppBundle\Controller\Services;

use AppBundle\Entity\Event;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class HolidayServiceController extends Controller {



public function createEventForm(Request $request) {

    $submittedForm = $request->get('event_create_form');
    $adminstatus = false;
    if (in_array('ROLE_ADMIN', $this->getUser()->getRoles())) {
        $adminstatus = true;
    }
    dump($submittedForm);

    $event = new Event();
    if (!empty($submittedForm)) {

            $creator = $this->getUser();
            $title = $submittedForm['title'];
            $startTime = $submittedForm['startTime'];
            $endTime = $submittedForm['endTime'];
            $notice = $submittedForm['notice'];
            $now = new\DateTime();
            $dateOf = new \DateTime();
            $explodedDate = explode('-', $submittedForm['dateOf']);
            $dateOf->setDate($explodedDate[2], $explodedDate[1], $explodedDate[0]);

            $event->setTitle($title);
            $event->setDateOf($dateOf);
            $event->setStartTime($startTime);
            $event->setEndTime($endTime);
            $event->setNotice($notice);
            $event->setCreator($creator);
            $event->setCreatedAt($now);
            if (!empty($submittedForm) && $adminstatus == true) {
                $status = $submittedForm['status'];
                $event->setStatus($status);
            } else {
                $event->setStatus(false);
            }
            return $event;
        }
    return $event;


}
}

现在,当我尝试创建一个新事件时,我收到以下错误:

无法转换属性路径的值&#34; startTime&#34;:预期为\ DateTime或\ DateTimeInterface。 500内部服务器错误 - TransformationFailedException

我知道这种情况正在发生,因为我传递了一个startTime数组而不是一个对象。

为了实现这一目标我需要做些什么?

提前thx。

1 个答案:

答案 0 :(得分:1)

如果您使用Symfony表单,则不必从请求&#34;手动&#34;中检索数据。你唯一应该做的就是处理请求:

$event = new Exvent();
$form = $this->createForm(EventCreateFormType::class, $event);
$form->handleRequest($request);

处理请求只是将请求中的数据绑定到实体属性。它从表单数组中获取值,查看属性应该是什么类型,并将其转换为适当的格式。

如果你想手动完成(那么你不必创建表单 - 它只是没用)你应该这样做:

$startTime = new \DateTime($submittedForm['startTime']);
$endTime = new DateTime($submittedForm['endTime']);

如上所述,如果你说startTime和endTimes是数组,那么在将它们放入DateTime构造函数之前,你必须从这些数组中构建datetime字符串。

然后startTime和endTime将是DateTime的类型。