zend-formzend-framework3

how to remove fields from form class and view


Depending on from where the form is called I want to remove some unused fields. I tried the following from my controller class:

switch ($typ){
        case 3:                   //Analyse
            $form->get('analyseid')->setValue($id); //works
            $form->remove('vertragid');  //doesn't work
            break;
    }

I get some errors:

No element by the name of [vertragid] found in form \wiedervorlage\add.phtml(25): Zend\Form\Fieldset->get('vertragid')

Of course I try to get attributes in my view.phtml skript.

My question is: How can I remove a field from the form and the view, too.


Solution

  • Althought I'm not really a fan of this kind of workarounds, the solution here is quite simple.

    If you need to remove certains elements given on some condition, you can remove them from the controller with the following lines:

    switch ($typ) {
        case 3:
            // Remove the element 'vertragid'
            $form->remove('vertragid');
            // Remove inputfilters. This is necessary, because if the element
            // is required, the inputfilter will always block the validation
            // of the form
             $form->getInputFilter()->remove('vertragid');
            break;
    }
    

    To avoid errors in your view, you have to check if that element exists in the form:

    if ($form->has('vertragid')){
        echo $this->formRow($form->get('vertragid');
    }