Ascendro Blog

Displaying 1-1 of 1 result.

Dynamic buttons in a yii data grid

A.   Requirement

The requirement was that on a clicking a grid view column, the page would show the view of the respective record below the grid itself, without a refresh.

B.   Initial solution

We tried to solve the issue using CHtml::ajaxLink()

C.   Challenge

We discovered that the initial solution tried by us is binding the link to the respective row id, and using the pager, so clicking one of the links would bring the record details from the first grid page.

D.   Final solution

Luckily, Yii Framework does not restrict the developer to using its function, so we used a smart alternative solution:

1. Add a class to the links, and change the href attribute to go to the correct controller/action, with the corresponding parameter :

 

array(
            'name' => 'ajaxSingleViewColumn',
            'value' => 'CHtml::link($data->name, array("controller/view", "id" => $data->id), array("class" => "ajaxLoadLink"))',
            'type' => 'raw',
 ),

 

2. Below the grid, put an empty div with a specific id (entity-details for example)

3. Write a live handler for the click event :

 

$(".ajaxLoadLink").live('click', function (e) {
            e.preventDefault();
            $.post(
                $(this).attr('href'),
                function (data) {
                    $("# entity-details").html(data);
                }
            )
            return false;
        }) ;

 

Of course, the controller called by the link should check if the request was made using ajax, and return the rendered partial:

if(Yii::app()->request->isAjaxRequest) {
            return $this->renderPartial('view',  array(
                'model' => $this->loadModel($id)
            ));
        }

E.   Conclusion

This simple solution can be used whenever you have a project that requires listing and a simple detail view on the same page, especially since ajax loading is faster than a full page reload, and the user experience is better since the pager does not reset.

LEAVE A COMMENT

Displaying 1-1 of 1 result.

Michael says:

Thats the stuff which could take a day or thirty minutes - if you would have had the right idea!