Monday, 26 October 2020

Date Format in lightning Component dd-mmm-yy (22-OCT-2020)



var monthNames = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN",

"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"

];


var date = new Date('01-JAN-2016')

date.setDate(date.getDate() - 1)

date = date.getDate()+"-"+monthNames[date.getMonth()]+"-"+date.getFullYear()


console.log(date)

Thursday, 10 September 2020

correct mime type for docx, pptx etc?

 

Extension MIME Type
.doc      application/msword
.dot      application/msword

.docx     application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx     application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm     application/vnd.ms-word.document.macroEnabled.12
.dotm     application/vnd.ms-word.template.macroEnabled.12

.xls      application/vnd.ms-excel
.xlt      application/vnd.ms-excel
.xla      application/vnd.ms-excel

.xlsx     application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx     application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm     application/vnd.ms-excel.sheet.macroEnabled.12
.xltm     application/vnd.ms-excel.template.macroEnabled.12
.xlam     application/vnd.ms-excel.addin.macroEnabled.12
.xlsb     application/vnd.ms-excel.sheet.binary.macroEnabled.12

.ppt      application/vnd.ms-powerpoint
.pot      application/vnd.ms-powerpoint
.pps      application/vnd.ms-powerpoint
.ppa      application/vnd.ms-powerpoint

.pptx     application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx     application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx     application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam     application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm     application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm     application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm     application/vnd.ms-powerpoint.slideshow.macroEnabled.12

.mdb      application/vnd.ms-access

Friday, 7 August 2020

Get Database.SaveResult error and sucesses list

 

To get the Error for Database.update which can be used in Classes

if (accountstoUpd.size() > 0) {

Database.SaveResult[] lsr = Database.update(accountstoUpd,false);

Integer recordid = 0;

for (Database.SaveResult SR : lsr) {

if (!SR.isSuccess()) {

this.errormsgs += 'Account Record:' + accountstoUpd[recordid].id + ', ' + SR.getErrors()[0].getMessage() + '<br/>';

}

recordid++;

}

}

if (this.errormsgs.length() > 0) {

ErrorLogs__c errtoSave = new ErrorLogs__c(details__c = this.errormsgs);

insert errtoSave;

}

Thursday, 6 August 2020

Logout from Community Portal using apex


Please use below code to redirect to community login page :

window.location.replace("<community-domain>/secur/logout.jsp?retUrl=<redirect-URL>");

Eg: 

1)  window.location.replace("/testPortal/secur/logout.jsp?retUrl=%2Flogin");

2)  window.location.replace("https://mycommunity-domain.com/secur/logout.jsp?retUrl=https%3A%2F%2Fmycommunity-domain.com%2Flogin");

Monday, 29 June 2020

Internal Refresh on component when event occurs


Scenario: In the lightning Layout details page will be standard page and besides, we have custom components. when the status is changed in standard layout then component should be refreshed.

used the below code in the Lightning component.

<aura:dependency resource="markup://force:editRecord" type="EVENT" />
<aura:handler event="force:refreshView" action="{!c.doInit}" />

Wednesday, 15 April 2020

Get Parent Record Id From Lightning URL



In component Create an attribute.

<aura:attribute name="recordId" type="String"/>


In Init method use the below code to get parent record Id from Related list.

        var pageRef = component.get("v.pageReference");      
        console.log(JSON.stringify(pageRef));      
        var state = pageRef.state; // state holds any query params      
        console.log('state = '+JSON.stringify(state));      
        var base64Context = state.inContextOfRef;      
        console.log('base64Context = '+base64Context);      
        if (base64Context.startsWith("1\.")) {          
            base64Context = base64Context.substring(2);          
            console.log('base64Context = '+base64Context);      
        }      
        var addressableContext = JSON.parse(window.atob(base64Context));      
        console.log('addressableContext = '+JSON.stringify(addressableContext));
        component.set("v.recordId", addressableContext.attributes.recordId);
        console.log('rec Id---'+component.get("v.recordId"));

reference : https://sfdclesson.com/2019/11/23/get-parent-record-id-from-lightning-url/


Thursday, 9 April 2020

Disable right-click in Salesforce Lightning Page



component add this:

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

In JS file add this in doInit:

doInit : function(component, event, helper) {
       document.addEventListener('contextmenu', event => event.preventDefault());

},

Tuesday, 7 April 2020

Download any video from Google Chrome


Follow the below steps on your computer/laptop in chrome (recommended).
  1. Login to udemy go to the course and play the lecture, for eg. first lecture is running
  2. Open ‘Developer tools’ by pressing ‘F12’ go to the ‘sources’ tab
  3. Switch to ‘Snippets’ tab
  4. Add new snippet with any name for eg. ‘udemy-downloader
  5. and paste the code below

    1. var videoLink = document.querySelector(".vjs-tech").getAttribute('src');
    2. window.open(videoLink,'_blank');
  6. Save the snippet file using ‘ctrl+s
  7. And now Right click on the snippet file (udemy-downloader) which have the scripts and click on Run
    It will download the video for you in selected Quality - (on which it is playing)
  8. Now you only need to follow step number to download your favorite lecture.

    Hope this is helpful :)

Tuesday, 3 March 2020

Navigating One Component to another component in customer Community using lightning components


To Achieve this we need to used forceCommunity:availableForAllPageTypes, and  lightning:isUrlAddressable

step 1:
Create a page in the lightning Community

steps:
Goto setup > All communities > select your community > Builder > on the top left you will find home > click on the drop-down > at the bottom of the drop-down you will find New page > click and create the new page (ex: page name - sample).

Once created click on 3 dots to see properties > take URL name.

step 2:
Component Name: component1.cmp

<aura:component implements="forceCommunity:availableForAllPageTypes,lightning:isUrlAddressable" access="global" > 
    <lightning:navigation aura:id="navService"/>
    <aura:attribute name="parameter" type="String" />
   
    <lightning:button label="Navigate" onclick="{!c.navigateToComTwo}"/>
   
</aura:component>

Component Controller JS: component1Controller.js

({ 
   
    navigateToComTwo : function(component, event, helper) { 
       
        component.set("v.parameter","I am from comp 1");
        var urlEvent = $A.get("e.force:navigateToURL");
        urlEvent.setParams({
                    // "/(pagename from community)?(name to pass parameter)="+(concatinate with values)
            "url": "/sample?param="+component.get("v.parameter"),
            "isredirect" :true
        });
        urlEvent.fire();
    } 
   
})

step 3:
Component Name: component2.cmp

<aura:component implements="forceCommunity:availableForAllPageTypes,lightning:isUrlAddressable" access="global" > 
     
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="Receivedparameter" type="String" />
     
    <div class="slds-box slds-theme_default">
        This is component two. {!v.Receivedparameter}
    </div> 
     
</aura:component>

Component Controller JS: component2Controller.js

({ 
   
    doInit : function( component, event, helper ) { 
       
        var url_string = window.location.href;
        var url = new URL(url_string);
        var urlparameter = url.searchParams.get("param");
        console.log('myPageRef---'+urlparameter);
       
        component.set("v.Receivedparameter",urlparameter);
    } 
   
})


Thursday, 27 February 2020

Expand/Collapsible complete table row in lightning component



Copy paste this code as it is you can get the view, later you can change this per your Requirement.

Component code:

<aura:component controller="AccountsController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
 
    <aura:attribute name="items" type="Object[]" default="[]" />
    <aura:attribute name="idvalue" type="String" />
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
 
    <table>
        <tr>
            <th >Detail</th>
            <th >Origin</th>
            <th >Destination</th>
            <th ># of Trips Per Week</th>
            <th >Minimum Charge</th>
            <th >Awarded?</th>
            <th >Detail</th>
            <th >Origin</th>
            <th >Destination</th>
            <th ># of Trips Per Week</th>
        </tr>
     
     
        <aura:iteration items="{!v.items}" var="item" indexVar="itemIndex">
            <tr>
                <td scope="row" >
                    <div >
                        <lightning:buttonIcon value="{!itemIndex}" onclick="{!c.toggle}" iconName="{!item.expanded?'utility:chevrondown':'utility:chevronright'}" />
                    </div>
                </td>             
                <td scope="row">
                    <div class="slds-cell-wrap" >{!item.Name}</div>
                </td>
                <td scope="row">
                    <div class="slds-cell-wrap">{!item.Name}</div>
                </td>             
                <td scope="row">
                    <div class="slds-cell-wrap">{!item.Name}</div>
                </td>
                <td scope="row">
                    <div class="slds-cell-wrap">{!item.Name}</div>
                </td>
                <td scope="row" >
                    <div class="slds-cell-wrap">{!item.Name}</div>
                </td> 
                <td scope="row" >
                    <div class="slds-cell-wrap">{!item.Name}</div>
                </td>
                <td scope="row" >
                    <div class="slds-cell-wrap">{!item.Name}</div>
                </td>
                <td scope="row" >
                    <div class="slds-cell-wrap">{!item.Name}</div>
                </td>
                <td scope="row" >
                    <div class="slds-cell-wrap">{!item.Name}</div>
                </td>
            </tr>
         
            <aura:if isTrue="{!item.expanded}" >
                <tr>
                    <td colspan="10">
                        <section style="border-style: outset;  border-width: thin;">
                            <div class="row">
                                <div class="column">
                                    <h2><b>Address</b></h2>
                                    <aura:if isTrue="{!not(empty(item.Title))}">
                                        <p>{!item.Name}</p>
                                        <aura:set attribute="else">
                                            &nbsp;
                                        </aura:set>
                                    </aura:if>
                                    <hr class="hrline"/>
                                    <h2><b>ASN Quantity</b></h2>
                                    <aura:if isTrue="{!not(empty(item.Name))}">
                                        <p>{!item.Name}</p>
                                        <aura:set attribute="else">
                                            &nbsp;
                                        </aura:set>
                                    </aura:if>
                                    <hr class="hrline"/>
                                    <h2><b>Sales Order Quantity</b></h2>
                                    <aura:if isTrue="{!not(empty(item.Name))}">
                                        <p>{!item.Name}</p>
                                        <aura:set attribute="else">
                                            &nbsp;
                                        </aura:set>
                                    </aura:if>
                                    <hr class="hrline"/>
                                    <h2><b>Original Quantity</b></h2>
                                    <aura:if isTrue="{!not(empty(item.Name))}">
                                        <p>{!item.Name}</p>
                                        <aura:set attribute="else">
                                            &nbsp;
                                        </aura:set>
                                    </aura:if>
                                    <hr class="hrline"/>
                                    <h2><b>Cancelled Quantity</b></h2>
                                    <aura:if isTrue="{!not(empty(item.Name))}">
                                        <p>{!item.Name}</p>
                                        <aura:set attribute="else">
                                            &nbsp;
                                        </aura:set>
                                    </aura:if>
                                    <hr class="hrline"/>
                                    <h2><b>Return sales Order number</b></h2>
                                    <aura:if isTrue="{!not(empty(item.Name))}">
                                        <p>{!item.Name}</p>
                                        <aura:set attribute="else">
                                            &nbsp;
                                        </aura:set>
                                    </aura:if>
                                    <hr class="hrline"/>
                                    <h2><b>Original Sales Order Number</b></h2>
                                    <aura:if isTrue="{!not(empty(item.Name))}">
                                        <p>{!item.Name}</p>
                                        <aura:set attribute="else">
                                            &nbsp;
                                        </aura:set>
                                    </aura:if>
                                    <hr class="hrline"/>
                                </div>
                                <div class="column">
                                    <h2><b>Unit</b></h2>
                                    <p>{!item.Name}</p>
                                    <hr class="hrline"/>
                                    <h2><b>Unit Price</b></h2>
                                    <p>{!item.Name}</p>
                                    <hr class="hrline"/>
                                    <h2><b>Discount Amount</b></h2>
                                    <p>{!item.Name}</p>
                                    <hr class="hrline"/>
                                    <h2><b>Net Amount</b></h2>
                                    <p>{!item.Name}</p>
                                    <hr class="hrline"/>
                                    <h2><b>Open Ext Amount</b></h2>
                                    <p>{!item.Name}</p>
                                    <hr class="hrline"/>
                                    <h2><b>Purchase Unit Price</b></h2>
                                    <p>{!item.Name}</p>
                                    <hr class="hrline"/>
                                    <h2><b>Kit Item</b></h2>
                                    <p>{!item.Name}</p>
                                    <hr class="hrline"/>
                                </div>
                                <div class="column">
                                    <h2><b>Revenue share Vender</b></h2>
                                    <p>{!item.Name}</p>
                                    <hr class="hrline"/>
                                </div>
                                <div class="column">
                                    <h2><b>FullFiller hours of Operation</b></h2>
                                    <p>{!item.Name}</p>
                                    <hr class="hrline"/>
                                </div>
                             
                            </div>
                        </section>
                        <section style="border-style: outset;  border-width: thin;">
                            <div class="row">
                                <div class="column">
                                    <h2><b>Column 1.1</b></h2> 
                                    <p>Some text..</p>
                                    <hr class="hrline"/>
                                 
                                </div>
                                <div class="column">
                                    <h2><b>Column 2.1</b></h2>
                                    <p>Some text..</p>
                                    <hr class="hrline"/>
                                </div>
                                <div class="column">
                                    <h2><b>Column 3.1</b></h2>
                                    <p>Some text..</p>
                                    <hr class="hrline"/>
                                </div>
                                <div class="column">
                                    <h2><b>Column 4.1</b></h2>
                                    <p>Some text..</p>
                                    <hr class="hrline"/>
                                </div>
                             
                            </div>
                        </section>
                        <section style="border-style: outset;  border-width: thin;">
                            <div class="row">
                                <div class="column">
                                    <h2>Column 1.1</h2>
                                    <p>Some text..</p>
                                    <hr class="hrline"/>
                                </div>
                                <div class="column">
                                    <h2>Column 2.1</h2>
                                    <p>Some text..</p>
                                    <hr class="hrline"/>
                                </div>
                                <div class="column">
                                    <h2>Column 3.1</h2>
                                    <p>Some text..</p>
                                    <hr class="hrline"/>
                                </div>
                                <div class="column">
                                    <h2>Column 4.1</h2>
                                    <p>Some text..</p>
                                    <hr class="hrline"/>
                                </div>
                            </div>
                        </section>
                    </td>
                </tr>
            </aura:if>
        </aura:iteration>
    </table>
