For example we have this ActiveForm
implementation in a sample view:
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'first_name')->textInput(['maxlength' => true]); ?>
<?=$form->field($model, 'last_name')->textInput(['maxlength' => true]); ?>
<div id="additional-form-fields"></div>
<a href="#" id="load-additional-form-fields">
Load more fields
</a>
<?php ActiveForm::end(); ?>
Now, I want to add more ActiveField
/ ActiveForm
fields inside this form and place them in the #additional-form-fields
element with Ajax, I'd do a simple jQuery
callback:
$('#load-additional-form-fields').click(function() {
$.get('/site/additional-fields', {}, function(data) {
$('#additional-form-fields').html( data );
});
});
And the action additional-fields
inside SiteController
would be something as:
public function actionAdditionalFields() {
$model = new User;
return $this->renderAjax('additional-fields', [
'model' => $model,
// I could pass a 'form' => new ActiveForm, here, but it's a big NO-NO!
]);
}
And this works perfectly, only if I don't use any other ActiveField
fields inside this action's view:
<?=$form->field($model, 'biography')->textInput(['maxlength' => true]); ?>
<?=$form->field($model, 'country')->textInput(['maxlength' => true]); ?>
<?=$form->field($model, 'occupation')->textInput(['maxlength' => true]); ?>
Of course, I have to pass or instatiate $form
somehow in this view, but it's NOT an option to use another ActiveForm::begin()
/ ActiveForm::end()
anywhere inside this view since it will create another <form>
tag and thus when I inject the Ajax response, I'll end up with with a <form>
inside a <form>
...
Now, my question is as follows: Since I want to use ActiveForm
, how can I share an instance of the ActiveForm
through out multiple requests?
Is it doable / possible, if so, please help me realize how?
So far I have tried to put $form
inside a session, but that's definitelly not working and not an option. Different than that, I've tried when passing parameters to renderAjax
:
[
'model' => $model,
'form' => new ActiveForm,
]
In this case I get the following:
- Form fields are created as they should with appopriate names and id's.
- jQuery is loaded again (at the bottom of the response:
<script src="...">
... you get the idea) - I don't get the generated JavaScript for validation.
Is there anyway to share an instance of $form
?