how to edit data from Datatable plugin using Bootstrap modal in CodeIgniter
Home » BLOG » Web development » How to edit data from Datatable plugin using Bootstrap modal in CodeIgniter

How to edit data from Datatable plugin using Bootstrap modal in CodeIgniter

category:  CodeIgniter, Web development
5 min read

In the last post, I wrote, “How to add data from Datatable plugin using Bootstrap modal in CodeIgniter” I show only adding new data. In this post, I will share how to edit data via Bootstrap modal. Let’s go.

Add a new column for the controller in the view page

In the template, we add the new column in the table tag. This table will use for the DataTable plugin.

            <!-- Render data in datatable plugin -->
            <table id="rep_news" class="table table-striped table-bordered table-hover" style="width:100%">
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Title</th>
                        <th>Slug</th>
                        <th>Text</th>
                        <th></th> <!-- add new column -->
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>Id</th>
                        <th>Title</th>
                        <th>Slug</th>
                        <th>Text</th>
                        <th></th> <!-- add new column -->
                    </tr>
                </tfoot>
            </table>

Add the edit control in the footer template

Open your footer template, add the column rendering as the code below. This JavaScript code will be added at the footer of template. It will be under the DataTable script.

<script>
    $(document).ready(function() {

        /**
         * DataTable initialization
         */
        $('#rep_news').DataTable({
            data: <?php echo json_encode($news) ?>,
            columns: [{
                    "data": "id"
                },
                {
                    "data": "title"
                },
                {
                    "data": "slug"
                },
                {
                    "data": "text"
                }
            ],
            columnDefs: [{
                    // # hide the first column
                    // https://datatables.net/examples/advanced_init/column_render.html                    
                    "targets": [0],
                    "visible": false
                },
                {
                    // # disable search for column number 2
                    // https://datatables.net/reference/option/columns.searchable                    
                    "targets": [3],
                    "searchable": false,
                    // # disable orderable column
                    // https://datatables.net/reference/option/columns.orderable
                    "orderable": false
                },
                {
                    // # action controller (edit,delete)
                    "targets": [4],
                    // # column rendering
                    // https://datatables.net/reference/option/columns.render
                    "render": function(data, type, row, meta) {
                        return '<button class="btn btn-sm btn-info" data-toggle="modal" data-target="#edit_news_modal" data-id="' + row.id + '" data-title="' + row.title + '" data-slug="' + row.slug + '" data-text="' + row.text + '">Edit</button>';
                    }
                }
            ],
            // # set order descending and ascending
            // https://datatables.net/reference/option/order
            "order": [
                [1, 'desc'],
                [2, 'asc']
            ]
        });

    }); // document ready ends
</script>

We add the render option for the last column for our table. We return the edit button with the row value to the data attributes. So that in the Bootstrap modal function, we can access the row value via the data attributes.

Notice that, we add the data-toggle and data-target to activate the edit Bootstrap modal.

Add an edit data modal in the view page

Open your template and add the edit modal code below. This code will render the edit data modal window.

<!-- Editing form modal -->
<div id="edit_news_modal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Edit News item</h4>
                <button type="button" class="close" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">

                <form method="post" id="update_form">
                    <input type="hidden" name="id" id="id" />
                    <div class="form-group">
                        <label for="title">Title</label>
                        <input type="text" name="title" id="title" class="form-control" placeholder="Enter title" />
                    </div>
                    <div class="form-group">
                        <label for="slug">Slug</label>
                        <input type="text" name="slug" id="slug" class="form-control" placeholder="Enter slug" />
                    </div>
                    <div class="form-group">
                        <label for="text">Text</label>
                        <textarea class="form-control" name="text" id="text" cols="30" rows="10" placeholder="Enter text"></textarea>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <input type="submit" name="update" id="update" value="Save" class="btn btn-success" />
                    </div>
                </form>

            </div> <!-- .modal-body -->
        </div> <!-- .modal-content -->
    </div> <!-- .modal-dialog -->
</div> <!-- .modal -->

Now when you click on the edit button, the edit modal will popup as the screen below.

edit data in modal
figure: edit data modal

Add the update form submitting

