• EMHDev
  • NEWBIE
  • 185 Points
  • Member since 2007

  • Chatter
    Feed
  • 7
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 23
    Questions
  • 88
    Replies
Hi All,

I've written a trigger for Orders where whenever I send an email through the Order the status in the order from 'draft' will become 'sent'. And it works like a charm. My trigger is :
 
trigger TaskTrigger on Task (after insert) {
    List<Order> ordersToUpdate = new List<Order>();

    for(Task t : Trigger.new) {
        if(t.WhatId.getSObjectType() == Order.sObjectType 
            && t.Subject.startsWith('Email:')) {
                ordersToUpdate.add(new Order(Id = t.WhatId, Status = 'Sent'));
        }
    }

    update ordersToUpdate;
}

My problem is with the test class. After modifying my calss alot of times I came to a result where System.AssertException: Assertion Failed: Expected: Sent, Actual: draft

My class is 
@isTest
   public class Test7{
    public static testmethod void TaskTrigger_Test1()
    {
             Account a = new Account(Name = 'Test');
        insert a;     

        Id pricebookId = Test.getStandardPricebookId();                         

        Product2 prd1 = new Product2 (Name='Test Product Entry 1',Description='Test Product Entry 1', isActive = true);
        insert prd1;

        PricebookEntry pe=new PricebookEntry(UnitPrice = 1,Product2Id=prd1.id,Pricebook2Id=pricebookId,isActive=true);
        insert pe;

        Order o = new Order(name='Test1',AccountId=a.id,EffectiveDate=system.today(),status='draft', PriceBook2Id=pricebookId);
        insert o;

        OrderItem oi = new OrderItem(OrderId=o.id,Quantity=1,PricebookEntryId=pe.id, unitPrice=1);
        insert oi;


        Task t = new Task(whatid=o.id,Priority = 'normal',status='open',subject='Email:xxxx');
        insert t;
        
        system.assertequals('Sent',o.status);
    }


}

 

I'm about to pull my hair out, so would really appreciate it if someone could help me see the simple mistake I must be making here.  I have a trigger that works perfectly when I perform manually the same steps I have written into the unit test.  I thought maybe it was that my trigger is a before update trigger, so I added some extraneous updates after the update in this test, but that didn't help.  And, when I do the updates manually exactly as in this unit test, it works, without extraneous follow-on updates.

 

Here's the trigger:

 

 

trigger searchZipCode on Account (before update) {

    // For each Account in the Trigger.new list of Accounts
    for (Account a : Trigger.new) {
        // check if the BillingPostalCode field is contained in the list of zips
        try {
            if (a.BillingPostalCode != NULL){
                if (a.ZipSearchList__c.contains(a.BillingPostalCode.substring(0,5)))
                {
                    a.ZipFound__c = TRUE;
                } else a.ZipFound__c = FALSE;
            }
        } catch (System.NullPointerException e) {
            system.debug(e.getMessage());
            a.ZipFound__c = FALSE;        
        } finally {
            // do nothing     
        }           
 }
}

 

 

 

Here's the unit test:

 

 

@isTest
private class searchZipCodeTest {

    static testMethod void testsearchZipCode() {
        String ziplist = '12345, 67890';
        String successZip = '12345';
        String failZip = '66666';
        
        Account successAccount = new Account(
            Name = 'Success University',
            // RecordType = '012A00000004OUY',
            Type = 'Graduate Institution',
            BillingPostalCode = successZip,
            ZipFound__c = FALSE
        );
        
        Account failAccount = new Account(
            Name= 'Fail University',
            // RecordType = '012A00000004OUY',
            Type = 'Graduate Institution',
            BillingPostalCode = failZip,
            ZipFound__c = FALSE
         );
        insert new Account[] { successAccount, failAccount };
 
        successAccount.ZipSearchList__c = ziplist;
        failAccount.ZipSearchList__c = ziplist;
        update successAccount;
        update failAccount;
        
        Test.StartTest();
        System.assertEquals('12345', successAccount.BillingPostalCode);
        System.assertEquals('12345, 67890', successAccount.ZipSearchList__c);
// This is the assert that fails:
System.assertEquals(TRUE, successAccount.ZipFound__c); System.assertEquals(FALSE, failAccount.ZipFound__c); Test.StopTest(); } }

 

 

 

Here's the error message:

 

Hi,

I am trying to write a Apex query to store the Id's of the queues that I have created. I then want to be able to quickly look up the Id of a specific queue by name.

What  I want is a map where the key is the name of the Queue and the Id is the value, so I wrote the following:

Map<String,Group> Queues = new Map<String, Group>([Select Name,Id from Group where Type = 'Queue']);

 

