Saturday 7 December 2019

Lightning Web Component lightning-file-upload and edit file content


A lightning-file-upload component provides an easy and integrated way for users to upload multiple files. The file uploader includes drag-and-drop functionality and filtering by file types.

to use lightning-file-upload you must have recordId of the record that the uploaded file is associated with, lightning-file-upload component will appear to disable in the absence of recordId.

Below code will upload the images and displays them with onclick functionality which will enable you to edit the title and description of uploaded files with delete functionality.








Points to remember: 
1. Not supported in Lightning Out or standalone apps, and displays as a disabled input.
2. The file uploader cannot be used to upload files with the following file extensions: .htm, .html, .htt, .htx, .mhtm, .mhtml, .shtm, .shtml, .acgi, .svg.
3. lwc file-upload multiple don't work in android, In android you cannot upload multiple files, pls refer this link

Reference: lwc deveoper guide, W3School, Salesforce Ideas

Tuesday 3 December 2019

lightning-input error message using Validity methods


When using lightning-input component, we can use validity methods (setCustomValidity, reportValidity, checkValidity) to display error messages.






Monday 28 October 2019

Salesforce Community Templates


Community templates let you build responsive communities for delivering rich, branded spaces for your customers and partners.

With Community Builder, you can edit the lightning template components to add information about your community, add images and CMS content with writing a single line of code. You can also create and add custom pages, build a lightning component and expose your salesforce objects.

Types of Templates:
1. Aloha: A configurable App Launcher template that lets users quickly find applications and access them using single sign-on authentication, including social logins.

2. Customer Account Portal: The Customer Account Portal template improves customer relationships and decreases service costs. The template provides features that make it easy for customers to see and pay invoices, update their account information, and search your knowledge base for answers.

Features:
a. Lightning community pages and components
b. Tile menu, for a visual navigation experience
c. Global search with a customizable list of searchable objects
d. Dashboards and reports
e. Customizable branding and design
f. Rich, responsive look and feel across multiple devices

3. Partner Central: Use this template to recruit, build, and grow your partner network to drive channel sales and marketing together in a branded online space. Easily configure lead distribution, deal registration, and marketing campaigns. Share training materials and sales collateral in a central space, and use reports to track your pipeline.

Features:
a. Lightning community pages and components
b. The Lead Inbox component to pass leads to partners
c. Customizable Quick Create action menu that you can configure for deal registration
d. Customizable navigation menu with preconfigured list views for leads, deals, and campaigns
e. Global search with a customizable list of searchable objects
f. Dashboards and reports
g. Customizable branding and design
h. Collaboration features such as groups, feeds, topics
i. Rich, responsive look and feel across multiple devices

4. Customer Service (Napili): The Customer Service template lets users post questions to the community, search for and view articles, collaborate, and contact support agents by creating cases. Supports Knowledge, Chatter Questions, and cases. This template provides a rich, self-service experience for your customers, where they can get answers to their questions at any time, on any device. 

Features:
a. Lightning community pages and components
b. Self-resolution of cases through knowledge and case creation
c. Collaboration features such as groups, feeds, topics
d. Global search with a customizable list of searchable objects
e. Moderation rules to weed out trolls and bots
f. Dashboards and reports
g. Recommendations
h. Customizable branding, design, and navigation
i. Rich, responsive look and feel across multiple devices


5. Help Center: A public-access, self-service community that exposes the articles that you make available from your knowledge base. You reduce the load on your customer support team, and your users get the satisfaction of finding their own solutions. Customers can search and read articles and contact your support team to resolve issues.

Feature:
a. Self-resolution of cases through knowledge and case creation
b. Lightning community pages and components

c. Customizable branding and design

6. Build your Own: Build your own template provides the basic pages every community needs but you can easily add more pages and components as needed for the experience you are building.

Feature:
a. Lightning community pages and components

b. Customizable branding and design

7. Salesforce Tabs + Visualforce: Standard Salesforce structure and tabs that you can customize using Visualforce. It Allows full platform access with a flexible configuration and supports most standard and custom objects, and Salesforce apps. 

