Sunday, December 22, 2019

Basic Trigger examples


Basic Trigger examples


 Populate contact description when user creates contact

trigger ContactBeforeInsert on Contact (before insert) {
// Trigger.New hold new version of Contacts
for(Contact contact: Trigger.new){
contact.Description = ‘Contact created successfully by using ContactBeforeInsert trigger’;
}
// No Need to write DML statement, trigger. New will be take care.
}

Populate contact description with modified user name when user updates contact.

trigger ContactBeforeUpdate on Contact (before update) {
// Trigger.New hold new version of Contacts
for(Contact contact: Trigger.new){
contact.Description = ‘Contact updated successfully by ‘+ userInfo.getUserName() ;
}
// No Need to write DML statement, trigger. New will be take care.
}

 How to write a trigger to inject the above 2 scenarios in one trigger

trigger ContactBeforeInsertUpdate on Contact (before insert, before update) {
// Trigger.New hold new version of Contacts
for(Contact contact: Trigger.new){
if(trigger.isInsert){
contact.Description = ‘Contact created successfully by using ContactBeforeInsert trigger’;
}
If(trigger.isUpdate){
contact.Description = ‘Contact updated successfully by ‘+ userInfo.getUserName() ;
}
}
// No Need to write DML statement, trigger. New will be take care.
}

Throw an error whenever the user try to delete the contact which is not associated to account

trigger contactBeforeDelete on Contact(before delete){
for(Contact contact: trigger.old){
if(contact.accountId == null){
contact.addError(“Hey! You are not authorized to perform this action.”);
}
}
}

when the leads are inserted into the data base it would add Doctor prefixed for all lead names. This is applicable for both inserting and updating the lead records


trigger PrefixDoctor on Lead (before insert,before update)
{

 List<Lead> leadList = trigger.new;

 for(Lead l: leadList)

 {

 l.firstname = 'Dr.'+ l.firstname;

 }


 }


The following trigger adds the Opportunity Owner into the sales team automatically whenever the Opportunity is created.

trigger OppTeam on Opportunity (after insert) {
 List<OpportunityShare> sharesToCreate = new List<OpportunityShare>();

 List<OpportunityTeamMember> oppteam = new List<OpportunityTeamMember

 > ();

 OpportunityShare oshare = new OpportunityShare();

 oshare.OpportunityAccessLevel = 'Edit';

 oshare.OpportunityId = trigger.new”0”.Id;

 oshare.UserOrGroupId = trigger.new”0”.createdbyid;

 sharesToCreate.add(oshare);

 OpportunityTeamMember ot = new OpportunityTeamMember();

 ot.OpportunityId = trigger.new”0”.Id;

 ot.UserId = trigger.new”0”.OwnerId;

 ot.TeamMemberRole = 'Account Manager';

 oppteam.add(ot);

 if(Oppteam!=null && Oppteam.size()>0)

 {

 insert Oppteam;

 }

 if(sharesToCreate!=null && sharesToCreate.size()>0)

 {

 list<Database.SaveResult> sr = Database.insert(sharesToCreate,false);

}


 }

Create “Sales Rep” field with data type (Text) on the Account Object. When we create the Account record, the Account Owner will be automatically added to Sales Rep field. When we update the Account owner of the record, then also the Sales Rep will be automatically updated.

triggerUpdateSalesRep on Account (Before insert,Before Update){
Set<Id>setAccOwner=new Set<Id>();
for(Account Acc: trigger.new)
{
setAccOwner.add(Acc.OwnerId);
}
Map<Id,User>User_map = new Map<Id,User>(“select Name from User where id
in:setAccOwner”);
for(Account Acc: Trigger.new)
{
User usr=User_map.get(Acc.OwnerId);
Acc.sales_Rep1__c=usr.Name;
}
}

Sunday, April 7, 2019

LightningOut in Salesforce

Expose Lightning component outside of lightning/salesforce

We can expose any component to outside of salesforce(it may be PHP/Wordpress/Sharepoint) or to classic VF page with usage of lightning Out.

We will directly jump to code and will see how to setup this.

Lets create a Component which you want to expose to VF page.

Component :LightningDataTableExample.cmp

<aura:component controller="AccountDataTableController" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" > <aura:attribute type="Account[]" name="acctList"/> <aura:attribute name="mycolumns" type="List"/> <aura:handler name="init" value="{!this}" action="{!c.fetchAcc}"/> <lightning:datatable data="{! v.acctList }" columns="{! v.mycolumns }" keyField="id" hideCheckboxColumn="true"/> </aura:component>

Add apex controller for the component 

public class AccountDataTableController { @AuraEnabled public static List <Account> fetchAccounts() { //Qyery 10 accounts List<Account> accList = [SELECT Id, Name, BillingState, Website, Phone, Industry, Type from Account LIMIT 10]; //return list of accounts return accList; } }

Lets add controller code for the component

({
    fetchAcc : function(component, event, helper) {
        helper.fetchAccHelper(component, event, helper);
    }
})


Lets add helpercode for the component

({ fetchAccHelper : function(component, event, helper) { component.set('v.mycolumns', [ {label: 'Account Name', fieldName: 'Name', type: 'text'}, {label: 'Industry', fieldName: 'Industry', type: 'text'}, {label: 'Phone', fieldName: 'Phone', type: 'Phone'}, {label: 'Website', fieldName: 'Website', type: 'url '} ]); var action = component.get("c.fetchAccounts"); action.setParams({ }); action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS") { component.set("v.acctList", response.getReturnValue()); } }); $A.enqueueAction(action); } })
Add this component in Page and it will look like below


Now lets expose this component in classic VF page. To achieve this we wil luse lightning out with lightning dependency app

Create a new Lightning app with below code to expose the component to app

App:LoutDataTableApp.app

<aura:application extends="ltng:outApp" access="GLOBAL">
<aura:dependency resource="c:LightningDataTableExample"/>
</aura:application>

Lets create a vf page and display this component in VF page.

Vf Page: LODataTable.vfp

<apex:page >
    <apex:includeLightning />   
    <div id="LcDisplayId"></div>     
 <script>     
    $Lightning.use("c:LoutDataTableApp", function() {      
    $Lightning.createComponent("c:LightningDataTableExample",
    {
       
  },
   "LcDisplayId",
    function(component) {
        
    });
 });
 </script>
</apex:page>

Lets see the same Lightning component in classic VF page