Yii 2.0: Overcoming removal of client helpers (e.g. ajaxLink) and ClientScript in Yii 2.0

31 followers

Problem Statement

With Yii Framework 2.0, one of the many changes, that Yii 1.x developers will face is removal of all client helpers and revamp of the CClientScript functionality. For example no more CHtml::ajaxLink or Html::ajaxLink. How do you cater to such requirements in Yii 2.0?

Reasoning

One of the critical changes in Yii 2 framework design that you will notice versus Yii 1.x, is that Yii 2 focuses on moving the entire presentational layer to a new View object. With this change, the Yii 2 team has also eliminated most of the client related functionality embedded in PHP classes from the core framework. Thus it has made the code cleaner to use. Hence, helpers like ajaxLink are no more available. This helps you manage your client assets better, improves performance, and control them better.

Solution

You can easily create and combine all such client helpers for your need into separate JS files. Use the new AssetBundle and AssetManager functionality with the View object in Yii2, to manage these assets and how they are loaded.

Alternatively, inline assets (JS/CSS) can be registered at runtime from within the View. For example you can clearly simulate the ajaxLink feature using a inline javascript. Its however recommended if you can merge where possible, client code (JS/CSS) into separate JS/CSS files and loaded through the AssetBundle. Note there is no more need of a CClientScript anymore:

$script = <<< JS
$('#el').on('click', function(e) {
    $.ajax({
       url: '/path/to/action',
       data: {id: '<id>', 'other': '<other>'},
       success: function(data) {
           // process data
       }
    });
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default), 
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END

Total 1 comment

#18293 report it
chrisvoo at 2014/10/12 03:20pm
For javascript IDE support

Supposing you want to use a jquery plugin in your view, you can:

  • put all your CSS/JS file in app\assets\AppAsset;
  • create a js folder in the web folder (or in another location of your choice)
  • put in the previously created folder a js file for your view;
  • include the content of the file and register the javascript
$jsView = file_get_contents(Yii::getAlias('@webroot/js/myfile.js'));
$this->registerJs($jsView, View::POS_END);
  • (optional) you can use a naming convention for your js files: name them as <ID_CONTROLLER>_<ID_ACTION> and include it with:
$contrAction = Yii::$app->urlManager->parseRequest(Yii::$app->request)[0];
$contrAction = str_replace("/", "_", $contrAction);
$jsView = file_get_contents(Yii::getAlias('@webroot/js/'.$contrAction.".js"));

Leave a comment

Please to leave your comment.