Fabian
Fabian

Reputation: 1836

Symfony2: send post request from one controller to another

I am developing an API method to save a user to the database by a given json.

The method looks something like this:

/**
 * Create user.
 *
 * @Rest\View
 */
public function cpostAction()
{
    $params = array();
    $content = $this->get("request")->getContent();
    if(!empty($content)){
        $params = json_decode($content, true);
    }

    $user = new User();
    $user->setUsername($params['username']);
    $user->setFbUserid($params['id']);

    $em = $this->getDoctrine()->getManager();
    $em->persist($user);
    $em->flush();

    return new Response(
      $this->get('serializer')->serialize($user, 'json'),
      201,
      array('content-type' => 'application/json')
    );
}

I want to call it in several ways: Once via ajax, and once in a different controller. My ajax request looks like this:

  $.ajax({
    type: "POST",
    url: "/api/users",
    data: '{"id":"11111","username":"someone"}'
  })
  .done(function(data){
  })
  .fail(function(data){
  });

And now, to come to my question: I want to do the same inside a controller! For example:

public function checkFBUserAction()
{
    $user_data = '{"id":"2222","username":"fritz"}'
    // post data to /api/users (router: _api_post_users) via POST
    // get response json back

}

How can i achieve this??

Upvotes: 1

Views: 2939

Answers (2)

Javad
Javad

Reputation: 4397

In your second action you can forward the request:

public function checkFBUserAction()
{
   $user_data = array("id"=>"2222","username"=>"fritz");
   $this->getRequest->headers->set('Content-Type'), 'application/json');
   $this->getRequest()->request->replace(array(json_encode($user_data)));
   $this->forward('YourBundle:ControllerName:cpost');
}

Upvotes: 1

Ghugot
Ghugot

Reputation: 1

If you want to use this feature as a service, the better way to do is to move this into a Symfony service, and call this both in your controller and where you want into your project.

Upvotes: 0

Related Questions