• sbb
  • NEWBIE
  • 379 Points
  • Member since 2010

  • Chatter
    Feed
  • 14
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 44
    Replies
Hi All,
I created a trigger, so that when a new event is created in Public Calendar a new CalendarEV record will be created automatically. I got error message after running test class that missing required fields, so no code coverage at all. I noticed that both Start and End fields in Event object are required Date/Time fields, so I wonder how to create Date/Time in test class for these two fields so that an event can be created and fire the trigger. Please help.

Error message: System.DmLException: insert failed. First exception on row 0; First error, Required field missing
Stack Trace: Class.CalendarEVTest.insertNewCalendarEV: Line11, colum 1

trigger CalendarEV on Event (after insert) {
List<Event> Events = new List<Event>();
   for (Event e : Trigger.new) {
           if (e.Subject != null ) {
               CalendarEV__c C = new CalendarEV__c();
               c.Name = e.Subject;
               c.Start__c = e.StartDateTime;
               c.End__c = e.EndDateTime;
               c.Location__c = e.Location;
               c.Description__c = e.Description;
                    
              insert C;
        }
    }
   }


@isTest
public class CalendarEVTest
{
    static testMethod void insertNewCalendarEV()
    {
        Test.StartTest();
        Event e = new Event();
        e.Subject = 'Test Event';
        e.Location = 'Test Location';
        e.Description = 'Test Description'; 
        insert e;
        Test.StopTest();
        System.assertEquals ('Test Event', e.Subject);
    }
}
Hi Folks,
      Iam trying to simplify my validation rule but i get error. My VR restricts users from role from chaning ownerid for subset of users, since all my users first name is "TBD" i want to simpify the rule by adding owner.firstname, here is my rule

AND(
     OR($UserRole.Id  = "00E30000000vEST",
        $UserRole.Id  = "00E40000001CZB5"),
        ISCHANGED(OwnerId),
        PRIORVALUE(OwnerId) <> "00540000000zpgS",
        PRIORVALUE(OwnerId) <> "00540000000oWNX",
        PRIORVALUE(OwnerId) <> "00540000000lkIN",
        PRIORVALUE(OwnerId) <> "00540000001SyUq",
        PRIORVALUE(OwnerId) <> "00540000001UnYg",
        PRIORVALUE(OwnerId) <> "00540000002FltR",
        PRIORVALUE(OwnerId) <> "00540000002nKbr",
        PRIORVALUE(OwnerId) <> "00540000002JAiR",
        PRIORVALUE(OwnerId) <> "00540000002IeDq",
        PRIORVALUE(OwnerId) <> "00540000002nU49",
        PRIORVALUE(OwnerId) <> "00540000002nU4Y",
        PRIORVALUE(OwnerId) <> "00540000002nU4T"
)

I want to use PRIORVALUE(Owner.FirstName <> "TBD") but i get this error "Incorrect argument type for function 'PRIORVALUE()'."

Any help is appreciated.
Hi guys,

We have a number field on the opportunity page that counts the number of products that the opportunity has and I'm trying to figure out how to run a workflow rule only when that number field increases in value.

For example, if the opportunity goes from having 1 product to 2 products or from 3 products to 5 products, it should run.

Is there a way to do this?

Thanks!
-Marc


I have a bit of code that checks to see if an account already exists based on a domain and reassigns the incoming lead based on Account owner. I need to update the trigger to leave a particular Account Owner Role out of the process but I can't figure out where to put the code.  Any help would be appreciated, thanks!  Here's the owner role id: 00E50000000t0Bf and here's the trigger:

trigger UpdateLeadOwner on Lead (before insert) {
    for (Lead leadInLoop : Trigger.new) {
   
if (leadInLoop.LeadSource != 'Contact Us' && leadInLoop.LeadSource != 'Reprint') {
    // Retrieve owner from Account record based on email domain name
    list <Account> acct = [Select OwnerId from Account WHERE Domain_1__c = :leadInLoop.Domain__c Limit 2];
        if (acct.size() == 1) {

    //the next line is for debugging, to check that you are getting a result back from the query
    System.debug('account owner id is: ' + acct[0].OwnerId);
    leadInLoop.OwnerId=acct[0].OwnerId;
        }
    }
}
}
Hi All -
Here is my situation.  I am doing some work for a small company.  They were out of liscenses.  They just got a new liscense in production for an SFDC developer (me).  They just refreshed their partial sanbox a couple days ago and are not eligible for a refresh.

