Debug “Validation Errors While Saving Record(s)” error message when calling Test.loadData()

Sometimes when you use Test.loadData() you might receive some confusing error message saying “Validation Errors While Saving Record(s)”, it is hard to understand what is wrong in data so it is possible to use the following code to debug the problem


StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'TestData' LIMIT 1];
String body = sr.Body.toString();
String[] fields = body.split('\r\n')[0].split(',');
SObject[] records = new List();
String[] lines = body.split('\r\n');
for ( Integer j = 1; j < lines.size(); j++ ) {
SObject r = new Custom_Object__c();
String[] data = lines[j].split(',');
for (Integer i = 0; i < fields.size(); i++ ) {
System.debug(LoggingLevel.ERROR, '@@@ fields[i]: ' + fields[i] + ' + data[i] ' + data[i] );
r.put( fields[i], data[i]);
}
records.add( r );
}
insert records;

So when you run a code like this you will find out the exact problem you face

Posted in salesforce | Leave a comment

War in Ukraine, information for donation to support Ukrainian Armed Forces

I am Ukrainian. I had to move out of my home city Lviv because I wasn’t able to work productively under air alarms sirens firing several times each day. I am now travelling over Europe to find some place where I can stay until the war in Ukraine is over.
If you know some place in Europe where I can stay for some time please let me know.
Also I encourage you to donate to Ukrainian national bank to support Ukrainian Armed Forces.

For donations in USD:

BENEFICIARY: National Bank of Ukraine

BENEFICIARY BIC: NBUA UA UX

BENEFICIARY ADDRESS: 9 Instytutska St, Kyiv, 01601, Ukraine

ACCOUNT NUMBER: 400807238

BENEFICIARY BANK NAME: JP MORGAN CHASE BANK, New York

BENEFICIARY BANK BIC: CHASUS33

ABA 0210 0002 1

BENEFICIARY BANK ADDRESS: 383 Madison Avenue, New York, NY 10017, USA

PURPOSE OF PAYMENT: for ac 47330992708 

For donations in EUR:

BENEFICIARY: National Bank of Ukraine

IBAN DE05504000005040040066

PURPOSE OF PAYMENT: for ac 47330992708

BENEFICIARY BANK NAME: DEUTSCHE  BUNDESBANK, Frankfurt

BENEFICIARY BANK BIC: MARKDEFF

BENEFICIARY BANK ADDRESS: Wilhelm-Epstein-Strasse 14, 60431 Frankfurt Am Main, Germany

For donations in GBP: BENEFICIARY/RECIPIENT NAME: National Bank of Ukraine

ACCOUNT NUMBER: 80033041

IBAN GB52CHAS60924280033041

BENEFICIARY ADDRESS: 9 Instytutska St, Kyiv, 01601, Ukraine

BENEFICIARY BANK NAME: JP MORGAN CHASE BANK NA, London

BENEFICIARY BANK BIC: CHASGB2L

SORT CODE: 60-92-42 

BENEFICIARY BANK ADDRESS: 125 London Wall, London EC2Y 5AJ, UK

REFERENCE FOR CREDITING ACCOUNT: 47330992708

For donations in AUD:

BENEFICIARY: National Bank of Ukraine

BENEFICIARY BIC: NBUA UA UX

BENEFICIARY ADDRESS: 9 Instytutska St, Kyiv, 01601, Ukraine

ACCOUNT NUMBER: 817532

BSB code 092-002

BENEFICIARY BANK NAME: RESERVE  BANK OF AUSTRALIA, Sydney

BENEFICIARY BANK BIC: RSBKAU2S

BENEFICIARY BANK ADDRESS: GPO Box 3947, Sydney NSW 2000, Australia

PURPOSE OF PAYMENT: for ac 47330992708

For donations in CAD:

BENEFICIARY: National Bank of Ukraine

BENEFICIARY BIC: NBUA UA UX

BENEFICIARY ADDRESS: 9 Instytutska St, Kyiv, 01601, Ukraine

ACCOUNT NUMBER: 3144-1044-166

BENEFICIARY BANK NAME: BANK OF MONTREAL, Toronto

BENEFICIARY BANK BIC: BOFMCAM2

BENEFICIARY BANK ADDRESS: 100 King Street West, 24th Floor, Toronto, Ontario, M5X 1A9, Canada

PURPOSE OF PAYMENT: for ac 47330992708

For donations in PLN:

BENEFICIARY: National Bank of Ukraine

BENEFICIARY BIC: NBUA UA UX

BENEFICIARY ADDRESS: 9 Instytutska St, Kyiv, 01601, Ukraine

ACCOUNT NUMBER: PL91113000070080239435200002

BENEFICIARY BANK NAME: Bank Gospodarstwa Krajowego

BENEFICIARY BANK BIC: GOSKPLPW

BENEFICIARY BANK ADDRESS: Al. Jerozolimskie 7, 00-955 Warszawa, Polska (temporary address: Chmielna 73, 00-801 Warszawa, Polska)

PURPOSE OF PAYMENT: for ac 47330992708

Posted in Uncategorized | Leave a comment

Icon Picker component is now available on AppExchange

Today I have published my Icon Picker component on AppExchange

https://appexchange.salesforce.com/appxListingDetail?listingId=a0N4V00000GyzlDUAR

Icon Picker documentation

This listing includes LWC component Icon Picker which allows to select Icon from SLDS Icons Library

It can be used in the following use cases

1. Component can be placed in Lightning App Builder “App page” and used in Dynamic Interactions

2. Component can be placed in Screen Flows

3. Component can be reused in other LWC

Using IconPicker in App page

Create a new App page or place the component on an existing App Page.

Go to App Builder in Setup

Click a New button to create a new App Builder page or use Edit to edit existing App Page

If you create a new Page, select App Page and click Next button

Define a label for the new page, for example, Demo, and select any layout, for example, header and left sidebar. Find Icon Picker component in the “Custom – Managed” section and Drag and Drop that component to any place, like header or sidebar.

You can add other components, your custom unpackaged components or the same component in another section. You can read about creating custom unpackaged LWC components embedding Icon Picker in the section “Use IconPicker in Custom LWC Development”. In the Properties pane, you can set header label and field level help and mandatory indicator, for example, use `Icon Picker – Pick an Icon` like header and `Here you can pick an SLDS Icon` as field level help. If you check the required checkbox, the red asterisk will appear on the screen.

On the Interactions pane, it is possible to configure the dynamic interactions.

For example, let’s set source the IconPicker component in the header section and target the custom TestComp component in the left sidebar and the IconPicker component in the main section. To start, click Interaction pane and then click Add Interaction button.

While the source component is selected in the App Builder, in the component selector select target component IconPicker component from Main Region.

Then set {!Event.icon} in SLDS Icon fullname value attribute

and then click the Save button. If you created a new Page, Activate the page and set access to profiles and add it to application

Select if you want to add the page to all profiles or only System Administrator and add to some app like Sales and click Add page to app

and then click Save button

Then click Back button

And then click again Add Interaction to add another interaction to testComp component

Select TestComp or your custom component as target in Component selector

Set {!Event.icon} into destination attribute SLDS Icon fullname value

and then click the Save button again. Now let’s see in action. Click on nine dots in the top left corner and input the App page name in search box and click on Demo in the results list.

On the demo tab, pick the icon and see that the picked icon is sent into two other components through Dynamic Interactions, so the same icon is now selected in two bottom components

Notice that configured header is displayed above the icon picker, the red asterisk is displayed since Required attribute checkbox is checked and the help text is displayed when mouse is hover the information icon

Using IconPicker in Screen Flows

It is possible to add IconPicker to Screen Flows.

Before doing that, please enable Enable Lightning runtime for flows in Setup/Process Automation Settings

Find Flows in Setup and click the New Flow button to create a new flow or reuse the existing Screen Flow and click on it.

If you create a new Flow, select Screen Flow type and click Next

Select Free Form

Find Screen in list of Elements on the Elements sidebar panel and drag and drop it into canvas

Once you have added Screen to Canvas, scroll down to the last Custom section and select Icon Picker and drop it into Screen canvas.

In the sidebar pane, you can set header label and field level help and mandatory indicator, for example, use `Icon Picker – Pick an Icon` like header label and `Here you can pick an SLDS Icon` as field level help. Use GlobalConstant.true or GlobalConstant.false to show or hide the red asterisk to appear on the screen. Set IconPicker as API Name.

Select screen properties and set value of label to something like `Icon Picker Screen` and API name or keep the default API name. Then click the Done button.

Choose what to do with the value, for example, you can create an Account record, whose Name is icon fullname. For that, select Create Records and drag and drop it into Flow canvas

Set Label and API Name to Create, select Use separate resources, and literal values in How to Set the Record Fields

Select Account as Object

Select Account Name as Field name

and then in value select Icon Picker and then SLDS Icon Fullname Value

Click on Done once finished

Add another Screen element and set Label and API Name to Final

Add a Display Text component to the Final Screen

Set API name to Created and Set Created account into the Text Box and then click insert Resource and select AccountId from Create

Then add with name and click again Insert a resource and select Icon Picker and then select Value (SLDS Icon Fullname Value)

Click Done now

Then connect Start element to Screen element and then Screen Element to Create records component and Create records component to Final Screen element.

Now click Save, then Activate and then Run. When prompted, set label and API name of Flow to Demo and set Description to `Demonstrate how Icon Picker element can be used in Screen Flow` and click Save

Once saved, click Activate and Run

When you run the demo, pick some icon

and then click Next

Now you should be able to see the confirmation that a new Account with given name which is equal to Icon name was created and now you can click the Finish button.

Using IconPicker in Custom LWC Development

You can use this component in your Custom LWC Development. Before you start, go to Setup Session Setting and check checkbox Use Lightning Web Security (beta) for Lightning web components.  and click the Save button.

If you don’t perform this step, you will not be able to use cross-namespaced LWC components in your development.

Then create a new LWC and put some code into html file like this

<template>

    <iconPicker-icon-picker label=”Picker” value={icon} onselect={handleSelect}></iconPicker-icon-picker>

    Label: {selectedItem.label} <br/>

    Icon fullname: {selectedItem.icon}

</template>

Go then to javascript file and put code like this

import { LightningElement, track, api } from ‘lwc’;

export default class TestComp extends LightningElement {

    @api icon;

    @track selectedItem = {};

    handleSelect(event) {

        this.selectedItem = event.detail;

    }

}

Go to js-meta.xml metadata file and put code like this

<?xml version=”1.0″ encoding=”UTF-8″?>

<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata”&gt;

    <apiVersion>53.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__Tab</target>

        <target>lightning__RecordPage</target>

        <target>lightning__AppPage</target>

        <target>lightning__HomePage</target>

    </targets>

    <targetConfigs>

        <targetConfig targets=”lightning__AppPage”>

            <property name=”icon” label=”SLDS Icon fullname value” type=”String” />

        </targetConfig>        

    </targetConfigs>

</LightningComponentBundle>

Setting target configuration will allow you to use your custom component on the App page using App Builder. If you want to put your custom LWC component or Icon Picker to App page using App Builder, refer to the first section. If you want to read more about global attributes and methods of Icon Picker component, refer to the next section

Global attributes and methods of Icon Picker component

Before you start using any of attributes or methods, make sure you have read the previous section and have enabled Use Lightning Web Security (beta) for Lightning web components in Setup\Session Settings.

Attributes

NAMETYPEACCESSREQUIREDDEFAULTDESCRIPTION
headerStringglobalThe header label for the icon picker input
mandatory BooleanglobalfalseThe indicator for the red box requiredness option
fieldLevelHelpStringglobalThe help tooltip displayed on hover over the information icon when set
valueStringglobalThe value of selected icon (input and output)

Methods

NAMEARGUMENTSACCESSDESCRIPTION
reportValidityglobalDisplays the error messages and returns false if the input is invalid.If the input is valid, reportValidity() clears displayed error messages and returns true.

Custom Events

select

The event fires when an icon is picked in the component.

The select event returns the following parameters.

 “label”: {

                                “type”: “string”,

                                “title”: “Id and route in parentheses”,

                                “description”: “Id and route in parentheses”

                            },

                            “icon”: {

                               “type”: “string”,

                               “title”: “Full icon name to use in lightning-icon”,

                               “description”: “Full icon name to use in lightning-icon like {!Event.icon} here or in LWC &amp;lt;lightning-icon icon-name={!icon}”

                            }

PARAMETERTYPEDESCRIPTION
labelstringId and route in parentheses
iconstringFull icon name to use in Dynamic interaction like {!Event.icon} or in LWC custom development <lightning-icon icon-name={!icon}

The select event properties are as follows.

PROPERTYVALUEDESCRIPTION
bubblesfalseThis event doesn’t bubble up through the DOM. May be changed in future releases to true if subscribers prefer such option
cancelablefalseThis event has no default behavior that can be canceled. You can’t call preventDefault() on this event.
composedfalseThis event doesn’t propagate outside of the component in which it was dispatched. May be changed in future releases to true if subscribers prefer such option

Localization support for Icon Picker component

Translations are not included in the package distribution. However, a custom override is available for the “Empty” label and “Complete the field.” label.

Date of this document: 2nd January of 2022

Posted in Uncategorized | Leave a comment

Lightning:unsavedChanges is not working when exposed via Lightning Out

On 9/3/2021 3:26 PM I have opened Salesforce support ticket asking why lightning:unsavedChanges is not working when exposed through Lightning Out. We had very long conversation over last two months, they have requested to provide org access to reproduce the issue and I have provided them. On 11/1/2021 8:31 PM Salesforce support suggests to raise an idea to have this supported in future releases. Two months have passed and the only workaround that Salesforce support can provide, it to suggest Idea on Idea Exchange. I have opened an idea https://ideas.salesforce.com/s/idea/a0B8W00000H4BVBUA3/support-lighningunsavedchanges-in-lightning-out

My original case description

The component “lighning:unsavedChanges” doesn’t work when exposed through Lightning Out

If component lightning:unsavedChanges is used in Aura component that is exposed via Lightning Out to the Visualforce Page and this page is set as a tab in the Lightning Expience, calling unsaved.setUnsavedChanges(true, { label: ‘My component name’ }); has no effect.
Is this a bug?

Salesforce Support response

We have tried checking with different teams on the workaround for this problem , however it is not working as expected in lightning.

The lighning:unsavedChanges is not supported in Lightning Out , and hence our team has mentioned that we do not usually provide workarounds for features that are not supported.

However, I still tried my best to search for ways to make the classic api solution work , but that does not seem to work in lightning context.

Please do raise an idea to have this supported in the future releases.

Please let us know if you have any queries / concerns.

During the conversation, they suggested to use window.postMessage or classic api, and they didn’t believe that this doesn’t work, now I feel a little bit relieved that they confirmed that such solution doesn’t work.

Posted in Uncategorized | Leave a comment

2GMP Version of BOF Per Man

BOF Per Man: Bulk Object and Field Permission Manager

This package allows editing Field and Object Security per Profiles and Permission Sets in bulk. It is very useful by Administrators and Developers to mass edit profiles and permission sets if the same set of permissions needs to be applied to several profiles, permission sets, objects or fields.

Now the package is upgraded to the 2GMP version. The new version includes the existing feature from the classic package version and brings new features of bulk object creation and bulk text field creation.

Release Notes for the 2GMP Version

https://github.com/Patlatus/BofPerMan/issues/4

Missing objects :PartyConsent EngagementChannelType CommSubscription CommSubscriptionChannelType CommSubscriptionConsent CommSubscriptionTiming

In the previous 1GMP version 1.0.3 some objects were not available for selection in Bulk Object Permission Manager tab like

  • PartyConsent
  • EngagementChannelType
  • CommSubscription
  • CommSubscriptionChannelType
  • CommSubscriptionConsent
  • CommSubscriptionTiming

