How to add buttons dinamically to collection

How to add buttons dinamically to collection

baratafeyobaratafeyo Posts: 5Questions: 1Answers: 0

I want to dinamically add buttons to a collection of a custom button called software. This button is going to have buttons that filter the table by software. The name of the buttons come dinamically from database. Here's what I've tried so far:

<script>

            $(document).ready(function () {
                $("#coreVersaoAPP-table").DataTable({


                    "ajax": {
                        "url": '@Url.Action("GetListFromCoreVersaoAPP", "CoreVersaoAPP")',
                        "type": "GET",
                        "datatype": "json"
                    },

                    "columns": [
                        { "data": "ID" },
                        { "data": "SOFTWARE" },
                        { "data": "VERSAO" },
                        { "data": "TIPO" },
                        { "data": "USERCD" },
                        { "data": "COREDTADD" },
                        {
                            "render": function (data, type, row) {
                                return "<a href='./UpdateCoreVersaoAPP?" + "id=" + row.ID + "'><i class='far fa-edit'></i></a>";
                            }
                        }
                    ],

                    language: {
                        search: "Procurar: ",
                        processing: "A carregar",
                        lengthMenu: "Mostrar _MENU_ registos",
                        info: "A mostrar de _START_ a _END_ registos de _TOTAL_ registos",
                        infoFiltered: "(filtrados _MAX_ registos de total)",
                        infoEmpty: "A mostrar 0 a 0 registos de 0 registos",
                        loadingRecords: "A carregar registos...",
                        zeroRecords: "Nenhum registo para mostrar",
                        emptyTable: "Tabela vazia",
                        paginate: {
                            first: "Primeiro",
                            previous: "Anterior",
                            next: "Próximo",
                            last: "Último"
                        },
                        aria: {
                            sortAscending: ": Ordenar por ordem crescente",
                            sortDescending: ": Ordenar por ordem decrescente"
                        }
                    },
                    "pagingType": "simple_numbers",
                    "scrollX": true,
                    "scrollCollapse": true,
                    "fixedHeader": true,
                    fixedColumns: {
                        leftColumns: 0,
                        rightColumns: 1
                    },
                    dom: "<'row'<'col-sm-6'B><'col-sm-6'f>>" + 'rtip',
                    buttons: [
                        {
                            "extend": 'colvis',
                            "text": '<i class="fas fa-columns"></i>',
                            "columns": ':not(.permanent)',
                            className: "colvis"
                        },
                        {
                            text: '<i class="fas fa-list-ol"></i>',
                            extend: "pageLength",
                            className: "show-entries"
                        },
                        {
                            text: "Software",
                            action: function (e, dt, button, config) {
                                $(".software-dropdown").toggle();
                            },
                            @*extend: 'collection',*@
                            className: "software-btn",
                        }

                    ],

                    // Defines the visibility of the column ID
                    "columnDefs": [
                        {
                            "targets": [0],
                            "visible": false,
                            "searchable": false
                        },
                        {
                            "targets": [6],
                            "width": "50px"
                        },
                        {
                            "targets": [0, 1, 2, 3, 4, 5],
                            "width": "250px"
                        }
                    ]

                });


                @*for ( i = 0; i < @Model.Rows.Count; i++) {  **This is the code to add the buttons**
                    $("#coreVersaoAPP-table").DataTable().button().add(
                        "-",
                        {
                            text: @Model.Rows[i][0],
                            action: function (e, dt, button, config) {
                                dt.columns(1).search(e.target.innerHTML).draw();
                            }
                        }
                    );
                }*@

            });

        </script>

        <script>
            document.addEventListener("DOMContentLoaded", () => {
                $(".software-list-items").click((e) => {
                    let name = e.target.innerHTML;
                    $("#coreVersaoAPP-table").DataTable().columns(1).search(name).draw();
                });
                $(".software-all").click((e) => {
                    let name = e.target.value;
                    $("#coreVersaoAPP-table").DataTable().columns(1).search("").draw();
                });
            });
        </script>

This is in MVC5. How can I make my button with the classname software-btn have a collection of dinamically added buttons? Do I have to specify which button I want the collection to be in? How can I do that?

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    I'm not quite following, but you can button().add() to add a button to a collection. If that doesn't help, we're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

  • baratafeyobaratafeyo Posts: 5Questions: 1Answers: 0

    I am having trouble creating a test case but what I want is to add buttons dinamically to a collection with button().add() but I don't know how to use it. Could you provide me with an example showing how to do this whith a collection because the example in the API doesn't show how to add buttons dinamically to a collection where the main button has index 2.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Here's an example demonstrating adding a button into the middle of a collection : http://live.datatables.net/sunofepu/1/edit . Hope that helps,

    Colin

  • baratafeyobaratafeyo Posts: 5Questions: 1Answers: 0

    Here's my piece of code that adds the button but no button appears in my button collection. I tried replicating the piece of code you showed me.

                    for ( i = 0; i < @Model.Rows.Count; i++) {
                        $("#coreVersaoAPP-table").DataTable().button().add(
                            '2-'+i,
                            {
                                text: @Model.Rows[i][0],
                                action: function (e, dt, button, config) {
                                    dt.columns(1).search(e.target.innerHTML).draw();
                                }
                            }
                        );
                    }
    

    My variable i is global. And I get the text from a query made to the database. The buttons don't even appear in my dropdown collection.

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    Your code, with a couple modifications, works here:
    http://live.datatables.net/sunofepu/2/edit

    Not sure what @Model.Rows is but the place to start is to debug your loop to see if its doing what you expect. Its hard to guess where the problem might be. If you need help with debugging please post a link to your page or a test case replicating the problem. Or update one of the above examples.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • baratafeyobaratafeyo Posts: 5Questions: 1Answers: 0

    It gives me the following error The name 'i' does not exist in the current context. @Model.Rows is an asp.net code. I don't think I can mix Javascript with Razor.
    I think that's why it works with you. You are not retrieving data from the database.

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974
    Answer ✓

    I'm not familiar with Razor. Are you trying to get a unique set of data from one of the columns? If so maybe the code in this example will help. Might be better to use Datatables API's to get the row data.

    Kevin

  • baratafeyobaratafeyo Posts: 5Questions: 1Answers: 0

    That helped but now I want to select all buttons in my collection where the main button has index 2 the set active equal to false so that the user knows which button he clicked on. How do I do it? Maybe with group selectors?

This discussion has been closed.