They are going to manually add another user account in the Sandbox for me.  Obviously my user ids are going to be different in the Sandbox and Production.  My sandbox user id will not exist in production.

Am I correct in that I will not be able to migrate any changes I make in the Sandbox to Production due to the fact that my Sandbox User Id is not in Production?

If so, has anyone else ran into this issue and how did you work around it?

Thank you
Jason

  • July 28, 2014
  • Like
  • 0
Hello,

I have created a trigger that updates a hidden field on an Account record that was needed in order to track changes on a seperate field that is a formula field. When the field value changes, the trigger runs and captures the previous value in the Account History. Below is my trigger code (in Sandbox) that works perfect:


trigger BusinessRatingChange on Account (before insert, before update)
{
    for(Account a:Trigger.new)
    {
        if(system.trigger.OldMap.get(a.Id).Business_Rating__c != system.trigger.NewMap.get(a.Id).Business_Rating__c)
        {
            a.Business_Rating_History__c = a.Business_Rating__c;
            }
            }
            }

However, when I attempt to create a NEW account, I get the below error that looks like is due to the "BeforeInsert" action on the trigger:


Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger BusinessRatingChange caused an unexpected exception, contact your administrator: BusinessRatingChange: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.BusinessRatingChange: line 5, column 1


Does anyone have any insight as to how I can remedy this? Thanks so much in advance for your assistance!!!

Eric

Hi,

 

I am trying to display picklist field output in visualforce page in the page block section as shown below:

 

VF Page:

------------

<apex:page standardController="Account" extensions="VisualAccountExtension" title="Display Accounts" >

                          <!-- other lines of code -->

 <apex:pageBlockSection title="{!UserTypeValue} is the type ">

                <!-- other lines of code -->

</apex:page>

 

In the extension "VisualAccountExtension", I have mentioned as :

--------------------------------------------------

 

List<User> UserTypeList = new List<User>();

String UserTypeValue  {get;set:}

 

 

 public String getUserTypeValue()
    {
        return UserTypeValue;
    }    
    public void SetUserTypeValue()
    {
        UserTypeList = [select Type__c from User where Id =:UserInfo.getUserId()];
        UserTypeValue = UserTypeList[0].Type__c;        
    }   

 

But I am not getting any output, in the page block section just   "is the type" is being displayed but I am not seeing the value of "UserTypeValue" in the visual force page.

Can some please help me where am I going wrong?

 

Thanks,

Babu.

  • December 18, 2012
  • Like
  • 0

I am studying Quinton Wall's post "Using Scheduled Apex jobs to retrieve stock quotes"  but am having trouble replicating the example. Quinton uses three different code snippets, but I am not sure how theey relate to each other. Are all three snippets suppose to be one class, or three separate classes? How dooes the code correlate? This is my first project in scheduing apex.

 

Thanks,

Hi guys,

I'm wondering if anyone can please help or at least point me in the direction of where I can get help for this issue.

 

For some reason I can't deploy some updated code from my sandbox to our live system. The last code deployed was on 16/07/2012, and this comprised of an updated trigger and test class.

 

Today I have tried to deploy a small change to both the trigger and test class and now I am getting a validation failure on a different object - validation of an assert in a different test class is occurring for some reason that I cannot explain. I have tried to run tests in my sandbox in order to recreate this assertion failure but I cannot reproduce the problem in my sandbox.

 

This is very strange and I am at a loss to figure out how this happened in the first place and more importantly how to resolve the issue. As it stands I cannot deploy any code to the live system now because of this.

If anyone can provide any help to me on this I would greatly appreciate it.

Hello

 

I have a Number field "Remaining_Occurrences__c" (not required, not unique)

 

If i try to put NULL value in it via Apex Data loader, it still shows the previous value.

 

I checked my Enterprise WSDl, and the property of this field is Nillable = true.

 

Any idea how can i set NULL value to the field?

 

Thanks

Sid

Hi ,

 

     I have a trigger which generates the standard field, Name of a custom object with  'a string + name of the corresponding Contact' before inserion/Updation.

