Question

I need to use a productRepository method from within a custom twig extension. I can use standard methods like 'findOneBy' but if I define a custom method in productRepository (say returnVariants() ) then I get this error:

An exception has been thrown during the rendering of a template ("Undefined method 'returnVariants'. The method name must start with either findBy or findOneBy!") in SyliusWebBundle:Frontend/Homepage:main.html.twig at line 16.

The code of the custom twig extension:

namespace Sylius\Bundle\WebBundle\Twig;

use Symfony\Bridge\Doctrine\RegistryInterface;

class ProductExtension extends \Twig_Extension
{
    public function __construct(RegistryInterface $doctrine)
    {
         $this->doctrine = $doctrine;
    }

    public function getFunctions()
    {
         return array(
             'product_func' => new \Twig_Function_Method($this, 'productFunc'),
          );
    }

    public function productFunc($id)
    {
         /* This works */
         $product = $this->doctrine->getRepository('SyliusCoreBundle:Product')
->findOneBy(array('id' => $id));
         /* This doesn't */
         $product = $this->doctrine->getRepository('SyliusCoreBundle:Product')->returnVariants();

         return $product->getPrice();
    }

Thank you very much for your help!

Was it helpful?

Solution

Make sure your entity is using the custom Repository

/** 
* @ORM\Entity(repositoryClass="Sylius\...\ProductRepository") 
**/
class Product { ... }

Also try clearing your cache

I would suggest not making a custom twig function. Call this function in the controller and pass the results to twig

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top