8. Koa (Retired): Koa is optimized for mobile devices. It is a text-based template that allows users to search for and view articles, and contact support if they are unable to find what they need.

9. Kokua (Retired): Unlike Koa, Kokua is a visually rich, self-service template that allows community members to search for and view articles, and contact support.

Note: Both Koa and Kokua templates are in phased retirement, and you can no longer use them to create communities. Salesforce supports existing communities built with Koa and Kokua, but recommend migrating to newer Lightning community templates.


Reference: Salesforce Community Doc

Steps to create Multilingual Community



1. Set the default language: This setting is not associated with the default language settings in your Salesforce org. By default, English is the language in which community content displays. 
1.a. In the community on the left sidebar, click on the gear icon and select Languages.
1.b. Select a language in the Default Community Language.


2. Add Language to community: Click on the Add Language button and select the languages you wanted to add to your community and save your changes.

once save you can select any the following settings



2.a. Active on Live Community: This checkbox controls whether the language is available to community visitors in the language selector.
2.b. Fallback Language: Controls which language to display if the selected site language is unavailable.
2.c. Display Label: This setting define the display label for each language. The display label appears in any language picker components you add to your community and in the language selector in Community Builder.

3. Export the content for translation: Click on Export Content and select the language you want to export for translation. Save the .xml file and send it to your translation service.

sample .xml file:
4. Import translated content: Once translation service completed the translation, import a translated .xml file back to community by clicking Import Translation.

Once import is complete test your community pages to make sure the content displays correctly.




Sunday 13 October 2019

AccountContactRelationship


This object is used to associate a single a single contact record to multiple account records so you can easily track the relationships between the people and businesses they work with.

The AccountContactRelation object supports person accounts. That means that a person account can be either a related contact on a business account or a related account on a contact. A person account can also be related to another person account as either a related contact or related account.

You can query AccountContactRelation records in your developer org, below query will give you the accountcontactrelation record info.

SELECT Id, ContactId, Contact.Name, AccountId, Account.Name FROM AccountContactRelation

You will have to enable setting Allow users to relate a contact to multiple accounts” setting from setup > account settings for above query to work.

You cannot delete AccountContactRelation record, only way to delete the records is to remove the account reference from contact.

Reference: Salesforce

Tuesday 10 September 2019

Convert Set to String


Option 1:





Drawback: once the set size increase above option to convert the set to string as it receives i.e.

Option 2:


output:

Sunday 7 July 2019

Related reference Fields Value in sObject SOQL


In Dynamic SOQL we create query string using Apex code at run time and use Database.Query method to fetch the results.

example: 
String queryString = ' SELECT Id, Name, AccountId FROM Contact LIMIT 1';
sObject result = Database.query(queryString);

above query will return me a contact information, if I wanted to access record's Name I can access it using sObject get() method i.e. result.get('Name') will give me Name value.




Output:


But the real challenge we will face when you try to access fields value from related object field, i.e. if you try to access Account.AnnaualRevenue you will get an exception 'System.SObjectException: Invalid field Account.AnnualRevenue for Contact'.

To fix this we we will use getSObject() method to traverse the relationship.

below code will traverse the relationship and get you the value:

References: sObject Class, String Class, Martin Borthiry

Asynchronous Apex Triggers

In Summer 19 release Salesforce introduce a new feature to process data using a combination of 'Asynchronous Apex Triggers' and Change Data Capture.
Any DML on Salesforce records causes platform to start a series of calculations, run business logic and database updates, all these are called as an Apex Transactions. You can reduce the Apex transaction time to complete the business logic and limit constraints by decoupling resource-intensive, non-transactional logic from database transaction and execute asynchronously. 

Asynchronous Apex triggers are change event triggers that run asynchronously after a database transaction is completed. They are ‘after-insert’ triggers and can be defined with the after insert keywords. They can be created the same way we create regular Apex triggers. You set the trigger to use a change event object instead of an sObject. The change event object name is suffixed with ChangeEvent. For example, Account change event object is named AccountChangeEvent. The change event object name for the custom object is suffixed with __ChangeEvent.

