添加自定义字段 jQuery 数据表

Posted

技术标签:

【中文标题】添加自定义字段 jQuery 数据表【英文标题】:Adding custom field jQuery Datatables 【发布时间】:2015-12-30 14:26:09 【问题描述】:

我正在使用 jQuery 数据表来填充我的数据。我正在使用我需要的服务器端方法,因为我正在获取十万条记录。但是我不知道如何添加自定义字段。例如

|Action|
________
http://localhost/qms/public/customer/1/edit

1 应该是哪个 ID

因为在数据表上,你只声明了你需要的列表,所以我不知道如何添加自定义的。

我目前有这个:

我需要放置操作列来编辑这些客户。我正在使用 Laravel 5.1

html 视图:

<table id="CustomerList" class="table table-striped table-bordered" cellspacing="0" >
    <thead>
        <tr>
            <th colspan="7"> <center>Customer Information<center></th>
            <!-- <th colspan="2"> <center>Actions<center></th> -->
        </tr>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Gender</th>
            <th>Phone Number</th>
            <th>Country</th>
            <th>Postcode</th>
        <!--     <th>Edit</th>
            <th>Delete</th> -->
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

阿贾克斯:

<script type="text/javascript">
    $(document).ready(function() 
        $.fn.dataTable.ext.legacy.ajax = true;
        $('#CustomerList').DataTable( 
            "processing": true,
            "serverSide": true,
            "ajax": "api/customer/all",
            "paging" : true,
            "searching" : true,
            "ordering" :  true,
         );
        var tt = new $.fn.dataTable.TableTools( $('#CustomerList').DataTable() );
        $( tt.fnContainer() ).insertBefore('div.dataTables_wrapper');
    );
</script>

控制器:

public function apiGetCustomers()

    /*=================================================================*/
    /*
     * Script:    DataTables server-side script for php and PostgreSQL
     * Copyright: 2010 - Allan Jardine
     * License:   GPL v2 or BSD (3-point)
     */

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * Easy set variables
     */

    /* Array of database columns which should be read and sent back to DataTables. Use a space where
     * you want to insert a non-database field (for example a counter or static image)
     */
    $aColumns = array('id', 'firstname', 'lastname', 'gender', 'phone_num', 'country', 'postcode' );

    /* Indexed column (used for fast and accurate table cardinality) */
    $sIndexColumn = "phone_num";

    /* DB table to use */
    $sTable = "customers";

    /* Database connection information */
    $gaSql['user']       = "postgres";
    $gaSql['password']   = "postgres";
    $gaSql['db']         = "qms";
    $gaSql['server']     = "localhost";



    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * If you just want to use the basic configuration for DataTables with PHP server-side, there is
     * no need to edit below this line
     */

    /*
     * DB connection
     */
    $gaSql['link'] = pg_connect(
        " host=".$gaSql['server'].
        " dbname=".$gaSql['db'].
        " user=".$gaSql['user'].
        " password=".$gaSql['password']
    ) or die('Could not connect: ' . pg_last_error());


    /*
     * Paging
     */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    
        $sLimit = "LIMIT ".intval( $_GET['iDisplayLength'] )." OFFSET ".
            intval( $_GET['iDisplayStart'] );
    


    /*
     * Ordering
     */
    if ( isset( $_GET['iSortCol_0'] ) )
    
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
            
                $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                    ".($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc').", ";
            
        

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
        
            $sOrder = "";
        
    

    /*
     * Filtering
     * NOTE This assumes that the field that is being searched on is a string typed field (ie. one
     * on which ILIKE can be used). Boolean fields etc will need a modification here.
     */
    $sWhere = "";
    if ( $_GET['sSearch'] != "" )
    
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        
            if ( $_GET['bSearchable_'.$i] == "true" )
            
                if($aColumns[$i] != 'id') // Exclude ID for filtering
                
                    $sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string( $_GET['sSearch'] )."%' OR ";
                
            
        
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ")";
    

    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    
        if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
        
            if ( $sWhere == "" )
            
                $sWhere = "WHERE ";
            
            else
            
                $sWhere .= " AND ";
            
            $sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string($_GET['sSearch_'.$i])."%' ";
        
    


    $sQuery = "
        SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";

    $rResult = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());

    $sQuery = "
        SELECT $sIndexColumn
        FROM   $sTable
    ";
    $rResultTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
    $iTotal = pg_num_rows($rResultTotal);
    pg_free_result( $rResultTotal );

    if ( $sWhere != "" )
    
        $sQuery = "
            SELECT $sIndexColumn
            FROM   $sTable
            $sWhere
        ";
        $rResultFilterTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
        $iFilteredTotal = pg_num_rows($rResultFilterTotal);
        pg_free_result( $rResultFilterTotal );
    
    else
    
        $iFilteredTotal = $iTotal;
    

    /*
     * Output
     */
    $output = array(
        "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    while ( $aRow = pg_fetch_array($rResult, null, PGSQL_ASSOC) )
    
        $row = array();
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        
            if ( $aColumns[$i] == "version" )
            
                /* Special output formatting for 'version' column */
                $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
            
            else if ( $aColumns[$i] != ' ' )
            
                /* General output */
                $row[] = $aRow[ $aColumns[$i] ];
            
        
        $output['aaData'][] = $row;
    

    echo json_encode( $output );

    // Free resultset
    pg_free_result( $rResult );

    // Closing connection
    pg_close( $gaSql['link'] );



【问题讨论】:

提示:从问题中删除数据库的用户名和密码 【参考方案1】:

    为自定义字段添加标题,就像上面的&lt;th&gt;Edit&lt;/th&gt;&lt;th&gt;Delete&lt;/th&gt;

    使用column rendering 添加自定义字段的内容。由于您使用“数组数组”作为数据源,因此您必须这样做:

小示范 -> http://jsfiddle.net/pqgynvys/

var table = $('#example').DataTable(
    data : data.data,
    columns : [
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        render : function() 
             return '<button>edit</button>'
         
       , 
        render : function() 
             return '<button>delete</button>'
         
        
  ]   
)  

【讨论】:

感谢您的回复。我会先更新这个@Gyrocode.com 的答案,我发现它更简单。不过谢谢!【参考方案2】:

解决方案

在 HTML 中,在 Action 的表头中添加一列。

在 DataTables 初始化选项中,将 columnDefs 添加到第 8 列("targets": 7,从零开始的索引)并使用 render 选项为该列生成内容。

render 函数中,您可以使用row 变量来访问该行的数据。由于您在 PHP 脚本中返回数组数组,因此您可以使用 row[0](1st 列,从零开始的索引)访问您的 ID。

var table = $('#CustomerList').DataTable( 
   "processing": true,
   "serverSide": true,
   "ajax": "api/customer/all"
   "columnDefs": [
         
            "targets": 7,
            "render": function(data, type, row, meta)
               return '<a href="/qms/public/customer/' + row[0] + '/edit">Edit</a>';  
            
                    
    ]        
);

演示

有关代码和演示,请参阅 this jsFiddle。

【讨论】:

以上是关于添加自定义字段 jQuery 数据表的主要内容,如果未能解决你的问题,请参考以下文章

根据 WooCommerce 中的自定义字段值将文本添加到订单摘要

SAP B1 BOM中添加自定义字段 真就无解了么

MySQL可以查询自定义字段

如何在 django 模型表单中添加自定义字段?

帝国CMS如何显示自定义字段

PCL:自定义点类型(合并PCL已有字段 | 添加新的字段)