How do I output data from a related object in a Twig template?
symfony, twig
Solution
I am assuming that Airline is a separate entity, which has an association to the Flight entity in Doctrine. Something like:
class Airline
{
private $id;
private $name;
private $flights;
...
}
Is that correct? If so, then that's the reason you're seeing that specific error. You're giving Twig an object, and telling it to print it out... but what does that mean, exactly?
Let's assume that your class looks like the above, and you're just trying to print out the name of the Airline.
You could do one of two things:
First, you could give your object a toString() method:
class Airline
{
public function toString()
{
return $this->getName();
}
}
Alternatively, you can give Twig something scalar to work with: Replace `{{ flight.airline }}` with `{{ flight.airline.name }}`.
Edit:
Just saw that your Airline object has a property called $IataCode. In that case, you'd render it in Twig using `{{ flight.airline.IataCode }}`.
Problem
I'm still very new to Symfony2 so please go easy on me. I'm trying to loop through a table of flights (for a flight ticket booking system), which have several related fields, such as airline, and airport. I'm using the following method in my custom repository: ``` public function getAllFlights($limit = 100) { $dql = 'SELECT f FROM Flightcase\BookingBundle\Entity\Flight f'; $query = $this->getEntityManager()->createQuery($dql); $query->setMaxResults($limit); return $query->getResult(); } ``` and the getAllFlights() is being passed to my Twig template like so: ``` $flights = $em->getRepository('FlightcaseBookingBundle:Flight')->getAllFlights(); return $this->render('FlightcaseBookingBundle:Flight:list.html.twig', array('flights' => $flights)); ``` And the Twig template is simply looping through the items inside the $flights collection like this: ``` {% for flight in flights %} <tr> <td>{{ flight.airline }}</td> <td>{{ flight.origin }}</td> <td>{{ flight.destination }}</td> <td>{{ flight.dateFrom }}</td> <td>{{ flight.timeFrom }}</td> <td>{{ flight.dateTo }}</td> <td>{{ flight.timeTo }}</td> </tr> {% endfor %} ``` But I get a ugly, cryptic exception telling me "Object of class Proxies\FlightcaseBookingBundleEntityAirlineProxy could not be converted to string" which leads me to believe I need to fetch a specific property inside the Airline object such as the IATA code to output as string. But how can I access the $airline->getIataCode() inside the Twig template? Or is there a way in my repository to convert the related objects into strings?