0

New to using Twig extensions, can use some help on this—can't figure out what is wrong.

Everything seems to be loading up correctly except with the function call in my extension class.

Am getting the following error:

FatalErrorException:Error:Cannot access property in /../PostExtension.php line 32

Line 32:

public function getPostCount($year, $month)

Have been searching for solutions and reading docs for hours and haven't been able to find the solution. Any help on this?

PostExtension.php

class PostExtension extends \Twig_Extension
{
private $em;

public function __construct(EntityManager $em)
{
    $this->em = $em;
}

public function getFilters()
{
    return array(
    );
}

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

public function getPostCount($year, $month)
{
    $post = $this->$em->getRepository('AcmeDemoBundle:Post')
        ->getPostCountsByMonth($year, $month);

    return $post;
}

public function getName()
{
    return 'post_extension';
}
}

Twig

{{ getPostCount('2014', 'July') }}

services.yml

services:
    acme.twig.extension:
        class: Acmer\DemoBundle\Twig\PostExtension
        tags:
            - { name: twig.extension }
        arguments:
            em: "@doctrine.orm.entity_manager"

Repository - getPostCountsByMonth

public function getPostCountsByMonth($year, $month)
{
    // Query for blog posts in each month
    $date = new \DateTime("{$year}-{$month}-01");
    $toDate = clone $date;
    $toDate->modify("next month midnight -1 second");

    $query = $this->createQueryBuilder('post')
        ->where('post.created BETWEEN :start AND :end')
        ->addOrderBy('post.created', 'DESC')
        ->setParameter('start', $date)
        ->setParameter('end', $toDate);

    $query->select('COUNT(post.created)');

    $month = $query
        ->getQuery()
        ->getSingleScalarResult();

    return $month;
}
2
  • You have a typo inside your getPostCount method $this->$em you should remove the $ sign because you want to access em property so use $this->em->... Commented Jul 4, 2014 at 7:51
  • Perfect!!! Can't believe I missed seeing that. Thank you so MUCH! Please make this an answer and I will happily accept it, sir! Commented Jul 4, 2014 at 8:00

1 Answer 1

3

You have a typo inside your getPostCount() method.

On this line $this->$em you should remove the second $ sign because you want to access em property so you should use it like this:

$post = $this->em->getRepository('AcmeDemoBundle:Post')
    ->getPostCountsByMonth($year, $month);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.