I am trying render a modal window dynamic, the problem is when return my response Json, i get the next error:
The Response content must be a string or object implementing __toString(), "boolean" given.
This is my controller:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
//Some Code...
public function detallesAction($id)
{
$em = $this->getDoctrine()->getManager();
$articulo = $em->getRepository("FicherosBundle:Articulo")->find($id);
$html = $this->render('FicherosBundle:Articulos:detalles.html.twig', array(
"articulo" => $articulo
))->getContent();
$response = new Response(json_encode(array(
"detalles" => $html
)));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
And this my template detalles.html.twig:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Detalles</h4>
<small class="font-bold">En esta ventana se ve reflejada toda la información del articulo.</small>
</div>
<div class="modal-body">
Hello world
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Cerrar</button>
</div>
And this is my call to AJAX from index.html.twig:
$('.detalles').click(function () {
var id = $(this).data("id");
var url = Routing.generate('articulos_detalles', { id: id });
$.ajax({
url: url,
cache: false,
success: function(response) {
$(".modal-content").html(response.detalles);
$("#myModal2").modal("show");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
})
});
Where is the problem? :/
It seems your html cannot be encoded correctly in json.
Also you should directly use the renderView
method and JsonResponse
to render it without specifying headers/encoding json manually.
This will prevent you from errors like you have now using a custom Response.
It should be :
$html = $this->renderView('FicherosBundle:Articulos:detalles.html.twig', array(
"articulo" => $articulo
))->getContent();
return new JsonResponse($html);
Hope this helps.