</aura:component>

Controller JS:

({
init : function(component, event, helper) {
var currentOrderId = component.get("v.recordId");
        var action = component.get("c.getAccounts");
     
        //action.setParams({ ADSRecId : "a0o4F000000QwVUQA0" });
     
        action.setCallback(this, function(response) {
        var state = response.getState();
            //alert(state);
            if (state === "SUCCESS") {
             
                var Responsedata = response.getReturnValue();
                //alert('Responsedata--'+JSON.stringify(Responsedata));
                component.set("v.items", response.getReturnValue());
             
            }
        });
                         
        $A.enqueueAction(action);
},
 
    toggle: function(component, event, helper) {
        var items = component.get("v.items"), index = event.getSource().get("v.value");
        items[index].expanded = !items[index].expanded;
        component.set("v.items", items);
    }
 
})


Styles:

.THIS table, .THIS th, .THIS td {
    border: 1px solid black;
    text-align: center;
    width: 5%;
}
.THIS th{
    font-weight: bold;
    color: black;
 
}
.THIS h2{
    color: black;
    text-align: left;
}
.THIS p{
    color: black;
    text-align: left;
}
.THIS .column {
    float: Left;
    width: 25%;
    padding: 10px;
    height: 315px;
}
.THIS .row:after {
    content: "";
    display: table;
    clear: both;
}
.THIS .hrline {
    margin-top: 1px;
    margin-bottom: 1px;
    width: 60%;
}


