Search code examples
phpcsszend-framework2

How to add a "new line" after a ZF2 form element?


Using ZF2 I am trying to place <br> or a similar element between my form elements. ZF1 had something like "Decorators" which are no longer in ZF2 to my knowledge. However, ZF2 does not have something $form->addBr() element, and that is what I need.

Here is how I render a form in my View:

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

Here is how I prepare my $form in my controller

    // Set up checkbox
    $checkbox = new Element\Checkbox('checkbox');
    $checkbox->setChecked(true);

    //Set up text
    $text = new Element\Text('text');
    $text->setLabel("Hi");
    $text->setValue(333);

    // Assemble Fielset
    $fieldset = new Fieldset("FS");
    $fieldset->setLabel("Label");

    $fieldset->add($checkbox);

    //NOTE:  I need a "NEW LINE" Here
    $fieldset->ADD_NEW_LINE();// no such method 


    $fieldset->add($text);

    // Assemble Form
    $form = new Form();
    $form->add($fieldset);

Current Issue:

Form elements render out on a single line when I want them to be on a new line each.

Question

When I want to ZF2 just render the entire form in one go, like I try to do here (preferably without having code in view that renders out the form line by line), how can I make it so that I can place new form elements on new lines?

I am open to any solutions -- whether it be programmatic ZF2 solutions or CSS solutions (if possible) or other solutions I can't think of yet. I just want the form to render out with elements being shown on new lines instead of showing up on a single line.

ZF2 Renders HTML like so:

<fieldset>
  <legend>Legend</legend>
  <label><span>Check</span>
    <input name="name[checkbox]" value="0" type="hidden">
    <input name="name[checkbox]" value="1" checked="checked" type="checkbox">
  </label>

  <label><span>Value</span>
    <input name="name[text]" value="123" type="text">
  </label>
</fieldset>


Solution

  • I was able to make this happen -- essentially copied ZF2's own mechanisms and got some help from this answer: https://stackoverflow.com/a/15827116/2883328

    I removed FieldSet that was only messing me up, and then used a loop to cycle through the Form elements, amending <br/> where I wanted it - after each element. So much for that.

    <?php
    /**
     * inside view template
     *
     * @var $this \Zend\View\Renderer\PhpRenderer
     * @var $form \Zend\Form\Form
     */
    $form = $this->form;
    ?>
    <fieldset>
        <legend>Legend</legend>
        <?php
        echo $this->form()->openTag($form);
        foreach ($form as $element)
            $formContent .= $this->formrow($element) . "<br/>"; //note the "BR"
    
        echo $formContent;
        echo $this->form()->closeTag();
    
        ?>
    </fieldset>