Search code examples
doctrine-ormsymfonyfosrestbundlejmsserializerbundle

JMS Serializer not working on custom repository method with FOSRest


I'm having trouble setting up JMS Serializer and FOSRestBundle, to serialize this custom repository method.

If I use $schedules = $em->getRepository('RadioBundle:Schedule')->findAll(); it works fine, but when I try my custom method none of the fields are excluded.

Can someone help me work out what's wrong?

Controller:

use RadioBundle\Entity\Schedule;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations\View;


class ScheduleController extends BaseController
{
    /**
     * @param $date
     * @return \Symfony\Component\HttpFoundation\Response
     * @View(serializerGroups={"schedule"})
     */
    public function getSchedulesScheduleAction($date)
    {
        $em = $this->getDoctrine()->getManager();
        list($startDate, $endDate) = $this->get('radio.utils.date_and_time')->findWeekRange($date);
        $schedules = $em->getRepository('RadioBundle:Schedule')->findByRange($startDate, $endDate);

        $view = $this->view(
            [
                'schedules' => $schedules,
            ],
            200
        );

        return $this->handleView($view);
    }
}

Repository Method:

class ScheduleRepository extends EntityRepository
{
    /**
     * @param \DateTime $startDate
     * @param \DateTime $endDate
     * @return array
     */
    public function findByRange(\DateTime $startDate, \DateTime $endDate)
    {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder();
        $qb->select('s')
            ->from('RadioBundle:Schedule', 's')
            ->leftJoin('s.radioShow', 'rs')
            ->add(
                'where',
                $qb->expr()->between(
                    's.startTime',
                    ':from',
                    ':to'
                )
            )
            ->orderBy('s.startTime', 'asc')
            ->andWhere('rs.isActive = true')
            ->setParameters(['from' => $startDate, 'to' => $endDate]);

        return $qb->getQuery()->getArrayResult();
    }
}

Solution

  • If you return results from your method with getArrayResult() it generates a nested arrays instead of entity objects.

    JMSSerializer needs to know what classes you're serializing to load proper metadata. So you should probably use getResult() instead.