如何在后端生成代码并在jQgrid中以JSON的形式发送到视图时添加自定义格式器?
问题描述:
我正在使用jQgrid,我从PHP构建它的内容并将其作为JSON发送到视图。下面是PHP代码片段我使用目前:如何在后端生成代码并在jQgrid中以JSON的形式发送到视图时添加自定义格式器?
$colFormats[] = [
'index' => 'actions',
'name' => 'actions',
'width' => 70,
'editable' => false,
'formatter' => 'show_btn',
'sortable' => false,
'align' => 'center'
];
foreach ($classMedata->getFieldNames() as $key => $value) {
$colFormats[] = [
'index' => $classMedata->getCollection().'.'.$value,
'name' => $value,
'width' => 100,
];
}
return $this->render('IntegrationBundle:api-logs:index.html.twig', [
'colFormats' => json_encode($colFormats),
'colNames' => json_encode($colNames),
]);
这是JavaScript代码,我对视图:
<script type="text/javascript">
var show_btn = function (cellVal, options, rowObject) {
return '<input style="height:22px;" type="button" value="Show" onclick="" />';
};
$(function() {
$("#grid").jqGrid({
url: '/sf/api-logs',
datatype: "json",
colNames: {{ colNames|raw }},
colModel: {{ colFormats|raw }},
width: 980,
height: 300,
pager: "#gridpager",
toppager: true,
hoverrows: true,
shrinkToFit: true,
autowidth: true,
rownumbers: true,
viewrecords: true,
rowList: [10, 20, 50, 100],
data: [],
rownumWidth: 50,
sortable: true,
jsonReader: {
root: 'rows',
page: 'page',
total: 'total',
records: 'records',
cell: '',
repeatitems: false
},
loadComplete: function (data) {
if (data.records === 0) {
$("#load_grid").addClass("info_msg").html($("<span>", {
"class": "grid-empty",
"text": "No results were found."
})).delay(800).fadeIn(400);
}
}
});
});
</script>
当PHP渲染视图我可以看到正确的JS代码为colNames
和colModel
:
colNames: ["Actions", "ID", "Object", ...],
colModel: [{
"index": "actions",
"name": "actions",
"width": 70,
"editable": false,
"formatter": "show_btn",
"sortable": false,
"align": "center"
},
{"index": "ApiLogs.id", "name": "id", "width": 100},
{"index": "ApiLogs.dataObject","name": "dataObject","width": 100}, ...
,而不是看到呈现在科拉姆Actions
的按钮,但我看到了undefined
字。我不确定我的错误在哪里。有任何帮助吗?
答
格式化程序最舒适的形式是字符串形式,如formatter: "myFormatter"
。你知道"predefined formatters"就像formatter: "integer"
,formatter: "date"
等等。我建议你将的寄存器作为“预定义的格式化程序”,并将其设置在后端。
要做到这一点,你只需要扩展
$.fn.fmatter.myFormatter = function (cellValue, options, rowData, addOrEdit) {
// the code of formatter (the same as the custom formatter)
return '<input style="height:22px;" type="button" value="Show" />';
};
$.fn.fmatter.myFormatter.unformat = function (cellValue, options, elem) {
// the code of unformatter, like
// return $(elem).text();
};
请在约jqGrid的所有问题,包括有关**的版本信息**的jqGrid和大约**叉**([免费的jqGrid] (https://github.com/free-jqgrid/jqGrid),商业版[Guriddo jqGrid JS](http://guriddo.net/?page_id=103334)或旧版/复古版jqGrid版本 Oleg