Passing data to the CButtonColumn click event

Site has moved

This site has moved to a new location. Visit the new site at http://programsdream.nl.

By Ronald van Belzen | July 20, 2013

One of the limitations of the click event of an CButtonColumn is that it does not take data from the CGridView. But passing row specific data to a Javascript on clicking the button is precisely what is needed in many cases.

The simplest workaround is to use jQuery to deliver the required data:

$this->widget('zii.widgets.grid.CGridView', array( 

  // omitted parameters

  'columns'=>array( 

    // omitted columns 

    array( 
      'class'=>'CButtonColumn', 
      'template'=>'{view}', 
      'buttons' => array( 
        'view' => array( 
          'url'=>'$data->id', 
          'click'=>'js:function() { viewPost($(this).attr("href"));return false; }', 
        ), 
      ) 
    ), 
  ), 
));

The trick is that the data is passed to the url and $(this).attr("href") passes it to the function called by the click event. Of course, the click event should return false to prevent the web browser from visiting the url. All navigation (if any) should be triggered by the Javascript in this solution.