Loop through Form Elements in the order they were added
Asked Answered
S

1

5

Zend Form 2 structures all Elements in Fieldsets. (Zend\Form\Form extends Fieldset - Form::add calls parent::add )

If i just add Elements to the Form i can get them via $form->getElements() if i use a fieldset i can get them via

foreach($form->getFieldsets() as $fieldset){
  $elements = $fieldset->getElements();
}

But imagine a form where i add a few hidden fields, then a fieldset, and at last a submit button.

How can i get the elements/fieldsets in their right order ?

Reason behind this, I'm working on a view helper which lets me print forms via a simple call to the view helper.

I don't want to call every form element via a call to formRow() (I know of the concept behind Form2 - separating logic from presentation)

Any help is much appreciated. TIA

Shooter answered 30/8, 2012 at 9:50 Comment(0)
C
9

you can do the following to get elements and fieldsets in the order they were added to the form:

/* $form is an instance of \Zend\Form\Form */
foreach ($form as $element) {

    // check if it's a form element or a fieldset etc.
    // and recursively iterate over elements of fieldsets etc.
}
Consubstantial answered 30/8, 2012 at 20:21 Comment(1)
ah thanks, so simple, i finally found where the IteratorAggregate Interface is set (in FieldsetInterface), but i dont find the current|next|prev methods for the iteration. so i never tried to directly loop over the object.Shooter

© 2022 - 2024 — McMap. All rights reserved.