• 3C
  • NEWBIE
  • 10 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 6
    Replies
We have a trigger that is meant to update account records to customer (meaning they have active assets) or location (no active assets). This is the relevant part of the associated class. In the final lines, Type is supposed to be updated to Location only if there are no active assets. However, in testing it is updating to Location whenever we deactivate any asset on an account, even if there are other assets that are still active. What could be causing this?
 
List<Account> accountsToUpdate = new List<Account>();
        for(String accountID: mapAccountToAssets.keySet())
        {
            Account loc = new Account(ID = accountID);
            Boolean hasOnMaintenanceAssets = false;
            Boolean isLocation = false;
            for(Customer_Asset__c ca: mapAccountToAssets.get(accountID))
            {
                if(ca.Account__r.RecordTypeID == AccountServices.recordTypesNameMap.get(Constants.ACCOUNT_RECORD_TYPE_FACILITY).ID)
                    isLocation = true;
                    
                if(ca.Maintenance_Status__c == Constants.STATUS_ON_SUBSCRIPTION && ca.Annual_Maintenance__c > 0)
                {
                    hasOnMaintenanceAssets = true;
                    loc.Type = 'Customer';
                    break;
                }
            }
            
            if(!hasOnMaintenanceAssets)
            {
                if(isLocation)
                    loc.Type = 'Location';
            }
            
            accountsToUpdate.add(loc);
        }
        
        update accountsToUpdate;
        
    }

 
  • March 17, 2015
  • Like
  • 0
I am trying to implement a roll-up summary of the earliest contract start date on the account object using the code outlined here (http://blog.elieperez.net/salesforce-lookup-roll-up-summary/). Below is my trigger.
 
trigger rollupContractsOnAccount on Contract (after insert,after update,after delete,after undelete) {
     
    string mysobjectParent = 'Account',      // Parent sobject API Name
           myrelationName = 'Contract__r', // Api name of the relation between parent and child (ends with __r)
           myformulaParent = 'Customer_Since__c',        // Api name of the number field that will contain the calculation
           mysobjectChild = 'Contract',  // Child sobject API Name
           myparentfield = 'Account', // Api name of the lookup field on chield object
           myfieldChild = 'Subscription_Start_Date__c';          // Api name of the child field to roll up
     
    LookupCalculation.Method method = LookupCalculation.Method.MIN; //Selected method: could be COUNT, SUM, MIN, MAX, AVG
     
    LookupCalculation calculation = new LookupCalculation(mysobjectParent, myrelationName, myformulaParent,
                                                          mysobjectChild, myparentfield, myfieldChild);
    List<sobject> objList = new List<sobject>((List<sobject>) Trigger.new);
    if(Trigger.isDelete)
        objList = Trigger.old;
    if(Trigger.isUpdate)
        objList.addAll((List<sobject>) Trigger.old);
    calculation.calculate(method, objList);
}

This gives me the error:

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger rollupContractsOnAccount caused an unexpected exception, contact your administrator: rollupContractsOnAccount: execution of AfterInsert caused by: System.SObjectException: Invalid field Account for Contract: Class.LookupCalculation.Calculate: line 25, column 1

What am I missing? The error is on "myparentfield," which is correct as Account for the Contract object.
  • January 28, 2015
  • Like
  • 0
I have the following trigger, but it's not working as intended. There are no errors in the code.. any ideas?
 
trigger createCancellationReport on Opportunity (after update) {

    List<Win_Loss_Report__c> reportstoinsert = new List<Win_Loss_Report__c>();

    for (Opportunity opp : Trigger.new) {

        // Create cancellation report only for cancellation oppys
        if (opp.StageName == 'Closed Won' & opp.Cancellation_Reason__c != null) {
            Win_Loss_Report__c cr = new Win_Loss_Report__c();
            cr.Opportunity__c   = opp.id;
            cr.Name = 'Cancellation Report';
            cr.RecordTypeID = '012J00000009NC9';
            reportstoinsert.add(cr); // bulk process
        } 
    } 
}

 
  • January 27, 2015
  • Like
  • 0
I have a Visualforce page embedded in the standard Account page layout. It is rendered depending on a boolean field at the Account level. If the boolean value is false, it does not render but still takes up the space it would if it did render. Is there any way to hide this empty space if the page doesn't render (other than collapsing the section)?

User-added image
  • September 05, 2014
  • Like
  • 0
I am getting this error for a scheduled job that sends mass emails every day.

First error: SendEmail failed. First exception on row 0; first error: LIMIT_EXCEEDED, Too many target object ids.: []

Here is the code:

global with sharing class EmailSenderBatch implements Database.Batchable<SObject>, Database.Stateful 
{
    public String query = '';
    global Set<ID> contactIDsToSendEmailTo;
    
    public EmailSenderBatch()
    {
        query = 'Select ID, Name from Account';
        contactIDsToSendEmailTo = new Set<ID>();
    }   
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, list<sObject> scope)
    {
        Set<ID> accountIDs = new Set<ID>();
        for(Account a: (List<Account>) scope)
            accountIDs.add(a.ID);
        
        Set<ID> accountIdsToSendEmailTo = new Set<ID>();
        for(Contract ctrct: [Select ID, AccountID, Subscription_Start_Date__c
                             from Contract 
                             where AccountID in: accountIDs
                             and Contract_Status__c =: 'Active'
                             and Subscription_Start_Date__c !=: null])
        {
        //send every 3 months and 9 months from subscription start date
            if(
            ((ctrct.Subscription_Start_Date__c.addMonths(3).month() == (Date.today().month()))
            || (ctrct.Subscription_Start_Date__c.addMonths(9).month() == (Date.today().month())))
            )
            {
                accountIDsToSendEmailTo.add(ctrct.AccountID);
            }
        }
        
        //if we have qualified accounts
        if(accountIDsToSendEmailTo.size() > 0)
        {
            for(Contact c: [Select ID, LastName, FirstName, Key_Contact__c
                            from Contact
                            where AccountID in: accountIdsToSendEmailTo
                            and Contact_Status__c =: Constants.STATUS_ACTIVE
                            ])
            {
                if(c.Key_Contact__c != null && c.Key_Contact__c.contains(Constants.CONTACTOBJ_PRIMARY_SUPPORT_CONTACT))
                    contactIDsToSendEmailTo.add(c.ID);
            }
        }
    }
    
    global void finish(Database.BatchableContext BC)
    {
        if(contactIDsToSendEmailTo.size() > 0)
        {
            List<ID> contactIDs = new List<ID>();
            contactIDs.addAll(contactIDsToSendEmailTo);
            Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.setSenderDisplayName('Andrew Simpson');
            mail.setTargetObjectIds(contactIDs);
            mail.setTemplateId(GenericServices.getGeneralSettingValueForKey(Constants.TEMPLATE_ID));
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
        }
    }
    
    global static void startCalculation()
    {
        EmailSenderBatch cesb = new EmailSenderBatch();
        Database.executeBatch(cesb);
    }
}

Is the error referring to the daily email limit or too many results from the query? Any help on how I could resolve the limit would be appreciated.
  • June 02, 2014
  • Like
  • 0
I'm trying to conditionally render a section if its record type is not at risk and it's not for changing an asset. It doesn't show up at all regardless of record type. Am I just organizing it wrong?

<apex:pageBlockSectionItem rendered="{!NOT(isChangeAsset) && case.RecordType.Name!='At Risk'}" >
  • May 06, 2014
  • Like
  • 0
We have a visualforce page replacing the "new" button on cases. It references a controller extension. The case will only save if the "new case" button is clicked from the account record. If it is clicked from the cases tab or another object, nothing happens. Any ideas on how to make the case record savable regardless of where its created?

public with sharing class CaseContExt
{
    public AccountModel am{get; private set;}
    public Casemodel cm {get; private set;}
    private final Account a;
    private Case c;
    private final String caseID;
    
    public CaseComment caseComment {get; set;}
    
    public Boolean isPortal{get; private set;}
    public Boolean isChangeAsset {get; private set;}
    public Boolean useDefaultAssignmentRules {get; set;}
    
    //public String entitlementAlert {get; private set;}
    public Boolean customization {get; set;}
    
    private Boolean initialChangeAssetLoad {get; set;}
    
    public CaseContExt(ApexPages.StandardController std)
    {
     
        caseID = ApexPages.currentPage().getParameters().get(CONSTANTS.QRY_STRING_CASE_ID);
        System.debug('\n\ncaseId = '+caseID+'\n\n');
        useDefaultAssignmentRules = false;
        if(caseID == null)
        {
            User u = [Select Id, Profile.UserLicense.LicenseDefinitionKey, ContactID, Contact.AccountID from User where id=: UserInfo.getUserId()];
            isPortal = u.Profile.UserLicense.LicenseDefinitionKey == Constants.CUSTOMER_PORTAL_LICENSE_KEY;
            
            this.c = (Case)std.getRecord(); 
            this.isChangeAsset = false;
            
            if(isPortal)
            {
                c.AccountID = u.Contact.AccountID;
                c.ContactID = u.ContactID;
            }
            else
            {
                c.AccountId = ApexPages.currentPage().getParameters().get(Constants.QRY_STRING_ACCOUNT_ID);
                c.ContactId = ApexPages.currentPage().getParameters().get(Constants.QRY_STRING_CONTACT_ID);
            }
               
            caseComment = new CaseComment();
            initialChangeAssetLoad = false;
        }
        else
        {
            
            this.c = (Case)std.getRecord(); 
            this.isChangeAsset = true;
            isPortal = false;
            useDefaultAssignmentRules = true;
            initialChangeAssetLoad = GenericServices.isNullOrEmpty(this.c.Customer_Asset__c)?false:true;
        }
        
        if(c.AccountID == null)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, System.label.No_Account_provided));
            return;
        }
        try
        {
            a = [Select ID, Name from Account where id =: c.AccountID];
        }
        catch(QueryException qexc)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, System.label.Invalid_Account_ID_URL_param));
            return ;
        }
        am = new AccountModel(a);
        cm = new CaseModel(c);
        if(cm.isContent)
          c.Issue_Type__c = CONSTANTS.ESCALATED_CASE_ISSUE_TYPE;
        loadData();
        
    }
    
    private void loadData()
    {
        try
      {
          am.getContacts(c.AccountID, c.ContactID);
      }
      catch(CaseException exc)
      {
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, exc.getMessage()));
      return;
      }
        contactOptions = am.contactOptions;
        if(c.ContactID == null)
            makeDependentPicklistSelections(contactOptions,'ContactID');
        else
            makeDependentPicklistSelections(c.ContactID,'ContactID');
        
        am.getAssets();
        productLineOptions = am.productLineOptions;
        makeDependentPicklistSelections(productLineOptions, 'Product_Line__c');
        makeDependentPicklistSelectionsForProductLine();
    }
    
    public void makeDependentPicklistSelectionsForProductLine()
    {
      assetOptions = new List<SelectOption>();
      assetOptions.add(new SelectOption('', 'None'));
      assetOptions.addAll(am.getAssetOptionsByLine(c.Product_Line__c));
      if(assetOptions.size() == 1)
          assetOptions = new List<SelectOption>{new SelectOption('', Constants.NO_ASSETS_AVAILABLE)};
        
        makeDependentPicklistSelections(assetOptions, 'Customer_Asset__c');
        makeDependentPicklistSelectionsForAsset();
        
        
    }
    
    public void makeDependentPicklistSelectionsForAsset()
    {
      componentOptions = am.getComponentOptionsByAsset(c.Customer_Asset__c);
      makeDependentPicklistSelections(componentOptions, 'Component__c');
      
      initialChangeAssetLoad = false;
    }
    
    private void makeDependentPicklistSelections(List<SelectOption> options, String fieldName)
    {
        if(options != null && options.size()> 0 && !initialChangeAssetLoad)
        {
            SYstem.debug('\n\noptions[0].getValue() = '+options[0].getValue()+'\n\n');
            c.put(fieldName, options[0].getValue());
            
        }
    }
    
    private void makeDependentPicklistSelections(String value, String fieldName)
    {
        if(value != null  && !initialChangeAssetLoad)
        {
            c.put(fieldName, value);
            
        }
    }
    
    public List<SelectOption> contactOptions {get; private set;}
    public List<SelectOption> productLineOptions{get; private set;}
    public List<SelectOption> assetOptions{get; private set;}
    public List<SelectOption> componentOptions{get; private set;}
    
    
    public Pagereference saveOnly()
    {
        SavePoint sp = Database.setSavePoint();
        try
        {
            return am.saveCase(cm, caseComment, Constants.REDIRECT_PARENT, useDefaultAssignmentRules, isChangeAsset,false);
        }
        catch(DMLException dmle)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, System.label.General_Error_On_Case+': '+dmle));
            Database.rollBack(sp);
            return null;
        }
        catch(Exception exc)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, System.label.General_Error_On_Case+': '+exc));
            Database.rollBack(sp);
            return null;
        }
    }
    
    public Pagereference saveAndAttach()
    {
        SavePoint sp = Database.setSavePoint();
        try
        {
            return am.saveCase(cm, caseComment, Constants.REDIRECT_ATTACH, useDefaultAssignmentRules, false,false);
        }
        catch(DMLException dmle)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, System.label.General_Error_On_Case+': '+dmle));
            Database.rollBack(sp);
            return null;
        }
        catch(Exception exc)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, System.label.General_Error_On_Case+': '+exc));
            Database.rollBack(sp);
            return null;
        }
    }
    
    public Pagereference saveAndClose()
    {
        SavePoint sp = Database.setSavePoint();
        try
        {
            return am.saveCase(cm, caseComment, Constants.REDIRECT_CLOSED, useDefaultAssignmentRules, false,true);
        }
        catch(DMLException dmle)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, System.label.General_Error_On_Case+': '+dmle));
            Database.rollBack(sp);
            return null;
        }
        catch(Exception exc)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, System.label.General_Error_On_Case+': '+exc));
            Database.rollBack(sp);
            return null;
        }
    }
    
    
    public void refreshAccount()
    {
        if(c != null )
        {
            if( !GenericServices.isNullOrEmpty(c.AccountID))
            {
                am = new AccountModel(new Account(id = c.AccountID));
                c.ContactID = null;
                loadData();
            }
            else
            {
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.FATAL, System.label.No_Account_provided+' - Please choose an Account before clicking Go'));
            }
        }
    }
}


  • May 01, 2014
  • Like
  • 0
