Hitesh Hadia
Hitesh Hadia

Reputation: 1063

Exception handling inside twig template

i am new to symfony2. my project has two entity

    [1] Category and
    [2] Evaluation

and category has many evaluation, so the problem is when i delete the category and then display the evaluation then it display me error like

"An exception has been thrown during the rendering of a template ("Entity was not found.") in HfAppBundle:SpecificEvaluations:index.html.twig at line 137. ".

on line number 137 this is the content {{evaluation.category.name}}. i had also try with

    {% if evaluation.category.name is not null %}
        {{evaluation.category.name}}
    {% endif %}

but it also give me same error. any one can help ?

thanks

Upvotes: 7

Views: 14754

Answers (3)

Yassine Guedidi
Yassine Guedidi

Reputation: 1715

Give a try to the default filter:

{{ evaluation.category.name|default('[No name]') }}

Upvotes: 0

malcolm
malcolm

Reputation: 5542

Use twig test defined :

{% if evaluation.category.name is defined %}
    {{evaluation.category.name}}
{% endif %}

Upvotes: 2

Praveesh
Praveesh

Reputation: 1327

Instead of checking for the category name, check whether the category associated with an evaluation exists.

{% if evaluation.getCategory  %}
        {{evaluation.category.name}}
{% endif %}

Ideally, when you delete a category that is linked to multiple evaluations, you should remove the relation between the deleted category and the evaluations.

For this, specify whether to delete all the evaluations when a category is deleted or to set the category of all related evaluations to null when deleting the category. For this, in yml the relation should be defined as

manyToOne:
        user:
          targetEntity: LB\CoreBundle\Entity\User
          joinColumn:
            name: user_id
            referencedColumnName: id
            onDelete: "SET NULL"

The onDelete can be either "SET NULL" or "CASCADE" depending on whether you need set the category field on evaluation as null or delete all the evaluations that are related to a category.

Modify your code for setting the category on evaluations as given below. You were not persisting the evaluations after setting the categorry to null.

$evaluations = $em->getRepository('HfAppBundle:Evaluation')->findByCategory($catId); 

foreach ($evaluations as $evl) { 
$evl->setCategory(null);
//this line was missing
 $em->persist($evl);
} 

$em->flush(); 

Upvotes: 0

Related Questions