• Sandeep Rahul PV
  • NEWBIE
  • 0 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 11
    Questions
  • 4
    Replies
Hi Guys,

How do Create, Update and Delete Picklist Value Sets through Apex?

Thanks
Sandeep.

User-added image

Hi Team,
 
I have created a Picklist Value set and I referred this to a custom picklist field. Now the requirement is I need to update the Picklist value set through apex on the batch run. Help me. 

Thank you
Sandeep.

User-added image

Hi Team,

I have an issue with Trigger, please help me.

Here I wrote an After Insert Trigger on EmailMessage sObject and this is the output(Image one) and can see ActivityId = Null but when I query the record with the same EmailMessage Id there is a value for ActivityId. What could be the issue?

User-added imageUser-added image

Hello,

We are using Partner Community. As we know all community users have their contacts. We sharing the Lead records as follows.

In the contact Object, we have on Standard Object "Related Accounts" as a child.

User:Contact.RelatedAccount = Lead.Account_Name__c (Custom Account lookup field).

=====================================================
Now the requirement is.

If the user U1 login to the community portal and the user has access to four Leads (L1,L2,L3,L4) and 
the L1 is the campaign member of Campaign C1.
the L2 is the campaign member of Campaign C2. and 
the L3, L4 does not belong to any Campaign. Then

User U1 should see only C1 and C2 Campaigns, not other campaigns.

If the user U2 Login to the community portal and the user has access to few Leads (L8, L9) and 
the L8 is the campaign member of Campaign C2. and 
the L9 does not belong to any Campaign. Then

User U2 should see only C2 Campaigns not other campaigns.

Please help me to complete the requirement.

Thank you.
Hi Guys,

I have an aura component that displays a newly created record on the lead detail page and it is forking fine for salesforce inside org but not in the community portal. Please help me to resolve this.

Thank you.
sandeep.
Aura:
====
<aura:component implements="lightning:availableForFlowScreens,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
    <aura:attribute name="Message" type="List" />
    <aura:attribute name="body" type="string" />
    <aura:attribute name="eventRecevied" type="boolean" />
    <lightning:empApi aura:id="empApi" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:if isTrue="{!v.eventRecevied}">
    {!v.body}
    </aura:if>
</aura:component>

Javascript:
========
({
    doInit : function(component, event, helper) {
        const empApi = component.find('empApi');
        const channel = '/event/SlickTextToastEvent__e';
        const replayId = -1;
        empApi.subscribe(channel, replayId, $A.getCallback(eventReceived => {
            // Process event (this is called each time we receive an event)
            console.log('Received event ', JSON.stringify(eventReceived));
            const body = component.get('v.Message');
            body.push(eventReceived.data.payload.Message__c);
            console.log('Received body ', eventReceived.data.payload.Message__c);
            console.log('Received body ', body);
            component.set('v.body',eventReceived.data.payload.Message__c);
            component.set('v.eventRecevied',true);
            helper.helperMethod(component, eventReceived.data.payload.Message__c);
        })) .then(subscription => {
            console.log('Subscription request sent to: ', subscription.channel);
        });   
     }
})

 

My Code:

Apex Class:
--------------------

public class LookupApexAuraServices {
@AuraEnabled
    public static List<Lead> ChooseExistingAcc(string leadId, string accountId){
        List<Lead> convertedList = new List<Lead>();
        Database.LeadConvert lc = new Database.LeadConvert();
        lc.setLeadId(leadId);
        lc.setAccountId(accountId);
        lc.setDoNotCreateOpportunity(true);
        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        convertedList = [SELECT Id, Name, RecordTypeId, 
                         IsConverted, ConvertedAccountId, ConvertedContactId 
                         FROM Lead where id =:leadId limit 1];
        system.debug('convertedList : '+convertedList);
        return convertedList;
    }
}

