Tuesday 17 February 2015

DataTables render function without a Switch

My use case is quite specific. I’m developing an application for a charity in my evenings and weekends and using DataTables to display a lot of their data. I hold a lot of Address data as well as other types of data which can be associated with Addresses using a junction table. For instance: I can create many-to-many relationships between Contacts and Addresses by storing the contact_id and address_id in a contact_address table. And between Churches, for instance, and Addresses by having each association being a line in my church_address. It really does work a treat, though diagrams detailing the structure are really messy.

This approach also allows me to create triggers so that should an Address, Contact or Church be deleted then the corresponding row in the junction table will also be deleted. Lovely.

There has recently been a requirement for Users to see all associations to a given address and I’m using Medoo to select this data before using Twig to render it to a table before using DataTables to fine-tune the table... because I really want the User to be able to access the associated record. I could use a switch within the render function to get the correct address but then I remembered this article about alternative to switch and decided to give it a whirl (I think one of the reasons I’m so keen on avoiding switch statements is that I seem to be using them so much elsewhere at the minute - is there a similar approach for PHP anyone?).

Anyway, this is how I’ve got around not using switch in this particular use-case:

$(function(){
    $("#addresses").DataTable({
        "columns": [
            {
                "title": "Association to:"
            },
            {
                "visible": false
            },
            {
                "title": "Actions",
                "render": function(data, type, full){
                    return  (association[full[0]]) ? association[full[0]](full) : full[1];
                }
            }
        ],
        "lengthMenu": [
            [10, 25, 50, -1],
            [10, 25, 50, "All"]
        ],
        "stateSave": true,
        "pageLength": 25
    });
});
var association = {
    "Contact": function(item) {
        return '<a href="/contact/?id=' + item[1] + '">' + item[2] + '</a>';
    },
    "Session": function(item) {
        return '<a href="/session/?id=' + item[1] + '">' + item[2] + '</a>';
    },
    "Trust": function(item) {
        return '<a href="/trust/?id=' + item[1] + '">' + item[2] + '</a>';
    },
    "Organisation": function(item) {
        return '<a href="/organisation/?id=' + item[1] + '">' + item[2] + '</a>';
    }
};