0

i am displaying records with edit,view delete buttons in lightning component when i click on edit it's showing editable form with save button,here i have sequence number data type field with some value,if i edit and give sequence number something like 2 and click on save button it needs to check database if the same sequence number is exists to any of the record if exist show error like popup "sequence number is already exists do you want to replace".if not exists it's update simply.Please guide me i am pasting code Here

apex controller

@AuraEnabled
    public static void updateDocGroupWithSequence(string depId,integer sequenceNo,string docGroupId){
        List<Document_Group__c> docGroupList = [Select id,Name,Sequence__c,Department__r.name,Is_Protected__c,LastModifiedBy.Name,CreatedBy.Name
                                            from Document_Group__c where Department__c =:depId];
         boolean seqBoolean;

        if(docGroupList.size() > 0){
            seqBoolean = true; // if seqBoolean is true when running this method i want to show error popup with YES and NO buttons.
            for(Document_Group__c doc : docGroupList){

            }
        }else{
            Document_Group__c  doc = new Document_Group__c();
            doc.id =  docGroupId;
            doc.Sequence__c = sequenceNo;
            update doc;
        }
    }

Component

<aura:component controller="DocumentGroupSequencingCtrl"
                implements="force:appHostable,forceCommunity:availableForAllPageTypes,flexipage:availableForAllPageTypes"
                access="global">
    <aura:attribute name="displayNewAccount" type="Boolean" default="false"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" /> <!-- calling doInit method in Component Controller -->
    <!--<aura:handler event="c:NewClosedModalEvent" action="{!c.newClosedModal}"/> --> <!-- create event for closed modal.-->
    <aura:attribute name="accLst" type="SupplierNet_Department__c[]"/> <!-- create Array type Account variable-->
    <aura:attribute name="documentGroupLst" type="Document_Group__c[]"/>
    <aura:attribute name="ContentVersions" type="ContentVersion[]"/>
    <aura:attribute name="editAccId" type="id"/>
    <aura:attribute name="viewAccId" type="id"/>
    <aura:attribute name="isEdit" type="boolean"/>
    <aura:attribute name="isView" type="boolean"/>
    <article class="slds-card">
        <div class="slds-grid slds-grid_frame">
        <div class="slds-card__header slds-grid">
            <header class="slds-media slds-media_center slds-has-flexi-truncate">

            </header>
           <!-- <div class="slds-no-flex">
                <lightning:button label="New" onclick="{!c.showAccountModal}"/>
            </div>-->
        </div>
        <div class="slds-card__body">
            <table class="slds-table slds-table_bordered slds-no-row-hover slds-table_cell-buffer">
                <thead >
                    <tr class="slds-text-title_caps" style="background-color:#d9f2e6;" >
                        <th scope="col">
                            <div class="slds-truncate" title="Departments" style="background-color:#f5d6eb;">Departments</div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <aura:iteration items="{!v.accLst}" var="acc"> <!-- iteration account record.-->
                        <tr class="slds-hint-parent">
                            <th scope="row">
                      <div class="slds-truncate" title="Adam Choi" style="background-color:#d9f2e6;">
                         <a href="javascript:void(0);" onclick="{!c.Clicked}" data-value="{!acc.Id}">
                         {!acc.Name} 
                         </a>
                     </div>
                                <!--<div class="exampleHolder">
                                    <lightning:spinner aura:id="mySpinner" />
                                </div> -->
                            </th>
                        </tr>                     
                    </aura:iteration>
                </tbody>
            </table>
        </div>

            <div id="DocPanel" class="slds-card">

                <table class="slds-table slds-table_bordered slds-table_cell-buffer">
                    <thead>
                        <tr class="slds-text-title_caps">
                            <th scope="col">
                                <div class="slds-truncate" title="Group Name">Group Name</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Department Name">Department Name</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Is Protected">Is Protected</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Sequence">Sequence#</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Last Modified By">Last Modified By</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Created By">Created By</div>
                            </th>
                            <th scope="col">
                                <div class="slds-truncate" title="Action">Action</div>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                     <aura:iteration items="{!v.documentGroupLst}" var="con">
                          <tr>
                            <th scope="row" data-label="Opportunity Name">
                                <div class="slds-truncate" title="Name"><a href="javascript:void(0);" onclick="{!c.ClickedGroup}" data-value="{!con.Id}">{!con.Name}</a></div>
                            </th>
                            <td data-label="Account Name">
                                <div class="slds-truncate" title="Name">{!con.Department__r.Name}</div>
                            </td>
                            <td data-label="Close Date">
                                <div class="slds-truncate" title="protected">
                                    <ui:outputCheckbox aura:id="output" value="{!con.Is_Protected__c}"/>
                                </div>
                            </td>
                            <td data-label="Prospecting">
                                <div class="slds-truncate" title="Seq">{!con.Sequence__c}</div>
                            </td>
                            <td data-label="Confidence">
                                <div class="slds-truncate" title="Last">{!con.LastModifiedBy.Name}</div>
                            </td>
                            <td data-label="Amount">
                                <div class="slds-truncate" title="Create">{!con.CreatedBy.Name}</div>
                            </td>
                              <td>
                                  <button type="button" onclick="{!c.edit}" id="{!con.Id}">Edit</button>&nbsp;&nbsp;
                                  <button type="button" onclick="{!c.view}" id="{!con.Id}">View</button>&nbsp;&nbsp;
                                  <button type="button" onclick="{!c.delete}" id="{!con.Id}">Del</button>
                              </td>
                        </tr>
                      </aura:iteration>
                    </tbody>
                    <div>
                    </div>
                </table>
                <div>
                <aura:renderIf isTrue="{!v.isEdit}">
                    <center><ui:button label="Save" press="{!c.save}"/></center>
                    <force:recordEdit aura:id="edit" recordId="{!v.editAccId}"/>
                </aura:renderIf>

                <aura:renderIf isTrue="{!v.isView}">
                    <force:recordView aura:id="view" recordId="{!v.viewAccId}"/>
                </aura:renderIf>
                  </div>
            </div>
       </div>
        <footer class="slds-card__footer"><a href="javascript:void(0);"></a></footer>
    </article>

    <aura:if isTrue="{!v.displayNewAccount}">
        <!--<c:Salesforceadda_NewAccount /> --> <!-- this is another component and contains popup and there fields to save account info -->
    </aura:if>
</aura:component>

controller.Js

({
    doInit : function(component, event, helper) {
        helper.getSupplierNetRecordsRecord(component); // Calling Helper method on load
    },
    showAccountModal : function(component,event,helper){
        component.set("v.displayNewAccount",true); // calls to show popup
    },
    newClosedModal:function(component,event,helper){
        component.set("v.displayNewAccount",false);
        helper.getAccontRecord(component); // Calling Helper method to display record after record save from popup
    },

    passid:function(component,event,helper){
        var id = event.getSource().get("v.value");
        //alert(event.currentTarget.value);
        //alert(id);
    },
    Clicked : function(component, event, helper){
        var ctarget = event.currentTarget;
        var id_str = ctarget.dataset.value;
        console.log(id_str);

        var action = component.get("c.getDocumentGroupRecords");
        action.setParams({ depId :  id_str});
        action.setCallback(this, function(response) {
            var state = response.getState(); //Checking response status
            console.log("contactsss... "+JSON.stringify(response.getReturnValue()));
            if (component.isValid() && state === "SUCCESS")
                component.set("v.documentGroupLst", response.getReturnValue());  // Adding values in Aura attribute variable.   
        });
        $A.enqueueAction(action);
    },
    ClickedGroup : function(component, event, helper){
        var ctarget = event.currentTarget;
        var id_str = ctarget.dataset.value;
        console.log(id_str);

        var action = component.get("c.LoadDocumentsByDepartMent");
        action.setParams({ depId :  id_str});
        action.setCallback(this, function(response) {
            var state = response.getState(); //Checking response status
            console.log("contactsss... "+JSON.stringify(response.getReturnValue()));
            if (component.isValid() && state === "SUCCESS")
                component.set("v.ContentVersions", response.getReturnValue());  // Adding values in Aura attribute variable.   
        });
        $A.enqueueAction(action);
    },
    save : function(component, event, helper) {
        try {
            component.find("edit").get("e.recordSave").fire();
        }catch (e) {
            console.log(e);
        }
        location.reload();// This will refresh the app to get the latest updated data.        
    },
    edit : function(component, event, helper) {
        component.set("v.isView",false);
        component.set("v.isEdit",true);
        console.log('Edit record ID..'+event.target.id);
        component.set("v.editAccId",event.target.id);
        component.set("v.viewAccId",event.target.id);
    },

    view : function(component, event, helper) {
        component.set("v.isEdit",false);
        component.set("v.viewAccId",event.target.id);
        component.set("v.isView",true);

    },

    delete : function(component, event, helper) {        
    if(confirm('Are you sure?'))
    helper.deleteAccount(component, event);        
    },
     toggle: function (cmp, event) {
        var spinner = cmp.find("mySpinner");
        $A.util.toggleClass(spinner, "slds-hide");
    }

})

