dpbfb7119 2017-12-23 11:31
浏览 36

在布尔值上调用成员函数format()?

I have a symfony 3 project. I am trying to post several pieces of information including two dates. The method looks like this:

    /**
 * @Route("/LegoPieces")
 * @METHOD("POST")
 * @View()
 *
 * @Annotations\QueryParam(
 * name="piece", nullable=false, description="piece"
 * )
 * @Annotations\QueryParam(
 * name="type", nullable=false, description="type"
 * )
 * @Annotations\QueryParam(
 * name="startDate", nullable=false, description="Start Date YYYY-MM-DD HH:MM:SS (Should be in the future)"
 * )
 * @Annotations\QueryParam(
 * name="endDate", nullable=false, description="End Date YYYY-MM-DD HH:MM:SS (Should be no more than 3 weeks in the future)"
 * )
 */
public function postAction(ParamFetcherInterface $paramFetcher)
{
    $piece = $paramFetcher->get('piece');
    $type = $paramFetcher->get('type');
    $start = $paramFetcher->get('startDate');
    $end   = $paramFetcher->get('endDate');
    $startDate = DateTime::createFromFormat(' Y-m-d H:i:s', $start);
    var_dump($startDate);
    $endDate = DateTime::createFromFormat(' Y-m-d H:i:s', $end);


    $em = $this->getDoctrine()->getManager('default');

    $data = new LegoPieces();
    $data->setPiece($piece);
    $data->setType($type);
    $data->setStartDate($startDate);
    $data->setEndDate($endDate);
    $em->persist($data);
    $em->flush();

    return new JsonResponse("LegoPieces Added Successfully", 200);
}

The setters look like this:

        /**
  * Set startDate
  *
  * @param \DateTime $startDate
  *
  * @return LegoPiece
  */
  public function setStartDate($startDate)
  {
   $this->startDate = $startDate;

   return $this;
  }

However every time I try to post the data I get the following error message:

 "message": "Call to a member function format() on boolean",
            "class": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",

I've tried everything and nothing works! Grateful for your help!

  • 写回答

2条回答 默认 最新

  • duanboshi1472 2017-12-23 13:53
    关注

    You should check the dates you pass into. The problem is most likely from your usage of

    DateTime::createFromFormat()
    

    As the documentation says:

    Returns a new DateTime instance or FALSE on failure.

    So, most likely the call fails, returns false and later on (probably in your template) you (or Twig when rendering the date) call format() on $startDate or $endDate but one of them is actually not a valid DateTime-object.

    My assumption is that the format ' Y-m-d H:i:s' is not correct, due to the initial whitespace?

    评论

报告相同问题?