Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to loop Elements in Form and display in view?

Hi guys,

Is there a way where i can loop all my Elements text fields, select dropdowns, buttons from my Form

class SampleForm extends Form{
    public function initialize(){

        $fname = new Text('fname');
        $lname = new Text('lname');
        $mname = new Text('mname');

        $this->add($fname, $lname, $mname);
    }
}

and in my form view I can do something like

{% for elements in  form %}
    <div class="form-group">
        {{ elements }}
     </div>
{% endfor  %}

is this possible?



32.7k
Accepted
answer

No. You add them independently.

    $this->add($fname);
    $this->add($lname);
    // ...

In your controller:

    $form = new YourForm();
    $this->view->form = $form;

And what you can do in your template is:

    {% for element in form %}
            <div class="form-group">
                <label for="{{ element.getName() }}">{{ element.getLabel() }}</label>
                {{ element }}
            </div>    
    {% endfor %}

Thank a lot @Calin Rada :)