When I do this, instead of the Name being the key, the Id is.  
(I am using "system.debug(Queues.keyset());" to see the keys

How do I create a Map with the Queue names as the key? The only way that I have been able to come up with so far is something like this:

 

 

Group[] X;
X = [Select Id, Name from Group where Type = 'Queue'];

Map<String,String> Q1 = new Map<String,String>();

for(Integer i = 0; i < X.size(); i++) {
Q1.put(X[i].Name, X[i].Id);
}

But this seems like overkill to run this each time a new email message comes in (the code will be part of an email handler that assigns new cases to the correct queue based on who the message is from.

 

 

Thanks!

Marc

I just updated a class to use the new URL class.  When I ran the test class and deployed it to production, it showed as 100% code coverage for ALL code in the IDE, although it should not have done, since it doesn't actually call all of my code.  However, in the Sandbox itself, the code coverage was way down, because it was counting blank lines and commented out code as not being covered!  So the same code is reported as 100% covered in the IDE and 83% in the sandbox from the Apex Classes link.

 

Has anyone else noticed this?  It appears to have happened today, since the summer 11 roll-out to production.  I did not have this issue when my sandbox was summer 11 and my production was spring 11, although I haven't deployed any code for a couple of weeks.

 

Salesforce, what's happening?

I have been bashing away at this without success all day and obviously am missing something.  I have a VF page which shows a list of custom objects called Lead Companies, which we use to tie leads from the company together. When a user clicks on one of the lead companies in the list, it displays a list of related leads in another pane (a table cell) on the page.  This works perfectly.

 

When clicking on one of leads, I want to open a new window with the standard salesforce lead detail view.  That way, I don't need to code the page and if there are permissions issues (my page needs to run in system mode), it will be taken care of. 

 

I use a Javascript function to pop up the window.  This works fine from a different part of the page which does something similar (but not the same) for accounts.  However, with the lead, it does not appear to run the setter to get the lead id from the param tag until AFTER calling the Javascript function.  From reading all the docs I can find, it should work.  However I know from previous experience that I must be missing something that will be obvious to those casting a fresh eye over this, so thanks in advance.

 

Javascript function - the alert shows a blank AnyId although the debug log shows that the setter is being called, but it only shows up in the log AFTER I've pressed OK on the alert:

 

<script type="text/javascript">
  function pop(AnyId) {
    var myWindow;
    alert('Id is '+AnyId);
    myWindow = window.open('/'+AnyId,'','width=550,height=550,scrollbars=yes');
  }
 </script>

 Relevant part of Visualforce page:

 

<apex:pageBlock title="Leads in Lead Company" id="leadDetails">    <apex:pageBlockTable value="{!relatedLeads}" var="leads">	    
  <apex:column headerValue="Name"> 
    <apex:commandLink value="{!leads.Name}" onclick="pop('{!LeadId}');" > 
      <apex:param name="LeadId" value="{!leads.Id}" assignTo="{!LeadId}" />
    </apex:commandLink>                
  </apex:column> 
... other columns ...
</apex:pageBlockTable>
</apex:pageBlock>

Controller code:

 

  public String LeadId { 
    get ;
    set {
      LeadId =  '/'+value; 
system.debug('### in LeadId setter: LeadId is '+LeadId);  	 	 
  	}
  } 

If anyone could tell me what I'm doing wrong I'd be very grateful. 

 

 

 

 

  • January 28, 2011
  • Like
  • 0

I'm getting an obscure error in production that doesn't occur in the test methods and doesn't occur in the sandbox.  I want to delete my set of triggers, class  and then the custom object from production and deploy again from the sandbox.  Is there a way to do this without having to archive the code, delete it from the sandbox, deploy the deletions and put it back into the sandbox again?  I would prefer to spare myself the pain and time involved in that!

  • November 20, 2010
  • Like
  • 0

I am getting a very strange error which only occurs in production, not in the Sandbox.  A lead trigger inserts record(s) into a custom object called a Lead Company.  This all works fine in the sandbox but when I test it in production, I get a DML error saying "invalid sobject for queue" on the insert statement.  I'm very puzzled because the test methods work fine.  Has anyone encountered this before?

  • November 20, 2010
  • Like
  • 0

I have a use case where, when a lead is converted, I need to convert all other leads from the same company.  I have a custom object (Lead Company) that the leads are linked to via Lookup.  The Lead Company has a flag Converted__c which is set when a lead is converted, from a lead <before update> trigger and the Lead Company record also then records the Account Id of the converted lead.  There is then a trigger on the Lead Company which detects that the flag has been set and then converts all other leads on that account to contacts.  Or at least, that is what is intended, but I get an error saying that it is recursive, as the conversion process then calls my lead trigger again.

 

So, I understand where the error is coming from, but what I can't work out is how to achieve this objective without the recursion.

 

Can anyone help me with a better solution?

 

Thanks

  • November 08, 2010
  • Like
  • 0

I have written a trigger that extracts certain totals from a custom object when the record is approved and updates some fields on the parent account.  This works fine in the sandbox.  However, I don't know how to go through the approval process from my test method (it is not done in Apex but from the  workflow approval engine in salesforce).  Can anyone explain or show me some sample test method code to help with this?  There is a snippet in the Apex Guide, but it is a single step approval process and our process is a two step process, so I need to:

- submit it for credit approval

- have the credit approver approve it

It then should move on to director approval and I need to

- have the director approve it.

 

So far, I have the following relevant code in the test method (I've set the data etc up earlier in the test method but not included it here so there is less to wade through):

 

		// Create an approval request for the JIS     
		Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
		req1.setComments('Submitting request for approval.');
		req1.setObjectId(JIS1.Id);

		// Submit the approval request for the JIS  
		Approval.ProcessResult result1 = Approval.process(req1);      

		// Verify the results  
		System.assert(result1.isSuccess());
		System.assertEquals('Pending', result1.getInstanceStatus(), 'Instance Status'+result1.getInstanceStatus());

		// Approve the submitted request      

		// First, get the ID of the newly created item    
		List<Id> newWorkItemIds = result1.getNewWorkitemIds();
		
		// Instantiate the new ProcessWorkitemRequest object and populate it  
		    
		Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
		req2.setComments('Approving request.');
		req2.setAction('Approve');
		req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
		
		// Use the ID from the newly created item to specify the item to be worked  
		    
		req2.setWorkitemId(newWorkItemIds.get(0));
		
		// Submit the request for approval  
		    
		Approval.ProcessResult result2 =  Approval.process(req2);
		
		// Verify the results  
		    
		System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());

 

 

 

However, I get a strange error at this line:


        Approval.ProcessResult result1 = Approval.process(req1); 

 

11:58:17.881|EXCEPTION_THROWN|[90,36]|System.DmlException: Process failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, missing required field: []
11:58:17.882|METHOD_EXIT|[90,36]|Approval.process(Approval.ProcessSubmitRequest)
11:58:17.882|FATAL_ERROR|System.DmlException: Process failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, missing required field: []

Class.TestJISApprovalTrigger.JISValuesonAccountTest: line 90, column 36
External entry point

 

I have no idea what required field it is referring to, there is no required field missing in the custom object record I've created.

 

I'd really appreciate some guidance here.

Thanks

I hope this is the correct place to post this, as I can't seem to get any response from support on this.  I've joined the new system log console pilot, but I can't get any data in it at all.  I'm using Firefox and what happens is that the log gets an Unread entry, when I click on the entry, either nothing at all happens (none of the panes are populated) or I then get an error:

 

it says "Salesforce System Error" and shows the code
221574575-9535
(-1278617611)

Not the best start to a pilot...

 

Has anyone got this working?

I have written an application which displays a console-type multi-pane view of accounts, contacts and tasks.  We use a 3rd party application which embeds a VF page into the detail page of accounts and contacts.  My application works beautifully in Firefox and Explorer when I take this VF page out of the detail page layouts, but when it is in the page layouts, the app still works fine in Firefox.  However, in Explorer, it actually causes the display to mess up and display everything in one column, i.e. full width, then says that they are attempting to display a page that requires a salesforce login and goes back to the login page. If I then log in, it displays a blank page with the URL

https://emea.salesforce.com/servlet/servlet.Integration?eid=0032000000W9PER&sfdc.tabName=01r200000002475&lid=01N200000000Q9G&autoMapValues=1&ic=1

which is the link to contact detail page, containing the embedded VF page in question.

 

Can anyone advise on this?  I use a <table> with <td> and <tr> tags to create the multi-pane display.

 

Thanks

When using the get; set; type syntax for a method in my controller:

public Id AccSel {
        get;
        set {
            AccSel = value;
            selectedAcc = accMap.get(AccSel);           
        }
    }

How do I call the method directly from my unit test (to get code coverage)?  The documentation examples all use the other syntax where you have methods like getAccSel and setAccSel, which you can of course call from the test method.  In order to cover this code, do I have to rewrite it with separate getAccSel and SetAccSel methods instead of using automatic properties?

If it is possible, how do I pass the parameter of "value"?

From the VF page I call it using assignTo:
<apex:commandButton value="Refresh List" action="{!resetConts}" rerender="ContactLst, ContDetailpg">
    <apex:param name="AccSel" value="{!selectedAcc.Id}" assignTo="{!AccSel}"/>
</apex:commandButton>

Using
ApexPages.currentPage().getParameters().put('AccSel', ids);
does not call the setter.

Any ideas?

 

Thanks

I need to set a query parameter in a test method.  The documentation makes only a quick reference to this, saying:

To set a query string parameter:

  • If you're writing a custom controller, use the setParameters() method with ApexPages.currentPage() to add a query parameter in a test method. For example:
    String key = 'name';
    String value = 'Caroline';
    ApexPages.currentPage().setParameters().put(key, value);
    Note
     The setParameters() method is only valid inside test methods.

However, when I put this in my test method, I get the error:

 

Save error: Method does not exist or incorrect signature: [System.PageReference].setParameters()    Testm62ConsoleController.cls    /m62 Sandbox/src/classes    line 80    Force.com save problem

 

Here is my test method:

 

 static testMethod void testConsoleController() {

		// Find a telesales user for the tests
        Profile p = [select id from profile where name='Telesales']; 
        User u = new User(alias = 'standt', email='standarduser@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', profileid = p.Id, 
            languagelocalekey='en_US', 
            localesidkey='en_GB', 
            timezonesidkey='Europe/London',
            username='standarduser@testorg.com');


        System.runAs(u) {
         		
		//Set up the data
		List<Account> accs = new List<Account>();
		for (Integer i=0; i<50; i++) {
			Account a = new Account(
				Name = 'Test Account 1',
				BillingCountry = 'United Kingdom',
				Phone = '+44 (0)12679 121 5555',
				To_be_cleansed__c = true
			);
			accs.add(a);
		}
		insert accs;
		
		List<Contact> conts = new List<Contact>();
		List<Task> tasks = new List<Task>();
		// Create two contacts for each account
		for (Integer i=0; i<50; i++) {
			Contact c = new Contact();
			c.FirstName = 'Test';
			c.LastName = 'Contact 1';
			c.AccountId = accs[i].Id;
			c.MailingCountry = 'United Kingdom';
			c.Email = 'no@email11111.com';
			c.Phone = '+44 (0)1423 564888';
			conts.add(c);
		
			Contact c1 = new Contact();
			c1.FirstName = 'Test';
			c1.LastName = 'Contact 1';
			c1.AccountId = accs[i].Id;
			c1.MailingCountry = 'United Kingdom';
			c1.Email = 'no2@email11111.com';
			c1.Phone = '+32 (0) 2 679 12 11';
			conts.add(c1);
			
			// Add a task for each account
			Task t = new Task(WhatId=accs[i].Id, Type='Telephone call', Subject='Test subject', Status='Not started', 
            				Priority='Normal'); 
            tasks.add(t);
		}
	
		insert conts;
		insert tasks;
		
        PageReference pageRef = Page.newConsole;  // Instantiate telesales console page
        Test.setCurrentPage(pageRef);
      
        //Instantiate and construct the controller class.   
        m62ConsoleController controller = new m62ConsoleController();		
		Test.startTest();
		
		controller.selectedAcc = accs[4];
		controller.last();
		if (controller.getHasPreviousAcc()) controller.previousAcc();
		if (controller.getHasNextAcc()) controller.nextAcc();
		
		controller.getMyAccounts();
		controller.first();
		String ids = accs[6].Id;
		ApexPages.currentPage().setParameters().put('AccSel', ids);

		ids = conts[12].Id;
		ApexPages.currentPage().setParameters().put('ConSel', ids);

		controller.resetConts();
		controller.viewCont();
		controller.resetTsks();
		controller.viewTsk();
		
	}
    }

 Can anyone advise what I'm doing wrong? I've searched all over for more information but can't find any.

Thanks.

 

I'm trying to enhance a VF page so that when when an opportunity is selected from a picklist, the contact list on the page is filtered to only show the contacts related via OpportunityContactRole, and vice versa.  I've used actionSupport for this, but the event is not firing. I've put a debug statement into the controller to tell me whether the action method is called, but it is not being called.

 

I can't see that I've done anything different to the examples I've seen, or the actionSupport with the inputField in my code, which is working.  Are there restrictions with being able to use actionSupport from within an action region that is rerendered from another part of the page?

 

Here is the code:

 

<apex:pageBlock title="Call/Meeting Report" mode="edit" id="thePageBlock"> <apex:pageMessages /> <apex:pageBlockButtons > <apex:commandButton value="Save" action="{!save}"/> <apex:commandButton value="Cancel" action="{!cancel}" immediate="true"/> </apex:pageBlockButtons> <apex:pageBlockSection columns="1"> <apex:inputField value="{!Call_Meeting_Report__c.Account__c}" required="true"> <apex:actionSupport event="onclick" action="{!getDetails}" rerender="opps, conts"/> </apex:inputField> <apex:pageBlockSectionItem > <apex:outputLabel value="Opportunity "/> <apex:selectList value="{!Call_Meeting_Report__c.Opportunity__c}" id="opps" size="1"> <!-- here is one of the actionSupports that is not firing --> <apex:selectOptions value="{!Opps}"/> <apex:actionSupport event="onchange" action="{!refreshContacts}" rerender="conts"/> </apex:selectList> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value="Contact "/> <apex:selectList value="{!Call_Meeting_Report__c.Primary_Contact__c}" id="conts" size="1"> <apex:selectOptions value="{!Conts}"/> <!-- here is the other one of the actionSupports that is not firing --> <apex:actionSupport event="onChange" action="{!refreshOpps}" rerender="opps"/> </apex:selectList> </apex:pageBlockSectionItem> <apex:inputField required="true" value="{!Call_Meeting_Report__c.Date__c}" /> <apex:inputField value="{!Call_Meeting_Report__c.Type__c}" required="true"/> <apex:inputField value="{!Call_Meeting_Report__c.Purpose__c}" required="true"/> <apex:inputField value="{!Call_Meeting_Report__c.Other_people_present__c}" style="width: 100%;" required="true"/> <apex:inputField value="{!Call_Meeting_Report__c.Call_Meeting_Objectives__c}" style="width: 100%;" required="true"/> <apex:inputField value="{!Call_Meeting_Report__c.Discussion__c}" style="width: 100%;" required="true"/> <apex:inputField value="{!Call_Meeting_Report__c.Next_actions__c}" style="width: 100%;" required="true"/> <apex:pageBlockSectionItem /> </apex:pageBlockSection> </apex:pageBlock>

 The relevant code in the controller (don't want the post the whole controller, it is quite long):

 

private Id a, newa, OppThere, ContThere; // Initialise the controller public ReportSearchController(ApexPages.StandardController controller) { //initialise the standard controller this.controller = controller; cmr = (Call_Meeting_Report__c)controller.getRecord(); } public void refreshContacts(){ system.debug('### in refreshcontacts'); OppThere = cmr.Opportunity__c; popContlist(OppThere); } public void refreshOpps(){ system.debug('### in refreshopps'); ContThere = cmr.Primary_Contact__c; popOpplist(ContThere); }

 The debug statements never appear in the system log.

 

Can anyone see what I'm doing wrong?

 

Thanks

 

 

 

 

  • February 17, 2010
  • Like
  • 0

I am struggling to set inputfield values from my unit tests.  I have read that I need to do it using

ApexPages.currentPage().getParameters().put(key,value)

 

But I can't work out how to associate the key with the inputfield.  I'm sure I'm missing something basic but have been struggling for days and haven't managed to get the values set.  Do I need to write setters for the inputField, and if so, how do I reference them?

 

Here is the VF code - very simple page:

 

<apex:page standardController="Call_Meeting_Report__c" extensions="ReportSearchController" showHeader="true" sidebar="true" action="{!loadDefaults}">
<apex:form >
<apex:pageBlock title="Call/Meeting Report" mode="edit" id="thePageBlock">
<apex:pageMessages />
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!save}"/>
<apex:commandButton value="Cancel" action="{!cancel}" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="1">
<apex:inputField value="{!Call_Meeting_Report__c.Account__c}" required="true">
<apex:actionSupport event="onChange" action="{!getDetails}" rerender="opps, conts" />
<apex:actionSupport event="onclick" action="{!getDetails}" rerender="opps, conts"/>
</apex:inputField>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Opportunity "/>
<apex:selectList value="{!Call_Meeting_Report__c.Opportunity__c}" id="opps" size="1">
<apex:selectOptions value="{!Opps}"/>
</apex:selectList>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Contact "/>
<apex:selectList value="{!Call_Meeting_Report__c.Primary_Contact__c}" id="conts" size="1">
<apex:selectOptions value="{!Conts}"/>
</apex:selectList>
</apex:pageBlockSectionItem>
<apex:inputField required="true" value="{!Call_Meeting_Report__c.Date__c}" />
<apex:inputField value="{!Call_Meeting_Report__c.Type__c}" required="true"/>
<apex:inputField value="{!Call_Meeting_Report__c.Purpose__c}" required="true"/>
<apex:inputField value="{!Call_Meeting_Report__c.Other_people_present__c}" style="width: 100%;" required="true"/>
<apex:inputField value="{!Call_Meeting_Report__c.Call_Meeting_Objectives__c}" style="width: 100%;" required="true"/>
<apex:inputField value="{!Call_Meeting_Report__c.Discussion__c}" style="width: 100%;" required="true"/>
<apex:inputField value="{!Call_Meeting_Report__c.Next_actions__c}" style="width: 100%;" required="true"/>
<apex:pageBlockSectionItem />
</apex:pageBlockSection>
</apex:pageBlock>

</apex:form>
</apex:page>

 The one I'm initially trying to get work is the Account__c field, but I'll need to do it with Opportunity__c and Primary_Contact__c as well to get the required code coverage.

 

Here is the test method that is (not) setting the value - although the accid parameter is being set, it is not bound to the account__c field:

 

public static testmethod void testloadDefaultsfromAcc() {
/* This is a basic test which simulates the primary positive case for the
load defaults method in the ReportSearchController class. */
Account acc = new Account();
Opportunity o = new Opportunity();
Contact c = new Contact();

setupData(acc, o, c); // inserts an account, contact, opportunity and OpportunityContactRole and relates them all

PageReference pref = Page.NewCallMeetingReport;
pref.getParameters().put('aid', acc.id);
Test.setCurrentPage(pref);

system.debug('@@@ aid '+pref.getParameters().get('aid'));
// Instantiate a new controller
ApexPages.StandardController con = new ApexPages.StandardController(new Call_Meeting_Report__c());

// Switch to runtime context
Test.startTest();
//Construct the ReportSearchController class
ReportSearchController rep = new ReportSearchController(con);

rep.loadDefaults();
Test.stopTest();

}

 

 

 

 If I do a System.AssertEquals on the account id, it always fails as the account is always null.  Please can someone help me regarding how to "put" my test data into the relevant fields?

 

The relevant bit of my controller is here - rather complex because the page is related to 3 objects and I need to detect where it is being called from.

 

 

//add an instance variable for the standard controller
private ApexPages.StandardController controller {get; set;}
// the actual call/meeting report
private Call_Meeting_Report__c cmr {get; set;}
private Id a, newa, OppThere, ContThere;

public List <selectOption> Opps {get; set;}
public List <selectOption> Conts {get; set;}
private String accid;


// Initialise the controller
public ReportSearchController(ApexPages.StandardController controller) {

//initialise the standard controller
this.controller = controller;
cmr = (Call_Meeting_Report__c)controller.getRecord();
this.accid = ApexPages.currentPage().getParameters().get('accid');

}

 

public void loadDefaults() {
Opps = new List<selectOption>();
Conts = new List<selectOption>();
String OppName, ContName;
Boolean fromOpp, fromCont, fromAcc;

a = cmr.Account__c;
fromAcc = (a!=null);
OppThere = cmr.Opportunity__c;
fromOpp = (OppThere != null);
ContThere = cmr.Primary_Contact__c;
fromCont = (ContThere != null);
system.debug('### Account is '+a+' Opp is '+OppThere+' Contact is '+ContThere);
// use some dynamic soql to find the related opportunities / contacts by account name

try {
if (fromAcc){ // populate Opportunity and Contact pulldowns
popOpplist();
popContlist();
} else {
if (fromOpp){
/* We need to 1. populate the Opportunity pulldown with the opportunity name
2. get the Account from the Opportunity and populate the Account field
*/
List <Opportunity> opplist = [Select Id, Account.Name, AccountId, Name from Opportunity where Id =:OppThere];
if (opplist.size() > 0) {
oppName = opplist[0].Name;
cmr.Account__c = opplist[0].AccountId;
a = cmr.Account__c;
system.debug('### setting account to '+cmr.Account__c);
} else {
system.debug('### No opps for '+OppThere+' - impossible?');
oppName = '---None---';
}
system.debug('### Opp already there, adding '+oppName);
Opps.add(new selectOption(OppThere, oppName));
popContlist(OppThere);
} else {
if (fromCont){
/* We need to 1. populate the Contacts pulldown with the Contact name
2. get the Account from the Contact and populate the Account field
*/
List <Contact> contlist = [Select Id, Account.Name, AccountId, Name from Contact where Id =:ContThere];
if (contlist.size() > 0) {
contName = contlist[0].Name;
cmr.Account__c = contlist[0].AccountId;
a = cmr.Account__c;
system.debug('### setting account to '+cmr.Account__c);
} else {
contName = '---None---';
system.debug('### No contacts for '+ContThere+' - impossible?');
}
system.debug('### Contact already there, adding '+ContThere);
Conts.add(new selectOption(contThere, contName));
popOpplist();
}
}
}
}
catch (Exception e) {
System.debug('### error '+e);
ApexPages.addMessages(e);
}


}

 

 

 Would be really grateful for any help.

 

  • February 12, 2010
  • Like
  • 0

I read on the board that the solution to aligning fields using outputLabel and selectOption is to put them inside a pageBlockSectionItem.  However, my code already is inside a pageBlockSectionItem, but is rendering left aligned and with the labels not bold.  I'm using an outputPanel as well, as I'm wondering if that is the problem?

 

Here is version 1 of the code:

 

<apex:page standardController="Call_Meeting_Report__c" extensions="ReportSearchController" showHeader="true" sidebar="true" action="{!loadDefaults}">
<apex:form >
<apex:pageBlock title="Call/Meeting Report" mode="edit" id="thePageBlock">
<apex:pageMessages />
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!save}"/>
<apex:commandButton value="Cancel" action="{!cancel}" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="2">
<apex:inputField value="{!Call_Meeting_Report__c.Account__c}" >
<apex:actionSupport event="onChange" action="{!getDetails}" rerender="Choose" />
<apex:actionSupport event="onkeyup" action="{!getDetails}" rerender="Choose"/>
<apex:actionSupport event="onclick" action="{!getDetails}" rerender="Choose"/>
</apex:inputField>
<apex:inputField value="{!Call_Meeting_Report__c.Date__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Type__c}"/>
<apex:pageBlockSectionItem >
<apex:outputPanel id="Choose">
<apex:outputLabel value="Choose Opportunity "/>
<apex:selectList value="{!Call_Meeting_Report__c.Opportunity__c}" id="opps" size="1">
<apex:selectOptions value="{!Opps}"/>
</apex:selectList>
<p/>
<apex:outputLabel value="Choose Contact "/>
<apex:selectList value="{!Call_Meeting_Report__c.Primary_Contact__c}" id="conts" size="1">
<apex:selectOptions value="{!Conts}"/>
</apex:selectList>
<p/>
</apex:outputPanel>
</apex:pageBlockSectionItem>
<apex:inputField value="{!Call_Meeting_Report__c.Purpose__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Other_people_present__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Discussion__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Next_actions__c}"/>
<apex:pageBlockSectionItem />
</apex:pageBlockSection>
</apex:pageBlock>

</apex:form>
</apex:page>

(Sorry about the tabbing, looks fine in eclipse).

 

I tried putting the outputPanel outside of the pageBlockSectionItems in version 2:

 

 

<apex:page standardController="Call_Meeting_Report__c" extensions="ReportSearchController" showHeader="true" sidebar="true" action="{!loadDefaults}">
<apex:form >
<apex:pageBlock title="Call/Meeting Report" mode="edit" id="thePageBlock">
<apex:pageMessages />
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!save}"/>
<apex:commandButton value="Cancel" action="{!cancel}" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="2">
<apex:inputField value="{!Call_Meeting_Report__c.Account__c}" >
<apex:actionSupport event="onChange" action="{!getDetails}" rerender="Choose" />
<apex:actionSupport event="onkeyup" action="{!getDetails}" rerender="Choose"/>
<apex:actionSupport event="onclick" action="{!getDetails}" rerender="Choose"/>
</apex:inputField>
<apex:outputPanel id="Choose">
<apex:pageBlockSectionItem>
<apex:outputLabel value="Opportunity "/>
<apex:selectList value="{!Call_Meeting_Report__c.Opportunity__c}" id="opps" size="1">
<apex:selectOptions value="{!Opps}"/>
</apex:selectList>
</apex:pageBlockSectionItem>
<p/>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Contact "/>
<apex:selectList value="{!Call_Meeting_Report__c.Primary_Contact__c}" id="conts" size="1">
<apex:selectOptions value="{!Conts}"/>
</apex:selectList>
</apex:pageBlockSectionItem>
<p/>
</apex:outputPanel>
<apex:inputField value="{!Call_Meeting_Report__c.Date__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Type__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Purpose__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Other_people_present__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Discussion__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Next_actions__c}"/>
<apex:pageBlockSectionItem />
</apex:pageBlockSection>
</apex:pageBlock>

</apex:form>
</apex:page>

 but got the same result.  I must be missing something - can anyone advise?

 

 

 

 

  • February 01, 2010
  • Like
  • 0

I have a custom object which has lookup fields to Account and Opportunity.  If the Account is populated, instead of using the standard search popup (which shows all opportunities, not just those belonging to the account), I want to use an Opportunity picklist which is populated with the opportunities belonging to the account whenever the account is selected/changed.  I think actionSupport is the right thing to use for this, but I can't get it to work correctly when creating a new record. It works fine in edit mode, when the account is already populated, but when creating a new record, when the search button next to account is used to pick the account, the event is not triggered (first problem).  If I just click in the account field to trigger the OnClick event, it triggers (I can see this in the system log), but the rerender does not happen.  Can anyone explain this?  I'd prefer to invoke actionSupport without having to click in the Account field, but the rerender is the bit giving me the biggest headache.

 

The page code is as follows:

 

<apex:page standardController="Call_Meeting_Report__c" extensions="OpportunitySearchController" showHeader="true" sidebar="true">
<apex:form >
<apex:pageBlock title="Call/Meeting Report" mode="edit" id="thePageBlock">
<apex:pageMessages />
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!save}"/>
<apex:commandButton value="Cancel" action="{!cancel}" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="2">
<apex:inputField value="{!Call_Meeting_Report__c.Account__c}" >
<apex:actionSupport event="onChange" action="{!getOpportunities}" rerender="ChooseOpp" />
<apex:actionSupport event="onkeyup" action="{!getOpportunities}" rerender="ChooseOpp"/>
<apex:actionSupport event="onclick" action="{!getOpportunities}" rerender="ChooseOpp"/>
</apex:inputField>
<apex:pageBlockSectionItem >
<apex:outputPanel id="ChooseOpp">
<apex:outputLabel value="Choose Opportunity"/>
<apex:selectList value="{!Call_Meeting_Report__c.Opportunity__c}" id="opps" size="1">
<apex:selectOptions value="{!Opportunities}"/>
</apex:selectList>
</apex:outputPanel>
</apex:pageBlockSectionItem>
<apex:inputField value="{!Call_Meeting_Report__c.Type__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Purpose__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Primary_Contact__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Other_people_present__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Next_actions__c}"/>
<apex:inputField value="!Call_Meeting_Report__c.Date__c}"/>
<apex:inputField value="!Call_Meeting_Report__c.Other_people_present__c}"/>
<apex:inputField value="{!Call_Meeting_Report__c.Discussion__c}"/>
<apex:pageBlockSectionItem />
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

 and the controller is:

 

public class OpportunitySearchController {

//add an instance variable for the standard controller
private ApexPages.StandardController controller {get; set;}
// the actual call/meeting report
private Call_Meeting_Report__c cmr {get; set;}
private Id a;

public List <selectOption> Opps;

// Initialise the controller
public OpportunitySearchController(ApexPages.StandardController controller) {

//initialise the standard controller
this.controller = controller;
cmr = (Call_Meeting_Report__c)controller.getRecord();
//this.a = (Account)controller.getRecord();

}

// the results from the search
public PageReference getOpportunities() {
Opps = new List<selectOption>();

a = cmr.Account__c;
system.debug('### Account is '+a);
// use some dynamic soql to find the related opportunities by name
try {
List <Opportunity> opplist = [Select o.Id, o.Name from Opportunity o Where AccountId = :a Order By o.Name];
for (Opportunity u:opplist) {
Opps.add(new selectOption(u.Id, u.Name));
system.debug('### option added -'+u.Name);
}
}
catch (Exception e) {
System.debug('### error '+e);
ApexPages.addMessages(e);
}
return null;

}


}

 

Debug log is showing that the code does get called, but the populated Opportunity pulldown does not appear on the page, which means the rerender isn't happening or I'm doing something else wrong.  Debug log:

 



18.0 DB,INFO;WORKFLOW,INFO;VALIDATION,INFO;CALLOUT,INFO;APEX_CODE,DEBUG;APEX_PROFILING,INFO
19:08:05.661|CODE_UNIT_STARTED|[EXTERNAL]VForcePage
19:08:05.662|USER_DEBUG|[27,9]|DEBUG|### Account is 001T000000Ga6kPIAR
19:08:05.662|SOQL_EXECUTE_BEGIN|[30,33]|Aggregations:0|Select o.Id, o.Name from Opportunity o Where AccountId = :a Order By o.Name
19:08:05.669|SOQL_EXECUTE_END|[30,33]|Rows:2|Duration:7
19:08:05.670|USER_DEBUG|[34,5]|DEBUG|### option added -Crazy Horses Ltd - Test 1
19:08:05.670|USER_DEBUG|[34,5]|DEBUG|### option added -Crazy Horses Ltd - Test 2
19:08:05.670|CODE_UNIT_FINISHED
19:08:05.672|VF_APEX_CALL|j_id36|{!getOpportunities}|PageReference: none
19:08:05.692|CODE_UNIT_STARTED|[EXTERNAL]VForcePage
19:08:05.692|CODE_UNIT_STARTED|[EXTERNAL]VForcePage
19:08:05.692|USER_DEBUG|[27,9]|DEBUG|### Account is 001T000000Ga6kPIAR
19:08:05.692|SOQL_EXECUTE_BEGIN|[30,33]|Aggregations:0|Select o.Id, o.Name from Opportunity o Where AccountId = :a Order By o.Name
19:08:05.702|SOQL_EXECUTE_END|[30,33]|Rows:2|Duration:10
19:08:05.702|USER_DEBUG|[34,5]|DEBUG|### option added -Crazy Horses Ltd - Test 1
19:08:05.703|USER_DEBUG|[34,5]|DEBUG|### option added -Crazy Horses Ltd - Test 2
19:08:05.703|CODE_UNIT_FINISHED
19:08:05.703|CODE_UNIT_FINISHED

 Any help would be greatly appreciated -

