Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 214
Dr Magneto Avatar asked Sep 27 '22 19:09

Dr Magneto


2 Answers

Use twig test defined :

{% if evaluation.category.name is defined %}
    {{evaluation.category.name}}
{% endif %}
like image 181
malcolm Avatar answered Oct 18 '22 08:10

malcolm


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(); 
like image 37
Praveesh Avatar answered Oct 18 '22 07:10

Praveesh