Metadata API – ABSYZ https://absyz.com Salesforce Gold Consulting and Implementation Partner Fri, 27 Nov 2020 10:46:44 +0000 en-US hourly 1 https://absyz.com/wp-content/uploads/2020/06/cropped-favicon-1-1-32x32.png Metadata API – ABSYZ https://absyz.com 32 32 Create/Update Salesforce Picklist definitions using metadata API https://absyz.com/create-update-salesforce-picklist-definitions-using-metadata-api/ https://absyz.com/create-update-salesforce-picklist-definitions-using-metadata-api/#respond Thu, 21 May 2020 07:51:19 +0000 http://blogs.absyz.com/?p=11116
Introduction:

Imagine you have a customer who is not familiar with Salesforce and there is a need to add/update picklist values along with record types in the system, then you cannot expect him to follow the ideal steps (Setup->Object Manager->) to make the changes. So, this problem can be solved by using Lightning Component with Metadata API Service. This component enables a user to make the required changes  across multiple fields in your Salesforce instance with couple of clicks from the UI itself.

Unique features:

1. On click Create/Update picklist values.

2. On click assigning of picklist values to the record types.

3. On click removing of picklist values from the record types.

4. On click Update of records upon updation of picklist values.

Display UI:

 

Functionality:

Step1: Object Name – Displays all the object names present in your Salesforce instance

Select an Object

 

Step2: Picklist – Displays all the fields of the selected Object

Select a Picklist

 

Step3: Action – Displays two actions available Create/Update

Select an Action which you want to perform

 

Step3a: If Action selected is ‘Create’

Select Record Types: – Displays all the available record types

Select the Record Types to which you want to assign the new picklist value

 

Step3b: Description – Contains the name of the new picklist value

Give the name of the new picklist value here

 

Step4: Action – Displays two actions available Create/Update

Select an Action which you want to perform

 

Step4a: Picklist Value to Update – Displays the picklist values related to the picklist field selected

Select a picklist value which you want to update

 

Step4b: Select RecordTypes

Selected Options – Displays all the record type names in which the selected value is already present

Available Options – Displays all the record type names in which the selected value is not present

Select the record types to which the picklist value need to be assigned and remove the record types from which the picklist value need to be removed

 

Step4c: Description – Contains the updated name of the picklist value

 

Step5: Save

Clicking on

 

required operation will be performed.

UI:

UniversalPicklist.cmp

You have to build a lightning component to get UI as shown in the above snippet, you need to display five fields and a button.

 

Object Name: You can either hard code what all objects you want to display in this field or get all the objects using schema

 

Picklist: As soon as you select an Object Name you need to make a server call and get all the respective picklist fields available. You can get all the fields using schema

Action: Since we need only two different actions here, you can display those two values using <lightning:select>

 

  • Create:- If you select ‘Create’ you need to make another server call and get all the record types in that particular object and display them in a format shown in the above snippet using <lightning:dualListbox>
  • Update:- If you select ‘Update’ this means that you want to update an existing picklist value. So, here also you need to make a server call get all the picklist values for a selected picklist field. You can refer to this doc for getting the picklist values

Picklist Value to Update: The obtained picklist values will be displayed here. As soon as a picklist value is selected, you should get all the record types which has and which doesn’t have this picklist value and display on the UI accordingly, as shown in the snippet.

Description: This field holds the new or updated picklist value which user enters

Back end Logic:

MetadataApiService.apxc

You should have a MetadataApiService class.

Refer this link, you can use the same class.

UniversalPicklistController.apxc

Create/Update picklist value for custom fields: You can refer to this link for creating or updating the piclist values using metadataservices

Create/Update picklist value for standard fields: Refer the below code for standard fields:

 

