1

I have a lightning component which uses jquery datatables.User needs to filter the datatable using Stage picklist and date field.Based on the user selection(Stage and Date) then datatable needs to refresh with underlying data(oppty list) returned from the apex controller.

How to pass Selected Stage and Date to apex controller and refresh datatable with underlying data(oppty list) returned from the apex Controller.

Once table is refreshed then user selects checkboxes (opportunities) and then clicks on Update Opptys.

How to process Selected Opportunities in apex Controller.

enter image description here

    public with sharing class OpptyCtrl {

   @AuraEnabled
   public static list <Opportunity> fetchOpportunity(String stage,Date cDate) {
      list<Opportunity> oppList = new list<Opportunity>();

     if(stage !='') 
      oppList= [SELECT Id,Name,Type,StageName,Amount,CloseDate,Account.Name FROM Opportunity where StageName=:stage and CloseDate =:cDate  LIMIT 500];
      else
      oppList= [SELECT Id,Name,Type,StageName,Amount,CloseDate,Account.Name FROM Opportunity LIMIT 500];

       return oppList;
    }

   @AuraEnabled
    public static List<String> getStages(){
        List<String> options = new List<String>();
        Schema.DescribeFieldResult fieldResult = Opportunity.StageName.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry f : ple) {
            options.add(f.getLabel());
        }
        return options;
    } 

    @AuraEnabled
    public static void processSelectedOpptys(){

    }

}

