Zend 1 to Zend 2, was using decorators, how can i achieve the same behavior now?

89 views Asked by At

The title of the question is not self-explanatory, as there are tons of questions about migrating a Zend 1 app to a Zend 2 one, so i'll cut to the specifics of my problem.

First and foremost we used decorators to our form elements inside our view files, something like this:

$element = new Zend_Form_Element_Text('element');
$element->setLabel('Element');
$element->setRequired();
$element->setDecorators(array(new Nti_Form_Decorator_Item()) );
print $element;

The new Nti_Form_Decorator_Item() part is the decorator in question. This class receives the element and added some custom html to render inside the view. So instead of a simple label/input, we get some nice divs with custom classes wraping the whole thing.

class Nti_Form_Decorator_Item extends Zend_Form_Decorator_Abstract {
...
...
public function render($content) {
    $element = $this->getElement();
    // Build all the html here, using some methods of 
    // the Zend_Form_Decorator_Abstract class.
    return html_entity_decode($html);
}

This was the way we did it in Zend 1, good old nice decorators.
Now that the team decided to update the framework, we are having lots of trouble with our views, as apparently the decorator thing is long gone and we didn't find a quick and easy way to achieve the same results in terms of customization for all of the view files (Every single one of the form elements inside our views used the decorator for a standard design).

I have looked upon things like ViewHelper and stuff, but couldn't understand how to do it.

Can someone provide me with some advice on how can we do it?

1

There are 1 answers

1
Tim Fountain On BEST ANSWER

If you want the same markup around every element, the simplest way is to override the formRow() helper. Define your own version of this helper:

namespace Nti\Form\View\Helper;

use Zend\Form\View\Helper\FormRow as ZfFormRow;
use Zend\Form\ElementInterface;

class FormRow extends ZfFormRow
{
    /**
     * @param  ElementInterface $element
     * @throws \Zend\Form\Exception\DomainException
     * @return string
     */
    public function render(ElementInterface $element)
    {
        // build your markup here
        $html = '<div>';
        $html .= parent::render($element);
        $html .= '</div>';

        return $html;
    }
}

and add it as an invokable to your module.config.php:

'view_helpers' => array(
    'invokables' => array(
        'form-row' => 'NtiForm\Form\View\Helper\FormRow'
    )
)