My trigger:--

____________________________________________________________________________________________

trigger trgname on cusobj__c (before insert,before update) {
Set<ID> conid = new Set<ID>();
List<contact> lstContact = new List<contact>();
Map<ID,contact> Mapname = new Map<ID,contact>();
for( cusobj__c tar :Trigger.New)
{
conid.add(tar.Contact__c); // Storing all the contact ids for which the name needs to be used
}
system.debug('Inside the trigger to update the name');
//Getting all the contact records in a list to be used in the name field
lstContact = [select id,name,firstname,lastname from contact where id in : conid];

for(integer i =0; i <lstcontact.size(); i++)
{
Mapname.put(lstcontact[i].id,lstcontact[i]); // Putting the contact id and name in a map
}

for( cusobj__c tar :Trigger.New)
{
// tar.name = 'TD Rem - ' + mapname.get(tar.Contact__c).firstname +' ' + mapname.get(tar.Contact__c).lastname;
tar.name = 'TD Rem - ' + mapname.get(tar.Contact__c).name;
}

}

_____________________________________________________________________________________________

 

I do have a test class for this trigger . But getting  error 'Assertion Failed: Expected: 20, Actual: 0' 

 

My Testclass:-

____________________________________________________________________________________________

@isTest
Private class testTrgTrgname{
Static testMethod void methodname(){
Contact con = new Contact();
con.FirstName= 'fname';
con.LastName = 'lname';

insert con;
System.debug('value for contact name:' + con);
Contact con1 = new Contact();
con1.LastName = 'lname1';
insert con1;
//Insert test data

cusobj__c Tmapt = new cusobj__c();
Tmapt.Appointment_Created__c = True;
Tmapt.Target_date__c = System.today()+3;
Tmapt.Contact__c = con.id;

insert Tmapt;
System.debug('value for Tmapt name:' + Tmapt.Name);
System.debug('value for Tmapt :' + Tmapt);
List<cusobj__c> ltmd = new List<cusobj__c>();
ltmd =[Select Contact__c from cusobj__c where id =:Tmapt.id];
System.assertEquals(1,ltmd.Size());

System.assertEquals('TD Rem-fname lname', Tmapt.Name);
cusobj__c Tpt = new cusobj__c();
Tpt.Appointment_Created__c = True;
Tpt.Target_date__c = System.today()+ 5;
Tpt.Contact__c =con1.id;
insert Tpt;
System.assertEquals(Tpt.Name, con1.name);
Contact newcon = new Contact();
newcon.lastname = 'lnewcon';
insert newcon;
//cusobj__c Ltar =[Select Contact__c from cusobj__c where id := Tmapt.id];
//Tmapt.Cotnact__c = newcon.id;
//update Tmapt;

}
}

______________________________________________________________________________________________

  

 

Any idea?? Please help...

 

 

Thank You,

sav3

  • May 18, 2012
  • Like
  • 0

