5

I have a custom object with a number of record types. Now, in my controller, I want to write an if statement to check whether the current record is a certain record type.

I wrote:

        if (RecordType.Name == 'Recordtype1'){
            variable1= 'value1';
        }else{
            variable1 = 'value2';
        }

The problem seems to be that :

Comparison arguments must be compatible types: Schema.SObjectField,String

So I assume the problem is that Recordtype1 is a String and RecordType.Name returns an SObjectField.

How can I solve this problem? Thanks, Lily

  • Did you try to cast RecordType.Name on a String ? – SF_user Sep 25 '14 at 12:45
  • how would I do that? – user8737 Sep 25 '14 at 13:03
4

Lily,

you cannot directly use RecordType.Name

you can query the RecordType to get the name using the RecordTypeId on the custom object record and then compare the name against a string.

something like

RecordType rt = [Select Name from RecordType where SobjectType = 'CustomObject' AND Id = :cObj.RecordTypeId limit 1];
if (rt.Name == 'Recordtype1'){
    variable1= 'value1';
}else{
    variable1 = 'value2';
} 

additional references :

What would be the best approach to get the recordtype id

Why am I not getting the Record Type name when I use RecordType.Name

| improve this answer | |
2

Thanks to relationship queries, if you are querying your custom object in your controller, you can include the record type name in the query:

select Id, Name, ..., RecordType.Name from MyCustomObject__c where ...

and check the name directly in your logic:

MyCustomObject__c myObject = ...;
if (myObject.RecordType.Name == 'Recordtype1') {
    variable1 = 'value1';
} else {
    variable1 = 'value2';
}

In the code posted in the question, RecordType.Name is being interpreted as an SObjectField token because RecordType is an SObjectType token known to the compiler. These tokens are useful when writing code that works with a variety of objects, but unfortunately are easy to accidentally reference in code with confusing results.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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