AlexMA AlexMA - 3 months ago 30
PHP Question

ZF2 Form: Customizing order of elements

I'm creating a form for a logged-in user to change their password, so I created a subclass of an existing password-reset form I have available. The forms will be identical except with an additional field for existing password. It's worked so far, except I can't figure out a way to manually set the order the new field; the only place I've gotten it to appear is at the end of the form. It seems that ZF2 requires you to

add()
form elements in the order that you want them rendered. I would do so, except the subclass form's constructor must the parent form's constructor before it can add new fields, by which point the parent form has already added its fields.

I have already tried setting the property
order
of my new field, but it did not work; I've tried several different combinations (I can't find the documentation for this feature anywhere, after lots of searching).

Subclass constructor snippet:

class ChangePassword extends ResetPassword implements InputFilterProviderInterface {

public function __construct() {
parent::__construct();

$this->add(array(
'type' => 'Zend\Form\Element\Password',
'name' => 'existingPassword',
'order' => 0,
'options' => array(
'label' => 'Existing Password',
'order' => 0,
),
'attributes' => array(
'required' => 'required',
'order' => 0,
)
));
}


Parent constructor snippet:

class ResetPassword extends Form implements InputFilterProviderInterface {

public function __construct() {
parent::__construct('reset-password');

$this->add(array(
'type' => 'Zend\Form\Element\Password',
'name' => 'password',
...

Answer

The key you're looking for which affects element order is named priority.

The form add() method accepts a second array containing $flags, and it's in this array that you must add the priority key/value pair.

Your constructor should end up looking something like this ...

class ChangePassword extends ResetPassword implements InputFilterProviderInterface {

    public function __construct() {
        parent::__construct();

        $this->add(array(
            'type' => 'Zend\Form\Element\Password',
            'name' => 'existingPassword',
            'options' => array(
                'label' => 'Existing Password',
            ),
            'attributes' => array(
                'required' => 'required',
            )
        ), // add flags array containing priority key/value 
        array(
            'priority' => 1000, // Increase value to move to top of form
        ));
    }
}