Twig Error Runtime:无法在null变量上调用方法('somemethod')

时间:2015-08-11 11:53:47

标签: symfony twig

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

  

无法在DuterteBundle中的空变量上调用方法(“getProvince”):第40行的选民:index.html.twig

实际上新数据将成功保存在数据库中,但显示它会抛出错误。如果我删除了上述数​​据,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

// VotersType

 $builder
        ->add('city')

// CityType

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

1 个答案:

答案 0 :(得分:2)

首先尝试检查城市是否存在。 这应该工作

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