0
votes

I'm using Zend Framework 1.12 on a project. I having some problems with the Zend_Form. Some fields are generated dynamically on execution time, but the Zend_Form is static, a element predefined at creation.

So, when the form is sent, the validation doesn't work because new fields were added and the sent form doesn't match the form created.

How do that adaptation?

2
Could you explain what you mean by "Some fields are generated dynamically on execution time" ? From my point of view, these form elements are created in the controller and added to the form BEFORE the validation occurs. So, that should work. Could you check that you are creating and adding the elements before the validation ? - Eric MORAND
The form elements are instantiated on the controller,then added to the view. I have a Zend_Form_Element_Select on a form, initially empty. The data is created by user, on the same form. So, each time that the user creates a new registry, a Ajax call is done and append the new registry on this select input. The Zend_Form_Element_Select,initially empty, is sent with more attributes than when was created. So, the methods of validation don't works, because the forms don't match. - Hugo Dias
Well, you should NOT send them to the view. You should add them to the form. And then send the form to the view. That's how it is supposed to work. - Eric MORAND
I had the same problems, i.e. fields dynamically added at runtime to the form are not found in the form itself (e.g. calling the $form get Values() function). However I do not see Zend_Form defined as static as you stated above. Why does this happen then? - MDT

2 Answers

1
votes

You should try, following solution: after sending the form, get the $_POST array, then check which fields/values do you have and create/modify form Object with this fields/validation.

0
votes

I would have done this way :

class MyForm extends Zend_Form
{
    public function init()
    {
        //... Create here the basic elements

    }

    public function initFromPostValue( $post )
    {
        if( array_key_exists( 'dynamicsField', $post ) ) {
            $el = $this->createElement( 'select', 'dynamicsField' )
                ->setValidators( array( ... PUT your validators here ) );

            $this->addElement( $el );
        }

    }
}

In the validation action :

public function validationAction()
{
    $form = new MyForm();
    $form->initFromPostValue( $_POST );

    if( $form->isValid( $_POST ) ) {
        // Form is valid
    } else {
        // Form is invalid
    }
}