In Yii 2.0.28, Gii generates views for a model, and specifically in view.php it inserts the following code:
Since this doesn’t seem to be needed in any of the other view files, and also removing it doesn’t seem to have any visible effect, I would like to ask: What does this do? And is it really necessary?
It includes yii.js useful for some functionality reporter here:
Without its registration many form features doesn’t work as expected…see CSFR implementation, for example.
Thanks for the reply. I’m sure it has good uses but my question is, what is the purpose of it in the context of the view file generated by Gii? From the Gii-generated CRUD view files, view.php is quite simple with just a DetailView widget and a couple buttons.
Moreover, I checked the debugger and yii.js is still loaded no matter if I remove that line, and everything looks fine.
Also, this line of code is not on the other more complex view files like index.php (with a GridView) or _form.php (with a form).
So I still want to ask, is it really necessary and what is it supposed to do in this particular file? I don’t feel comfortable with lines of codes that I don’t know their true purpose or maybe it’s a bug on the Gii generated code…
By the way, the link you shared with me says “This section has not been written yet.”.
Thank you for that link. I searched a lot but I couldn’t find the exact commit so I appreciate it.
That being said, again, removing that line of code doesn’t seem to have any effect. The delete button (as mentioned in that bug description) still works as intended. Does it break the delete button functionality for you if you remove that line?
Could it be that such bug was fixed somewhere else internally in the framework thus that line becoming legacy code in the Gii generator that is not needed anymore?
Check your layout view file (“views/layout/main.php”) and probably you’ll find the registration of “AppAsset”.
And in the “AppAsset” class you’ll see that “yii\web\YiiAsset” is required as a dependency.
public $depends = [
Thus “yii.js” will be loaded no matter whether you will register “yii\web\YiiAsset” in “view.php” or not, because it will be registered in the layout view file.
So, you won’t need “YiiAsset::register” in your “view”. But someone with a different layout may need it. Gii must register YiiAsset in “view”, because it can not assume that the user’s layout file always registers YiiAsset.
Hi @softark, thank you very much for your detailed response!
This explains everything clearly. Now I can safely remove it from the view since I register yii.js on the layout level, and also to avoid a potential waste of time trying to load it twice.
You don’t have to worry about it. The registering of an asset can be safely called multiple times without any harmful side effects. The loading of an asset will be just once even if it has been registered multiple times.