• frederic baudax
  • NEWBIE
  • 80 Points
  • Member since 2009

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 27
    Replies

Hi there-

 

So I got assistance on this code, built the test class and deployed it. It works fine when creating a Task under Opp but throws a null pointer exception error when I create a task under any other object.

 

Goal: When adding a task in opportunity automatically pull the assigned rep and select the picklist field for them on the task. When no rep selected do nothing.

 

Both fields are named Assigned_Rep__c, however the field on the Opp is a reference Assigned_Rep__r.Name. I do not need any trigger except when accessed from an opportunity.

 

Error:

 

Attempt to de-reference a null object Trigger.populatePicklist: line 9, column 34

 Trigger

trigger populateAssignedRep on Task(before insert, before update){
    
    
    String oppPrefix = Schema.SObjectType.Opportunity.getKeyPrefix();
    List<Id> oppIds = new List<Id>();
    
    for(Task t: Trigger.new){
        String relatedTo = (String)t.WhatId;
        String relatedToPrefix = relatedTo.subString(0,3);
        if(oppPrefix == relatedToPrefix){
           oppIds.add(t.WhatId);
        }
    }
    
    Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>();
    if(!oppIds.isEmpty()){
        oppMap.putAll([Select Id, Name, Assigned_Rep__c, Assigned_Rep__r.Name from Opportunity where Id IN :oppIds]);
        
    
          for(Task t: trigger.new){
             String relatedTo = (String)t.WhatId;
             String relatedToPrefix = relatedTo.subString(0,3);
             if(oppPrefix == relatedToPrefix){
                if(oppMap.containsKey(t.WhatId)){
                   Opportunity opp = oppMap.get(t.WhatId);
                   if(opp.Assigned_Rep__c != null){
                      t.ARI_Rep__c = opp.Assigned_Rep__r.Name;                    }
                }
             }
          }
    }
}

 

I'm using this as my first venture into triggers, and was able to handle the test class by myself, so I am extremely appreciative of the help I am getting. Thanks everyone.

 

  • September 09, 2010
  • Like
  • 0

Trying to solve one last problem on a trigger I am working on. Currently, the trigger works fine on 'insert' and 'delete', but generating the following error message when 'updating':

 

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger rollupCaseHoursTo360 caused an unexpected exception, contact your administrator: rollupCaseHoursTo360: execution of AfterUpdate caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.rollupCaseHoursTo360: line 91, column 44

 

The problem occurs when one of our particular fields is NULL; which is the case most of the time.  So the update trigger needs to test to make sure the value is not NULL before executing the rest of the code.  Below is a copy of the update section of trigger and comments of how I tried to test for the NULL value and section generating error:

 

 

.
.
.
else if(Trigger.isUpdate)
{
	//Tried adding test to verify value was not null before executing rest of code
	if (Case.X360_Contract_Cycle__c != NULL) {
	
	//sum total both old and new
	Case [] oldTime = Trigger.old;
	Case [] newTime = Trigger.new;
	Double newSum = 0.0;
	Double oldSum = 0.0;

	for(Case newTe: newTime)
		{
			for(Case oldTe : oldTime)
				{

// SECTION GENERATING ERROR IF 'X360_Contract_Cycle__c' IS NULL
X360_Contract_Cycle__c oldTimesheet = [Select Id, Name, Delivered_Hours__c from X360_Contract_Cycle__c where Id = :oldTe.X360_Contract_Cycle__c];

X360_Contract_Cycle__c newTimesheet = [Select Id, Name, Delivered_Hours__c from X360_Contract_Cycle__c where Id = :newTe.X360_Contract_Cycle__c];
					
					
					Case [] newSumHours = [Select Id, Case_Hours__c  from Case where X360_Contract_Cycle__c = :newTimesheet.Id];
					Case [] oldSumHours = [Select Id, Case_Hours__c from Case where X360_Contract_Cycle__c = :oldTimesheet.Id];

							//sum premiums from child objects
							for(Case oldSumHour : oldSumHours)
							{
								//converting 'Case_Hours__c' from string data type to number (double)
    							double oldCaseHours = double.valueOf(oldSumHour.Case_Hours__c);
								oldSum += oldCaseHours;
							}

							for(Case newSumHour : newSumHours)
							{
								//converting 'Case_Hours__c' from string data type to number (double)
    							double newCaseHours = double.valueOf(newSumHour.Case_Hours__c);
								newSum += newCaseHours;
							}

					newTimesheet.Delivered_Hours__c = newSum;
					oldTimesheet.Delivered_Hours__c = oldSum;

					//sheetsToUpdate.add(newTimesheet);
					//sheetsToUpdate.add(oldTimesheet);

					sheetsToUpdate.add(newTimesheet);
					if(newTimesheet.Id != oldTimesheet.Id){
						sheetsToUpdate.add(oldTimesheet);
					}

				}
			}


update sheetsToUpdate;

}

}

 

