• Aar3538
  • NEWBIE
  • 130 Points
  • Member since 2012

  • Chatter
    Feed
  • 5
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 13
    Replies

Hi, 

 

I am trying to write a trigger for automatic approval process, but I only want it to run under certain conditions. 

Here is my code:

 

trigger TOApprovalSubmit on Time_Off_Requests__c (after insert) {
    
    Time_Off_Requests__c ToTime;
    
    
            for (Time_Off_Requests__c TOR : trigger.new) {
                Date DateFrom = ToTime.Request_Start_Date__c;
                Date DateTo = ToTime.Request_End_Date__c;
                Integer DaysOff = DateFrom.daysBetween(DateTo);
                
                if(DaysOff > 5){
                Approval.ProcessSubmitRequest app = new Approval.ProcessSubmitRequest();
                app.setObjectId(TOR.id);
                Approval.ProcessResult result = Approval.process(app);
            
                }
            }
}

 I keep getting a "System.NullPointerException: Attempt to de-reference a null object" error. I think I understand what the error is saying, but I am not sure why I am getting it. The event type is "After Insert" wouldn't that mean that there would be a value for the field that I am trying to reference? 

 

Please help. 

 

Thank you. 

Newbie here - so please be gentle...

 

I have a trigger that I am trying to get to create child record every time a parent is created - works ok, but I need it to create a child record for each product in a lookup (quote_product__c). The code below simply takes one if the IDs from quote_product__c, and it works fine, but I need to loop through every product where active__c = true. ex: [Select id from quote_product__c where active__c = true]

Parent = Quote__c

Child = Quote_Line__c

lookup = Quote_Product__c

trigger AutoCreateQuoteLines on Quote__c (after insert) {
    List<Quote_Line__c> quotelines = new List<Quote_Line__c>();

    for (Quote__c newQuote: Trigger.New) {
        if (newQuote.Account__c != null) {
            quotelines.add(new Quote_Line__c(
                        Quote__c = newQuote.Id,
                        Product__c = 'a27J00000004Fq6'));
        }
    }
    insert quotelines;
}

 Thanks in advance for any help!

I'm having fun trying bulkifying my triggers.  Maybe too much fun!

 

Anyway, in the code below, about 8 lines form the bottom, there is this line:

        b.Balance__c = b.Balance__c + trans.Qty__c;

This line works fine when adding data through the web interface, but fails with a NullPointerException when I use the data loader.  

 

If I change the line to:

b.Balance__c =  trans.Qty__c;

Then the data loader does not err out.  So I know the problem is when I try to add in the current balance.  Could it be that my table is named Balance__c and it also also has a column named Balance__c?  But it works through the web interface, just not through the data loader.

 

 

Any idea why?  I believe it is thoroughly bulikified.

trigger afterInsertUpdateTrans on Trans__c (after insert, after update) {
    // create a map of existing balance records
    // since locations and equipment are dynamic,
    // balance records are not created until a transaction containing the location and equipment is added
    // there is a single unique balance record for very combination of location and equipment that has a transaction
    // Balance_Key__c is a calculated variable that concatenates the Location Id and Equipment Id
    // Balance_Key__c is defined on both the Trans__c and Balance__c tables
    Map<string,Id> balanceMap = new  Map<string,id>();
    for (Balance__c myBals : [select Balance_Key__c,Id from Balance__c]) {
        balanceMap.put(myBals.Balance_Key__c,myBals.Id);
    }

    string bk;       // to hold the results of the lookup of the key into balanceMap

    // add any missing balance records
    
    List<Balance__c> balanceToInsert = new List<Balance__c>{}; 
    for (Trans__c trans : Trigger.new) 
     {
     bk = balanceMap.get(trans.Balance_Key__c);
     If (bk==null){  // add a row to balanceToInsert
         Balance__c b = new Balance__c();
         b.Location__c = trans.Location__c;
         b.Equipment__c = trans.Equipment__c;
         balanceToInsert.add(b);
     }
    
     }    
    insert balanceToInsert;
    // finished adding any missing balance records



    // make a map of balance records
    map<string, Balance__c> balanceMap2 = new map<string, Balance__c>([select Balance_Key__c, id,Balance__c from Balance__c]);            
    Id balanceObjectId; // to hold the results of the lookup of the key into Balances 

    Map<string,Id> balanceLookup = new  Map<string,id>();
    for (Balance__c myBals : [select Balance_Key__c,Id from Balance__c]) {
        balanceLookup.put(myBals.Balance_Key__c,myBals.Id);
    }

   List<Balance__c> balanceToUpdate = new List<Balance__c>{};

    for (Trans__c trans : Trigger.new) 
 {

     balanceObjectId = balanceLookup.get(trans.Balance_Key__c); 

     Balance__c b = balanceMap2.get(balanceObjectId);
     
     If (trigger.IsInsert){
         // the next line works in the web interface
         // but fails in apex data loader with a System.NullPointerException
         b.Balance__c = b.Balance__c + trans.Qty__c;
         } Else {
         b.Balance__c = b.Balance__c + trans.Qty__c - System.Trigger.oldMap.get(trans.Id).Qty__c;
        }
    balanceToUpdate.add(b);
}
update balanceToUpdate;

}

 

HI there,

 

working on a trigger too get the parent role of the opportunity Owner user, as I beleive I can;t do it using a formula in SF. If possible please let me know. But my issue is that the trigger bellow will not let me update the field "Manager_role__C" as the error says that  "Can't execute the After Update" as record is read only . Tried to change the trigger to "before update" and got another error as it says " execution of BeforeUpdate caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.AboveRole: line 20, column 1"

 

Pretty sure it is a simple thing in my code but driving me crazy as usual.. Not sure also if this is becasue I have other triggers in the Oppt object , all 'After update" but they will change values in other objects than the Oppt itself. Here is the code:

 

trigger AboveRole on Opportunity (before insert, before update) {
  Set<Id> recordIds = new Set<Id>();
  Set<Id> acctIds = new Set<Id>();
  Set<Id> userIds = new Set<Id>();
  Set<Id> roleIds = new Set<Id>();
 

  for(opportunity S:Trigger.new)
    if(S.type == 'Renewal'){
     recordIds.add(S.id);
      acctIds.add(S.accountid);
    userIds.add(S.ownerid);
 
        
    List<User> RoleUSer = [Select userroleID from USER where id in :userids];
    roleIds.add(RoleUser[0].userroleID);
    List<Userrole> roleparent =[Select parentroleid from userrole where id in:roleIds];
       IF (roleparent.size() > 0){
       S.manager_role__C = roleparent[0].parentroleid;
       update s;      
       }
    }

}

 


 

I'm trying to get coverage for he last 3 lines of a trigger I wrote, but I can't figure out how to get these last few lines covered.  Any help is much appriciated.

 

The Test Code I have now is:

 

public class TestSetGroup4BookLU{

    static testMethod void test1(){
    
      lod4__Group__c g = new lod4__Group__c(Name='Hello'); 

      g.Group_Owner__c = UserInfo.getUserId();
     
      insert g;
      
      lod4__Event__c b = new lod4__Event__c(Name='Hello Event 2012');
      b.Group_Owner_LU__c = UserInfo.getUserId();
      b.OwnerId = UserInfo.getUserId();
     
      insert b;
 
      b = [select id, Group_Owner_LU__c from lod4__Event__c where id = :b.id];
      
      g.Sales_Executive__c = b.Group_Owner_LU__c;
      g.Group_Owner__c = UserInfo.getUserId();
    }

}

 

The test coverage that is missing is below in Red:

 

 1

 

  trigger setBookingLU4Group on lod4__Group__c (before insert, before update) {

 4   lod4__Group__c [] triggerBatch = Trigger.new;
 6   // List of Booking IDs
 7   List<String> bookIDs = new List<String>();
 9   for(lod4__Group__c g:triggerBatch){
 10   bookIDs.add(g.lod4__Event__c); // Adding BookingIDs to List
 11   }
 13   // Booking Map
 14   Map<ID, lod4__Event__c> bookMap = new Map<ID, lod4__Event__c>([select id, OwnerId, Group_Owner_LU__c from lod4__Event__c where Id = :bookIDs]);
 17   for(lod4__Group__c g:triggerBatch){
 19   if(bookMap.containsKey(g.lod4__Event__c)){
 20   lod4__Event__c book = bookMap.get(g.lod4__Event__c) ;
 21   g.Sales_Executive__c = book.OwnerId;
 22   g.Group_Owner__c = book.Group_Owner_LU__c;
 24   }
 26   }
 28

  }

  • February 20, 2012
  • Like
  • 0

Hi all,

 

I have a problem when trying to develop a solution that deals with 'large' amounts of data. The situation is the following. 

We have to develop for our customer a solution that handles records inserted in their Salesforce under a custom object (Unprocessed Agreements). Each record from this custom object hosts information that, once processed, will end in Accounts, Contacts and a custom object called 'Agreements'. Basically, each record of the custom object has all the information of an agreement with its account and its contact related. So processing each record of 'Unprocessed Agreements' means to create an Account (if not already in SF); a Contact (if not already in SF) and an Agreement (if is already in Salesforce, updates this agreement). All the logic built to meet this requirements has to rely on a scheduled class that will run and perform this every day.

The number of agreements, Accounts and Contacts might be around 3000 for each entity, in order to not hit the SOQL limits, we developed the functionality so that first 'dumps' all the accounts, contacts and agreements existing in Salesforce into Lists, and we do searches over that lists to check if the Accounts, Contacts or Agreements were created before, then we build the logic on top of this checks. 

Our problem seems that when we want to perform searches over those Lists of records, we hit a limit: ''Too many statements: 200001" when looping over those lists. We make sure to not hit the SOQL query limit, but we faced this limit mentioned above. The logic built works as desired when we keep low the amount of Accounts, Contacts and Agreements. 

Do you have any ideas on how to handle this?

Best regards, 

 

MGA.

Ok so my knowledge of Apex Triggers has improved over the years (mainly thanks to help from people on here) however I cant get this one:

 

I need a trigger to change the owner on an account when the Type is changed to 'Customer'. The way I need to trigger to decide who to change the owner to by counting the number of  accounts where type is 'Customer' for each Owner 1, Owner 2 and Owner 3 and then assigning the ownership to the Owner with the least Accounts. Where each owner has the same number of accounts, then it should assign ownership to the person who had an account assigned the longest time ago.

 

is this possible?

Hi, 

 

I am trying to write a trigger for automatic approval process, but I only want it to run under certain conditions. 

Here is my code:

 

trigger TOApprovalSubmit on Time_Off_Requests__c (after insert) {
    
    Time_Off_Requests__c ToTime;
    
    
            for (Time_Off_Requests__c TOR : trigger.new) {
                Date DateFrom = ToTime.Request_Start_Date__c;
                Date DateTo = ToTime.Request_End_Date__c;
                Integer DaysOff = DateFrom.daysBetween(DateTo);
                
                if(DaysOff > 5){
                Approval.ProcessSubmitRequest app = new Approval.ProcessSubmitRequest();
                app.setObjectId(TOR.id);
                Approval.ProcessResult result = Approval.process(app);
            
                }
            }
}

 I keep getting a "System.NullPointerException: Attempt to de-reference a null object" error. I think I understand what the error is saying, but I am not sure why I am getting it. The event type is "After Insert" wouldn't that mean that there would be a value for the field that I am trying to reference? 

 

Please help. 

 

Thank you. 

Newbie here - so please be gentle...

 

I have a trigger that I am trying to get to create child record every time a parent is created - works ok, but I need it to create a child record for each product in a lookup (quote_product__c). The code below simply takes one if the IDs from quote_product__c, and it works fine, but I need to loop through every product where active__c = true. ex: [Select id from quote_product__c where active__c = true]

Parent = Quote__c

Child = Quote_Line__c

lookup = Quote_Product__c

trigger AutoCreateQuoteLines on Quote__c (after insert) {
    List<Quote_Line__c> quotelines = new List<Quote_Line__c>();

    for (Quote__c newQuote: Trigger.New) {
        if (newQuote.Account__c != null) {
            quotelines.add(new Quote_Line__c(
                        Quote__c = newQuote.Id,
                        Product__c = 'a27J00000004Fq6'));
        }
    }
    insert quotelines;
}

 Thanks in advance for any help!

Hi Everyone!

 

I'm pretty new to Apex and am having an issue with bulkifying my Asset trigger code below.  Basically, I need to update account records based on information on the related asset records.  The code takes the Asset(s) from the trigger, creates a set for all the related accounts then uses that set in a SOQL query to pull a list of accounts and then pull a list of all active assets related to those accounts - which could include more asset records than the trigger asset(s).

 

I then have a for-loop to iterate through the accounts.  Inside that for-loop I then have another for-loop to iterate through the assets. If the account id in the asset for-loop == account in the account for-loop, use the asset info to update the account info.

 

Everything works fine until I do an update to the Asset object using data loader when there are a lot of records.  It successfully updates about 20 records and then the remaining records of the 200 record batch fail.  The error I get is:

 

'AssetTrigger: System.LimitException: Too many script statements: 200001'

 

I assume it is because I am iterating through ALL the asset records for each account id to look for a match that brings the statement count past the limit but I can't figure out a more efficient way to do it.  Is there a way to set up the asset for-loop to only iterate through the asset records where the account Id matches?  Could it be something else?  200000 statements seems REALLY high.

 

Any assistance would appreciated.  Don't be afraid to provide suggestions for improving any of the code - I can take it!

 

 

 

public with sharing class UpdateAcctFromAsset {

	public void updateAcctCustInfo(List<Asset> trigAssets)
	{	
		String sProdFam_TA = 'Recruitment';
		String sProdFam_TM = 'Talent Management';		
		String sProdFam_WCAD = 'Workforce Compliance';
		String sProdFam_VMS = 'Vendor Management';
		String sProdFam_LMS = 'Learning Management';
		String sProdFam_AQ = 'Aquire';
		String sProdFam_PRI = 'PRI';
		String sProdFam_Tablet = 'Tablet Application';
		
		//Get account id's from all Assets
		Set<Id> accountIds = new Set<Id>();
		for(Asset a: trigAssets){
			accountIds.add(a.AccountId);						
		}		
		//Get list of customer accounts so we can set the new values
		List<Account> custAccts = new List<Account>([Select Id, Type, TA_Client__c, TM_Client__c, WCAD_Client__c, 														LMS_Client__c, PRI_Client__c, VMS_Client__c, Aquire_Client__c, Tablet_Client__c
								from Account 
								where id IN :accountIds]);
														
		List<Asset> acctAssets	= new List<Asset>([Select Id, AccountId, Product_Family__c, System_Status__c 
								from Asset
								where AccountId IN :accountIds 
								AND (NOT System_Status__c = 'Inactive') 														AND (NOT System_Status__c = 'Cancelled')]);											
		
		//Cycle through accounts and update values		
		for(Account acct: custAccts){
			acct.TA_Client__c = false;
			acct.TM_Client__c = false;
			acct.WCAD_Client__c = false;
			acct.LMS_Client__c = false;
			acct.PRI_Client__c = false;
			acct.VMS_Client__c = false;
			acct.Aquire_Client__c = false;
			acct.Tablet_Client__c = false;
			Boolean bIsCustomer = false;		
			
			//Go through each Asset and update				
			for (Asset ast : acctAssets){
				if (ast.System_Status__c != 'Inactive' && ast.System_Status__c != 'Cancelled' && ast.AccountId == acct.Id){
					If (ast.Product_Family__c == sProdFam_TA){
						acct.TA_Client__c = true;
						bIsCustomer = true;
					}
					If (ast.Product_Family__c == sProdFam_TM){
						acct.TM_Client__c = true;
						bIsCustomer = true;
					}	
					If (ast.Product_Family__c == sProdFam_WCAD){
						acct.WCAD_Client__c = true;
						bIsCustomer = true;
					}
					
					If (ast.Product_Family__c == sProdFam_VMS){
						acct.VMS_Client__c = true;
						bIsCustomer = true;
					}
						
					If (ast.Product_Family__c == sProdFam_LMS){
						acct.LMS_Client__c = true;
						bIsCustomer = true;
					}
						
					If (ast.Product_Family__c == sProdFam_PRI){
						acct.PRI_Client__c = true;
						bIsCustomer = true;
					}
					
					If (ast.Product_Family__c == sProdFam_AQ){
						acct.Aquire_Client__c = true;
						bIsCustomer = true;
					}
						
					If (ast.Product_Family__c == sProdFam_Tablet){
						acct.Tablet_Client__c = true;
						bIsCustomer = true;
					}
				}									
			}
			//Update Account type status
			if (acct.Type != 'Partner' && bIsCustomer == true){
				acct.Type = 'Customer';			
			}
			if (acct.Type != 'Partner' && bIsCustomer == false){
				acct.Type = 'Prospect';
			}
		}					
		update custAccts;			
	}

 

  • March 21, 2012
  • Like
  • 0

I'm having fun trying bulkifying my triggers.  Maybe too much fun!

 

Anyway, in the code below, about 8 lines form the bottom, there is this line:

        b.Balance__c = b.Balance__c + trans.Qty__c;

This line works fine when adding data through the web interface, but fails with a NullPointerException when I use the data loader.  

 

If I change the line to:

b.Balance__c =  trans.Qty__c;

Then the data loader does not err out.  So I know the problem is when I try to add in the current balance.  Could it be that my table is named Balance__c and it also also has a column named Balance__c?  But it works through the web interface, just not through the data loader.

 

 

Any idea why?  I believe it is thoroughly bulikified.

trigger afterInsertUpdateTrans on Trans__c (after insert, after update) {
    // create a map of existing balance records
    // since locations and equipment are dynamic,
    // balance records are not created until a transaction containing the location and equipment is added
    // there is a single unique balance record for very combination of location and equipment that has a transaction
    // Balance_Key__c is a calculated variable that concatenates the Location Id and Equipment Id
    // Balance_Key__c is defined on both the Trans__c and Balance__c tables
    Map<string,Id> balanceMap = new  Map<string,id>();
    for (Balance__c myBals : [select Balance_Key__c,Id from Balance__c]) {
        balanceMap.put(myBals.Balance_Key__c,myBals.Id);
    }

    string bk;       // to hold the results of the lookup of the key into balanceMap

    // add any missing balance records
    
    List<Balance__c> balanceToInsert = new List<Balance__c>{}; 
    for (Trans__c trans : Trigger.new) 
     {
     bk = balanceMap.get(trans.Balance_Key__c);
     If (bk==null){  // add a row to balanceToInsert
         Balance__c b = new Balance__c();
         b.Location__c = trans.Location__c;
         b.Equipment__c = trans.Equipment__c;
         balanceToInsert.add(b);
     }
    
     }    
    insert balanceToInsert;
    // finished adding any missing balance records



    // make a map of balance records
    map<string, Balance__c> balanceMap2 = new map<string, Balance__c>([select Balance_Key__c, id,Balance__c from Balance__c]);            
    Id balanceObjectId; // to hold the results of the lookup of the key into Balances 

    Map<string,Id> balanceLookup = new  Map<string,id>();
    for (Balance__c myBals : [select Balance_Key__c,Id from Balance__c]) {
        balanceLookup.put(myBals.Balance_Key__c,myBals.Id);
    }

   List<Balance__c> balanceToUpdate = new List<Balance__c>{};

    for (Trans__c trans : Trigger.new) 
 {

     balanceObjectId = balanceLookup.get(trans.Balance_Key__c); 

     Balance__c b = balanceMap2.get(balanceObjectId);
     
     If (trigger.IsInsert){
         // the next line works in the web interface
         // but fails in apex data loader with a System.NullPointerException
         b.Balance__c = b.Balance__c + trans.Qty__c;
         } Else {
         b.Balance__c = b.Balance__c + trans.Qty__c - System.Trigger.oldMap.get(trans.Id).Qty__c;
        }
    balanceToUpdate.add(b);
}
update balanceToUpdate;

}

 

Hi all,

 

I have a simple trigger which pulls data from the lead object and places it into a custom "Finance" object when the lead is created or updated.  For some reason, the Trigger.new[0].Id is returning NULL in the trigger which fires before insert.  

 

I'm going crazy because I can't see any reason why the Id would be NULL...  Here's my code:

 

 

 

trigger FinanceNew on Lead (before insert) {
	
	Map<String,User> userList = new Map<String,User>{};
	
	// Places each returned user into a map with their sfID as the key
	for(User tmp : [SELECT Id,Name,Email,Phone FROM User]){
	  userList.put(tmp.Id,tmp);
	}
	
	for(integer i = 0; i<Trigger.new.size(); i++){
	
		string leadName = null;
		
		if(Trigger.new[i].FirstName != ''){
			leadName = Trigger.new[i].FirstName + ' ' + Trigger.new[i].LastName;
		}else{
			leadName = Trigger.new[i].LastName;
		}
		
		User ownerInfo = userList.get(Trigger.new[i].OwnerId);
		
		ID leadId = Trigger.new[i].Id; // THIS IS RETURNING NULL!!
		
		Finance__c financeRecord = new Finance__c(
		
			Name = leadName,
			Lead__c = leadId,
			Lead_Email__c = Trigger.new[i].Email,
			Lead_Phone__c = Trigger.new[i].Phone,
			Lead_Owner_Name__c  = ownerInfo.Name,
			Lead_Owner_Email__c = ownerInfo.Email,
			Lead_Owner_Phone__c = ownerInfo.Phone
			
		);
	
		insert financeRecord;
	
	}

}

 

The Lead.Id assignment should be very straight forward.  Every other field pulling directly from the Trigger.new record inserts the correct information.

 

Thanks in advance for any help!

 

Josh

  • February 28, 2012
  • Like
  • 0

Getting started with force.com and ran into a roadblock right away.  I defined a custom object, and then used it in an Apex class definition.  However when I used the object name in the class definition (page 29 of developer guide) (with the _c), I get aninvalid type compile error. 

 

Went back to basics from the developers guide to replicate their simple example.  Followed instructions to define a "Book" object as in the guide, and then copied the code:

 

public class MyHelloWorld {

 

    public static void applyDiscount(Book__c[] books) {    

        for (Book__c b : books)  {    

           b.Price__c *= 0.9;    

        }

     }

 }

 

I get similar "Error: Compile Error: Invalid type: Book__c at line 4 column 10".  Is there some setting I need to make to make the custom object visible to Apex?  I've searched everywhere and can't find any reference to it.

 

Can anyone point me in the right direction to get moving?

 

robertcw7777

 

 

HI there,

 

working on a trigger too get the parent role of the opportunity Owner user, as I beleive I can;t do it using a formula in SF. If possible please let me know. But my issue is that the trigger bellow will not let me update the field "Manager_role__C" as the error says that  "Can't execute the After Update" as record is read only . Tried to change the trigger to "before update" and got another error as it says " execution of BeforeUpdate caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.AboveRole: line 20, column 1"

 

Pretty sure it is a simple thing in my code but driving me crazy as usual.. Not sure also if this is becasue I have other triggers in the Oppt object , all 'After update" but they will change values in other objects than the Oppt itself. Here is the code:

 

trigger AboveRole on Opportunity (before insert, before update) {
  Set<Id> recordIds = new Set<Id>();
  Set<Id> acctIds = new Set<Id>();
  Set<Id> userIds = new Set<Id>();
  Set<Id> roleIds = new Set<Id>();
 

  for(opportunity S:Trigger.new)
    if(S.type == 'Renewal'){
     recordIds.add(S.id);
      acctIds.add(S.accountid);
    userIds.add(S.ownerid);
 
        
    List<User> RoleUSer = [Select userroleID from USER where id in :userids];
    roleIds.add(RoleUser[0].userroleID);
    List<Userrole> roleparent =[Select parentroleid from userrole where id in:roleIds];
       IF (roleparent.size() > 0){
       S.manager_role__C = roleparent[0].parentroleid;
       update s;      
       }
    }

}

 


Hi all

 

i have a this error when i run my test 

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, workflow2: execution of AfterUpdate caused by: System.ListException: Duplicate id in list: 

 

this my trigger  :


trigger workflow2 on Contract (after update) {
List<Account>accList=new List <Account>();
set<id>accIds = new Set<id>();
for(contract c:trigger.new)
{
accIds.add(c.AccountId);
}
Map<id,Account>accMap=new Map<id,Account>([Select(select status from contrats__r)from account Where id in :accIds]);
List<contract> myContracts =[select AccountId from contract where AccountId in :accIds and status='activé'] ;


Set<ID> myAccountsIDs = new Set<ID>(); // here we will have only the ID's of those accounts that have a contract in status 'activé'
for (contract c : myContracts)
{
myAccountsIDs.add(c.AccountId);
}
for(contract c :trigger.new)
{
account ac=accMap.get(c.AccountId);
if(c.status=='activé')
{

ac.A_I__c='active';

}


if(c.status=='expiré'&& myAccountsIDs.contains(c.AccountId) == false)
{

ac.A_I__c='inactive';

}
accList.add(ac);
}
update accList;
}

 

thanks for your help

  • February 25, 2012
  • Like
  • 0

Hi,

 

I'm using following trigger for sharing records to hiring manager via apex

 

trigger Hiring_Manager_Job_Share on Position__c (after insert) {

    // We only execute the trigger after a Job record has been inserted 
    // because we need the Id of the Job record to already exist.
    if(trigger.isInsert){
     
    // Job_Share is the "Share" table that was created when the
    // Organization Wide Default sharing setting was set to "Private".
    // Allocate storage for a list of Position__Share records.
    List<Position__Share> jobShares  = new List<Position__Share>();

    // For each of the Job records being inserted, do the following:
    for(Position__c job : trigger.new){

        // Create a new Position__Share record to be inserted in to the Job_Share table.
        Position__Share hiringManagerShare = new Position__Share();
            
        // Populate the Position__Share record with the ID of the record to be shared.
        hiringManagerShare.ParentId = job.Id;
            
        // Then, set the ID of user or group being granted access. In this case,
        // we’re setting the Id of the Hiring Manager that was specified by 
        // the Recruiter in the Hiring_Manager__c lookup field on the Job record.  
        // (See Image 1 to review the Job object's schema.)
        hiringManagerShare.UserOrGroupId = job.Hiring_Manager__c;
            
        // Specify that the Hiring Manager should have edit access for 
        // this particular Job record.
        hiringManagerShare.AccessLevel = 'read';
            
        // Specify that the reason the Hiring Manager can edit the record is 
        // because he’s the Hiring Manager.
        // (Hiring_Manager_Access__c is the Apex Sharing Reason that we defined earlier.)
        hiringManagerShare.RowCause = Schema.Position__Share.RowCause.Hiring_Manager_Access__c;
            
        // Add the new Share record to the list of new Share records.
        jobShares.add(hiringManagerShare);
    }
        
    // Insert all of the newly created Share records and capture save result 
    insert jobShares;
        
    // Error handling code omitted for readability.
    }
}

 

and OWD for Position__c is Publice Read Only.

 

Now, when I create a new position record I get this error

Apex trigger Hiring_Manager_Job_Share caused an unexpected exception, contact your administrator: Hiring_Manager_Job_Share: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: AccessLevel (trivial share level Read, for organization with default level Read): [AccessLevel]: Trigger.Hiring_Manager_Job_Share: line 41, column 1

 

I can understand that this is trivial case and can be passed why my code is not working? What I am missing here?

  • February 24, 2012
  • Like
  • 0

Hi All,

 

I am trying to deploy changes to Apex Classes in production org via sandbox using change sets.

But upon hitting validate button or test run, I am getting the following error-

System.ListException: List index out of bounds: 0, Stack Trace-Class.DeleteRWClient.DelRecs: line 79, column 1

 

I haven't got  clue about Apex Classes, the below codes were developed by someone else which unfortunately has errors and I am trying to fix it with your assistance. Can anyone guide me with this please, it would be a massive help.. 

 

public class DeleteRWClient
{
private string mstrSource;
public string mstrClientID;
private string mstrURL ;
public string mstrNoDel = '';
public string mstrClientName;
List<Opportunity> objListOppor = null;
List<RW_Client_Contact__c> objCM = null;

public DeleteRWClient(ApexPages.StandardController controller)
{
mstrClientID = ApexPages.currentPage().getParameters().get('ClientID');
List<RWClientMaster__c> objRWM = [SELECT NAME FROM RWClientMaster__c WHERE ID = : mstrClientID];
if(objRWM.size() !=0)
{
mstrClientName = objRWM[0].Name;
}
if(ApexPages.currentPage().getParameters().get('source') == null)
{
SourcePage='/apex/RWClientMaster?id=' + mstrClientID + '&sfdc.override=1&emessage=You cannot delete the Client, as it has associated Accounts and Contacts to it';
}
else
{
if(ApexPages.currentPage().getParameters().get('ContactID') != null)
{
objListOppor = [SELECT o.Contact__c From Opportunity o
WHERE o.Contact__c =: ApexPages.currentPage().getParameters().get('ContactID') ];
if(objListOppor .size() !=0)
{
mstrNoDel += 'You cannot delete the Contact, as it has associated Appointments set with this Contact Already';
}
else
{

mstrNoDel += 'Contact is no more associated with RWClient' + ' ' + mstrClientName;
}
}
else
{
mstrNoDel += 'You cannot delete the Client, as it has associated Accounts and Contacts to it';
}

SourcePage= ApexPages.currentPage().getParameters().get('source') + '&emessage=' + mstrNoDel;
}


}

public String SourcePage
{
get{return mstrSource;}
set{mstrSource = value;}
}


public DeleteRWClient()
{

}
public PageReference DeleteRec()
{
//return null;

objCM = [Select ID, r.ContactID__c From RW_Client_Contact__c r
WHERE r.ContactID__c =: ApexPages.currentPage().getParameters().get('ContactID')
AND r.RW_Client_Master__r.ID =:mstrClientID];
delete objCM ;
return new PageReference(SourcePage);
}
static testMethod void DelRecs()
{
List<RWClientMaster__c> objLstCl = [SELECT ID FROM RWClientMaster__c ORDER BY CREATEDDATE DESC LIMIT 1];
ApexPages.currentPage().getParameters().put('ClientID',objLstCl[0].ID );
ApexPages.currentPage().getParameters().put('source','');
List<RW_Client_Contact__c> objClCont = [Select r.ContactID__c, r.RW_Client_Master__c from RW_Client_Contact__c r
WHERE RW_Client_Master__c =:objLstCl[0].ID LIMIT 1];
ApexPages.currentPage().getParameters().put('ContactID',objClCont[0].ContactID__c);
ApexPages.StandardController controller;
DeleteRWClient objDw = new DeleteRWClient(controller);
DeleteRWClient objDw1 = new DeleteRWClient();

objDW.SourcePage = ApexPages.currentPage().getParameters().get('source');
objDW.mstrClientID = ApexPages.currentPage().getParameters().get('ClientID');

string strPage = objDW.DeleteRec().getUrl();

ApexPages.currentPage().getParameters().put('ClientID',objLstCl[0].ID );
ApexPages.currentPage().getParameters().put('source','rc');
ApexPages.currentPage().getParameters().put('ContactID',objClCont[0].ContactID__c);

objDw = new DeleteRWClient(controller);
objDw1 = new DeleteRWClient();

objDW.SourcePage = ApexPages.currentPage().getParameters().get('source');
objDW.mstrClientID = ApexPages.currentPage().getParameters().get('ClientID');

strPage = objDW.DeleteRec().getUrl();


}

}

 

Regards,

Swapnil

 

 

I'm trying to get coverage for he last 3 lines of a trigger I wrote, but I can't figure out how to get these last few lines covered.  Any help is much appriciated.

 

The Test Code I have now is:

 

public class TestSetGroup4BookLU{

    static testMethod void test1(){
    
      lod4__Group__c g = new lod4__Group__c(Name='Hello'); 

      g.Group_Owner__c = UserInfo.getUserId();
     
      insert g;
      
      lod4__Event__c b = new lod4__Event__c(Name='Hello Event 2012');
      b.Group_Owner_LU__c = UserInfo.getUserId();
      b.OwnerId = UserInfo.getUserId();
     
      insert b;
 
      b = [select id, Group_Owner_LU__c from lod4__Event__c where id = :b.id];
      
      g.Sales_Executive__c = b.Group_Owner_LU__c;
      g.Group_Owner__c = UserInfo.getUserId();
    }

}

 

The test coverage that is missing is below in Red:

 

 1

 

  trigger setBookingLU4Group on lod4__Group__c (before insert, before update) {

 4   lod4__Group__c [] triggerBatch = Trigger.new;
 6   // List of Booking IDs
 7   List<String> bookIDs = new List<String>();
 9   for(lod4__Group__c g:triggerBatch){
 10   bookIDs.add(g.lod4__Event__c); // Adding BookingIDs to List
 11   }
 13   // Booking Map
 14   Map<ID, lod4__Event__c> bookMap = new Map<ID, lod4__Event__c>([select id, OwnerId, Group_Owner_LU__c from lod4__Event__c where Id = :bookIDs]);
 17   for(lod4__Group__c g:triggerBatch){
 19   if(bookMap.containsKey(g.lod4__Event__c)){
 20   lod4__Event__c book = bookMap.get(g.lod4__Event__c) ;
 21   g.Sales_Executive__c = book.OwnerId;
 22   g.Group_Owner__c = book.Group_Owner_LU__c;
 24   }
 26   }
 28

  }

  • February 20, 2012
  • Like
  • 0