Categorie: Zend Framework
Using ZendX_JQuery_Form and a custom view script
A while ago I was looking into the awesome features of ZendX, an extension to the Zend Framework that as the time of writing still comes as an extra, but is most likely to be part of the framework in the nearby future.
ZendX lets you use some great jQuery features, all the Zend-way. To learn how you can implement ZendX_JQuery I refer to an excellent videotutorial, which you can find at Zendcasts. To create an autocomplete text-field I used this tutorial, however, there's no Zend_Form created and that was what I needed.
After some searching I found out how to implement and use it in a custom Zend view-script. Here’s how:
First of all, create your Zend Form, but this time let it extend the ZendX_JQuery_Form class. This will allow you to use some ZendX_JQuery specific features, such as auto completion. Let’s create two text-input fields, one with auto completion and one without.
class MyCustom_Form extends ZendX_JQuery_Form { public function init() { $text = $this->createElement('text', 'text'); $text->setLabel('Text:'); $this->addElement($text); $autocomplete = $this->createElement('AutoComplete', 'autocomplete'); $autocomplete->setLabel('Autocomplete:'); $autocomplete->setJQueryParam('source', '/controller/action'); $this->addElement($autocomplete); } }
Notice that we create an element of type AutoComplete and also set the setJQueryParam to the url that will provide the auto completion-data (probably json).
After creating an instance of the form and passing it on to the view, you could simply do
<?php echo $this->form; ?>
and it would work.
However, if you plan to create a custom layout for your form, you will have to create something like this:
<?php $form = $this->form; ?> <form method="<?php echo $form->getMethod() ?>" action="<?php echo $form->getAction()?>"> <table> <tr> <td><?php echo $form->text->renderLabel(); ?></td> <td><?php echo $form->text->renderViewHelper(); ?></td> <td><?php if(count($form->text->getMessages()) > 0) { ?> <ul class="error"> <?php foreach ($form->text->getMessages() as $message) { ?> <li><?php echo $message;?></li> <?php } ?> </ul> <?php } ?> </td> </tr> <tr> <td><?php echo $form->autocomplete->renderLabel(); ?></td> <td><?php echo $form->autocomplete->renderUiWidgetElement(); ?></td> <td><?php if(count($form->autocomplete->getMessages()) > 0) { ?> <ul class="error"> <?php foreach ($form->autocomplete->getMessages() as $message) { ?> <li><?php echo $message;?></li> <?php } ?> </ul> <?php } ?> </td> </tr> </table> </form>
Notice that by the autocomplete-field , instead of using renderViewHelper(), we have to use renderUiWidgetElement(), as the former won’t work! I spent quite some time finding this out, so I’m glad to share it and hope people who are searching for a solution to the same or similar “problem” will find it.
Cheers.