Thursday, 22 February 2018

Salesforce - Serialize/deserialize Parent and child records

JsonString will be like


{"totalSize":1,"done":true,"records":[{"attributes":{"type":"Account","url":"/services/data/v39.0/sobjects/Account/00190000016V11FAAS"},"Id":"00190000016V11FAAS","Name":"birlasoft","Contacts":{"totalSize":6,"done":true,"records":[{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYh46AAD"},"Id":"0039000002MYh46AAD","Name":"Krishna K"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYgxfAAD"},"Id":"0039000002MYgxfAAD","Name":"Krishna K"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYgXrAAL"},"Id":"0039000002MYgXrAAL","Name":"Riaz Test"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYhF4AAL"},"Id":"0039000002MYhF4AAL","Name":"Deepika HR"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000002MYhHoAAL"},"Id":"0039000002MYhHoAAL","Name":"Romit Shilpe"},{"attributes":{"type":"Contact","url":"/services/data/v39.0/sobjects/Contact/0039000001AlZ2XAAV"},"Id":"0039000001AlZ2XAAV","Name":"Riazgood boy"}]}}]}




To process the above jsonString, below class will be useful

public class ParentChildJSON {
    public static void readJSON(){
        //I have stored the response jsonString in a static resource called ParentChildJSON
       // StaticResource srObject = [select id,body from StaticResource Where Name = //'ParentChildJSON'];
        //replace jsonString here
       //String jsonString = srObject.body.toString();
        String jsonString='';
        System.debug('jsonString: '+jsonString);
        //get the json in a map
        Map<String,Object> mp=(Map<String,Object>)JSON.deserializeUntyped(jsonString);
        String acc_cont_json='';
        //get accounts with contacts here
        for(String ky:mp.keySet()){
            if(ky.equals('records')){
                acc_cont_json=JSON.serialize(mp.get(ky));
            }
        }
        //now get accounts
        RecordVO[] rvos = getdeserializeSObjects(acc_cont_json);
        System.debug('total accounts: '+rvos.size());
        System.debug('accounts: '+rvos[0].recordFields);
        System.debug('contacts: '+rvos[0].children);
    } 
    public static RecordVO[] getdeserializeSObjects(String jsonString)
    {
        Object[] recObjects = (Object[])JSON.deserializeUntyped(jsonString);
        return serializeObjects(recObjects);
    }
    public static RecordVO[] serializeSObjects(SObject[] recs)
    {
        Object[] recObjects = (Object[])JSON.deserializeUntyped(JSON.serialize(recs));
        return serializeObjects(recObjects);
    }
 
    public class RecordVO
    {
        public Map<String, Object> recordFields { get; set; }
        public RecordVO[] children { get; set; }
     
        public RecordVO(Map<String, Object> fields, RecordVO[] ch)
        {
            recordFields = fields;
            children = ch;
        }
    }
 
    private static RecordVO[] serializeObjects(Object[] recObjects)
    {
        RecordVO[] rvos = new RecordVO[]{};
         
            // loop over each record
            for (Object recObj : recObjects)
        {
            Map<String, Object> recordFields = new Map<String, Object>();
            RecordVO[] children = new RecordVO[]{};
             
                // loop over each field or children
                Map<String, Object> objMap = (Map<String, Object>)recObj;
            for (String attr : objMap.keyset())
            {
                if (attr != 'attributes')
                {
                    // get children if applicable
                    if (objMap.get(attr) instanceof Map<String, Object>)
                    {
                        Object childObj = ((Map<String, Object>)objMap.get(attr)).get('records');
                        Object[] childObjList = (Object[])childObj;
                        if (childObjList != null)
                        {
                            RecordVO[] childrenVOs = serializeObjects(childObjList);
                            children.addAll(childrenVOs);
                        }
                    }
                    else
                    {
                        recordFields.put(attr, objMap.get(attr));
                    }
                }
            }
         
            rvos.add(new RecordVO(recordFields, children));
        }
     
        return rvos;
    }
}












call will be like,

ParentChildJSON.readJSON();




 //now get accounts & contacts
        RecordVO[] rvos = getdeserializeSObjects(acc_cont_json);
        System.debug('total accounts: '+rvos.size());
        System.debug('accounts: '+rvos[0].recordFields);
        System.debug('contacts: '+rvos[0].children);
        List<Account> acclist=new List<Account>();
        List<Contact> contlist=new List<Contact>();       
        for(RecordVO rvo:rvos){ 
            //add accounts
            acclist.add(new Account(Id=String.valueOf(rvo.recordFields.get('Id')),
                                    Name=String.valueOf(rvo.recordFields.get('Name'))));
            //add all contacts
            for(RecordVO vo:rvo.children){
                contlist.add(new Contact(Id=String.valueOf(vo.recordFields.get('Id')),
                                         FirstName=String.valueOf(vo.recordFields.get('Name'))));
            }
        }
        System.debug('acclist: '+acclist);
        System.debug('contlist: '+contlist);





Sunday, 18 February 2018

vlocity - Redirect from one omniscript to another omniscript

Add Done Action in the omniscript Step,



click on Done action to redirect to another omniscript.

Tuesday, 13 February 2018

Salesforce - How to get the API names of all objects that are related to an object.


Below code returns the all the related objects API names for the object Custom_Object__c.

Set<String> results = new set<String>();
for( ChildRelationship r: Custom_Object__c.SObjectType.getDescribe().getChildRelationships())
    results.add(string.valueOf(r.getChildSObject()));
System.debug(string.join(new List<String>(results),',');



for instance, to get all the related objects of Account, just replace Custom_Object__c in the above code like this,

Set<String> results = new set<String>();
for( ChildRelationship r: Account.SObjectType.getDescribe().getChildRelationships())
    results.add(string.valueOf(r.getChildSObject()));
System.debug(string.join(new List<String>(results),',');


The output is the comma separated list of all the related objects.


Get All apex classes related to an object:

1) create a contact record and use this contactId as parentId for the attachment.
2) replace the objectName with the list of objects separated by comma.
3) run the below code in dev console and download the file as csv.

String objectName='Task,AttachedContentDocument,Attachment,CombinedAttachment,ContentDocumentLink,ContentVersion,EmailMessage,EmailStatus,EntitySubscription,FeedComment,FeedItem,FlowRecordRelation,NetworkActivityAudit,PartnerNetworkRecordConnection,Task,TaskFeed,TopicAssignment';

List<String> objlist=objectName.split(',');
List<ApexClass> classeslist=[SELECT Id, Name,lastmodifiedby.name, Body FROM ApexClass order by Name];
String records='';
integer counter=0;
for(String ky:objlist){
for(ApexClass c:classeslist){
if(c.Body.containsIgnoreCase(ky) || c.Name.containsIgnoreCase(ky)){
records+=c.Name+',ApexClass,'+c.lastmodifiedBy.name+',ApexClass.'+c.Name+','+ky+'\n';
counter++;
}
}
}

//create attachment
Attachment att=new Attachment();
att.name='Complaints.csv';
att.parentId='0035B00000IStwD';
att.contenttype='csv';
att.body=Blob.valueOf(records);
insert att;
System.debug('file created with total records: '+counter);