简体   繁体   中英

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

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

Try to check first if city exist. This should work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM