Wednesday, 2 March 2022

How to delete files from object by Apex

Delete files, Change related record of files / Attachments / ContentDocument/ ContentDocumenLink from object by Apex.

Here we will consider the examples of files on Account object. Actually we can not directly change the related record id on files. To change related id we have to follow below steps: 

1. First , files are stored in contentDocument object and linked with ContentDocumentLink object.

2. So if you want to update related record id then you must have to updatte ContentDocumentLink object.

3. But Related Object Id is stored in LinkedentityId field of ContentDocumentLink object and this field can not be overwritten. so we can not directly change related record Id.

4. Then to change related record id , we first need to delete record of ContentDocumentLink object then insert new record with same data with your new related record Id. 

Lets see steps below:

To fetch files , use below query

List<ContentDocumentLink> listContentLink = [Select Id,Linkedentity.name,LinkedentityId,ContentDocumentId from ContentDocumentLink Where LinkedentityId='0017F00001eFkvN'];  //LinkedentityId - is Account Id

List<ContentDocumentLink> listCloneData = new List<ContentDocumentLink>();

List<ContentDocumentLink> listDeleteData = new List<ContentDocumentLink>();

for(ContentDocumentLink objConDoc : listContentLink){

    ContentDocumentLink objCloneContentDoc = objConDoc.clone(); // Take clone of existing data

    objCloneContentDoc.LinkedentityId = '0017F00000yz5xpQAA'; // Assign new account record Id

    listCloneData.add(objCloneContentDoc); // add new data in clone list

    listDeleteData.add(objConDoc);

}

// First insert data 

if(!listCloneData.isEmpty()){

    insert listCloneData;

}

// Delete data

if(!listDeleteData.isEmpty()){

    delete listDeleteData;

}


File data of account object and needs to delete by apex.

Image 1: Account with File before delete


Account with File after delete

Image 2: Account with File after delete

Wednesday, 23 February 2022

Find duplicate element from a list in Salesforce Apex

Find duplicate element from a list in Salesforce Apex

How to find duplicate element from a list in Apex

Below are the  ways to find duplicate element:

1. Choose 'Set' instead of 'List' -- It prevents to add duplicate elements in list.

like we have a set of elements {2,1,5,7,6,5}

if we choose 'List':

List<Integer> listData = new List<Integer>{2,1,5,7,6,5};

then Output is : (2, 1, 5, 7, 6, 5)


If we choose 'Set':  :

Set<Integer> listData = new Set<Integer>(2, 1, 5, 7, 6, 5);

then Output is : (2, 1,7, 6, 5) -- Duplicates removed

2. Find duplicates by sorting of list elements : 

List<Integer> listData = new List<Integer>{2,1,5,7,6,5};
listData.sort();  // Sort the data - It sorts in ascending order
System.debug(listData);  // output is - (1, 2, 5, 5, 6, 7)

Integer elementPosition = listData.indexOf('5'); // Now you want to find duplicate of any '5' (you can check for any element) , then first find the index of that element

// below check if data on 'elementPosition' is equals to data on 'elementPosition+1' or 'elementPosition-1' , if found then there is duplicate element in list.

if(listData.get(elementPosition) == listData.get(elementPosition+1) ||                   listData.get(elementPosition) == listData.get(elementPosition+1))
{
    System.debug('Duplicate found')
}



    

Friday, 18 February 2022

Fetch the greatest/Max/Min date from the list

As we have scenario to fetch greater date value from the multiple objects like I have to find greatest createddate from 2-3 contacts data so that this date can be used further.  


Lets consider the scenario on contact objects.


List<DateTime> listCreatedDates = new List<DateTime>();
List<Contact> cons = [select id, CreatedDate from Contact limit 2];

For(Contact c : cons) {
    listCreatedDates.add(c.CreatedDate);
} listCreatedDates.sort(); DateTime minDate = listCreatedDates.get(0);
DateTime maxDate = listCreatedDates.get(listCreatedDates.size()-1);
System.debug('minDate : ' + minDate );
System.debug('maxDate : ' + maxDate );


Lets discuss about the above code:

Output for me - 
List<Contact> cons = [select id, CreatedDate from Contact limit 2];
Contact result to get minimum greatest, maximum and minimum date from the list by apex.


minDate : 2020-02-06 07:59:15
maxDate : 2020-07-18 13:23:36

Monday, 21 January 2019

Create Dual ListBox in Lightning Component

Create Dual ListBox in Lightning Component

Hey All!!!,I am going to show you that how you can create DualListBox using Salesforce Lightning Component

DualListbox component represents two side-by-side listboxes. Select one or more options in the list on the left. Move selected options in to the list at the right. The order of the selected options is maintained and you can reorder options.

Here I am taking account object and populating name fields values in to the duallistbox. You can assume any fields of any objects as per the requirements.

Here I am taking account object and populating name fields values in to the duallistbox. You can assume any fields of any objects as per the requirements.


Follow the below process step by step then you will be able to create Dual List Box:








Step 1:  Create Apex Controller DualListBoxCtrl.apex ” and use below code

public class DualListBoxCtrl {
    @AuraEnabled
        public static List<Account> getListValue(){
          List<Account> accName = [SELECT Id,Name FROM Account ORDER BY Account.Name ASC limit 500];
              if(accName != null && accName.size()>0){
                 return accName;
                 }
return accName; }
}




Step 2:  Create lightning component “DualListBox.cmp” and use below code.

<aura:component controller="DualListBoxCtrl">
<aura:attribute name="options" type="List" default="[]"/>
 <aura:attribute name="values" type="List" default="[]"/>
 <aura:handler name="init" value="{!this }" action="{!c.init }"/>

    <lightning:dualListbox name="multipleOptions"
                           label= "Accounts"
                           sourceLabel="Available Options"
                           selectedLabel="Selected Options"
                           options="{!v.options}"
                           value="{!v.values}"
                           onchange="{! c.handleChange }"
                           variant = "label-hidden"/>
</aura:component>



Step 3:  Create lightning Controller “DualListBoxController.js” and use below code.


({
     init: function (component, event, helper) {
     helper.getListHelper(component, event);
    },
    handleChange: function (component, event) { 

    // Get the selected values when user moves in to selected box.
    var valueList=component.get('v.values');
    console.log(JSON.stringify(valueList));
 }



Step 4:  Create lightning Helper “DualListBoxHelper.js” and use below code.

({
       getListHelper : function(component, event) {
       var action = component.get("c.getListValue");
       action.setCallback(this, function(a){
       var rtnValue = a.getReturnValue();
       component.set("v.values",rtnValue);
      
       var options = [];
       if(rtnValue.length>0){
               for(var i=0;i< rtnValue.length;i++){
                   options.push({ label: rtnValue[i].Name,value: rtnValue[i].Name});
                }
               console.log('options'+options.length);
               component.set("v.options",options);
         }           

 });


Dual list box using lightning aura component.
DualListBox


Wednesday, 18 April 2018

Open Lightning Modal With Progress Indicator Using Lightning Component

Here, I am displaying salesforce lightning modal with a progress indicator in footer using lightning component.

In this article, you will be able to open modal on click button and close the modal and add progress indicator in a footer.

Let's start process step by steps:



Step 1: Create lighting component 'ProgressIndicator.cmp' and use below code.



<aura:component >
    <aura:attribute name="showpage1" type="boolean" default="true"/>
    <aura:attribute name="showpage2" type="boolean" default="false"/>
    <aura:attribute name="showpage3" type="boolean" default="false"/>
    <aura:attribute name="openModal" type="boolean" default="false"/>
    <aura:attribute name="currentstep" type="String" default="step1"/>
    <lightning:button variant="brand" label="Open" onclick="{!c.openModal}" />
    <aura:if isTrue="{!v.openModal}">
        <div class="demo-only" style="height: 640px;">
            <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-slide-up-open">
                <div class="slds-modal__container">
                    <header class="slds-modal__header">
                        <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick="{!c.hideModal}">
                            <lightning:icon iconName="utility:close" size="small" alternativeText="Close"/>
                        </button>
                        <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Modal Header</h2>
                    </header>
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <aura:if isTrue="{!v.showpage1}">
                            <p>Step 1</p>
                        </aura:if>
                        <aura:if isTrue="{!v.showpage2}">
                            <p>Step 2</p>
                        </aura:if>
                        <aura:if isTrue="{!v.showpage3}">
                            <p>Step 3</p>
                        </aura:if>
                    </div>
                    <footer class="slds-modal__footer slds-modal__footer_directional">
                        <lightning:progressIndicator currentStep="{!v.currentstep}">
                            <lightning:progressStep label="Step 1" value="step1" onclick="{!c.page1}"/>
                            <lightning:progressStep label="Step 2" value="step2" onclick="{!c.page2}"/>
                            <lightning:progressStep label="Step 3" value="step3" onclick="{!c.page3}"/>
                        </lightning:progressIndicator>
                    </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
        </div>
    </aura:if>
</aura:component>


 Step 2: Create lighting component controller 'ProgressIndicatorController.js' and use this code.


({
     openModal : function(component, event, helper) {
        component.set("v.openModal",true);
    },
    page1 : function(component, event, helper) {
        component.set("v.showpage1",true);
        component.set("v.showpage2",false);
        component.set("v.showpage3",false);
        component.set("v.currentstep","step1");
       
            },
    page2 : function(component, event, helper) {
        component.set("v.showpage2",true);
        component.set("v.showpage1",false);
        component.set("v.showpage3",false);
        component.set("v.currentstep","step2");
            },
    page3 : function(component, event, helper) {
        component.set("v.currentstep","step3");
            component.set("v.showpage3",true);
        component.set("v.showpage2",false);
        component.set("v.showpage1",false);
            },
    hideModal: function(component, event, helper) {
        component.set("v.openModal",false);
    }
})

Step 3: Create lighting app for preview the components.

<aura:application >
    <c:ProgressIndicator/>
</aura:application>

Friday, 16 March 2018

Create Custom MultiSelect Picklist Using Lightning Component

MultiSelect In Salesforce Lightning Component

I am going to show to create custom multiselect component using salesforce lightning design system static HTML.
Here I am retrieving data from custom object in list and populate in options and making options multiselect.
Follow the below process step by step then you will be able to create multiselect picklist:


Step 1:  Create lightning component “MultiSelectComponent.cmp” and use below code.


<aura:component controller="ExpenseOptionsCtr">
    <aura:attribute name="lstExpenseData" type="Expense__c[]" />
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"></aura:handler>
          <c:QFMultiSelectUIComp options_="{!v.lstExpenseData}" />
</aura:component>

When you will save this code then it will fail to save because we didn’t create QFMultiSelectUIComp” till now. Before we create this component let we should create MultiSelectComponentController and MultiSelectComponentHelper . Now follow next step.

Step 2:  Create lightning component controller “MultiSelectComponentController.js” and use below code.


({
    doInit : function(component, event, helper) {
        helper.expenseDetails(component, event, helper);
    }
})

Step 3:  Create lightning component helper “MultiSelectComponentHelper.js” and use below code.



({
    expenseDetails : function(component, event, helper) {
        var action = component.get("c.getExpenseDetails"); //Calling Apex class controller 'getTemplateRecrod' method
        action.setCallback(this, function(res) {
            var state = res.getState();
            if (state === "SUCCESS") {
                 component.set("v.lstExpenseData", res.getReturnValue());
            } else {
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Error :",
                    "mode": "sticky",
                    "message": res.getError()[0].message
                });
                toastEvent.fire();
            }
        });
        $A.enqueueAction(action);               
    }
})



We defined the controller “ExpenseOptionsCtr” in component so now create controller .

Step 4:  Create apex controller “ExpenseOptionsCtr.apxc” , in this getting data from custom object Expense__c but you can use any object.


public class ExpenseOptionsCtr {
          @AuraEnabled
    public static List<Expense__c> getExpenseDetails(){
        List<Expense__c> lstExpense=[Select Id,Name From Expense__c];
        return lstExpense;
    }
}

Step 5:  Create lightning component “QFMultiSelectUIComp.cmp” and use below code.



<aura:component >
    <aura:attribute name="MultipleoptnId" type="object" />
    <aura:attribute name="options_" type="String[]" />
    <aura:attribute name="selectedItems" type="String[]" />
    <aura:attribute name="infoText" type="String" default="Select an option..." />
    <aura:attribute name="width" type="String" default="245px;" />
    <aura:attribute name="dropdownLength" type="Integer" default="4" />
    <aura:registerEvent name="selectChange" type="c:SelectChange" />
    <aura:method name="reInit" action="{!c.init}" description="Allows the lookup to be reinitalized">
    </aura:method>
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <aura:attribute name="dropdownOver" type="Boolean" default="false" />
    <div aura:id="main-div" class=" slds-picklist slds-dropdown-trigger slds-dropdown-trigger--click ">
        <button class="slds-button slds-button--neutral slds-picklist__label" style="{!'width:' + v.width }" aria-haspopup="true" onclick="{!c.handleClick}" onmouseleave="{!c.handleMouseOutButton}">
            <span class="slds-truncate" title="{!v.infoText}">{!v.infoText}</span>
            <lightning:icon iconName="utility:down" size="small" class="slds-icon" />
        </button>
        <div class="slds-dropdown slds-dropdown--left" onmouseenter="{!c.handleMouseEnter}" onmouseleave="{!c.handleMouseLeave}">
            <ul class="{!'slds-dropdown__list slds-dropdown--length-' + v.dropdownLength}" role="menu">
                <aura:iteration items="{!v.options_}" var="option">
                    <li class="{!'slds-dropdown__item ' + (option.selected ? 'slds-is-selected' : '')}" role="presentation" onclick="{!c.handleSelection}" data-value="{!option.Name}" data-selected="{!option.selected}">
                        <a href="javascript:void(0);" role="menuitemcheckbox" aria-checked="true" tabindex="0">
                            <span class="slds-truncate">
                                <lightning:icon iconName="utility:check" size="x-small" class="slds-icon slds-icon--selected slds-icon--x-small slds-icon-text-default slds-m-right--x-small" />
                                {!option.Name}
                            </span>
                        </a>
                    </li>
                </aura:iteration>
            </ul>
        </div>
    </div>
</aura:component>


Do not panic if your code is not getting save. Just follow the complete process
and save code in the last. It will save successfully.

Step 6:  Create lightning component controller “QFMultiSelectUICompController.js” 
and use below code.


({
    init: function(component, event, helper) {
        var values = helper.getSelectedValues(component);
        helper.setInfoText(component, values);
    },

    handleClick: function(component, event, helper) {
        var mainDiv = component.find('main-div');
        $A.util.addClass(mainDiv, 'slds-is-open');
    },

    handleSelection: function(component, event, helper) {
        var item = event.currentTarget;
        if (item && item.dataset) {
            var value = item.dataset.value;
            var selected = item.dataset.selected;
            var options = component.get("v.options_");


            //contro(ctrl) key ADDS to the list (unless clicking on a previously selected item)
            //also, ctrl key does not close the dropdown (uses mouse out to do that)
            if (event.ctrlKey) {
                options.forEach(function(element) {

                    if (element.Name === value) {
                        element.selected = selected === "true" ? false : true;
                    }
                });
            } else {
                options.forEach(function(element) {
                    if (element.Name === value) {
                        element.selected = selected === "true" ? false : true;
                    } else {
                        element.selected = false;
                    }
                });
                var mainDiv = component.find('main-div');
                $A.util.removeClass(mainDiv, 'slds-is-open');
            }
            component.set("v.options_", options);

            var values = helper.getSelectedValues(component);
            var labels = helper.getSelectedLabels(component);

            helper.setInfoText(component, labels);
            helper.despatchSelectChangeEvent(component, values);

        }
    },

    handleMouseLeave: function(component, event, helper) {
        component.set("v.dropdownOver", false);
        var mainDiv = component.find('main-div');
        $A.util.removeClass(mainDiv, 'slds-is-open');
    },

    handleMouseEnter: function(component, event, helper) {
        component.set("v.dropdownOver", true);
    },

    handleMouseOutButton: function(component, event, helper) {
        window.setTimeout(
            $A.getCallback(function() {
                if (component.isValid()) {
                    //if dropdown over, user has hovered over the dropdown, so don't close.
                    if (component.get("v.dropdownOver")) {
                        return;
                    }
                    var mainDiv = component.find('main-div');
                    $A.util.removeClass(mainDiv, 'slds-is-open');
                }
            }), 200
        );
    }
})

Step 7:  Create lightning component helper “MultiSelectComponentHelper.js” and 
use below code.



({
    setInfoText: function(component, labels) {
        if (labels.length === 0) {
            component.set("v.infoText", "Select an option...");
        }
        if (labels.length === 1) {
            component.set("v.infoText", labels[0]);
        }
        else if (labels.length > 1) {
            component.set("v.infoText", labels.length + " options selected");
        }
    },
   
    getSelectedValues: function(component){
        var options = component.get("v.options_");
        console.log('options:='+options);
        var values = [];
        if(options!==undefined){
            options.forEach(function(element) {
                if (element.selected) {
                    values.push(element.Name);
                }
            });
        }
        return values;
    },
   
    getSelectedLabels: function(component){
        var options = component.get("v.options_");
        var labels = [];
        if(options!==undefined){
            options.forEach(function(element) {
                if (element.selected) {
                    labels.push(element.Name);
                }
            }); 
        }
       
        return labels;
    },
   
    despatchSelectChangeEvent: function(component,values){
        var compEvent = component.getEvent("selectChange");
        compEvent.setParams({ "values": values });
        compEvent.fire();
    }
})

Now you will save the code but it will not save because we didn’t create event right now.

Let’s create event “SelectChange.evt”

Step 8:  Create lightning event “SelectChange.evt” and use below code.

<aura:event type="COMPONENT" description="Despatched when a select has changed value" >
  <aura:attribute name="values" type="String[]" description="Selected values" access="global" />
</aura:event>

Source :- https://www.girikon.com/blog/multiselect-in-salesforce-lightning-component/