在html表中创建链接

时间:2011-04-10 22:24:08

标签: php codeigniter html-table

我有以下代码来生成表

    $query = $this->search_employee->getAll($config['per_page'], $this->uri->segment(3));

    $this->table->set_heading('Name', 'Department');
    $tmp = array ( 'table_open'  => '<table border="0" cellpadding="2" cellspacing="1" width="70%">' );
    $this->table->set_template($tmp);

    $data['main_content'] = 'display_professors';
    $data['table'] = $this->table->generate($query);

我的问题是如何在Name列下的每一行下创建链接到view_employee / ID

的链接?

我正在使用codeigniter的table class

1 个答案:

答案 0 :(得分:2)

可能有更好的方法可以做到这一点,但我只是遍历查询行来创建表行:

if ($query->num_rows() > 0)
{
    foreach ($query->result() as $row)
    {
        $this->table->add_row(anchor('view_employee/ID/' . $row->employee_id, $row->employee_name), $row->employee_department);
    }
}

$data['table'] = $this->table->generate();

等...

<强>更新

根据你对这个答案的评论,我不知道这个方法如何将html放入模型中而不是你自己的例子。毕竟,您在视图中所做的任何一种方式都是<?= $table; ?>或类似的。

如果您绝对想要将两者分开,可以这样做:

$data['rows'] = array();    

if ($query->num_rows() > 0)
{
    foreach ($query->result() as $row)
    {
        $this_row = array();
        $this_row['link'] = site_url('view_employee/ID/' . $row->employee_id);
        $this_row['employee_name'] = $row->employee_name;
        $this_row['employee_department'] = $row->employee_department;

        $data['rows'][] = $this_row;
    }
}

然后在视图中:

<table border="0" cellpadding="2" cellspacing="1" width="70%">
  <tr>
    <th>Name</th>
    <th>Department</th>
  </tr>
<? foreach($rows as $row): ?>
  <tr>
    <td><a href="<?= $row['link']; ?>"><?= $row['employee_name']; ?></a></td>
    <td><?= $row['employee_department']; ?></td>
  </tr>
<? endforeach; ?>
</table>