This code has been working perfectly for months, but suddenly it stopped. The last time the email template was used was 2/24/14. I have verified that there have been conditions where it should have been sent since then but hasn't. Any ideas?

global with sharing class NPSEmailSenderBatch implements Database.Batchable<SObject>, Database.Stateful
{
    public String query = '';
    global Set<ID> contactIDsToSendEmailTo;
   
    public NPSEmailSenderBatch()
    {
        query = 'Select ID, Name from Account';
        contactIDsToSendEmailTo = new Set<ID>();
    }  
   
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, list<sObject> scope)
    {
        Set<ID> accountIDs = new Set<ID>();
        for(Account a: (List<Account>) scope)
            accountIDs.add(a.ID);
       
        Set<ID> accountIdsToSendEmailTo = new Set<ID>();
        for(Contract ctrct: [Select ID, AccountID, Subscription_Start_Date__c
                             from Contract
                             where AccountID in: accountIDs
                             and Contract_Status__c =: 'Active'
                             and Subscription_Start_Date__c !=: null])
        {
        //send every 6 months and 12 months from subscription start date
            if(
            ((ctrct.Subscription_Start_Date__c.addMonths(6).month() == (Date.today().month()))
            || (ctrct.Subscription_Start_Date__c.month() == Date.today().month() && ctrct.Subscription_Start_Date__c.year() < Date.today().year()))
                && ctrct.Subscription_Start_Date__c.day() == Date.Today().day()
            )
            {
                accountIDsToSendEmailTo.add(ctrct.AccountID);
            }
        }
       
        //if we have qualified accounts
        if(accountIDsToSendEmailTo.size() > 0)
        {
            for(Contact c: [Select ID, LastName, FirstName, Key_Contact__c
                            from Contact
                            where AccountID in: accountIdsToSendEmailTo
                            and Contact_Status__c =: Constants.STATUS_ACTIVE
                            ])
            {
                if(c.Key_Contact__c != null && c.Key_Contact__c.contains(Constants.CONTACTOBJ_PRIMARY_CONTACT))
                    contactIDsToSendEmailTo.add(c.ID);
            }
        }
    }
   
    global void finish(Database.BatchableContext BC)
    {
        if(contactIDsToSendEmailTo.size() > 0)
        {
            List<ID> contactIDs = new List<ID>();
            contactIDs.addAll(contactIDsToSendEmailTo);
            Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.setSenderDisplayName('Client Care');
            mail.setTargetObjectIds(contactIDs);
            mail.setTemplateId(GenericServices.getGeneralSettingValueForKey(Constants.NPS_TEMPLATE_ID));
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
        }
    }
   
    global static void startCalculation()
    {
        NPSEmailSenderBatch cesb = new NPSEmailSenderBatch();
        Database.executeBatch(cesb);
    }
}
  • April 07, 2014
  • Like
  • 0
Here is my form code. I'm trying to create a lead record from the pre-chat form if one does not already exist.

<form method='post' id='prechatForm'>
    First Name:<font color="red">*</font><input type="text" name="liveagent.prechat:FirstName" /><br />
    Last Name:<font color="red">*</font> <input type="text" name="liveagent.prechat:LastName" /><br />
    Email:<font color="red">*</font> <input type="text" name="liveagent.prechat:Email" /><br />
    Phone Number:<font color="red">*</font> <input type='text' name='liveagent.prechat:Phone' /><br />
    Company Name:<font color="red">*</font> <input type='text' name='liveagent.prechat:Company' /><br />
    State:<font color="red">*</font> <select name="liveagent.prechat:State">
          <option value='Select State' selected='selected'>Select State</option>
          <option value='AK'>AK</option>
          <option value='AL'>AL</option>
          <option value='AR'>AR</option>
          <option value='AZ'>AZ</option><option value='CA'>CA</option><option value='CO'>CO</option><option value='CT'>CT</option><option value='DE'>DE</option><option value='FL'>FL</option><option value='GA'>GA</option><option value='HI'>HI</option><option value='IA'>IA</option><option value='ID'>ID</option><option value='IL'>IL</option><option value='IN'>IN</option><option value='KS'>KS</option><option value='KY'>KY</option><option value='LA'>LA</option><option value='MA'>MA</option><option value='MD'>MD</option><option value='ME'>ME</option><option value='MI'>MI</option><option value='MN'>MN</option><option value='MO'>MO</option><option value='MS'>MS</option><option value='MT'>MT</option><option value='NC'>NC</option><option value='ND'>ND</option><option value='NE'>NE</option><option value='NH'>NH</option><option value='NJ'>NJ</option><option value='NM'>NM</option><option value='NV'>NV</option><option value='NY'>NY</option><option value='OH'>OH</option><option value='OK'>OK</option><option value='OR'>OR</option><option value='PA'>PA</option><option value='RI'>RI</option><option value='SC'>SC</option><option value='SD'>SD</option><option value='TN'>TN</option><option value='TX'>TX</option><option value='UT'>UT</option><option value='VA'>VA</option><option value='VT'>VT</option><option value='WA'>WA</option><option value='WI'>WI</option><option value='WV'>WV</option><option value='WY'>WY</option>
        </select><br />
        <br/><font color="red">*</font>Indicates a required field.<br /><br />
        <!-- Saves values entered in the pre-chat fields to the chat transcript -->
        <input type="hidden" name="liveagent.prechat.save:FirstName" value="First_Name__c" />
        <input type="hidden" name="liveagent.prechat.save:LastName" value="Last_Name__c" />
        <input type="hidden" name="liveagent.prechat.save:Email" value="Email__c" />
        <input type="hidden" name="liveagent.prechat.save:Phone" value="Phone__c" />
        <input type="hidden" name="liveagent.prechat.save:Company" value="Company__c" />
        <input type="hidden" name="liveagent.prechat.save:State" value="State__c" />
       
<!-- Map lead fields  -->
<input type="hidden" name="liveagent.prechat.findorcreate.map:Lead" value="FirstName,FirstName;LastName,LastName;Email,Email;" />

<!-- Match lead by email -->
<input type="hidden" name="liveagent.prechat.findorcreate.map.doFind:Lead" value="Email,true;" />
<input type="hidden" name="liveagent.prechat.findorcreate.map.isExactMatch:Lead" value="Email,true;" />

<!-- Create unmatched lead -->
<input type="hidden" name="liveagent.prechat.findorcreate.map.doCreate:Lead" value="FirstName,true;LastName,true;Email,true;" />

<!-- Save lead to lookup -->
<input type="hidden" name="liveagent.prechat.findorcreate.saveToTranscript:Lead" value="Lead" />

<!-- Display lead -->
<input type="hidden" name="liveagent.prechat.findorcreate.showOnCreate:Lead" value="true" />

    <input type='submit' value='Request Chat' id='prechat_submit'/> 
</form>
  • February 11, 2014
  • Like
  • 1
I'm suddenly getting this error when pushing unrelated code to production. The class in question has been working fine for over a year. The error lines are anywhere it says tstcont.submitCase();

@isTest
class TestWeb2CaseCont {
    static testMethod void testCaseWithContact(){
        Account a = TestUtils.getAccount('ut Acc1');
        insert a;
        Contact ct = TestUtils.getContact(a, 'ut Contact1');
        ct.Email = 'utContact1@testclass.com';
        insert ct;
       
        Web2CaseCont tstcont = new Web2CaseCont();
        tstcont.c.SuppliedEmail = ct.Email;
        tstcont.submitCase();
        System.assertEquals(ct.Id, tstcont.c.ContactId);
        System.assertEquals(a.Id, tstcont.c.AccountId);
    }
   
    static testMethod void testCaseWithoutContact(){       
        Web2CaseCont tstcont = new Web2CaseCont();
        tstcont.submitCase();
        System.assertEquals(tstcont.c.ContactId, null);
        System.assertEquals(tstcont.c.AccountId, null);
    }
   
    static testMethod void testPageParameters(){       
        Test.setCurrentPageReference(new PageReference('Page.Web2Case'));
        System.currentPageReference().getParameters().put('pline', 'None');
        System.currentPageReference().getParameters().put('Origin', 'None');
        System.currentPageReference().getParameters().put('co', 'None');       
       
        Web2CaseCont tstcont = new Web2CaseCont();
        tstcont.submitCase();
        System.assertEquals(tstcont.c.Product_Line__c,'None' );
        System.assertEquals(tstcont.c.Origin,'None' );
        System.assertEquals(tstcont.c.SuppliedCompany,'None' );
    }
   
    static testMethod void testAttachment(){       
        Attachment att = new Attachment();
        att.Name = 'ut attachment';
        att.Body = Blob.valueOf(att.Name);
        Web2CaseCont tstcont = new Web2CaseCont();
        tstCont.att = att;
        tstcont.submitCase();
    }
   
    static testMethod void testFailure(){          
        Web2CaseCont tstcont = new Web2CaseCont();
        tstcont.c = null;
        tstcont.submitCase();
        System.assertEquals(tstcont.msg, System.label.WebCaseFailure );
    }
}
  • February 03, 2014
  • Like
  • 0
Here is my form code. I'm trying to create a lead record from the pre-chat form if one does not already exist.

