yii2 name field attribute using variable

227 views Asked by At

I'm trying to create in an activeform a series of controls using a loop for not being to declare the various fields of the model in order to have a generic template to which I pass only the name of the table and it creates the edit form. So that if I pass the table A and it has 3 fields it creates three fields, the b has 5 fields it creates 5 fields etc etc.

$tfields= Array ( [0] => id [1] => brand_id [2] => group_id) and i create this code

foreach($tfields as $key => $value) {
    if (strlen($value)>0){
 echo $form->field($model,  $value)->textInput();
}
  }

but when i run the code i get this error

Calling unknown method: yii\data\ActiveDataProvider::isAttributeRequired()

any ideas? tks a lot!

1

There are 1 answers

0
marco cardinale On

the problem was tha i use an ActiveDataProvider as model, using instead and DynamicModel

in the controller

$model2= new \yii\base\DynamicModel([
   ]);

in the form

 foreach(explode(',',$fields) as $item){
    if (strlen($item)<>0){ //to avoid empty 
   echo $form->field($model2, $item)->textInput();
     }
  }