T
T
tsifra2014-08-25 10:17:01
symfony
tsifra, 2014-08-25 10:17:01

Check if related doctrine entity exists in twig?

The root entity has

/**
     * @var \Backend\SalesBundle\Entity\SalesOrder
     *
     * @ORM\OneToOne(targetEntity="Backend\CatalogBundle\Entity\CatalogProduct")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="product_id", referencedColumnName="product_id")
     * })
     */
    private $product;

When called in twig - everything is ok for the case when the product is in the database and when the product is no longer in the database
{{ item.product.productId }}
But if you make the call below, then the database will be called and doctrine will generate an error "entitty doen't exist" if the associated product is in the database no.
{{ item.product.name }}
The question is how to make the twig code so that it reacts normally to the absence of a record in the database?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tsifra, 2014-08-29
@tsifra

After digging through the Internet, it turned out that an elegant solution, apparently, does not exist.
As a result, it was written to do this:

public function getProduct()
    {
        try {
            $sku = $this->product->getSku();
        } catch (\Doctrine\ORM\EntityNotFoundException $e) {
            return null;
        }
        
        return $this->product;
    }

Although this leads to a different kind of problem if you need to get poductId {{ item.product.productId }}
Here's another option. Set fetch="EAGER" then immediately after the initialization of the root entity, the product will get null
/**
     * @var \Backend\SalesBundle\Entity\SalesOrder
     *
     * @ORM\ManyToOne(targetEntity="Backend\CatalogBundle\Entity\CatalogProduct", fetch="EAGER")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="product_id", referencedColumnName="product_id")
     * })
     */
    private $product;

P
Pavel Solovyov, 2014-08-25
@pavel_salauyou

do a check on if item.product

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question