<form method='post' id='prechatForm'>
    First Name:<font color="red">*</font><input type="text" name="liveagent.prechat:FirstName" /><br />
    Last Name:<font color="red">*</font> <input type="text" name="liveagent.prechat:LastName" /><br />
    Email:<font color="red">*</font> <input type="text" name="liveagent.prechat:Email" /><br />
    Phone Number:<font color="red">*</font> <input type='text' name='liveagent.prechat:Phone' /><br />
    Company Name:<font color="red">*</font> <input type='text' name='liveagent.prechat:Company' /><br />
    State:<font color="red">*</font> <select name="liveagent.prechat:State">
          <option value='Select State' selected='selected'>Select State</option>
          <option value='AK'>AK</option>
          <option value='AL'>AL</option>
          <option value='AR'>AR</option>
          <option value='AZ'>AZ</option><option value='CA'>CA</option><option value='CO'>CO</option><option value='CT'>CT</option><option value='DE'>DE</option><option value='FL'>FL</option><option value='GA'>GA</option><option value='HI'>HI</option><option value='IA'>IA</option><option value='ID'>ID</option><option value='IL'>IL</option><option value='IN'>IN</option><option value='KS'>KS</option><option value='KY'>KY</option><option value='LA'>LA</option><option value='MA'>MA</option><option value='MD'>MD</option><option value='ME'>ME</option><option value='MI'>MI</option><option value='MN'>MN</option><option value='MO'>MO</option><option value='MS'>MS</option><option value='MT'>MT</option><option value='NC'>NC</option><option value='ND'>ND</option><option value='NE'>NE</option><option value='NH'>NH</option><option value='NJ'>NJ</option><option value='NM'>NM</option><option value='NV'>NV</option><option value='NY'>NY</option><option value='OH'>OH</option><option value='OK'>OK</option><option value='OR'>OR</option><option value='PA'>PA</option><option value='RI'>RI</option><option value='SC'>SC</option><option value='SD'>SD</option><option value='TN'>TN</option><option value='TX'>TX</option><option value='UT'>UT</option><option value='VA'>VA</option><option value='VT'>VT</option><option value='WA'>WA</option><option value='WI'>WI</option><option value='WV'>WV</option><option value='WY'>WY</option>
        </select><br />
        <br/><font color="red">*</font>Indicates a required field.<br /><br />
        <!-- Saves values entered in the pre-chat fields to the chat transcript -->
        <input type="hidden" name="liveagent.prechat.save:FirstName" value="First_Name__c" />
        <input type="hidden" name="liveagent.prechat.save:LastName" value="Last_Name__c" />
        <input type="hidden" name="liveagent.prechat.save:Email" value="Email__c" />
        <input type="hidden" name="liveagent.prechat.save:Phone" value="Phone__c" />
        <input type="hidden" name="liveagent.prechat.save:Company" value="Company__c" />
        <input type="hidden" name="liveagent.prechat.save:State" value="State__c" />
       
<!-- Map lead fields  -->
<input type="hidden" name="liveagent.prechat.findorcreate.map:Lead" value="FirstName,FirstName;LastName,LastName;Email,Email;" />

<!-- Match lead by email -->
<input type="hidden" name="liveagent.prechat.findorcreate.map.doFind:Lead" value="Email,true;" />
<input type="hidden" name="liveagent.prechat.findorcreate.map.isExactMatch:Lead" value="Email,true;" />

<!-- Create unmatched lead -->
<input type="hidden" name="liveagent.prechat.findorcreate.map.doCreate:Lead" value="FirstName,true;LastName,true;Email,true;" />

<!-- Save lead to lookup -->
<input type="hidden" name="liveagent.prechat.findorcreate.saveToTranscript:Lead" value="Lead" />

<!-- Display lead -->
<input type="hidden" name="liveagent.prechat.findorcreate.showOnCreate:Lead" value="true" />

    <input type='submit' value='Request Chat' id='prechat_submit'/> 
</form>
  • February 11, 2014
  • Like
  • 1
