• iSqFt_AD
  • NEWBIE
  • 5 Points
  • Member since 2011

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 54
    Replies

Here is my scheduled class and following it is the error I have gotten. This has been running for about a week now and I have received this error on two occasions. Basically it looks at a formula field and reassigns Accounts to the Owner's manager if the field states "YES". Can anyone provide a fix? Thank you!

 

global class AccountOwnerReassignCronJob implements Schedulable{
    global void execute(SchedulableContext SC) {
     List <Account> acc = [Select OwnerId, Owner.ManagerId From Account Where Up_for_Reassignment__c ='YES'];         

    for(Account a: acc){
        if(a.Owner.ManagerId != null)
            a.OwnerId = a.Owner.ManagerId;
    }
    update(acc);
} 
}

 

ERROR:

 

Apex script unhandled exception by user/organization: 00560000001L3AU/00D6000000077GT

 

Scheduled job 'Reassign Stagnant Accounts' threw unhandled exception.

 

caused by: System.LimitException: Too many DML rows: 10001

 

Class.AccountOwnerReassignCronJob.execute: line 9, column 1

I found this trigger and made a couple changes to it in attempts to get a simple roll up count of activities in the Activity History of Accounts. 

 

trigger Activity_Count_2 on Task (after insert, after update, after delete, after undelete) {
List<Account> uplist=new List<Account>();
List<Account> lelist=[select id,Activity_Count_2__c from Account];
List<AggregateResult> st=new List<AggregateResult>();
st=[select count(Id),whoid from task where id=:Trigger.new and status='Completed' group by whoid];
for(Integer i=0;i<st.size();i++)
{
for(Account a:lelist)
{
if(a.id==st[i].get('whoid'))
{
a.Activity_Count_2__c=(Integer)st[i].get('expr0')+a.Activity_Count_2__c;
uplist.add(a);
}
}
}
update uplist;
}

 

Unfortunately, when I went to log an activity at the Account I received this error:

 

"Apex trigger Activity_Count_2 caused an unexpected exception, contact your administrator: Activity_Count_2: System.LimitException: Too many query rows: 50001"

 

 

What am I missing here?

I have pieced together  a trigger in order to clone a Closed Won opportunity. The one part I do not understand is that I want the new Opportunity's name to be in the format of "Opp Name - Renewal - Year" with Year being the year after the current one. So if I Closed Won an Opportunity today (2012), then the cloned opportunity name would become "Opportunity Name - Renewal - 2013".

 

I have the Name - Renewal part but what do I need to add after it to get the dynamic year?

 

 newOpp.Name=o.Name + ' - Renewal';

 


Thank you!

What is it about line 27 that would give the user creating the Contact this error, as well as email me the error?

 

Error: 


Apex script unhandled trigger exception by user/organization: 00560000000rvkR/00D6000000077GT

 

contactDuplicatePreventer: execution of BeforeUpdate

 

caused by: System.NullPointerException: Attempt to de-reference a null object

 

Trigger.contactDuplicatePreventer: line 27, column 1

 

Trigger:

 

trigger contactDuplicatePreventer on Contact (before insert, before update) {

    Map<String, Contact> contactMap = new Map<String, Contact>();

    for (Contact contact : System.Trigger.new) {
    
        // Make sure we don't treat an email address that
        // isn't changing during an update as a duplicate.
        if ((contact.Email != null) && (System.Trigger.isInsert || (contact.Email != System.Trigger.oldMap.get(contact.Id).Email))) {
    
            // Make sure another new contact isn't also a duplicate
            if (contactMap.containsKey(contact.Email)) {
                contact.Email.addError('Another new Contact has the same email address.');
            } else {
                contactMap.put(contact.Email, contact);
            }
        }
    }
    
    // Using a single database query, find all the contacts in
    // the database that have the same email address as any
    // of the contacts being inserted or updated.
    for (Contact contact : [SELECT Email FROM Contact WHERE Email IN :contactMap.KeySet()]) {
       if(contact.email != null){
          Contact newContact = contactMap.get(contact.Email);
          System.debug('new contact = ' + newContact);
          System.debug('email = ' + newContact.Email);
        newContact.Email.addError('A Contact with this email address already exists.');}
        }
}

 

Thanks!

 

 

This class already exists and is functioning in our Production instance. I made one change to it and am attempting to deploy it into Production and I get an error.

 

Test Class:

