How to add zend form element at specific position?

310 views Asked by At

I have created an abstract form class that adds a submit element to the form. When my other form classes extend this form class I am having to call parent::__construct() at the bottom of the class so that the submit element is added last.

How do I set the submit button to always be the last element in the form, event if I call parent::__construct() first?

2

There are 2 answers

0
Richard Parnaby-King On BEST ANSWER

The form add function accepts two parameters - either an array or element instance, and an array of flags. One of the flag options is priority. The smaller the number, the lower in the list of elements it will appear. Therefore, setting it to -1000 (unless you have greater than 1000 elements) will set the submit button to appear at the bottom of the form:

$this->add([
    'name' => 'submit',
    'type' => 'submit',
    'attributes' => [
        'value' => 'Submit',
        'class' => 'btn btn-sm',
    ],
    'options' => []
],
[ 'priority' => -1000 ]);
0
Greco Jonathan On

RichardParanby-King's answer is good but careful for the view :

In the view we have a lot of options to show the form :

  • <?= $this->form($form)?>
  • <?= $form->get('{element}') ?>
  • loop over $form->getIterator()
  • loop over $form->getElements()

etc...

I have to say I used a lot this structure in all of my projects :

<?php foreach ($form->get('fieldset')->getElements()  as $elementName => $element): ?>
     <?= $this->partial('partial/formElement', ['element' => $element])?>
<?php endforeach ?>

The problem is : getElements does not use priority, so its just give the element in order of when it was instanciated.

In the view we have to use the iteration method ($form->getIterator()) to get back this priority.