+ Start a Discussion
MrTheTylerMrTheTyler 

Setting an ID field to '' (empty string) using put()

I found some interesting behavior today.

 

contact c  = new contact();
c.put('accountid', '');

system.debug(c.get('accountid')==null); //prints false
system.debug(c.accountid==null); //System.StringException: Invalid id: 

 

Why is the put() method allowed to update an ID field with an empty string if the direct route of c.accountid='' would raise an exception?

 

 

Cheers,

 

 

Tyler

Rahul SharmaRahul Sharma

Wow, wierd behavour.

I'm also eager to know why it alows put with a blank value.

If we change code to this it don't show error.

contact c  = new contact();
c.put('accountid', '');
system.debug( c.get('accountid')==''); 
system.debug(String.valueof(c.accountid)=='');

 

MrTheTylerMrTheTyler

The small annoyance that comes with this for me is that I am dealing with records passed from another developer's area of the system.  In these records there are several lookup fields which I need to determine whether they have a value.  I thought I was losing it for 2 hours when my if(record.lookupfield == null ) kept raising exceptions.  So now instead of if(record.lookupfield == null) I make a call the following function which is doing just what Rhaul suggests by casting id to a string;

 

	static boolean isIDFieldEmpty(string s){
		return (s==null || s=='');
	}

 

 

Cheers,

 

Tyler

Rahul SharmaRahul Sharma

ohh, i was wondering where you encountered this issue, Is it working now?

MrTheTylerMrTheTyler

Yes the workaround works around the strange behavior.  I'm still curious to know if this is a bug as this behavior means that any lookup field of any sObject must be treated as though it could have this empty string value.

 

 

Cheers,

 

Tyler