Migrating 4 to 5: replacing Zend's headLink and headScript?


#1

Up until Pimcore 4 the Zend Framework was used. In a lot of controllers I have pieces of code like this to include stylesheets and scripts. What is the recommended way of doing this in Pimcore 5?

$this->view->headLink()->appendStylesheet('/css/home.css');
$this->view->headScript()->appendFile('/js/home.js');

#2

Hi,
this should work as before … Pimcore 5 ships with several templating helpers: https://pimcore.com/docs/5.0.x/MVC/Template/Templating_Helpers/index.html

Cheers…


#3

Hi Fash,

Thanks for the reply, but they are not working for me. Is there anything I need to configure/enable/register?

All my calls to the view helpers in any controller throw an exception similar to this:

UndefinedMethodException
HTTP 500 Internal Server Error
Attempted to call an undefined method named "headLink" of class "Pimcore\Templating\Model\ViewModel".

My code in /src/AppBundle/Controller/DefaultController.php:

namespace AppBundle\Controller;

class DefaultController extends \Pimcore\Controller\FrontendController {

    public function init() {
	parent::init();
    }

    public function homeAction() {
	$this->view->headLink()->appendStylesheet('/css/slick.css');
    }
}

#4

Ah, you can’t do that in the controller anymore that way. Either you move that to the view, or you get the service from the container ($this->get('Pimcore\Templating\Helper\HeadLink')) and then call appendStylesheet on it.


#5

Thank you very much, it is working a lot better this way!

<?php

namespace AppBundle\Controller;

class DefaultController extends \Pimcore\Controller\FrontendController {
    
    public function homeAction() {

        $headLink = $this->get('Pimcore\Templating\Helper\HeadLink');
        $headLink->appendStylesheet('/css/slick.css');
        $headLink->appendStylesheet('/css/home.css');

        $headScript = $this->get('Pimcore\Templating\Helper\HeadScript');
        $headScript->appendFile('/js/slick.js');
        $headScript->appendFile('/js/home.js');
    }
}

#6

:+1:
if you register your controllers as services and use autowiring, you also could add the template helpers as params to your action - this would free your code from direct container access.
public function homeAction(Pimcore\Templating\Helper\HeadLink $headLink, Pimcore\Templating\Helper\HeadScript $headScript) {...}

Cheers…