• mng
  • NEWBIE
  • 50 Points
  • Member since 2011

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

hello,

 

I am confused with what values the Trigger.new should contain during a trigger on before Update or before Insert.

 

I have a trigger on Case object:

 

trigger limitHighPriorityCases on Case (before insert,before update) {
 
  for (Case c : Trigger.new)
   {
    if ( (c.Priority == 'High') && (c.IsClosed == FALSE) )
    {
      //some code
} } }

 

 

When I update a case with Closed status, the IF loop is executed, which I don't really understand since Trigger.new is supposed to conatin the new version of the case, therefore IsClosed should be equal to TRUE and the IF loop souldn't execute.

 

Could someone clarify?

 

Thank you

Marc

  • August 19, 2011
  • Like
  • 0

Hi All,

 

The following works and returns the result as expected:

 

private List<Opportunity> opps;

 

opps = [SELECT Id, Name, Amount, CloseDate, StageName,LeadSource FROM Opportunity WHERE Id IN ('006U00000026EE0IAM','006U00000026EDs')];



However, I am trying to make it work this way, but the query does not return any results.

 

String sClause = '\'' + '006U00000026EE0IAM' + '\'' + ',' + '\'' + '006U00000026EE0IAM' + '\'';

 

opps = [SELECT Id, Name, Amount, CloseDate, StageName,LeadSource FROM Opportunity WHERE Id IN (:sClause)]; 

 

Can someone let me know what is the proper syntax?

 

Thanks in advance.

      


So I want to merge accounts. I know that when I merge accounts, only the update and delete triggers will fire on the Winning and Losing accounts, respectively. However, I also want some triggers to fire on some objects related to Accounts when the Accounts are merged. Let's call the objects Account_Object_1 and Account_Object_2. There's nothing special about these two objects, just the following.

 

Account_Object_1:

- Notable fields:

> Account__c [ Lookup(Account) ]

 

Account_Object_2:

- Notable fields:

> Account__c [ Lookup(Account) ]

> Account_Object_1__c [ Lookup(Account_Object_1__c) ]

> Checkbox__c [ Checkbox ]

- Validation rule:

> Fail when: Account__c <> Account_Object_1__r.Account__c

 

There's a trigger sitting on Accounts. After delete, it wants to do this:

 

public static void doSomething( List<Account> deletedAccounts )
{
	Set<Id> masterAccountIds = new Set<Id>();

	for( Account account : deletedAccounts )
	{
		if( account.MasterRecordId != null )
		{
			masterAccountIds.add( account.MasterRecordId );
		}
	}

	if( !masterAccountIds.isEmpty() )
	{
		List<Account_Object_2__c> relatedObjects = [ SELECT Id Account__c, Account_Object_1__r.Account__c
FROM Account_Object_2__c
WHERE Account__c IN :masterAccountIds ]; for( Account_Object_2__c accountObject : relatedObjects ) { System.debug( accountObject.Account__c );
                 System.debug( accountObject.Account_Object_1__r.Account__c );
                 accountObject.Checkbox__c = true; } try { update relatedObjects; } catch( System.Exception ex ) { throw ex; } } }

 

It's pretty simple, but it just wants to do an Update on all the Objects, and at this point in the trigger it will pull in Account_Object_2 records that originally belonged to the Account as well as the new ones that got carried over from the merge.

 

So here's where it starts getting strange.

 

If you throw this code into an org, and merge accounts through the UI, it's going to be fine. The accounts will merge, the triggers will fire, and those checkboxes on those related records are going to populate correctly. You can test this out for yourself.

 

Aha! Gotcha! You shouldn't leave code untested! So a unit test would just involve creating a couple of each record, inserting them, and ultimately getting here.

 

Test.startTest();

	merge testMasterAccount testLoserAccount;

Test.stopTest();

 Seeing as how it supposedly works through the UI..this statement shouldn't cause a problem, right? However, surprise surprise, it fails. Why?

 

17:28:45.522|VALIDATION_RULE|03d50000000Gu6s|Sync_Rule
17:28:45.526|VALIDATION_FORMULA|Account__c <> Account_Object_1__r.Account__c|Account__c=0015000000ZgXdq , Account_Object_1__r.Account__c=0015000000ZgXdr
17:28:45.526|VALIDATION_FAIL

 

Ah, so it's that validation rule. It's saying that the field value on the Account_Object_2 record isnt the same as the one on its related record, eh? I'll just take a peek inside the trigger and take a look at what's wrong here...

 

17:28:45.509|USER_DEBUG|[21]|DEBUG|0015000000ZgXdqAAF
17:28:45.509|METHOD_EXIT|[21]|System.debug(ANY)
17:28:45.509|METHOD_ENTRY|[22]|System.debug(ANY)
17:28:45.509|USER_DEBUG|[22]|DEBUG|0015000000ZgXdqAAF

 Or not. So as you can see from the method being executed, it's making debugs right after it queries for those related objects back. There aren't any other triggers, workflows, changes happening to the object between the DML and the query, so it's not like those values are changing elsewhere. What this basically looks like is that the validation rule is using values that are not the same as what exists in the queryable context of apex, and that's just baffling.

 

So. Ideas? Thanks for reading.

  • May 11, 2011
  • Like
  • 0

hello,

 

I am confused with what values the Trigger.new should contain during a trigger on before Update or before Insert.

 

I have a trigger on Case object:

 

trigger limitHighPriorityCases on Case (before insert,before update) {
 
  for (Case c : Trigger.new)
   {
    if ( (c.Priority == 'High') && (c.IsClosed == FALSE) )
    {
      //some code
} } }

 

 

When I update a case with Closed status, the IF loop is executed, which I don't really understand since Trigger.new is supposed to conatin the new version of the case, therefore IsClosed should be equal to TRUE and the IF loop souldn't execute.

 

Could someone clarify?

 

Thank you

Marc

  • August 19, 2011
  • Like
  • 0

Hi,

 

I am trying to insert a record in a custom object which has a recordtype in my test class.

I am not sure on how to create a record type and assign it to the object.

 

Any ideas on how to go about doing it ?

 

Thanks

Prady

  • August 19, 2011
  • Like
  • 0

Hi All,

 

The following works and returns the result as expected:

 

private List<Opportunity> opps;

 

opps = [SELECT Id, Name, Amount, CloseDate, StageName,LeadSource FROM Opportunity WHERE Id IN ('006U00000026EE0IAM','006U00000026EDs')];



However, I am trying to make it work this way, but the query does not return any results.

 

String sClause = '\'' + '006U00000026EE0IAM' + '\'' + ',' + '\'' + '006U00000026EE0IAM' + '\'';

 

opps = [SELECT Id, Name, Amount, CloseDate, StageName,LeadSource FROM Opportunity WHERE Id IN (:sClause)]; 

 

Can someone let me know what is the proper syntax?

 

Thanks in advance.

      


Need help in save button: Whenwhen we are saving the records in VF page we are able to see the values but when we open the record again and see we are unable to see the values. This is my class 

 

public class SSOWcontrollers{ 

ApexPages.StandardController controller;
Public SSOW__c ssow;
Public SSOWcontrollers(ApexPages.StandardController stdController) {}
    public void savessow()
    {
    String sId = ApexPages.currentPage().getParameters().get('id');
        SSOW__C sow = [SELECT Id FROM SSOW__c WHERE Id= :sId];
        if (sow != null) {
        update sow;
        }
        HVoIP__c hv = [SELECT Id FROM HVoIP__c WHERE SSOW__c = :sId];
        if (hv != null) {
        update hv;
        }
        VoIP__c v = [SELECT Id FROM VoIP__c WHERE SSOW__c = :sId];
        if (v != null) {
        update v;
        }
        VLS__c vl = [SELECT Id FROM VLS__c WHERE SSOW__c = :sId];
        if (vl != null) {
        update vl;
        }
        VPN__c vp = [SELECT Id FROM VPN__c WHERE SSOW__c = :sId];
        if (vp != null) {
        update vp;
        }
        EIA__c e = [SELECT Id FROM EIA__c WHERE SSOW__c = :sId];
        if (e != null) {
        update e;
        }
        DIA__c d = [SELECT Id FROM DIA__c WHERE SSOW__c = :sId];
        if (d != null) {
        update d;
        }
        Managed_Network_Security__c mns = [SELECT Id FROM Managed_Network_Security__c WHERE SSOW__c = :sId];
        if (mns != null) {
        update mns;
        }
        Managed_Router__c mr = [SELECT Id FROM Managed_Router__c WHERE SSOW__c = :sId];
        if (mr != null) {
        update mr;
        }
     }

}
     Here is the part of the vf page where i created a save button

 

<apex:pageBlockButtons location="TOP" > 

<apex:commandButton id="theButton" action="{!savessow}" value="save"  />           

</apex:pageBlockButtons>    

Hi all,

I have two Parent records that share the same Child record. I would like to be able to count the number of related Child records. Neither are master-detail records, hence the requirement for an Apex Trigger.

I have a working count trigger for the Parent records (included below for referece), but I suspect I need another trigger on the Child records in order for the Count trigger to fire?

The other question: An attendee (Child record) can be removed from an Event or Group without the record being deleted. A user will edit the Attendee and clear the lookup field. Is this possible to include in the same Child trigger to fire the Count Trigger on the Parent?

 

I'm fairly new to triggers :)

 

Event - Parent
Group - Parent

Attendee - Child

 

trigger CountRelatedAttendees on event_c__c (before insert, before update) {
    event_c__c[] s = Trigger.new;
    String sid = null;    
    Sid = s[0].id;

    	Integer i = [select count() from attendees__c where Event_no__c = :sid];

    s[0].Places_used__c = i;
    }

 

 

  • August 18, 2011
  • Like
  • 0
Hi, I have a managed package in my instance.. I have created a trigger in my sandbox instance.. But When I run the test classes it is showing too many scriot statements error.. Here is my code: trigger dateConvert on CnP__CnP_Transaction__c (before insert) { for(CnP__CnP_Transaction__c c:Trigger.new){ c.CnP__bSource__c = Integer.valueOf(c.CnP__bSource__c); if(c.CnP__bSource__c == 2 ){ String delimslash = '/'; String[] DDate; Datetime myDate; String tdate = c.Dummy_Field__c; if(tdate!=null){ String[] splitdate = tdate.split(' '); DDate = splitdate.get(0).split('/'); String TTime = splitdate.get(1); String month = DDate.get(0); String day = DDate.get(1); String year = DDate.get(2); String hour = TTime.split(':').get(0); String minute = TTime.split(':').get(1); String second = '00'; myDate = datetime.newInstance(integer.ValueOf(year),integer.ValueOf(month), integer.ValueOf(day), integer.ValueOf(hour), integer.ValueOf(minute), integer.ValueOf(second)); c.CnP__TransactionDate__c = myDate; c.CnP__TransactionTimeZone__c = myDate; } } } } Help me Regarding this. Anu

Hello, I am new to writing tests - working off of the template in how to write good unit tests. This is my effort but I get the error Invalid id value for this SObject type:

 

public class ActiveAffiliationsTriggerTest

static testMethod void ActiveAffiliationsTest() 

{     
    // Set up the Contact record.   

Contact c = new Contact(FirstName='Test Contact', LastName ='Test Last');   

insert c;


   // Verify that the initial state is as expected.   

c = [SELECT DVA_Affiliation_MDA_and_Active__c          

FROM Contact          

WHERE Id = :c.Id];   

System.assertEquals(null, c.DVA_Affiliation_MDA_and_Active__c);


   // Set up the Affiliation record.   

String affiliationName = 'Test Affiliation';   

Affiliation__c a = new Affiliation__c(Id=c.Id,                                     

Active__c=TRUE);


   // Insert Affiliation.   

insert a;    


   // Verify that the results are as expected.   

c = [SELECT FirstName, LastName, DVA_Affiliation_MDA_and_Active__c          

FROM Contact        

 WHERE Id = :c.Id];     

}

}

 

contact is contact

Affliliation__c is a related object where Contact is the master - contact can have more than one Affiliation record

DVA_Affiliation_MDA_and_Active__c is a number field the trigger fills in calulating on the Contact record how many affiliations the contact has

 

  • July 28, 2011
  • Like
  • 0

I keep getting Error:Apex trigger UpdateOpportunityCode96Box caused an unexpected exception, contact your administrator: UpdateOpportunityCode96Box: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.UpdateOpportunityCode96Box: line 18, column 8

 

Anyone have any ideas? Appreciate any help.

 

Here is my code: 

 

trigger UpdateOpportunityCode96Box on OpportunityLineItem (after update)
{
List<id> oppIds=new List<id>();
for (OpportunityLineItem oli : trigger.new)
{
   if (oli.Magnys_Service_Code_Copy__c == '96')
   oppIds.add(oli.opportunityid);
}
Map<Id, Opportunity> oppsById=new Map<Id, Opportunity>();
List<Opportunity> opps= [select id, Contains_Code_96__c from Opportunity WHERE id in :oppIds];
oppsById.putAll(opps);
List<Opportunity> oppsToUpdate=new List<Opportunity>();
for (OpportunityLineItem oli : trigger.new)
   {   
       Opportunity opp=oppsById.get(oli.opportunityid);
       opp.Contains_Code_96__c = true;
       oppsToUpdate.add(opp);
   }
update oppsToUpdate;
}

trigger UpdateOpportunityCode96Box on OpportunityLineItem (after update){List<id> oppIds=new List<id>();for (OpportunityLineItem oli : trigger.new){   if (oli.Magnys_Service_Code_Copy__c == '96')   oppIds.add(oli.opportunityid);}Map<Id, Opportunity> oppsById=new Map<Id, Opportunity>();List<Opportunity> opps= [select id, Contains_Code_96__c from Opportunity WHERE id in :oppIds];oppsById.putAll(opps);
List<Opportunity> oppsToUpdate=new List<Opportunity>();for (OpportunityLineItem oli : trigger.new)
   {          Opportunity opp=oppsById.get(oli.opportunityid);       opp.Contains_Code_96__c = true;       oppsToUpdate.add(opp);   }
update oppsToUpdate;}

 

Hi,

 

I have seconadry contact email on my case. So when any email is sent out from within Salesforce (using "Send an Email" button), the secondary contact email must also be included in the email. I wrote a trigger on EmailMessage object to update the CcAddress with the secondary contact email address. It is inserting the email address in the to filed but is not send email to secondary conatct. Here is my code.

 

 

trigger SeconadryConInfoOnEmails on EmailMessage (before insert,before update) {
    Set<Id> parentCase = new Set<Id>();
    Map<id,Case> mapCase = new Map<Id,Case>();
    for(EmailMessage t : Trigger.New){
        parentcase.add(t.ParentId);
    }    
    List<Case> lstCase = [select Id,Sec_Contact__c,Con_Email__c,Con_Phone__c from Case where Id in :parentCase];
    for(case c: lstCase){
        mapCase.put(c.Id,c);
    }
    for(EmailMessage m :  Trigger.New){
        if(mapCase.containskey(m.ParentId)){
            if(mapCase.get(m.ParentId).Con_Email__c!=NULL){
                if(m.CcAddress ==NULL){
                    m.CcAddress = mapCase.get(m.ParentId).Con_Email__c;

                }
                else{
                    m.CcAddress = m.CcAddress+';'+mapCase.get(m.ParentId).Con_Email__c;
                } 
            }
        }
    }
}

 

 

 

Can anyone help me to solev my issue.

Thanks in advance.

  • May 11, 2011
  • Like
  • 0