Create Cgridview With Dynamic Columns

Hello all,

This seems like it should be easy, but I’m not understanding how to do this.

I have a view that has a variable number of columns depending on the query criteria. I want to just display all columns in a CGridView (actually, I just need them to download to Excel spreadsheet.)

I have tried variations of using CArrayDataProvider and CSqlDataProvider. The query itself is very simple. Just




        $results = Yii::app()->db->createCommand()

                ->select()

                ->from('v_reservation_report')

                ->where('event_id=:event_id', array(':event_id'=>$event_id))

                ->queryAll();

       

it is returning all columns, but since I don’t know the column names in advance, I don’t know how to configure gridview. I tried using the getColumns() method to get the columns from the table, but I was unable to assign that array to the CGridView.

Does anyone have an example of an implementation like this?

I’ll try to put some code I was working with together and update this post with more information.

Hi JCJ,

Try this. If $results is based on a CActiveDataProvider, you can access the table schema and get an array of columns with this line of code…




$results->data[0]->tableSchema->columns;



With that, you can then loop through the columns and build an array for CGridView like this…




$columns = array();

foreach ($results->data[0]->tableSchema->columns as $column=>$columnSchema)

{

	$columns[] = $column;

}



Lastly, use $columns as your array for CGridView…




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

		'id'=>'my-grid',

		'dataProvider'=>$results,

		'columns'=>$columns,

	));

	



This should work fine, but you’ll be limited in how you can customise each column. If you do need to customise the columns, you will be able to tap in to the data that is in the $columnSchema object (below var_dump shows the first column in my $results->data[0]->tableSchema->columns example array)…




array

  'id' => 

    object(CMysqlColumnSchema)[259]

      public 'name' => string 'id' (length=2)

      public 'rawName' => string '`id`' (length=4)

      public 'allowNull' => boolean false

      public 'dbType' => string 'int(11)' (length=7)

      public 'type' => string 'integer' (length=7)

      public 'defaultValue' => null

      public 'size' => int 11

      public 'precision' => int 11

      public 'scale' => null

      public 'isPrimaryKey' => boolean true

      public 'isForeignKey' => boolean false

      public 'autoIncrement' => boolean true

      public 'comment' => string '' (length=0)

      private '_e' (CComponent) => null

      private '_m' (CComponent) => null