+ Start a Discussion
RJ12RJ12 

I'm doing a REST API call to get the global value set and trying to deserialize the JSON result to get the picklist values in a List<String>.

Here is the JSON:

{
  "size": 1,
  "totalSize": 1,
  "done": true,
  "queryLocator": null,
  "entityTypeName": "GlobalValueSet",
  "records": [
    {
      "attributes": {
        "type": "GlobalValueSet",
        "url": "/services/data/v53.0/tooling/sobjects/GlobalValueSet/0Nt59000000AAAAAAA"
      },
      "Metadata": {
        "customValue": [
          {
            "color": null,
            "default": false,
            "description": null,
            "isActive": null,
            "label": "USA",
            "urls": null,
            "valueName": "USA"
          },
          {
            "color": null,
            "default": false,
            "description": null,
            "isActive": null,
            "label": "Canada",
            "urls": null,
            "valueName": "Canada"
          }
        ],
        "description": null,
        "masterLabel": "US States & Territories",
        "sorted": false,
        "urls": null
      },
      "Id": "0Nt59000000AAAAAAA"
    }
  ]
}
I need help in fixing the error and also how to get valueNames in a List<String>

Error: System.JSONException: Malformed JSON: Expected '{' at the beginning of an object.

Here is what I have tried so far:

Wrapper:
    public class GlobalValueSetWrapper{
        Metadata metadata;

    public class Metadata {
        public List<CustomValue> customValue;
    }
    
    public class CustomValue {
        public String label;  
        public String valueName;
    }
    }


Class:
//calling API to get the JSON result
HttpResponse res = GlobalValueSetAPIHandler.getResponse('Countries');
GlobalValueSetWrapper wrapper = (GlobalValueSetWrapper) JSON.deserialize(res.getBody(), GlobalValueSetWrapper.class);
Best Answer chosen by RJ12
RJ12RJ12

I'm able to fix it.

public class GlobalValueSetWrapper{
    public List<Records> records;

    public class Records {
        public Metadata metadata;
    }
    
    public class Metadata {
        public List<CustomValue> customValue;
    }

    public class CustomValue {
        public String label;
        public String valueName;    
    }

    public static List<String> getPicklistValues(HttpResponse response){
        List<String> picklistValues = new List<String>();
        
        GlobalValueSetWrapper wrapper = (GlobalValueSetWrapper) System.JSON.deserialize(response.getBody(), GlobalValueSetWrapper.class);
        
        for(GlobalValueSetWrapper.customValue value : wrapper.records[0].metadata.customValue){
            picklistValues.add(value.valueName);
        }
        system.debug('Piclist Values: ' + picklistValues);
        
        return picklistValues;
    }
}
msb-appsupport1.3905906418879758E12msb-appsupport1.3905906418879758E12 
I want to use Apex code and visualforce page to create a new lead.

In web, I need to choose a record type before I create a new lead. And there are three types of leads.
In visualforce page, I want to create a new lead with assigned record type using code.

The confusion for me is that the recordType is related list for the lead. I could extract a list of record type by the following.

for (list<RecordType> rts : [SELECT ID, name FROM RecordType WHERE SObjectType = 'Lead' Order by name])

However, I could not pull out the recordType for a lead by the following, since the recordType is related list.

Lead l = [SELECT RecordType FROM LEAD].

Besides, what I want is create a new lead like below.
Lead l = new Lead(firstname='testInsertLead2', lastname='test',company='Temp Company', RecordType = 'registration type lead');

Could anyone help me with this to access the related list using apex code or visualforce page?

Thanks a lot.


Best Answer chosen by msb-appsupport1.3905906418879758E12
Chidambar ReddyChidambar Reddy
Hi

Try the following it will be user friendly



Map<String,Id> recordtypeMap  = new Map<String,Id>();

for(Record Type leadRT :  [select id, Name from RecordType where SObjectType = 'Lead' ]){

recordtypeMap.put(leadRT.Name,leadRT.Id);
 }

//you can create lead by following 

Lead l = new Lead(firstname='testInsertLead2', lastname='test',company='Temp Company', RecordTypeId = recordtypeMap.get('registration type lead'));

// be sure to enter record type name correctly other wise it would give an error.



