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(
'user_id'=>'1',
'name'=>'david',
),
array(
'user_id'=>'2',
'name'=>'andrew',
),
);
$testArray2 = array(array(
'id'=>'1',
'name'=>'david',
),
array(
'id'=>'2',
'name'=>'andrew',
),
);
$dataProvider1 = new CArrayDataProvider(
$testArray1, array(
'sort'=>array(
'attributes'=>array('user_id'),
'defaultOrder'=>array('user_id' => false),
),
'pagination'=>array(
'pageSize'=>10,
),
));
$dataProvider2 = new CArrayDataProvider(
$testArray2, array(
'sort'=>array(
'attributes'=>array('id'),
'defaultOrder'=>array('id' => false),
),
'pagination'=>array(
'pageSize'=>10,
),
));
$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
yii_root/framework/web/CArrayDataProvider.php(99)
087 else
088 return $this->rawData;
089 }
090
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 }
102
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…