8

This is a question about the isSet function on SObjects.

Even though the documentation says it has a void type, it really is a boolean.

The sample in documentation provided is quite simple and works fine:

Contact c = new Contact(LastName = 'Joyce');
System.assertEquals(true, c.isSet('LastName'));
System.assertEquals(true, c.isSet(Contact.LastName));

However the isSet function doesn't seem to work for OwnerId only when using the Schema.SObjectField parameter version

Contact c = new Contact(OwnerId = UserInfo.getUserId());
System.assertEquals(true, c.isSet('OwnerId')); // works fine
System.assertEquals(true, c.isSet(Contact.OwnerId)); // Fails

I've tried isSet with other polymorphic lookup fields like Task.WhatId and this behaviour appears to be the same for those as well.

Is this expected? what am I missing

1 Answer 1

9

It is expected behavior, because when sObject is not created yet, the lookup fields will not appear as you expect in the isSet method with parameter of SObjectField Class.

However, after insertion there is possibility to retrieve OwnerId.

Contact c = new Contact(LastName = 'Joyce', OwnerId = UserInfo.getUserId());
insert c;
c = [SELECT LastName, Owner.Id FROM Contact LIMIT 1];
System.assertEquals(true, c.isSet('OwnerId')); // works fine
System.assertEquals(true, c.isSet(Contact.OwnerId)); // works fine

Note:

If you make select like this: c = [SELECT LastName, OwnerId FROM Contact LIMIT 1]; (OwnerId instead of Owner.Id) it will fail:

Contact c = new Contact(LastName = 'Joyce', OwnerId = UserInfo.getUserId());
insert c;
c = [SELECT LastName, OwnerId FROM Contact LIMIT 1];
System.assertEquals(true, c.isSet('OwnerId')); // works fine
System.assertEquals(true, c.isSet(Contact.OwnerId)); // fails

Note 2:

However, it will work like this:

Contact c = new Contact(LastName = 'Joyce', OwnerId = UserInfo.getUserId());
insert c;
c = [SELECT LastName, OwnerId FROM Contact LIMIT 1];
System.assertEquals(true, c.isSet('OwnerId')); // works fine
System.assertEquals(true, c.isSet(Contact.Owner.Id)); // works fine

P.S.: that bothers me too, but this is how it works.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .