Git Product home page Git Product logo

salesforce-utils's Introduction

Salesforce-Utils



Repository with tools, tricks, commands and resources for Salesforce development and administration.

Table of content

LWC

Tip

Evita Visualforce Page. 😊

LWC Debug

Pasos DEBUG LWC

  1. Debug mode -> Seleccionar usuario y habilitar (Permite ver el JS direcamente en la consola del navegador, pudiendo podificar, debugear, etc)
  2. Session settings -> Caching | Enable Secure persistent browser caching to improve performance:False (Permite que puedas refrescar sin que se te mantenga la Cache)
  3. Session Settings -> Lightning Web Security | Use Lightning Web Security for Lightning web components and Aura components:False

Organization - Production - Sandbox

Standard - Custom Objects

Formula Fields

Cuando se desee mostrar correctamente el label en vez de el APIName de una picklist, utilizar funcionalidades de las fórmulas. Ej.: Tengo una picklist que muestra los valores como: A-Suceso, B-EspacioBlanco-B12. Si se desea poner espacios entre los guiones, la fórmula debería ser así:

IF(
    CONTAINS(Text(RelatedObject__r.PicklistField__c), '-'),
    SUBSTITUTE(
        SUBSTITUTE(
            Text(RelatedObject__r.PicklistField__c),
            '-',
            ' - '
        ),
        '  -  ',
        ' - '
    ),
    Text(RelatedObject__r.PicklistField__c)
)

ORG Doctor

To check org's status: ORG Doctor

Grant Salesforce Support login access to your organization

  1. In the upper right, click your image (avatar) and then click Settings.
  2. In Quick Find search field, enter "Grant" and click Grant Account Login Access.
  3. Set the Access Duration option to Salesforce.com Support. Note: It is recommended to set the Access Duration to one month for technical escalations. It can be extended later if needed.
  4. Click Save.

Salesforce Help

Apex

Search all lookups in other objects

List<String> referencedFields = new List<String>();
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

for (Schema.SObjectType sot : gd.values()) {
  Schema.DescribeSObjectResult objResult = sot.getDescribe();
  Map<String, Schema.SObjectField> fields = objResult.fields.getMap();
  
  for (String fieldName : fields.keySet()) {
    Schema.DescribeFieldResult fieldResult = fields.get(fieldName).getDescribe();
    Schema.DisplayType fieldType = fieldResult.getType();
    
    if (fieldType == Schema.DisplayType.Reference) {
      List<Schema.SObjectType> referenceTo = fieldResult.getReferenceTo();
      for (Schema.SObjectType ref : referenceTo) {
        if (ref.getDescribe().getName().equals('NombreDelObjeto')) {
          referencedFields.add(objResult.getName() + '.' + fieldName);
          System.debug('FIELD: ' + objResult.getName() + '.' + fieldName);
        }
      }
    }
  }
}

System.debug('FIELDS: ' + referencedFields);

Code review checklist

Expert code review

Postman

Postman for Salesforce Developers. Postman Workspace

Reach query limits

If you are going to reach the limit of queries per DML in loop:

  1. Set method -> last in the Trigger Handler.
  2. Control with next if and break process.
  3. Invoke error control framework if there is one.
