【发布时间】:2015-08-11 11:53:46
【问题描述】:
我最近将我的应用程序从 Symfony 1.4 更新到了 Symfony 2.7。使用下面的模板代码,我在显示已经从数据库中保存的旧数据时没有问题。但是,我注意到当用户通过填写表单创建新数据时,twig 在浏览器中显示时会抛出错误。错误告诉
无法在 DuterteBundle:Voters:index.html.twig 第 40 行的空变量上调用方法(“getProvince”)
实际上新数据会成功保存在数据库中,但显示会抛出错误。如果我删除上述数据,Twig 就可以正常工作。关于如何解决这个问题的任何想法?
//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
//选民类型
$builder
->add('city')
//城市类型
$builder
->add('province')
//实体(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;
}
【问题讨论】:
-
@Qoop 我不认为这是解决方案,因为它在显示旧数据时确实有效。只有通过填写表单添加新数据时才会引发错误。
-
尝试小写的
{{ entity.city.getProvince() }}