• gedeef
  • NEWBIE
  • 55 Points
  • Member since 2013

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 15
    Replies

Hi,

 

I am new to apex and creating a trigger to delete newly inserted contacts with duplicate emails. Actually since emails have to be unique in our salesforce instance, we are trying to do a cleanup right after new contacts are inserted.

 

Here's my trigger and I cannot get it saved due to this error: 
Error: Compile Error: unexpected token: global at line 28 column 0

 

Could any please help?? Thank you!!

 

****trigger****

trigger manageEmailAfterInsert on Contact (after insert, after update) {

/* This trigger is created by Heller to delete the duplicate contacts being inserted */
Set<String> setEmail = new Set<String>();
Map<String, Id> contactMap1 = new Map<String, Id>();
List<String> ToBeDeleted = new List<String>();
for (Contact Contact : trigger.new)
{
setEmail.add(Contact.Email);
contactMap1.put(Contact.Email,Contact.Id);
}

for(Contact dupContact : [select email from Contact where email in: setEmail])
{
if(contactMap1.containsKey(dupContact.Email))
{
ToBeDeleted.add(contactMap1.get(dupContact.Email));
}
}

If(ToBeDeleted.size() > 0)
//delete ToBeDeleted;
DeleteDupContact.deleteRecords();
}


global class DeleteDupContact {
@future
public deleteRecords(String[] ToBeDeleted) {

try {
DeleteResult[] deleteResults = connection.delete(ToBeDeleted);
for (int i = 0; i < deleteResults.length; i++) {
DeleteResult deleteResult = deleteResults[i];
if (deleteResult.isSuccess()) {
System.out
.println('Deleted Record ID: ' + deleteResult.getId());
} else {
// Handle the errors.
// We just print the first error out for sample purposes.
Error[] errors = deleteResult.getErrors();
if (errors.length > 0) {
System.out.println('Error: could not delete ' + 'Record ID '
+ deleteResult.getId() + '.');
System.out.println(' The error reported was: ('
+ errors[0].getStatusCode() + ') '
+ errors[0].getMessage() + '\n');
}
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}

Hi,

Requirement :

  1.  To Create a field called ‘chatter Group’ in opportunity creation page and the details page .Once the user enters the value in the field, along with other mandate fields and on saving the opportunity , a chatter group need to be created( with the name entered in the chatter group field) with the owner of the opportunity being the collaboration member to the group. Chatter group is not a mandatory field and the group can be created while updating the opportunity as well. A post feed should come to the group on  insertion and every time the opportunity is updated.
  2. Once a user is added to the ‘opportunity Team Member’ of the opportunity , he should automatically be added to the created group.

 

Problem : On Implementing the following  trigger , creation of the chatter group is happening . The opportunity team members are added to the chatter group .

Posting of a feed to the group is happening once an opportunity is created . But on editing an opportunity , the feed post to the group is happening twice .

 

Kindly let us know the solution to get feed post to the group to come only once on updating the opportunity.

 

Please find below the trigger that has been written to achieve the same.

 

 

trigger CrtGrpFeed on Opportunity (after update) {
    List<FeedItem> filist = new List<FeedItem>();
    List<Opportunity> opp = new List<Opportunity>();
    String strGroupFlag ;
    String strGroupName ;
    String strGroupId ;
    ID GrpId ;
    ID OppOwnerId ;
 
    try
    {
   
        for (Opportunity oppnew:Trigger.new)
        {
             opp = [select Name, OwnerId ,Chatter_Group__c , Chatter_group_flag__c , Chatter_Group_Id__c from Opportunity where Id =: oppnew.Id];   
             strGroupFlag = opp[0].Chatter_group_flag__c ;
             strGroupName = opp[0].Chatter_Group__c ;
             strGroupId = opp[0].Chatter_Group_Id__c ;   
             OppOwnerId = opp[0].OwnerId ;
             
             system.debug('@@@@@@@@@@@@@@@@@@@ Chatter Flag @@@@@@@@@@@@@@@@@@' +oppnew.Chatter_group_flag__c);
              if( oppnew.Chatter_group_flag__c != '1'  && oppnew.Chatter_Group__c <> null )
                 {
                          List<FeedItem> filist1 = new List<FeedItem>();
                          FeedItem post = new FeedItem();
                           String strName = [Select Name from User where Id =: oppnew.LastModifiedById].Name;
                            post.parentid = oppnew.id;
                            post.Body = 'New Chatter Group  '  +  oppnew.Chatter_Group__c +  'has been created for this pursuit ' +    'on ' +                            oppnew.LastModifiedDate;
                             filist1.add(post);
                           Database.insert(filist1,false);      
                           
                      system.debug('*************** CreateGroupInitiate *********************'); 
                      for (Opportunity op:opp)
                      {
                         CollaborationGroup grp= new CollaborationGroup();
                         grp.Name = strGroupName;
                         grp.CollaborationType = 'Private';
                         grp.OwnerId = OppOwnerId ;
                         system.debug('*************** Owner added *********************' + grp.OwnerId);
                         insert grp;
                         system.debug('*************** Group Inserted *********************');
                         GrpId = grp.Id;
                         strGroupId = grp.Id;
                         op.Chatter_Group_ID__c = GrpId;
                         op.Id = oppnew.Id ;  
                         op.Chatter_group_flag__c = '1'; 
                         upsert op ;
                        
                     List<CollaborationGroupMember> grpMrList = new List<CollaborationGroupMember>();
                         List<OpportunityTeamMember> OppList1 = [Select UserId , Opportunityid from OpportunityTeamMember where opportunityId= :oppnew.Id];
                         if(!OppList1.isEmpty())
                         { 
                         
                             for(OpportunityTeamMember member: OppList1)
                             {
                                   system.debug('*************** Member added initiation *********************');
                                   CollaborationGroupMember grpMr = new CollaborationGroupMember() ;
                                   grpMr.memberid = member.UserId;
                                   system.debug('@@@@@@@@@@@@@@@ UserId @@@@@@@@@@@@@@@' + grpMr.memberid);

                                   grpMr.CollaborationGroupId = GrpId ;
                                   system.debug('*************** Member added *********************' + member.UserId);    
                                   grpMrList.add(grpMr);
                                   system.debug('@@@@@@@@@@@@@@@ UserId @@@@@@@@@@@@@@@' + grpMrList );
                             
                             }
                             system.debug('@@@@@@@@@@@@@@@@@ CG Group members before insrt after loop@@@@@@@@@@@@@@@@@@@@'  ) ;
                             insert grpMrList;
                             system.debug('*************** Group members added *********************' ) ;
                         }
                     
                     }             
                
        }
   
      
         if( oppnew.Chatter_group_flag__c == '1'  && oppnew.Chatter_Group__c <> null &&  oppnew.Chatter_group_flag__c  == '1')
         {
           system.debug('*************** FeedPostInitiate *********************');
                 List<FeedItem> filist2 = new List<FeedItem>();
                 FeedItem post2 = new FeedItem();
                 post2.ParentId = strGroupId; //Chatter Group ID
                 String strName = [Select Name from User where Id =: oppnew.LastModifiedById].Name;
             
                 system.debug('*************** strName *********************' + strName);
            
                 post2.Body = 'Please find below the pursuit details ' +  '\n This was updated by '
                 + strName + ' at ' + oppnew.LastModifiedDate + '\n Pursuit Stage :' + oppnew.StageName 
                 + '\n Pursuit Type:' + oppnew.Type + '\n Estmated Pursuit value :' + oppnew.Estimate_Proposal_Value__c
                 + '\n Pursuit Currency : ' + oppnew.CurrencyIsoCode ;
                 system.debug('***************Currency Code Flag *********************'+ oppnew.CurrencyIsoCode  );
                 filist2.add(post2);
             
                       insert filist2;
       
        }
     }
  
   
    }
    
    catch (Exception e) 
    {
       // Generic exception handling code here Contact.AccountId
       system.debug('Exeption ->  ' + e );
    }
  

}

Hi All,

I am writting a trigger in which I am using:

Testpro__c.AllowableLimit__c = Testpro__c.AllowableLimit__c = Testpro__c.AllowableLimit__c-i;

Where i is an integer, with value=1 where as AllowableLimit__c is a field of number type and have default value of 10,

When in my trigger I am trying to save this line- I am getting error:

Error: Compile Error: Arithmetic expressions must use numeric arguments at line 6 column 63

My full trigger code is:
trigger testpatpro on Testpatient__c (before insert, before update) {
Integer i;
i=1;
if(Testpatient__c.Testpro__c!= Null)
{
//Testpro__c.AllowableLimit__c = Testpro__c.AllowableLimit__c = Testpro__c.AllowableLimit__c-i;

System.debug('Test');
}
}

where Testpatient__c and Testpro__c object have look up relationship.

I know its due to mismatch of Datatype, any idea how I can rectify it.

Thanks

  • July 05, 2013
  • Like
  • 0

Hi all,

 

I wonder if anyone can help or direct me.

 

I am trying to write my first trigger from scratch (until now I've only really updated existing ones and very rarely at that).

 

I have an object called "Audit" which has a lookup relationship to another object called "Reviewer".

 

What I need to happed is the following.

 

If within the Audit object the lookup for the reviewer changes, then two things need to happen:

 

1. Within the OLD Reviewer object I need to update a field called "Workload" and decrement the value within it by 1.

2. Within the NEW Reviewer object I need to update a field called "Workload" and increment the value within it by 1.

 

(If either old or new are blank/null then do nothing for that step but continue with the other step)

 

I think the above sounds pretty straightforward really but I'm stuck.

 

Any assistance would be gratefully received.

 

Thank you,

 

mi5tery

 

Hi,

 

I am new to apex and creating a trigger to delete newly inserted contacts with duplicate emails. Actually since emails have to be unique in our salesforce instance, we are trying to do a cleanup right after new contacts are inserted.

 

Here's my trigger and I cannot get it saved due to this error: 
Error: Compile Error: unexpected token: global at line 28 column 0

 

Could any please help?? Thank you!!

 

****trigger****

trigger manageEmailAfterInsert on Contact (after insert, after update) {

/* This trigger is created by Heller to delete the duplicate contacts being inserted */
Set<String> setEmail = new Set<String>();
Map<String, Id> contactMap1 = new Map<String, Id>();
List<String> ToBeDeleted = new List<String>();
for (Contact Contact : trigger.new)
{
setEmail.add(Contact.Email);
contactMap1.put(Contact.Email,Contact.Id);
}

for(Contact dupContact : [select email from Contact where email in: setEmail])
{
if(contactMap1.containsKey(dupContact.Email))
{
ToBeDeleted.add(contactMap1.get(dupContact.Email));
}
}

If(ToBeDeleted.size() > 0)
//delete ToBeDeleted;
DeleteDupContact.deleteRecords();
}


global class DeleteDupContact {
@future
public deleteRecords(String[] ToBeDeleted) {

try {
DeleteResult[] deleteResults = connection.delete(ToBeDeleted);
for (int i = 0; i < deleteResults.length; i++) {
DeleteResult deleteResult = deleteResults[i];
if (deleteResult.isSuccess()) {
System.out
.println('Deleted Record ID: ' + deleteResult.getId());
} else {
// Handle the errors.
// We just print the first error out for sample purposes.
Error[] errors = deleteResult.getErrors();
if (errors.length > 0) {
System.out.println('Error: could not delete ' + 'Record ID '
+ deleteResult.getId() + '.');
System.out.println(' The error reported was: ('
+ errors[0].getStatusCode() + ') '
+ errors[0].getMessage() + '\n');
}
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}

HI all,

 

I've just spent the last four hours attempting to write and test my first trigger.  We have a custom object Health Check that has a Master-Detail relationship to Accounts.  We instantiate a new HC record ~3 months.  We want to copy the notes from the previous HC to the new one.  I have taken a clicks & code approach to this. I am looking for hope on my code, but if there is a better way to approach this whole effort, I'm certainly open.

 

On the Health Checks object, I have a "Date Conducted" field and a rich text field (I know, but my users insisted) called "Health Check Notes." I also have an Account__c field, which contains the parent Account's ID.

On Accounts, I have a "Last Health Check Conducted" field and a "Health Check Notes" field (also a RTF).

 

I have a WFR that fires when a new Health Check is created or edited.  If "Date Conducted" >= "Last Health Check Conducted" (also covers my users editing their notes after the call as issues are resolved), I copy the contents of the Health Check Notes field from the child Health Check object to the parent Account.  That's tested and working.

 

Next, when a new HC is created, I need to copy the contents from the parent Account into the new HC record.  Since WFR won't go parent->child, I did some research and wrote a trigger:

 

trigger populateHealthCheckNotes on Health_Check__c (after insert){
  
    Map<Id,Account> accounts = new Map<Id,Account>
    ([select ID, Health_Check_Notes__c from Account where Id IN :trigger.newMap.keySet()]);
  
    for(Health_Check__c hc : trigger.new){
         if(hc.Account__c != null){
         hc.Health_Check_Notes__c = accounts.get(hc.Account__c).Health_Check_Notes__c;    
          }
    }   
 
}

 

 

 

I wrote a Test Class to go with this:

@isTest 
private class testPopulateHealthCheckNotesTrigger {
  static testMethod void testNotePopulation()  {
    Account testAccount = new Account(Health_Check_Notes__c = 'Negotiating',Name = 'test Name');
    insert testAccount;
    Health_Check__c testHealthCheck = new Health_Check__c(Account__c = testAccount.ID);

Test.startTest();
insert testHealthCheck;
Test.stopTest();
system.assert(testHealthCheck.Health_Check_Notes__c == testAccount.Health_Check_Notes__c);
}

}

 

 

 

However, I'm getting this error:

 

Time Started 6/25/2013 11:52 AM Class testPopulateHealthCheckNotesTrigger Method Name testNotePopulation Pass/Fail Fail Error Message System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, populateHealthCheckNotes: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.populateHealthCheckNotes: line 8, column 1: [] Stack Trace Class.testPopulateHealthCheckNotesTrigger.testNotePopulation: line 9, column 1

 

I'm pretty sure I'm doing something wrong and it has to do with grabbing the account ID and making sure I'm copying the right information, but I'm not sure where/how I'm going wrong exactly.  I need this to work, as I have a similar copy-and-paste exercise to do with two other fields, but trying to start small and stay on sure footing here.

 

All help greatly appreciated.

 

Not sure what missing here, something obvious I think. Had below to iterate through List to add fields in list to 3 Sets. This seems redundant first off, second it's not working, 3rd there's a better way to do it.  Adding to set so I can remove the duplicate field values. Two example records and my goal are:.

 

Record 1: July, Monday;Wednesday;Saturday, 2013

Record 2: July, Wednesday;Friday, 2013

 

Trying to get to:

yearsSet (1 record) - 2013

monthSet(1 record) - July

daysSet(4 records) - Monday, Wednesday, Friday, Saturday

 

List<Schedule_Connection__c> schconnList = [select id, Address_Type__c, Address_Type__r.Provider__c, Address_Type__r.Address__c,Schedule_Development__r.Scheduled_Days__c, Schedule_Development__r.YearNumber__c, Schedule_Development__r.MonthNumber__c, Schedule_Development__r.Start_Time__c,
Schedule_Development__r.End_Time__c from Schedule_Connection__c where Id in:schconnections];

Set<Integer> yearsSet = new Set<Integer>(), monthsSet = new Set<Integer>();
Set<String> daysSet = new Set<String>();
For(Schedule_Connection__c record : schconnList) {
yearsSet.add((record.Schedule_Development__r.YearNumber__c).intvalue());
monthsSet.add((record.Schedule_Development__r.MonthNumber__c).intvalue());
daysSet.addall((record.Schedule_Development__r.Scheduled_Days__c.split(';')));

 

Hello All,

 

I modified a trigger I found online to suit my company's needs, but I'm having issues writing a test for it. I'm able to test the first 4 lines no problem, but I'm having issues testing the last two (beginning with the for loop). Can anyone provide assistance?

 

trigger OppTaskContactRole on Task (before insert, before update)
{

    for (Task curr: Trigger.new)
    {
        if (curr.WhatId != null && curr.WhoID == null && curr.WhatId.getsobjecttype()==opportunity.sobjecttype )  {
            List<OpportunityContactRole> roles = [SELECT OpportunityId, ContactId
            FROM OpportunityContactRole
            WHERE isPrimary = true AND OpportunityId = :curr.whatId
            LIMIT 1];
                
            if(!roles.isEmpty()){
                for(OpportunityContactRole ocr : roles){
                    curr.WhoId = ocr.ContactId;
                }
            }
        }
    }
}

Hi,

Requirement :

  1.  To Create a field called ‘chatter Group’ in opportunity creation page and the details page .Once the user enters the value in the field, along with other mandate fields and on saving the opportunity , a chatter group need to be created( with the name entered in the chatter group field) with the owner of the opportunity being the collaboration member to the group. Chatter group is not a mandatory field and the group can be created while updating the opportunity as well. A post feed should come to the group on  insertion and every time the opportunity is updated.
  2. Once a user is added to the ‘opportunity Team Member’ of the opportunity , he should automatically be added to the created group.

 

Problem : On Implementing the following  trigger , creation of the chatter group is happening . The opportunity team members are added to the chatter group .

Posting of a feed to the group is happening once an opportunity is created . But on editing an opportunity , the feed post to the group is happening twice .

 

Kindly let us know the solution to get feed post to the group to come only once on updating the opportunity.

 

Please find below the trigger that has been written to achieve the same.

 

 

trigger CrtGrpFeed on Opportunity (after update) {
    List<FeedItem> filist = new List<FeedItem>();
    List<Opportunity> opp = new List<Opportunity>();
    String strGroupFlag ;
    String strGroupName ;
    String strGroupId ;
    ID GrpId ;
    ID OppOwnerId ;
 
    try
    {
   
        for (Opportunity oppnew:Trigger.new)
        {
             opp = [select Name, OwnerId ,Chatter_Group__c , Chatter_group_flag__c , Chatter_Group_Id__c from Opportunity where Id =: oppnew.Id];   
             strGroupFlag = opp[0].Chatter_group_flag__c ;
             strGroupName = opp[0].Chatter_Group__c ;
             strGroupId = opp[0].Chatter_Group_Id__c ;   
             OppOwnerId = opp[0].OwnerId ;
             
             system.debug('@@@@@@@@@@@@@@@@@@@ Chatter Flag @@@@@@@@@@@@@@@@@@' +oppnew.Chatter_group_flag__c);
              if( oppnew.Chatter_group_flag__c != '1'  && oppnew.Chatter_Group__c <> null )
                 {
                          List<FeedItem> filist1 = new List<FeedItem>();
                          FeedItem post = new FeedItem();
                           String strName = [Select Name from User where Id =: oppnew.LastModifiedById].Name;
                            post.parentid = oppnew.id;
                            post.Body = 'New Chatter Group  '  +  oppnew.Chatter_Group__c +  'has been created for this pursuit ' +    'on ' +                            oppnew.LastModifiedDate;
                             filist1.add(post);
                           Database.insert(filist1,false);      
                           
                      system.debug('*************** CreateGroupInitiate *********************'); 
                      for (Opportunity op:opp)
                      {
                         CollaborationGroup grp= new CollaborationGroup();
                         grp.Name = strGroupName;
                         grp.CollaborationType = 'Private';
                         grp.OwnerId = OppOwnerId ;
                         system.debug('*************** Owner added *********************' + grp.OwnerId);
                         insert grp;
                         system.debug('*************** Group Inserted *********************');
                         GrpId = grp.Id;
                         strGroupId = grp.Id;
                         op.Chatter_Group_ID__c = GrpId;
                         op.Id = oppnew.Id ;  
                         op.Chatter_group_flag__c = '1'; 
                         upsert op ;
                        
                     List<CollaborationGroupMember> grpMrList = new List<CollaborationGroupMember>();
                         List<OpportunityTeamMember> OppList1 = [Select UserId , Opportunityid from OpportunityTeamMember where opportunityId= :oppnew.Id];
                         if(!OppList1.isEmpty())
                         { 
                         
                             for(OpportunityTeamMember member: OppList1)
                             {
                                   system.debug('*************** Member added initiation *********************');
                                   CollaborationGroupMember grpMr = new CollaborationGroupMember() ;
                                   grpMr.memberid = member.UserId;
                                   system.debug('@@@@@@@@@@@@@@@ UserId @@@@@@@@@@@@@@@' + grpMr.memberid);

                                   grpMr.CollaborationGroupId = GrpId ;
                                   system.debug('*************** Member added *********************' + member.UserId);    
                                   grpMrList.add(grpMr);
                                   system.debug('@@@@@@@@@@@@@@@ UserId @@@@@@@@@@@@@@@' + grpMrList );
                             
                             }
                             system.debug('@@@@@@@@@@@@@@@@@ CG Group members before insrt after loop@@@@@@@@@@@@@@@@@@@@'  ) ;
                             insert grpMrList;
                             system.debug('*************** Group members added *********************' ) ;
                         }
                     
                     }             
                
        }
   
      
         if( oppnew.Chatter_group_flag__c == '1'  && oppnew.Chatter_Group__c <> null &&  oppnew.Chatter_group_flag__c  == '1')
         {
           system.debug('*************** FeedPostInitiate *********************');
                 List<FeedItem> filist2 = new List<FeedItem>();
                 FeedItem post2 = new FeedItem();
                 post2.ParentId = strGroupId; //Chatter Group ID
                 String strName = [Select Name from User where Id =: oppnew.LastModifiedById].Name;
             
                 system.debug('*************** strName *********************' + strName);
            
                 post2.Body = 'Please find below the pursuit details ' +  '\n This was updated by '
                 + strName + ' at ' + oppnew.LastModifiedDate + '\n Pursuit Stage :' + oppnew.StageName 
                 + '\n Pursuit Type:' + oppnew.Type + '\n Estmated Pursuit value :' + oppnew.Estimate_Proposal_Value__c
                 + '\n Pursuit Currency : ' + oppnew.CurrencyIsoCode ;
                 system.debug('***************Currency Code Flag *********************'+ oppnew.CurrencyIsoCode  );
                 filist2.add(post2);
             
                       insert filist2;
       
        }
     }
  
   
    }
    
    catch (Exception e) 
    {
       // Generic exception handling code here Contact.AccountId
       system.debug('Exeption ->  ' + e );
    }
  

}

dom.XmlNode tempNode = hdr.addChildElement('Company Name', null, null);

tempNode.addTextNode('ABC & XYZ ');

tempNode = hdr.addChildElement('Company Address', null, null);

tempNode.addTextNode('ABC & XYZ, <former 123ABC> ');

 

The xml created by this gives incorrect output with &amp; &lt; etc

 

i cannot include characters like & and < in DOM.Document's dom.XmlNode

 

Avoiding XMLStreamWriter, as it easily reaches heap limit.