Using primary key of entity when formatting data using 'render' on table creation.

Using primary key of entity when formatting data using 'render' on table creation.

David@QuantumDavid@Quantum Posts: 36Questions: 4Answers: 2

I've been away from DT for quite sometime so if I knew how to do this... I forgot!
I'm using DataTables Editor + PHP to load data to the page and I want to render one of the columns with a custom checkbox, that points to a function with the uID of that row as a parameter... When I use table.row( this ).id() or table.row( this ).index() it returns undefined. Where am I going wrong here? Find an excerpt from my code below.
Thanks in advance,
David

        var table = $('#organisations').DataTable( {
        dom: 'Bfrtip',
        rowId: 'org_id',
        ajax: 'DataTablesSource/php/table.organisations.php',
        order: [],
        scrollY:        '100px',
        scrollCollapse: true,
        paging:         false,
        columns: [
            {
                "data": "org_id"
            },
            {
                "data": "org_name"
            },
            {
                "width": "60px",
                "data": "org_is_active"
            }
        ],
        columnDefs: [ {
            "targets": 2,
            "data": "org_is_active",
            "render": function ( data, type, row, meta ){
                return '<input type="checkbox" onClick="(function anon(){alert( '+ table.row( this ).index() +');})();" checked>';
            }
        },
        {
                "targets": 0,
                "visible": false
        }],
        select: true,
        lengthChange: false,
        buttons: [
            { extend: 'create', editor: editor },
        ]
    } );

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,296Questions: 26Answers: 4,768
    Answer ✓

    it returns undefined. Where am I going wrong here?

    Likely because the variable table isn't available yet until initialization is complete. The meta parameter of the columns.render contains the row ID. So you would do something like {alert( '+ meta.row +');}.

    I've seen other posts about problems with setting up click events this way in Datatables. It may work but here are a couple other options for you to look at. They are with buttons instead of checkboxes but the concept should be the same.

    With defaultContent:
    http://live.datatables.net/xijecupo/1/edit

    With option column.render:
    http://live.datatables.net/qemodapi/1/edit

    Kevin

  • David@QuantumDavid@Quantum Posts: 36Questions: 4Answers: 2
    edited October 2019

    @kthorngren , thanks for those alternatives, I'll definitely keep those tags in case it doesn't work out as expected later on. But combining meta.row with my existing code: alert( '+ table.row( meta.row ).id() +');} proved successful :smiley:

This discussion has been closed.