({
    scriptsLoaded : function(component, event, helper) {
        console.log('Script loaded..'); 
    },

    doInit : function(component,event,helper){

        var action2 = component.get("c.getStages");
        var InputStage = component.find("InputStage");
        var opts=[];
        action2.setCallback(this, function(a) {
            opts.push({
                label: "--- None ---",
                value: ""
            });
            for(var i=0;i< a.getReturnValue().length;i++){
                opts.push({label: a.getReturnValue()[i], value: a.getReturnValue()[i]});
            }
            InputStage.set("v.options", opts);

        });
         $A.enqueueAction(action2); 

        //call apex class method
        var action = component.get('c.fetchOpportunity');
         action.setParams({
            stage : '',
        });
        action.setCallback(this, function(response) {
            //store state of response
            var state = response.getState();
            if (state === "SUCCESS") {
                //set response value in lstOpp attribute on component.
                component.set('v.lstOpp', response.getReturnValue());

                // when response successfully return from server then apply jQuery dataTable after 500 milisecond
                setTimeout(function(){ 
                   // $('#tableId').DataTable();
                    $('#tableId').DataTable({
                    "pageLength": 10,
                    "columnDefs": [ {
                    "targets": [0], 
                    "orderable": false  
                    }] ,
                    rowGroup: {
                    dataSrc: 2,
                   }
                }); 
                    // 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); 
    },

    onPicklistChange: function(component, event, helper) {
        //get the value of select option
        var selectedStage = component.find("InputStage");
        console.log(selectedStage.get("v.value"));
        var selectedDate = component.find("cdate");
         console.log(selectedDate.get("v.value"));
        var action = component.get('c.fetchOpportunity');
        console.log(action);


        action.setParams({
            stage : selectedStage.get("v.value"),
            cDate : selectedDate.get("v.value")
        });
        action.setCallback(this, function(response) {
            //store state of response
            var state = response.getState();
            if (state === "SUCCESS"){
                component.set('v.lstOpp', response.getReturnValue());
                console.log('response ##'+response.getReturnValue());
                setTimeout(function(){ 
                    $('#tableId').DataTable({
                    "pageLength": 10,
                    "columnDefs": [ {
                    "targets": [0], 
                    "orderable": false  
                    }] ,
                    rowGroup: {
                    dataSrc: 3,
                   }
                }); 
                    // 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); 
    },
            //Select all Leaf Jobs
    handleSelectAllOpp: function(component, event, helper) {
        var getID = component.get("v.lstOpp");
        var checkvalue = component.find("selectAll").get("v.value");        
        var checkOppty = component.find("checkOpp"); 
        if(checkvalue == true){
            for(var i=0; i<checkOppty.length; i++){
                checkOppty[i].set("v.value",true);
            }
        }
        else{ 
            for(var i=0; i<checkOppty.length; i++){
                checkOppty[i].set("v.value",false);
            }
        }
    },

    //Process the selected Opptys
    handleSelectedOpps: function(component, event, helper) {
        var selectedOpptys = [];
        var checkvalue = component.find("checkOpp");

        if(!Array.isArray(checkvalue)){
            if (checkvalue.get("v.value") == true) {
                selectedOpptys.push(checkvalue.get("v.text"));
            }
        }else{
            for (var i = 0; i < checkvalue.length; i++) {
                if (checkvalue[i].get("v.value") == true) {
                    selectedOpptys.push(checkvalue[i].get("v.text"));
                }
            }
        }
        console.log('selectedOpptys-' + selectedOpptys);
    }
})

<aura:component controller="OpptyCtrl" implements="force:appHostable">

   <ltng:require styles="{!join(',', $Resource.datatable + '/DataTables-1.10.16/media/css/jquery.dataTables.min.css',
                                      $Resource.datatable + '/DataTables-1.10.16/extensions/RowGroup/css/rowGroup.foundation.min.css')}" 
                  scripts="{!join(',', 
                           $Resource.jquery224 , 
                           $Resource.datatable + '/DataTables-1.10.16/media/js/jquery.dataTables.min.js' ,
                           $Resource.datatable + '/DataTables-1.10.16/extensions/RowGroup/js/dataTables.rowGroup.min.js')
                           }" afterScriptsLoaded="{!c.scriptsLoaded}"/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="isSelectAll" type="boolean" default="false"/>
    <aura:attribute name="lstOpp" type="opportunity[]"/>  


    <div class="slds-grid slds-grid_vertical  slds-size--1-of-8">
             <label class="slds-form-element__label" for="select-01">Select Stage</label> 
            <div class="slds-col slds-select">
                <ui:inputSelect aura:id="InputStage" change="{!c.onPicklistChange}"/> 
            </div>
            <div class="slds-col">
                Closed Date <ui:inputDate aura:id="cdate" class="field" value="{!v.today}" displayDatePicker="true" />  
            </div>

            <div class="slds-col">
                 <lightning:button label="Update Opptys" class="slds-button_brand" onclick="{!c.handleSelectedOpps}"  />
            </div>              
        </div>

    <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>           
                        <label class="slds-checkbox">
                            <ui:inputCheckbox value="{!v.isSelectAll}" change="{!c.handleSelectAllOpp}" aura:id="selectAll"/>
                            <span class="slds-checkbox--faux" />
                            <span class="slds-form-element__label"></span>
                        </label>
                    </th>
                    <th>Name</th>
                    <th>Account</th>
                    <th>Type</th>
                    <th>Stage</th>
                    <th>Amount</th>
                    <th>Close Date</th> 
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.lstOpp}" var="opp">
                    <tr>
                        <td>
                            <label class="slds-checkbox">
                                <ui:inputCheckbox aura:id="checkOpp" value="" text="{!opp.Id}"/>
                                <span class="slds-checkbox--faux" />
                                <span class="slds-form-element__label"></span>
                            </label>
                        </td>
                        <td>{!opp.Name}</td>
                        <td>{!opp.Account.Name}</td>
                        <td>{!opp.Type}</td>
                        <td>{!opp.StageName}</td>
                        <td>{!opp.Amount}</td>
                        <td>{!opp.CloseDate}</td>
                    </tr>
                </aura:iteration>  
            </tbody>
        </table>
    </div>
</aura:component>

<aura:application extends="force:slds">
    <c:opptyDataTable/>
</aura:application>

UPDATED

Updated but Row Grouping is not working.How do I get checkboxes against each record.

doInit : function(component,event,helper){

        var action2 = component.get("c.getStages");
        var InputStage = component.find("InputStage");
        var opts=[];
        action2.setCallback(this, function(a) {
            opts.push({
                label: "--- None ---",
                value: ""
            });
            for(var i=0;i< a.getReturnValue().length;i++){
                opts.push({label: a.getReturnValue()[i], value: a.getReturnValue()[i]});
            }
            InputStage.set("v.options", opts);

        });
         $A.enqueueAction(action2); 

        //call apex class method
        var action = component.get('c.fetchOpportunity');
         action.setParams({
            stage : '',
        });
        action.setCallback(this, function(response) {
            //store state of response
            var state = response.getState();
            if (state === "SUCCESS") {
                //set response value in lstOpp attribute on component.
                //component.set('v.lstOpp', response.getReturnValue());

                // when response successfully return from server then apply jQuery dataTable after 500 milisecond
                setTimeout(function(){ 
                   // $('#tableId').DataTable();
                    $('#tableId').DataTable({
                    "pageLength": 10,
                    "columnDefs": [ {
                    "targets": [0], 
                    "orderable": false  
                    }] ,
                        "data": response.getReturnValue(),
    "columns": [
        {
        "data": "Name", 
        "title": "Opportunity Name"
    }, {
        "data": "Account.Name", 
        "title": "Account"
    },{
        "data": "Type", 
        "title": "Type"
    },
     {
        "data": "StageName", 
        "title": "Stage"
    },
      {
        "data": "Amount", 
        "title": "Amount"
    },
       {
        "data": "CloseDate", 
        "title": "CloseDate"
     }          ],
                    rowGroup: {
                    dataSrc: 2,
                   }
                }); 
                    // 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); 
    },

enter image description here

1

I think what you're doing is adding some query filter to your page, then you want to refresh your DataTable with the underlying data returned from the Controller.

What you could do is change the way your table is initiated, specifying the data and columns as part of that. For example:

$('#tableId').DataTable({ "data": [{ "Name": "Burlington Textiles Weaving Plant Generator", "AccountName": "Burlington Textiles Corp of America" },{ "Name": "Edge Emergency Generator", "AccountName": "Edge Communications" }], "columns": [{ "data": "Name", "title": "Opportunity Name" }, { "data": "AccountName", "title": "Account Name" }] }

This way, you would remove your and its contents and just initialise the table with the data you've returned back from the controller. You'll not that the data array looks very similar to an array of SObjects so you wouldn't have much work to do there to format the data accordingly. The syntax supplied is from memory, but have a look here at the different data sources you can use. Should give you some idea.

  • Thanks @Phil Hawthorn. I tried to intialise datatable with data array and it displayed the data but how do i get checkboxes in datatable. – sfdc Oct 4 '18 at 16:42
  • @sfdc If that is a separate issue (it sounds like one, although this isn't my expertise), consider posting a new question. – David Reed Oct 4 '18 at 17:28
  • @DavidReed Its same issue. – sfdc Oct 4 '18 at 17:38
  • But it's not really what you asked in the first place. – Phil Hawthorn Oct 9 '18 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.