As part of our integration, we bring in contract data from a different source and insert/update them into salesforce Contract object. Everything works fine except that the End Date (Contract's standard field) ends up being NULL even though there is a valid date in the correct format in the source. We don't have the same problem with the 'Start Date' field. I suspect that the Contract End Date is a bit special -- but I have no problem updating it directly in salesforce! So I wonder why it doesn't let me put a date in there via integration!

 

I also noticed that you can't build a Field Update (workflow) to update this standard End Date field!

 

Am I missing something? How can I update this field?

 

Any help is appreciated.

 

Thanks!

  • October 26, 2012
  • Like
  • 0

Is it possible to hide the 'Task' section altogether on LeadConvert.jsp page? I guess building a VisualForce page is the answer, but I would really appreciate if somebody could point me to sample code that does something similar. I want to retain most of the functionality on that page and just customize the layout a bit.

 

Thanks much! 

  • January 10, 2012
  • Like
  • 0

I have been trying to upload a file to the 'Content' area using API (from my Java program) -- but it is ending up in the Personal workspace instead of where I want it to go (another workspace I have created for this purpose). No matter what I try, it appears to have no effect! So I am wondering if it is really possible to publish to a workspace using API? If it is, could someone please tell me what I am doing wrong (obviously, I am a newbie -- so please help!)?

 

Thanks!

 

Here is my code snippet:

 

 

  ContentVersion cv = new ContentVersion();

  File file = new File("C:/tests/test.txt");

  byte[] myFileByteArray = null;

 

  ContentWorkspaceDoc wsDoc = new ContentWorkspaceDoc();

  ContentWorkspace ws = null;

 

  try{

  QueryResult qr = binding.query("SELECT id from ContentWorkspace WHERE name = 'Email Attachments' limit 1");

  SObject[] records = qr.getRecords();

 

  if (qr.getSize() > 0){

  System.out.println("Workspace found");

  ws = (ContentWorkspace) records[0];

  }

 

  myFileByteArray = getBytesFromFile(file);

 

  cv.setVersionData(myFileByteArray);

         cv.setTitle("Attachment via API");

  cv.setPathOnClient(file.getPath());

  

  wsDoc.setContentWorkspaceId(ws.getId());

        System.out.println("Workspace set");

 

          cv.setContentDocumentId(wsDoc.getContentDocumentId ());

       

 

 

  SaveResult sr = binding.create(new com.sforce.soap.enterprise.sobject.SObject[] {cv})[0];

  if (sr.isSuccess()) {

         System.out.println("Successfully added attachment.");

        System.out.println("Status = " + cv.getPublishStatus());

    } else {

        System.out.println("Error adding attachment: " +sr.getErrors(0).getMessage());

    }

 

 }catch (Exception e){

  e.printStackTrace();

}

 

 

I posted this under "General Development" 3 days ago and got no response. So I am trying my luck here now. Thanks for any help!

  • July 05, 2010
  • Like
  • 0

I have been trying to upload a file to the 'Content' area using API (from my Java program) -- but it is ending up in the Personal workspace instead of where I want it to go (another workspace I have created for this purpose). No matter what I try, it appears to have no effect! So I am wondering if it is really possible to publish to a workspace using API? If it is, could someone please tell me what I am doing wrong (obviously, I am a newbie -- so please help!)?

 

Thanks!

 

Here is my code snippet:

 

 

  ContentVersion cv = new ContentVersion();

  File file = new File("C:/tests/test.txt");

  byte[] myFileByteArray = null;

 

  ContentWorkspaceDoc wsDoc = new ContentWorkspaceDoc();

  ContentWorkspace ws = null;

 

  try{

  QueryResult qr = binding.query("SELECT id from ContentWorkspace WHERE name = 'Email Attachments' limit 1");

  SObject[] records = qr.getRecords();

 

  if (qr.getSize() > 0){

  System.out.println("Workspace found");

  ws = (ContentWorkspace) records[0];

  }

 

  myFileByteArray = getBytesFromFile(file);

 

  cv.setVersionData(myFileByteArray);

         cv.setTitle("Attachment via API");

  cv.setPathOnClient(file.getPath());

 

  wsDoc.setContentWorkspaceId(ws.getId());

        System.out.println("Workspace set");

 

          cv.setContentDocumentId(wsDoc.getContentDocumentId());

       

 

 

  SaveResult sr = binding.create(new com.sforce.soap.enterprise.sobject.SObject[] {cv})[0];

  if (sr.isSuccess()) {

         System.out.println("Successfully added attachment.");

        System.out.println("Status = " + cv.getPublishStatus());

    } else {

        System.out.println("Error adding attachment: " +sr.getErrors(0).getMessage());

    }

 

 }catch (Exception e){

  e.printStackTrace();

}

 

  • July 02, 2010
  • Like
  • 0
I have to elements united with a lookup relation: bMerchants and Products.
If you insert one Merchant two Products will be create, I write a trigger but it throw me this error:

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger InsertProducts caused an unexpected exception, contact your administrator: InsertProducts: execution of AfterInsert caused by: System.StringException: Invalid id: 24: Trigger.InsertProducts: line 29, column 1


This is the code of the Trigger:
 
trigger InsertProducts on Merchant__c (after insert) {

  List<Product__c> products= new List<Product__c>();

  for(Merchant__c m: Trigger.new)
      {
        Product__c pproducts = new Product__c();
        pproducts.Merchant__c = String.valueOf(m.Name);
        products.add(pproducts);
      }
    
  insert products;

 }

I made everything I don't know what to do, please if any body could help me I would appreciate.

Thanks and Regards.
I have a class where I am using exception handling, but my test class is not covering the exception block.

try {
       
              dbAccountUpdateResult = Database.update(mapAccount.values());
              dbContactUpdateResult = Database.update(mapContact.values());
        }
     catch (DMLException e)
      {
        UTIL_LoggingService.logDmlResults(dbAccountUpdateResult,null, null , null, CLASSNAME, METHODNAME, null);
        UTIL_LoggingService.logDmlResults(dbContactUpdateResult,null, null , null, CLASSNAME, METHODNAME, null);
      }


Here "UTIL_LoggingService" is my class which is used for exception handling and "logDmlResults" is my method name.
Hi All,
I created a trigger, so that when a new event is created in Public Calendar a new CalendarEV record will be created automatically. I got error message after running test class that missing required fields, so no code coverage at all. I noticed that both Start and End fields in Event object are required Date/Time fields, so I wonder how to create Date/Time in test class for these two fields so that an event can be created and fire the trigger. Please help.

Error message: System.DmLException: insert failed. First exception on row 0; First error, Required field missing
Stack Trace: Class.CalendarEVTest.insertNewCalendarEV: Line11, colum 1

trigger CalendarEV on Event (after insert) {
List<Event> Events = new List<Event>();
   for (Event e : Trigger.new) {
           if (e.Subject != null ) {
               CalendarEV__c C = new CalendarEV__c();
               c.Name = e.Subject;
               c.Start__c = e.StartDateTime;
               c.End__c = e.EndDateTime;
               c.Location__c = e.Location;
               c.Description__c = e.Description;
                    
              insert C;
        }
    }
   }


@isTest
public class CalendarEVTest
{
    static testMethod void insertNewCalendarEV()
    {
        Test.StartTest();
        Event e = new Event();
        e.Subject = 'Test Event';
        e.Location = 'Test Location';
        e.Description = 'Test Description'; 
        insert e;
        Test.StopTest();
        System.assertEquals ('Test Event', e.Subject);
    }
}
Hi All,

   How to use datepicker on visualforcepage ?
   I tried different codes avialble on internet but it is either not showing calendar else gives error while saving page itself i.e.  "Error: Component <apex:input> in '/apex/samplePage' requires HTML docType version 5.0 or higher in samplePage at line 16 column 82"
  I want to run it on my current settings.

Can anyone please help me ?

Tried code : 
1) public Date datename { get; set; }

    <apex:input label="datePicker" value="{! datename }" type="auto"/>