I am far from a full fledged Developer so trying to hack my way through this a bit.  Logically I thought the IF test would work, but the rest of the code appears to execute regardless if the value is NULL or not.  If the value is not NULL the update works fine.  Any suggestions?  Thanks!!

 

Hi,

 

I am new to salesforce trigger.NEED HELP!!!

 

I am trying to write a trigger to update contacts field with the response received tracked in campaign member object.

 

I have one field call Subcribered at contact level.When a contact is tagged for campaign then we are waiting for his reply after receiving the reply we update campaign member status.

 

So is there any way we can update the Subcribered checkbox as check once the campaign member status changed.

 

Suppose:

ABC has subscibed for the email then we change it status to Responed then salesforce should automatically update the his Subscribed checkbox.

 

Please help

 

 

 

Hope someone can give me an idea to get around this,

 

Just after our instance was upgraded to winter 11 we reached the 100.000 accounts mark, we have a deduplication trigger/class that merge duplicates from prospects inserted trough imports. As obviously i started getting the limit error I’ve been looking trough the boards. Based on my readings I’ve created a new fields, trough workflow it gets populated with the recordtypid (external id to get it indexed) and changed the query to only inspect that part of our records. That made the trick and all went well but today when trying to deploy a new Class all of a sudden I’m getting that error again on the same triggers and for the same query.

 

 

SELECT *fields*  FROM Account where Status__c = 'Prospect' AND Isdeleted = false AND VAT__c != NULL AND recordtypeid__c = '012200000008qQz' AND createddate > :bypass AND VAT__c IN :VATnrs LIMIT :intLimit

 

 

Status__c is a picklist (thus supposed to be indexed by default) and both recordtypeid__c and VAT__c are external id fields. As you can see i'm already stripping out the NULL values and I’ve even tried to get around it by taking a timeframe of only a couple of months but it still fails.

 

Anyone experienced something similar and found out how to fix it ?

 

Thanks in advance for any help.

Kr,

Fred

We're going to build an automatic dump of customers into SFDC on a nightly base, in order to avoid duplicates we're using an external Id.

 

We also want to avoid creating dupes if the external Id hasn't been added in SFDC but still update that accounts.

 

The idea is the following

1) check if external Id exist in SFDC, if match proceed to update

if not =>

2) check if "another unique id" exist in SFDC, if match add the SF id and proceed to update

if not =>

3) check if the "some fields" match an account in SFDC, if match add the SF id and proceed to update

if not =>

4) check if the "some other fields" match an account in SFDC, if match flag  and insert

if not =>

5) insert

 

Obviously it needs to be bulk free. I have made a few attemps to build a trigger based on Maps and sets but no success. Seems a lot more complex than what i thought in first instance.

 

Can anyone help me with a basic sample or guidlines to achieve something like this.

 

Thanks in advance!

wonder if anyone has already done this and/or if it's possible.

 

I'm trying to embed a button that check if condition X is met into a VF page trough the onclick tag

 

if not met => process

if met display a popup with "ok/cancel" 

  => if cancel, return to record

  => if ok, process

 

Tried about all options/formats I could think off but to no avail

 

to give the basics, if the stock X is 0 when you try to place an order > display msg to inform it will take time, if the user cancel,no action taken or on OK go on with the order. if the stock is > 0 go on without popup

 

shoul be something along the line of onclick="{!if(Visibility_Item_Stock__c.available_quantity_F__c == 0 ,'true','false'); return confirm('Be aware there might be a delay since there is no stock right now, Dealer support will inform you when and if the stock will be replenished.')}"

 

Thanks to anyone that would help on this 

 

Hello,

Need some help here, it's not my first trigger thought i'm still a starter. I've written the following simple cross-object field update trigger, basically when a call center agent enter his report (custom object) some fields need to be update on account level.

 

I've been checking the manual, boards and can only come up with the idea it's coded correctly yet i have the following issues:
1) the trigger doesn't fire when the RecordType.Name does match but does whenever it doesn't match


2) when the trigger fires, a System.QueryException: List has no rows for assignment to SObject is returned for Account__r.Id

 

 I guess i'm overlooking something really obvious here but i'm out of ideas and starting to have a headache.

 

Here is my trigger:

 

trigger updatefields on Prospection_Call_report__c (after insert, after update) {

for(Prospection_Call_report__c ob : Trigger.new){

//issue 1

if (ob.RecordType.Name == 'Account managers' ) {

//issue 2 Account__r.Id returns no rows
Account acc = [SELECT Id FROM Account WHERE Id = :ob.Account__r.Id];


acc.Current_Operator__c = ob.actual_provider__c;
acc.Current_Tariff__c = ob.Actual_tariff__c;
acc.Current_Number_Of_Cards__c = ob.Subscriptions_AM__c;
acc.Current_Contract_End_Date__c = ob.Contract_duration_AM__c;
update acc;

}
}
}

 No risk of bulk action as no mass uploads/updates will be done, ever.

 

Thanks in advance for any help provided

 

Cheers,

Fred

 

Hi Everyone,

 

I am getting the following Err "" Compile Error: set must have exactly 1 type argument at line 1 column 1"

 

 

trigger Test123 on Lead(before insert, before update) {
        //Set<Id,Integer> ownerids=new Set<Id,Integer>();
        
        Set<Id> ownerids=new Set<Id>();
    
//reterving the owner id for the lead
for(Lead l : Trigger.new)
{
        Id ownerId=l.OwnerId;
        ownerids.add(ownerId);
    //User theower1=[SELECT Id, Region__c FROM User where Id = :l.OwnerId];
    //User theowner=[SELECT id,region__c FROM USER WHERE id=l.ownerId];u
}   
List<User> theower1=[SELECT Id, Region__c FROM User where Id IN:ownerids];
Map<Id.User> userownerlead=new Map<Id.User>(theower1);

    
    for(Lead l : Trigger.new)
        l.Region__c=theower1.Region__c;
         l.Region__c=userownerlead.get(l.OwnerId).Region__c;
         
}
}

 

Can u please what is going wroing in my code

thanks for help in advance

Hi everyone-

 

I believe I'm coming pretty close to finalizing my apex code.  Unfortunately I'm getting a compile error and could use some help.  I have included comments within the code to show exactly what I'm trying to accomplish.  Can somebody please take a look and see what modifications need to be made?

 

trigger LastSWDate on Task (before insert, before update) {
	
	//To do - If the subject of a completed task contains "SW", put the date of the completed task in the 
	//the "Last_SW_Activity__c" field on the account object

//Create a set of related account ID's
Set <ID> acctIDs = new Set <ID> ();


//For every task, add it's related to account ID to the set
	for (Task t: Trigger.new){
	  acctIDs.add(t.accountID);
//Create a map to match the task related to ID's with their corresponding account ID's
	  Map<ID, Account> acctMap = new Map<ID, Account> ([Select ID, Last_SW_Activity__c from Account where ID in :acctIDs]);
//Create the account object
      Account acctRec = acctMap.get(t.accountID);

//If the account ID isn't null, the subject line starts with "sw", and the task has been marked as completed    
	If (t.accountID =!null && t.subject.indexOf('sw') && t.Status == 'Completed')
//Check to see if the Last_SW_Activity__c field is current compared with the latest completed activity
  	  If (acctMap.get.(t.accountID).Last_SW_Activity__c < t.endDateTime || acctMap.get(t.accountID).Last_SW_Activity ==null){
//Update the Last_SW_Activity__c field on the account object with the task's end date  
  		  acctrec.Last_SW_Activity__c = t.endDatetime;
  	}
  }
}

 

 

 

 The error I'm getting states "Invalid field endDatetime for SObject Task".  It's refering to the last line of code.  Does anybody have any idea why it's giving me that error?

  • July 19, 2011
  • Like
  • 0

Hey all,

 

I'm having a problem with what is probably a very simple solution, but I just can't wrap my head around it.  

I'm trying to update an Account.Type field with a set value when an Opportunity hits a certain Stage, but only if an Account is a specific type already. 

 

