'ZendFramework - How to add ->HeadScript() from Controllers?

I have a case where i need to add the Javascript from controller to the Layout where it has already HeadScript();

How to do that from controller?

e.g: $this->view->HeadScript()->appendScript();

This is controller: Both does not apply.

class RouterController extends Zend_Controller_Action
{
  public function init()
  {
    $this->view->HeadScript()->appendFile('/js/test.js')->setIndent(8);
    $this->view->HeadScript( Zend_View_Helper_HeadScript::FILE, '/js/test.js' );
  }
}

This is the view file: index.phtml

<?//$this->HeadScript()->appendFile('/js/test.js')->setIndent(8);?>

If i uncomment in view it works but not in Controller. I want to apply this from controller how now?



Solution 1:[1]

I got this to work from the preDispatch method in a controller, remember you have to pass layout changes before headers are passed.

public function preDispatch() {
        parent::preDispatch();
        $layout = new Zend_Layout();

        $layout->getView()->headScript()->appendScript('/javascript/form.js', 'text/javascript');
    }

you still have to have the headScript placeholder in your layout.

Solution 2:[2]

$this->view->headScript()->appendFile('/path/to/file.js');

Solution 3:[3]

<?//$this->HeadScript()->appendFile('/js/test.js')->setIndent(8);//Your question ?>
$this->view->headScript()->appendFile('/path/to/file.js');//Alex Howansky's answer

There slightly different. :)

Solution 4:[4]

$this->view->HeadScript( Zend_View_Helper_HeadScript::FILE, '/path/to/file.js' );

or

$this->view->HeadScript( Zend_View_Helper_HeadScript::SCRIPT, 'js code' );

The same for $this->view->InlineScript().

Solution 5:[5]

$headScript = $this->getServiceLocator()->get('viewhelpermanager')->get('headScript');
$headScript->prependFile($this->getSystemBaseUrl()."js/front_end/lib/jQuery/jquery-2.2.3.min.js","text/javascript");

Solution 6:[6]

In case if its still useful to someone, you need to include following in layout script file:

<?php echo $this->headScript(); ?>

Reference: https://framework.zend.com/manual/1.11/en/zend.view.helpers.html#zend.view.helpers.initial.headscript

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alex Howansky
Solution 3 undefined
Solution 4 Al_
Solution 5 Tunaki
Solution 6 Komal