Twig 错误运行时:无法在空变量上调用方法 ('somemethod')

Twig Error Runtime: Impossible to invoke a method('somemethod') on a null variable

我最近将我的应用程序从 Symfony 1.4 更新到 Symfony 2.7。使用下面的模板代码,我在显示已经从 database.However 保存的旧数据时没有问题,我注意到当用户通过填写​​表单创建新数据时,twig 在显示它时会抛出错误 browser.The 错误告诉

Impossible to invoke a method ("getProvince") on a null variable in DuterteBundle:Voters:index.html.twig at line 40

实际上新数据将成功保存在数据库中,但显示它会抛出 error.If 我删除了上述数​​据,Twig 将正常工作 fine.Any 关于如何解决这个问题的想法?

//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;
}

先尝试检查城市是否存在。 这应该有效

<td>{% if entity.city %}{{ entity.City.getProvince() }}{% endif %}</td>