custom sql query results to CDetailView

This is a bried guide about displaying of custom sql query results.

The result of the query will display on CDetailView widget

Remember that the query have to returns only one row. In any case the code takes into only the first row-result

  • Prepare and execute the sql query
$connection = Yii::app()->db;
$command = $connection->createCommand('select * from your_table');
$row = $command->queryRow(); //executes the SQL statement and returns the first row of the result.

  • Convert the results to the appropriate for CDetailView format
$res = array();
    foreach ($row as $key=>$val) {
        $res[] = array('label'=>$key,'value'=>$val);
    }
  • Display the data
$this->widget('zii.widgets.CDetailView', array(
'data' => array(), //to avoid error
'attributes' => $res,
));

Notes:

  • If you want to change the name of the displayed columns you could either set alias on sql query
$command = $connection->createCommand('select col_1 as 'my name column',col_2 as 'my name column2' ... from your_table');

or make a match (with mapping array) in foreach loop.

  • If you not sure about the purity of the data you have to use
$res[] = array('label'=>$key,'value'=>CHtml::encode($val));

I show you now how to make the similar task using other Providers

With CSqlDataProvider

$sqlProvider = new CSqlDataProvider('select * from your_table');
$sqlProvider = $sqlProvider->getData();
$sqlData = $sqlProvider[0];

$this->widget('zii.widgets.CDetailView', array(
    'data' => $sqlData,
));

With CArrayDataProvider

$connection = Yii::app()->db;
$command = $connection->createCommand('select * from your_table');
$row = $command->queryRow();

$sqlData = new CArrayDataProvider(array($row));
$sqlData = $sqlData->getData();
$sqlData = $sqlData[0];
$this->widget('zii.widgets.CDetailView', array(
    'data' => $sqlData,
));