Erica

 

 

 

  • January 29, 2010
  • Like
  • 0

I modified an Apex class which was written by a contractor, to add an additional field to the class, using the Eclipse IDE.  When I then generated a new WSDL in salesforce, instead of just producing a WSDL for the class, it produced what looks like the Enterprise WSDL as well as my class.  Does anyone know why, and how I can correct this?  We are using the Partner WSDL in the code.

 

Secondly, the website doesn't seem to be loading the new WSDL as the additional field that all this trouble was for, is not being populated. I've checked the PHP test page and can't see anything wrong with it, but when we print the object, the new field does not appear.

 

I don't know if these two problems are related, has anyone else experienced something similar? Test page code below:

 

<body>

<?PHP

require_once ('sfdc/SforcePartnerClient.php');
require_once ('sfdc/SforceHeaderOptions.php');

// virtual user system admin
$sfdcUsername = "xxxxxxxxxxx";
$sfdcPassword = "yyyyyyyyyyyyyy";
$sfdcToken = "zzzzzzzzzzzzzz";

//$emailToFetch = "fetchbyemail@noemail.com";
$emailToFetch = "jobyrblume@hotmail.com";
//echo $emailToFetch;

$sfdc = new SforcePartnerClient();
$SoapClient = $sfdc->createConnection("sfdc/partner.wsdl.xml");
$loginResult = false;
$loginResult = $sfdc->login($sfdcUsername, $sfdcPassword.$sfdcToken);

