Include array or class/object in form model class

zend-form

#1

Hello world,

I have a multistep form and in step 3 there have to be some elements (and filters) that are dependant on the choise made in step 2.

In step 2 the user fills in a categorie (select out of 150 possibilities) and in the next step the user has to fill in some characteristics belonging to that categorie, so the characteristics in step 3 are dependant on the choise in step 2. There are about 10 characteristics per categorie, so put al that inputs in one form is a bit to much.

Via the controller i pass the choice to the form model, so my idea was to make 150 classes that produce the inputs and filters (or other includes like a JSON) and include the correct one in the form model bases on the categorie choise.

But wat is the safest way, include an array in the form model class with require_once, include an JSON array or do it with a new class like this:

class PlaatsenadvertentieForm extends Form
{
private $rubriek;

private $characteristics;

// Constructor.
public function __construct($step,$categorie)
{
    $this->categorie= $categorie;
    
    //instantiate new object for the characteristics based on the categorie
    $this->characteristics= new characteristics($this->categorie);
    
    // Define form name
    parent::__construct('plaatsen_advertentie');
 
    // Set POST method for this form
    $this->setAttribute('method', 'post');

    // Set binary content encoding (voor foto upload).
    $this->setAttribute('enctype', 'multipart/form-data');

    // Execute elements and filter functions
    $this->addElements($step);
    $this->addInputFilter($step);
   
}

protected function addElements($step) 
{
    if ($step==1) {
        …../////
   If (($step==1) {
        …//// some other elements
$this->add($this->characteristics->getCharacteristics());

  }

#2

I don’t know how require_once could help here, but I think it ends in a hidden dependence.

If I understand your problem correctly then the constructor injection is the right choice.


Some comments to your code:

Can be omitted, because this is the default method for a form which is created with zend-form.
See: https://github.com/zendframework/zend-form/blob/7fde0e8e830c47837bb91f20595e3b61bc7a0078/src/Form.php#L31-L33

Can be omitted when the file element is used in the form. If the method prepare is called then this will be set automatically.
See:

English names and comments would help here in the forum for a better understanding.
No idea if anyone here understands Dutch. :wink:


#3

I made some adjustments, maybe now its more clear :grinning: