Problem using CArrayDataProvider and CGridView when array does not have an 'id' field.

I have been trying to use CArrayDataProvider to format some array data to then display using the CGridView widget, however it does not seem to work unless there is a defined ‘id’ key in the array. This seems to me to be an unnecessary requirement, so I’m not sure if this is actually the case or I am missing something. As an example:

<?php $testArray1 = array(array(









	$testArray2 = array(array(









	$dataProvider1 = new CArrayDataProvider(

			$testArray1, array(



				'defaultOrder'=>array('user_id' => false),






	$dataProvider2 = new CArrayDataProvider(

			$testArray2, array(



				'defaultOrder'=>array('id' => false),






	$this->widget('zii.widgets.grid.CGridView',array('dataProvider' => $dataProvider1,));

	$this->widget('zii.widgets.grid.CGridView',array('dataProvider' => $dataProvider2,));


The two arrays are exactly the same except that the id fields are labeled differently (‘user_id’ vs ‘id’). The problem is that the array with the id field labeled ‘id’ will work (can be displayed by the widget CGridView), whereas that with the id field labeled ‘user_id’ gave me the following error:

PHP Error

Undefined index: id


087         else

088             return $this->rawData;

089     }


091     /**

092      * Fetches the data item keys from the persistent data storage.

093      * @return array list of data item keys.

094      */

095     protected function fetchKeys()

096     {

097         $keys=array();

098         foreach($this->getData() as $i=>$data)

[b]099             $keys[$i]=is_object($data) ? $data->{$this->keyField} : $data[$this->keyField];[/b]

100         return $keys;

101     }


103     /**

104      * Calculates the total number of data items.

105      * This method simply returns the number of elements in {@link rawData}.

106      * @return integer the total number of data items.

107      */

108     protected function calculateTotalItemCount()

109     {

110         return count($this->rawData);

111     }

Any ideas? I can’t think that it is a requirement to always have an ‘id’ field…

Set the keyField property when you initialize the dataprovider. See the ArrayDataProvider api for details.

Perfect! Thanks a lot.

Thanks a lot.

Hi, I have also worked in CArrayDataProvider.

If you are using following things then no need to required id field.


$dataProvider=new CArrayDataProvider($rawData);

Try this.


[color="#006400"]/* moved from Bug Discussions */[/color]