0

I'm trying to use Jquery data table and want to know how to fetch the selected values from the data table. On select of the row the count should be updated. Refernce i'm using is https://www.gyrocode.com/projects/jquery-datatables-checkboxes

here is the code I tried. Currently i'm checking on click of button , but I will change to onclick of checkbox.

 cmp
 <aura:component controller="jQueryDataTableCtrl">
   <ltng:require styles="{!join(',',
                       $Resource.FrameworkBase_CF + '/css/datatables.min.css',
                       $Resource.FrameworkBase_CF + '/css/dataTables.checkboxes.css')
                       }"
              scripts="{!join(',',
                       $Resource.FrameworkBase_CF + '/js/jquery-3.2.1.min.js',
                       $Resource.FrameworkBase_CF + '/js/datatables.min.js',
                       $Resource.FrameworkBase_CF + '/js/dataTables.checkboxes.min.js')
                       }" afterScriptsLoaded="{!c.scriptsLoaded}"/>

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

<aura:attribute name="lstOpp" type="opportunity[]"/>

<div class="slds-m-around_medium">
    <lightning:button variant="brand" label="Get Selected" title="Brand action" onclick="{! c.handleClick }" />
    <table id="tableId" class="slds-table slds-table_bordered slds-table_cell-buffer" cellspacing="0" width="100%">
        <thead>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Type</th>
            <th>Stage</th>
            <th>Amount</th>
            <th>Close Date</th>
        </tr>
        </thead>
        <tbody>
        <aura:iteration items="{!v.lstOpp}" var="acc">
            <tr>
                <td></td>
                <td>{!acc.Name}</td>
                <td>{!acc.Type}</td>
                <td>{!acc.StageName}</td>
                <td>{!acc.Amount}</td>
                <td>{!acc.CloseDate}</td>
            </tr>
        </aura:iteration>
        </tbody>
    </table>
</div>
</aura:component>

Js file:

 ({
    
        doInit: function (component, event, helper) {
    
        },
    
        scriptsLoaded: function (component, event, helper) {
            
            const action = component.get('c.fetchOpportunity');
            action.setCallback(this, function (response) {
    
                var state = response.getState();
                if (state === "SUCCESS") {
                    //set response value in lstOpp attribute on component.
                    component.set('v.lstOpp', response.getReturnValue());
                    setTimeout(function () {
                        helper.table = $('#tableId').DataTable({
                                'columnDefs': [
                                    { 'targets': 0, 'checkboxes': true }
                                ]
                            }
                        );
                        $('#tableId tbody').on( 'click', 'input', function () {
                            $(this).toggleClass('selected');
                        } );
                        // add lightning class to search filter field with some bottom margin..
                        $('div.dataTables_filter input').addClass('slds-input');
                        $('div.dataTables_filter input').css("marginBottom", "10px");
                    }, 500);
                }
            });
            $A.enqueueAction(action);
        },
        handleClick : function (component, event, helper){
            console.log('=====table======',helper.table);
            var count = helper.table.rows( { selected: true } ).count();
            console.log('===count=====',count);
        }
    })

Helper:

({
    table : '',
    helperMethod : function() {
        
    }
})

Apex:

public with sharing class jQueryDataTableCtrl {
@AuraEnabled
   public static list <Opportunity> fetchOpportunity() {
      Return [SELECT Name,Type,StageName,Amount,CloseDate FROM Opportunity LIMIT 30];
          
    }
}

Thanks in advance

0

1 Answer 1

1

As you have used jquery and datatable, use that throughout. Dont mix Aura and jquery+datatable

Change your aura:iteration to allow first column to have Id also change your query to [SELECT Id, Name,Type,StageName,Amount,CloseDate FROM Opportunity LIMIT 30];

        <aura:iteration items="{!v.lstOpp}" var="acc">
            <tr>
                <td>{!acc.Id}</td>
                <td>{!acc.Name}</td>
                <td>{!acc.Type}</td>
                <td>{!acc.StageName}</td>
                <td>{!acc.Amount}</td>
                <td>{!acc.CloseDate}</td>
            </tr>
        </aura:iteration>

Have a button as <lightning:button label="FetchSelectedRow" onclick="{!c.fetchSelectedRowFromTable}"/>

