salesforce small knowledge

1Severalwaystogettherecordtype

//Thefirsttypeisrecommended,becausenosqlqueryisrequired
StringrecordType=Schema.SObjectType.Good__c.getRecordTypeInfosByName().get('mid-rangebrand').getRecordTypeId();
system.debug('Type1:'+recordType);
//Thesecondtype:
List<RecordType>list_type=[Selectid,Name,IsActive,DeveloperNameFROMRecordTypewhereName='LuxuryBrand'andIsActive=true];
System.debug('Thesecondtype:'+list_type);

//Thethirdtype
List<RecordType>list_type3=[selectId,DeveloperName,NamefromRecordTypewhere(DeveloperName='MiddleBrand'ORDeveloperName='extravagant')
ANDSObjectType='Good__c'];
System.debug('Thethirdtype:'+list_type3);

//fourth
List<RecordType>list_type2=[SelectId,Name,DeveloperNameFromRecordTypewheresobjecttype='Good__c'];
System.debug('Thefourthtype:'+list_type2);

2ConversionofListandJSONstring

Stringjson_String=JSON.serialize(List<Opportunity>list_object);
List<Opportunity>)JSON.deserialize(Stringjson_String,List<Opportunity>.class);

3BASE64bitandMD5encryption

//base64Encode:base64encoding
StringAccountId='X66666694292';
Stringmytime=Datetime.now().format('yyyyMMddHHmmss');
StringauthorizationHeader=EncodingUtil.base64Encode(Blob.valueOf(AccountId+':'+mytime));
System.debug('authorizationHeader:'+authorizationHeader);

//Thevalueofsigis32-bituppercaseMD5encryption(accountID+accountAPISecret+timestamp)
Stringsig=AccountId+APISecret+mytime;
Stringtoken=EncodingUtil.convertToHex(Crypto.generateDigest('MD5',Blob.valueOf(sig))).toUpperCase();

4Getthesqlofallfields

SELECTFIELDS(ALL)FROMVehicle__cLIMIT5

OR

Stringquery='select';
for(StringfieldApi:Schema.SobjectType.Opportunity.fields.getMap().keySet()){<!---->
if(fieldApi=='Id')
continue;
query+=fieldApi+',';
}
query+='IdfromOpportunity';
System.debug(query);

5Executescheduledtasksatspecifiedtime

//Queryscheduledtasks
SELECTId,NextFireTime,StartTime,EndTime,State,PreviousFireTime,CronJobDetail.Name,OwnerId,CreatedById,CreatedDate,TimesTriggeredFROMCronTriggerWHERECreatedById='0051v00000AOGwyAAH'
//Querytheapexjob,whereyoucanfindtheclassnamecorrespondingtothescheduledtask
selectApexClassId,Id,JobItemsProcessed,JobType,
Status,NumberOfErrors,MethodName
fromAsyncApexJob
whereJobTypein('BatchApexWorker','ScheduledApex')

privatevoidcreateNewSchedule(){<!---->
SyncFromSapToSfSchedulesc=newSyncFromSapToSfSchedule();
System_Setting__cssc=System_Setting__c.getValues('Setting');
Datetimedt=Datetime.now().addMinutes(Integer.valueOf(ssc.SAP_Interval_Minutes__c));
List<String>args=newList<String>();
args.add(String.valueOf(dt.minute()));
args.add(String.valueOf(dt.hour()));
args.add(String.valueOf(dt.day()));
args.add(String.valueOf(dt.month()));
args.add(String.valueOf(dt.year()));
Stringfmt=String.format('30{0}{1}{2}{3}?{4}',args);//Executeonceataspecifiedtime
System.debug('***executiontime:'+fmt);
Idsid=System.schedule('SAPsyncdatatoSF_'+dt.format('yyMMddHHmmss.SSS'),fmt,sc);
}

6Stoprunningbatch

//Ifthebatchentersaninfiniteloop,itisbesttomodifythecode,modifytheconditions,andstopthebatch
for(AsyncApexJobaJob:[Selectid,StatusfromAsyncApexJobwhereStatus='Queued'orStatus='holding'])
{<!---->
System.AbortJob(aJob.Id);
}

