我遇到了一个问题,即通过id从enum获取字符串。
这是我的数据表代码:
<script type="text/javascript">
$(document).ready(function(){
var datatable = $('#datatable').DataTable(
{
dom: "lrtip",
responsive: true,
processing: true,
serverSide: true,
bSortCellsTop: true,
ajax: {
url: "{{ route('driver.list') }}",
data: { '_token' : '{{csrf_token() }}'},
type: 'POST',
},
columns: [
{ data: 'first_name', name: 'first_name', className: 'text-center', },
{ data: 'last_name', name: 'last_name', className: 'text-center', 'visible': false,
'searchable': false, },
{ data: 'gender', name: 'gender', className: 'text-center', },
{ data: 'race', name: 'race', className: 'text-center', 'visible': false,
'searchable': false, },
{ data: 'email', name: 'email', className: 'text-center', },
{ data: 'mobile', name: 'mobile', className: 'text-center', },
{ data: 'nric', name: 'nric', className: 'text-center', },
{ data: 'date_of_birth', name: 'date_of_birth', className: 'text-center', 'visible': false,
'searchable': false, },
{ data: 'license', name: 'license', className: 'text-center', },
{ data: 'type', name: 'type', className: 'text-center', 'visible': false,
'searchable': false, },
{ data: 'action', name: 'action', className: 'text-center', orderable: false, searchable: false },
],
initComplete: function () {
this.api().columns().every(function () {
$('#datatable thead tr#filterRow th:not(:last-child)').each( function () {
var title = $('#datatable thead th').eq( $(this).index() ).text();
$(this).html( '<input type="text" class="col-md-12" placeholder="Search by '+title+'" />');
if (title == "Gender") {
var select = $('<select>');
var genderList = {!! json_encode($genderList) !!};
for (var i = 0;i < genderList.length; i++) {
option = $('<option>',{
value: i,
text: genderList[i],
});
select.append(option);
}
$(this).html(select);
}
});
$('select').select2({
allowClear: true,
});
$("#datatable thead input,#datatable thead select").on('keyup change', function () {
console.log($(this).val());
datatable.column( $(this).parent().index()).search(this.value).draw();
});
});
}
});
});
</script>
这是我的枚举代码:
<?php
namespace App\Helpers\Enums;
final class Gender {
const MALE = 0;
const FEMALE = 1;
public static function getList() {
return [
Gender::MALE,
Gender::FEMALE,
];
}
public static function getArray() {
$result = [];
foreach (self::getList() as $arr) {
$result[$arr] = self::getString($arr);
}
return $result;
}
public static function getString($val) {
switch ($val) {
case 0:
return "Male";
case 1:
return "Female";
}
}
}
?>
我想通过id从enum中获取字符串。
为什么当我选择男性/女性时,它没有处理数据?任何的想法 ?
答案 0 :(得分:0)
如果您正在使用Yajra的Datatable软件包,为什么不使用变换器,它适用于Fractal,请参见:https://datatables.yajrabox.com/eloquent/transformer
然后你可以在你的变压器中做这样的事情:
public function transform(Driver $driver)
{
return [
'gender' => $driver->gender == 0 ? 'Male' : 'Female'
];
}