Skip to content

Commit

Permalink
Added support for Tart_Table to export to csv format
Browse files Browse the repository at this point in the history
  • Loading branch information
Yasen Yanev committed Feb 21, 2014
1 parent f1be38b commit f55de78
Showing 1 changed file with 34 additions and 6 deletions.
40 changes: 34 additions & 6 deletions classes/Kohana/Tart/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ abstract class Kohana_Tart_Table extends Tart_Group {

protected $_footer;
protected $_attributes = array('class' => 'table table-striped table-hover');
function __construct($collection = array(), array $items = array())

function __construct($collection = array(), array $items = array())
{
$this->collection($collection);
$this->items($items);
Expand All @@ -27,7 +27,7 @@ public function attributes($key = NULL, $value = NULL)
{
if ($key === NULL)
return $this->_attributes;

if (is_array($key))
{
$this->_attributes = $key;
Expand All @@ -36,10 +36,10 @@ public function attributes($key = NULL, $value = NULL)
{
if ($value === NULL)
return Arr::get($this->_attributes, $key);

$this->_attributes[$key] = $value;
}

return $this;
}

Expand All @@ -65,7 +65,7 @@ public function render()
$h('input', array('type' => 'checkbox', 'name' => 'all', 'value' => '1', 'checked' => array_diff($self->collection()->ids(), $self->selected()) ? NULL : 'checked'));
});
}
foreach ($self->columns() as $column)
foreach ($self->columns() as $column)
{
$h('th', array('width' => $column->width()), $column->label());
}
Expand Down Expand Up @@ -98,6 +98,34 @@ public function render()
return $html->render();
}

public function to_csv()
{
if ( ! ($handle = fopen('php://output', 'w+')))
throw new Kohana_Exception('Cannot open php://output for writing');

ob_start();
fputcsv($handle, array_keys($this->columns()));

foreach ($this->collection() as $index => $item)
{
$values = array();
$index = 0;

foreach ($this->columns() as $column)
{
$values[] = Text::to_plain($column->index($index++)->item($item)->render());
}

fputcsv($handle, $values);
}

$csv = ob_get_contents();
ob_clean();
fclose($handle);

return $csv;
}

public function columns($name = NULL, $value = NULL)
{
return $this->items($name, $value);
Expand Down

0 comments on commit f55de78

Please sign in to comment.