Dynamic sub forms using ajax

I would like to have a form that can dynamically load one of many sub forms based on a user’s input.

What I’ve tried so far is having a dropDownList with some ajax that will call an action in the controller. This controller will then renderPartial the subform and the resulting code will be inserted into the current page.

The problem is, this rendered sub-form also has its own pair of form tags. This causes the data in the sub-form to be lost when the outer form is submitted.

Any thoughts?


Just don’t render the <form> tags in the sub-form.

It seems this piece of code renders the <form> tags:

<?php $form=$this->beginWidget('CActiveForm', array(




)); ?>


<?php $this->endWidget(); ?>

If I render the main form as well as the sub-form at the same time, then the extra form tags are not added.

If I render the sub-form using an ajax call, then they are added.

I could just write the sub form by hand without using Yii, but then I wouldn’t be able to do this:

<div class="row">

		<?php echo $form->labelEx($model,'title'); ?>

		<?php echo $form->textField($model,'title'); ?>

		<?php echo $form->error($model,'title'); ?>


So things like validation output wouldn’t be as nice.

You could either:

  1. create a ticket to ask for a way to prevent the form tags from being generated by CActiveForm, and see if Qiang runs with it

  2. Use the CHtml::* methods instead of CActiveForm (this is how it used to always be done, and it’s not really any worse IHMO)

You could also just pass the $form variable into a renderPartial. Separate your form fields from the beginWidget/endWidget into a separate partial, so then you can pull in the renderPartial at will while passing $form.

I have been trying to troubleshoot this exact problem for a while now. I am using the CHtml approach, but I am still quite new to Yii and I am not sure how we could validate and have errors show up on the ajax loaded sub-form, when the outer main form is submitted. Any thoughts ?

Thank you kindly, this is my first ever post :)