อ้างอิง sObject Fields แบบไดนามิกจากค่าสตริง

Oct 23 2020

เป็นไปได้ไหมที่จะอ้างอิงฟิลด์ของ sObject (โอกาสในตัวอย่างนี้) แบบไดนามิกจากค่าสตริง

ตัวอย่างเช่นใช้รหัสต่อไปนี้:

 for(Opportunity o: oppList) {
      for(String s : strList) {
           // I'd like to set the opportunity field values based on the string 
           // value that contains the API name of the opportunity field
      }
 }

ดังนั้นตัวแปรจึงstrListมีชื่อฟิลด์ API โอกาส ฉันกำลังพยายามล้างบางฟิลด์ในโอกาสในทริกเกอร์ก่อนการอัปเดต แต่ฉันต้องเข้าถึงชื่อฟิลด์แบบไดนามิกในไฟล์strList.

คำตอบ

2 sfdcfox Oct 23 2020 at 04:09

ใช่เมธอด "get" และ "put" อนุญาตให้อ่านและเขียนฟิลด์ตามชื่อฟิลด์:

for(Opportunity record: records) {
  for(String fieldName: fieldNames) {
    Object value = record.get(fieldName); // Get a field value!
    record.put(fieldName, null); // Clear a field!
  }
}