$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_WS_NAME_", "SubscriptionService");
define ("_WS_WSDL_", "sfdc/" . _WS_NAME_ . ".wsdl.xml");
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);

// SOAP Client for Web Service
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));

try {
$wsParams=array('email'=>$emailToFetch);
$response = $client->fetchByEmail($wsParams);
// set a variable to store how many results were returned
$resultsSize = sizeOf($response->result);

$id = $response->result->id;
$firstName = $response->result->firstName;
$lastName = $response->result->lastName;
$company = $response->result->company;
$country = $response->result->country;
$email = $response->result->email;
$phone = $response->result->phone;
$newsletter = $response->result->newsletter;
$slides = $response->result->slides;
$whitepapers = $response->result->whitepapers;
$events = $response->result->events;
$speialOffers = $response->result->specialOffers;
$weeklyDigest = $response->result->weeklyDigest;
$subsChanged = $response->result->subsChanged;
$sObjectType = $response->result->sObjectType; // this will either be 'Contact' or 'Lead'
$error = $response->result->error;
$errorMessage = $response->result->errorMessage;
echo '<p>Name: '.$firstName.'</p>';
echo '<p>Subs changed: '.$subsChanged.'</p>';

} catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Ooop! Error: <b>" . $errors . "</b>"; // fatal exception. log it to somewhere or send email
die;
}

if ($resultsSize == 1) {
if ($response->result->error == 1) { ?>
<p>There were no results returned for the address <? echo $emailToFetch ?></p>
<p>Please check and try again</p>
<form action="<? $_SERVER['PHP_SELF'] ?>" method="post" class="subs-form">
<input name="subscription_address" id="subscription_address" type="text" size="30"/><input type="submit" name="submit" value="Submit" class="contact-button"/>
</form>
<p>If the form is unable to return your subscription please <a href="#">contact us</a></p>
<?
} else {
print_r($response);
}
} else { // Multiple Results!!!?>
<p>There were <? echo $resultsSize; ?> results returned for the email address <? echo $response->result[0]->email; ?></p>
<p>Please enter your personal details to select your record.</p>

<?
}
?>


</body>

 The class looks like this:

 

global class Subscriber {

webservice String id;
webservice String firstName;
webservice String lastName;
webservice String company;
webservice String country;
webservice String email;
webservice String phone;
webservice Boolean newsletter;
webservice Boolean slides;
webservice Boolean whitepapers;
webservice Boolean events;
webservice Boolean specialOffers;
webservice Boolean weeklyDigest;
webservice Date subsChanged;
webservice String sObjectType;
webservice Boolean error;
webservice String errorMessage;

}

 

 subsChanged is the new field in there.  The class passes the test methods and appears to be sitting happily in salesforce, before I made this change, everything was working happily.

 

I'd be really grateful for any advice.  This is my first foray into Apex web services and so far it isn't a happy one!

 

Erica

 

 

 

I'm new to VF, coming from scontrols.  I have some custom objects related to Opportunities which can each have tasks related to them.  The salesguys want to see one list of tasks, no matter which of the custom objects or indeed the Opportunity itself they are related to.  I've been trying to write a list controller for tasks with no luck at all.  I know there is no standard controller for listing tasks but is there any reason why a custom controller would not work?  Does anyone have some template code I could use as I'm new to Apex as well and I can't get my code accepted by the IDE?

Apex Code is as follows (still needs the query to be filtered but am trying to get proof of concept first):

 

public class OppTasks { public ApexPages.StandardSetController setCon { get { if(setCon == null) { setCon = new ApexPages.StandardSetController(Database.getQueryLocator([Select WhatId, Subject, Status, OwnerId, Id, Description, ActivityDate From Task])); } return setCon; } set; } public List<Task> getActivities() { return (List<Task>) setCon.getRecords(); } }

 Visualforce page:

 

<apex:page controller="OppTasks"> <apex:form > <apex:pageblock id="thePage"> <apex:pageblocktable value="{!activity}" var="t" > <apex:column value="{!t.Subject}"/> <apex:column value="{!t.WhatId}"/> <apex:column value="{!t.Status}"/> <apex:column value="{!t.ActivityDate}"/> </apex:pageblocktable> </apex:pageblock> </apex:form> </apex:page>

 I have tried a variety of values  including {!tasks}, I get the error "Unknown property OppTasks.activity".

 

Can anyone help a newbie?  Many thanks - Erica

 

 

 

 

  • February 25, 2009
  • Like
  • 0
Please can someone help me with a frustrating problem.  I have installed the latest Eclipse (Europa) IDE and all works fine except that I can't print.  The print button is greyed out.  Can anyone help? I'm running on XP. I've seen the problem reported by others when I've googled it, but can't find a solution.

Thanks,
Erica
  • March 19, 2008
  • Like
  • 0
I have a custom Invoice object which gets a related Case created if the invoice goes overdue.  That works fine.  Now, we want to stop the invoice from being edited by anyone except users from a particular profile, once the invoice has a related Case.  If I use the standard button override, I end up with a recursive loop because I'm trying to use the standard edit functionality (when they are allowed to edit), so it keeps calling my scontrol.  Current (bad) code is as follows:
Code:
function EditInvoice() {
  var IsCase ="{!m62_Invoice__c.Case_Number__c}";
  var TopDog = false;
  var _profile = "{!$Profile.Name}";
  if  ((_profile == "Financial Controller") || (_profile == "System Administrator")){
    TopDog = true;
  }
alert("Profile is " + _profile + " topdog is " + TopDog);
  
  var retURL= escape("/{!m62_Invoice__c.Id}");
  if ((IsCase == "") || TopDog) {  // No Case been created OR profile is that of financial controller or Sysadmin
    parent.location.href = retURL+"/e";   
  } else {
    alert ("You cannot edit the invoice once a Case has been added");
    parent.location.href = retURL;
  }
}

Using retURL + "/e" simply causes the function to be called again and again forever if the conditions are met, so it is obviously not the way to do it.

Basically I want to avoid rewriting all the edit functionality but stop certain users from editing the record under certain conditions (i.e. once a case has been created and if the user is not from a named profile).

Does anyone have any ideas to help me here?

Thanks,
Erica

  • January 23, 2008
  • Like
  • 0
