function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JasonRogersJasonRogers 

IDs as strings

Is there a way to convert IDs to strings?  I have a custom field on Opportunity that relates to another opportunity (marking the first opportunity as an upsale to the second).  I then need to do tests on the custom field against another opportunity's id, specifically that the custom field value is equal to the id or that the id starts with the custom field value, but there seems to be no way to compare strings and ids.  My APEX code is:
Code:
    public Opportunity[] relatedOpportunitiesFor(Opportunity opportunity) {
        Opportunity[] account_opportunities = opportunity.account.opportunities;
        Opportunity[] relatedOptys = new Opportunity[0];
        for (opportunity candidate : account_opportunities) {
            if(candidate.main_Opportunity__c.indexOf(opportunity.id) != -1
             && opportunity.id.indexOf(candidate.main_Opportunity__c) != -1
             && candidate.type == 'New') {
                relatedOptys.add(candidate);
            }
        }
        return relatedOptys;
    }

 

JasonRogersJasonRogers
I just realized that I mis-copied that code.  The if-statement inside the for-loop should be: Code:
         if((candidate.main_Opportunity__c.indexOf(opportunity.id) != -1
             || opportunity.id.indexOf(candidate.main_Opportunity__c) != -1)
             && candidate.type == 'New')
Thanks.  
JasonRogersJasonRogers
Still no response?

Aren't there any Salesforce folks on this list?  Has no one ever needed to translate between IDs and strings?
Ron HessRon Hess
I've never had to do this, but i tried this and it appears to compile.

Code:
package TestPackage{
 webService String TestService(String param1, String param2) {
  Id i = '0063000000BYIPp';   
  String s  = i;
  System.debug(s);
  return s;
 }
}

running this in the Apex Debug Log window, shows that it does work to cast an Id to a String

1174866104176:Package.TestPackage.TestService: line 5, column 9: 0063000000BYIPpAAP

Cumulative resource usage:
Number of SOQL queries: 0 out of 100
Number of query rows: 0 out of 10000
Number of DML statements: 0 out of 100
Number of DML rows: 0 out of 10000
Number of cursors: 0 out of 10
Number of queryMore operations: 0
Number of transaction control statements: 0 out of 20
Number of script statements: 6
Maximum heap size: 0 out of 1000000