Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have some logic where I need to iterate thru a bunch of Opportunities. I need to be able to determine when I hit a new Opportunity Owner ID.

I try:

String lastownerId = '';

for (Opportunity opportunity: opportunities) {
    if(opportunity.OwnerId == (lastownerId)) {
        ...
        ...

I get: System.StringException: Invalid id:

any tips?

share|improve this question
add comment

3 Answers

up vote 6 down vote accepted

Salesforce has an ID-type, so you could use Id lastownerId = null; instead. This has the big advantage of being 15/18 character id insensitive in comparison, using string type may get you false negatives depending on what the input-id's look like.

Right now, you're apparently comparing some non-id string with an id. You will definitely get the error you see if you compare for example "apples" with an actual id, right now you're comparing it to an empty string which is also an invalid id. Comparing a valid id to null will not generate an error and result in False being returned as you might expect.

share|improve this answer
1  
Completely agree with this. I ran into an issue the other day where I had a Custom Setting with a string type for ID. The issue ended up being comparing an 18-digit Id with a 15-digit one like Martin describes. Definitely use the Id type whenever you can. –  James Loghry Jan 2 '13 at 21:31
add comment

You can't convert an empty String to an Id so the if-condition fails on first execution. Try changing the variable declaration to

Id lastOwnerId = null;
share|improve this answer
add comment

Here you are comparing ID data type(opportunity.OwnerId) with String data type(lastownerId) value thats why you are getting this error.

There are 2 possible solutions -

1) either change lastownerId data type to Id like - 
       Id lastownerId = null;

2) OR convert opportunity.OwnerId to string first then compare;
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.