Symfony2 + AJAX: Can't fetch data in controller - ajax

Problem
I'm using Symfony2 with AJAX to insert a new record in my 'locations' table.
I can easily pass the data I want from the form to my Controller that handles that
AJAX request. I checked with Firebug and all the GET values are as I wanted.
Just to be clear the controller is not in the location controller but in the debug controller, don't know if that matters. (just for sandbox-testing atm).
Because of the relationships in the database the location entity has a district column which needs a district-entity object.
Problem is now this code is returning the succes response fine if I leave out the $em->flush(). If I add the $em->flush() to perform the insert, I get an 500 Internal error in my console of my browser.
Here's the code for my controller:
$request = $this->container->get('request');
if($request->isXmlHttpRequest()){
$street = $request->query->get('street');
$zip = $request->query->get('zip');
$lat = $request->query->get('lat');
$name = $request->query->get('name');
$number = $request->query->get('number');
// insert into object
$entity = new Location();
$entity->setStreet($street);
$entity->setZip($zip);
$entity->setLat($lat);
$entity->setName($name);
$entity->setNumber($number);
$em = $this->getDoctrine()->getManager();
$district = new District();
// get the district hard coded for testing
$district = $em->getRepository("SnowFrontBundle:District")->find(7);
$entity->setDistrict($district);
//$entity->setDistrict(null);
$em->persist($entity);
$em->flush();
//prepare the response, e.g.
$response = array("code" => 100, "success" => true);
return new Response(json_encode($response));
}
Question
What could be wrong with the $em->flush() part? How can I see what the real error is? (instead of 500 internal error). As well should I be using a createFormBuilder?

Related

Error in post method in laravel on hosting

The data is shown normal, it can be updated and everything, but when saving a record it is not saved and it shows me this error.
public function store(Request $request, Cuenta $cuenta){
$cuenta->id_cliente = $request->select_cliente;
$cuenta->id_plan = $request->select_plan;
$cuenta->id_plan_cuotas = $request->select_cuota;
$cuenta->tipo_cuota = $request->select_tipo_cuota;
$cuenta->id_agente = $request->select_agente;
$cuenta->save();
$data = DB::select("call change_status_create_cuotas(?, ?, ?)",array($request->select_cuota, $request->select_tipo_cuota ,$request->select_cliente));
return redirect()->route('cuentas.index');
}
This is code to save the data, in the localhost it works correctly, but in the hosting it does not leave anything.

Laravel controller and adding to the result set

I've checked the Q&A about this and can't find anything, so thought i'd ask.
I have a very simple Laravel controller returning all results from a table as below via the 'Name model'. There is then also a further call to my controller, via the model to count the rows and all works and sends to the result set fine...
// All results from my 'Name' model:
$results = $this->name->getAllResults(); // All works fine.
// I then use my controller again, count the rows via the model and add them to $results:
$results['count'] = $this->countNames(); // Again fine
BUT, when i try to add a string to the $results array before i pass it off to th view, as in:
$results['test'] = 'Test'; // This fails in the view
$results['test'] = 124; // But this passes in the view and renders.
It only seems to allow me to add an INT to my result set array. as $results['test'] = 124 also fails.
I then finally, have this sending to my view via:
return view('names', compact('results')); // And that works fine.
Can anyone see what it is I am missing and why integer added to $results works and not a string?. Many thanks in advance.
You are updating collection data. The following line will give collection of models.
$results = $this->name->getAllResults(); // This may give collection of the model
And below, you are updating the collection object.
$results['count'] = $this->countNames();
You can do the following to safely send data to view, without modifying any.
$results = $this->name->getAllResults();
$count = $this->countNames();
$test = 'Test';
$test2 = 124;
return view('names', compact('results','count','test','test2'));

View Same user_id

