Norbert Szenasi
Norbert Szenasi

Reputation: 993

Display columns as rows using jqGrid

Is there a way to display columns as rows? So that the number of rows represents the number of properties of the object we are trying to display and the number of columns is the number of records returned (in my case it is always one record).

Picture

enter image description here

I tried searching for an existing answer but haven't found one. I also tried using formatters but I guess they are only used to format a specified cell and not the whole table.

Upvotes: 3

Views: 1443

Answers (1)

Oleg
Oleg

Reputation: 221997

I suppose that you need to display enumerable properties of the object (see here) and the values of the properties. The corresponding code could be for example the following:

var myobject = {
    prop1: "value1",
    prop2: 2,
    prop3: new Date(),
    prop4: true,
    prop5: function () { return "Hello world!"; },
    prop6: null,
    prop7: { x: 1, y: 2, z: "some text"}
};
$("#grid").jqGrid({
    colModel: [
        { name: "name", width: 80 },
        { name: "type", width: 80 },
        { name: "value", width: 400 }
    ],
    datatype: "jsonstring",
    datastr: myobject,
    jsonReader: {
        repeatitems: false,
        root: function (obj) {
            var prop, result = [], value;
            for (prop in obj) {
                if (obj.hasOwnProperty(prop)) {
                    value = obj[prop];
                    result.push({
                        name: prop,
                        type: $.type(value),
                        value: $.type(value) === "object" ?
                                JSON.stringify(value) :
                                String(value)
                    });
                }
            }
            return result;
        },
    },
    iconSet: "fontAwesome",
    autoencode: true,
    rownumbers: true,
    cmTemplate: { autoResizable: true },
    autoResizing: { compact: true },
    viewrecords: true,
    pager: true
});

The demo https://jsfiddle.net/OlegKi/euau0yqj/2/ uses the code and displays the following results

enter image description here

The main logic of the demo is in jsonReader.root, which should return the array with the data. I used in the demo free jqGrid, the fork of jqGrid, which I develop since a year, but the main functionality should work with the old versions of jqGrid too.

Upvotes: 3

Related Questions