• DCBoy
  • NEWBIE
  • 25 Points
  • Member since 2011

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 9
    Replies

I am writing a trigger that, among other things, is supposed to check if a record exists for my custom object Statistic__c with the same date and level as the one trying to be inserted.

 

Simply I want to grab the date and level from the trigger do a SOQL to find existing records and return an error to the record trying to be inserted/updated if a match is found. No problem, right?

 

Well as I am trying to bulkify, this is getting much more complicated. The issue is once I have my list of existing records how I then sync up to the list of statistic__c to send errors to the proper one. So I thought to create a map where the key = date+level and the value is the sobject. So that would work fine, I think except what if in the bulk upload are 2 records that have the same date and level. When creating the map, the 2nd record will overwite the first, so the 2nd will be found to return an error, but not the first. So does this mean I need a map with a key of date+level and the value a LIST of Statistic__c? That is what I am thinking, but this seems very complicated.

 

Perhaps I am overlooking some tip or trick to more efficiently do this.

 

Here is the code I have so far:

 

trigger UpdateDateStatistics on Statistic__c (before insert, before update, after delete, after insert, after undelete, 
after update) {

if(Trigger.isBefore) {
List<Date> dateList = new List<Date>();
List<Id> levelList = new List<Id>();
Map<String,Statistic__c> smap = new Map<String,Statistic__c>();

for(Statistic__c s : Trigger.new) {
dateList.add(s.date__c);
levelList.add(s.level__c);
             smap.put(s.date__c.format()+s.level__c,s);
         }
        List<Statistic__c> existing = [select id, date__c, level__c from Statistic__c where date__c in :dateList and level__c in :levelList];
        for(Statistic__c e : existing) {
             Statistic__c se = smap.get(e.date__c.format()+e.level__c);
            se.addError('A Record already exists for this Level and Date. Please edit that record or choose an unused date and level combinations');
}
} else { // isAfter
 // do some other stuff not relavant here
}
}

 

 

Thanks.

 

 

  • April 01, 2011
  • Like
  • 0

Hi, 

I have a datetime field and need to use it in a formula field. When I use TEXT( ClosedDate ) it outputs the time like this 2011-07-22 21:32:48Z. What does the word "Z" mean in this output and what time zone is it in? My org is in North America, the user is in Pacific Time Zone and the output seems like GMT but am not sure coz I was expecting 8 hours to be the difference between PST and GMT.

 

Is there a way to display datetime in user's time zone in a formula field?

 

Thanks in adv.

  • July 22, 2011
  • Like
  • 0

I have two page layouts (standard detail pages, not Visualforce) for Case. The user by default gets the first page layout when he clicks on a case number. The first page layout has very few fields (max 10). A button on the detail page should take him to the second page layout where there many more fields from the Case object (~50). Is there any way this can be achieved using minimal coding? Here are the options I have already explored

- Changing record type on th case record on click of the button [Unnecessary update on the record]

- Tried changing profile of the logged in user [Apex exception - cannot change logged in user's profile id]

- Creating one of the page layouts as a visual force page [Code maintenance cost is high]

 

Are there any other ideas with minimal coding that can be explored?

  • July 19, 2011
  • Like
  • 0

Hi

While creating an email, our users like the concept of applying a template for canned response. They would like to have a similar functionality for creating case notes (aka Comments). Out of the box, I dont believe you can extend templates to other objects. So using custom visual force and apex, I was able to get the list of templates but am stuck figuring out how to apply the template? Can you please provide some pointers on how to apply template to a record and get the output so a note can be created?

 

 

  • April 04, 2011
  • Like
  • 0

I would like to capture all times that SFDC throws an exception that it can't handle.

 

By 'capture' I mean that I want to set up an object that takes the output from:

 

e.getStackTraceString() and puts it into an instance with an attribute 'StackTrace__c'

 

The object set-up is the easy part. :)


The hard part is figuring out if there's a way to make Apex code's uncaught exceptions 'caught' and captured in a central place.

 

Does anyone know if this is possible?

Use case:  
(multiple custom objects, 1 record triggers multiple records in other custom object)

 

- Custom Object A contains multi-select picklist with values apple, orange , grape, & banana 

- User creates record in object A and makes selections apple, orange from picklist

- Trigger: Creates two records in Custom Object B based on the selections of apple & orange  

- Apple & Orange are differnt record types in Custom Object B

 

I'm new to triggers and here's my questions:

 

1. Is this a difficult trigger?

2. Should I be looking to use triggers for this use case in the first place?

 

All guidance and feedback is welcome - thanks.  

 

 

Hi I have a trigger that creates a custom object when an opportunity stage is set to "closed lost" and saved. I created a test class to deploy into prod, but can only get 64%coverage. Can someone help me increase my test coverage or guide me in the right dirrection so I can get as close to 100% Also when I run the test I get one Test Failure: System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [CloseDate]: [CloseDate]

 

Below is my test Class:

 

@isTest
private class MyTestWLATrigger
{
    static testmethod void TestMethod1()
    {
        //Fill all mandatory properties of opportunity and don't miss stage name
        Opportunity opp = new Opportunity() ;
        opp.Name = 'Test Oppty' ;
        opp.stageName = '4: Generate Offer' ;
        opp.WonLostReason1__c = '' ;
        //Now insert the opportunity
        insert opp ;
        
        //To let your trigger code covered in write this
        opp.stageName = 'Closed Lost' ;
        //change the stage name
        opp.WonLostReason1__c = 'Price' ;
        //Now update the opportunity
        update opp ;
        System.assertEquals(opp.Name, opp.stageName, opp.WonLostReason1__c);
        
    }
}

And below is my trigger:

 

trigger AutoCreateWinLossAnalysisOnOpportunity on Opportunity (after update) 
{

  List<Opportunity> closedOps = new List<Opportunity>();
  List<Win_Loss_Analysis__c> newwinLossObjects = new List<Win_Loss_Analysis__c>();  
  List<Win_Loss_Analysis__c> updatewinLossObjects = new List<Win_Loss_Analysis__c>();
  
  List<RecordType> recordTypesForOppty = new List<RecordType>();
  recordTypesForOppty = [Select Name, ID From RecordType where SobjectType = 'Win_Loss_Analysis__c'];
  System.debug('recordTypesForOppty'+recordTypesForOppty);
  
    List<Id> ExistingIds = new List<Id>();
    
     
    Integer  count = Trigger.new.size(); 
    for(Opportunity newvalue : Trigger.new)
    {
      Opportunity oldvalue = Trigger.oldMap.get(newvalue.Id);
        if(oldvalue.StageName != newvalue.StageName || oldvalue.WonLostReason1__c != newvalue.WonLostReason1__c)  
       {
           if(newvalue.StageName == 'Closed Lost'){
            if(newvalue.WonLostReason1__c == 'Price' 
              || newvalue.WonLostReason1__c == 'Product Feature/Functionality' 
              || newvalue.WonLostReason1__c =='Relationship')
            {
            System.debug('newvalue'+newvalue);
               closedOps.add(newvalue);
                 ExistingIds.add(newvalue.Id);
       
            }
          }
       }
    }
    system.debug('Found : ' + closedOps.size() + ' Opps that need analysis records created');
    if (closedOps.size() > 0)  
    { 
      List<Win_Loss_Analysis__c> existing = [SELECT Id,Opportunity_Name__c FROM Win_Loss_Analysis__c WHERE  Opportunity_Name__c  in :ExistingIds];
      system.debug('Found : ' + existing.size() + ' Existing Win Loss Records');
      string LossAnalysis = null;
      for (Opportunity oppty : closedOps)
      {       
              // get the recordTypeId
              Id WinLossObjectRecordTypeId = null;
              string typeName;
              LossAnalysis = oppty.WonLostReason1__c.toLowerCase();
              System.debug('******LossAnalysis *******'+LossAnalysis);
          for (RecordType recordType : recordTypesForOppty)
          {
          
          System.debug('recordType'+recordType);
            typeName = recordType.Name.toLowerCase();
            
            System.debug('recordType.Name.toLowerCase()>>>>>>>'+recordType.Name.toLowerCase());
              System.debug('******typeName *******'+typeName );
            if (LossAnalysis == 'price' && typeName == 'price (lost)') 
            {
            
            System.debug('ist if>>>>>>');
              WinLossObjectRecordTypeId = recordType.Id;
            }
            if (LossAnalysis == 'product feature/functionality' && typeName == 'productfeature (lost)') 
            {
             System.debug('2nd if>>>>>>');
              WinLossObjectRecordTypeId = recordType.Id;
            }
            if (LossAnalysis == 'relationship' && typeName == 'relationship (lost)') 
            {
             System.debug('3rd if>>>>>>');
              WinLossObjectRecordTypeId = recordType.Id;
            }
          }
          system.debug('Record type id: ' + WinLossObjectRecordTypeId + ' found for oppt id' + WinLossObjectRecordTypeId );
              // construct the new custom object with the required fields set
              
              Win_Loss_Analysis__c wL = new Win_Loss_Analysis__c();
              System.debug('oppty.Id>>>>>>>'+oppty.Id);
              wL.Opportunity_Name__c = oppty.Id;
              wL.RecordTypeId = WinLossObjectRecordTypeId;
              System.debug('*************Checking RecordTypeId***********'+WinLossObjectRecordTypeId);
              System.debug('WinLossObjectRecordTypeId>>>>>>>'+WinLossObjectRecordTypeId);
              wL.Account_Name__c = oppty.AccountId;
               System.debug('oppty.AccountId>>>>>>>'+oppty.AccountId);
              if(existing.size() > 0)
              {
                   for(Win_Loss_Analysis__c exist : existing)
                {
                  if(exist.Opportunity_Name__c == oppty.Id)
                  {
                    wL.Id = exist.Id;
                    break;  
                  }              
                }
              }
              
              if(wL.Id == null)
              {
                newwinLossObjects.add(wL);
              }
              else
              {
                updatewinLossObjects.add(wL);
              }
              
      }
    }
    system.debug('Inserting ' + newwinLossObjects.size() + ' new Win Loss Objects' );
    system.debug('Updating ' + updatewinLossObjects.size() + '  Win Loss Objects' );
    if(newwinLossObjects.size() > 0)
         insert newwinLossObjects;
   
    if(updatewinLossObjects.size() > 0)
         update updatewinLossObjects;

}

I was wondering if there is a way to send a email using the email field of a custom object using apex. I have tried a lot of differnt techniques and nothing seems to be working for me. Can someone please give me a clue as to how I can accomplish this. 

Hi ,

 

I am new in salesforce and i wana that how we create/return  xml  of any (Custom or standard) in salesforce .

 

Vikas

Is there a way to redirect a user to an Account Page Layout based on logic in Apex code? There is a clear path to redirect to a VisualForce page, but I do not want to recreate the various Account Page Layouts in VisualForce.

 

I have read that you can include VisualForce elements in a Page layout, but I am either looking to redirect from the Apex code to a page layout or include a Page Layout in a VisualForce page (without recoding the PageLayout in VisualForce markup).

 

I realize that I can use profiles to direct a user to different Page Layouts, but I need more granular control than a profile will provide, hence the apex code.

 

I am writing a trigger that, among other things, is supposed to check if a record exists for my custom object Statistic__c with the same date and level as the one trying to be inserted.

 

Simply I want to grab the date and level from the trigger do a SOQL to find existing records and return an error to the record trying to be inserted/updated if a match is found. No problem, right?

 

Well as I am trying to bulkify, this is getting much more complicated. The issue is once I have my list of existing records how I then sync up to the list of statistic__c to send errors to the proper one. So I thought to create a map where the key = date+level and the value is the sobject. So that would work fine, I think except what if in the bulk upload are 2 records that have the same date and level. When creating the map, the 2nd record will overwite the first, so the 2nd will be found to return an error, but not the first. So does this mean I need a map with a key of date+level and the value a LIST of Statistic__c? That is what I am thinking, but this seems very complicated.

 

Perhaps I am overlooking some tip or trick to more efficiently do this.

 

Here is the code I have so far:

 

trigger UpdateDateStatistics on Statistic__c (before insert, before update, after delete, after insert, after undelete, 
after update) {

if(Trigger.isBefore) {
List<Date> dateList = new List<Date>();
List<Id> levelList = new List<Id>();
Map<String,Statistic__c> smap = new Map<String,Statistic__c>();

for(Statistic__c s : Trigger.new) {
dateList.add(s.date__c);
levelList.add(s.level__c);
             smap.put(s.date__c.format()+s.level__c,s);
         }
        List<Statistic__c> existing = [select id, date__c, level__c from Statistic__c where date__c in :dateList and level__c in :levelList];
        for(Statistic__c e : existing) {
             Statistic__c se = smap.get(e.date__c.format()+e.level__c);
            se.addError('A Record already exists for this Level and Date. Please edit that record or choose an unused date and level combinations');
}
} else { // isAfter
 // do some other stuff not relavant here
}
}

 

 

Thanks.

 

 

  • April 01, 2011
  • Like
  • 0