I'm working on a project using Symfony 2, I've built a bundle to handle all my database services which passes JSON data back and forward.
My Problem/Question:
Is it possible to post a straight up JSON object? Currently I'm spoofing a normal form post for my ajax calls by giving the object a name json={"key":"value"}
if I don't give it a name I can't seem to get the data from the Symfony request object $JSON = $request->request->get('json');
I want to be able to use the one service bundle to handle both data coming from AJAX calls, or a normal Symfony form. Currently I'm taking the submitted Symfony form, getting the data then using JSON_ENCODE, I just can't work out how to post the data through to my services controller which is expecting request data.
To summarise:
I want Symfony to accept a JSON post object rather than a form.
I want to pass the JSON object between controllers using Request/Response
If I'm going about this all wrong, feel free to tell me so!
If you want to retrieve data in your controller that's been sent as standard JSON in the request body, you can do something similar to the following:
public function yourAction()
{
$params = array();
$content = $this->get("request")->getContent();
if (!empty($content))
{
$params = json_decode($content, true); // 2nd param to get as array
}
}
Now $params
will be an array full of your JSON data. Remove the true
parameter value in the json_decode()
call to get a stdClass
object.
I wrote method to get content as array
protected function getContentAsArray(Request $request){
$content = $request->getContent();
if(empty($content)){
throw new BadRequestHttpException("Content is empty");
}
if(!Validator::isValidJsonString($content)){
throw new BadRequestHttpException("Content is not a valid json");
}
return new ArrayCollection(json_decode($content, true));
}
And I use this method as shown below
$content = $this->getContentAsArray($request);
$category = new Category();
$category->setTitle($content->get('title'));
$category->setMetaTitle($content->get('meta_title'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With