2

I am trying to learn ZF2 and I just want to specify Javascript and CSS files to be included in my layout. I currently pass an array of paths relative to my public directory to my view and then loop through them. I would like to make use of the built in ZF2 solution using:

$this->headScript();
$this->headStyle();

I have tried many suggested methods on similar questions, but I must not be following them correctly.

One of the solutions I tried which seemed to make sense was here by using either of these in my controller:

$this->getServiceLocator()->get('Zend\View\HelperPluginManager')->get('headLink')->appendStylesheet('/css/style.css');
$this->getServiceLocator()->get('viewhelpermanager')->get('headLink')->appendStylesheet('/css/style.css');

I am not sure what viewhelpermanager it seems like a placeholder the poster used, but I have seen it in more than one question. I went ahead and found the location of Zend\View\HelperPluginManager but that did not work either.

By "not working" I mean my page is displayed without CSS and there is zero output from these:

$this->headScript();
$this->headStyle();

It seems like such a simple task and I do not know why I am having this much of a difficulty.

EDIT #1:

Here is my controller:

<?php
namespace CSAdmin\Controller;

use Zend\View\Model\ViewModel;
use Zend\View\HelperPluginManager;

class LoginController extends AdminController
{
    public function __construct() {
        parent::__construct();
    }

    public function indexAction()
    {
        //Set Action specific Styles and Scripts
        $viewHelperManager = $this->getServiceLocator()->get(`ViewHelperManager`);
        $headLinkHelper = $viewHelperManager->get('HeadLink');
        $headLinkHelper->appendStylesheet('/css/admin/form.css','text/css',array());
        $headLinkHelper->appendStylesheet('/css/admin/styles.css','text/css',array());

        //Override view to use predefined Admin Views
        $view = new ViewModel(array('data'=>$this->data));
        $view->setTemplate('CSAdmin/login/login.phtml'); // path to phtml file under view folder

        //Set the Admin Layout
        $layout = $this->layout();
        $layout->setVariable('layout', $this->layoutVars);
        $layout->setTemplate('layout/CSAdmin/login.phtml');

        //Render Page
        return $view;
    }

My AdminController:

<?php
namespace CSAdmin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AdminController extends AbstractActionController
{
    protected $data = array();
    protected $layoutVars = array();
    protected $viewHelper;

