Salesforce:Apex 触发器检查电子邮件域是否存在
Salesforce: Apex trigger to check whether email domain exists
我想知道邮箱域是否存在于数据库中。例如:如果要插入xxx@abc.com,我想检查具有相同域(abc.com)的电子邮件是否已经存在。以下是检查整个电子邮件是否存在的代码。
trigger trig_Contact_webToContact on Contact (before insert)
{
final String errMsg = 'The email already exists on another Contact: ';
Set< String > emailSet = new Set< String >();
for( Contact c : Trigger.new ) emailSet.add( c.Email );
Map< String, Id > duplicateContactMap = new Map< String, Id >();
for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
duplicateContactMap.put( c.Email, c.Id );
for( Contact c : Trigger.new ){
Id duplicateContactId = duplicateContactMap.get( c.Email );
if( duplicateContactId != null )
c.addError( errMsg + duplicateContactId );
}
}
首先,只从电子邮件中获取域,而不是整个电子邮件:
Set< String > emailDomainSet = new Set< String >();
for( Contact c : Trigger.new ) {
if (String.isBlank(c.Email)) continue;
int indexOfAt = c.Email.indexOf('@');
if (indexOfAt > 0) emailDomainSet.add( c.Email.substring(indexOfAt) );
}
那么,在您的情况下,您需要使用 query(queryString) 方法。先写一个SOQL字符串
string queryString = 'select name from Contact where ';
string whereClause = ' ';
for (string domainItem : emailDomainSet) {
whereClause += ' or Email like \'%'+domainItem + '\' ';
}
whereClause = whereClause.substring(4);//remove first or in where clause
queryString += whereClause;
然后,运行它。
而不是
for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
你应该放
for( Contact c : (List<Contact>)Database.query(queryString) )
我想知道邮箱域是否存在于数据库中。例如:如果要插入xxx@abc.com,我想检查具有相同域(abc.com)的电子邮件是否已经存在。以下是检查整个电子邮件是否存在的代码。
trigger trig_Contact_webToContact on Contact (before insert)
{
final String errMsg = 'The email already exists on another Contact: ';
Set< String > emailSet = new Set< String >();
for( Contact c : Trigger.new ) emailSet.add( c.Email );
Map< String, Id > duplicateContactMap = new Map< String, Id >();
for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
duplicateContactMap.put( c.Email, c.Id );
for( Contact c : Trigger.new ){
Id duplicateContactId = duplicateContactMap.get( c.Email );
if( duplicateContactId != null )
c.addError( errMsg + duplicateContactId );
}
}
首先,只从电子邮件中获取域,而不是整个电子邮件:
Set< String > emailDomainSet = new Set< String >();
for( Contact c : Trigger.new ) {
if (String.isBlank(c.Email)) continue;
int indexOfAt = c.Email.indexOf('@');
if (indexOfAt > 0) emailDomainSet.add( c.Email.substring(indexOfAt) );
}
那么,在您的情况下,您需要使用 query(queryString) 方法。先写一个SOQL字符串
string queryString = 'select name from Contact where ';
string whereClause = ' ';
for (string domainItem : emailDomainSet) {
whereClause += ' or Email like \'%'+domainItem + '\' ';
}
whereClause = whereClause.substring(4);//remove first or in where clause
queryString += whereClause;
然后,运行它。 而不是
for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
你应该放
for( Contact c : (List<Contact>)Database.query(queryString) )