php - 如何为 Codeigniter 表创建可排序表 THEAD 链接

标签 php codeigniter

我似乎无法让我的 thead th 链接能够整理我的数据。我尝试了很多不同的方法,现在不知道该怎么做。

例如 如果用户点击用户 ID thead 链接,它将按用户 ID 升序或降序等对用户进行排序。用户名相同,添加日期的链接。我已经尝试过使用外源脚本,但因为它是用 Controller 控制的,所以它不起作用。

使用我的代码

我想要实现的是用户列表表的头部区域有 5 个 thead 我想制作它所以当我点击其中一个时它会根据那个整理列表按 asc 和 or 或 dsc 排列的字段。试图让它与当前分页一起工作,分页工作正常

一些库是自动加载的。

Codeigniter 用户 Controller

protected function getList() {
    $data['heading_title'] = $this->lang->line('heading_title');

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

    $data['breadcrumbs'][] = array(
        'text' => '<i class="fa fa-home"></i>' .' '.  $this->lang->line('text_home'),
        'href' => site_url('admin/dashboard')
    );

    $data['breadcrumbs'][] = array(
        'text'      => $this->lang->line('heading_title'),
        'href'      => site_url('admin/users')
    );

    $data['text_enabled'] = $this->lang->line('text_enabled');
    $data['text_disabled'] = $this->lang->line('text_disabled');

    $data['column_user_id'] = $this->lang->line('column_user_id');
    $data['column_name'] = $this->lang->line('column_name');
    $data['column_status'] = $this->lang->line('column_status');
    $data['column_last_updated'] = $this->lang->line('column_last_updated');
    $data['column_date_added'] = $this->lang->line('column_date_added');
    $data['column_action'] = $this->lang->line('column_action');

    $data['delete'] = site_url('admin/users/delete');
    $data['insert'] = site_url('admin/users/add');

    $data['text_confirm'] = $this->lang->line('text_confirm');

    $data['button_insert'] = $this->lang->line('button_insert');
    $data['button_edit'] = $this->lang->line('button_edit');
    $data['button_delete'] = $this->lang->line('button_delete');

    $this->load->library('setting'); 

    $this->load->library('pagination'); 

    $config = array(); 
    $config["base_url"] = base_url('admin/users'); 
    $config['total_rows'] = $this->db->get('user')->num_rows(); 
    $config["per_page"] =  $this->setting->get('config_limit_admin');
    $config["uri_segment"] = 3;  

    $config['full_tag_open'] = "<ul class='pagination'>";
    $config['full_tag_close'] ="</ul>";
    $config['num_tag_open'] = '<li>';
    $config['num_tag_close'] = '</li>';
    $config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
    $config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
    $config['next_tag_open'] = "<li>";
    $config['next_tagl_close'] = "</li>";
    $config['prev_tag_open'] = "<li>";
    $config['prev_tagl_close'] = "</li>";
    $config['first_tag_open'] = "<li>";
    $config['first_tagl_close'] = "</li>";
    $config['last_tag_open'] = "<li>";
    $config['last_tagl_close'] = "</li>";

    $this->pagination->initialize($config);

    $data['users'] = $this->db->get('user', $config["per_page"], $this->uri->segment(3));

    if (isset($this->request->post['selected'])) {
        $data['selected'] = (array)$this->request->post['selected'];
    } else {
        $data['selected'] = array();
    }

    return $this->load->view('user/users_list', $data);
}

查看

<form action="<?php echo $delete; ?>" method="post" enctype="multipart/form-data" id="form-user">

<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<td style="width: 1px;" class="text-center"><input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" /></td>
<td class="text-center" style="color: #1E91CF; font-size: 14px; font-weight: bold;"><?php echo $column_user_id; ?></td>
<td class="text-center" style="color: #1E91CF; font-size: 14px; font-weight: bold;"><?php echo $column_name; ?></td>
<td class="text-center" style="color: #1E91CF; font-size: 14px; font-weight: bold;"><?php echo $column_status; ?></td>
<td class="text-center" style="color: #1E91CF; font-size: 14px; font-weight: bold;"><?php echo $column_last_updated; ?></td>
<td class="text-center" style="color: #1E91CF; font-size: 14px; font-weight: bold;"><?php echo $column_date_added; ?></td>
<td class="text-center" style="color: #1E91CF; font-size: 14px; font-weight: bold;"><?php echo $column_action; ?></td>
</tr>
</thead>
<tbody>
<?php foreach ($users->result() as $user) { ?>  
<td class="text-center"><?php if (in_array($user->user_id, $selected)) { ?>
<input type="checkbox" name="selected[]" value="<?php echo $user->user_id; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" value="<?php echo $user->user_id ?>" />
<?php } ?>
</td>
<td class="text-center"><?php echo $user->user_id; ?></td>
<td class="text-center"><?php echo $user->username; ?></td>
<td class="text-center"><?php if ($user->status == TRUE) { echo $text_enabled; } else { echo $text_disabled ; } ?></td>
<td class="text-center"><?php echo $user->last_updated; ?></td>
<td class="text-center"><?php echo $user->date_added; ?></td>
<td class="text-center"><?php echo anchor("admin/users/edit/" . $user->user_id, '<div class="btn btn-primary text-right" role="button"><i class="fa fa-pencil"></i>
 Edit</div>');?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="row">
<div class="col-sm-6 text-left">
<?php echo $this->pagination->create_links();?>
</div>
</div>
</form>

模型获取用户

public function getUsers() {
  $this->db->select('*');
  $this->db->from($this->db->dbprefix . 'user');
  $query = $this->db->get();

  if ($query->num_rows() > 0) {
      return $query->result();
      return true;
  } else {
      return false;
  }
}

最佳答案

好的,让我们排序和分页吧!

首先,分页是如何工作的

当你分页时,你说:

"There are (let's say) 25 elements. I want to show page 2, so, if I'm (let's say) showing 5 elements per page, I have to order them and then show from element 6 to 10"

这样,如果你想显示第 3 页,你将按(比方说)id 排序,然后从元素 11 到 15 显示。总结一下,你必须知道:

  • 你展示了多少元素
  • 您要列出的页面(稍后您将转换为偏移量,继续阅读)
  • 您用于列出的顺序。

示例:我将使用下表,将其插入 DDBB 并运行查询以了解我的意思:

CREATE TABLE IF NOT EXISTS `elements` (
  `id` int(11) DEFAULT NULL,
  `letter` char(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `elements` (`id`, `letter`) VALUES
    (10, 'a'),(9, 'b'),(8, 'c'),(7, 'd'),   (6, 'e'),   (5, 'f'),   (4, 'g'),   (3, 'h'),   (2, 'i'),   (1, 'j');

现在,让我们分页!

假设您要显示第 3 页,每页 2 个元素,按上升 id 排序。您必须显示 ID 为 5 和 6 的元素,因为第 1 页的 ID 为 1 和 2,而第 2 页的 ID 为 3 和 4。因此,我们的偏移量将是:

$offset = ($elements_per_page) * ($page – 1);
// In this example: $offset = 2 * (3 – 1 ) = 4.

要知道,要按 id 排序并显示您必须运行的页面中的元素:

SELECT *
FROM elements
ORDER BY id ASC
LIMIT 4, 2

您将按以下顺序得到:(5,'f') 和 (6, 'e')

如果你想通过信件订购它们,你会运行

SELECT *
FROM elements
ORDER BY letter ASC
LIMIT 4, 2

wich 按以下顺序为您提供:(6, 'e') 和 (5, 'f')

说明:limit 子句允许您指定偏移量和要显示的元素数。

From http://dev.mysql.com/doc/refman/5.0/en/select.html, "With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1)"

好了,现在,您知道必须如何构建查询,那么,让我们使用 CI 来构建它。

使用 CI 构建分页

您的模型需要知道您要显示的内容:顺序、您要显示的页面以及元素的数量,因此,它必须是这样的:

MODEL users_model.php

public function getUsers( $offset, $elements_per_page, $order_field, $order_direction ) 
{    
    $this->db->select('*');
    $this->db->from($this->db->dbprefix . 'user');

    $this->db->order_by( $order_field, $order_direction )

    // Be careful, the order is differente here than in real MySQL query LIMIT: LIMIT $OFFSET, $ELEMENTS_PER_PAGE
    $this->db->limit($elements_per_page, $offset );  


    $query = $this->db->get();

    if ($query->num_rows() > 0) {
        return $query->result();
    } else {
        // This just to keep allways the same kind of data returned, ;D
        return array();
    }
}

// We'll use this to know how many users there are.
public function countUsers() 
{
    return $this->db->count_all_results( $this->db->dbprefix . 'user' );
}

使用上面的代码,您有一个模型类基础,可以开始将值从数据库发送到 Controller ,但您还必须使用 Controller 。它必须处理页面以确保您在范围内,以确保您要排序的值是它真正存在的字段......好吧, Controller 工作,你知道吗?

Controller :users.php

public function user_results()
{
    // To control the page you're sending is ok, you have to count first the number of elements
    $page   = $this->input->get( $page );

    $elements_per_page  = 3; // You could also send it in your request

    $this->load->model('users_model');  
    $total      = $this->users_model->countUsers();
    $get_offset =  ( $page – 1 ) * $elements_per_page;
    // And you have to control the offset:
    $min_offset = 0; 
    $max_offset = floor( $total / $elements_per_page ); 
    $offset = ( ( get_offset > $max_offset ) ? $max_offset : ( ( $get_offset < $min_offset ) ? $min_offset : $get_offset ) ); 

    // Then, you have to control the fields to order. I'd recommend you white list filter:
    $get_order_field    = $this->input->get('order_field');
    $order_fields   = array( 'id', 'letter');
    $order_field    = in_array( $get_order_field, $order_fields ) ? $get_order_field : 'id';

    $get_order_direction    = $this->input->get('order_direction');
    $order_directions   = array( 'asc', 'desc');
    $order_field        = in_array( $get_order_direction, $order_directions ) ? $get_order_direction : 'asc';

    // And now, you can show a list of the elements you want to show from the page:       
    $data['users'] = $this->users_model->getUsers( $offset, $elements_per_page, $order_field, $order_direction );

    $this->load->view('table_users_view', $data );
}

为了完成后端,我将所有表值放在一个 View 中:

View :table_users_view.php

<table>
  <tr>
    <th>Id</th>
    <th>Name</th>
  </tr>
  <?php if ( !empty( $users ) : ?>
      <?php foreach ( $users as $user ) : ?> 
  <tr>
    <td><?=$user->id?></td>
    <td><?=$user->name?></td>   
  </tr>
      <?php endforeach; ?> 
  <?php endif; ?>
</table>

好吧,这是开始回答您的问题。现在您可以分页了,但需要自动添加分页链接,看起来像 BASE_URL/users/?page=1&order_field=id&order_direction=asc。而且,您必须在 JS 中编写一个通过 html 中的 anchor 触发的 AJAX 调用。如果您理解以上所有代码,接下来的步骤是:

  • 在表格的标题中编写一个带有 anchor 的 AJAX 调用。
  • 根据所选页面的值和这些值重新加载内容:为此,您需要一个 Controller 方法,该方法采用 AJAX 参数并向您返回 tbody,而不是整个表格。

或多或少:

$(document).ready(function({
    $('.order').click( function(){
        var field = $(this).data('field');
        var dir   = $(this).data('dir');       
        var page  = $('.pagination active').data('page');
        $.ajax({
            type: 'get',
            dataType: 'json'
            url:  BASE_URL + 'users/ajax/?page=' + page + '&order_direction=' + dir + '&order_field=' + field,
            success: function(data) {
                $('table.users tbody').html(data.tbody);
            }
        });
    })   
});

您的 View 应更改为:

<div class="pagination">
    <span class="active" data="1">1</span>
    <span data="2">2</span>
    <span data="3">3</span>
</div>

<table>
  <tr>
    <th>
      <span class="order" data-field="id" data-dir="asc">Up</span>
      <span class="order" data-field="id" data-dir="desc">Down</span>
      ID
    </th>
    <th>
      <span class="order" data-field="name" data-dir="asc">Up</span>
      <span class="order" data-field="name" data-dir="desc">Down</span>
      Name
    </th>
  </tr>
  <tbody>
  <?php if ( !empty( $users ) : ?>
      <?php foreach ( $users as $user ) : ?> 
  <tr>
    <td><?=$user->id?></td>
    <td><?=$user->name?></td>   
  </tr>
      <?php endforeach; ?> 
  <?php endif; ?>
  </tbody>
</table>

并且您将需要一个“局部 View ”来仅加载 tbody 的数据:

View :table_users_partial_view.php

      <?php if ( !empty( $users ) : ?>
          <?php foreach ( $users as $user ) : ?> 
      <tr>
        <td><?=$user->id?></td>
        <td><?=$user->name?></td>   
      </tr>
          <?php endforeach; ?> 
      <?php endif; ?>

如果您要发送 AJAX 请求,则必须修改您的 Controller 以显示部分 View :

CONTROLLER:已修改为仅返回部分数据:

public function user_results()
{
    // To control the page you're sending is ok, you have to count first the number of elements
    $page  = $this->input->get( $page );

    $elements_per_page = 3; // You could also send it in your request

    $get_offset    =  ( $page – 1 ) * $elements_per_page;
    // And you have to control the offset:
    $min_offset    = 0; 
    $max_offset    = floor( $total / $elements_per_page ); 
    $offset    = ( ( get_offset > $max_offset ) ? $max_offset : ( ( $get_offset < $min_offset ) ? $min_offset : $get_offset ) ); 

    // Then, you have to control the fields to order. I'd recommend you white list filter:
    $get_order_field   = $this->input->get('order_field');
    $order_fields  = array( 'id', 'letter');
    $order_field   = in_array( $get_order_field, $order_fields ) ? $get_order_field : 'id';

    $get_order_direction   = $this->input->get('order_direction');
    $order_directions  = array( 'asc', 'desc');
    $order_field       = in_array( $get_order_direction, $order_directions ) ? $get_order_direction : 'asc';

    // And now, you can show a list of the elements you want to show from the page:
    $this->load->model('users_model');

    $data['users'] = $this->users_model->getUsers( $offset, $elements_per_page, $order_field, $order_direction );
    if ( !$this->input->is_ajax_request() ) {
        $this->load->view('table_users_view', $data );
    } else {
        $return = array( 
            'tbody' => $this->load->view('table_users_partial_view
        );  
        // This is to give back the value as a JSON the JS will understand. In fact, in the AJAX call we indicated it.
        echo json_encode( $return );
    }
}

免责声明:只有从头开始的 SQL 是经过测试的代码,如果只是复制/粘贴,以上所有内容都可能或无法正常工作。该代码用于澄清并为您提供遵循的路径:您必须先理解,然后再编写代码。以上就是写的希望对大家有用,有什么不明白的可以留言。祝您编码愉快!

关于php - 如何为 Codeigniter 表创建可排序表 THEAD 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26448106/

相关文章:

javascript - &lt;script&gt; 标签显示在 ajax 响应中并执行?

php - 无法从 codeigniter paypal 库获得 curl 响应

mysql - codeigniter , mysql查询性能问题

php - 批量插入后检索 ID

php - 使用 datagrid 、 flash 、 php 、 mysql 、 as3 显示数据库中的数据

php - 如何在cakephp中连接三个表,其中一个是HABTM表

javascript - 如何使用javascript计算表格的行数

php - 使用 PHPExcel 和 AJAX 制作 Excel 文件

php - CodeIgniter:动态登录后重定向?

php - 尝试从命令行运行 cURL(xampp/windows 环境)