Skip to content

Commit

Permalink
MVC - add exportCsv() to ApiControllerBase to easily stream recordset…
Browse files Browse the repository at this point in the history
…s as csv files to the client and add asRecordSet() to ArrayField to be able to use this easily.

Sometimes it's practical to be able to use tools like excel to modify data, in order to do this we need an import and an export option in the model.
The export seems to be quite easy, controllers and forms can easily use this with a construction like:

$this->exportCsv($mymodel->myarray->asRecordSet());

The import is likely a bit more challenging.
  • Loading branch information
AdSchellevis committed Feb 20, 2024
1 parent edf756e commit a8d1a84
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,34 @@ protected function searchRecordsetBase(
];
}

/**
* passtru recordset (key value store) as csv output
* @param array $records dataset to export (e.g. [['field' => 'value'], ['field' => 'value']])
*/
protected function exportCsv(
$records,
$headers = [
'Content-Type: text/csv', 'Content-Transfer-Encoding: binary', 'Pragma: no-cache', 'Expires: 0'
]
) {
$records = is_array($records) ? $records : [];
$stream = fopen('php://temp', 'rw+');
if (isset($records[0])) {
fputcsv($stream, array_keys($records[0]));
}
foreach ($records as $record) {
fputcsv($stream, $record);
}
fseek($stream, 0);
foreach ($headers as $header) {
header($header);
}
ob_end_flush();
rewind($stream);
fpassthru($stream);
fclose($stream);
}

/**
* passtru configd stream
* @param string $action configd action to perform
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,4 +264,26 @@ public function isFieldChanged()
}
return false;
}

/**
* @param bool $include_static include non importable static items
* @param array $exclude fieldnames to exclude
* @return array simple array set
*/
public function asRecordSet($include_static=false, $exclude = [])
{
$records = [];
$iterator = $include_static ? $this->iterateItems() : parent::iterateItems();
foreach ($iterator as $akey => $anode)
{
$record = [];
foreach ($anode->iterateItems() as $tag => $node) {
if (!in_array($tag, $exclude)) {
$record[$tag] = (string)$node;
}
}
$records[] = $record;
}
return $records;
}
}

0 comments on commit a8d1a84

Please sign in to comment.