for(CronTriggerjob:[SELECTIdFROMCronTriggerWHEREid='08e0T000002XaGoQAK']){<!---->
System.debug('job.Id+++++++++'+job.Id);
System.abortJob(job.Id);
}

7Automatedemailsinsalesforce

1.ProcessAutomationSettings
//Configurethesenderemailaddressofsalesforcehere
2.Organization-WideEmailAddresses

8Generaterandomnumbers

//@size0-sizerandomnumber
publicstaticIntegergetRandomNumber(Integersize){<!---->
return((math.random())*size).intValue();
}

//@size[lowerValue,upperValue]randomnumberintherange
publicstaticIntegergetRandomNumber(IntegerlowerValue,IntegerupperValue){<!---->
return(math.random()*(upperValue-lowerValue+1)+lowerValue).intValue();
}

9CustomSubmitforApprovalbutton

//ButtonimplementsJScode

{<!---->!REQUIRESCRIPT("/soap/ajax/35.0/connection.js")}
{<!---->!REQUIRESCRIPT("/soap/ajax/35.0/apex.js")}

varrecordtype='{!Opportunity.RecordType}';
varstatus='{!Opportunity.ApprovalStatus__c}';//Approvalstatus
varstage='{!Opportunity.StageName}';

if(recordtype!='requiredrecordtype'){<!---->
alert('Thecurrentbusinessopportunityrecordtypeis:'+recordtype+'cannotusethisapproval!');
}elseif(status=='approving'){<!---->
alert('Thecurrentbusinessopportunityisbeingapproved,pleasewaitpatientlyfortheapprovalresult!');
}elseif(status=='Passed'){<!---->
alert('Thecurrentbusinessopportunityhasbeenapproved,pleasedonotsubmitrepeatedly');
}else{<!---->
varrequest=newsforce.ProcessSubmitRequest();
request.objectId="{!Opportunity.Id}";
varprocessRes=sforce.connection.process([request]);
if(processRes[0].getBoolean('success')){<!---->
alert("Thequotationhasbeensubmittedforapproval,pleasewaitfortheapprovaltobecompleted!");
window.location.reload();
}else{<!---->
alert("Submissionapprovalerror:"+processRes[0].errors.message);
}
}

10apex@futureannotation

