0
votes

I have an entity called Event, with a field startDate (type="date"), and another called slug (type="string"). I have created a controller action to get a specific event based on these parts. The router passes eventDate as the format 'Y-m-d', and the eventSlug. Now I have successfully created a DateTime object with $startDate = DateTime::createFromFormat('Y-m-d', $eventDate). Now if I issue

$event = $eventRepo->findOneBy(array(
    'startDate' => $startDate,
    'slug'      => $eventSlug,
));

it gets nothing ($event is NULL). Do I miss something in Doctrine documentation, or did I find a bug?

1
If I leave the startDate part and use only the slug, it works like charm, so the problem is in the startDate thing for sure. - GergelyPolonkai

1 Answers

2
votes

First ensure that actually an Event with the given slug and start date exists. Is slug unique field?

Anyway you can let Doctrine do the param conversion for you, without using PHP format function:

$repo = $this->getDoctrine()->getRepository('AcmeHelloBundle:Event');
$qb   = $repo->createQueryBuilder('e');

$event = $qb
    ->andwhere($qb->expr()->eq('e.slug', ':slug'))
    ->andWhere($qb->expr()->eq('e.start_date', ':start_date'))
    ->setParameter('slug', $eventSlug)
    ->setParameter('start_date', $startDate)
    ->getQuery()
        ->getOneOrNullResult();

Or, use the Doctrine param converter:

/**
 * @Route("/event/show/{slug}/{start_date}")
 * @Method("GET")
 * @ParamConverter("event", class="AcmeHelloBundle:Event")
 * @Template
 */
public function showAction(Event Event)
{
}

Internally, Doctrine param converter do it for you: It checks for any parameter in the request and find an entity using slug and start_date.