0

In my view I have an array that I can reach by doing:

$model->stabilimenti;

Now in the same View, in registerJS I'm trying to save this array in a Javascript array, so I can add some clientside checks.

<?php
$this->registerJs(<<<JS
    jQuery(document).ready(function(){

    let jsArray = [];
    jsArray = $model->stabilimenti;

JS
);

With non-array variables this kind of approach works.

I've also tried to use this notation but without any success.

let jsArray = <?php echo json_encode($model->stabilimenti); ?>;

Is this a lecit operation ?

1

1 Answer 1

1

You are missing the closing braces and parenthesis }) of the .ready(function(){ function if that is not a typo pasting the code here.

You should parse the php array to javascript staying in php using yii\helpers\JSON or json_encode on the array $model->stabilimenti and convert it to json and then assign it to the javascript variable. and try loading the code at DOM ready, by using \yii\web\View::POS_READY when registering your script.

And you should keep the code separate from each other. See the below code it should work correctly

<?php
$stabilimenti = \yii\helpers\Json::encode($model->stabilimenti);

$js = <<<JS
jQuery(document).ready(function(){
    let jsArray = {$stabilimenti};
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.