From 807241b991d6f0e4f4c079ea2957751ed259d1be Mon Sep 17 00:00:00 2001 From: Ankit Agarwal Date: Fri, 17 Jan 2014 13:42:47 +0800 Subject: [PATCH] MDL-44059 libraries: Add a method to return html for row instead of just printing it --- lib/tablelib.php | 22 ++++++++++++++++++---- lib/tests/tablelib_test.php | 14 ++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/lib/tablelib.php b/lib/tablelib.php index 4e0058ce058..1c296773f56 100644 --- a/lib/tablelib.php +++ b/lib/tablelib.php @@ -980,6 +980,18 @@ class flexible_table { * This function is not part of the public api. */ function print_row($row, $classname = '') { + echo $this->get_row_html($row, $classname); + } + + /** + * Generate html code for the passed row. + * + * @param array $row Row data. + * @param string $classname classes to add. + * + * @return string $html html code for the row passed. + */ + public function get_row_html($row, $classname = '') { static $suppress_lastrow = NULL; $oddeven = $this->currentrow % 2; $rowclasses = array('r' . $oddeven); @@ -989,13 +1001,14 @@ class flexible_table { } $rowid = $this->uniqueid . '_r' . $this->currentrow; + $html = ''; - echo html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid)); + $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid)); // If we have a separator, print it if ($row === NULL) { $colcount = count($this->columns); - echo html_writer::tag('td', html_writer::tag('div', '', + $html .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $colcount)); } else { @@ -1013,20 +1026,21 @@ class flexible_table { $content = ' '; } - echo html_writer::tag('td', $content, array( + $html .= html_writer::tag('td', $content, array( 'class' => 'cell c' . $index . $this->column_class[$column], 'id' => $rowid . '_c' . $index, 'style' => $this->make_styles_string($this->column_style[$column]))); } } - echo html_writer::end_tag('tr'); + $html .= html_writer::end_tag('tr'); $suppress_enabled = array_sum($this->column_suppress); if ($suppress_enabled) { $suppress_lastrow = $row; } $this->currentrow++; + return $html; } /** diff --git a/lib/tests/tablelib_test.php b/lib/tests/tablelib_test.php index 46a317eb193..033b3d6a809 100644 --- a/lib/tests/tablelib_test.php +++ b/lib/tests/tablelib_test.php @@ -323,4 +323,18 @@ class core_tablelib_testcase extends basic_testcase { 10 ); } + + public function test_get_row_html() { + $data = $this->generate_data(1, 5); + $columns = $this->generate_columns(5); + $headers = $this->generate_headers(5); + $data = array_keys(array_flip($data[0])); + + $table = new flexible_table('tablelib_test'); + $table->define_columns($columns); + $table->define_headers($headers); + $table->define_baseurl('/invalid.php'); + $row = $table->get_row_html($data); + $this->assertRegExp('/row 0 col 0/', $row); + } }