I have been working with Zend Framework for a few months now. I have so far been succesfully using some view helpers, action helpers and partials. Now i have come across some javascript libraries i want to use in my project such as TinyMCE and others.
My question is, what is the best way to implement these in a Zend Project? Preferably i would like to be able to add or enable these javascript libraries on a view level. So for example when i go to my addSomething.phtml wich contains a zend_form, one of my text area's becomes a TinyMCE editor field. However i do not want this on all my forms or even all my text area elements.
So what is the best way to implement and then approach these libraries under ZF 1.11.11?
Thanks in advance for any advice given :)
You can use a view helper to load javascript and css files on a per controller/view basis. This is something I have experimented with and I find it quite helpful, although I haven't taken the step of putting it into a live project yet, I'm still assessing it.
Here is the devzone article I got the idea from. All credit to Andy Baird for posting the technique.
Basically you setup two view helpers, one for javascript:-
class Zend_View_Helper_JavascriptHelper extends Zend_View_Helper_Abstract
{
function javascriptHelper() {
$request = Zend_Controller_Front::getInstance()->getRequest();
$file_uri = 'media/js/' . $request->getControllerName() . '/' . $request->getActionName() . '.js';
if (file_exists($file_uri)) {
$this->view->headScript()->appendFile('/' . $file_uri);
}
}
}
and one for css:-
class Zend_View_Helper_CssHelper extends Zend_View_Helper_Abstract
{
function cssHelper() {
$request = Zend_Controller_Front::getInstance()->getRequest();
$file_uri = 'media/css/' . $request->getControllerName() . '/' . $request->getActionName() . '.css';
if (file_exists($file_uri)) {
$this->view->headLink()->appendStylesheet('/' . $file_uri);
}
return $this->view->headLink();
}
}
Then you call them from your layout script:-
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My app title</title>
<? $this->headLink()->appendStylesheet('/media/css/global.css') ?>
<? $this->headLink()->appendStylesheet('/media/css/iefix.css','screen','lt IE 7') ?>
<?= $this->cssHelper() ?>
<? $this->headScript()->appendFile('/media/js/jquery-1.3.2.min.js') ?>
<? $this->headScript()->appendFile('/media/js/global.js') ?>
<? $this->javascriptHelper() ?>
<?= $this->headScript() ?>
</head>
You then store your javascript and css files in folders that reflect the name of the action they are used with, for example:-
media/js/index/index.js
media/css/index/index.css
to load css and javascript for you index action.
In practice I have found it preferable to put javascript and css in the same folder, so I miss out the js
& css
parts of the paths above and adjust the $file_url
variable in both helpers accordingly.