• mjohnson-TIC
  • NEWBIE
  • 497 Points
  • Member since 2011
  • Software Developer
  • TIC Gums

  • Chatter
    Feed
  • 14
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 24
    Questions
  • 110
    Replies
I need a formula that calculates how many days are in the current month.

I've been using this: DAY(DATE(YEAR(TODAY()),MONTH(TODAY())+1,1)-1)
till now but it's starting to give me an error: #Error!

HELP!
To start...I'm not developer...so this is probably a silly question but...we've recently gone through a migration to a new SFDC org and I have a bit of code originally written 8 years ago and the test class that was written for it simply won't work.  But I don't know enough about writing test code to have the foggiest idea why! :(

It's a crucial part of our current billing process...so any help would be greatly appreciated!
/*
Description:
 Automatically email customer their invoice once it’s been approved.
 
Functional Logic (API names in brackets[]):
 Whenever a case is updated and the Send Invoice [Send_Invoice__c] flag is true
 send an email to the case contact [ContactId] including the case attachment as 
 an email attachment if and only if there is one and only one attachment of a size less than 5 MB attached to the case.
 
Updates:
12/14/09 - Send a user friendly error email to the case owner if invoice fails to get sent
02/14/08 - Reset send_invoice__c flag if email fails

*/
@isTest
private class InvoiceMailerTest {

  // ensure no errors occur when sending a invoice correctly and that
  // send invoice flag remains checked
    static testMethod void testInvoiceMailer() {
    
    // create test case
    Case testCase = getTestCase();
    insert testCase;
    
    // add one attachment to simulate adding an invoice
    Attachment testAttachment = getTestAttachment(testCase);
    insert testAttachment;
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is still checked as any errors will uncheck it
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == true, 
      'The invoice mailer appears to be failing when a case has a valid contact and attachment.');
    
    }
    
    // ensure no exceptions are thrown if case has no contact id
    // and that the send invoice flag is reset
    static testMethod void testInvoiceMailerErrorNoContactId() {
      // create test case and zero out contact id field
      Case testCase = getTestCase();
      testCase.contactId = null;
      insert testCase;
      
      // add one attachment to simulate adding an invoice
    Attachment testAttachment = getTestAttachment(testCase);
    insert testAttachment;
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is not checked as no contact id should generate an
    // error email and uncheck the send invoice flag
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == false, 
      'The invoice mailer appears to have succeeded even though the test case had no associated contact.');  
    }
    
    // ensure no exceptions are thrown if case has no attachments
    // and that the send invoice flag is reset
    static testMethod void testInvoiceMailerErrorNoAttachment() {
      // create test case
    Case testCase = getTestCase();
    insert testCase;
    
    // don't add any attachments
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is not checked as a case with no attachments
    // should generate an error email and uncheck the send invoice flag
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == false, 
      'The invoice mailer appears to have succeeded even though the test case had no associated attachment');
    }
    
    // ensure no exceptions are thrown if case has more than one attachment
    // and that the send invoice flag is reset
    static testMethod void testInvoiceMailerErrorTooManyAttachments() {
      // create test case
    Case testCase = getTestCase();
    insert testCase;
    
    // add multiple attachments
    Attachment testAttachment1 = getTestAttachment(testCase);
    insert testAttachment1;
    Attachment testAttachment2 = getTestAttachment(testCase);
    insert testAttachment2;
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is not checked as a case with more than one attachment
    // should generate an error email and uncheck the send invoice flag
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == false, 
      'The invoice mailer appears to have succeeded even though the test case has more than one associated attachment');
    }
    
    // create a generic case related to a contact with a non-null email
    private static Case getTestCase() {
      Contact testContact = new Contact(lastName = 'Test', email = 'test@mailinator.com');
      insert testContact;
      
      Case testCase = new Case(contactId = testContact.id);
      return testCase;
    }
    
    // create a generic attachment related to a given case
    private static Attachment getTestAttachment(Case parentCase) {
      Blob attachmentContent = Blob.valueOf('Hello World!');
      Attachment testAttachment = 
        new Attachment(parentId = parentCase.id,
                 name = 'Invoice.pdf',
                 body = attachmentContent);
      return testAttachment;
    }
}


 
I have a visualforce sites form. When the visitor clicks the submit button, I save the information in the database and then redirect the user to a landing page (e.g www.example.com). I would like to ideally display a "Thank you" page for 5 seconds that confirms that the form was submitted before doing the redirect.
 
VF Page:

             <apex:pageBlockButtons > 
                <apex:commandButton action="{!Submit}" value = "Submit" />  
            </apex:pageBlockButtons>

    
Apex Code;

public pagereference Submit() { 
         
   //save to db code first
   //redirect now 
   landingPage = new PageReference('http://www.example.com');
   landingPage.setRedirect(true);
   return landingPage;

}


 
hello

i am trying to make a validation rule for a currency field with 2 decimal values so that it only enables the user to put .00 .25 .50 and .75, with any other value in the decimals i need it to trigger the erro message.
this is what i've got so far:

NOT(REGEX(TEXT( Gross_Pay__c ), "[0-9]+[.]{1}[25,50]{2}")) it works for 25 and other values but not for 50

it has to be a validation rule with REGEX.
My delete button seems to only be deleting the top row, not the specified row. A {!rowNumber+1} deletes the 2nd row each time, then hits an out of bounds error, naturally. Can anybody see what I'm doing wrong?
 
public void addRow(){
        expenseLineItemAllocationList.add(new Expense_Line_Item_Allocation__c());
    }
    
    public void saveCompany(){
        for(Expense_Line_Item_Allocation__c ela: expenseLineItemAllocationList) ela.Expense_Line_Item_Detail__c = expenseLineItem.Id;
        upsert expenseLineItemAllocationList;
    }
    
    public integer rowIndex {get; set;}
    public Expense_Line_Item_Allocation__c del;
    public void deleteRow(){
        //System.debug('row to be deleted ' + rowIndex );
        //System.debug('row item to be deleted '+expenseLineItemAllocationList[rowIndex]);
        del = new Expense_Line_Item_Allocation__c();
        del = expenseLineItemAllocationList.remove(rowIndex);
    }
 
<apex:pageBlockSection id="Allocation" title="Allocate Expenses" Columns="1"  collapsible="false" rendered="{!(expenseLineItem.AllocationCheckbox__c == true)}">
                <apex:outputLabel value="Please select the Managed Company and the percentage amount you wish to allocate to it. Press Save in order to see the Allocation Split value." />
                <apex:variable var="rowNumber" value="{!0}"/>
                <apex:pageBlockTable id="allocationTable" var="allocation" columns="4" value="{!expenseLineItemAllocationList}">
                    <apex:column headerValue="Managed Company">
                        <apex:inputField value="{!allocation.Product__c}"/>
                    </apex:column>
                    <apex:column headerValue="Allocation %">
                        <apex:inputField value="{!allocation.Allocation__c}"/>
                    </apex:column>
                    <apex:column headerValue="Allocation Split">
                        <apex:outputField value="{!allocation.Allocation_Split__c}"/>
                    </apex:column>
                    <apex:column headerValue="Action">
                        <apex:commandButton value="Delete" action="{!deleteRow}" rerender="Allocation">
                            <apex:param name="Allocation" value="{!rowNumber}" assignTo="{!rowIndex}"/>
                        </apex:commandButton>
                    </apex:column>
                    <apex:variable var="rowNumber" value="{!rowNumber}" />
                </apex:pageBlockTable>
                <apex:commandButton value="Add Row" action="{!addRow}" rerender="allocationTable"/>
            </apex:pageBlockSection>

 
Hi All -

We are looking to implement SAML SSO for our Salesforce instance. From what I've gleaned, it's best practice to set up a custom domain when doing this (we are currently using the generic domain). We are also somewhat concerned about our API integrations once we go live and enforce SAML logins - how does this affect those logins and integrations?

If anyone can comment on some of these, I would be most appreciative. 
trigger CWUserValidation on Case (before update)
{
       
        for (Case objCase : Trigger.new)
        {
           //If the current user is a Tier 2 user and they assign the case to a Tier 3 user, throw error.
           if(objCase.CW_Current_User_s_Profile__c == 'CW MineStar Support - Tier 2' && objCase.CW_Owner_Role__c == '00E300000019awI')            
           {
                trigger.new[0].addError('You cannot assign a case directly to a Tier 3 user. Please choose a Tier 3 queue.');
           }
              //If the current user is a Tier 3 user and they assign the case to a Tier 2 user, Dealer user or Dealer Queue, throw error.
              if(objCase.CW_Current_User_s_Role__c == '00E300000019awI' && (objCase.CW_Owner_Role__c == '00E300000019awS'||objCase.CW_Owner_Role__c == '00E300000019awc'||objCase.CW_Owner_Role__c == '00E300000019awX'||objCase.CW_Owner_Role__c == '00E300000019awN'))              
              {
                trigger.new[0].addError('You cannot assign a case directly to a Tier 2 user, Please assign to the CW Support Advocate (L2) Queue.');
              }else{
                    //If the current user is a Tier 3 user and they assign the case to a Dealer queue, throw error
                    if(objCase.CW_Current_User_s_Role__c == '00E300000019awI' && objCase.CW_Queue_Case_Owner__c.contains('Dealer'))            
                    {
                        trigger.new[0].addError('You cannot assign a case to a Dealer queue, Please assign to the CW Support Advocate (L2) Queue.');
                    }else{
                         //If the current user is a Tier 3 user and they assign the case to a Dealer user 
                         if(objCase.CW_Current_User_s_Role__c == '00E300000019awI' && objCase.CW_Owner_Profile__c == '00e30000001aw4D')
                        {
                           trigger.new[0].addError('You cannot assign a case to a Dealer user, Please assign to the CW Support Advocate (L2) Queue.');
                        }
                         }
                   }    
         }       
}
My trigger if it hits this line, it errors with the error below:
if(objCase.CW_Current_User_s_Role__c == '00E300000019awI' && objCase.CW_Queue_Case_Owner__c.contains('Dealer'))


