Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller must return a response in Symfony2

Tags:

ajax

symfony

I have an ajax call in my code. What I want to achieve with the call works fine. I want to delete some records from the database which is actually deleted when the method is called via ajax but as in symfony method it must return a response and thats why when the method is executed its gives me the error

My Ajax call is

  $.ajax({
        type: "POST",
        data: data,
        url:"{{ path('v2_pm_patents_trashpatents') }}",
        cache: false,
        success: function(){
        document.location.reload(true);
        }
    });

And the method that is executed is

 public function trashpatentAction(Request $request){
    if ($request->isXmlHttpRequest()) {
        $id = $request->get("pid");
        $em = $this->getDoctrine()->getEntityManager();
        $patent_group = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')->find($id);
        if($patent_group){
            $patentgroup_id = $patent_group->getId();
            $em = $this->getDoctrine()->getEntityManager();
            $patents = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')
            ->findBy(array('patentgroup' => $patentgroup_id));
            if($patents){
                foreach($patents as $patent){
                    if($patent->getIs_deleted()==false){
                        $patent->setIs_deleted(true);
                        $em->flush();
                    }
                }
            }
            $patent_group->setIs_deleted(true);
            $em->flush();
        }
        else{
            $em = $this->getDoctrine()->getEntityManager();
            $patent = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')->find($id);
            if ($patent) {
                $patent->setIs_deleted(1);
                $em->flush();
            }
        }
        return true;
    }
}

How can I successfully return from this method ? Any ideas? Thanks

like image 837
Zoha Ali Khan Avatar asked Jun 25 '12 14:06

Zoha Ali Khan


2 Answers

Replace return true; with return new Response();. Also don't forget to write use Symfony\Component\HttpFoundation\Response; at the top.

like image 159
Anton Babenko Avatar answered Nov 05 '22 05:11

Anton Babenko


You can also pass error code 200 and the content type like below.

return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));

Here is the full example of the controller

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class WelcomeController extends Controller
{
    public function indexAction()
    {
        return new Response('Its coming from here .', 200, array('Content-Type' => 'text/html'));
    }
}
like image 3
Sam Kaz Avatar answered Nov 05 '22 05:11

Sam Kaz