2) public String datename { get; set; }

    <apex:form>   
    Date: <apex:inputText value="{!datename}" size="10" id="demo"    onfocus="DatePicker.pickDate(false, this , false);" />   
   </apex:form>

Thanks,
Abhishek

Can anyone help with a sample code that can autopopulate a lookup field from a text field on the same object (lead) upon creation

Both the text field and the lookup field are on the lead object. While creating a new lead, we have the value of the text field written from an external source and we want to write that same value into the lookup field.

thank you
Hi,

I am looking to disable couple of fields when I launch my Visual Force Page from a Custom Button, can I get som help in terms of a sample code ?  I know this is basic but am new to Apex and Visual Force. Appreciate the help

Thanks
SC
Hi Folks,
      Iam trying to simplify my validation rule but i get error. My VR restricts users from role from chaning ownerid for subset of users, since all my users first name is "TBD" i want to simpify the rule by adding owner.firstname, here is my rule

AND(
     OR($UserRole.Id  = "00E30000000vEST",
        $UserRole.Id  = "00E40000001CZB5"),
        ISCHANGED(OwnerId),
        PRIORVALUE(OwnerId) <> "00540000000zpgS",
        PRIORVALUE(OwnerId) <> "00540000000oWNX",
        PRIORVALUE(OwnerId) <> "00540000000lkIN",
        PRIORVALUE(OwnerId) <> "00540000001SyUq",
        PRIORVALUE(OwnerId) <> "00540000001UnYg",
        PRIORVALUE(OwnerId) <> "00540000002FltR",
        PRIORVALUE(OwnerId) <> "00540000002nKbr",
        PRIORVALUE(OwnerId) <> "00540000002JAiR",
        PRIORVALUE(OwnerId) <> "00540000002IeDq",
        PRIORVALUE(OwnerId) <> "00540000002nU49",
        PRIORVALUE(OwnerId) <> "00540000002nU4Y",
        PRIORVALUE(OwnerId) <> "00540000002nU4T"
)

