Button onclick JsExpression, which contains PHP

Hello Yii community,

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:


$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; ?>\";




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!

There is a register function you can use

$this->registerJs(" your is code ");

There are a few yii2 tabular input plugins that allow multiple model instances in the same form that work pretty well.

I finally managed to solve this, it was a problem with some characters of PHP’s html generated code. If I do:

$formField = $form->field($model, 'elements[]', []);

$formField = str_replace(["\r\n", "\n", "\r"], ' ', $formField);

$formField = str_replace(["\""], '\'', $formField);

$this->registerJs('var addField = function(field) {

    form = document.getElementById(\'my-form\');

    form.innerHTML += field;

};', View::POS_HEAD);

echo Html::button(

    'Add keyword',


        'id' => 'myButton',

        'class' => 'btn btn-primary',

        'onclick' => 'addField("' . $formField . '")',



…works perfectly.