GaiaM
GaiaM

Reputation: 11

symfony: Error: Call to a member function getDateTime() on a non-object

How can I solve

Error: Call to a member function getDateTime() on a non-object

Here are is my code:

  $repository = $this->getDoctrine()
        ->getRepository('AppBundle\Entity\Menu');
        $today = date_create_from_format('Y-m-d H:i', date('Y-m-d H:i'));

        $menu = $repository->findAll();

        if($menu->getDateTime() == \DateTime('now')){
            $primiOne = $menu->getPrimiOne();
            $primiTwo = $menu->getPrimiTwo();
            $primiThree = $menu->getPrimiThree();
            $secondOne = $menu->getSecondOne();
            $secondTwo = $menu->getSecondTwo();
            $secondThree = $menu->getSecondThree();
            $sideOne = $menu->getSideOne();
            $sideTwo = $menu->getSideTwo();
            $sideThree = $menu->getSideThree();

and the entity is:

 /**
 * @var \DateTime
 *
 * @ORM\Column(name="date_time", type="string")
 */
private $dateTime;
/**
 * Set dateTime
 *
 * @param string $dateTime
 *
 * @return Menu
 */
public function setDateTime($dateTime)
{
    $this->dateTime = $dateTime;

    return $this;
}

/**
 * Get dateTime
 *
 * @return string
 */
public function getDateTime()
{
    return $this->dateTime;
}

Upvotes: 0

Views: 147

Answers (1)

Tomasz Madeyski
Tomasz Madeyski

Reputation: 10890

You are calling this:

$menu = $repository->findAll();

which will never be instance of your entity because findAll() method returns all objects from given table from db, so this is going to be an array of your entities - this is your mistake - you should query for one object, not all objects.

So, either do:

$menuItems = $repository->findAll();
$menu = $menuItems[0];
if ($menu->getDateTime() (...) )

or

$menu = $repository->findOneBy($criteriaArray);
if ($menu->getDateTime() (...) )

Upvotes: 1

Related Questions