Multiple models in the same view
Often, we can find many models of same or different class in a single view. First of all, remember that Yii2 encapsulates all the views' form attributes in the same container, named the same as the model class name. Therefore, when the controller receives the data, these will all be organized in a key of the $_POST
array named the same as the model class name.
If the model class name is Customer
, every form input name attribute will be Customer[attributeA_of_model]
This is built with: $form->field($model, 'attributeA_of_model')->textInput()
.
In the case of multiple models of the same class, the container will again be named as the model class name but every attribute of each model will be inserted in an array, such as:
Customer[0][attributeA_of_model_0] Customer[0][attributeB_of_model_0] … … … Customer[n][attributeA_of_model_n] Customer[n][attributeB_of_model_n]
These are built with:
$form->field($model, '[0]attributeA_of_model')->textInput(); $form...