    public function __construct() {
        $this->layoutVars['customStyles'] = array();
        $this->layoutVars['customScripts'] = array();
        $this->layoutVars['miscCode'] = array();
        //$this->viewHelper = $viewHelper;
    }
}

EDIT #2:

@Wilt Error message for the above to controllers: Error message for the above to controllers

Line 19 is

$viewHelperManager = $this->getServiceLocator()->get("ViewHelperManager");

EDIT #3:

There are two modules involved here. Admin and CSAdmin, the controllers from Admin extend the controllers from CSAdmin and all of the controllers from CSAdmin extend a base controller within CSAdmin AdminController. AdminController extends AbstractActionController.

My controller and service_manager arrays for each module.config.php for both modules are below:

Admin:

'service_manager' => array(
    'invokables' => array(
        'CSAdmin\Form\LoginForm' => 'CSAdmin\Form\LoginForm'
    ),
    'factories' => array(
    )
),
'controllers' => array(
    'invokables' => array(
    ),
    'factories' => array(
        'Admin\Controller\Login' => 'Admin\Factory\LoginControllerFactory',
    )
),
// This lines opens the configuration for the RouteManager
'router' => array(
    // Open configuration for all possible routes
    'routes' => array(
        'admin' => array(
            'type' => 'literal',
            'options' => array(
                'route'    => '/admin',
                'defaults' => array(
                    'controller' => 'Admin\Controller\Login',
                    'action'     => 'index',
                ),
            ),
            'may_terminate' => true,
            'child_routes'  => array(
                'home' => array(
                    'type' => 'literal',
                    'options' => array(
                        'route'    => '/home',
                        'defaults' => array(
                            'controller' => 'Admin\Controller\Login',
                            'action' => 'home'
                        )
                    )
                ),
            )
        )
    )
)

CSAdmin:

'service_manager' => array(
    'invokables' => array(
    ),
    'factories' => array(
        'CSAdmin\Mapper\LoginMapperInterface'   => 'CSAdmin\Factory\LoginMapperFactory',
        'CSAdmin\Service\LoginServiceInterface' => 'CSAdmin\Factory\LoginServiceFactory'
    )
),
'controllers' => array(
    'invokables' => array(
    ),
    'factories' => array(
        'CSAdmin\Controller\Admin' => 'CSAdmin\Factory\AdminControllerFactory',
        'CSAdmin\Controller\Login' => 'CSAdmin\Factory\LoginControllerFactory',
    )
 )

EDIT #4:

/module/Admin/src/Admin/Factory/LoginControllerFactory.php:

namespace Admin\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Admin\Controller\LoginController;
use CSAdmin\Service\LoginServiceInterface;

class LoginControllerFactory implements FactoryInterface
{
    /**
    * Create service
    *
    * @param ServiceLocatorInterface $serviceLocator
    * @return mixed
    */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {

        $realServiceLocator = $serviceLocator->getServiceLocator();
        $loginService        = $realServiceLocator->get('CSAdmin\Service\LoginServiceInterface');
        $loginForm     = $realServiceLocator->get('FormElementManager')->get('CSAdmin\Form\LoginForm');

        return new LoginController(
            $loginService,
            $loginForm
        );
    }
}

/module/CSAdmin/src/CSAdmin/Factory/AdminControllerFactory.php:

namespace CSAdmin\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use CSAdmin\Controller\AdminController;
use Zend\View\Helper\BasePath;

class AdminControllerFactory implements FactoryInterface
{
    /**
    * Create service
    *
    * @param ServiceLocatorInterface $serviceLocator
    * @return mixed
    */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {

        $realServiceLocator = $serviceLocator->getServiceLocator();
        //$viewHelper        = $realServiceLocator->get('Zend\View\Helper\BasePath');
        //return new AdminController($viewHelper);
        return new AdminController();
    }
}

/module/CSAdmin/src/CSAdmin/Factory/LoginControllerFactory.php:

namespace CSAdmin\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use CSAdmin\Controller\LoginController;

class LoginControllerFactory implements FactoryInterface
{
    /**
    * Create service
    *
    * @param ServiceLocatorInterface $serviceLocator
    * @return mixed
    */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {

        $realServiceLocator = $serviceLocator->getServiceLocator();
        $loginService        = $realServiceLocator->get('CSAdmin\Service\LoginServiceInterface');
        $loginForm     = $realServiceLocator->get('FormElementManager')->get('CSAdmin\Form\LoginForm');

        return new LoginController(
            $loginService,
            $loginForm
        );
    }
}

EDIT #5:

After correcting the type of quotes being used I am still not getting the stylesheets in my layout. As a test I change ->appendStylesheet() to ->someMethod() and it properly reports that the method does not exist. So it definitely has an instance of the HeadLink object. As a next step I decided to just try defining everything in the layout file and it still does not use the stylesheets. See below for the exact code used in the <head> tag of my layout file.

<?php echo $this->doctype(); ?>
<html lang="en">
<head>      
    <meta charset="utf-8">
    <title><?php echo $this->layout['title']; ?></title> //Intend to change eventually.
<?php 
$this->headLink()->appendStylesheet('/css/admin/form.css');
$this->headLink()->appendStylesheet('/css/admin/styles.css');
echo $this->headScript();
echo $this->headStyle(); //This outputs nothing when viewing with the chrome debugger.
</head>

EDIT #6: In order to get it to work, instead of using:

echo $this->headScript();
echo $this->headStyle();

I just had to do:

echo $this->headLink();
3
  • @Wilt I have updated my question. Commented Nov 19, 2015 at 15:44
  • @Wilt, Ah, okay. So there is headLink, headScript, headStyle. I thought headLink was a generic instance of the other two and I was still supposed to access them with echo $this->headScript() and echo $this->headStyle(). All I had to do was echo out $this->headLink(). Thank you very much for your help and patience. Commented Nov 24, 2015 at 14:32
  • You are welcome. I cleanup the comments that are not relevant to others. Maybe you can do the same... Commented Nov 24, 2015 at 14:45

2 Answers 2

2

You will have to add echo to output the result...

echo $this->headScript();
echo $this->headStyle();
echo $this->headLink();

UPDATE

To get the Zend\View\HelperPluginManager in your controller you can do like this:

$viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');

Then you can do:

$headLinkHelper = $viewHelperManager->get('headLink');

UPDATE 2

Another thing, but it is a bit ridiculous, no wonder it was hard to find. You used wrong quotes:

`ViewHelperManager` //You cannot use these: `

Try like this:

'ViewHelperManager'

or like this:

"ViewHelperManager"
Sign up to request clarification or add additional context in comments.

1 Comment

@d.lanza38 $this->getServiceLocator()->get('ViewHelperManager'); should work. If not, then you broke something in your controller. Add your controller code to your question.
2

you need to append file in this way

$this->headScript()->appendFile(
     '/js/prototype.js',
     'text/javascript',
        array('conditional' => 'lt IE 7')
    );

then you write it

        echo $this->headScript();

note echo head script is required only one time. otherwise you inser js more time

more info at

http://framework.zend.com/manual/current/en/modules/zend.view.helpers.head-script.html

3 Comments

In your first set of code, can that go inside my controller? Are there any classes I need to declare with use at the top in order for this to work? I'm getting an error Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for headStyle. What if I needed to include an external style sheet such as with Google Fonts? Will this account for that?
It can go in your controller, but that's when you'd need to use the view helper manager. The viewhelpermanager line in your question is valid and should let you achieve this.
to insert google fonts simple indicare full uri without conditional array

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.