2
votes

To show an database count in my layout.phtml I want to use the view helper to render ths count (set in an db field).

How do I use my database model in a view helper?

Helper:

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

class CountHelper extends AbstractHelper
{
    protected $count; 

    public function __invoke()
    {
        return $this->count();
    }

    public function setTableCount($sm, $myCountTable)
    {
        $this->count = $sm->get($myCountTable)->getCount();
        return $this->count;        
    }
}

Module

public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                'CountHelper' => function($sm) {
                    $helper = new \Application\View\Helper\CountHelper();
                    $helper->setTableCount($sm, 'Application\Model\MyCountTable');

                    return $helper;
                },...

Error:

Catchable fatal error: Argument 1 passed to Application\Model\MyeCountTable::__construct() must be an instance of Zend\Db\TableGateway\TableGateway, none given, called in /usr/local/zend/share/ZendFramework2/library/Zend/ServiceManager/AbstractPluginManager.php on line 175 and defined in

1
Have at look at this answer from @jurian-sluiman -> stackoverflow.com/questions/14175009/zf2-service-locator/… - Crisp
Thanks for the replay, I updated my code above - directory
In your getViewHelperConfig() change the $helper->setTableCount() line to the following, $helper->setTableCount($sm->getServiceLocator(), 'Application\Model\MyCountTable'); - Crisp
Yea that works! Thanks a lot!!!! :) - directory
yah nice work, this worked finally and simple :) - Chali

1 Answers

1
votes

create a view helper

namespace My\View\Helper;
use Zend\View\Helper\AbstractHelper;

class CounterHelper extends AbstractHelper
{
    protected $count;

    public function __invoke()
    {
       return $this->count;   
    }

    public function setTableCount($sm, $mytablemodel)
    {
        $this->count =  $sm->get($mytablemodel)->getCountedData();
        return $this->count;
    }
}

and inject view_helpers via factories

'view_helpers' => array(
    'factories' => array(
     'counter_helper' => function($sm) {
        $helper = new \My\View\Helper ;
            $helper->setTableCount($sm, 'mytablemodelthatalreadyregisteredinSM');

        return $helper;
     }
    )
),