Test Class:
------------------
@IsTest
public class LookupApexAuraServices_Test {
    private class RestMock implements HttpCalloutMock {
        public HTTPResponse respond(HTTPRequest req) {
            String fullJson = 'your Json Response';
            
            HTTPResponse res = new HTTPResponse();
            res.setHeader('Content-Type', 'text/json');
            res.setBody(fullJson);
            res.setStatusCode(200);
            return res;
        }
    }
static testmethod void testChooseExistingAcc(){
        Id devRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId();
        List<Account> acclist = new List<Account>();
        Account a = new Account();
        a.RecordTypeId = devRecordTypeId;
        a.FirstName = 'Accfname';
        a.LastName = 'AccTestLName';
        acclist.add(a);
        insert acclist;
        List<Lead> leadlst = new List<Lead>();
        lead l = new lead();
        l.FirstName = 'testf';
        l.LastName = 'testlast';
        l.Email = 'asdfg@gmail.com';
        leadlst.add(l);
        lead ld = new lead();
        ld.FirstName = 'testfirst';
        ld.LastName = 'testlast';
        ld.Email = 'asdf@gmail.com';
        leadlst.add(ld);
        insert leadlst;
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new RestMock());
        LookupApexAuraServices.ChooseExistingAcc(ld.Id, a.Id);
        Test.stopTest();
    }
}
Code COverage is 95% but while deployment getting this error
Getting This Error While Validating in Production during Production "System.DmlException: ConvertLead failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Your lead is missing a field mapping for the fields. For help, talk with your admin" ....?
User-added imagePlease Help Me guys.