Change your SetTimeout to :

            setTimeout(function () {
                $('#tableId').DataTable({
                        'columnDefs': [
                            {
                                'targets': 0, 'checkboxes': true
                            }
                        ]
                    }
                );

and add this to controller fetchSelectedRowFromTable:

fetchSelectedRowFromTable: function (component, event, helper) {
    // WIll give you array of OpportunityId which is selected.
    let selectedIdArray = $('#tableId').DataTable().column(0).checkboxes.selected();
}

then you can work with Ids.

For full code:

CMP:

<aura:component controller="AwSnap" implements="force:appHostable,flexipage:availableForAllPageTypes,
flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride" access="global">
    <ltng:require styles="{!join(',',
                           $Resource.FrameworkBase_CF + '/css/datatables.min.css',
                           $Resource.FrameworkBase_CF + '/css/dataTables.checkboxes.css')
                           }"
                  scripts="{!join(',',
                           $Resource.FrameworkBase_CF + '/js/jquery-3.2.1.min.js',
                           $Resource.FrameworkBase_CF + '/js/datatables.min.js',
                           $Resource.FrameworkBase_CF + '/js/dataTables.checkboxes.min.js')
                           }" afterScriptsLoaded="{!c.scriptsLoaded}"/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <aura:attribute name="lstOpp" type="opportunity[]"/>

    <div class="slds-m-around_medium">
        <table id="tableId" class="slds-table slds-table_bordered slds-table_cell-buffer" cellspacing="0" width="100%">
            <thead>
            <tr>
                <th></th>
                <th>Name</th>
                <th>Type</th>
                <th>Stage</th>
                <th>Amount</th>
                <th>Close Date</th>
            </tr>
            </thead>
            <tbody>
            <aura:iteration items="{!v.lstOpp}" var="acc">
                <tr>
                    <td>{!acc.Id}</td>
                    <td>{!acc.Name}</td>
                    <td>{!acc.Type}</td>
                    <td>{!acc.StageName}</td>
                    <td>{!acc.Amount}</td>
                    <td>{!acc.CloseDate}</td>
                </tr>
            </aura:iteration>
            </tbody>
        </table>
    </div>

    <lightning:button label="FetchSelectedRow" onclick="{!c.fetchSelectedRowFromTable}"/>
</aura:component>

Controller ::

doInit: function (component, event, helper) {

},

scriptsLoaded: function (component, event, helper) {
    const action = component.get('c.fetchOpportunity');
    action.setCallback(this, function (response) {

        var state = response.getState();
        if (state === "SUCCESS") {
            //set response value in lstOpp attribute on component.
            component.set('v.lstOpp', response.getReturnValue());
            setTimeout(function () {
                $('#tableId').DataTable({
                        'columnDefs': [
                            {
                                'targets': 0, 'checkboxes': {
                                    'selectRow': true
                                }
                            }
                        ]
                    }
                );
                // add lightning class to search filter field with some bottom margin..
                $('div.dataTables_filter input').addClass('slds-input');
                $('div.dataTables_filter input').css("marginBottom", "10px");
            }, 500);
        }
    });
    $A.enqueueAction(action);
},

fetchSelectedRowFromTable: function (component, event, helper) {
    // WIll give you array of OpportunityId which is selected.
    let selectedIdArray = $('#tableId').DataTable().column(0).checkboxes.selected();
}

Class:

@AuraEnabled
public static list <Opportunity> fetchOpportunity() {
    Return [SELECT Id, Name,Type,StageName,Amount,CloseDate FROM Opportunity LIMIT 30];

}
4
  • after these changes , now I no longer can select the check box, it is not allowing to check
    – shaan
    Commented Nov 30, 2020 at 6:08
  • That is highly unlikey, as suggested earlier, do your logic inside scriptsLoaded and not in doInit. I have update full code, just check if you have missed anything. FYI, above code works fine. Commented Nov 30, 2020 at 6:13
  • After I changed this, component is not working { 'targets': 0, 'checkboxes': { 'selectRow': true } } , so , I suspect the static resource file is not same as you have,
    – shaan
    Commented Nov 30, 2020 at 6:33
  • I am using datatable version ` DataTables 1.10.20` and Jquery 3.2.1 and Datatable checkbox (Gyro) version v1.2.12, also replace that with 'checkboxes': true Commented Nov 30, 2020 at 6:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .