Salesforceで動的にsObjectのすべての必須フィールドのリストを取得します

Aug 23 2020

スキーマレベルで必須とマークされたフィールドのリストを作成したいと思います。以下のスニペットを試しました。うまく機能しますが、デフォルト値のフィールドでは失敗します。

Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get('contact') ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;   
 
for(String f : fields.keyset())
{
   Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe();
   if( desribeResult.isCreateable() && !desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate())
   {
     //This is mandatory/required field 
   }
}

:デフォルト値が設定されているフィールドを含める必要があります。

回答

1 HengkyIlawan Aug 26 2020 at 23:13

この条件!desribeResult.isDefaultedOnCreate()は、レコードの作成時にフィールドにデフォルト値があるかどうかを決定するため、この条件は必要ありません。

システム定義のフィールドが必要ない場合は、 isCustom()

if (desribeResult.isCreateable() 
        && !desribeResult.isNillable()
        && describeResult.isCustom()) {

  //This is mandatory/required field 

}