Is there a better way to design zend_forms instead of using decorators?

I am currently using zend_decorators to add styles to my form. I was wondering if there is an alternative way to do this? It's hard to write decorators. I would love the random use of divs and CSS styling:

<input type="submit" class="colorfulButton" > 

      

This is much easier than setting a decorator for a specific control and adding it. As this requires creating a decorator for each style implementation and adding it using a control. See helpers for a trick?

+2


source to share


2 answers


There are several ways. You can roll your own item view item helpers (which might get pretty awkward soon).

Or ... you can use a viewcript for a form like this (very simple example):

class Your_Form extends Zend_Form
{
    public function init()
    {
        $this->setDecorators( array(
            'PrepareElements',
             array( 'ViewScript', array( 'viewScript' => 'path/to/viewscript.phtml' ) )
        ) );

        // only use basic decorators for elements
        $decorators = array(
            'ViewHelper',
            'Label',
            'Errors'
        );

        // create some element
        $someElement = new Zend_Form_Element_Text( 'someElement' );
        // set the basic decorators for this element and set a css class
        $someElement->setDecorators( $decorators )
                    ->setAttrib( 'class', 'someCssClass' );

        // add (potentially multiple) elements to this from
        $this->addElements( array(
            $someElement
        ) );

    }
}

      



See the section on Standard Decorators about PrepareElements for why you need to create a PrepareElements decorator for your form for decoration when using the ViewScript decorator.

Then in viewcript:

<?
    // the form is available to the viewscript as $this->element
    $form = $this->element;
?>
<!-- put whatever html you like in this script and render the basic element decorators seperately -->
<div>
   <? if( $form->someElement->hasErrors() ): ?>
   <?= $form->someElement->renderErrors() ?>
   <? endif; ?>
   <?= $form->someElement->renderLabel(); ?>
   <?= $form->someElement->renderViewHelper(); ?>
</div>

      

+3


source


If you just want to set a class attribute on a form element, there is no need to define a decorator: this can be done using some of the standard zend_form element methods.

See the method , in the Metadata and Attributes section of the manual, and an example given there (cited): setAttrib()



// Equivalent to $element->setAttrib('class', 'text'):
$element->class = 'text;

      


And if you can set a class attribute that way, you can probably set it when building the form elements or in the .ini file that will define those elements - there is an example that shows that a little later on the page, in the Configuration section .

+1


source







All Articles