[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 374
  • Last Modified:

Could you point how to use moment.min.js to be used in conjunction with datatables plugin?

Hi Experts


Accordingly with some researchs a way to correctly configure date(s) when using datatables is with moment.min.js

So, folowing the examples:

Considering a Codeigniter's helper outputs to the view.

Helper's code that forms datatable

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

if (!function_exists('datatables_padrao2'))
{


    function datatables($fields, $options, $search)
    {


        $order = $cont = 4;
        $order_type = "asc";

        if (isset($options['order']))
        {

            if (isset($options['order_type']) && $options['order_type'] == 'desc')
                $order_type = 'desc';

            foreach ($fields as $field => $label)
            {

                if ($options['order'] == $field)
                {
                    $order = $cont;
                }

                $cont++;
            }


        }

        $datatables = '
            <link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.bootstrap.css">
            <link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.plugins.css">

            <script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/jquery.dataTables.js"></script>
            <script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/dataTables.bootstrap.js"></script>
            
            <!-- Moment declaration -->
            <script src="' . base_url() . 'public/vendor/plugins/moment/moment.min.js"></script>
            
            ';

        if (!isset($options['id']))
            $options['id'] = 'datatables_ajax';

        if (!isset($options['search_submit']))
            $options['search_submit'] = '.search_submit';

        $datatables .= '

        <script type="text/javascript">

            $(document).ready(function(){

                  // Is here the correct place to declare ?
                  $.fn.dataTable.moment( "DD/MM/YYYY hh:mm");


                $("#pesquisar_groups_form").on("submit",function(){

                    // não submete pagina - dont reload
                    return false;

                });
                
                $(".clear_pesquisa").on("click",function(){

                    // $("#pesquisar_groups_form").trigger("reset");
                    redrawDataTables("");
                });

                redrawDataTables("");

                $("' . $options['search_submit'] . '").on("click", function (e) {

                    var table = "";
                    var where = {';


        if (isset($search['like']))
        {

            $datatables .= '"like" : {';

            $cont = 0;
            foreach ($search['like'] as $val)
            {

                if ($cont == 0)
                    $datatables .= '"' . $val . '" : $("#pesquisar_groups_form").find("#' . $val . '").val()';
                else
                    $datatables .= ',"' . $val . '" : $("#pesquisar_groups_form").find("#' . $val . '").val()';

                $cont++;

            }
            $datatables .= '}';


            if (isset($search['where']))
                $datatables .= ',';

        }

        if (isset($search['where']))
        {

            $datatables .= '"where" : {
                                ';

            $cont = 0;
            foreach ($search['where'] as $val)
            {

                if ($cont == 0)
                    $datatables .= '"' . $val . '" : $("#pesquisar_groups_form").find("#' . $val . '").val()
                                ';
                else
                    $datatables .= ',"' . $val . '" : $("#pesquisar_groups_form").find("#' . $val . '").val()
                                ';

                $cont++;

            }
            $datatables .= '}
                            ';
        }

        $datatables .= '}
                    ';

        $datatables .= '

                    redrawDataTables(where);
                });
            });

            function redrawDataTables(where) {



                if (typeof table != "undefined" && typeof table != undefined && table != "") {

                    $("#exemplo").empty();
                    table.destroy();
                }

                if (typeof where == "undefined" || typeof where == undefined) {
                    where = "";
                }

                table =  $("#' . $options['id'] . '").DataTable({
                    "paging":   true,
                    // "pagingType": "scrolling",
                    "pagingType": "full_numbers",
                    // "sPaginationType": "four_button",
                    "retrieve": true,
                    "searching": false,
                    "ordering": true,

                    "order": [
                        [ 
                            ' . $order . ', "' . $order_type . '"
                        ]
                    ],

                    aaSorting: [],

                    "lengthChange": false,
                    "info": false,
                    "ajax": {
                        "url": "' . base_url() . $options['controller'] . '/' . $options['action'] . '",
                        "type": "post",
                        "data": where,
                        "processing": true,
                    },
                    "language": {
                        "sEmptyTable": "Nenhum registro encontrado",
                        "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                        "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
                        "sInfoFiltered": "(Filtrados de _MAX_ registros)",
                        "sInfoPostFix": "",
                        "sInfoThousands": ".",
                        "sLengthMenu": "_MENU_ resultados por página",
                        "sLoadingRecords": "Carregando...",
                        "sProcessing": "Processando...",
                        "sZeroRecords": "Nenhum registro encontrado",
                        "sSearch": "Pesquisar",
                        "oPaginate": {
                            "sNext": "",
                            "sPrevious": "",
                            "sFirst": "",
                            "sLast": ""
                        },
                        "oAria": {
                            "sSortAscending": ": Ordenar colunas de forma ascendente",
                            "sSortDescending": ": Ordenar colunas de forma descendente"
                        }
                    }
                });

                $("#datatables tr").addClass("tr_clicked projeto-cursor-pointer");
            }
        </script>';

        $datatables .= '

            <style>
                .pagination > li:last-child > a{
                    z-index: 0;
                }
                .input-group {
                    z-index: 0;
                }
            </style>';

        $datatables .= '

            <table id="' . $options['id'] . '" class="table admin-form theme-warning fs13" cellspacing="0" width="' . $options['width'] . '">
                <thead>
                    <tr>';

        if (array_key_exists('active_ind', $fields))
            $fields = array_merge($fields, array('acoes' => 'Ações'));

        foreach ($fields as $field => $title)
        {
            $datatables .= '<th>' . $title . '</th>';
        }

        $datatables .= '</tr>
                    </thead>
                </table>';


   
        return $datatables;
    }
}

Open in new window



Error founded:
img004

Could you check and give a help?

Thanks in advance.
0
Eduardo Fuerte
Asked:
Eduardo Fuerte
  • 3
  • 3
1 Solution
 
leakim971PluritechnicianCommented:
please share a link to your page, you will increase help.
1
 
Eduardo FuerteAuthor Commented:
Hi leakim971

This site is still intranet.
0
 
leakim971PluritechnicianCommented:
you need to include this : http://cdn.datatables.net/plug-ins/1.10.9/sorting/datetime-moment.js after your line 45

            <!-- Datatable Moment declaration -->
            <script src="' . base_url() . 'your/path/to/datetime-moment.js"></script>

Open in new window


/**
 * This plug-in for DataTables represents the ultimate option in extensibility
 * for sorting date / time strings correctly. It uses
 * [Moment.js](http://momentjs.com) to create automatic type detection and
 * sorting plug-ins for DataTables based on a given format. This way, DataTables
 * will automatically detect your temporal information and sort it correctly.
 *
 * For usage instructions, please see the DataTables blog
 * post that [introduces it](//datatables.net/blog/2014-12-18).
 *
 * @name Ultimate Date / Time sorting
 * @summary Sort date and time in any format using Moment.js
 * @author [Allan Jardine](//datatables.net)
 * @depends DataTables 1.10+, Moment.js 1.7+
 *
 * @example
 *    $.fn.dataTable.moment( 'HH:mm MMM D, YY' );
 *    $.fn.dataTable.moment( 'dddd, MMMM Do, YYYY' );
 *
 *    $('#example').DataTable();
 */

(function($) {

$.fn.dataTable.moment = function ( format, locale ) {
	var types = $.fn.dataTable.ext.type;

	// Add type detection
	types.detect.unshift( function ( d ) {
		// Null and empty values are acceptable
		if ( d === '' || d === null ) {
			return 'moment-'+format;
		}

		return moment( d.replace ? d.replace(/<.*?>/g, '') : d, format, locale, true ).isValid() ?
			'moment-'+format :
			null;
	} );

	// Add sorting method - use an integer for the sorting
	types.order[ 'moment-'+format+'-pre' ] = function ( d ) {
		return d === '' || d === null ?
			-Infinity :
			parseInt( moment( d.replace ? d.replace(/<.*?>/g, '') : d, format, locale, true ).format( 'x' ), 10 );
	};
};

}(jQuery));

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Eduardo FuerteAuthor Commented:
Hi @leakim971

You pointed the right way!

But something is preventing the datatables plugin grid to be loaded.

$(document).ready(function(){

	  //The js call - no error
	  $.fn.DataTable.moment( "DD/MM/YYYY hh:mm");
	  ...

Open in new window

0
 
leakim971PluritechnicianCommented:
be sure to add the plugin in the right order.
post the file you're using, of course you need the moment.js too somewhere (custom dataTable plugin or not)
0
 
Eduardo FuerteAuthor Commented:
Thanks for help!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now