I have written the following code:
Code:
function GetProductLineItems(OppId) {
 
 var i=0;
 var ProdName = "";
 var _Query = "Select o.TotalPrice, o.PricebookEntry.Name From OpportunityLineItem o WHERE  o.OpportunityId='" + OppId + "'";
 var queryResult = sforce.connection.query(_Query);
 var lineItemList = queryResult.getArray("records"); 
 
 var JIS = new sforce.SObject("Job_Information_Sheet__c"); //create JIS sobject
    

 if (lineItemList.length > 0) {
// Initialise values that will be grouped
   JIS.Background_Value__c = 0;
   JIS.Training_value__c = 0;
   JIS.Messaging_Value__c = 0;
   JIS.Movie_value__c = 0;
   JIS.Slide_Production_Value__c = 0;
   JIS.Other_Value__c = 0;

  for (i=0; i<lineItemList.length; i++) { 
     ProdName  = lineItemList[i].get("PricebookEntry.Name");
alert("Product is "+ProdName);
     switch(ProdName) {

 However, ProdName always comes up null and when I do the query in the Eclipse Explorer, the results give me a value for the TotalPrice but in the PricebookEntry column it just shows "PricebookEntry", which I have to click on to see the pricebookentry name.  I want to copy the prices to fields in a custom object but the field to copy to depends on what the pricebook entry is, hence the switch statement and the need to extract the product (pricebookentry) name.

Can anyone tell me how to code it to traverse into the pricebookentry and extract the name?  I've tried a few approaches and none of them work.

Many thanks,
Erica



  • January 16, 2008
  • Like
  • 0
I'm trying to populate a search picklist so that only relevant values are displayed. The user is viewing an invoice (custom object) and may want to add the invoice to an existing Case or create a case if no cases exist for that account.  I can't find a way to populate the salesforce search popup.  I have some rather muddled code at the moment I'm posting below, I know it is wrong because the Option property is probably not relevant to the picklist, but I'm at a loss and would really value some guidance here.  I know this can't work in edit mode but they don't need to be in edit mode, the scontrol is invoked from a button on the detail view page.

Code:
function GetCaseList(AccountID) {
   var strSQL="Select CaseNumber From Case where AccountId = '" + AccountID+"'";
   var result = sforce.connection.query(strSQL);
   if (result.getBoolean("success")) { //if successful 
 var records = result.getArray("records");
 var _Caselist = document.getElementById('CF00N20000001CqW7'); // URL of Case picklist window
 _Caselist.options.length = 0;
 i=0;
 while ( i<records.length) {
    var _case = records[i].CaseNumber;
           _Caselist.options[i] = new Option(_case);
           i++;
        }
        var retURL= escape("/{!m62_Invoice__c.Id}");
        parent.location.href = retURL;
  
    } else {
        alert("No records returned for this account.\n\nCreate a new Case.\n\nClick OK to refresh."); //alert note
    }


}
I'd really appreciate some guidance here -

Thanks,
Erica

  • October 31, 2007
  • Like
  • 0
I have experienced what has to be a bug in code coverage storage in salesforce.  I had 95% coverage of a class but when checking it, realised I could get complete coverage by adding another test method, which I did.  Now salesforce will only report the coverage from the last method run, although it states that all 5 methods have been passed!  What do I do now? I won't be able to deploy my code, which has to be deployed today to production.  It is reporting 59% because that it what the additional method (the only one it is now counting) covers.
When I look in the developer console at the test results, clicking on each method aside from the newest one shows blank in the code coverage pane.  I'm trying to run the tests again from the IDE instead of the Developer Console, but it is hanging as Not Responding.  The sandbox is a full sandbox on cs12. Has anyone else encountered this?
Hi All,

I've written a trigger for Orders where whenever I send an email through the Order the status in the order from 'draft' will become 'sent'. And it works like a charm. My trigger is :
 
trigger TaskTrigger on Task (after insert) {
    List<Order> ordersToUpdate = new List<Order>();

    for(Task t : Trigger.new) {
        if(t.WhatId.getSObjectType() == Order.sObjectType 
            && t.Subject.startsWith('Email:')) {
                ordersToUpdate.add(new Order(Id = t.WhatId, Status = 'Sent'));
        }
    }

    update ordersToUpdate;
}

My problem is with the test class. After modifying my calss alot of times I came to a result where System.AssertException: Assertion Failed: Expected: Sent, Actual: draft

My class is 
@isTest
   public class Test7{
    public static testmethod void TaskTrigger_Test1()
    {
             Account a = new Account(Name = 'Test');
        insert a;     

        Id pricebookId = Test.getStandardPricebookId();                         

        Product2 prd1 = new Product2 (Name='Test Product Entry 1',Description='Test Product Entry 1', isActive = true);
        insert prd1;

        PricebookEntry pe=new PricebookEntry(UnitPrice = 1,Product2Id=prd1.id,Pricebook2Id=pricebookId,isActive=true);
        insert pe;

        Order o = new Order(name='Test1',AccountId=a.id,EffectiveDate=system.today(),status='draft', PriceBook2Id=pricebookId);
        insert o;

        OrderItem oi = new OrderItem(OrderId=o.id,Quantity=1,PricebookEntryId=pe.id, unitPrice=1);
        insert oi;


        Task t = new Task(whatid=o.id,Priority = 'normal',status='open',subject='Email:xxxx');
        insert t;
        
        system.assertequals('Sent',o.status);
    }


}

 

Hi,

 

I have a approval process, i want to include the comments also as a part of the email. From a lilttle searching i found that SF doesnt allow it.

Is it true? Are there any workarounds for this?

 

Thanks

Prady

  • June 28, 2011
  • Like
  • 0

I just updated a class to use the new URL class.  When I ran the test class and deployed it to production, it showed as 100% code coverage for ALL code in the IDE, although it should not have done, since it doesn't actually call all of my code.  However, in the Sandbox itself, the code coverage was way down, because it was counting blank lines and commented out code as not being covered!  So the same code is reported as 100% covered in the IDE and 83% in the sandbox from the Apex Classes link.

 

Has anyone else noticed this?  It appears to have happened today, since the summer 11 roll-out to production.  I did not have this issue when my sandbox was summer 11 and my production was spring 11, although I haven't deployed any code for a couple of weeks.

 

Salesforce, what's happening?

I have been bashing away at this without success all day and obviously am missing something.  I have a VF page which shows a list of custom objects called Lead Companies, which we use to tie leads from the company together. When a user clicks on one of the lead companies in the list, it displays a list of related leads in another pane (a table cell) on the page.  This works perfectly.

 

When clicking on one of leads, I want to open a new window with the standard salesforce lead detail view.  That way, I don't need to code the page and if there are permissions issues (my page needs to run in system mode), it will be taken care of. 

 

I use a Javascript function to pop up the window.  This works fine from a different part of the page which does something similar (but not the same) for accounts.  However, with the lead, it does not appear to run the setter to get the lead id from the param tag until AFTER calling the Javascript function.  From reading all the docs I can find, it should work.  However I know from previous experience that I must be missing something that will be obvious to those casting a fresh eye over this, so thanks in advance.

 

Javascript function - the alert shows a blank AnyId although the debug log shows that the setter is being called, but it only shows up in the log AFTER I've pressed OK on the alert:

 

<script type="text/javascript">
  function pop(AnyId) {
    var myWindow;
    alert('Id is '+AnyId);
    myWindow = window.open('/'+AnyId,'','width=550,height=550,scrollbars=yes');
  }
 </script>

 Relevant part of Visualforce page:

 

<apex:pageBlock title="Leads in Lead Company" id="leadDetails">    <apex:pageBlockTable value="{!relatedLeads}" var="leads">	    
  <apex:column headerValue="Name"> 
    <apex:commandLink value="{!leads.Name}" onclick="pop('{!LeadId}');" > 
      <apex:param name="LeadId" value="{!leads.Id}" assignTo="{!LeadId}" />
    </apex:commandLink>                
  </apex:column> 
... other columns ...
</apex:pageBlockTable>
</apex:pageBlock>

Controller code:

 

  public String LeadId { 
    get ;
    set {
      LeadId =  '/'+value; 
system.debug('### in LeadId setter: LeadId is '+LeadId);  	 	 
  	}
  } 

If anyone could tell me what I'm doing wrong I'd be very grateful. 

 

 

 

 

  • January 28, 2011
  • Like
  • 0

I'm getting an obscure error in production that doesn't occur in the test methods and doesn't occur in the sandbox.  I want to delete my set of triggers, class  and then the custom object from production and deploy again from the sandbox.  Is there a way to do this without having to archive the code, delete it from the sandbox, deploy the deletions and put it back into the sandbox again?  I would prefer to spare myself the pain and time involved in that!

  • November 20, 2010
  • Like
  • 0

I am getting a very strange error which only occurs in production, not in the Sandbox.  A lead trigger inserts record(s) into a custom object called a Lead Company.  This all works fine in the sandbox but when I test it in production, I get a DML error saying "invalid sobject for queue" on the insert statement.  I'm very puzzled because the test methods work fine.  Has anyone encountered this before?

  • November 20, 2010
  • Like
  • 0

I'm about to pull my hair out, so would really appreciate it if someone could help me see the simple mistake I must be making here.  I have a trigger that works perfectly when I perform manually the same steps I have written into the unit test.  I thought maybe it was that my trigger is a before update trigger, so I added some extraneous updates after the update in this test, but that didn't help.  And, when I do the updates manually exactly as in this unit test, it works, without extraneous follow-on updates.

 

Here's the trigger:

 

 

trigger searchZipCode on Account (before update) {

    // For each Account in the Trigger.new list of Accounts
    for (Account a : Trigger.new) {
        // check if the BillingPostalCode field is contained in the list of zips
        try {
            if (a.BillingPostalCode != NULL){
                if (a.ZipSearchList__c.contains(a.BillingPostalCode.substring(0,5)))
                {
                    a.ZipFound__c = TRUE;
                } else a.ZipFound__c = FALSE;
            }
        } catch (System.NullPointerException e) {
            system.debug(e.getMessage());
            a.ZipFound__c = FALSE;        
        } finally {
            // do nothing     
        }           
 }
}

 

 

 

Here's the unit test:

 

 

@isTest
private class searchZipCodeTest {

    static testMethod void testsearchZipCode() {
        String ziplist = '12345, 67890';
        String successZip = '12345';
        String failZip = '66666';
        
        Account successAccount = new Account(
            Name = 'Success University',
            // RecordType = '012A00000004OUY',
            Type = 'Graduate Institution',
            BillingPostalCode = successZip,
            ZipFound__c = FALSE
        );
        
        Account failAccount = new Account(
            Name= 'Fail University',
            // RecordType = '012A00000004OUY',
            Type = 'Graduate Institution',
            BillingPostalCode = failZip,
            ZipFound__c = FALSE
         );
        insert new Account[] { successAccount, failAccount };
 
        successAccount.ZipSearchList__c = ziplist;
        failAccount.ZipSearchList__c = ziplist;
        update successAccount;
        update failAccount;
        
        Test.StartTest();
        System.assertEquals('12345', successAccount.BillingPostalCode);
        System.assertEquals('12345, 67890', successAccount.ZipSearchList__c);
// This is the assert that fails:
System.assertEquals(TRUE, successAccount.ZipFound__c); System.assertEquals(FALSE, failAccount.ZipFound__c); Test.StopTest(); } }

 

 

 

Here's the error message:

 

I have a use case where, when a lead is converted, I need to convert all other leads from the same company.  I have a custom object (Lead Company) that the leads are linked to via Lookup.  The Lead Company has a flag Converted__c which is set when a lead is converted, from a lead <before update> trigger and the Lead Company record also then records the Account Id of the converted lead.  There is then a trigger on the Lead Company which detects that the flag has been set and then converts all other leads on that account to contacts.  Or at least, that is what is intended, but I get an error saying that it is recursive, as the conversion process then calls my lead trigger again.

 

So, I understand where the error is coming from, but what I can't work out is how to achieve this objective without the recursion.

 

Can anyone help me with a better solution?

 

Thanks

  • November 08, 2010
  • Like
  • 0

Hi All,

 

I just found this link to a salesforce manual for the debug log:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_debugging_system_log_console.htm

 

My log doesn't look anything like this. I only have 3 secions:

 

- Filter Details (hidden by defaul)

- Execute Apex

- Logs

 

Is the link above pointing to a more recent/out-of-date version?

 

TIA