I am trying to implement a roll-up summary of the earliest contract start date on the account object using the code outlined here (http://blog.elieperez.net/salesforce-lookup-roll-up-summary/). Below is my trigger.
 
trigger rollupContractsOnAccount on Contract (after insert,after update,after delete,after undelete) {
     
    string mysobjectParent = 'Account',      // Parent sobject API Name
           myrelationName = 'Contract__r', // Api name of the relation between parent and child (ends with __r)
           myformulaParent = 'Customer_Since__c',        // Api name of the number field that will contain the calculation
           mysobjectChild = 'Contract',  // Child sobject API Name
           myparentfield = 'Account', // Api name of the lookup field on chield object
           myfieldChild = 'Subscription_Start_Date__c';          // Api name of the child field to roll up
     
    LookupCalculation.Method method = LookupCalculation.Method.MIN; //Selected method: could be COUNT, SUM, MIN, MAX, AVG
     
    LookupCalculation calculation = new LookupCalculation(mysobjectParent, myrelationName, myformulaParent,
                                                          mysobjectChild, myparentfield, myfieldChild);
    List<sobject> objList = new List<sobject>((List<sobject>) Trigger.new);
    if(Trigger.isDelete)
        objList = Trigger.old;
    if(Trigger.isUpdate)
        objList.addAll((List<sobject>) Trigger.old);
    calculation.calculate(method, objList);
}

This gives me the error:

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger rollupContractsOnAccount caused an unexpected exception, contact your administrator: rollupContractsOnAccount: execution of AfterInsert caused by: System.SObjectException: Invalid field Account for Contract: Class.LookupCalculation.Calculate: line 25, column 1

What am I missing? The error is on "myparentfield," which is correct as Account for the Contract object.
  • January 28, 2015
  • Like
  • 0
I have the following trigger, but it's not working as intended. There are no errors in the code.. any ideas?
 
trigger createCancellationReport on Opportunity (after update) {

    List<Win_Loss_Report__c> reportstoinsert = new List<Win_Loss_Report__c>();

    for (Opportunity opp : Trigger.new) {

        // Create cancellation report only for cancellation oppys
        if (opp.StageName == 'Closed Won' & opp.Cancellation_Reason__c != null) {
            Win_Loss_Report__c cr = new Win_Loss_Report__c();
            cr.Opportunity__c   = opp.id;
            cr.Name = 'Cancellation Report';
            cr.RecordTypeID = '012J00000009NC9';
            reportstoinsert.add(cr); // bulk process
        } 
    } 
}

 
  • January 27, 2015
  • Like
  • 0
I am getting this error for a scheduled job that sends mass emails every day.

First error: SendEmail failed. First exception on row 0; first error: LIMIT_EXCEEDED, Too many target object ids.: []

Here is the code:

global with sharing class EmailSenderBatch implements Database.Batchable<SObject>, Database.Stateful 
{
    public String query = '';
    global Set<ID> contactIDsToSendEmailTo;
    
    public EmailSenderBatch()
    {
        query = 'Select ID, Name from Account';
        contactIDsToSendEmailTo = new Set<ID>();
    }   
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, list<sObject> scope)
    {
        Set<ID> accountIDs = new Set<ID>();
        for(Account a: (List<Account>) scope)
            accountIDs.add(a.ID);
        
        Set<ID> accountIdsToSendEmailTo = new Set<ID>();
        for(Contract ctrct: [Select ID, AccountID, Subscription_Start_Date__c
                             from Contract 
                             where AccountID in: accountIDs
                             and Contract_Status__c =: 'Active'
                             and Subscription_Start_Date__c !=: null])
        {
        //send every 3 months and 9 months from subscription start date
            if(
            ((ctrct.Subscription_Start_Date__c.addMonths(3).month() == (Date.today().month()))
            || (ctrct.Subscription_Start_Date__c.addMonths(9).month() == (Date.today().month())))
            )
            {
                accountIDsToSendEmailTo.add(ctrct.AccountID);
            }
        }
        
        //if we have qualified accounts
        if(accountIDsToSendEmailTo.size() > 0)
        {
            for(Contact c: [Select ID, LastName, FirstName, Key_Contact__c
                            from Contact
                            where AccountID in: accountIdsToSendEmailTo
                            and Contact_Status__c =: Constants.STATUS_ACTIVE
                            ])
            {
                if(c.Key_Contact__c != null && c.Key_Contact__c.contains(Constants.CONTACTOBJ_PRIMARY_SUPPORT_CONTACT))
                    contactIDsToSendEmailTo.add(c.ID);
            }
        }
    }
    
    global void finish(Database.BatchableContext BC)
    {
        if(contactIDsToSendEmailTo.size() > 0)
        {
            List<ID> contactIDs = new List<ID>();
            contactIDs.addAll(contactIDsToSendEmailTo);
            Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.setSenderDisplayName('Andrew Simpson');
            mail.setTargetObjectIds(contactIDs);
            mail.setTemplateId(GenericServices.getGeneralSettingValueForKey(Constants.TEMPLATE_ID));
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
        }
    }
    
    global static void startCalculation()
    {
        EmailSenderBatch cesb = new EmailSenderBatch();
        Database.executeBatch(cesb);
    }
}

Is the error referring to the daily email limit or too many results from the query? Any help on how I could resolve the limit would be appreciated.
  • June 02, 2014
  • Like
  • 0
Hello all.  I am posting under my supervisors name/account.  I have been tasked with taking a fresh copy of the PROD database and replacing the Sandbox database to give us identical database objects (tables, queries) and data at the time of execution in both environments.  I know most people end up pushing the Sandox to Prod but we need to do the opposite.  I have only been exposed to Salesforce for the past two days sdo it's all very new to me.  However, I do have a strong DBA background (MS SQL Server). 

How would I go about doing this?  We have a Enterprise license of SalesForce and I do have access to a UI called "Workbench".

(To emphasize, this is for the database only.)

Thanks!


This code has been working perfectly for months, but suddenly it stopped. The last time the email template was used was 2/24/14. I have verified that there have been conditions where it should have been sent since then but hasn't. Any ideas?