Before creating after-insert triggers make sure you have enable objects for Change Data Capture. If not you can enable it following below steps:

Setup > Integrations > Change Data Capture, Select your Object.



You can create from after-insert triggers in the Developer Console the same way you create an Apex object trigger or you can try below command in VS Code terminal.

sfdx force:apex:trigger:create- n OpportunityChangeAyncTrigger -s OpportunityChangeEvent -e 'after insert' -d 'force-app/main/default/triggers'



Testing Change Event Triggers

To test change event triggers, enable the generation of change event notifications for the test method.

Test.enableChangeDataCapture();

The Test.enableChangeDataCapture() method ensures that Apex tests can fire change event triggers regardless of the entities selected in Setup. This method doesn’t affect the Change Data Capture entity selections for the org.

After performing DML operations, deliver the event messages to the corresponding trigger with:

Test.getEventBus().deliver();

Alternatively, if you use the Test.startTest(), Test.stopTest() method block in your test, change event messages fire the associated trigger after Test.stopTest() executes.



Monday 27 May 2019

Lightning Web Component : lightning-record-view-form


lightning-record-view-form component is a wrapper component that accepts a record ID and is used to display one or more fields and labels associated with that record using lightning-output-field.

lightning-record-view-form requires a record ID to display the fields on the record. It doesn't require additional Apex controllers or Lightning Data Service to display record data. This component also takes care of field-level security and sharing for you, so users see only the data they have access to.

Displaying Record Fields:
To display the fields on a record, specify the fields using lightning-output-field.


Attributes:
NAME ACCESS DESCRIPTION REQUIRED
record-id global The ID of the record to be displayed. Yes
object-api-name global Api name of object. Yes

Reference: Salesforce Developer Guide, Salesforce Component Library

Lightning Web Component: lightning-record-form


lightning-record-form component enables you to quickly create forms to add, view, or update a record. 

Using this component to create record forms is easier than building forms manually with lightning-record-edit-form and lightning-record-view-form. However, lightning-record-form does not support client-side validation quite the same as lightning-record-edit-form.

The object-api-name attribute is always required, and record-id is required if you are editing a record.

NOTE: this component take cares of field-level security and sharing for you, so users will only see the data that they have access to.

Modes
This component accepts mode value that determines the user interaction determine for them. The values can be one of the following:

a. editCreates an editable form to add a record or update an existing one. When updating an existing record, specify the record-idEdit mode is the default when record-id is not provided, which displays a form to create new records.

b. viewCreates a form to display a record that the user can also edit. The record fields each have an edit button. View mode is the default when record-id is provided.

c. readonlyCreates a form to display a record without enabling edits.

Specifying Record Fields

For all modes component expect the fields attribute or layout-type attribute.
Use the fields attributes to pass record fields as an array of strings. The fields display in the order they pass.

Use the layout-type attribute to specify a Full or Compact layout.

Salesforce don't recommend using the fields with layout-type attribute as the display order of the fields can vary.To display an custom layout use lightning-record-edit-form or lightning-record-view-form. If fields and layout-type are provided, the fields you define in the fields property are displayed before the other fields from the given layout type.


Viewing a Record with Option to Edit Fields:
Use mode="view" and pass the ID of the record and the corresponding object API name to be displayed. Specify the fields using the fields attribute, or layout-type attribute to display all the fields defined on the Full or Compact layout. The view mode loads the form using output fields with inline editing enabled.

below example creates a form for an account record in a view mode.
Adding the component on page layout and save it.
Editing a Record:
To edit a record, pass the ID of the record and the corresponding object API name to be edited. When record-id is passed, edit mode loads the form with input fields displaying the specified record's field values. The form also displays Submit and Cancel buttons.
Add the component on page-layout and save it. 

Creating a Record:
Pass in the object API name for the record to be created. Specify the fields you want using the fieldsattribute, or use the Full layout to load fields.

The compact layout cannot be used for creating records. If you specify layout-type="Compact", the full layout is shown. If you specify the fields attribute, be sure to include any fields that are designated as required for the object's records.
Because no recordId is passed, form load in edit mode with Submit and Cancel buttons.
Add the component on page-layout and save it.


Display Form based on RecordTypes:
If your org uses record types, picklist fields display values according to your record types. You must provide a record type ID using the record-type-id attribute if you have multiple record types on an object and you don't have a default record type. Otherwise, the default record type ID is used.

Client Side Validation:
The lightning-record-form component performs client-side validation on record fields only if you interact with them. For example, if you edit a record that includes a required field and submit the form without interacting with that required field, you see only that an error occurred. The form does not flag the required field as incorrect.

To customize the behaviour of your form when it loads or when data is submitted, use the onload and onsubmit attributes to specify event handlers.


Attributes:
NAME ACCESS DESCRIPTION REQUIRED
record-type-id global The ID of the record type, which is required if you created multiple record
types but don't have a default.
No
mode global displays the form in view, edit and read-only mode. No
layout-type global Possible values: Compact, Full. No
record-id global The ID of the record to be displayed. No
object-api-name global The API name of the object. Yes
columns global Specifies the number of columns for the form. No
fields global List of fields to be displayed. The fields display in the order you list them. No



Reference: Salesforce Developer Guide, Salesforce Component Library

Monday 8 April 2019

Salesforce Connect


Salesforce connect is a framework that enables you to view, search and modify data that's stored outside your Salesforce org. Instead of extracting and copying that data into your org using ETL tool, we can use external objects to access that data real time using web-service callouts.


Salesforce recommend to use Salesforce Connect if

  1. You have large amount of data that you don't want to copy into your Salesforce org.
  2. You need small amount of data at any one time.
  3. You need real-time access to the latest data.
  4. You store your data in the cloud or in a back-office system, but want to display or process that data in your Salesforce org.

External Objects:

External objects in Salesforce are similar as custom objects but they are mapped to data located outside your Salesforce org. Each of the external object’s fields maps to a table column on the external system. External objects enable users to search and interact with the external data.

Each org can have up to 100 external objects and external objects do not count towards the amount for custom objects.

With external objects we can
  • Access external objects via list views, detail pages, record feeds, custom tabs, and page layouts.
  • Enable chatter feeds on external objects pages for collaboration.
  • Enable create, edit, and delete operations on external objects.
  • Define relationships between external objects and standard or custom objects to integrate data from different sources.
External objects are also available to standard Salesforce tools such as Salesforce app, global search, SOSL, SOQL queries, Apex, Visualforce, APIs, change sets and packages.

Following features is not allowed with External objects
  1. Formula fields is not allowed, you cannot create formula field on External object.
  2. You cannot create workflow rules on External objects
  3. You cannot write triggers on External objects.
  4. You cannot write sharing rules on External objects.

Type of External Connectors:

  1. OData 2.0 adaptor or OData 4.0 adaptor - Connects to data exposed by any OData 2.0 or 4.0 producer on the Internet. OData (Open Data Protocol) is a modern, REST-based protocol for integrating data.
  2. Cross-org adaptor - Connects to data that’s stored in another Salesforce org. The Cross-org adapter uses the standard Lightning Platform REST API.
  3. Custom adaptor created via Apex - If the OData and cross-org adapters aren’t suitable for your needs, develop your own adapter with the Apex Connector Framework.

Set up Salesforce Connect:

  1. Install Salesforce Lightning Connect package from this link.
  2. Click Install to start the installation.
  3. Once installation complete, select External Orders app.
  4. Under QuickStart tab, click Set Customer IDs to assign customer ID numbers to the account records in org.
    This step will populate CustomerIDs to Account records in Salesforce org.
  5. Go to setup, search and open External Data Sources.
  6. Click on 'New External Data Source'.
  7. Enter label as OrderDB and select Salesforce Connect: OData 2.0 as the type.
  8. In URL enter https://orderdb.herokuapp.com/orders.svc/.  

    If you are connect with external system that requires authentication than you can configure that under Authentication section but in our case we don't need it.

  9. Click Save.
  10. Click on Validate and Sync, it retrieve OData 2.0 metadata from database and lists the available tables.
  11. Click on Sync.
    Syncing creates the external objects corresponding to the tables that you selected. Syncing does not store any data in Salesforce. Syncing only defines mappings to external tables or repositories that contain the data.

    You can choose to manually create the external objects. Doing so enables you to customize the external object names, decide which table columns to create custom fields for, and customize the custom field names.
