How to pass a render function in a JSON string?

How to pass a render function in a JSON string?

mtdvlpmtdvlp Posts: 2Questions: 1Answers: 0

I have variable tables, where the column information is gathered on the server and passed in a JSON string.

I am trying to add a renderer to one column that has a checkbox, and the render function looks like it should do that. However, I would like to pass a function name to datatables, something like

        columns: [
            { data: "firstColumn" },
                    . . .
            {
                data:   "checkboxColumn",
                render: "myFunction"
                className: "dt-body-center"
            }
        ],

However myFunction is obviously not recognized as a function. I tried to make it myFunction() since I saw a mention of that syntax in the documentation, but JSON does not like that.

Is there a way to do this? Either by something with the syntax or by making another Javascript call after the main initialization?

Answers

  • allanallan Posts: 61,705Questions: 1Answers: 10,102 Site admin

    You would do:

    data:   "checkboxColumn",
    render: function ( data, type, row ) {
      return ...;
    }
    

    where data is whatever the value of the checkboxColumn property for that row. If you need the other data points for the row, you have them in the row parameter that is passed in (that is the original object used for the row's data).

    Allan

  • mtdvlpmtdvlp Posts: 2Questions: 1Answers: 0

    I don't think that helps me. My core problem is that I cannot create an inline function, because the column specification is being passed via JSON.

    And I cannot figure out how to create a column specification with the function name that go through JSON.

  • allanallan Posts: 61,705Questions: 1Answers: 10,102 Site admin

    Oh I see - the column information is JSON? In that case, I'm afraid there really is no option to use a function at this time, since as you are seeing, JSON cannot contain a function.

    You would have to process the JSON on the client-side - perhaps have a prefix of : or something for the data name, have the code look for that, and if found replace it with a function.

    Allan

This discussion has been closed.