public with sharing class CommunityJourneyData {

    public static JSONGenerator resultJson;

    @AuraEnabled
    public static boolean checkNamedCredentials(){
        NamedCredential[] credentials = [SELECT Id, DeveloperName FROM NamedCredential WHERE DeveloperName LIKE 'Salesforce_Marketing_Cloud%'];
        return credentials.size() > 0;
    }

    @AuraEnabled
    public static String getJourneyMembership(String userId) {
        if (String.isBlank(userId)) {
            return '[]';
        }
        resultJson = JSON.createGenerator(true);
        resultJson.writeStartArray(); // [
        // Callout to SFMC to get the list of all journeys a user is in
        NamedCredential[] credentials = [SELECT Id, DeveloperName FROM NamedCredential WHERE DeveloperName LIKE 'Salesforce_Marketing_Cloud%'];
        for (NamedCredential credential : credentials) {
            checkJourneyMembershipWithNamedCredential(credential.DeveloperName, userId);
        }
        resultJson.writeEndArray(); // ]
        return resultJson.getAsString();
    }

    @AuraEnabled
    public static void checkJourneyMembershipWithNamedCredential(String credential, String userId) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:' + credential + '/interaction/v1/interactions/contactMembership');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        JSONGenerator requestJson = JSON.createGenerator(true);
        requestJson.writeStartObject();
        requestJson.writeFieldName('ContactKeyList');
        requestJson.writeStartArray();
        requestJson.writeString(userId);
        requestJson.writeEndArray();
        requestJson.writeEndObject();
        String requestBody = requestJson.getAsString();
        req.setBody(requestBody);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        //check if the request failed
        if (checkResponseStatus(res.getStatusCode()) == false) {
            return;
        }
        //Received a successful response

        JSONParser parser = JSON.createParser(res.getBody());


        //parse the JSON response to get the values in Contact Membership
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'contactMemberships')) {
                parser.nextToken();
                if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
                    String name = '';
                    String key = '';
                    Integer version = 0;
                    while ((parser.nextToken() != null) && (parser.getCurrentToken() != JSONToken.END_ARRAY)) {
                        if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'definitionKey')) {
                            parser.nextToken();
                            resultJson.writeStartObject(); // {
                            key = parser.getText();
                            resultJson.writeStringField('key', key);
                            name = getJourneyName(parser.getText(), credential);
                            resultJson.writeStringField('name', name);
                            resultJson.writeStringField('namedCredential', credential);
                        }
                        if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'version')) {
                            parser.nextToken();
                            version = parser.getIntegerValue();
                            resultJson.writeNumberField('version', version);
                            resultJson.writeBooleanField('exitingFromJourney', getExitStatus(key, userId, version, credential));
                            resultJson.writeEndObject(); // }
                        }
                    }
                }
            }
        }
    }

    @AuraEnabled
    public static String getJourneyName(String journeyKey, String namedCredential) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:' + namedCredential + '/interaction/v1/interactions/key:' + journeyKey);
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        if (checkResponseStatus(res.getStatusCode()) == false) {
            return '';
        }

        JSONParser parser = JSON.createParser(res.getBody());
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'name')) {
                parser.nextToken();
                String journeyName = parser.getText();
                return journeyName;
            }
        }
        return '';
    }

    @AuraEnabled
    public static Boolean ejectFromJourney(List<String> journeyKey, String userId, List<Integer> version, List<String> namedCredential) {
        if (journeyKey.size() != version.size()) {
            throw new CommunityJourneyException('An error has occurred while ejecting from journey');
        }
        for (Integer i = 0; i < journeyKey.size(); i++) {
            HttpRequest req = new HttpRequest();
            req.setEndpoint('callout:' + namedCredential[i] + '/interaction/v1/interactions/contactexit');
            req.setMethod('POST');
            req.setHeader('Content-Type', 'application/json');

            JSONGenerator requestJson = JSON.createGenerator(true);
            requestJson.writeStartArray(); // [
            requestJson.writeStartObject(); // {
            requestJson.writeStringField('ContactKey', userId);
            requestJson.writeStringField('DefinitionKey', journeyKey[i]);
            requestJson.writeFieldName('Versions');
            requestJson.writeStartArray(); // [
            requestJson.writeNumber(version[i]);
            requestJson.writeEndArray(); // ]
            requestJson.writeEndObject(); // }
            requestJson.writeEndArray(); // ]
            String requestBody = requestJson.getAsString();
            req.setBody(requestBody);
            Http http = new Http();
            HTTPResponse res = http.send(req);
            if (checkResponseStatus(res.getStatusCode()) == false) {
                throw new CommunityJourneyException('An error has occurred while ejecting from journey');
            }
            Map<String, Object> response = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            List<Object> errors = (List<Object>) response.get('errors');
            if (errors.size() > 0) {
                throw new CommunityJourneyException('An error has occurred while ejecting from journey');
            }
        }
        return true;
    }

    @AuraEnabled
    public static Boolean getExitStatus(String journeyKey, String userId, Integer version, String namedCredential) {
        if (String.isBlank(journeyKey) || String.isBlank(userId) || (version < 1)) {
            throw new CommunityJourneyException('An error has occurred while getting the exit status');
        }
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:' + namedCredential + '/interaction/v1/interactions/contactexit/status');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');

        JSONGenerator requestJson = JSON.createGenerator(true);
        requestJson.writeStartArray(); // [
        requestJson.writeStartObject(); // {
        requestJson.writeStringField('ContactKey', userId);
        requestJson.writeStringField('DefinitionKey', journeyKey);
        requestJson.writeFieldName('Versions');
        requestJson.writeStartArray(); // [
        requestJson.writeNumber(version);
        requestJson.writeEndArray(); // ]
        requestJson.writeEndObject(); // }
        requestJson.writeEndArray(); // ]
        String requestBody = requestJson.getAsString();
        req.setBody(requestBody);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        if (checkResponseStatus(res.getStatusCode()) == false) {
            throw new CommunityJourneyException('An error has occurred while retrieving the exit status from this journey');
        }

        JSONParser parser = JSON.createParser(res.getBody());
        Boolean result = false;
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'message')) {
                parser.nextToken();
                if (parser.getText() == 'Exit process Completed.') {
                    return false;
                }
                if (parser.getText() == 'Exit request received for processing') {
                    result = true;
                }
                if (parser.getText() == 'Exit request Not Found') {
                    return false;
                }
            }
        }

        return result;
    }

    public static Boolean checkResponseStatus(Integer responseCode) {
        if ((responseCode > 299) || (responseCode < 200)) {
            return false;
        }
        return true;
    }

}


============================================================

public class CommunityJourneyException extends Exception {

}
Hi Guys,

Please Help out. I have created one Email Template. And I have use this in Email Services As follows,

public class sendEmailNotification {
    public static void sendemail(){
        String EmailId;
        Id OrgWideEAId;
        Lead leadLst = [Select Id from Lead limit 1];
        EmailTemplate emailTemplate = [Select Id,Subject,Description,HtmlValue,DeveloperName,Body from EmailTemplate where name = 'EmailToClinicUsersWithClinic'];
        for(OrgWideEmailAddress owa : [SELECT Id, Address, DisplayName FROM OrgWideEmailAddress]){
            if(owa.DisplayName.contains('Medi')){
                EmailId = owa.Address;
                OrgWideEAId = owa.Id;
            }
        }
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setTargetObjectId(leadLst.id);
        message.setSubject('Sample Notification');
        message.setReplyTo(EmailId);
        message.setUseSignature(false);
        message.setOrgWideEmailAddressId(OrgWideEAId);
        message.setBccSender(false);
        message.setSaveAsActivity(false); 
        message.setTemplateID(emailTemplate.Id);
        message.setHtmlBody(emailTemplate.Body);
        //message.setWhatId(ld.accountid); //This is important for the merge fields in template to work
        message.toAddresses = new String[] {'sandeep@gmsil.com'};
            Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
                Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        
        if (results[0].success) 
        {
            System.debug('The email was sent successfully.');
        } else {
            System.debug('The email failed to send: ' +  results[0].errors[0].message);
        }
    }
    
}

I should get this:
User-added image

I Got This:
User-added image

 
Hi 

I have created an email template and automated it, like whenever a lead creates and sends the email to that lead. If the email recipient replay back then I have to store that in Lead custom fields. Is there any way to do it?
User-added imageWithout any knowledge, user record id got assigned to LinkedEntityId in ContentDocumentLink object what is the issue
Hi Guys,

How do Create, Update and Delete Picklist Value Sets through Apex?

Thanks
Sandeep.

User-added image
Hi Guys,

Please Help out. I have created one Email Template. And I have use this in Email Services As follows,

public class sendEmailNotification {
    public static void sendemail(){
        String EmailId;
        Id OrgWideEAId;
        Lead leadLst = [Select Id from Lead limit 1];
        EmailTemplate emailTemplate = [Select Id,Subject,Description,HtmlValue,DeveloperName,Body from EmailTemplate where name = 'EmailToClinicUsersWithClinic'];
        for(OrgWideEmailAddress owa : [SELECT Id, Address, DisplayName FROM OrgWideEmailAddress]){
            if(owa.DisplayName.contains('Medi')){
                EmailId = owa.Address;
                OrgWideEAId = owa.Id;
            }
        }
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setTargetObjectId(leadLst.id);
        message.setSubject('Sample Notification');
        message.setReplyTo(EmailId);
        message.setUseSignature(false);
        message.setOrgWideEmailAddressId(OrgWideEAId);
        message.setBccSender(false);
        message.setSaveAsActivity(false); 
        message.setTemplateID(emailTemplate.Id);
        message.setHtmlBody(emailTemplate.Body);
        //message.setWhatId(ld.accountid); //This is important for the merge fields in template to work
        message.toAddresses = new String[] {'sandeep@gmsil.com'};
            Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
                Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        
        if (results[0].success) 
        {
            System.debug('The email was sent successfully.');
        } else {
            System.debug('The email failed to send: ' +  results[0].errors[0].message);
        }
    }
    
}

I should get this:
User-added image

I Got This:
User-added image

 
Hello Frens,

I have a map<ID,ID>. Is there any way I get the key from value ?

ex: Map<1,101>

I have access to 101 but anyway I can get its key ?
Note: values are unique too. No redundant values.