CWUserValidation: execution of BeforeUpdate
caused by: System.NullPointerException: Attempt to de-reference a null object
Trigger.CWUserValidation: line 17, column 1

Not sure what I'm doing wrong here, can anyone help?
  • November 14, 2014
  • Like
  • 0
I need a trigger that if there is a change on Account record gets all the Opportunities and Opportunity Products belong to that Account refreshed (edit and saved) using the updated information from parent Account record.
Can anybody advise?

Thank you,
Serghei

I'm having some trouble returning data from this SOQL query:

 

SELECT CALENDAR_YEAR(CreatedDate), SUM(Amount)
FROM Opportunity
GROUP BY CALENDAR_YEAR(CreatedDate)

 It returns absolutly nothing even though I have multiple opportunities with amounts.

 

Here is the full method:

 

@RemoteAction
    global Static List<sObject> loadOppsByMonth(){
    	return [SELECT CALENDAR_MONTH(CreatedDate), SUM(Amount), SUM(ExpectedRevenue) FROM Opportunity GROUP BY CALENDAR_MONTH(CreatedDate)];
    }

 Is my return datatype wrong? Should I be looping through the data returned from this query?

 

Full context of the situation: I'm trying to write a query that provides summerized data to a LineChart using the Google Charting API

I am having an issue with single sign-on using Active Directory Federation Services 2.0. Recently one of our users needed his User-Principal Name changed in Active Directory, which is the mapping used in Federation Services against the Federation ID in Salesforce. Active Directory was updated with the new User-Principal Name and I updated the Federation ID on the user record to match the new User-Principal Name. Unfortunately now when attempting single sign-on, I get a login error (the message I've gotten when there is no Federation ID for the User-Principal Id passed). 

Does anyone know exactly how ADFS extracts data from Active Directory? Does something need to be restarted or a domain controller need to be rebooted to register this change?
Does anyone have a way to trigger an event (call apex code) when the schema of an object changes (such as a new field being added)? The only way I can come up with, is scheduling an apex job to perform desired actions based on metadata timestamps on objects (createddate modifieddate etc). Does anyone use or can anyone come up with a more realtime way to do this?

Begining last week (or at least when I was notified), none of the actions associated with apex commandbuttons are initiating when clicked for all Visualforce pages associated with 1 specific Apex class I created. Clicking apex:commandbuttons with actions associated with this particular class do not even register an event log when trying to debug. I have not touched these Visualforce pages or Apex class in several months, and there have been no issues until last week. My temporary work around is creating an apex:actionsupport with the appriate onclick action for each button, but this is not ideal. Any ideas what might be causing this?

Has anyone had an issue with deploying Visualforce pages recently? Before they use to deploy almost instantly from a sandbox instance to production, recently (within the past 1-2 weeks) they are taking as long as classes and triggers are to push. Has a change been made recently that requires Visualforce to go through unit testing?

Hi All,

 

I have Visualforce Page used in several Dashboards as a component and I was wondering if it were possible to dynamically retrieve the Id of the Dashboard through the Apex controller. Ultimately I would like to run a query within the Apex controller based on the RunningUserId of the Dashboard being viewed, as this VIsuaforce page is being used on several Dashboards. I'd prefer not to create a new Visualforce page for each Dashboard.

Hi All,

 

I'm attempting to configure OpenSSO with Salesforce for single sign-on. The "Verification Certificate" generated by OpenSSO is in text format, which is just a long encrypted string. Apparently the "Identity Provider Certificate" requires this to be in X509 certificate format. Does anyone know how to convert this encrypted string to X509 certificate format?

I've been doing some work creating content in Visualforce that is rendered/opened in different formats (PDF, csv, excel etc). The few ways I have found to force rendering or download of the Visualforce page onload is to renderAs="PDF" or setting contenttype="text/csv" etc. The issue is during the load of the page, the page itself is saved using the naming convention of the Visualforce page, meaning you cannot specify the necessary extension. 

 

I was wondering if anyone had a workaround or any ideas to force the save of the page to a dynamic name and specify a file extension (for instance force a Visualforce page named Report with contenttype="application/csv" save as {dynamicname}.csv). 

 

My temporary work-around is having the file emailed as an attachment, as you can specify name of attachment and file extension dynamically in Visualforce templates. I would prefer the option to directly download rather then use this work-around. Anyone have any ideas?

I am building an automated email which I am adding a Visualforce attachment that I would like to open as an XLS file  in excel. I am doing so using the following messaging:attachment syntax.

 

    <messaging:attachment renderAs="application/vnd.ms-excel" filename="testexcel.xls">
        <c:TestExcel />
    </messaging:attachment>

 The component I am using I kept as simple as possible just to get it working, which is a 3 column table with 10 rows of contacts. Here is my component code.

 

<apex:component controller="TestClass" access="global">
      <apex:dataTable value="{!Contacts}" var="c">
         <apex:column value="{!c.Name}"/>
         <apex:column value="{!c.Email}"/>
         <apex:column value="{!c.Phone}"/>
      </apex:dataTable>
</apex:component>

 

The message sends and the attachment shows up fine on the email. The issue I am having is while opening the file I get the "The file you are trying to open, 'testexcel.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?" message because it is not encoded correctly. Clicking open, opens the file just fine, but I would really like to find a way to prevent this warning message from popping up when my users open the file. I originally considered doing it in CSV, but I need to format certain cells with certain styling.

 

Does anyone know of any tags or headers I can try adding so that this warning message does not pop up, or does anyone have any idea how to force a formatted Visualforce table to open in Excel without warning? Thanks!

Hi All,

 

I was wondering if anyone might have any idea as to possibly aggregate a manipulated list of an object without actually updating any values of the records returned. Here is the easiest example I can think of to help try to explain what I am doing.

 

I retrieve and manipulate a list of accounts.

 

for(Account a: [Select Name, Last_Year_Sales__c, CreatedDate from Account LIMIT 20]){

if(a.CreatedDate >= datetime.now().adddays(-100)){
 a.Name = 'New';

}else{

a.Name = 'Old';

}

 

Now I would like to aggregate the SUM of Last_Year_Sales__c and group by the manipulated value of Name without actually updating the name of these accounts in the database. Is there a way to use AggregateResult to summarize this list of retrieved data without actually querying the Account object in the database? It would be very nice to aggregate custom or manipulated lists of data generated in Apex.

Hi All,

 

Does anyone know if it is possible to query the related ownerid of the contact/lead record related to a task? I realise the "who" field of task is a lookup to the "name" object which is related to a user/contact/lead. Is the ownerid of the related user/contact/lead captured anywhere on the "name" object (I did not see it under standard fields of the object) or is there any shortcut to get to this id without another select statement based on the whoid of the task? This query could potentially return results of hundreds of tasks so I am hesitant to use an additional select statement if it is possible to retrieve this id an easier way.

Over the last 2-3 days I've been getting the following message when trying to a query through the developer console in Salesforce.

 

Response to EXEC to /_ui/common/apex/debug/ApexCSIAPI was : -1, transaction aborted

 

I am on na3 instance. Anyone have any ideas?

Hi All,

 

I am all of a sudden having an issue when trying to convert rich text from a visualforce page to a string within a controller. When I take the richtext="true" tag off the apex:inputtextarea, it records the value of the text I have in the input just fine, but when I set the tag to true it records the value as null, event when entering text in the input. Has anyone had a problem with this recently (specifically in a spring 12 sandbox) ? I set the version of the page to 24.0 fyi.

 

Simple example:

 

public with sharing class Example {

 

public string test {get;set;}

 

public void debugpage(){

system.debug(test);

 

}

 

<apex:page controller="Example">

 

<apex:inputtextarea value="{!test}/>

<br/>

<apex:commandbutton value="Debug" action="{!debugpage}"/>

 

</apex:page>

 

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

Putting a value in the inputtextarea on this page and clicking the debug button will show the value entered.

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

 

<apex:page controller="Example">

 

<apex:inputtextarea richtext="true" value="{!test}/>

<br/>

<apex:commandbutton value="Debug" action="{!debugpage}"/>

 

</apex:page>

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

Setting the inputtextarea tag of richtext="true" will show the debug of test as null. I have tried creating links, inserting images, just using plain text etc in the rich text editor and the string never returns any value.

 

Any ideas?

Hi All,

 

I've run into an issue where I am able to return results from the ContentDocument object using the system log API but no results are returned from the exact same query I have written in my apex class. Anyone know of any restrictions or ways around this issue?

 

 

Does anyone know what object records of the files tab are stored in and if they are queryable or editable through the API?

Hello All,

 

I recently ran into a situation where I wanted to use a Visualforce page to override new and edit buttons of a custom object. The issue was when I overrode the edit button, inline editing while viewing records of this object became disabled. Because this object had multiple page layouts, I did not want to deal with the daunting task of creating a custom Visualforce page with inline edit functionality for each of these layouts - not to mention the upkeep if anything needed changed. Initially it seemed like the solution would be easy enough, take the edit button off each page layout and replace it with a custom button pointing to my Visualforce page. Unfortunately I overlooked the fact most users edited records of this object by clicking the edit links next to each on the related list from account. 

 

The solution I derived was adding an html component to the left sidebar of all pages that is just a simple javascript snipplet that is working great. See below with my comments.

 

<script>

//retrieve first 4 digits of id to uniquely identify object
var pricing = window.top.location.href.substring(27,31);

//retrieve 2 characters after id to identify if in edit mode
var isedit= window.top.location.href.substring(42,44);

//check if object is in edit mode
if(pricing == 'a015' && isedit == '/e'){
//retrieve full object id and redirect to custom Visualforce page
var pid = window.top.location.href.substring(27,42);
window.top.location = '/apex/ProductPricingEdit?id='+pid;
}
</script>

 

I realize the implication that this may be poor design simply because this script must evaluate every page load on any screen, but for a few objects it is actually very light in comparison with everything else on the page that now has to load. Hope this helps some people out!

Hi All,

 

I am having an issue rendering a span as font family Geometr231 Hv BT when I render as pdf. The font shows up fine when in html but when rendered as a pdf it loses this style. Anyone have any ideas or know of a similar font style I can use to render as pdf?

I can't find what I am doing wrong here though I have done it 10000 time before, something is not returning correctly.

 

I have an Custom_Object__c with fields Status__c and Type__c

 

I have 10 records Status__c = 'Open' and Type__c = 'New'

I have 20 records Status__c = 'Closed' and Type__c = 'New'

 

I run this query and for some reason am running into this problem

 

for(Custom_Object__c c: [Select Status__c from Custom_Object__c where (Status__c = 'Open' OR Status__c = 'Closed') and Type__c = 'New']){}

 

This query 10 rows are returned

 

for(Custom_Object__c c: [Select Status__c from Custom_Object__c where (Status__c = 'Closed' OR Status__c = 'Open') and Type__c = 'New']){}

 

This query 20 rows are returned.....any ideas whats wrong with this logical OR statement that is not returning all 30 rows?

I found something very odd  this morning in the evaluation of number formula fields. Here is a simple formula example where it is returning the incorrect value.

 

IF(Number_Field__c != null, 1, 2)

 

For some reason entering a number in Formula_Field__c will NOT cause the expected 1 to be returned on this record but rather 2. That means even on a record where a value is entered for Number_Field__c, the expressions Number_Field__c != null returns false meaning the system recognizes this as Formula_Field__c =  null?

Hello All,

 

I've been trying to come up with a way of doing the following and have so far been unsuccessful. Onchange of a lookup field I would like to assign the value of the Id to a string in the controller and perform an action method to rerender another section of the page based on that value. This is not what I am trying to do but is a very straight forward example of what I am trying to accomplish.

APEX Class

public string ContactId {get;set;}

 

public string getContactEmail(){

string ContactEmail = [Select Email from Contact where Id=: ContactId].Email;

return ContactEmail;

-----------

VF Page

 

<apex:inputfield value="{!Form__c.Contact__c}">

 

In this example I would like to assign the Id value of the contact from the Form__c.Contact__c inputfield to the ContactId string in the controller when the lookup field is changed. I have tried using javascript to acheive the lkid value of this field and several other ways with no success. Anyone have any ideas of assigning the Id value of a lookup field to a string on change without turning the lookup field into a select list (over 1000 records return so this is not an option). ?

I have a visualforce page I am rendering as a PDF and for some reason all of a sudden a datepicker is shown below of the content of the page as displayed below. I have had this bug occur before in visualforce pages not rendered as a pdf with showhead="false" but had a workaround using <style type="text/css">.datePicker{display:none;}</style>. Anyone else have this problem or have any workarounds?

 

 

 

 

 

inputsalesforceJanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecember2010201120122013201420152016SunMonTueWedThuFriSatToday

Does anyone know of any easy methods to ignore case of a string literal doing a replace? For instance:

 

string a = 'one';

string b = 'OneTwoThree';

string c = b.replace(a,'Four');

 

The above replace would not work due to case sensitivity because string a = 'one' and not 'One'.

 

Is there some way of ignoring the case on string a?

Hi, I've got a lead trigger bulkification issue.  The following piece of code throws a too many soql queries error when more than 200 leads are inserted:
 
if(Trigger.isInsert || Trigger.isUpdate){  
        
            if(HelperClass.firstRun2){
                
            HelperClass.firstRun2=false;          
        
            for(Lead l1: trigger.new){               
                if((UserInfo.getUserId() == Label.MarketoIntegrationUser || UserInfo.getUserId() == Label.WebsiteIntegrationUser) &&
                   (l1.RecordTypeId == leadRecordTypeId) && (l1.Country == 'United States' || 
                   l1.Country == 'United States of America' ||
                   l1.Country == 'USA' ||
                   l1.Country == 'U.S.' ||
                   l1.Country == 'U.S.A'
                   ) ){     
               
                    Set<String> postalCodes = new Set<String>();

                    for( Lead l : trigger.new ) {
                            if(l.PostalCode != null && l.PostalCode.length() >=5)
                                try{                          
                                    String zipStringx = l.PostalCode.substring(0,5);
                                    postalCodes.add( zipStringx );  
                                   // postalCodes.add( l.PostalCode );     
                                } catch(DMLException e){
                                     ApexPages.addMessages(e);
                                     Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
                                     String[] toAddresses = new String[] {'sfdc-admins@pingidentity.com'};
                                     mail.setToAddresses(toAddresses);
                                     mail.setReplyTo('sfdc-admins@pingidentity.com');
                                     mail.setSenderDisplayName('Apex error message');
                                     mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
                                     mail.setPlainTextBody(e.getMessage());
                                     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                                
                                }        
                                                                                         
                    }

                    Map<String, Zip_State_Table__c > validZips = new Map<String, Zip_State_Table__c >();

                    for( Zip_State_Table__c obj : [SELECT  Id, 
                                        Name,
                                        ZipCode__c,
                                        Territory__c                                            
                                        FROM Zip_State_Table__c 
                                            WHERE ZipCode__c IN :postalCodes] ) {
                        validZips.put( obj.ZipCode__c, obj );
                    }

                    for( Lead l : trigger.new ) {
                        if( l.PostalCode != null && l.PostalCode.length() >=5 ) { 
                            if( validZips.containsKey(l.PostalCode.substring(0,5)) ) { 
                                l.State = validZips.get(l.PostalCode.substring(0,5)).Name;
                                l.RegionTerritoryHidden__c = validZips.get(l.PostalCode.substring(0,5)).Territory__c;
                            } else {}

                        } 
                    }
                }
                }
            }
        }

I know the error in the above code is with this part of the code:  
 
for( Zip_State_Table__c obj : [SELECT  Id, 
                                        Name,
                                        ZipCode__c,
                                        Territory__c                                            
                                        FROM Zip_State_Table__c 
                                            WHERE ZipCode__c IN :postalCodes] ) {
                        validZips.put( obj.ZipCode__c, obj );
                    }


I'm unable to re-write that code to avoid the error.  Does anyone see how I can re-write that code with the soql query for loop to avoid the too many soql queries error?  Thanks 
 
  • December 03, 2014
  • Like
  • 0
Hi!  I outsourced a request that was over my head, but there's an issue we didn't consider that our partner wants to charge a lot to fix.  I'd like to do it myself, but they're recommending against it.  Can someone help me understand if their reason makes sense?  
 
We use Cases as Product RMAs.  Each RMA Case has at least one custom object Return Line Item (RLI) related to it.  The RLI contains the product information (part number, quantity sold, qty returning, qty received, etc).  Our problem was that large customers would only return part of the product they requested an RMA for.  Because RMA cases had to be processed in full, credit would be delayed and inventory would be incorrect.  We asked our vendor to create a process that would create a second case for anything that had been returned and update the original case to show only what was pending return.

So for example:
Original Case
Line 1 has qty 3 expected and nothing has been received
Line 2 has qty 2 expected and 1 has been received
Line 3 has qty 4 expected and 4 have been received
 
Press Button.
 
Line 1 for qty 3 stays on the original case
Line 2 for qty 1 stays on the original case
 
Line 2 for qty 1 moves to the cloned case
Line 3 for qty 4 moves to the cloned case
  
Our issue is that from the example above Line 3 still exists on the original case and the qty expected is now 0.  It’s causing confusion in our process and I want to delete that RLI from the original case.  I created the following code to do so, but when I asked the opinion of the person who created the original process he said “There is the issue of doing DML in a trigger, and doing a query in a for loop is never a good idea, especially with how many transactions your trigger structure currently processes.”  What does he mean?  Is it really a concern since only one case would be updated at a time?
 
trigger DeleteZeroQtyReturn on Return_Line_Item__c (after update) {

List<Id> lstId = new List<Id>();
 
for(Return_Line_Item__c RLI: Trigger.old){
        List<Return_Line_Item__c> existRLIList = [Select Id from Return_Line_Item__c where QTY_Returned__c = 0 and Split_with_Button__c=true];
        delete existRLIList;
    }

}

 
  • December 02, 2014
  • Like
  • 0
Hi Everyone,

This is probably a pretty easy answer, but I'm just drawig a blank.  The code snippet below is designed to clone an Opportunity.  The RecClone class is set up to pull in all createable fields for the clone, since the clone function that Apex offers only pulls those fields that you specifically name.  The clone works fine, but I want to overwrite some of the clone fields with other values.  How do I pull the values from Line 3 and replace them with the values from lines 4 - 10?
 
String soql = RecClone.getCreatableFieldsSOQL('Opportunity','Id =: OppId');
                    Opportunity opp = (Opportunity)Database.query(soql);
                    Opportunity opp2 = opp.clone(false, true);
                        opp2.CloseDate = opp.Renewal_Date_Next__c;
                        opp2.OwnerId = amh.Assigned_Account_Manager__c;
                        opp2.Term__c = 12;
                        opp2.Renewal__c = 'Yes';
                        opp2.Effective_Date__c = opp.Renewal_Date_Next__c;
                        opp2.Renewed_Opportunity__c = opp.Id;
                        Opp2.StageName = 'Call Scheduled';

                insert opp2;

 
I need a formula that calculates how many days are in the current month.

I've been using this: DAY(DATE(YEAR(TODAY()),MONTH(TODAY())+1,1)-1)
till now but it's starting to give me an error: #Error!

HELP!
I am trying to pull attachments from a parent object onto the approval email alert (as links) when the child object is submitted for approval.  I am able to pull all the fields from the parent object onto the VF template; but for some reason attachments will not work and i receive the following error message:  Error: Aggregate Relationship is used in an unsupported complex expression containing 'OBJECTA__r.attachments'. 

Beginning of template:
<messaging:emailTemplate subject="CDR Approval Request - {!RelatedTo.PARENT__r.Account__r.Name}" recipientType="User" relatedToType="CHILD__c">
<messaging:htmlEmailBody >

Section pertaining to attachments:
<apex:repeat value="{!relatedTo.PARENT__r.Attachments}" var="a"> 
 <p><a href="https://CS15.salesforce.com/{!URLFOR($Action.Attachment.Download, a.name)}">{!a.Name}</a> ({!a.BodyLength} B)</p>
</apex:repeat>

I believe referencing 'PARENT__r' is the problem, but I do not know how else to reference that the attachments need to pull from the parent object (not child as it will have none)?

Do I need to create a controller to pull the parent object attachments and then reference that controller in the email template??

Please help!
 
To start...I'm not developer...so this is probably a silly question but...we've recently gone through a migration to a new SFDC org and I have a bit of code originally written 8 years ago and the test class that was written for it simply won't work.  But I don't know enough about writing test code to have the foggiest idea why! :(

It's a crucial part of our current billing process...so any help would be greatly appreciated!
/*
Description:
 Automatically email customer their invoice once it’s been approved.
 
Functional Logic (API names in brackets[]):
 Whenever a case is updated and the Send Invoice [Send_Invoice__c] flag is true
 send an email to the case contact [ContactId] including the case attachment as 
 an email attachment if and only if there is one and only one attachment of a size less than 5 MB attached to the case.
 
Updates:
12/14/09 - Send a user friendly error email to the case owner if invoice fails to get sent
02/14/08 - Reset send_invoice__c flag if email fails

*/
@isTest
private class InvoiceMailerTest {

  // ensure no errors occur when sending a invoice correctly and that
  // send invoice flag remains checked
    static testMethod void testInvoiceMailer() {
    
    // create test case
    Case testCase = getTestCase();
    insert testCase;
    
    // add one attachment to simulate adding an invoice
    Attachment testAttachment = getTestAttachment(testCase);
    insert testAttachment;
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is still checked as any errors will uncheck it
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == true, 
      'The invoice mailer appears to be failing when a case has a valid contact and attachment.');
    
    }
    
    // ensure no exceptions are thrown if case has no contact id
    // and that the send invoice flag is reset
    static testMethod void testInvoiceMailerErrorNoContactId() {
      // create test case and zero out contact id field
      Case testCase = getTestCase();
      testCase.contactId = null;
      insert testCase;
      
      // add one attachment to simulate adding an invoice
    Attachment testAttachment = getTestAttachment(testCase);
    insert testAttachment;
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is not checked as no contact id should generate an
    // error email and uncheck the send invoice flag
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == false, 
      'The invoice mailer appears to have succeeded even though the test case had no associated contact.');  
    }
    
    // ensure no exceptions are thrown if case has no attachments
    // and that the send invoice flag is reset
    static testMethod void testInvoiceMailerErrorNoAttachment() {
      // create test case
    Case testCase = getTestCase();
    insert testCase;
    
    // don't add any attachments
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is not checked as a case with no attachments
    // should generate an error email and uncheck the send invoice flag
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == false, 
      'The invoice mailer appears to have succeeded even though the test case had no associated attachment');
    }
    
    // ensure no exceptions are thrown if case has more than one attachment
    // and that the send invoice flag is reset
    static testMethod void testInvoiceMailerErrorTooManyAttachments() {
      // create test case
    Case testCase = getTestCase();
    insert testCase;
    
    // add multiple attachments
    Attachment testAttachment1 = getTestAttachment(testCase);
    insert testAttachment1;
    Attachment testAttachment2 = getTestAttachment(testCase);
    insert testAttachment2;
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is not checked as a case with more than one attachment
    // should generate an error email and uncheck the send invoice flag
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == false, 
      'The invoice mailer appears to have succeeded even though the test case has more than one associated attachment');
    }
    
    // create a generic case related to a contact with a non-null email
    private static Case getTestCase() {
      Contact testContact = new Contact(lastName = 'Test', email = 'test@mailinator.com');
      insert testContact;
      
      Case testCase = new Case(contactId = testContact.id);
      return testCase;
    }
    
    // create a generic attachment related to a given case
    private static Attachment getTestAttachment(Case parentCase) {
      Blob attachmentContent = Blob.valueOf('Hello World!');
      Attachment testAttachment = 
        new Attachment(parentId = parentCase.id,
                 name = 'Invoice.pdf',
                 body = attachmentContent);
      return testAttachment;
    }
}


 
Hello,

Can someboby please help me with the steps and approach, how to confugre the Monthly and weekly calendars in the same field? something like toggle where user should be able to select which calender he wants to use.

Please suggetions!!.
Hi all,

I'm very new to Apex, but am convinced this scenario is possible. Problem is I can't find any examples anywhere, which surprises me.

I have a text field on Account called 'Originating_Lead__c' containing the 18 char ID of a Lead.

On the Lead is a lookup to Account.

I want to insert the ID of the Account record into the Account lookup field on the Lead record that corresponds to the ID held in the Originating_Lead__c field on Account.

I'm know I can't do this declaratively as it's "going down the tree", but I'm surprised this issue hasn't crept up before on here - have trawled right through and haven't found anything. Does anybody know of any examples of similar triggers for similar problems? 

Have browsed and used this community extensively but never posted a question - never needed to!

Thanks in advance.
Michael
Hi,
   I deployed my code on production and I can see that from he logs that my apex class is getting called from my visualforce page, but not a single debug statement is getting printed. It works fine in sandbox enviornment but on production its not printing anything. I have run this code on production before and it used to work fine. but suddenly it stopped working.

Anyone faced same issue before ?

Thanks,
Abhishek 
Hello,
I'm just an admin, not a dev (yet). I would like to create a roll up field at the opportunity taht will be the summ of the product meeting a certain criteria. When I create a rollup summary field at the opportunity level, I can filter the criterias, but not the one I am interested in: Product Name.
How can I filter the product name in this field?
Many thanks!
  • December 02, 2014
  • Like
  • 0

I would like to send the 'name' field in the Lead Object to an external API. However only the 'FirstName' and 'LastName' are available.

Can I edit the WSDL file that is created with the outbound message and change 'FirstName' to 'name' then save it?

Hi All -

We are looking to implement SAML SSO for our Salesforce instance. From what I've gleaned, it's best practice to set up a custom domain when doing this (we are currently using the generic domain). We are also somewhat concerned about our API integrations once we go live and enforce SAML logins - how does this affect those logins and integrations?

If anyone can comment on some of these, I would be most appreciative.