Here's the code:

trigger SetAccountToP on Opportunity (before insert, before update) {
    
   for(Opportunity o : Trigger.New){
        if((o.StageName == 'Proposal/Price Quote' || o.StageName == 'Negotiation/Review' || o.StageName == 'Closed Won') && o.Account.Type == 'User')
        {   Account a = o.account;
            a.Type = 'Prospect';
            update a;  
         }   
    }
}

 

 

I know this code is pretty bad, but I've tried many things and this is the easiest to read through to illustrate my point.


Any help would be appreciated.

Hoping to get some guidance and maybe lift the fog I seem to be in with understanding test methods for Apex Classes. I have gotten the test methods for triggers down fairly well but am still struggling with getting coverage on my classes that query records and return them to visualforce pages dynamically. I have 3 classes/VF pages that are plaguing me on coverage at the moment. The first is listed below. Any examples and/or recommendations would be appreciated.

 

Lead Inbox:

This is a Class and VF page that we created as a home page component. It returns and displays unread leads for our users filters by lead source so that they can be aware of new Leads assigned to them that need their attention. The class and page is designed to get the leads and also return a count of how many unread leads they have. I have used sharing on this class as the lists generated need to be specific to the rep or manager viewing the inbox on their homepage. I also have a reference to a sorting class on here that allows the reps to sort the list in the VF page.

 

Here's the class. The code works perfectly but I currently have 0% coverage as I have no test method on it.

 

public with sharing class LeadInbox {


 
public PageReference ViewData() {
return null;
}

List<Lead> rqs;
public String sortField {get; set;}
public String previousSortField {get; set;}

 public List<Lead> getLead() {

  if(rqs == null){
  rqs = [select Id, Name, Company, LeadSource, Status, OwnerId, CreatedDate from Lead 
  
  Where (
  (LeadSource='Partner Referral'
   OR
  LeadSource='Employee Referral'
   OR
  LeadSource='External Referral Program'
   OR
  LeadSource='Management Networking'
   OR
  LeadSource='Sales Inquiry (Web)'
   OR
  LeadSource='Telemarketing'
  )

  AND
  IsUnreadByOwner = TRUE
  AND
  Status != 'Disqualified')
  ORDER BY Lead.CreatedDate Desc
  Limit 4 ];
  }
  return  rqs;
 }


public void doSort(){
        String order = 'asc';
        
        /*This checks to see if the same header was click two times in a row, if so 
        it switches the order.*/
        if(previousSortField == sortField){
            order = 'desc';
            previousSortField = null;
        }else{
            previousSortField = sortField;
        }
       
        //To sort the table we simply need to use this one line, nice!
        superSort.sortList(rqs,sortField,order);
    }


public Integer getUnreadLeads() {

return [

select count() from Lead

where (IsConverted = False
 AND 
  IsUnreadByOwner = TRUE
 AND
  Status != 'Disqualified'
 AND
  (LeadSource ='Partner Referral'
   OR
  LeadSource='Employee Referral'
   OR
  LeadSource='External Referral Program'
   OR
  LeadSource='Management Networking'
   OR
  LeadSource='Sales Inquiry (Web)'
   OR
  LeadSource='Telemarketing'
  )

];

}

 

and the VF page: It works perfectly as well. :) 

 

<apex:page cache="true" controller="LeadInbox" tabStyle="Lead" showHeader="false">
<html>

<body>

<apex:form id="test">
  <apex:pageblock title="">

    <table width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr>     
             <td width="13%" height="120">
              
                 <table>
                 
 <tr><td align="center"><font size="5" color="#0000CC"><a href="/00Q?fcf=00B30000005veVy" target="_parent"><b>{!UnreadLeads}</b></a></font></td></tr>                
 <tr><td align="center"> <font size="3" color="#0000CC">Unread Referral Leads</font></td></tr>
                    
                 </table>       
            </td>
    
            <td width="87%">
        <apex:pageBlockTable value="{!Lead}" var="L" id="table">
                                               
            <apex:column >
                <apex:facet name="header">Action</apex:facet>
                <apex:outputLink title="" value="/{!L.id}" target="_blank" style="font-weight:bold">View</apex:outputLink>&nbsp;        
            </apex:column>    
            
           <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.Name.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="Name" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.Name}"/>
                </apex:column>

            
           <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.Company.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="Company" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.Company}"/>
                </apex:column>
            
            <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.LeadSource.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="LeadSource" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.LeadSource}"/>
                </apex:column>
            
            <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.Status.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="Status" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.Status}"/>
                </apex:column>
            
            <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.OwnerId.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="OwnerId" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.OwnerId}"/>
                </apex:column>
            
            <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink value="{!$ObjectType.Lead.Fields.CreatedDate.Label}" action="{!doSort}" rerender="table">
                            <apex:param name="sortField" value="CreatedDate" assignTo="{!sortField}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputField value="{!L.CreatedDate}"/>
                </apex:column>
            
        </apex:pageBlockTable>
        
      </td>
      
     </tr>   
    </table>    
        
  </apex:pageblock>
    
</apex:form>

</body>
</html>
</apex:page>

Any help on developing a test method on this would be appreciated. Its just a query and page render so I know its can't be THAT complicated. I have read through all the documentation on writing test methods and something about it for classes just doesn't make sense to me.

 

Hi there-

 

So I got assistance on this code, built the test class and deployed it. It works fine when creating a Task under Opp but throws a null pointer exception error when I create a task under any other object.

 

Goal: When adding a task in opportunity automatically pull the assigned rep and select the picklist field for them on the task. When no rep selected do nothing.

 

Both fields are named Assigned_Rep__c, however the field on the Opp is a reference Assigned_Rep__r.Name. I do not need any trigger except when accessed from an opportunity.

 

Error:

 

Attempt to de-reference a null object Trigger.populatePicklist: line 9, column 34

 Trigger

trigger populateAssignedRep on Task(before insert, before update){
    
    
    String oppPrefix = Schema.SObjectType.Opportunity.getKeyPrefix();
    List<Id> oppIds = new List<Id>();
    
    for(Task t: Trigger.new){
        String relatedTo = (String)t.WhatId;
        String relatedToPrefix = relatedTo.subString(0,3);
        if(oppPrefix == relatedToPrefix){
           oppIds.add(t.WhatId);
        }
    }
    
    Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>();
    if(!oppIds.isEmpty()){
        oppMap.putAll([Select Id, Name, Assigned_Rep__c, Assigned_Rep__r.Name from Opportunity where Id IN :oppIds]);
        
    
          for(Task t: trigger.new){
             String relatedTo = (String)t.WhatId;
             String relatedToPrefix = relatedTo.subString(0,3);
             if(oppPrefix == relatedToPrefix){
                if(oppMap.containsKey(t.WhatId)){
                   Opportunity opp = oppMap.get(t.WhatId);
                   if(opp.Assigned_Rep__c != null){
                      t.ARI_Rep__c = opp.Assigned_Rep__r.Name;                    }
                }
             }
          }
    }
}

 

I'm using this as my first venture into triggers, and was able to handle the test class by myself, so I am extremely appreciative of the help I am getting. Thanks everyone.

 

  • September 09, 2010
  • Like
  • 0

Hello,

 

I began writing an apex that auto populates fields in my case based on a lookup field before saving (hope that made sense :) ).

 

My lookup field relates the case to an account by account number. I have some field such as main contact, phone, address, etc. that I would like to auto populate once the lookup field is populated before submitting/saving.

 

Is this possible with a Before Update? Can someone help me out with the first few lines? Thanks!

 

 

  • September 08, 2010
  • Like
  • 0

Trying to solve one last problem on a trigger I am working on. Currently, the trigger works fine on 'insert' and 'delete', but generating the following error message when 'updating':

 

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger rollupCaseHoursTo360 caused an unexpected exception, contact your administrator: rollupCaseHoursTo360: execution of AfterUpdate caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.rollupCaseHoursTo360: line 91, column 44

 

The problem occurs when one of our particular fields is NULL; which is the case most of the time.  So the update trigger needs to test to make sure the value is not NULL before executing the rest of the code.  Below is a copy of the update section of trigger and comments of how I tried to test for the NULL value and section generating error:

 

 

.
.
.
else if(Trigger.isUpdate)
{
	//Tried adding test to verify value was not null before executing rest of code
	if (Case.X360_Contract_Cycle__c != NULL) {
	
	//sum total both old and new
	Case [] oldTime = Trigger.old;
	Case [] newTime = Trigger.new;
	Double newSum = 0.0;
	Double oldSum = 0.0;

	for(Case newTe: newTime)
		{
			for(Case oldTe : oldTime)
				{

// SECTION GENERATING ERROR IF 'X360_Contract_Cycle__c' IS NULL
X360_Contract_Cycle__c oldTimesheet = [Select Id, Name, Delivered_Hours__c from X360_Contract_Cycle__c where Id = :oldTe.X360_Contract_Cycle__c];

X360_Contract_Cycle__c newTimesheet = [Select Id, Name, Delivered_Hours__c from X360_Contract_Cycle__c where Id = :newTe.X360_Contract_Cycle__c];
					
					
					Case [] newSumHours = [Select Id, Case_Hours__c  from Case where X360_Contract_Cycle__c = :newTimesheet.Id];
					Case [] oldSumHours = [Select Id, Case_Hours__c from Case where X360_Contract_Cycle__c = :oldTimesheet.Id];

							//sum premiums from child objects
							for(Case oldSumHour : oldSumHours)
							{
								//converting 'Case_Hours__c' from string data type to number (double)
    							double oldCaseHours = double.valueOf(oldSumHour.Case_Hours__c);
								oldSum += oldCaseHours;
							}

							for(Case newSumHour : newSumHours)
							{
								//converting 'Case_Hours__c' from string data type to number (double)
    							double newCaseHours = double.valueOf(newSumHour.Case_Hours__c);
								newSum += newCaseHours;
							}

					newTimesheet.Delivered_Hours__c = newSum;
					oldTimesheet.Delivered_Hours__c = oldSum;

					//sheetsToUpdate.add(newTimesheet);
					//sheetsToUpdate.add(oldTimesheet);

					sheetsToUpdate.add(newTimesheet);
					if(newTimesheet.Id != oldTimesheet.Id){
						sheetsToUpdate.add(oldTimesheet);
					}

				}
			}


update sheetsToUpdate;

}

}

 

I am far from a full fledged Developer so trying to hack my way through this a bit.  Logically I thought the IF test would work, but the rest of the code appears to execute regardless if the value is NULL or not.  If the value is not NULL the update works fine.  Any suggestions?  Thanks!!

 

i hve two custom object

with lookup relationship obj2 has three record type,

when i m creating obj1 it should create three field according to recoed type.

trigger LicenceInsert on Licence__c (after insert) 
{
Licence__c c=new Licence__c ();
System.debug(trigger.new[0].id);
if(c.id !=null)
{
List<OtherActivity__c> OtherActivity= new List<OtherActivity__c>();
OtherActivity__c a=new OtherActivity__c();
a.RecordTypeId='01290000000TdtQAAS';
a.DatamigrationApplicable__c='Yes';
a.DMTypeOnboarding__c='Yes';
a.LicenceID__c='trigger.new[0].id';
a.MigrationType__c='free';
OtherActivity.add(a);
OtherActivity__c b=new OtherActivity__c();
b.RecordTypeId='01290000000TdtLAAS';
b.LicenceID__c='trigger.new[0].id';
b.PaidTraining__c='no';
b.TrainingType__c='onboarding';
OtherActivity.add(b);
OtherActivity__c t=new OtherActivity__c();
t.RecordTypeId='01290000000TdtGAAS';
t.LicenceID__c='trigger.new[0].id';
t.UserSetUPStatus__c='Create';
OtherActivity.add(t);
insert OtherActivity;
}
}
no error but it is not creating data according to record type
  • June 17, 2010
  • Like
  • 0

I was testing my trigger in dataloader and received the following error:

 

Error:

SalesInvoiceTotalsToOpportunity: execution of AfterUpdate

caused by: System.ListException: Duplicate id in list: 006S0000003fw8pIAA

Trigger.SalesInvoiceTotalsToOpportunity: line 55, column 2

 

trigger SalesInvoiceTotalsToOpportunity on Sales_Invoice__c (after insert, after update) {

	Set<Id> opIds = new Set<Id>();
	for (Sales_Invoice__c si : Trigger.new) {
		opIds.add(si.Opportunity__c);
	}
	
	List<Sales_Invoice__c> salesInvoiceList = [Select Opportunity__c, Date__c, Payment_Posting_Date__c, Subtotal__c, Amount_Paid__c From Sales_Invoice__c Where Opportunity__c in: opIds];
	
	Map<Id, List<Sales_Invoice__c>> oppyToSalesInvoiceMap = new Map<Id, List<Sales_Invoice__c>>();
	
	for (Sales_Invoice__c salesInvoice : salesInvoiceList) {
		
		List<Sales_Invoice__c> salesInvoices = oppyToSalesInvoiceMap.get(salesInvoice.Opportunity__c);
		if (salesInvoices == null) { 
			
			salesInvoices = new List<Sales_Invoice__c>();
			oppyToSalesInvoiceMap.put(salesInvoice.Opportunity__c, salesInvoices);
		}
		salesInvoices.add(salesInvoice);
	}
	
	List<Opportunity> opps = [Select Date_Paid__c, Date_Invoiced__c, Total_Invoiced_Amt__c, Total_Paid_Amt__c From Opportunity Where Id in: opIds];

	List<Opportunity> oppsToUpdate = new List<Opportunity>();
	
	for (Id oppyId : oppyToSalesInvoiceMap.keySet()) {
		Decimal invoicedAmt = 0;
		Decimal totalPaid = 0;
		List<Sales_Invoice__c> salesInvoices = oppyToSalesInvoiceMap.get(oppyId);
		for (Sales_Invoice__c salesInvoice : salesInvoices) {
			invoicedAmt =  invoicedAmt + salesInvoice.Subtotal__c;
			totalPaid = totalPaid + salesInvoice.Amount_Paid__c;
		}
		
		for (Opportunity o : opps) {
		o.Total_Invoiced_Amt__c = invoicedAmt;
		o.Total_Paid_Amt__c = totalPaid;
		oppsToUpdate.add(o);
		}
	}
	
	
	update oppsToUpdate;

}

 

How can I correct the trigger so it will work in bulk mode? 

Thanks.

Hi I have an contact object and application object. As soon as an contact oject is created , then related application is created.

I hae two fields as math score and english score and field as admission status on application object .

Now, i have written a trigger such that whenever an math and english test scores are updated then automatically the admission status field on application object is updated to placement exam.IT works fine now, but if i change the admission status and then try to update the two field values on contact record it gives me an error. Please find below the code and error.i would appreciate any kind of help.thank you

 

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

List<EnrollmentrxRx__Enrollment_Opportunity__c> application=[Select Id from EnrollmentrxRx__Enrollment_Opportunity__c where EnrollmentrxRx__Applicant__c in: Trigger.New Limit 1];
List<EnrollmentrxRx__Enrollment_Opportunity__c> application2 = new List<EnrollmentrxRx__Enrollment_Opportunity__c>();
for(Contact con : Trigger.New)
{
if(con.Math_Placement_Exam_Score__c!=null && con.English_Placement_Exam_Score__c!=null)
{
if(application.size()>0)
{
for(EnrollmentrxRx__Enrollment_Opportunity__c application1 : application )
{
application1.EnrollmentrxRx__Admissions_Status__c = 'Placement Exam';
application2.add(application1);
}
}
}

}
update application2;
}

 

Error:

 

Error:Apex trigger AdmissionStatus caused an unexpected exception, contact your administrator: AdmissionStatus: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a0BS0000002zp9SMAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, EnrollmentrxRx.EOBeforeUpdate: execution of BeforeUpdate caused by: System.Exception: EnrollmentrxRx:Too many SOQL queries: 21 (EnrollmentrxRx): []: Trigger.AdmissionStatus: line 20, column 1

  • June 14, 2010
  • Like
  • 0

Hi,

 

I have a trigger that needs to be deployed to production.

I have written test method to get a code coverage of above 75%. This works fine when i do "Run All Test Cases", but not individually.

When i run my test class individually i get 68% coverage, while the  average of all test cases is 96%.

 

My issue is i need to push only individual trigger but not all triggers and classes?

does it allow me to deploy?can any body let me know how this could be achieved or am i doing anything wrong?

 

Thanks,

Sales4ce

 

 

I desperately need to map some custom fields from the Account to a Contract.  How would I go about writing this code?  I can't find anyone who is doing this, but I'm sure it can be done, if someone can help me with the code, or and idea outside of the box!  Please help!!!!!

I am getting the following error from one of my test scripts.

 

 Program_Session_Testing_New.runPositiveTestCases System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AddSessionMembers2: execution of BeforeInsert

caused by: System.DmlException: Insert failed. First exception on row 1; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Leisure_Services_Client__c]: [Leisure_Services_Client__c]

 

I added the necessary Leisure Services Client data to the tables, only to have the Insert fail again, this time on row 2.  I added yet another client, only to have a failure on row 3.

 

Is there something obvious that I am doing wrong?  It's as if the system is trying to put in an extra record.

 

 

Here is the test script.

 

@isTest
private class Program_Session_Testing_New {
static testMethod void runPositiveTestCases() {
//Setup User;
//User u1 = [select id from User where alias='auser'];
//Run As U1
//System.RunAs(u1){
//List<Program_Attendance__c> addclient = new List<Program_Attendance__c>();
System.debug('Inserting user... (single record validation)');

Program__c TestProg = New Program__c (name = 'digital photos');
Insert TestProg;

Leisure_Services_Client__c TestClient = New Leisure_Services_Client__c (First_Name__c = 'Joe', Last_Name__c = 'Smith', Differentiator__c = '1', Birth_Date__c = system.today(), Postal_Code__c = 'V4V3G2');
Insert TestClient;

Leisure_Services_Client__c TestClient2 = New Leisure_Services_Client__c (First_Name__c = 'Jack', Last_Name__c = 'Smith', Differentiator__c = '1', Birth_Date__c = system.today(), Postal_Code__c = 'V4V3G2');
Insert TestClient2;


Program_Schedule__c TestSched = New Program_Schedule__c (Program__c = TestProg.id, Start_Date__c = datetime.newInstance(2009, 10, 21), Date_and_Time__c = system.now(), Normal_Credit_Hours__c = 2, Semester__c = 'Winter 2010');
Insert TestSched;

Class_Member__c classmember = new Class_Member__c(name = 'Joe Smith', Program_Schedule__c = TestSched.id, Program__c = TestProg.id, Client__c = TestClient.id);
Insert classmember;
Class_Member__c classmember2 = new Class_Member__c(name = 'Mike Smith', Program_Schedule__c = TestSched.id, Program__c = TestProg.id, Client__c = TestClient2.id);
Insert classmember2;

Program_Session__c testsession = new Program_Session__c (Program_Schedule__c = TestSched.id, Date_Time__c = datetime.newInstance(2010, 03, 01), Session_Number__c = 1, Create_Attendance_Lists__c = True);
Insert testsession;

//testsession.Credit_Hours__c = 2;

//Update testsession;


}
}

 

Here is the trigger that is failing.

 

trigger AddSessionMembers2 on Program_Session__c (Before Insert, Before Update) {

//Create list to insert into Session Attendance
List<Program_Attendance__C> ClientsforSession = New List<Program_Attendance__C>();

Set<id> ProgInstance = New Set<id>();

For (Program_Session__c PSCAC :Trigger.new){
ProgInstance.add(PSCAC.id);
ProgInstance.add(PSCAC.Program_Schedule__C);


//Check the checkboxes to see whether to proceed
If (PSCAC.Attendance_Lists_Created__c == False){
If (PSCAC.Create_Attendance_Lists__c == True) {


//Check to see if attendance is already added for the session
Double CountClientsThisSession = [Select Count() from Program_Attendance__c where Program_Session__C in :ProgInstance];
If (CountClientsThisSession == 0) {

//create a set of class members
List<Class_Member__c> AllClassMembers = New List<Class_Member__c>();
    

ID ProgSessID = PSCAC.ID;
ID ScheduleID = PSCAC.Program_Schedule__c;
String ProgSessName = PSCAC.name;

//Get the list of current attendees
List<Class_Member__c> CurrentClassMembers = New List<Class_Member__C>([Select name, Client__c from Class_Member__c where Program_Schedule__C in :ProgInstance]);

//Iterate through list
For (Class_Member__c MemberstoInsert : CurrentClassMembers){
//Check Program_Schedule_ID 

ID ClientID = MemberstoInsert.Client__c;

//build name
String ProgAttendName = ProgsessName + ' ' + MemberstoInsert.name;

ClientsforSession.add(New Program_Attendance__c(name = ProgAttendName, Leisure_Services_Client__c = ClientID, Program_Session__c = ProgSessID,Program_Schedule__c = ScheduleID));

}

}
Insert ClientsforSession;
PSCAC.Attendance_Lists_Created__c = True;
}
}
}
}