Zend Framework 2 - View Helpers Within View Helpers

So anyway, rant over and still happily playing with Zend Framework 2...

Just a snippet, took a while to find an elegant solution to this one.

The basic problem was needing to access a Zend viewHelper from inside a custom viewHelper. Should be fairly simple, but took a little time to find.

Why did I need to do this? 

Zend's DateFormat helper (Zend\I18n\\View) throws an exception if an invalid date, datetime or timestamp is parsed to it. This includes nulls.

Unfortunately I'm processing data through a table generator service which takes viewHelpers as agruments 'per-column', and in some instances I need null dates to be parsed into the said helper as it determines no action.

Why not just add a null check into the DateFromat class?

That's fine until we update Zend at some point in the future and the change we made disappears. It's always best to extend.

There was a lot of mucking about trying to find this very simple piece of logic, and it comes courtesy of Crisp from this stackoverflow answer.

This  post didn't contain any usage, so here's the working viewHelper.


use Zend\View\Helper\AbstractHelper;
use IntlDateFormatter;

class DateFormatNull extends AbstractHelper
{
    public function __invoke(
               $date, 
               $dateformat = IntlDateFormatter::NONE, 
               $timeformat = IntlDateFormatter::NONE
             )
    {
        if (is_null($date)) {
            return null;
        }

        $dateHelper = $this->view->plugin('dateFormat');
        return $dateHelper($date, $dateformat, $timeformat);
    }
}

Whatever we would parse to dateFormat we need to parse to DateFormatNull as well,so it also needs the same required parameters ($date), although, for my purposes I've only included the optional date and time format options; dateFormat has additional parameters to this, but I don't need to worry about them here.

There may be a much easier way than this even to solve the problem, but it does the job.

That's it, hopefully this will be helpful to someone else as well, but if you now a better way do share!

Comments

Popular Posts