The@futureannotationisusuallyusedforasynchronousexecution.Mustbeastaticmethodandhasnoreturnvaluevoid
@futuredefaultstofalse,whichmeansitcannotbecalledbyothermethods
When@futureistrue,itmeansthatitcanbecalledbyothermethods
@futurestaticvoidmyMethod(Stringa,Integeri){<!---->System.debug('Methodcalledwith:'+a+'and'+i);//Performlong-runningcode}

11SFExamEntry

RegisteredaccountaddressforSFexamcertification
SFExamEntry

12SalesCloudandSFMCConnection

TrailheadLearningLinks:SFMCandSFDCConnectionSteps

13Getsalesforcetoken

Clickthesettingstosearchfortheapplication(APPS)tocreateaconnection
Getclientidandclientsecret
requestpostman:

https://test.salesforce.com/services/oauth2/[email protected]&password=34!F1k&grant_type=password&client_id=3MVG9iyskUi6RKTou6rkmDPksyGfLXbThSo7ZK_AkbO6PsWBGw6rSB9gwW4rH72s&client_secret=ACAB3FAE91973A465A831A2A39933D220AAE1726907FFA957E0FBC3

Ifunsupportgranttypeappears,tryaddingthesecuritykeytothepassword.Thesecuritykeyisobtainedinthepersonalsettings

IftheIPrestrictionissetintheprofile,thereisnoneedtoaddakeyafterthepassword.TheusualpracticeistosettheIPrangeto0-255.
Asecuritykeyisrequiredifnoiprangeissetintheprofile.

14salesforceschedule

Configurable

//Inthecustomsettings,configurehowmanyminutestoexecuteonce
privatevoidcreateNewSchedule(){<!---->
SyncFromSapToSfSchedulesc=newSyncFromSapToSfSchedule();
System_Setting__cssc=System_Setting__c.getValues('Setting');
Datetimedt=Datetime.now().addMinutes(Integer.valueOf(ssc.SAP_Interval_Minutes__c));
List<String>args=newList<String>();
args.add(String.valueOf(dt.minute()));
args.add(String.valueOf(dt.hour()));
args.add(String.valueOf(dt.day()));
args.add(String.valueOf(dt.month()));
args.add(String.valueOf(dt.year()));
Stringfmt=String.format('30{<!---->0}{<!---->1}{<!---->2}{<!---->3}?{<!---->4}',args);//Executeonceataspecifiedtime
System.debug('***executiontime:'+fmt);
Idsid=System.schedule('SAPsyncdatatoSF_'+dt.format('yyMMddHHmmss.SSS'),fmt,sc);
}

Simpleandrude

//Executeeveryfiveminutes
System.schedule('SampleScheduler1','000***?',newSampleScheduler());
System.schedule('SampleScheduler2','005***?',newSampleScheduler());
System.schedule('SampleScheduler3','010***?',newSampleScheduler());
System.schedule('SampleScheduler4','015***?',newSampleScheduler());
System.schedule('SampleScheduler5','020***?',newSampleScheduler());
System.schedule('SampleScheduler6','025***?',newSampleScheduler());
System.schedule('SampleScheduler7','030***?',newSampleScheduler());
System.schedule('SampleScheduler8','035***?',newSampleScheduler());
System.schedule('SampleScheduler9','040***?',newSampleScheduler());
System.schedule('SampleScheduler10','045***?',newSampleScheduler());
System.schedule('SampleScheduler11','050***?',newSampleScheduler());

15salesforcemetadataisuploadedwithvscode

Firstcreatethemetadata,thenpullitfromvscode:
Usethecommandinvscode:
sfdxforce:cmdt:record:insert-fC:\workspace/AXAUATBatch1/webServiceNew/MineType.csv–typenameMineType__mdt
https://sfdclesson.com/2021/02/20/mass-insert-custom-metadata-type-records/)

16Formulafieldrealizesjumpurlthroughid

HYPERLINK(CASESAFEID(Owner.Id),Owner.LastName+Owner.FirstName)

17Savethepdfonsalesforce

@AuraEnabled
publicstaticStringsavePDF(StringaccountId,Stringurl){<!---->
PageReferencelogPage=newPageReference(url);
blobcontent;
if(Test.isRunningTest()){<!---->
content=Blob.valueOf('TestData');
}else{<!---->
content=logPage.getContent();//getthepdf
}
List<ContentDocumentLink>contentDocumentLinks=[
SELECTId,ContentDocumentId
FROMContentDocumentLink
WHERELinkedEntityId=:accountIdANDContentDocument.LatestPublishedVersion.Title='SummaryInAGlance'
ANDContentDocument.createdbyId=:UserInfo.getUserId()
];

Set<Id>contentDocumentId=newSet<Id>();
for(ContentDocumentLinkcontentDocumentLink:contentDocumentLinks){<!---->
contentDocumentId.add(contentDocumentLink.ContentDocumentId);
}
//SetToBeDeleted__c=true,makeitdeletedautomaticallyinscheduleJob,runningevery12:00am
ContentVersioncontentVersion=newContentVersion(
ToBeDeleted__c=true,
PathOnClient='SummaryInAGlance.pdf',
Origin='H',
ContentLocation='S',
VersionData=content,
Title='SummaryInAGlance',
ContentDocumentId=contentDocumentId.size()>0?newList<Id>(contentDocumentId)[0]:null,
ReasonForChange=contentDocumentId.size()>0?'savenewMatrix':null
);
insertcontentVersion;
StringdocumentId=contentVersion.ContentDocumentId;
if(contentDocumentId.size()==0){<!---->
contentVersion=[SELECTId,ContentDocumentIdFROMContentVersionWHEREId=:contentVersion.Id];
documentId=contentVersion.ContentDocumentId;
insertnewContentDocumentLink(LinkedEntityId=accountId,ContentDocumentId=contentVersion.ContentDocumentId,ShareType='V');
}
returndocumentId;
}