Dynamically adding ActiveForm fields

Hi all, I have a static ActiveForm to which I dynamically add multiple elements.

I have a "+" button that runs a method that returns data to be added to the form.

the function looks like this:




public function actionPalodzes($i)

    {   	

		$mod = new Palodzes();

		echo Html::activeTextInput($mod,"[$i]platums",['style'=>'max-width:50px;']);

		echo Html::activeTextInput($mod,"[$i]garums",['style'=>'max-width:50px;']);

		

                /*

		$form = new ActiveForm();

		echo $form->field($mod, "[$i]platums")->textInput();

		echo $form->field($mod, "[$i]garums")->textInput();

		*/

		

    }



Every time I try to get it working with ActiveForm (the commented out fields) it returns a new form and I just can’t find a way to add to the existing form.

Is this even possible?

Thank you :)

Show the code where you are calling this action from.

This is the code. It is in _form.php ActiveForm fields are above and below this statement.




echo Html::input('button','btn_add','+',[

		'onclick'=>'$.post( "' . Yii::$app->urlManager->createUrl(['piedavajumi/palodzes', 'i'=>'']).'"+$("#palcnt").val(),

				function( data ){

					var val = $("#palcnt").val();

					$( "#palcnt" ).val( parseInt(val) + 1 );

					$( "div#apalodzes" ).append( data );

				});

		',//onclick end

]); 



It appends the data to a div.

Thank you!

I’ve managet to hack ActiveField type elements into the form like so:


 

echo "<span class=\"form-group field-palodzes-$i-platums required\">";

	echo "<label class=\"control-label\" for=\"palodzes-$i-platums\">Platums</label>";

	echo Html::activeTextInput($mod,"[$i]platums");

	echo '<span class="help-block"> </span>';

echo '</span>';



And manually add a custom validation like so:




$("#piedform").yiiActiveForm('add', {

	"id":"palodzes-0-platums",

	//"name":"Palodzes[0][platums]",

	"container":".field-palodzes-0-platums",

	"input":"#palodzes-0-platums",

	"message":".field-palodzes-0-platums .help-block",

	"validateOnType":true,

	"validate":function (attribute, value, messages, deferred) {yii.validation.number(value, messages, {"pattern":/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/,"message":"Platums must be a number.","skipOnEmpty":1});yii.validation.required(value, messages, {"message":"\u0160is lauks ir oblig\u0101ts"});}

});



Is there a way to generate the validation code automatically? like it is done when the form is created for the first time?