Change the edit url, dynamically using the Datatable Editor

223 Views Asked by At

I'm looking on how to update the ajax configuration dynamically using data from a resource when updating a record. Django REST expects the id at the end of the url and the request method must be type PUT

1

There are 1 best solutions below

0
Wolfgang Leon On

I've spent some time figuring out how to update the ajax request made by the Datatable Editor plugin. I'm using Django Rest as the backend. This might be useful for some people looking for a similar answer.

Technically you can update the ajax options if the editor object before it sends the request by using the preSubmit Event.

    editor.on('preSubmit', (e, request,) =>{
        let _url = new URL(window.location.origin + "/" + editor.ajax().url)

        if(request.action == 'edit'){
            editor.ajax().url = `${_url.protocol}//${_url.host}/api/v1/some-endpoint/${Object.keys(request.data)[0]}/${_url.search}`;
            editor.ajax().type = 'PUT'
        }

        editor.ajax().data = request.data[Object.keys(request.data)]

    })

This will update the ajax configuration of the edit request right before it get sent. Django Rest expects a PUT request and the id of the record to be added at the end of the URL. As you can see we grab the id from the data object (Its the first key of the request.data object), and we can also change the type of request to PUT.