We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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?



51.1k
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 :)