//Anyone can help to create a view data with same id? it is a multiple viewing.
this is my Controller. i dont khow apply in Model and View
function Get_Pitch($id){
$this->load->model('users_model');
$data['query'] = $id;
$this->load->view('view_pitch', $data);
}
Example this is my url "http://localhost/SMS_System/home/sample/102"
in my database is
id=1 name=erwin user_id=102
id=2 name=flores user_id=102
id=3 name=sample user_id=202
how to view the same user_id?
First of all with what you've supplied your URL won't work, you aren't following the normal conventions for CI so it won't know where to look. I am assuming your controller is called sample then you need to tell the application which function you're calling in that controller, finally URL names should be lower case so I changed that, so your URL should read:
"http://localhost/SMS_System/home/sample/get_pitch/102"
Also you need to get your data from a model, you loaded the model then didn't use it. The line after loading the model calls a function from that model and passes it the id you got from your url. Notice the if not isset on the id, this ensures that if someone goes to that page without the id segment there are no errors thrown from the model having a missing parameter, it will just return nothing, that is handled in the view.
Controller:
function get_pitch($id){
//the following line gets the id based on the segment it's in in the URL
$id=$this->uri_segment(3);
if(!isset($id))
{
$id = 0;
}
$this->load->model('users_model');
$data['query'] = $this->users_model->getUserData($id);
$this->load->view('view_pitch', $data);
}
Your model takes the id passed from the controller and uses that to retrieve the data from the database. I normally create the array I am going to return as an empty array and handle that in the view, this makes sure you get no errors if the query fails. The data then returns to the controller in the last line and is passed to the view in your load view call.
Model:
function getUserData($id)
{
$this->db->where('id',$id);
$result = $this->db->get('users') //assuming the table is named users
$data = array(); //create empty array so we aren't returning nothing if the query fails
if ($result->num_rows()==1) //only return data if we get only one result
{
$data = $result->result_array();
}
return $data;
}
Your view then takes the data it received from the model via the controller and displays it if present, if the data is not present it displays an error stating the user does not exist.
View:
if(isset($query['id']))
{
echo $query['id']; //the variable is the array we created inside the $data variable in the controller.
echo $query['name'];
echo $query['user_id'];
} else {
echo 'That user does not exist';
}

Symfony 2.1 ajax filter with KNP Paginator Bundle

Hi, I have page with a table with a list of elements (index.html.twig.). I'm using KNP Paginator Bundle to paginate the result. Now I want to implement some kind of filters in this page to filter the table result. I'm using AJAX to do this, so I create another view (grupos.html.twig) with the table and the paginator inside to render the result of the query.
Here is the controller code:
public function filtrarGrupoPorLetraAction(){
if ($this->getRequest()->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$letra = $this->getRequest()->get('letra');
$entities = $em->getRepository('GrupoBundle:Grupo')->filtrar($letra);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$entities,
$this->get('request')->query->get('page', 1) /*page number*/,
25/*limit per page*/
);
return $this->render('GrupoBundle:Grupo:grupos.html.twig', compact('pagination'));
}
}
but this code render a new page and I want to pass the result to index.html.twig to render a div.
How can I do this?
Simply append your result data to your div
if you just need a json response, use the code below
// create a JSON-response with a 200 status code
$response = new Response(json_encode($yourData));
$response->headers->set('Content-Type', 'application/json');
return $response;
if you need to render a a template
return $this->renderView('YourTemplateFile', $yourParams);
hope this helped

Doctrine 2/ Multi-step form / entity into session

I am working under Symfony2 and Doctrine 2.1.6 and I try to setup a multi-step form.
Between each form page, I try to send the doctrine entity into $_SESSION.
According to that dotrine documentation it is possible and even the way to settle multipage forms:
http://docs.doctrine-project.org/en/2.1/cookbook/entities-in-session.html
But according to a lot of other post on stackoverflow, it is just not possible to send entities into session.
I have the following controller Action where i pretty much copied/ past the doctrine documentation.
public function indexAction(Request $request, $id)
{
$session = $request->getSession();
$em = $this->getDoctrine()->getEntityManager();
if (isset($_SESSION['propertyAdd'])) {
$property = $_SESSION['propertyAdd'];
$property = $em->merge($property);
}
else {
$property = new property;
}
$form = $this->createForm(new propertyType($this->getDoctrine()),$property);
// check form
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()){
$em->detach($property);
$_SESSION['propertyAdd'] = $property;
// redirection to next step here
}
}
return $this->render('AddProperty:'.$id.'.html.twig', array(
'form' => $form->createView(),));
}
the line $_SESSION['propertyAdd'] = $property; give me the following error:
Fatal error: Uncaught exception 'ErrorException' with message 'Notice: Unknown: "id" returned as member variable from __sleep() but does not exist in Unknown line 0' in G:..\Symfony\vendor\symfony\src\Symfony\Component\HttpKernel\Debug\ErrorHandler.php on line 65
If I replace this line by using the Symfony2 helper
$session->set('propertyAdd', $property);
It throws the following exception:
Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::serialize() must return a string or NULL
Is the doctrine example workable.
This doesn't answer your question, but why would you:
Create an entity
Serialize it
Put it in the session (I personally don't believe it's a good thing to transform an object to a string)
Get it from the session in the form's next step
Deserialize it
Add the new data to it
Serialize it
Put it again in the session
An so on...
Why don't you store the form data directly in the session, and create the entity after all the form's steps were complete?
If you're doing this to validate the entity, you can simply use forms (that aren't linked to an entity) and add the validation constraints to them.

Resources