@WebGuardMan

Почему не работает DataTable с датами Unixcode?

Добрый день, таблица datatable упорно не хочет преобразовывать даты из unixcode в удобночитаемые, сортировка и поиск работают хорошо, плагины подключены. Есть аналогичные таблицы с другими данные и они успешно работают, проблема только в этой. Что здесь не так?
Исходный текст страницы

{include file="header.tpl"}

<script type="text/javascript" src="js/datatables.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/plug-ins/1.10.12/dataRender/datetime.js"></script>
<script type="text/javascript" src="js/moment-with-locales.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/datatables.min.css"/>
<style>
.dataTables_filter input { 
	width: 500px !important
	}
.namefield, .tabresult { 
	width: 660px !important;
	margin-bottom: 0px !important;
	}
</style>

  <div class="container theme-showcase" role="main">

{include file="navbar.tpl"}

<!-- Small modal -->
<div class="modal fade" id="payinfo_modal">
  <div class="modal-dialog">
    <div class="modal-content">
      Идет загрузка данных ...
    </div>
  </div>
</div>

<div class="row">
	<div class="container" id="actionres"> <!-- Блок для сообщений о выполнении действия -->

	</div>
		<div class="container"> <!-- Начало контейнера таблицы списка юзеров -->
		
			<table class="table table-striped table-hover table-condensed table-bordered" id="mp3list">
			<thead>
				<tr>
				<td class="text-nowrap text-center"><b>&nbsp;№ пп</b></td>
				<td class="text-nowrap"><b><span class="glyphicon glyphicon-user"></span>&nbsp;Пользователь</b></td>
				<td class="text-center text-nowrap"><span class="glyphicon glyphicon-time"></span>&nbsp;<b>Регистрация</b></td>
				<td class="text-center text-nowrap"><span class="glyphicon glyphicon-time"></span>&nbsp;<b>Был активен</b></td>

				<td class="text-center text-nowrap"><span class="glyphicon glyphicon-link"></span>&nbsp;<b>Где находится / С чего сидит</b></td>
				<td class="text-center text-nowrap"><span class="glyphicon glyphicon-usd"></span>&nbsp;<b>Фрешей</b></td>
				<td class="text-right text-nowrap"><span class="glyphicon glyphicon-config"></span>&nbsp;<b>Действия</b></td>
				</tr>
			</thead>
				<tbody>
		{foreach from=$UsersList item=user}
				<tr {if $user.userid!=0}class="warning"{/if}>
				<td class="text-nowrap text-center">{$user.pp}</td>
				<td class="text-center text-nowrap">
				<a href=http://freshrecords.ru/member.php?u={$user.userid} target="_Blank" data-toggle="modal" data-remote="userinfo.php?userid={$user.userid}" data-target="#payinfo_modal">{$user.userinfo.username}</a>
				{if $user.userid!=0}<br>{/if}
					{if $user.userinfo.usergroupid==28}<span class="label label-warning" title="Этот пользователь в настоящее время имеет статус Голд">Голд</span><br>{/if}
					{if $user.userinfo.usergroupid==8}<span class="label label-danger" title="Этот пользователь в настоящее время Заблокирован">В бане</span><br>{/if}
					{if $user.userinfo.usergroupid==7}<span class="label label-success" title="Модератор">Модератор</span><br>{/if}
					{if $user.userinfo.usergroupid==4}<span class="label label-default" title="Зарегистрирован, но еще не прошел активацию">Неактивирован</span><br>{/if}
					{if $user.userinfo.usergroupid==5 OR $user.userinfo.usergroupid==6}<span class="label label-danger" title="Администратор или смотритель">Администратор</span><br>{/if}
				<img src="images/flags/{$user.geo.country.iso}0.gif" data-toggle="tooltip" data-placement="left" title="{$user.geo.country.name_ru}, {$user.geo.city.name_ru}" />&nbsp;<a href="ip.php?ip={$user.host}" target="_Blank">{$user.host}</a>
				</td>
				<td class="text-center text-nowrap">{if $user.userinfo.joindate>0}{$user.userinfo.joindate}{else}0{/if}</td>
				<td class="text-center text-nowrap">{if $user.lastactivity>0}{$user.lastactivity}{else}0{/if}</td>
				
				<td class="text-left" width="250">
					<a href="http://freshrecords.ru{$user.location}" target="_Blank">{$user.locshort}</a><br>
					{$user.useragent}
				</td>
				<td class="text-center text-nowrap"><span class="text-success"><b>{$user.userinfo.vbbux}</b></span></td>

				<td class="text-right txt-nowrap">
				{if $user.userid!=0}
				<div class="btn-group">
				  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Опции <span class="caret"></span></button>
				   <ul class="dropdown-menu" role="menu">
					<li><a href="#" data-toggle="modal" data-remote="add_service.php?action=new&userid={$user.userid}" data-target="#payinfo_modal"><span class="glyphicon glyphicon-plus"></span> Предоставить услугу</a></li>
					<li class="divider"></li>
					<li><a href="userpayments.php?userid={$user.userid}" target="_Blank"><span class="glyphicon glyphicon-usd"></span> Платежи пользователя</a></li>
					<li><a href="downstat.php?userid={$user.userid}" target="_Blank"><span class="glyphicon glyphicon-download"></span> Список скачиваний</a></li>
					<li><a href="user_profit.php?userid={$user.userid}" target="_Blank"><span class="glyphicon glyphicon-usd"></span> Доходы пользователя</a></li>
					<li class="divider"></li>
					<li><a href="#" data-toggle="modal" data-remote="banuser.php?userid={$user.userid}" data-target="#payinfo_modal"><span class="glyphicon glyphicon-remove"></span> Заблокировать</a></li>
				  </ul>
				</div>
				{/if}
				</td> 
				</tr>
		{/foreach}	
			</tbody>
			</table>
		</div> <!-- Конец контейнера таблицы списка юзеров-->			  