I want to use PRIORVALUE(Owner.FirstName <> "TBD") but i get this error "Incorrect argument type for function 'PRIORVALUE()'."

Any help is appreciated.
Can someone help me figure out what's wrong with this trigger? I'm writing it to create lookup rollup-summary esque fields on the parent object, Invoice__c, from the child Line_Item__c. I get this error though upon updating a record:

"Line_Item_Invoice_RollupTrigger: execution of AfterUpdate
caused by: System.NullPointerException: Argument cannot be null.
Trigger.Line_Item_Invoice_RollupTrigger: line 55, column 1"

Here's the trigger:
trigger Line_Item_Invoice_RollupTrigger on Line_Item__c (after update, after insert, after delete) {
     Map<Id, Double> LineItemTotal = new Map<Id, Double>();
     Map<Id, Double> LineItemTotalAdjusted = new Map<Id, Double>();
     Map<Id, Double> NumberofLineItems = new Map<Id, Double>();
     List<Invoice__c> invoicesToUpdate = new List<Invoice__c>();
     List<Line_Item__c> itemsForInvoice;
     List<Line_Item__c> items;
     if (trigger.isDelete) {
         items = trigger.old;
     }
     else {
         items = trigger.new;
    }
    // Go through all line items that the trigger is acting on.
    Set<ID> setInvoiceId = new Set<ID>();
    for (Line_Item__c triggerItem: items) {       
        
            // Get the invoice's ID for the line item and then
            // ensure its ID exists in the line item / line item adjusted totals
            // maps and their totals default to $0.00.        
        if (!LineItemTotal.containsKey(triggerItem.Invoice__c)) {
            LineItemTotal.put(triggerItem.Invoice__c, 0.0);
        }
        if (!LineItemTotalAdjusted.containsKey(triggerItem.Invoice__c)) {
            LineItemTotalAdjusted.put(triggerItem.Invoice__c, 0.0);
        }
        if (!NumberofLineItems.containsKey(triggerItem.Invoice__c)) {
            NumberofLineItems.put(triggerItem.Invoice__c, 0);
        }
        
        if(triggerItem.Invoice__c != NULL)
            setInvoiceId.add(triggerItem.Invoice__c);
    }
    
    // Sum the total cost of the line items
    // for the current invoice (see invoice above).
    //
    // 1. Get all of the line items for the invoice.
    // 2. For each line item update the mapping for the invoice 
    //    to be (previous total + total cost).    
    List<Line_Item__c> lstInvLineItem_LineItemTotal = new List<Line_Item__c>();
    List<Line_Item__c> lstInvLineItem_LineItemTotalAdjusted = new List<Line_Item__c>();
    List<Line_Item__c> lstInvLineItem_NumberofLineItems = new List<Line_Item__c> ();
    if(setInvoiceId.size()>0){
        lstInvLineItem_LineItemTotal = [SELECT Id, Cost__c, Invoice__c FROM Line_Item__c
                WHERE Invoice__c IN :setInvoiceId];
        lstInvLineItem_LineItemTotalAdjusted = [SELECT Id, Total_Cost_incl_Adjustment__c, Invoice__c FROM Line_Item__c
                WHERE Invoice__c IN :setInvoiceId];
        lstInvLineItem_NumberofLineItems = [SELECT Id, One__c, Invoice__c FROM Line_Item__c
                WHERE Invoice__c IN :setInvoiceId];
    }
    // If the list has records, add those IDs and totals to the map.
    if(lstInvLineItem_LineItemTotal.size()>0){
        for(Line_Item__c item:lstInvLineItem_LineItemTotal){    
            LineItemTotal.put(item.Invoice__c, 
                LineItemTotal.get(item.Invoice__c) + item.Cost__c); 
        }
    }
    // If the list has records, add those IDs and totals to the map.    
    if(lstInvLineItem_LineItemTotalAdjusted.size()>0){
        for(Line_Item__c item:lstInvLineItem_LineItemTotalAdjusted){    
            LineItemTotalAdjusted.put(item.Invoice__c, 
                LineItemTotalAdjusted.get(item.Invoice__c) + item.Total_Cost_incl_Adjustment__c); 
        }
    }
    
    // If the list has records, add those IDs and totals to the map.
    if(lstInvLineItem_NumberofLineItems.size()>0) {
        for(Line_Item__c item:lstInvLineItem_NumberofLineItems) {
            NumberofLineItems.put(item.Invoice__c,
                NumberofLineItems.get(item.Invoice__c) + item.One__c);
        }
    }
    
    List<Id> invoices = new List<Id>();
    for (Id previous : LineItemTotal.keyset()) {
        invoices.add(previous);
    }
    for (Id current : LineItemTotal.keyset()) {
        if (!LineItemTotal.containsKey(current)) {
            invoices.add(current);
        }
    }
    // Get a list of all invoices where its Id is in the invoices map.
    List<Invoice__c> lstInvoices = new List<Invoice__c>();
    if(invoices.size()>0){
        lstInvoices = [SELECT Id, Line_Item_Total__c, Line_Item_Total_Adjusted__c, Number_of_Line_Items__c
             FROM Invoice__c WHERE Id IN :invoices];
    }
    // Update the map with line item and line item adjusted totals.
    if(lstInvoices.size()>0){
        for(Invoice__c invoice:lstInvoices){
            if (LineItemTotal.containsKey(invoice.id)) {
                invoice.Line_Item_Total__c = LineItemTotal.get(invoice.id);
            }
            
            if (LineItemTotalAdjusted.containsKey(invoice.id)) {
                invoice.Line_Item_Total_Adjusted__c = LineItemTotalAdjusted.get(invoice.id);
            }
            
            if (NumberofLineItems.containsKey(invoice.id)) {
                invoice.Number_of_Line_Items__c = NumberofLineItems.get(invoice.id);
            }
            
            invoicesToUpdate.add(invoice);
        }
    }
    update invoicesToUpdate;
}


