Skip to content

Instantly share code, notes, and snippets.

@tarot
Last active July 8, 2016 02:36
Show Gist options
  • Select an option

  • Save tarot/f4b42e6d51e491988cff to your computer and use it in GitHub Desktop.

Select an option

Save tarot/f4b42e6d51e491988cff to your computer and use it in GitHub Desktop.
PicklistとMultiPicklistとTextかTextAreaな数式項目の値を、指定したLongTextArea項目に連結してコピーする。SOSLはこれらの項目を検索できないので。トランスレーションには無力(最後に更新した時のユーザ言語で保存される)。`NOW()`関数や親レコードを参照する数式にも無力(最後に更新した時の値で保存される)
public without sharing class FindHelper {
private static Map<Schema.SObjectType, Schema.SObjectField[]> fieldCache = new Map<Schema.SObjectType, Schema.SObjectField[]>();
public static void beforeSave(SObject[] xs, Schema.SObjectField searchField) {
Schema.SObjectField[] copyingFields = copyingFieldsOf(xs.getSObjectType());
Integer length = searchField.getDescribe().getLength();
for (SObject e : xs) {
putSearchField(e, copyingFields, searchField, length);
}
}
private static void putSearchField(SObject o, Schema.SObjectField[] copyingFields, Schema.SObjectField searchField, Integer length) {
String[] joiner = new String[] {};
for (Schema.SObjectField e : copyingFields) {
String x = (String) o.get(e);
if (!String.isBlank(x)) {
joiner.add(x);
}
}
o.put(searchField, String.join(joiner, ' ').left(length));
}
private static Schema.SObjectField[] copyingFieldsOf(Schema.SObjectType objectType) {
if (fieldCache.containsKey(objectType)) {
return fieldCache.get(objectType);
}
Schema.SObjectField[] result = new Schema.SObjectField[] {};
Map<String, Schema.SObjectField> fields = objectType.getDescribe().fields.getMap();
String[] fieldNames = new List<String>(fields.keySet());
fieldNames.sort();
for (String key : fieldNames) {
Schema.DescribeFieldResult describe = fields.get(key).getDescribe();
Schema.DisplayType type = describe.getType();
if (
type == Schema.DisplayType.Picklist ||
type == Schema.DisplayType.MultiPicklist ||
describe.getCalculatedFormula() != null && (type == Schema.DisplayType.String || type == Schema.DisplayType.TextArea)
) {
result.add(describe.getSobjectField());
}
}
fieldCache.put(objectType, result);
return result;
}
}
@tarot

tarot commented Jul 31, 2015

Copy link
Copy Markdown
Author

つかいかた

trigger SampleTrigger on Sample__c (before insert, before update) {

    if (Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
        FindHelper.beforeSave(Trigger.new, Sample__c.LongTextArea__c);
    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment