How do you create a custom JSON output with FOSRestBundle?
The code already has methods which are used to convert entities and paginated result sets to JSON. As well as generate unique URLs to view/edit the entities in the outputted JSON.
How can these be used with FOSRestBundle?
Example of custom method to convert Bars to JSON output:
$json = $this->getJsonFactory('Bar')
->dataTableFormat($data);
return $this->jsonResponse($json);
How can this custom method be used as the output for JSON from view?
$data = $this->getDoctrine()->getRepository('Foo:Bar')
->findAll();
$view = $this->view($data, 200)
->setTemplate("Foo:Bar:index.html.twig")
->setTemplateVar('bars')
;
JMSSerializerBundle is available if it helps.
Using custom handlers this is possible, see docs: http://symfony.com/doc/master/bundles/FOSRestBundle/2-the-view-layer.html#custom-handler
Working example:
$handler = $this->get('fos_rest.view_handler');
if (!$handler->isFormatTemplating($view->getFormat())) {
$templatingHandler = function ($handler, $view, $request) {
$data = $this->getJsonFactory('Bar')
->dataTableFormat($$view->getData());
$view->setData($data);
return $handler->createResponse($view, $request, 'json');
};
$handler->registerHandler('json', $templatingHandler);
}
The $templatingHandler method handles calling the JsonFactory and setting the formatting of data for json output.
Related
I load models with relations (like a book, authors, publisher, keywords) and send it out to the web interface in JSON. Users will edit it there, and then the interface will send it back as JSON. The question is how do I create a model from the JSON (the opposite of toJson() call) and then save it to the database. It would also be helpful if I could compare the original data - reloaded from the db again - with the data I receive from the web layer.
You can decode the JSON once it's received by the server:
$decoded = json_decode( Input::get('json') );
If you want to compare the models one option is grabbing the ID of the model from your decoded JSON (make sure you double check the user has access to it in case they try fudging the data on you), loop over your key/values for your decoded data and match them against each other.
$model = YourModel::find( $decoded->id ); // dont forget to ensure they have access to this model
// Set up an empty array to store anything that's changed
$changes = array();
// Loop over your decoded values
foreach( $decoded as $key => $value ) {
// If the value in your model doesn't match the decoded value, add to the changes array
if( $model->{$key} != $value ) {
$changes[$key] = $value;
}
}
you can convert it to a collection by using collect(json_decode($json)).
collection Docs
I want to pass this JSON data to some view but don't know how its works.
I have used, make view also, and convert this data to JSON and pass other way but it didn't work
$items = Items::all();
return response()->JSON($items);
e.g view is items.create
For Laravel ver 4.2,
You can pass your data to your blade view with a variable (eg:$data) having an array which will be used in your blade.
$flag is variable being used in the JS part of your code, so you can pass that also as an array: Response::json(['param1' => $foo1, 'param2' =>$foo2)]);
In your controller return the view:
return Response::json(['view' => View::make('yourbladename', $data)->render(), 'flag'=>$flag]);
In your JS use the data variables as:
function(data){
$('#DivToAppendHTML').append(data.view); //this appends html blade to the Div having the ID DivToAppendHTML
if(data.flag == 1){ //this uses the second variable passed in controller for any other purpose
$('.classname').remove();
}
}
If you want to create JSON response, you need to convert collection to an array:
$items = Items::all()->toArray(); // $items is array now
return response()->json($items);
If you want to pass some JSON data to a view, do this:
$items = Items::all()->toJson();
return view('items.create', compact('items'));
am pretty new to json and i have this data that i would like to pass to a view script..the data comes from an sql query i have executed as below:
public function get_specific_users($param)
{
$select=new \Zend\Db\Sql\Select;
$select->from('users');
$select->columns(array('username','password','firstname','lastname','reputation'));
$select->where(new \Zend\Db\Sql\Predicate\Like('username',$param. "%"));
$resultSet=$this->tableGateway->selectWith($select);
return $resultSet;
}
this is how i call the function from my controller:
$users=$this->getUserTable()->get_specific_users('jo');
return new JsonModel(array('data' =>$users));
can i be able to pass the $users as above or should i first convert the resultset to an array..?if not how can i go about it..thanks in advance..
okay..i did more research and got it..had to include the following:
$users=$this->getUserTable()->get_specific_users('jo');
$result = \Zend\Json\Json::encode($users);
return $result;
the output was pretty clean json data which i can now parse using jquery..
im try encode an Doctrine entity as JSON string, to send as Ajax response.
So, i check the doc: The Serializer Component
I try with this code:
$em = $this->getDoctrine()->getManager();
// Get the entities repository
$sesiones_registradas = $em->getRepository('AuditBundle:AuditSession')->findAll();
// Instance the object
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));
// Convert only an item
foreach($sesiones_registradas as $sesion){
echo $serializer->normalize($sesion,'json');
break;
}
// Stop script
die();
Last code, fails saying:
Could not normalize object of type
AppsManantiales\AuditBundle\Entity\AuditSession, no supporting
normalizer found.
And if change $serializer->normalize($sesion,'json') by $serializer->serialize($sesion, 'json'); The error message is:
Serialization for the format json is not supported
Any ideas ?.
Your problem come from the fact you inverted both normalizers and encoders.
The line:
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));
must be:
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array(new JsonEncoder()));
Use the JMS Serializer Bundle
The docs can be found here: http://jmsyst.com/bundles/JMSSerializerBundle
I'm trying to integrate jQuery validation engine with my MVC project to perform inline validation. I have a field inside a jQuery form which is calling to an MVC controller and expects a JSON response. According this article written by the plugin's author...
Now this will send the field in ajax to the defined url, and wait for
the response, the response need to be an array encoded in json
following this syntax: ["id1", boolean status].
So in php you would do this: echo json_encode($arrayToJs);
How to achieve this in ASP.NET MVC4?
My current controller looks like this.
public JsonResult FunctionName(string fieldValue)
{
return Json((new { foo = "bar", baz = "Blech" }), JsonRequestBehavior.AllowGet);
}
The response body shows that it returns key value pairs that look like this
{"foo":"bar","baz":"Blech"}
How can I return JSON in the expected format?
The square brackets indicate an array within a JSON object.
See this article: http://www.w3schools.com/json/json_syntax.asp
This test code:
return Json(new object[] { "id1", false }, JsonRequestBehavior.AllowGet);
should return:
["id1",false]
If you want to return an array within the json, which i think you do. Then you can return a Dictionary. Your not seeing an array in the json output now because of the anonymous type you are passing in is two key values.
public JsonResult MyMethodName(string name)
{
IDictionary<string, bool> myDict = LoadDictionaryFromSomewhere();
return Json(myDict, JsonRequestBehaviour.AllowGet);
}