Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Reset HeadTitle Position from View

Posted in Teknologi, Tutorial PHP, Zend Framework 2 by samsonasik on July 14, 2013

zf2-zendframework2Sometime, we need to reset position of title that default we can look at ZendSkeletonApplication like “My Album – ZF2 Skeleton Application” to something like “ZF2 Skeleton Application – My Album”.
We CAN NOT do this from view :

$this->headTitle($title, 'PREPEND');
//OR
$this->headTitle($title, 'APPEND');

because of the layout rendered after view rendered, so we need to pass a value from view to layout via placeholder. So after set a title at view, we need to pass a value via placeholder view helper.

// module/Album/view/album/album/index.phtml:
$title = 'My albums';
$this->headTitle($title);
$this->placeholder('titleType')->set('PREPEND');

so we can set the title type at layout like the following :

// module/Application/view/layout/layout.phtml:
echo $this->headTitle('ZF2 Skeleton Application', 
        $this->placeholder('titleType', 'APPEND'))
          ->setSeparator(' - ')->setAutoEscape(false);

$this->placeholder(‘titleType’, ‘APPEND’) that passed at 2nd parameter of headTitle() means that if titleType already set, so get from the already data, if no, set to ‘APPEND’ as default value.

When situation need to remove layout title ( parameter is ‘SET’), and use the view title, we need to make a conditional like this :

// module/Application/view/layout/layout.phtml:
if ($this->placeholder('titleType', 'APPEND') == 'SET') { 
    echo $this->headTitle()->setAutoEscape(false);
} else {
   echo $this->headTitle('ZF2 Skeleton Application', 
          $this->placeholder('titleType', 'APPEND'))
             ->setSeparator(' - ')->setAutoEscape(false);
}

That’s it 😉

references:
1. http://stackoverflow.com/questions/13949809/zend-framework-2-make-content-page-variable-accessable-in-layout-phtml
2. http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.placeholder.html#zend-view-helpers-initial-placeholder

5 Responses

Subscribe to comments with RSS.

  1. Bakyt Niyazov said, on July 14, 2013 at 7:34 pm

    There is some small possibility that it was inspied by this issue 🙂
    https://github.com/zendframework/zf2/issues/4810

    • Bakyt Niyazov said, on July 15, 2013 at 12:24 am

      But I forgot to say Thanks for this post!

      • samsonasik said, on July 15, 2013 at 12:31 am

        No. I’m not inspired by that issue :). You’re welcome!

  2. coud said, on July 18, 2013 at 12:43 pm

    You can also pass a variable to your layout from your view using $this->layout()->titleType = ‘APPEND’;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: