Yii Framework Forum

Export related data to excel in Yii 1.1.16


(Syl) #1

Hey guys. I am trying to export data to Excel using the function below:

public function exportToExcel(){
// filename for download
$filename = "UserGroups->" . date('Ymd') . ".xls";
$data = Yii::app()->session['data']->getData();
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach ($data as $row) {
if (!$flag) {
// display field/column names as first row
echo "userGroupID \t";
echo "userID \t";
echo "groupID \t";
echo "active \t";
echo "dateActivated \t";
echo "insertedBy \t";
echo "updatedBy \t";

echo "\n";
$flag = true;
}
echo $row->userGroupID . " \t";
echo $row->userID . " \t";
echo $row->groupID . " \t";
echo $row->active . " \t";
echo $row->dateActivated . " \t";
echo $row->insertedBy . " \t";
echo $row->updatedBy . " \t";
echo "\n";
}
Yii::app()->end();
}

The export is working fine but it picks data as it is from the model whereas I need to export related data; like username instead of userID, groupName instead of groupsID, e.t.c.
I have the following relations in my model.

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'user' => array(self::BELONGS_TO, 'Users', 'userID'),
        'group' => array(self::BELONGS_TO, 'Groups', 'groupID'),
        'active_' => array(self::BELONGS_TO, 'EntityStates', 'active'),
        'insertedBy_' => array(self::BELONGS_TO, 'Users', 'insertedBy'),
        'updatedBy_' => array(self::BELONGS_TO, 'Users', 'updatedBy'),
    );
}

Any ideas how I can achieve what I want??


(Alirz23) #2

you can access properties from related object like you would do it on an object for example

$this->user->username
$this->group->groupName

(Syl) #3

Works like charm. Thanks.


(Syl) #4

Replaced:

echo $row->userID . " \t";
echo $row->groupID . " \t";

With:

  echo $row->user->userName . " \t";
  echo $row->group->groupName . " \t";

And it works perfectly