Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a Json into a Entity in Symfony2

I'm developing an sale system with an iPad front-end and a Symfony2 based server. The comunication between them is made by POST method in jSon format.

I have seen that there is a posibility of binding a form into an entity but I don't know if there would be possible to do that if I recive a jSon object.

For example this is what I have in the front end(for simplicity is in Javascript):

var sale=new Sale();
sale.client=10;
sale.user=1;
sale.product=11;
sale.quantity=100;
var jSon={"client": sale.client,
                            "user":sale.user,
                            "product":sale.product,
                            "quantity":sale.quantity}     

$.post("http://examplepath.com/new_sale", jSon,
             function (data) {
                if (data) {
                    alert(data);
                }
                else {
                    alert("Not working :-(");
                }
            }
);   

Now when I recive the jSon in the I do something like this:

$sale=new Sale(); //This is my entity :)
$sale->setUser($request->request->get("user"));
$sale->setClient($request->request->get("client"));
$sale->setProduct($request->request->get("product"));
$sale->setDate($date);

$em = $this->getDoctrine()->getEntityManager();
$em->persist($sale);
$em->flush();

Is there any way to bind the jSon recieved by POST with my Sale entity without doing all those nasty setters ?

like image 317
user1966562 Avatar asked Jan 10 '13 12:01

user1966562


1 Answers

What you are looking for is called Serialization.

You can use the default Serializer component provided by Symfony 2, but a more handy approach would be by using JMSSerializerBundle.

like image 178
iamdto Avatar answered Oct 10 '22 09:10

iamdto