Next, we will add the JavaScript code to handle the form submitting. Below is the code.

        /**
         * Add update data via ajax 
         */
        $('#update_form').on("submit", function(event) {
            event.preventDefault();

            // # form validation
            // Optional, you can use the jQuery validation plugin (https://applerinquest.com/how-to-validate-a-form-with-jquery-validation-plugin/)
            // if you don't want to do the form validation manually.

            // For the warning message, you can use the Alert message from Bootstrap if you like. I use alert() because I want to keep the post short.
            // https://getbootstrap.com/docs/4.0/components/alerts/
            var edit_modal = $('#edit_news_modal');
            var $title = edit_modal.find('#title');
            var $slug = edit_modal.find('#slug');
            var $text = edit_modal.find('#text');

            if ($title.val() == "") {
                alert("Title is required");
                $title.focus();

            } else if ($slug.val() == '') {
                alert("Slug is required");
                $slug.focus();

            } else if ($text.val() == '') {
                alert("Text is required");
                $text.focus();

            } else {
                $.ajax({
                    url: "<?php echo base_url('index.php/news/upd_news_item') ?>",
                    method: "POST",
                    data: $('#update_form').serialize(),
                    dataType: "JSON", // you must set dataType as JSON while sending the Ajax request
                    beforeSend: function() {
                        $('#update').val("Updating");
                    },
                    success: function(response) {
                        // # get the response from our controller
                        // console.log(response);
                        // console.log(response.upd_status);
                        // console.log(response.data);

                        if (response.upd_status) {
                            // reset the form
                            $('#update_form')[0].reset();
                            $('#update').val("Save");

                            // hide the Bootstrap modal
                            $('#edit_news_modal').modal('hide');

                            // refresh the Datatable plugin
                            $('#rep_news').dataTable().fnDestroy();
                            $('#rep_news').DataTable({
                                data: response.data,
                                columns: [{
                                        "data": "id"
                                    },
                                    {
                                        "data": "title"
                                    },
                                    {
                                        "data": "slug"
                                    },
                                    {
                                        "data": "text"
                                    }
                                ],
                                columnDefs: [{
                                        // # hide the first column
                                        // https://datatables.net/examples/advanced_init/column_render.html                    
                                        "targets": [0],
                                        "visible": false
                                    },
                                    {
                                        // # disable search for column number 2
                                        // https://datatables.net/reference/option/columns.searchable                    
                                        "targets": [3],
                                        "searchable": false,
                                        // # disable orderable column
                                        // https://datatables.net/reference/option/columns.orderable
                                        "orderable": false
                                    },
                                    {
                                        // # action controller (edit,delete)
                                        "targets": [4],
                                        // # column rendering
                                        // https://datatables.net/reference/option/columns.render
                                        "render": function(data, type, row, meta) {
                                            return '<button class="btn btn-sm btn-info" data-toggle="modal" data-target="#edit_news_modal" data-id="' + row.id + '" data-title="' + row.title + '" data-slug="' + row.slug + '" data-text="' + row.text + '">Edit</button>';
                                        }
                                    }
                                ],
                                // # set order descending and ascending
                                // https://datatables.net/reference/option/order
                                "order": [
                                    [1, 'desc'],
                                    [2, 'asc']
                                ]
                            });

                            // success message
                            alert('success');

                        } else {

                            alert('data is not updated. you must check the update script in your model.');
                        }

                    },
                    error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(err.Message);
                    }
                });
            }
        });

In the JavaScript code, it does the form validation first. Then it calls Ajax for sending the form data to update the data in the database.

If the update is success, it will show the success message and hide the modal. Finally, it will refresh the data at the table.

You must set the datatype as JSON in the Ajax call.

important

Add the update data item method in the controller

In the Ajax call, we need to send the request to the URL object. In our ajax call, we send the request to “index.php/news/upd_news_item“. But we don’t create the upd_news_item method yet. Let create now.

Open your controller, in my case, it is the news controller and add the code below.

    /**
     * Update new data from Bootstrap modal
     */
    public function upd_news_item()
    {
        $upd = $this->news_model->upd_news();
        $news = $this->news_model->get_news();

        // # Return our data back to ajax with Json format (json_encode)
        // you must use "echo" for returning the result you want.
        echo json_encode(
            // using the array for returning data
            array(
                'upd_status' => $upd,
                'data' => $news
            )
        );
    }

In the method, we call upd_news method from the news model for updating the data. Next, we query all news data and send it back to the Ajax call.

Notice that, we use “echo” for returning the result back to Ajax and send the array as the result. Also, we use json_encode function to convert the array to JSON because our Ajax sets the datatype as JSON.

Important

Add upd_news method in the model

In the controller above, we call the upd_news method from the model for updating the data. But we don’t create this method yet.

To create the method, add the code below.

    public function upd_news()
    {
        $this->load->helper('url');

        $slug = url_title($this->input->post('title'), 'dash', TRUE);

        $data = array(
            'title' => $this->input->post('title'),
            'slug' => $slug,
            'text' => $this->input->post('text')
        );

        $this->db->where('id', $this->input->post('id'));
        return $this->db->update('news', $data);
    }

Now you can edit the data with the Bootstrap modal via Ajax.

Conclusion

With Bootstrap modal and Datatable plugins, your users can manage the data easier and faster. I hope this post will be useful for everyday.