You can create custom tabs to access Order and Order Details records.

Order record in Salesforce will look like: 





Once External objects created in Salesforce Org, click on OrderDetails external object
  1. Click Edit next to orderID field.


  2. Click on Change Field Type.
  3. Now select External Lookup Relationship and click Next.


  4. Select Orders as related object and click Next.


  5. Enter length as 18 and click Next.
  6. Select visible to all profile and Save.
  7. Now from select Order object and under Fields and Relationships click Edit next to CustomerID.
  8. Click the Change Field Type button.
  9. Select Indirect Lookup RelationShip and click Next.
  10. Select Account as related object and click Next.
  11. Select Customer_ID__c as the value of Target Field and click Next.
  12. Enter length size as 18 and click Next.
  13. Make relationship visible to all profile and save the changes. This steps will link the Accounts with Order records which which was populated at the starting. From Order record when we click on CustomerID link it will take us to Account detail page.




Difference between External Objects and Custom objects are:

  • External object API names have the suffix __x rather than __c
  • External objects have a reference to their external data source and a table within that source.
  • External objects have different standard fields. Display URL is the OData 2.0 URL representing a record in the external database, while External ID is the primary key value for each record.
  • You cannot write triggers and workflow rules for external objects.
  • You cannot create formula field on external objects.

Relationship Types:

There are three types of external relationships

Type of Relationship Child Object Parent Object Must External Data Contain Salesforce IDs?
Lookup Standard, Custom, or External Standard or Custom Yes
External Lookup Standard, Custom, or External External No
Indirect Lookup External Standard or Custom No



Wednesday 3 April 2019

SOQL Injection


A SOQL injection consists of insertion or injection of SOQL query via the input data from client to application. A successful SQQL injection exploit can read sensitive data from the database.

Below is the example of Apex and Lightning Component code vulnerable to SOQL injection.





Now enter name existing contact name and click on search button to see the result, in my case I search for contact whose Name contains 'Winter'.



Now in search box enter " winter%' OR Name LIKE ' " and click on search button to all contact records.


How to prevent SOQL injection?

1. Static Query: To prevent SOQL injection attach, avoid using dynamic SOQL queries. Instead, use static queries and binding variables.

2. Escaping Single Quotes: use of string.escapeSingleQuotes() method arounf variable function escapes any instance that it finds of a ‘ quote in the string using the backslash (\) escape character. This prevents an attacker’s input from being treated as code by constraining them to the boundary of the string.


References: Salesforce Developer Guide, trailhead

Saturday 23 March 2019

lightning:map component

lightning:map introduced in winter 19 which can be use display a map of one or more locations using Google Maps. We can pass markers to the component to define the locations to map. A marker can be a coordinate pair of latitude and longitude, or a set of address elements: City, Country, PostalCode, State, and Street.

This component requires API version 44.0 and later. lightning:map has required attribute mapMarkers which accepts array of markers that indicate location. A market contains

  • Location information: This can be a coordinate pair of latitude and longitude, or an address composed of address elements.
  • Descriptive information: This is information like title, description and an icon which is information relevant to the marker but not specifically related to location.
Example
Create a new Object called 'Tower' with two new custom fields
1. Field Label: State
    Type: Master-Detail (Account)

2. Field Label: Location
    Type: GeoLocation (Latitude & Longitude Display Notation: Decimal )

Once metadata is ready then create some Tower records with Latitude & Longitude values.

Now copy & paste below code to show Map with markers.

UtilityClass.cls TowerController.cls TowerMap.cmp TowerMapController.js TowerMapHelper.js