symfonyknppaginator

how to use knpPaginatorBundle with rest api?


I try to use

public function listeleAction(Request $request) { $em=$this->getDoctrine()->getManager();

    $yasam_list=$em->getRepository("VanBundle:Yasam")->findAll();

    if (count($yasam_list)>0)
    {
    $yanit=array();
    foreach ($yasam_list as $meta)
    {
        $new_yasam=array();
        $new_yasam['id']=$meta->getId();
        $new_yasam['adi']=$meta->getAdi();
        $new_yasam['adres']=$meta->getAdres();
        $new_yasam['kategori_id']=$meta->getKategori()->getAdi();
        array_push($yanit,$new_yasam);
    }
        $paginator=$this->get('knp_paginator');

        $result= $paginator->paginate(
            $yanit,
            $request->query->getInt('page',1),
            $request->query->getInt('limit',10)
        );

    }else{
        $yanit["success"] = 0;
  $response["message"] = "Bu kategoriye en kısa sürede veri eklenecektir. ";
    }

    $response=new Response(json_encode(array('yasamlar' =>$result),JSON_UNESCAPED_UNICODE));
    $response->headers->set('Content-type','application/json; charset=utf-8');
    $response->setStatusCode(200);
    return $response;
}

my json output

{
"yasamlar": {}
}

How can I solve this? thanks all


Solution

  • I solved

    public function indexAction(Request $request)
        {
    
            $em=$this->getDoctrine()->getManager();
            //listelenecek bütün Yasam
            $yasam_list=$em->getRepository("VanBundle:Yasam")->findAll();
    
    
    
            $pager=$this->get('knp_paginator');
            $paginated=$pager->paginate($yasam_list,$request->query->getInt('page',1), $request->query->getInt('limit',10));
    
            $factory=new KnpPaginatorFactory();
            $collection=$factory->createRepresentation($paginated,new Configuration\Route('yasamjson_index'),array()); 
    
            $serializer = $this->get('jms_serializer');
            $data = $serializer->serialize([
                'meta' => $collection,
                'data' => $paginated->getItems()
            ], 'json');
    
    
           return new Response($data);
    
        }