</div>	
	</div> <!-- общий контейнер -->

<script language="JavaScript">
jQuery.fn.dataTable.render.moment = function ( from, to, locale ) {
    // Argument shifting
    if ( arguments.length === 1 ) {
        locale = 'ru';
        to = from;
        from = 'YYYY-MM-DD';
    }
    else if ( arguments.length === 2 ) {
        locale = 'ru';
    }
 
    return function ( d, type, row ) {
        var m = window.moment( d, from, locale, true );
 
        // Order and type get a number value from Moment, everything else
        // sees the rendered value
        return m.format( type === 'sort' || type === 'type' ? 'x' : to );
    };
};

$(document).ready( function () {
    $('#mp3list').DataTable( {
		"order": [[ 3, "desc" ]],
		"paging":   true,
		"language": {
            "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Russian.json"
        },
		columnDefs: [ {
			targets: [2,3],
			render: $.fn.dataTable.render.moment( 'X', 'DD-MM-YY HH:mm' )
		} ],
		columnDefs: [ {
			targets: [1,4,6],
			orderable: false
		} ]
	} );
	$('body .dropdown-toggle').dropdown();
} );

$('#mp3list').on('init.dt', function () {
        $(".dataTables_filter input").addClass("");
    } );
	
$('#payinfo_modal').on('hidden.bs.modal', function (e) {
    $(this).removeData('bs.modal');
})
</script>

{include file="footer.tpl"}

  • Вопрос задан
  • 50 просмотров
Решения вопроса 1
@WebGuardMan Автор вопроса
Проблема решена использованием data-атрибутов, оказывается это очень удобно и не нужно использовать плагины moments. С помощью атрибутов можно задать значения для поиска и сортировки отличное от отображаемого и это круто.
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
NeiroNx
@NeiroNx
Программист
Если бы было все так просто то тогда не изобретали бы плагины сортировки для каждого формата отдельно. Есть плагин datetime-moment пишут что для любого формата подходит.
И во вторых раз работают другие с этим же кодом, то скорее всего проблема в данных.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы