PHP错误调用数组上的成员函数format()

时间:2017-03-04 12:52:51

标签: php symfony

我有一个日期时间字段

    /**
 * @var \DateTime
 *
 * @ORM\Column(name="date", type="datetime", nullable=true)
 */
private $datetime;  

/**
 * Set date
 *
 * @param \DateTime $datetime
 *
 */
public function setDate($datetime)
{
    $this->datetime = $datetime;

    return $this->datetime ?? new \DateTime();
}

/**
 * Get date
 *
 * @return \DateTime
 */
public function getDate(): \DateTime
{
    return $this->datetime ?? new \DateTime();
}

我在下面这个错误:

调用数组

上的成员函数format()

The error on the page

任何人都知道我为什么会这样做?

编辑:

下面是我用来生成表单以读取DateTime值然后从表单中收集数据并在表中创建新实体的代码:

$trainingform = new Training();

    $form = $this->createFormBuilder($trainingform)
        ->add('Leader', TextType::class)
        ->add('Date', DateTimeType::class, ['label' => 'Date and Time'])
        ->add('topics', TextType::class, ['label' => 'Topics Being Covered'])
        ->getForm();

    if ($form->handleRequest($request)->isValid()) {
        $trainingform->setLeader($request->request->get('form')['Leader']); 
        $trainingform->setDate($request->request->get('form')['Date']);
        $trainingform->setTopics($request->request->get('form')['topics']);
        $em->persist($trainingform);
        $em->flush();
    }

1 个答案:

答案 0 :(得分:0)

要正确处理您的数据,您应该使用symfony表单getData - 方法,这会将您的请求转换为您之前在表单中指定的状态。在你的情况下,它应该是这样的:

    $trainingForm = new Training();

    $form = $this->createFormBuilder($trainingForm)
        ->add('Leader', TextType::class) // 'Leader' should be named as your property
        ->add('datetime', DateTimeType::class, ['label' => 'Date and Time']) //changed your Date to datetime as your property is
        ->add('topics', TextType::class, ['label' => 'Topics Being Covered'])  //should be named as your property as well
        ->add('submit', SubmitType::class, ['label' => 'Submit form']) //should be there
        ->getForm();

    $form->handleRequest($request)

    if (form->isSubmitted() && form->isValid()) {
        $trainingForm= $form->getData();
        $em->persist($trainingForm);
        $em->flush();
    }

为了避免这种不一致,您可以在setter方法中指定所需的类型:

/**
 * Set date
 *
 * @param \DateTime $datetime
 */
public function setDate(\DateTime $datetime) //typhint added
{
    $this->datetime = $datetime;
}

`

Setter不应该返回任何东西。然后你会得到你可以控制的步骤的错误,你会知道你应该在哪里挖掘。