I am new to Symfony framework. I am having some difficulties in pulling data from database. Here is my controller class:
class CrisisCtrl extends Controller{
public function listAction(Request $request)
{
$locations = $this->getDoctrine()->getRepository('AppBundle:Crisis')->findAll();
return $this->render(':index.html.twig', array(
'locations' => $locations
));
}
}
I followed an online tutorial to type all these out manually. When I typed $this->
, I tried to find getDoctrine()
from the suggestion list, however, I got nothing to select, therefore I typed them out manually and I not sure if this will cause any problem or not because apparently my code have some errors for now.
Inside my index.html.twig, I got these:
{% extends 'base.html.twig' %}
{% block page_content %}
// all the HTML
{% endblock %}
{% block custom_javascripts %}
<!-- Custom Theme Scripts -->
<script src="...//removed code"
async defer></script>
<script>
{% for location in locations %}
var map;
function initMap() {
var myLatLng = {lat: '{{ location.latitude }}', lng: '{{ location.latitude }}' };
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 10
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
{% endfor %}
</script>
{% endblock %}
However, I am getting error message saying the variable 'locations' does not exist
and the error is highlighted at the for loop in twig. I have been researching on other ways to fetch data from database and all of them are doing the same way.
I have no idea why is it so. Any ideas? Thanks in advance.
UPDATED
In my DefaultController class, I have these:
class DefaultController extends Controller
{
/**
* @Template("AppBundle:Default:index.html.twig")
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
return array();
}
}
The problem now is that the action is not calling the CrisisCtrl class. It is now executing the function above. I am not allowed to touch this function because if I changed it, other functions will be malfunctioned.
So in my CrisisCtrl class, before the listAction, I added these:
/**
* @Template("AppBundle:Default:index.html.twig")
* @Route("/", name="homepage")
*/
My file structure as such:
and my JavaScript is nested inside the index.html.twig. So I wonder how do I actually specify the route?