How to add an external javascript file to a Zend Framework 2 application?

Mangala Edirisinghe picture Mangala Edirisinghe · Apr 27, 2012 · Viewed 20.6k times · Source

I need to add jQuery and other javascript files to my Zend Framework project. I am trying to do it with an Action controller:-

public function userinfoAction()
{   
    $this->view->headScript()->appendFile($basePath .'/js/validate_jquary.js');
    $this->headScript()->appendFile('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'); 
    return new ViewModel();
}

But it is not working.

Answer

aimfeld picture aimfeld · Nov 30, 2012

Here is how you can use view helpers from within a controller in ZF2 to solve your problem:

public function someAction()
{                 
     $this->getViewHelper('HeadScript')->appendFile($basePath . '/js/somejs.js');    
}

protected function getViewHelper($helperName)
{
    return $this->getServiceLocator()->get('viewhelpermanager')->get($helperName);
}