Thank you,
Choose it as Best Answer if it resolved your issue.



StormConsultingStormConsulting 
How can I get the current Salesforce User ID in an Apex class?

Any help is appreciated!

Chris
Best Answer chosen by Admin (Salesforce Developers) 
hisrinuhisrinu
You can get the current user id like this.

UserInfo.getUserId() which returns the user id of the current user.
Shaolin MasterShaolin Master 
I want to know how to parse the URL params from a get request
/services/apexrest/Endpoint/?subject=test&status=active&priority=1&origin=?subject=test&status=active&priority=1
I want to parse the url params in the class below
@HttpGet
    global static void getStatus() {
        RestRequest request = RestContext.request;
        System.debug(request.requestURI); 
        
    }

Please help!
Best Answer chosen by Shaolin Master
Maharajan CMaharajan C
Hi,

You have to write like below to parse the request:
@HttpGet
global static void getStatus() {
    RestRequest req = RestContext.request;
    String subject = req.params.get('subject');
    String status = req.params.get('status');
    String priority = req.params.get('priority');
    String origin = req.params.get('origin');
    
    system.debug('subject --> ' + subject  + ' status --> ' + status + 'priority --> ' + priority + 'origin --> ' + origin);

}

Thanks,
Maharajan.C
Palmira AngelovaPalmira Angelova 
Hi friends,

I need to look up specific Contacts on Accounts, but only include Contacts on Accounts that have Opportunities WHERE Stage IN('X','Y','Z') i.e. what I think of as a child -> parent -> child lookup. I've been using workbench for this. 

I couldn't figure out a way to do this within the syntax, so instead I opted for Account -> Contacts WHERE Account -> Opportunities meets my criteria, which seemed to make sense to me. However, my query is getting an error telling me I can't have a child -> parent lookup in the where clause:
"MALFORMED_QUERY: 
AND Id IN(SELECT Account.Id FROM Opportunity WHERE
ERROR at Row:5:Column:24
The inner select field 'Account.Id' cannot have more than one level of relationships"

Here is my query:
SELECT Id,
       (SELECT Id FROM Contacts WHERE Send_Partner_Updates__c = TRUE)
FROM Account
WHERE Account.POS_Provider_s__c NOT IN('Toshiba ACE', 'Toshiba ACE (old, non-integrated)')
      AND Id IN(SELECT Account.Id FROM Opportunity WHERE Stage IN('6 - Deployed', '6 - Deploying', '6.5 - Fully Deployed'))

Does anyone have a way to get by this? When I tried "SELECT Id FROM Opportunity", removing the child->parent lookup within the Opportunity query, I get this error: "The selected field 'Id' in the subquery and the left operand field in the where expression in the outer query 'Id' should point to the same object type"...so I haven't been able to think of a way around these two limitations.

Thanks for your help!
Best Answer chosen by Palmira Angelova
jigarshahjigarshah
Palmira,

Change the Account.Id to AccountId in the subquery for Opportunity hence your updated Soql query will now become
SELECT Id,
    (SELECT Id FROM Contacts WHERE Send_Partner_Updates__c = TRUE)
FROM Account
WHERE Account.POS_Provider_s__c NOT IN('Toshiba ACE', 'Toshiba ACE (old, non-integrated)')
      AND Id IN (SELECT AccountId, Stage FROM Opportunity WHERE Stage IN('6 - Deployed', '6 - Deploying', '6.5 - Fully Deployed'))
Hope that helps.
Best Answer chosen by Jetta
sharathchandra thukkanisharathchandra thukkani
Through the constructor of the Batch class you can do that..i.e if your class is DemoBatch. In the batch class define a List and assign in the Constructor When you will create instanace of batch.. you can do something like..

global class DemoBatch implements Database.batchable<sObject>{
global List<sObject> myList;
global DemoBatch(List<sObject> objList){
myList = objList;
}

}
----------------
DemoBatch  db = new DemoBatch(objList);
db.executeBatch(db);

But you can pass the query string and you can query in the start method.
Zen Newman 16Zen Newman 16 
Hello- I'm writing a scheduled Apex class that grabs all Accounts that are listed as 'Active' in a custom field, find's the most recent closed won Opportunity and passes a value from a lookup field on that opp back to another lookup on the Account. The class isn't flagging any problems for me, but throws an error when it tries to run upon being scheduled.

The error seems to indicate that it couldn't find any records to update. I verified that there are records that meet the criteria, and when I run the SOQL query in isolation it finds those records. When I try to debug it in the Execute Annonymous window, it also doesn't return any system.debug messages. I appreciate any help figuring out where I'm going wrong! 
The error:
Sandbox

Apex script unhandled exception by user/organization: 0053i000002hKdg/00D1g0000002qa7
Source organization: 00D3i000000ttF8 (null)
Scheduled job 'Se Update2' threw unhandled exception.

caused by: System.QueryException: List has no rows for assignment to SObject

Class.UpdateSEOnAccount.execute: line 8, column 1
The Apex Class:
global class UpdateSEOnAccount implements Schedulable{
    global void execute (SchedulableContext ctx){
        UpdateSE();
    }
    public void UpdateSE(){
        List<Account> Actlst = new list<account>();
        for(Account a : [SELECT Id FROM Account WHERE Customer_Status__c = 'Active']){    
             a.Sales_Engineer__c = [SELECT Id, SE__c, AccountId 
                          FROM Opportunity 
                          WHERE AccountId = : a.id AND StageName = 'Closed Won'
                          ORDER BY CloseDate DESC LIMIT 1].SE__c;
           system.debug('a is '+ a.Id);
           if(a.SE__c <> NULL){
           Actlst.add(a);
           }
            system.debug('size of list is '+ Actlst.size());
        }
        if(Actlst.size()>0){
            update Actlst;
        }
    }
}


 
Best Answer chosen by Zen Newman 16
veer soniveer soni
hy,
try below code. I'm sure it will help you.
global class UpdateSEOnAccount implements Schedulable{
    global void execute (SchedulableContext ctx){
        UpdateSE();
    }
    public void UpdateSE(){
        List<Account> Actlst = new list<account>();
        for(Account a : [SELECT Id,(SELECT Id, SE__c, AccountId FROM Opportunities WHERE StageName = 'Closed Won' ORDER BY CloseDate DESC LIMIT 1) FROM Account WHERE Customer_Status__c = 'Active']){    
              if(a.Opportunities.size() > 0){ 
Opportunity opp = a.Opportunities[0]; 
if(opp.SE__c != null){
 a.Sales_Engineer__c = opp.SE__c; 
Actlst.add(a);
 } 
}
}
        if(Actlst.size()>0){
            update Actlst;
        }
    }
}

don't forget to mark it as best answer.
Thank you
Tony Montana 6Tony Montana 6 
if(requestId != null) {
        
               List<GLOBAL_Request__c> requestObj = [select id, business_unit__c, recordtype.developername from GLOBAL_Request__c where id=:requestId AND recordtype.developername = 'Send_Survey' Limit 1];
            if (requestObj != null){        
            List<User> usrRec =[select id, NT_Login_Name__c from User where id=:UserInfo.getUserId() And NT_Login_Name__c != null Limit 1];
                    if(usrRec != null){
                    List<Contact> contactRec = [select id, contactRec.NT_Login_Name__c from contact where NT_Login_Name__c=:usrRec.NT_Login_Name__c ORDER by LastModifiedDate DESC Limit 1];         
                        if (contactRec != null){
                          List<Participant__c> participantRec = [select Id, Name,Survey_Taken_Date__c from Participant__c where Participant__c=:contactRec.Id AND Request__c=:requestObj.Id ORDER by CreatedDate DESC LIMIT 1];
                            if(participantRec != null && participantRec.Survey_Taken_Date__c == null){
                                ParticipantId = participantRec.Id;
                                contactId = contactRec.Id;
                                requestId = requestObj.Id;
                                Participant__c updateSurveyTakenDate = new Participant__c(id = ParticipantId, Survey_Taken_Date__c = System.now());            
                                       upsert updateSurveyTakenDate;  
                            } else if(participantRec != null && participantRec.Survey_Taken_Date__c != null){
                                Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, System.Label.LABS_SF_You_have_already_taken_this_survey));
                                return false;
                            } else {
                                Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, System.Label.LABS_SF_Participant_Not_Part_Of_This_Pool));                    
                                 return false;
                            }
                        }
                    }
            }
        }
  
And I am getting the following error.


1.Variable does not exist: NT_Login_Name__c
2.Variable does not exist: Id
3.Variable does not exist: Survey_Taken_Date__c
4.Variable does not exist: Id
5.Variable does not exist: Survey_Taken_Date__c

Will appreciate your help.

Thanks,
TM
      
Best Answer chosen by Tony Montana 6
Maharajan CMaharajan C
Hi Tony,

Instead of Null check use the IsEmpty function to check the list has data or not:

IsEmpty function will solve the List index out of bounds: 0 issue.
 
if(requestId != null) {

    List<GLOBAL_Request__c> requestObj = [select id, business_unit__c, recordtype.developername from GLOBAL_Request__c where id=:requestId AND recordtype.developername = 'Send_Survey' Limit 1];
	if (!requestObj.isEmpty()){        
	List<User> usrRec =[select id, NT_Login_Name__c from User where id=:UserInfo.getUserId() And NT_Login_Name__c != null Limit 1];
			if(!usrRec.isEmpty()){
			List<Contact> contactRec = [select id, contactRec.NT_Login_Name__c from contact where NT_Login_Name__c=:usrRec[0].NT_Login_Name__c ORDER by LastModifiedDate DESC Limit 1];         
				if (!contactRec.isEmpty()){
				  List<Participant__c> participantRec = [select Id, Name,Survey_Taken_Date__c from Participant__c where Participant__c=:contactRec[0].Id AND Request__c=:requestObj[0].Id ORDER by CreatedDate DESC LIMIT 1];
					if(!participantRec.isEmpty() && participantRec[0].Survey_Taken_Date__c == null){
						ParticipantId = participantRec[0].Id;
						contactId = contactRec[0].Id;
						requestId = requestObj[0].Id;
						Participant__c updateSurveyTakenDate = new Participant__c(id = ParticipantId, Survey_Taken_Date__c = System.now());            
							   upsert updateSurveyTakenDate;  
					} else if(!participantRec.isEmpty() && participantRec[0].Survey_Taken_Date__c != null){
						Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, System.Label.LABS_SF_You_have_already_taken_this_survey));
						return false;
					} else {
						Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, System.Label.LABS_SF_Participant_Not_Part_Of_This_Pool));                    
						 return false;
					}
				}
			}
	}
}

Thanks,
Maharajan.C
fiona gentryfiona gentry 
Hi,

Dear folks,

Here is what i want to do and thankfully was able to get answer using thread below with List
https://developer.salesforce.com/forums/ForumsMain?id=9062I000000BjjoQAC
,but now i am rewriting the same code using Map,but am getting error as 
 
Method does not exist or incorrect signature: void get(String) from the type Map
Here is what the end goal is 
 
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:

Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
Transform #2: 17 ➝ 1 + 7 ➝ 8

Here is code with Map
public class SDASMapConvert {
    

    
    
public static Integer returnInteger(String z, integer k){
        Integer retInt;
        String key = 'abcdefghijklmnopqrstuvwxyz';

        List<String>myAlphabets = z.split('');
        Map<String, String> myMap = new Map<String, String>();
        String strarr = '';

       for (integer i = 0; i < myAlphabets.size(); i += 2) {
        myMap.put(myAlphabets[i], myAlphabets[i + 1]);
    }

    for (String s : myMap.keySet()) {
        System.debug(s + ' is ' + map.get(s));
        strarr += string.valueOf(s);
    }
        
        system.debug('strarr --> ' + strarr);
        String s = '';
        for(integer i = 0; i < k ; i++){
            system.debug(' strarr --> ' + strarr);
            Integer total = 0;
            for(String s1 : strarr.split('')){
                total += integer.valueOf(s1);
            }
            system.debug(' total --> ' + total);
            strarr = string.valueOf(total);
        }
        
        system.debug(' ************* ' + strarr);
        if(!string.isEmpty(strarr))
            retInt = integer.valueOf(strarr);
        
        system.debug(' ************* ' + retInt);
        
        return retInt;
    }
    


}

Regards
Fiona
Best Answer chosen by fiona gentry
Maharajan CMaharajan C
Hi Flona,