Apex Class:

public class AccountsController {
      @AuraEnabled
      public static List <Account> getAccounts() {
        return [SELECT Id, name, industry, Type, NumberOfEmployees, TickerSymbol, Phone FROM Account ORDER BY createdDate ASC];
      }
}


Output Images:











Monday, 10 February 2020

Convert List of Records into picklist in lightning.



Converting List of Account records into Picklist values in the component.

Component:- ListToPicklist.cmp

<aura:component access="global" controller="ListToPicklistcon" implements="flexipage:availableForAllPageTypes">

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
   <aura:attribute name="objInfo" type="account" default="{sobjectType : 'Account'}" />

   <div class="slds-form-element">
      <label class="slds-form-element__label" for="select-01">Select Label</label>
      <div class="slds-select_container">
         <ui:inputSelect  aura:id="accIndustry" class="slds-select" change="{!c.onPicklistChange}"/>
      </div>
   </div>
 
</aura:component>

JS:- ListToPicklistController.js

({
doInit: function(component, event, helper) {
        helper.fetchPickListVal(component, 'accIndustry');
    },
    onPicklistChange: function(component, event, helper) {
        // get the value of select option
        alert(event.getSource().get("v.value"));
    },
})

Helper:- ListToPicklistHelper.js

({
    fetchPickListVal: function(component, elementId) {
       
        var action = component.get("c.getselectOptions");
       
        var opts = [];
        action.setCallback(this, function(response) {
            if (response.getState() == "SUCCESS") {
                var allValues = response.getReturnValue();
  alert('allValues---'+allValues);
                if (allValues != undefined && allValues.length > 0) {
                    opts.push({
                        class: "optionClass",
                        label: "--- None ---",
                        value: ""
                    });
                }
                for (var i = 0; i < allValues.length; i++) {
                    opts.push({
                        class: "optionClass",
                        label: allValues[i],
                        value: allValues[i]
                    });
                }
                component.find(elementId).set("v.options", opts);
            }
        });
        $A.enqueueAction(action);
    },
})

Apex Class: 

public class ListToPicklistcon {
   
    @AuraEnabled
    public static List < String > getselectOptions() {
       
        List<account> values = [select id,name from account];
        List < String > allOpts = new list < String > ();
       
        // Add these values to the selectoption list.
        for (account a: values) {
            allOpts.add(a.name);
        }
        system.debug('allOpts ---->' + allOpts);
        allOpts.sort();
        return allOpts;
    }
   
}



Thursday, 9 January 2020

Date Formatting in Apex


Datetime to String

String dateFormat = 'yyyy-MM-dd\'T\'HH:mm:ss\'Z\'';

DateTime dt = DateTime.now();
String dateString = dt.format(dateFormat);

System.debug(dateString); // 2016-02-29T22:30:48Z

Date to String

String dateFormatString = 'yyyy-MM-dd';

Date d = Date.today();
Datetime dt = Datetime.newInstance(d.year(), d.month(),d.day());
String dateString = dt.format(dateFormatString);
System.debug(dateString); // 2016-02-29

Useful Examples

// 2016-02-29
Datetime.now().format('yyyy-MM-dd');

// 2016-02-29T23:50:24Z873
Datetime.now().format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'SSS');

// 2016.02.29 AD at 23:52:20 EST
Datetime.now().format('yyyy.MM.dd G \'at\' HH:mm:ss z');

// Mon, 29 Feb 2016 23:54:22 -0500
Datetime.now().format('EEE, d MMM yyyy HH:mm:ss Z');

// Today is Monday
Datetime.now().format('\'Today is\' EEEE');

// Tuesday March 01, 2016 is the 61 day of the year
Datetime.now().format('EEEE MMMM dd, YYYY \'is the\' D \'day of the year\'');

// Tuesday March 01, 2016 is the 1 day of the month

Datetime.now().format('EEEE MMMM dd, YYYY \'is the\' d \'day of the month\'');