global with sharing class NPSEmailSenderBatch implements Database.Batchable<SObject>, Database.Stateful
{
    public String query = '';
    global Set<ID> contactIDsToSendEmailTo;
   
    public NPSEmailSenderBatch()
    {
        query = 'Select ID, Name from Account';
        contactIDsToSendEmailTo = new Set<ID>();
    }  
   
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, list<sObject> scope)
    {
        Set<ID> accountIDs = new Set<ID>();
        for(Account a: (List<Account>) scope)
            accountIDs.add(a.ID);
       
        Set<ID> accountIdsToSendEmailTo = new Set<ID>();
        for(Contract ctrct: [Select ID, AccountID, Subscription_Start_Date__c
                             from Contract
                             where AccountID in: accountIDs
                             and Contract_Status__c =: 'Active'
                             and Subscription_Start_Date__c !=: null])
        {
        //send every 6 months and 12 months from subscription start date
            if(
            ((ctrct.Subscription_Start_Date__c.addMonths(6).month() == (Date.today().month()))
            || (ctrct.Subscription_Start_Date__c.month() == Date.today().month() && ctrct.Subscription_Start_Date__c.year() < Date.today().year()))
                && ctrct.Subscription_Start_Date__c.day() == Date.Today().day()
            )
            {
                accountIDsToSendEmailTo.add(ctrct.AccountID);
            }
        }
       
        //if we have qualified accounts
        if(accountIDsToSendEmailTo.size() > 0)
        {
            for(Contact c: [Select ID, LastName, FirstName, Key_Contact__c
                            from Contact
                            where AccountID in: accountIdsToSendEmailTo
                            and Contact_Status__c =: Constants.STATUS_ACTIVE
                            ])
            {
                if(c.Key_Contact__c != null && c.Key_Contact__c.contains(Constants.CONTACTOBJ_PRIMARY_CONTACT))
                    contactIDsToSendEmailTo.add(c.ID);
            }
        }
    }
   
    global void finish(Database.BatchableContext BC)
    {
        if(contactIDsToSendEmailTo.size() > 0)
        {
            List<ID> contactIDs = new List<ID>();
            contactIDs.addAll(contactIDsToSendEmailTo);
            Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
            mail.setSenderDisplayName('Client Care');
            mail.setTargetObjectIds(contactIDs);
            mail.setTemplateId(GenericServices.getGeneralSettingValueForKey(Constants.NPS_TEMPLATE_ID));
            Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
        }
    }
   
    global static void startCalculation()
    {
        NPSEmailSenderBatch cesb = new NPSEmailSenderBatch();
        Database.executeBatch(cesb);
    }
}
  • April 07, 2014
  • Like
  • 0
I'm suddenly getting this error when pushing unrelated code to production. The class in question has been working fine for over a year. The error lines are anywhere it says tstcont.submitCase();

@isTest
class TestWeb2CaseCont {
    static testMethod void testCaseWithContact(){
        Account a = TestUtils.getAccount('ut Acc1');
        insert a;
        Contact ct = TestUtils.getContact(a, 'ut Contact1');
        ct.Email = 'utContact1@testclass.com';
        insert ct;
       
        Web2CaseCont tstcont = new Web2CaseCont();
        tstcont.c.SuppliedEmail = ct.Email;
        tstcont.submitCase();
        System.assertEquals(ct.Id, tstcont.c.ContactId);
        System.assertEquals(a.Id, tstcont.c.AccountId);
    }
   
    static testMethod void testCaseWithoutContact(){       
        Web2CaseCont tstcont = new Web2CaseCont();
        tstcont.submitCase();
        System.assertEquals(tstcont.c.ContactId, null);
        System.assertEquals(tstcont.c.AccountId, null);
    }
   
    static testMethod void testPageParameters(){       
        Test.setCurrentPageReference(new PageReference('Page.Web2Case'));
        System.currentPageReference().getParameters().put('pline', 'None');
        System.currentPageReference().getParameters().put('Origin', 'None');
        System.currentPageReference().getParameters().put('co', 'None');       
       
        Web2CaseCont tstcont = new Web2CaseCont();
        tstcont.submitCase();
        System.assertEquals(tstcont.c.Product_Line__c,'None' );
        System.assertEquals(tstcont.c.Origin,'None' );
        System.assertEquals(tstcont.c.SuppliedCompany,'None' );
    }
   
    static testMethod void testAttachment(){       
        Attachment att = new Attachment();
        att.Name = 'ut attachment';
        att.Body = Blob.valueOf(att.Name);
        Web2CaseCont tstcont = new Web2CaseCont();
        tstCont.att = att;
        tstcont.submitCase();
    }
   
    static testMethod void testFailure(){          
        Web2CaseCont tstcont = new Web2CaseCont();
        tstcont.c = null;
        tstcont.submitCase();
        System.assertEquals(tstcont.msg, System.label.WebCaseFailure );
    }
}
  • February 03, 2014
  • Like
  • 0