Are you looking something like below:
 
Public class SDASMapConvert {
    
    public static Integer returnInteger(String z, integer k){
        Integer retInt;
        String key = 'abcdefghijklmnopqrstuvwxyz';
        
        List<String>myAlphabets = z.split('');
        Map<String, String> myMap = new Map<String, String>();
        String strarr = '';
        
        for (integer i = 0; i < myAlphabets.size(); i++) {
            String intNum = String.valueOf(key.indexOf(myAlphabets[i].toLowerCase())+1);
            myMap.put(myAlphabets[i], intNum);
        }
        
        for (String s : myMap.keySet()) {
            System.debug(s + ' is ' + myMap.get(s));
            strarr += string.valueOf(myMap.get(s));
        }
        
        system.debug('strarr --> ' + strarr);
        String s = '';
        for(integer i = 0; i < k ; i++){
            system.debug(' strarr --> ' + strarr);
            Integer total = 0;
            for(String s1 : strarr.split('')){
                total += integer.valueOf(s1);
            }
            system.debug(' total --> ' + total);
            strarr = string.valueOf(total);
        }
        
        system.debug(' ************* ' + strarr);
        if(!string.isEmpty(strarr))
            retInt = integer.valueOf(strarr);
        
        system.debug(' ************* ' + retInt);
        
        return retInt;
    }    
    
}

Thanks,
Maharajan.C
Sabrina Oliveira 3Sabrina Oliveira 3 
I'm using a Lightning Component to update a field called "Observations__c" in Account Object.
User-added image

It's working fine, but when I try to use it inside another component, I receive the following error:

EXCEPTION_THROWN [9]|System.NullPointerException: Attempted to upsert a null list

Component: 

<aura:component implements="force:lightningQuickActionWithoutHeader,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" controller="getAccount">

<aura:handler name="init" action="{!c.init}" value="{!this}" />
<aura:attribute name="accounts" type="Account" />
<aura:attribute name="recordId" type="Id" />

<ltng:require styles="/resource/slds103/assets/styles/salesforce-lightning-design-system.min.css"/>

 <form>
    <ui:inputText aura:id="client"
                  label="{!$ObjectType.Account.fields.Observations__c.Label}"
                  class="form-control"
                  value="{!v.accounts.Observations__c}"
                  placeholder="Insira, caso necessário, comentários adicionais"
    />
    <br />
    <ui:button class="form-control" aura:id="button" label="Anexar observação" press="{!c.save}"/>
</form>

 </aura:component>

Controller js:
({
init : function(component, event, helper) {
    var accId = component.get("v.recordId");
    var action = component.get("c.getAcct");

    action.setParams({
        "accountId": component.get("v.recordId")
    });

    action.setCallback(this, function(data) {
        component.set("v.accounts", data.getReturnValue());
    });

    $A.enqueueAction(action);
}, 
save : function(component, event, helper) {

    var action = component.get("c.saveAcct");
    var accounts = component.get("v.accounts");

    action.setParams({"act": accounts});
    $A.enqueueAction(action);

    console.log('save ran');

}
})

Apex Controller:
public class getAccount {
    @AuraEnabled 
    public static Account getAcct(Id accountId){
        return (Account) Database.query( ' SELECT Name, Observations__c FROM Account WHERE Id =: accountId LIMIT 1 ' )[0];
    }

    @AuraEnabled 
    public static Account saveAcct(Account act){
        upsert act;
        return act;
    }  
}

I'm calling <c:sparkAccount/> in my second component, but it is not working.
User-added image

What am I doing wrong? 
Best Answer chosen by Sabrina Oliveira 3
Maharajan CMaharajan C
Hi Sabrina,

This is because of the force:hasRecordId will loose the current page record Id context inside the child component. To overcome this you have to pass recordId from parent to child component.
 
<c:sparkAccount  recordId="{! v.recordId }"/>

Important The recordId attribute is set only when you place or invoke the component in an explicit record context. For example, when you place the component directly on a record page layout, or invoke it as an object-specific action from a record page or object home.

https://salesforce.stackexchange.com/questions/241412/forcehasrecordid-cascade



Thanks,
Maharajan.C