if (Limits.getQueries() < Limits.getLimitQueries() {
  insert sObjectList;
}
else {
  ErrorLog__c.insertError();
  break;
}

Test an .AddError()

Test.startTest();
try {
  update workOrder;
  Assert.fail('The update did not fail');
} catch (DmlException e) {
  Assert.isTrue(e.getMessage().contains(Label.FailLabel), 'The error is not the propper one');
}
Test.stopTest();

Developer console doesn't show logs

When the 'Developer Console' does not show any log and freezes, this is what to do1: if you have any Chromium based browser such as Chrome, edge, opera, etc. you have to open the dev tools from the console, open the network section and refresh and magically it is solved:

  1. Login and open Developer Console by Chrome
  2. Open Developer tools and select Network
  3. Reload on Developer Console

Trigger Frameworks

  • Dan Appleman2
  • Hari Krishnan3
  • Scot Wells4
  • O'Hara5
  • Mitch Spano6

SOQL

Chain LIKE and NOT LIKE

# Forma de encadenar varios LIKE y NOT LIKE
SELECT Name
FROM Object
WHERE (NOT Name LIKE 'ST%')
  AND (NOT Name LIKE 'PA%')

# Bind 
SELECT Name FROM Object
WHERE (NOT Name LIKE 'ST%')
  AND (Name NOT IN :var)

Subquery examples

SELECT Name 
FROM Account 
WHERE Id NOT IN 
  (
    SELECT AccountId 
    FROM Opportunity 
    WHERE IsClosed = true
  )

Search by KeyPrefix

SELECT Id, DeveloperName
FROM EntityDefinition
WHERE KeyPrefix = 'XXX'

Search Entities and Fields

To search all fields in all objects, even deleted ones.

SELECT Id, DeveloperName, EntityDefinition.DeveloperName
FROM CustomField

See scratch-org expiration

SELECT Id, TrialExpirationDate
FROM Organization

Naming convention

Object Fields

Field Type API Name
Auto Number AUT_AutoNumberField__c
Boolean FLG_BooleanField__c
Currency DIV_CurrencyField__c
Date & DateTime DAT_DateTimeField__c
Email EMA_EmailField__c
Formula FOR_FormulaField__c
Geolocation GEO_GeolocationField__c
Lookup LKP_LookUpField__c
Master-Detail Relationship MDR_MasterDetailField__c
Multi-Select Picklist MSE_MultiSelectField__c
Number NUM_NumberField__c
Percent PER_PercentField__c
Phone TEL_PhoneField__c
Picklist SEL_PicklistField__c
Roll-Up Summary RUS_RollUpSummaryField__c
Text TXT_TextField__c
Time HOR_TimeField__c
URL URL_URLField__c

Metadata

Metadata Type API Name
Custom Label LAB_LabelName
Custom Metadata CMT_CustomMetadataName
Custom Setting CS_CustomSettingName
Event LEV_EventName
External Credential EC_ExtCredentialName
Flow FLW_FlowName
Lightning Page LP_PageName
List View LV_ListViewName
Named Credential NC_NamedCredentialName
Path PTH_PathName
Tab TAB_TabName
Validation Rule VR_PathName
Workflow WF_ObjectNameProcess

Trigger and Classes

Metadata Type API Name
Trigger TRG_TriggerName
Trigger Handler TRG_ClassNameHandler
Helper TRG_ClassNameHelper
Batch BATCH_ClassName
Scheduler SCH_ClassName
Interface INT_InterfaceName
Test ClassAPIName_Test
Test Suite TestSuiteName_TestSuite

Visualforce

Metadata Type API Name
Visualforce Page VFP_PageName
Visualforce Controller VFC_ControllerName
Visualforce Controller Test ControllerAPIName_Test

List of common API suffixes in Salesforce

API Suffixes7 Used for
__c Object / Field
__r Relationship
__e Events
__b Big Objects
__mdt Custom Metadata Type
__x External Object
__share Sharing Object
__Tag Salesforce Tags
__voteStat Rating for an article
__viewStat Number of view per article
__kav Knowledge Article Objects
__history Field History Tracking
__xo Salesforce-to-Salesforce (S2S) spoke
__pc Custom Persona Account Field
__ChangeEvent Change Data Capture
__StateCode__s Custom Address field
__CountryCode__s Custom Address field
__Street__s Custom Address field
__PostalCode__s Custom Address field
__City__s Custom Address field
__GeocodeAccuracy__s Custom Address field
__dlm (Data Model Object) for the Customer Data Platform.
__chn Change Event channel
__latitude__s Latitude Coordinate
__longitude__s Longitude Coordinate

VS Code

Tricks

Tip

It is recommended to have the following line in your settings.json to detect conflicts before deploying to the ORG.

"salesforcedx-vscode-core.detectConflictsAtSync": true,

Unable to get issuer cert locally

Caution

Al hacer sfdx force:org:list aparece ese error.

Solution: add this environment variable NODE_TLS_REJECT_UNAUTHORIZED = 0

My settings.json

{
    "[json]": {
        "editor.defaultFormatter": "vscode.json-language-features"
    },
    "[xml]": {
        "editor.defaultFormatter": "DotJoshJohnson.xml"
    },
    "apexPMD.runOnFileOpen": true,
    "better-comments.tags": [
        {
            "backgroundColor": "transparent",
            "bold": true,
            "color": "#FF2D00",
            "italic": false,
            "strikethrough": false,
            "tag": "!",
            "underline": true
        },
        {
            "backgroundColor": "transparent",
            "bold": true,
            "color": "#C848CE",
            "italic": false,
            "strikethrough": false,
            "tag": "-->",
            "underline": false
        },
        {
            "backgroundColor": "transparent",
            "bold": true,
            "color": "#3498DB",
            "italic": false,
            "strikethrough": false,
            "tag": "?",
            "underline": false
        },
        {
            "backgroundColor": "transparent",
            "bold": false,
            "color": "#474747",
            "italic": false,
            "strikethrough": true,
            "tag": "//",
            "underline": false
        },
        {
            "backgroundColor": "transparent",
            "bold": true,
            "color": "#FF8C00",
            "italic": false,
            "strikethrough": false,
            "tag": "todo",
            "underline": false
        },
        {
            "backgroundColor": "transparent",
            "bold": true,
            "color": "#98C379",
            "italic": false,
            "strikethrough": false,
            "tag": "*",
            "underline": false
        }
    ],
    "codesnap.showWindowControls": false,
    "codesnap.shutterAction": "copy",
    "codesnap.target": "window",
    "diffEditor.maxComputationTime": 0,
    "editor.bracketPairColorization.independentColorPoolPerBracketType": true,
    "editor.cursorBlinking": "expand",
    "editor.cursorSmoothCaretAnimation": "on",
    "editor.fontFamily": "JetBrains Mono, Victor Mono, Consolas, 'Courier New', monospace",
    "editor.fontLigatures": "'ss01', 'cv03', 'zero'",
    "editor.glyphMargin": false,
    "editor.guides.bracketPairs": true,
    "editor.indentSize": "tabSize",
    "editor.minimap.autohide": true,
    "editor.minimap.maxColumn": 60,
    "editor.occurrencesHighlight": "multiFile",
    "editor.overviewRulerBorder": false,
    "editor.scrollbar.verticalScrollbarSize": 8,
    "editor.stickyScroll.defaultModel": "indentationModel",
    "editor.stickyScroll.enabled": true,
    "editor.stickyScroll.maxLineCount": 10,
    "files.autoSave": "afterDelay",
    "git.confirmSync": false,
    "prettier.tabWidth": 4,
    "salesforcedx-vscode-apex.java.home": "",
    "salesforcedx-vscode-core.detectConflictsAtSync": true,
    "security.workspace.trust.untrustedFiles": "open",
    "settingsSync.ignoredExtensions": [],
    "symbols.hidesExplorerArrows": false,
    "terminal.integrated.stickyScroll.enabled": true,
    "window.zoomLevel": 1,
    "workbench.colorCustomizations": {
        "editor.lineHighlightBorder": "#ffffff1f"
    },
    "workbench.colorTheme": "Night Owl",
    "workbench.iconTheme": "material-icon-theme",
    "workbench.productIconTheme": "fluent-icons",
    "workbench.settings.applyToAllProfiles": [],
    "workbench.sideBar.location": "right",
    "workbench.tree.enableStickyScroll": true,
    "workbench.tree.stickyScrollMaxItemCount": 10,
    "xml.symbols.maxItemsComputed": -5000
}

References

Footnotes

  1. Developer Console menus are unresponsive

  2. Dan Appleman - Triggers without frameworks

  3. Hari Krishnan

  4. Scott Wells

  5. O'hara

  6. Mitch Spano

  7. Suffixes in Salesforce

salesforce-utils's People

Contributors

manvil95 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.