I want to submit a form whose field is an array of an unknown number of elements.
class DynamicForm extends Model
{
/** var string[] */
public elements[];
}
Inside the view that there is the form submission, I want to add a button which has an 'onclick' Javascript function, which adds a new field in the form innerHtml. Unfortunately, I can't find a way to embed some PHP code inside my javascript expression. Here is where I am right now:
<?php
$form = ActiveForm::begin([
'id' => 'test-form',
'layout' => 'horizontal',
'fieldConfig' => [
'errorOptions' => [
'role' => 'alert',
],
'horizontalCssClasses' => [
'label' => 'col-sm-3',
'offset' => 'col-sm-offset-3',
'wrapper' => 'col-sm-9',
'error' => '',
'hint' => '',
],
],
]);
$formField = $form->field($model, 'elements[]', []);
$JsFunction = new \yii\web\JsExpression(
"function addField() {
document.getElementById(\"test-form\").innerHTML += \"<?php echo $formField; ?>\";
};
addField();"
);
echo Html::button(
'Add element',
[
'class' => 'btn btn-primary',
'onclick' => $JsFunction,
]
);
?>
Strange thing is that, if I put inside the innerHTML a string like "<p>hello!</p>"
, it works perfectly. Another strange thing is that, if I put the HTML code that the 'php echo' command generates,
'<input type=\"text\" id=\"dynamicform-elements\" class=\"form-control\" name=\"DynamicForm[elements][]\">'
it still works!
Although I think that entering manual HTML code for Yii::ActiveForm
is not a really good practice, that's why I want the PHP to do the job for it.
Thank you in advance!