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

  1. Problem Statement
  2. Reasoning
  3. Solution

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?


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.


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) {
       url: '/path/to/action',
       data: {id: '<id>', 'other': '<other>'},
       success: function(data) {
           // process data
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default), 
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END