1

In a managed package i am trying to create an account record. There are org which use recordtypes and some orgs dont use recordtypes. So we have a setting which defines the recordtype needs to be associated with the account.

Here is the code i am using

if(String.isBlank(CS.Account_Default_Record_type__c) || Schema.SObjectType.Account.getRecordTypeInfosByName().size() > 1)
                {
                    account ac = new Account(name ='Storage Account');
                    insert ac;
                }
                else
                {

                    account ac = new Account(name ='Storage Account', recordtypeid = CS.CMFSH__Account_Default_Record_type__c );
                    insert ac;
                }

My dev env does not have recordtype for Account so it does give an error

Field does not exist: recordtypeid on Account

If i do enable recordtype this error should go off.

My question is, Would there be an error when we try install the app in an org which doesnt have recordtype enabled for account?

Is there a way we can assign value to field without using account.recordtypeid explicitly.

2 Answers 2

3

You can check if record type exists or not using the below schema method.

Schema.SObjectType.Account.getRecordTypeInfosByName().size()

If it exists then you can dynamically add values using sobject put method like

Account ac = new Account(name ='Storage Account');
if(Schema.SObjectType.Account.getRecordTypeInfosByName().size() > 1){
    ac.put('RecordtypeId',CS.CMFSH__Account_Default_Record_type__c);
}
insert ac;

Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm

0
-1

You need to check for the both conditions

  1. If Custom setting RecordType is Blank and There is no recordType for Account Record.

Try below code

if(String.isBlank(CS.Account_Default_Record_type__c) && Account.SObjectType.getDescribe().getRecordTypeInfos().size() ==1){
    account ac = new Account(name ='Storage Account');
    insert ac;
}else{
    account ac = new Account(name ='Storage Account', recordtypeid = CS.CMFSH__Account_Default_Record_type__c );
    insert ac;
}
3
  • This will still give compile time/install time error as you are refereing "recordtypeid " in apex code for orgs which has no recordtype enabled. Commented Jul 12, 2018 at 9:26
  • @PranayJaiswal is right. it does give compile error
    – Prady
    Commented Jul 12, 2018 at 9:32
  • @tushar - Have you tried this in your ORG. I tried the same and not getting any Error because every object has Master Record Type. There is one change in the Code need to use Account.SObjectType.getDescribe().getRecordTypeInfos().size() ==1 instead of Account.SObjectType.getDescribe().getRecordTypeInfos().size() ==0
    – Amit Singh
    Commented Jul 12, 2018 at 9:36

You must log in to answer this question.

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