Hi guys,

We have a number field on the opportunity page that counts the number of products that the opportunity has and I'm trying to figure out how to run a workflow rule only when that number field increases in value.

For example, if the opportunity goes from having 1 product to 2 products or from 3 products to 5 products, it should run.

Is there a way to do this?

Thanks!
-Marc


I have a bit of code that checks to see if an account already exists based on a domain and reassigns the incoming lead based on Account owner. I need to update the trigger to leave a particular Account Owner Role out of the process but I can't figure out where to put the code.  Any help would be appreciated, thanks!  Here's the owner role id: 00E50000000t0Bf and here's the trigger:

trigger UpdateLeadOwner on Lead (before insert) {
    for (Lead leadInLoop : Trigger.new) {
   
if (leadInLoop.LeadSource != 'Contact Us' && leadInLoop.LeadSource != 'Reprint') {
    // Retrieve owner from Account record based on email domain name
    list <Account> acct = [Select OwnerId from Account WHERE Domain_1__c = :leadInLoop.Domain__c Limit 2];
        if (acct.size() == 1) {

    //the next line is for debugging, to check that you are getting a result back from the query
    System.debug('account owner id is: ' + acct[0].OwnerId);
    leadInLoop.OwnerId=acct[0].OwnerId;
        }
    }
}
}
Hello,

I have created a trigger that updates a hidden field on an Account record that was needed in order to track changes on a seperate field that is a formula field. When the field value changes, the trigger runs and captures the previous value in the Account History. Below is my trigger code (in Sandbox) that works perfect:


trigger BusinessRatingChange on Account (before insert, before update)
{
    for(Account a:Trigger.new)
    {
        if(system.trigger.OldMap.get(a.Id).Business_Rating__c != system.trigger.NewMap.get(a.Id).Business_Rating__c)
        {
            a.Business_Rating_History__c = a.Business_Rating__c;
            }
            }
            }

However, when I attempt to create a NEW account, I get the below error that looks like is due to the "BeforeInsert" action on the trigger:


Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger BusinessRatingChange caused an unexpected exception, contact your administrator: BusinessRatingChange: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.BusinessRatingChange: line 5, column 1


Does anyone have any insight as to how I can remedy this? Thanks so much in advance for your assistance!!!

Eric