1 Answer 1

2

You need to split up the class code into 2 Aura methods - one to check if duplicate exists, other one to update record when the user has confirmed a replace or there exists no record with same sequence

@AuraEnabled
public static boolean checkIfSequenceNumberExists(string depId,integer sequenceNo,string docGroupId){

    List<Document_Group__c> docGroupList = new List<Document_Group__c>([SELECT id,Name,Sequence__c,Department__r.name,Is_Protected__c,LastModifiedBy.Name,CreatedBy.Name
                                                                        FROM Document_Group__c where Department__c =:depId]);

    return (docGroupList.size() > 0) ? true : false;    
}

@AuraEnabled
public static void updateDocGroupWithSequence(string depId,integer sequenceNo,string docGroupId){

    Document_Group__c objDocumentGroup = new Document_Group__c([SELECT Id,Sequence__c FROM Document_Group__c WHERE Department__c =:depId LIMIT 1]);
    if(objDocumentGroup != null){   

        objDocumentGroup.id =  docGroupId;
        objDocumentGroup.Sequence__c = sequenceNo;
        update objDocumentGroup;
    }
}

In (Helper.js) js within setCallback() you can check for the value of the boolean returned and perform action accordingly

var action = component.get("c.checkIfSequenceNumberExists");
action.setParams({<set all your params here>}); //set all parameters and values here
action.setCallback(this, function(response){

    var state = response.getState();            
    if (component.isValid() && state === "SUCCESS"){

        var doesSequenceExist = response.getReturnValue();
        if(doesSequenceExist){

            //code here to show the confirm box
            var isConfirmed = confirm("Sequence number already exists. Do you want to replace?");
            if(isConfirmed){            

                //code to execute when yes button is clicked, in your case it should be call to "updateDocGroupWithSequence" for update
            }else{

                //code to execute when cancel button is clicked
            }
        }   
    }
});
$A.enqueueAction(action);

I have used javascript confirm box here. You can use a custom modal to enhance user experience.

13
  • A bot nitpicky but this return (docGroupList.size() > 0) ? true : false; can be shortened to this return docGroupList.size() > 0; - Apologies but code for the sake of using the keyboard is a pet peeve :) Otherwise, thanks for taking the time to answer the OP's question
    – Eric
    Commented Oct 14, 2017 at 14:46
  • Hi Sikha Baid, In apex controller side i did some thing because i am good in apex but in javascript i am literally poor i know it's not fair to ask you give some more deatil code.here i am not using helper.Js here is my apex controller methods as you provided and modified bit as per my requirement
    – Sfdc
    Commented Oct 14, 2017 at 15:51
  • where do you call your action method? Controller.js? If so you can go ahead using that but not really advisable. Controller.js are for delegating to helper.js. Helper.js should ideally have all the business logic.
    – Sikha Baid
    Commented Oct 14, 2017 at 15:55
  • action.setParams({<set all your params here>}); //set all parameters and values here (here i got confused..........)
    – Sfdc
    Commented Oct 14, 2017 at 15:58
  • can i use your js code in helper like this validateSeuencehelper : function( component ) { // your js code in this Js function }
    – Sfdc
    Commented Oct 14, 2017 at 16:03

You must log in to answer this question.

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