You will need an Apex Trigger
, I think. Below are some snippets you will find helpful.
Parent Type
You can determine the SObjectType
of the ParentId
field as follows:
public Boolean isContactRecord(Attachment record)
{
return record.ParentId != null &&
record.ParentId.getSObjectType() == Contact.sObjectType;
}
You can filter matching records to get the collection you care about:
public List<Attachment> filterContactRecords(List<Attachment> records)
{
List<Attachment> contactRecords = new List<Attachment>();
for (Attachment record : records)
{
if (isContactRecord(record)) contactRecords.add(record);
}
return contactRecords;
}
Parsing
You will need to use Regular Expressions
to get the FirstName
and LastName
values. The expression I think you should use is:
Mailchimp Stats for:\s+(\w+ \w+)
In Apex
, you could use this as follows:
static final Pattern names = Pattern.compile('(Mailchimp Stats for:\\s+(\\w+ \\w+)');
class Parser
{
final String name;
final String subject;
Parser(Attachment record)
{
Matcher m = names.matcher(record.Body);
if (m.find())
{
name = m.group(1);
line = record.Body.substringBefore('\n');
}
}
}
public static List<Task> parseNames(List<Attachment> contactRecords)
{
Map<String, Parser> nameToData = new Map<String, Parser>();
for (Attachment record : contactRecords)
{
Parser data = new Parser(record);
if (data.Name != null) nameToData.put(data.Name, data);
}
List<Task> tasks = new List<Task>();
for (Contact contact : [SELECT Name FROM Contact WHERE Name IN :nameToData.keySet()])
{
tasks.add(new Task(
ParentId=contact.Id,
Subject=nameToData.get(contact.Name).subject
// other fields
));
}
return tasks;
}
Architecture
How you want to manipulate the relevant Contact
records is unclear based on your OP, but the above should at least get you started. If you really want to check all these child records every time a Contact
gets updated, you will want a before update
trigger. I recommend implementing a handler pattern. You will need to research which pattern you feel works best for you.
However, it doesn't seem like the logical trigger event. My suggestion is that you should just trigger this logic whenever you create a Note
or Attachment
. In this case, you should use an after insert
trigger.
Workflow Rule
orProcess Builder
to analyze child records. It is unclear why you want this logic to be applied on update to theContact
, it seems like it should be when theNote
/Attachment
is created?