These objects and new objects added in Winter 2022 Salesforce Release are available in the new 2GMP version Bulk Object Permission Manager

https://github.com/Patlatus/BofPerMan/issues/1

Alphabet order, search, API name

New Feature Parameter is defined in the new 2GMP version to display API Names instead of Labels.

https://github.com/Patlatus/BofPerMan/issues/5

Failed to update records: FIELD_INTEGRITY_EXCEPTION

New Feature Parameter is defined in the new 2GMP version to enable experimental resolve dependency feature.

Internal #24 Make interface for bulk object creation

New feature and new tab added to bulk create objects

Internal #27 Make interface for bulk field creation

New feature and new tab added to bulk create text fields

Internal #12 Bulk tab permission – no way to bulk update tab permissions

New feature and new tab added to manage tab permissions in bulk

Posted in Uncategorized | Leave a comment

Delete existing Duplicate Rules from the org?

Save the script

https://gist.github.com/bdovh/1c0d87feab88bd712126e9f485a2f8ed
mkdir deploy
MY_XML="deploy/destructiveChanges.xml"
rm $MY_XML
rm "deploy/package.xml"

echo '<?xml version="1.0" encoding="UTF-8"?>\n<Package xmlns="http://soap.sforce.com/2006/04/metadata">\n<version>52.0</version>\n</Package>' >> "deploy/package.xml"


echo '<?xml version="1.0" encoding="UTF-8"?>\n' >> "$MY_XML"
echo '<Package xmlns="http://soap.sforce.com/2006/04/metadata">' >> "$MY_XML"
echo '    <types>' >> "$MY_XML"
for each in $(sfdx force:mdapi:listmetadata -m DuplicateRule --json | jq '.result[].fullName' -r); do
    echo "        <members>$each</members>" >> "$MY_XML"
done
echo '        <name>DuplicateRule</name>' >> "$MY_XML"
echo '    </types>' >> "$MY_XML"
echo '    <version>52.0</version>' >> "$MY_XML"
echo '</Package>' >> "$MY_XML"
sfdx force:mdapi:deploy -d deploy -w 500

as file delete.sh and then execute it

Posted in Uncategorized | Leave a comment

Is this possible to implement placeholder in lightning:datatable?

I have some weird requirement to display placeholder in the datatable and I don’t want to implement a custom datatable component for this but to use standard lightning:datatable.

Is this possible to implement such placeholder so that if a cell has blank value, a placeholder in gray text color is displayed instead of the value using standard lightning:datatable?

0

Recently a new feature was released which allows to define custom data types in standard lightning:datatable component.

Create a LWC component customTable with the following JS

import LightningDatatable from 'lightning/datatable';
import placeHolder from './placeHolder.html';

export default class CustomTable extends LightningDatatable {
    static customTypes = {
        placeHolder: {
            template: placeHolder,
            standardCellLayout: true,
            typeAttributes: ['placeHolder'],
        }
    }
}

Create in the customTable folder additional file placeHolder.html

<template>
    <template if:true={value}>
        <lightning-formatted-text value={value}></lightning-formatted-text>
    </template>
    <template if:false={value}>
        <lightning-formatted-text value={typeAttributes.placeHolder} style="color:#c9c7c5"></lightning-formatted-text>
    </template>
</template>

Update your row data to include placeholder text

rowData.placeHolder = 'Invoke action to populate this cell...';
Posted in Uncategorized | Leave a comment

How can we create custom objects in bulk?

There could be several ways to automate sobject creation, if we need to create multiple custom objects.

If you use SFDX, it is possible to use shane plugin to create custom object metadata file and then deploy those files or create a package from them and install the package.

upperlim=2000
for ((i=0; i<=upperlim; i++)); do
echo "$i"
sfdx shane:object:create -t custom -l "CustomObject$i" -p "CustomObjects$i" -a "CustomObject${i}__c"
done

Another option is to use Metadata API and create them in Apex

for (Integer i = 0; i < 100; i++) {
HttpResponse res = MetadataApiCustomObjectCreate.add('CustomObject' + i);
System.debug(res.getBody());
}
public without sharing class MetadataApiCustomObjectCreate {
private static String getSoapBodyXml(String name) {
return ''
+ '<?xml version="1.0" encoding="utf-8"?>'
+ '<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/&quot; xmlns:xsd="http://www.w3.org/2001/XMLSchema&quot; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">&#39;
+ '<env:Header>'
+ '<urn:SessionHeader xmlns:urn="http://soap.sforce.com/2006/04/metadata">&#39;
+ '<urn:sessionId>' + UserInfo.getSessionId() + '</urn:sessionId>'
+ '</urn:SessionHeader>'
+ '</env:Header>'
+ '<env:Body>'
+ '<createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">&#39;
+ '<metadata xsi:type="CustomObject">'
+ '<label>' + name + '</label>'
+ '<pluralLabel>' + name +'s' + '</pluralLabel>'
+ '<fullName>' + name + '__c' + '</fullName>'
+ '<nameField><label>Name</label><type>Text</type></nameField>'
+ '<deploymentStatus>Deployed</deploymentStatus>'
+ '<sharingModel>ReadWrite</sharingModel>'
+ '</metadata>'
+ '</createMetadata>'
+ '</env:Body>'
+ '</env:Envelope>'
;
}
public static HttpResponse add(String name) {
HttpRequest req = new HttpRequest();
req.setEndpoint(URL.getOrgDomainUrl().toExternalForm() + '/services/Soap/m/50.0');
req.setMethod('POST');
req.setHeader('Content-Type', 'text/xml');
req.setHeader('SOAPAction', '""');
req.setBody(getSoapBodyXml(name));
return new Http().send(req);
}
}
Posted in Uncategorized | Leave a comment

Salesforce: Use Apex to find out the current permissions of a user to an object

On enterprise projects Users tend to have a lot of Permission Set assigned.
So sometimes it is hard to determine what kind of access they have to a particular object, since verifying the profile settings and all the permission sets settings is a cumbersome task.
Instead, a simple apex script can do this job.
First, we need to find the DurableId of the object which access we need to check.
For this, we need a simple SOQL Query
SELECT DurableId FROM EntityDefinition where QualifiedApiName = ‘CustomObject__c’
Then we need to combine this with a user id and separate them by a dot and query the corresponding record from UserEntityAccess object.
SELECT Id, IsCreatable, IsReadable FROM UserEntityAccess where DurableId = ’01I0r0000005CqU.0051K000008xPfC’
And now we can see the actual permissions which User has to a particular field.

Posted in Uncategorized | Leave a comment

Find out which permission set provides read access to a field

To find which permission set provides read access to a field, use the following SOQL


SELECT ParentId FROM FieldPermissions WHERE
Field = 'CustomObject__c.CustomField__c'
AND SObjectType = 'CustomObject__c'
AND PermissionsRead = true
AND ParentId IN (SELECT PermissionSetId from PermissionSetAssignment WHERE AssigneeId = '005USerID0000AAA')

view raw

whichPS.soql

hosted with ❤ by GitHub

Posted in Uncategorized | Leave a comment

Salesforce: Use Apex to find out the current permissions of a user to a field

On enterprise projects Users tend to have a lot of Permission Set assigned.
So sometimes it is hard to determine what kind of access they have to a particular field, since verifying the profile settings and all the permission sets settings is a cumbersome task.
Instead, a simple apex script can do this job.
First, we need to find the DurableId of the field which access we need to check.
For this, we need a simple SOQL Query
SELECT DurableId FROM FieldDefinition where EntityDefinitionId = ‘CustomObject__c’ AND DeveloperName = ‘CustomField’
Then we need to combine this with a user id and separate them by a dot and query the corresponding record from UserFieldAccess object.
SELECT Id, IsAccessible, IsUpdatable FROM UserFieldAccess where DurableId = ’01I0r0000005CqU.00N0r000001AgFw.0051K000008xPfC’
And now we can see the actual permissions which User has to a particular field.

Posted in Uncategorized | Tagged , , , | Leave a comment