Dynamic Nested Forms in Yii2


Many thanks to the DoingITeasyChannel on YouTube which helped me get started on using this widget with nested forms.

I have the following code working on my Yii2 Site, and I’m very thank for this widget. @wbraganca you’ve done a great job with this. I hope I can give back by posting some helpful code here.

I recommend reading ALL of the example before copying the code.

dynamic forms

dynamic forms

FORM code

Starting with the View here, you can see I have three parts to my form. There is a header from the model Deposit, a parent DynamicForm from the model Payment, and a child/nested DynamicForm from the model PaymentLoads.

Modification of the Original Model Class

In order to make this work, the original Model Class had to be modified. The following two changes were made:

  • Added $data = null to the function arguments.
  • Changed the initialization of the $post variable to be $post = empty($data) ? Yii::$app->request->post($formName) : $data[$formName];

Here is the complete Model Class which I renamed to DynamicForms.


To reuse code between the Create and Update functions, I created an additional function called saveDeposit. The Create and Update actions call this function to save the data from the DynamicForm.

The following is the validation code referenced in the above controller

DepositCreate VIEW code

I’ve included the Create file here for those interested in how I styled the panel.



Prakash S

Prakash S

I would like to introduce myself as a Software professional opting for the career in software industry. I'm Prakash S, a MCA graduate and trained as industry level practice for Software technology. Basically I am a PHP Developer but now days exploring more in HTML5, CSS, AngularJS and jQuery libraries.