/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class testTriggerSet {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
        
        //test of leadDuplicatePreventer
        Lead l = new Lead();
        l.LastName = 'tester smith';
        l.Company = 'tester company';
        l.Email = 'tester@tester.com';
        l.Phone = '(513) 888-8888';
        l.Status = 'Open';
        l.LeadSource = 'Kiosk';
        insert l;
            
        //test of 
        
        Task t = new task();
        t.Subject = 'test task';
        t.ActivityDate = Date.today();
        t.Type = 'Phone Conversation';
        t.Focus__c = 'Sales Activity';
        t.WhatId = '001P000000Wfluj';
        insert t;
        
        Account a = new account();
        a.Name = 'tester account';
        a.Phone = '(513) 333-3321';
        insert a;
        
        Opportunity o = new Opportunity();
        o.Name = 'tester opp';
        o.StageName = 'Proposal Made';
        o.CloseDate = Date.today();
        o.Amount = 444.23;
        o.Contract_Length_in_Months__c = 12;
        insert o;
        
        o.StageName = 'Proposal Made';
        update o;
        
        Contact c = new Contact();
        c.LastName = 'tester';
        c.Email = 'joe@sss.com';
        c.Phone = '(513) 332-3321';
        insert c;
        
        
    }
}

 

Update Made:

 

o.Contract_Length_in_Months__c = 12;

 

Error when attempting to Validate:

 

testTriggerSet.myUnitTest()Class311

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []", Failure Stack Trace: "Class.testTriggerSet.myUnitTest: line 31, column 1"

I am looking for a way to report on Last Activity against a record but not have it include Event Dates which can be in the future. We want to rely on Last Activity Date to run some workflows and this will not be reliable if an Event is scheduled and the Last Activity Date is in the future because of it.


Thanks.

Disclaimer - I have no development experiement. I have been using the canned trigger that is floating around the internet that reassigns Contacts and Opportunities to the new owner when an Account Owner is changed. I have been getting feedback from representatives in my organization that want the transfers to be for the Contacts only. I attempted to pull out the pieces of the code that involve the Opportunity but I get the following error:

 

Error: Compile Error: unexpected token: { at line 17 column 75

 

(Note I have put asteriks around the bracket the error is referring to for reference:

trigger reassignRelatedContacts on Account (after update) {
   try {
      Set<Id> accountIds = new Set<Id>(); //set for holding the Ids of all Accounts that have been assigned to new Owners
      Map<Id, String> oldOwnerIds = new Map<Id, String>(); //map for holding the old account ownerId
      Map<Id, String> newOwnerIds = new Map<Id, String>(); //map for holding the new account ownerId
      Contact[] contactUpdates = new Contact[0]; //Contact sObject to hold OwnerId updates
      
      for (Account a : Trigger.new) { //for all records
         if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId) {
            oldOwnerIds.put(a.Id, Trigger.oldMap.get(a.Id).OwnerId); //put the old OwnerId value in a map
            newOwnerIds.put(a.Id, a.OwnerId); //put the new OwnerId value in a map
            accountIds.add(a.Id); //add the Account Id to the set
         }
      }
      
      if (!accountIds.isEmpty()) { //if the accountIds Set is not empty
         for (Account act : [SELECT Id, (SELECT Id, OwnerId FROM Contacts) **{** //SOQL to get Contacts for updated Accounts
            String newOwnerId = newOwnerIds.get(act.Id); //get the new OwnerId value for the account
            String oldOwnerId = oldOwnerIds.get(act.Id); //get the old OwnerId value for the account
            for (Contact c : act.Contacts) { //for all contacts
               if (c.OwnerId == oldOwnerId) { //if the contact is assigned to the old account Owner
                  Contact updatedContact = new Contact(Id = c.Id, OwnerId = newOwnerId); //create a new Contact sObject
                  contactUpdates.add(updatedContact); //add the contact to our List of updates
               }
          }
         update contactUpdates; //update the Contacts
      }
   } catch(Exception e) { //catch errors
      System.Debug('reassignRelatedContacts failure: '+e.getMessage()); //write error to the debug log
   }
}

 

The bracket in question has an end bracket, which is what is confusing. Where am I making a mistake?

Context: Our sales users have a finite amount of time to work an Account before it can be pulled from their ownership and reassigned. I currently have a formula field that identifies if an Account can be reassigned by populating "YES" or "NO".

 

Desired Outcome: Run a trigger at midnight everyday that takes all Accounts where the custom forumla field Up_for_Reassignment__c says "YES" and reassigns them to the user's manager.

 

I know this involves a fairly simple trigger, but then it also requires an Apex Class that uses the Scheduler. I am not well versed in Apex Coding. Does someone have a standard Apex class built with the scheduler in it that I can insert my trigger into?

 

Thanks,

Hello,

 

I am working through a way to track GAAP revenue on my opportunities. We are a subscription based company that has some products where revenue is recognized as a one-time upfront fee (service fees, setup fees, etc) and the rest of our products are subscription based where the revenue is recognized monthly. Here is my thought process in steps:

 

1. Products have a custom field that identify them as a one-time fee or a reoccuring subscription fee. 

2. There is a rollup summary field on the opportunity that sums one-time products and a second rollup summary that sums all subscription products. 

3. A custom formula field divides the subscription revenue by the contract terms, breaking it down into monthly revenue.

 

So now, at the Opportunity level, I have my Amount, my Upfront Revenue, and my Monthly Subscription Revenue.

 

My question to you is, how can I build a formula that can take the Monthly Subscription Revenue and know (based off a start and end date) how much of it should be recognized in each year? I believe there is a way to have a formula calculate how many months are left in the year, and take the Monthly Subscription Revenue and multiply the two to get the GAAP revenue for the current year.

 

Anyone?

Has anyone figured out a way on the Opportunity or Opportunity Product to build a formula field to be able to track GAAP revenue against that product?

 

I have been tasked with finding a way to take an opportunity that has a one-time setup fee as a product (revenue forcasted immediately) and a monthly subscription product (revenue forecasted based on Total Price divided by number of months in contract length) and then reporting on forecasted revenue based on GAAP analysis. So for example if an Opportunity has a setup fee product for $3,000 and a 12 month subscription product that starts on April 1st for $1,000 a month for a total Amount of $15,000, the GAAP revenue of this sale is forecasted as $4,000 in April and $8,000 across May-December for a total GAAP revenue of $12,000, since the last three months of the subscription will be recognized in 2013.

 

Anyone know of a way to do this effectively in Salesforce without a financial app or heavy reliance on exporting to Excel?

trigger contactDuplicatePreventer on Contact (before insert, before update) {

    Map<String, Contact> contactMap = new Map<String, Contact>();

    for (Contact contact : System.Trigger.new) {
    
        // Make sure we don't treat an email address that
        // isn't changing during an update as a duplicate.
        if ((contact.Email != null) && (System.Trigger.isInsert || (contact.Email != System.Trigger.oldMap.get(contact.Id).Email))) {
    
            // Make sure another new contact isn't also a duplicate
            if (contactMap.containsKey(contact.Email)) {
                contact.Email.addError('Another new Contact has the same email address.');
            } else {
                contactMap.put(contact.Email, contact);
            }
        }
    }
    
    // Using a single database query, find all the contacts in
    // the database that have the same email address as any
    // of the contacts being inserted or updated.
for (Contact contact : [SELECT Email FROM Contact WHERE Email IN :contactMap.KeySet()]) { if(contact.email != null){
        Contact newContact = contactMap.get(contact.Email);
        newContact.Email.addError('A Contact with this email address already exists.'); }
    }
}

 

I found the above trigger online and have implemented it into our production instance of SFDC. It appears to work except I occasionally get emails with the following error:

 

"

Subject: Developer script exception from iSqFt : contactDuplicatePreventer : contactDuplicatePreventer: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.contactDuplicatePreventer: line 25, column 9

 

Apex script unhandled trigger exception by user/organization: 005600000019X1a/00D6000000077GT

 

contactDuplicatePreventer: execution of BeforeUpdate

 

caused by: System.NullPointerException: Attempt to de-reference a null object

 

Trigger.contactDuplicatePreventer: line 25, column 9"

 

Can anyone tell me what I need to do to fix the trigger to prevent this? The user is also seeing a similar error on screen which is quite confusing to them.


Thank you.

Disclaimer: I am not a developer. I had someone assist me with the code for this trigger. It works great except for it fires every time there is an edit and I need it to only fire the first time the Stage is set to Closed Won.

 

trigger Original_Owner_Role on Opportunity (before insert, before update){

Set<Id> uIds = new set<Id>();
for(Opportunity o : Trigger.New){
uIds.add(o.OwnerId);
}
Map<Id,User> userOppty = new Map<Id,User>([Select Id, UserRole.Name from User where Id IN :uIDs]);
for(Opportunity o : Trigger.New){
if(o.StageName == 'Closed Won'){
o.Original_Owner_Role__c = userOppty.get(o.OwnerId).UserRole.Name;
}
}
}

 

I want to create a formula field that will pull out the area code from an Accounts phone number. For some reason I am hitting a road block on this.


Thanks in advance.

I am not a developer but I know this should be a fairly simply trigger to write. Here is the expected result:

 

If the custom formula text field Up_for_Reassignment__c is "YES", the Account should be reassigned to the Account Owner's manager (via the Manager field on the User page).

 

I need this to happen automatically at the moment the Up_for_Reassignment__c field changes from NO to YES. 

 

Anyone?


Thanks!

I have a custom Account field called Closed Won Opps. It counts the number of Closed Won Opportunities on the Account. I have a custom date field on the Account as well that I want to populate with TODAY() when the Closed Won Opps count goes up.

 

It wont let me use a formula like ISCHANGED(Closed_Won_Opps_c) so I am asking for your help.

 

Thanks!

Does anyone have a snippet of code that might work similar to a workflow rule, but that when the Opportunity Stage becomes Closed Won, the Opportunity Owner's Role is populated into a read-only text field?

 

Thank you,

I thought I could figure this out but need some guidance. I am trying to build a workflow rule that sends an email alert when an Opportunity's Stage changes from Closed Won to Closed Lost. 

 

Anybody (Stevemo or Shashikant)?


Thanks in advance.

I know that several people have this code that changes the Send notification email box on objects like Opportunities to True rather than False. It looks like Salesforce as incorporated it into Cases but not anything else.


Can anyone supply this code?

 

Thank you,

Has anyone come up with a way to create an Unread by Owner field on Accounts, Contacts, or Opportunities? Accounts is our main focus but I figured the logic would be the same for all three objects.


Thanks,

Here is our scenario: We are subscription based and when a Lead requests a trial, there is a date field that populates the date they filled out the web-to-lead form. When the lead is converted and a new Account is created, that date field populates a date field on the Account. The issue is that when a Lead is converted and attached to an existing Account, the date field does not update the Account's date field. Ideally we want the Account's Trial Date field to be populated with the most recent trial request date from any lead converted into it. Premier Support said it is beyond their scope.

 

Is this possible to do this? Does anyone have code that could be tweaked to work by someone here that has enough code experience to make the modifications?

 

Am I just having a pipedream?

 

Thanks!

Here is my scheduled class and following it is the error I have gotten. This has been running for about a week now and I have received this error on two occasions. Basically it looks at a formula field and reassigns Accounts to the Owner's manager if the field states "YES". Can anyone provide a fix? Thank you!

 

global class AccountOwnerReassignCronJob implements Schedulable{
    global void execute(SchedulableContext SC) {
     List <Account> acc = [Select OwnerId, Owner.ManagerId From Account Where Up_for_Reassignment__c ='YES'];         

    for(Account a: acc){
        if(a.Owner.ManagerId != null)
            a.OwnerId = a.Owner.ManagerId;
    }
    update(acc);
} 
}

 

ERROR:

 

Apex script unhandled exception by user/organization: 00560000001L3AU/00D6000000077GT

 

Scheduled job 'Reassign Stagnant Accounts' threw unhandled exception.

 

caused by: System.LimitException: Too many DML rows: 10001

 

Class.AccountOwnerReassignCronJob.execute: line 9, column 1

I found this trigger and made a couple changes to it in attempts to get a simple roll up count of activities in the Activity History of Accounts. 

 

trigger Activity_Count_2 on Task (after insert, after update, after delete, after undelete) {
List<Account> uplist=new List<Account>();
List<Account> lelist=[select id,Activity_Count_2__c from Account];
List<AggregateResult> st=new List<AggregateResult>();
st=[select count(Id),whoid from task where id=:Trigger.new and status='Completed' group by whoid];
for(Integer i=0;i<st.size();i++)
{
for(Account a:lelist)
{
if(a.id==st[i].get('whoid'))
{
a.Activity_Count_2__c=(Integer)st[i].get('expr0')+a.Activity_Count_2__c;
uplist.add(a);
}
}
}
update uplist;
}

 

Unfortunately, when I went to log an activity at the Account I received this error:

 

"Apex trigger Activity_Count_2 caused an unexpected exception, contact your administrator: Activity_Count_2: System.LimitException: Too many query rows: 50001"

 

 

What am I missing here?

I have pieced together  a trigger in order to clone a Closed Won opportunity. The one part I do not understand is that I want the new Opportunity's name to be in the format of "Opp Name - Renewal - Year" with Year being the year after the current one. So if I Closed Won an Opportunity today (2012), then the cloned opportunity name would become "Opportunity Name - Renewal - 2013".

 

I have the Name - Renewal part but what do I need to add after it to get the dynamic year?

 

 newOpp.Name=o.Name + ' - Renewal';

 


Thank you!

What is it about line 27 that would give the user creating the Contact this error, as well as email me the error?

 

Error: 


Apex script unhandled trigger exception by user/organization: 00560000000rvkR/00D6000000077GT

 

contactDuplicatePreventer: execution of BeforeUpdate

 

caused by: System.NullPointerException: Attempt to de-reference a null object

 

Trigger.contactDuplicatePreventer: line 27, column 1

 

Trigger:

 

trigger contactDuplicatePreventer on Contact (before insert, before update) {

    Map<String, Contact> contactMap = new Map<String, Contact>();

    for (Contact contact : System.Trigger.new) {
    
        // Make sure we don't treat an email address that
        // isn't changing during an update as a duplicate.
        if ((contact.Email != null) && (System.Trigger.isInsert || (contact.Email != System.Trigger.oldMap.get(contact.Id).Email))) {
    
            // Make sure another new contact isn't also a duplicate
            if (contactMap.containsKey(contact.Email)) {
                contact.Email.addError('Another new Contact has the same email address.');
            } else {
                contactMap.put(contact.Email, contact);
            }
        }
    }
    
    // Using a single database query, find all the contacts in
    // the database that have the same email address as any
    // of the contacts being inserted or updated.
    for (Contact contact : [SELECT Email FROM Contact WHERE Email IN :contactMap.KeySet()]) {
       if(contact.email != null){
          Contact newContact = contactMap.get(contact.Email);
          System.debug('new contact = ' + newContact);
          System.debug('email = ' + newContact.Email);
        newContact.Email.addError('A Contact with this email address already exists.');}
        }
}

 

Thanks!

 

 

I am looking for a way to report on Last Activity against a record but not have it include Event Dates which can be in the future. We want to rely on Last Activity Date to run some workflows and this will not be reliable if an Event is scheduled and the Last Activity Date is in the future because of it.


Thanks.

Working on a trigger that creates a new opportunity when a particular type of opportunity is Closed Won.  I can't clone it because a number of things change, but for creating the new opportunity I need to be able to get at the values of not only the opportunity but the product line items.

 

There are two things I'm not sure of:

 

1) Are the product line items included via the Opportunity when I create a map of Opportunities?  If so, how do I reference them later when extracting certain values to apply to the new Opportunity?

 

2) How do I create the line items for the new opportunity?

 

Here's the code I have so far excluding the items referenced above:

 

 

trigger createRepSitesRecurringOpportunity on Opportunity (after insert, after update) { RecordType rt = [SELECT Id FROM RecordType WHERE Name = 'Rep Sites' AND SobjectType = 'Opportunity']; // Create map for Contact ID's & Opportunities, that match our RecordType criteria Map<Id,Opportunity> mapRepSitesOpportunities = new Map<Id, Opportunity>(); // Loop through the Opportunities being inserted and see if there are any for the Rep Sites record type and "Apply Recurring Billing = true". for (Opportunity o : trigger.new) { If ((o.RecordTypeId == rt.Id) && (o.Apply_Recurring_Billing__c == true)){ mapRepSitesOpportunities.put(o.Contact__c, o); } } system.debug('mapRepSitesOpportunities.size at Line 15 = ' + mapRepSitesOpportunities.size()); If (mapRepSitesOpportunities.size() > 0) { //Check for Rep Sites = Active and remove Opportunities from the list where Rep is no longer active. List<Id> contactidsForOpptToNotCreate = new List<Id>(); for (Contact c : [Select Id, Rep_Sites__c from Contact where Id in :mapRepSitesOpportunities.keySet()]) { If (c.Rep_Sites__c <> 'Active') { mapRepSitesOpportunities.remove(c.Id); } } } system.debug('mapRepSitesOpportunities.size at Line 29 = ' + mapRepSitesOpportunities.size()); //Create Oppt with the correct Recurring product/amount and set the Close Date to First Day of the next month If (mapRepSitesOpportunities.size() > 0) { List<Opportunity> opptsToInsert = new List<Opportunity>(); Opportunity newOppt = new Opportunity(); for(Opportunity oppt : [Select RecordTypeId, Name, Contact__c, AccountId, Amount From Opportunity where Id in :mapRepSitesOpportunities.values()]) { newOppt.Name = oppt.Name + ' Recurring Auto Generated'; newOppt.AccountId = oppt.AccountId; newOppt.Contact__c = oppt.Contact__c; newOppt.RecordTypeId = oppt.RecordTypeId; newOppt.CloseDate = Date.today(); //change this to first of next month newOppt.Amount = oppt.Amount; //stop mapping this once the product is created and amount set there. newOppt.StageName = 'Recurring Billing'; opptsToInsert.add(newOppt); } insert(opptsToInsert); } }

 

 Where do I go next?