Welcome Guest, Not a member yet? Register   Sign In
Right justify numeric fields in table display
#1

[eluser]andycorpes[/eluser]
Hi Group,

I'm using the HTML table helper to create a table from a databaswe result. I can't figure out how to make the numeric columns right justified. Is there anyway to do this using the table template? or have i got to add each cell individually and specify an id or class attribute for each cell?

Andy
#2

[eluser]Michael Wales[/eluser]
I wouldn't use the table helper honestly - I would just loop through each of the returned results, something like this:

Code:
<table>
&lt;?php foreach ($result as $row) { ?&gt;
  <tr><td>&lt;?= $row->column_1; ?&gt;</td>
      <td>&lt;?= $row->column_2; ?&gt;</td>
      <td>&lt;?= $row->column_3; ?&gt;</td></tr>
&lt;?php } ?&gt;
</table>

You could then easily apply an id or class to any of the columns and style them with CSS.

Or - if you want to be really ghetto with it, you could use CSS selectors (which may not be supported in all browsers) and setup an adjacent sibling selector:

Code:
tr > td + td + td {text-align:right;}

That would target and td, that follows a td, that follows a td, that is a child of a tr.
#3

[eluser]Phil Sturgeon[/eluser]
Code:
<table>
&lt;?php foreach ($result as $row) { ?&gt;
  <tr><td>&lt;?='<div style="text-align:'.(is_numeric($row->column_1) ? 'right' : 'left').'">'.$row->column_1.'</div>'; ?&gt;</td>

      <td>&lt;?='<div style="text-align:'.(is_numeric($row->column_2) ? 'right' : 'left').'">'.$row->column_2.'</div>'; ?&gt;</td>
      <td>&lt;?='<div style="text-align:'.(is_numeric($row->column_3) ? 'right' : 'left').'">'.$row->column_3.'</div>'; ?&gt;</td></tr>
&lt;?php } ?&gt;
</table>

Not the neatest solution, but works.
#4

[eluser]Derek Allard[/eluser]
Yeah, the problem with the table class is that it is really only good for uniform results (ie: database results) and lacks the flexibility that you'd need for these types of issues. I've been wanting to re-write that lib for a bit now Wink That said, would something like this work for you?
Code:
$this->load->library('table');

// set up table template here
// get some data here

foreach ($result->result() as $data) {
     $this->table->add_row(array($data->field1, $data->field2, '<div class="numberfield">' . $data->field3 . '</div>'));
}

echo $this->table->generate();
#5

[eluser]Phil Sturgeon[/eluser]
Combine my ternary statements with that code in your controller and thats a perfect solution.




Theme © iAndrew 2016 - Forum software by © MyBB