Reputation: 1724
I recently updated my app from Symfony 1.4 to Symfony 2.7. Using the template code below, I have no problem when displaying the old data that are already save from the database.However, I noticed that when a user create a new data by filling form, twig will throw errors when displaying it in browser.The error tells
Impossible to invoke a method ("getProvince") on a null variable in DuterteBundle:Voters:index.html.twig at line 40
Actually the new data will successfully saved in the database but displaying it will throw the error.If I delete the said data, Twig will just work fine.Any Idea on how to fix this?
//voters.html.twig
<td>{{ entity.getCity() }}</td>
<td>{{ entity.City.getProvince() }}</td>//this where the error comes when adding new data by filling the form
//voters.orm.yml
manyToOne:
city:
targetEntity: City
inversedBy: voters
joinColumn:
name: city_id
referencedColumnName: id
orphanRemoval: false
//city.orm.yml
manyToOne:
province:
targetEntity: Province
cascade: { }
mappedBy: null
inversedBy: city
joinColumns:
province_id:
referencedColumnName: id
orphanRemoval: false
oneToMany:
voters:
targetEntity: Voters
mappedBy: city
//province.yml.orm
oneToMany:
city:
targetEntity: City
mappedBy: province
//VotersType
$builder
->add('city')
//CityType
$builder
->add('province')
//entity(voters.php
/**
* Set city
*
* @param \Project\Bundle\DuterteBundle\Entity\City $city
* @return Voters
*/
public function setCity(\Project\Bundle\DuterteBundle\Entity\City $city = null)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* @return \Project\Bundle\DuterteBundle\Entity\City
*/
public function getCity()
{
return $this->city;
}
//city.php
/**
* @var \Project\Bundle\DuterteBundle\Entity\Province
*/
private $province;
/**
* Set province
*
* @param \Project\Bundle\DuterteBundle\Entity\Province $province
* @return City
*/
public function setProvince(\Project\Bundle\DuterteBundle\Entity\Province $province = null)
{
$this->province = $province;
return $this;
}
/**
* Get province
*
* @return \Project\Bundle\DuterteBundle\Entity\Province
*/
public function getProvince()
{
return $this->province;
}
Upvotes: 0
Views: 1780
Reputation:
Try to check first if city exist. This should work
<td>{% if entity.city %}{{ entity.City.getProvince() }}{% endif %}</td>
Upvotes: 2