//Read
        MetadataApiService.StandardValueSet StandardField = (MetadataApiService.StandardValueSet) service.readMetadata('StandardValueSet', new String[] { picklistapiname }).getRecords()[0];
        
        MetadataApiService.StandardValue sv = new MetadataApiService.StandardValue();
        sv.fullName = valueInTheDescription;
        sv.default_x = false;
        StandardField.standardValue.add(sv);
        
        // Update 
        List<MetadataApiService.SaveResult> lstResults = service.updateMetadata( new MetadataApiService.Metadata[] { StandardField });

Updating Record Types: You can refer to this link to update Record Types

UniversalPicklistCntrlSessionIdGenerator.vfp

Use this code for generating session Id

 

<apex:page >
    Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id
</apex:page>

UniversalPicklistControllerUtils.apxc

 

global class UniversalPicklistControllerUtils {
    global static String getSessionIdFromVFPage(PageReference visualforcePage){
            String content= visualforcePage.getContent().toString();
            Integer s = content.indexOf('Start_Of_Session_Id') + 'Start_Of_Session_Id'.length(),
                e = content.indexOf('End_Of_Session_Id');
            return userinfo.getSessionId();
    }
}

 

]]>
https://absyz.com/create-update-salesforce-picklist-definitions-using-metadata-api/feed/ 0
Increase your Productivity with the Apex Metadata API https://absyz.com/increase-your-productivity-with-the-apex-metadata-api/ https://absyz.com/increase-your-productivity-with-the-apex-metadata-api/#respond Mon, 23 Mar 2020 10:45:09 +0000 http://blogs.absyz.com/?p=10385

The force.com Platform provides us with features which are out of the box and helps increase productivity! Such is the “Metadata API”.

Here, we will see how we can leverage the Metadata API and avoid doing tasks manually thus ultimately saving a lot of time!

What is Metadata API?

Launched back in the Summer’17 release the Apex Metadata API lets you make metadata changes directly from apex.

We can use the handy features of apex in order to build custom setup UI scripts and perform automation actions behind the script.

Let’s consider an example and see how it can help :

Suppose you are an ISV and have created an app involving automation’s and many other features which are not generally available.You have packaged all your changes and is ready to be installed across org’s.

Now, the admin team comes into picture for rolling out the changes. The admin team has to perform a lot of post installation steps manually using the setup UI over and over.

This is where the metadata API comes in, you can create custom setup UI scripts to guide the admins through the process, and perform back end change actions using metadata api which updates the metadata while they go through the process over clicks and that’s it the changes will be available.

Thus, avoiding repetitive steps.

Let’s look at few use cases where we can use the Metadata API:

  1. Using the Metadata API we can build tools which can automate configuration changes.
  2. We can update our metadata changes in multiple org’s by deploying it across multiple org’s from apex using the Metadata API Deploycallback class which uses a deployment container and executes based on actions specified.
  3. We can control multiple org metadata in a single org. And can perform CRUD operations.

There are lots of use cases around, let’s implement few and see how actually the Metadata API can help us increase productivity!

In our example here we will be retrieving the metadata from the contact object. We will retrieve a section named ‘Additional Information’ from the page layout of contact, add a new field into that section all from apex!!

Sounds Interesting ain’t that? Let’s check it out…

[sourcecode language=”Java”]

public class UpdateContactPageLayout {
public Metadata.layout addLayoutItem(){

//Retreive metadata from the contact page layout using Metadata.Operations.retrieve method
List Metadata.Metadata layoutsList =
Metadata.Operations.retrieve(Metadata.MetadataType.Layout,
new List String{‘Contact-Contact Layout’});

//Getting Layout from the contact object
Metadata.Layout layoutMetadata = (Metadata.Layout) layoutsList.get(0);
Metadata.LayoutSection contactLayoutSection = null;
List Metadata.LayoutSection layoutSections = layoutMetadata.layoutSections;

for (Metadata.LayoutSection section : layoutSections) {
/** Assigning section value to contactLayoutSection Variable if section label satisfies condition **/

if (section.label == ‘Additional Information’) {
contactLayoutSection = section;
break;
}

}

List Metadata.LayoutColumn contactColumns = contactLayoutSection.layoutColumns;
List Metadata.LayoutItem contactLayoutItems = contactColumns.get(0).layoutItems;

Metadata.LayoutItem newField = new Metadata.LayoutItem();
newField.behavior = Metadata.UiBehavior.Edit;
newField.field = ‘AMAPI__Apex_MD_API_Twitter_name__c’;
contactLayoutItems.add(newField);

system.debug(‘newfield Inserted’);
system.debug(‘contactLayoutItems’ + contactLayoutItems);
system.debug(newField);

return layoutMetadata;
}
}

[/sourcecode]

 

Let’s check out the logs and see whether a new field was created or not!

If you are trying this out instead of “amapi” in the newField.field variable specify your org’s namespace followed by the field you want to create.

E.g: ‘yourOrgNameSpace_Field_Name__c’

Screenshot (73)

We can see that the field got created, but in order to finally add the field in your layout we need to deploy the Metadata changes using Deploy container. This will finally add your metadata to the page layout.

Refer here for Deployment Container Class.

Now, let’s quickly look at another example of creating a record in a Custom Metadata Type.

In our case we have already created a Custom Metadata type called “Vat Rate”.

And we will be creating a new record for the custom Metadata Type using Custom Metadata API from apex.

If you are a newbie and have no idea how to create a custom metadata type refer this “Create Custom MetadataType“!

Let’s look at the code:

[sourcecode language=”Java”]

public class MetadataExample {
public void updateMetadata(){

//Retreive custom metadata type details from org
Metadata.CustomMetadata customMetadata = new Metadata.CustomMetadata();

//insert the fullName and Label value for the record you want to create

customMetadata.fullName = ‘VAT_Rate.NewRecordFromMetadataAPI’;
customMetadata.label = ‘NewRecordFromMetadataAPI’;

//We will populate the field called Rate in the Custom Metadata type with some value
Metadata.CustomMetadataValue customField = new Metadata.CustomMetadataValue();
customField.field = ‘Rate__c’;
customField.value = 10;

/**Adding record values to the customMetadata type ***/
customMetadata.values.add(customField);

/** Deployment Container to deploy the metadata changes **/

Metadata.DeployContainer deployContainer = new Metadata.DeployContainer();
deployContainer.addMetadata(customMetadata);

/** This will invoke the deployment Process of the changes **/
system.debug(‘customMetadata’+customMetadata);
system.debug(‘Metadata deployed’);

Id asyncResultId = Metadata.Operations.enqueueDeployment(deployContainer, null);
}
}

[/sourcecode]

Also, check the logs just to be sure there are no errors! 😀

Screenshot (74)

You can track your metadata change deployment in the Deployment Status.

Navigate to Setup –>In Quick Find type “Deployment Status” and click on the record initiated with proper timestamp details.

Screenshot (77)

Once the changes are deployed, we will navigate to the Custom Metadata Type and check whether a record has been created or not.

Let’s navigate to the Vat Rate Custom metadata type and see.

Screenshot (78)

 

Now let’s navigate to the record detail page and check whether the value of “rate” specified in code is populated or not.

Screenshot (79)

That’s it! We have created a metadata record type using the Metadata API from Apex and not manually!!

Advantages of using the Metadata API:

  1. You can deploy your metadata changes using deployable packages across multiple org’s without needing to create change sets and doing tasks manually.
  2. You can write custom scripts to perform backend actions for automating metadata changes across the org. thus eliminating a major heck of manually work for the SF admins out there!! Interesting? Ain’t that.

You can also create CustomMetadata types using the MetadataService class library.

That shall be all for now!

We will continue to dive deep on this in the next follow up blog and also check how to test your MetadataAPI and discuss possibilities of designing a solution for Bulk Creation of Custom Metadata Types and automate Metadata Changes.

Thank you for reading!!

Don’t be shy to try it out, and keep on blazing your trails!! 🙂 

 

 

 

 

 

]]>
https://absyz.com/increase-your-productivity-with-the-apex-metadata-api/feed/ 0