• notsosmart
  • NEWBIE
  • 25 Points
  • Member since 2012

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 27
    Questions
  • 13
    Replies

My procedure needs to filter out converted leads from my lookups.  I've noted that the Lead status field piciklist includes a 

field Labeled Converted but I don't know the coding reference for my SOQL statement.

 

If I filter by the status values that are checked as converted, it still gets one that is not checked on the status.  

 

Id like to understand how this work anyway in order to write clean code because I'm thinking there is another reference that is more reliable.

 

Thanks.

I'm having a problem referencing the class fields (Street, City, etc) of address fields named something other than just address. Ie BillingAddress.  

 

When I use BillingAddress.Street it result in:

 

Didn't understand relationship 'BillingAddress' in field path.

 

Do you know what I'm missing here?  Thanks

.I'm getting the above referenced error on all methods in my test method..

 

Excerpt from the test method:

/**
* Purpose : This class contains unit tests for the Conversion controller.
*/
@isTest(seeAllData=true)
private class Test_ConvertAccounts_Devt{

private static ApexPages.StandardController ctl;
private static ConvertAccountsDev ext;
private static ApexPages.StandardController ctlWithData;
private static ConvertAccountsDev extWithData;

private static Account a; 

private static Account account;
private static Account myAccount;
private static List<AccountLineItem> ail;

static{

//Build mock data
setupReportWithItem();


//Instantiate and empty controller.
ctl = new ApexPages.StandardController(new Account());


//Instantiate a full controller.
ctlWithData = new ApexPages.StandardController(a);
extWithData = new ConvertAccountsDev(ctlWithData);
extWithData.isDone = false;

//Added....
ext = new ConvertAccountsDev(ctlWithData);

system.debug('**********************************');
system.debug('ctlWithData&colon; ' + ctlWithData);
system.debug('ext: ' + ext);
system.debug('**********************************');

account = new Account();
myaccount = new Account();


} // End

 

/// the page reference call segment:

 

static testMethod void CanTestExit(){

PageReference xit = ext.Exit();

} // End

 

-----------

 

There I get the failure for:

 

System.NullPointerException: Attempt to de-reference a null objectClass.Test_ConvertAccounts_Devt.CanTestExit: line 107, column 1

 

 

Any ideas?  Thanks.

In an Apex batch process, I am s creating record of a new RecordType that is a consolidation of 2 existing RecordTypes of  each Account record.

 

It is functioning properly EXCEPT it's not getting the Related Lists.  I presume that it would require specific code to address it but,  for instance,  to populate the Related Contacts, I used:

 

Note - The item.Accounts is the source record List which includes Account.Contacts in the query,  myAccount is the new record being created.

 

myAccount.Contacts = item.Account.Contacts;     I got the error  -  field is not writable.

 

I tried     myAccount.Contacts.Id = 'xx';   -  ( xx is just to test the reference) which resulted in  the error  -   Invalid foreign key relationship.

 

Any ideas on how this would be populated?

 

 

I have a test method for a custom lookup which works fine interactively.  My coverage is 97% on the test method but only 8% for the overall total.  I noted that some managed packages are being covered at very low %'s causing this.

 

The packages are:

 

Inline image 1

 

Is there a way to have them excluded from the test?

 I did not see anything under annotations for this.

Do you know how I could find out the repercussions of doing so>

 

Do you know if the overall Total not passing but the individual method does will cause it to not be able to deploy.

I'm getting this message on my test method for a custom lookup.  It's also commented in the code above line 56.

 

It appears to me that I'm using the same concept a the call to save Contact that works.  The code test out fine interactively.

 

Any clues?  Thanks.

 

THE TEST METHOD IS:

 

/* Purpose : This class contains unit tests for the Custom Lookup.
*/
@isTest(seeAllData=true)
private class test_CustomContactLkpCntl {

public static testMethod void test_CustomContactLkpCntl() {

//Use the PageReference Apex class to instantiate a page

PageReference pageRef = Page.CustomContactLookup;

//In this case, the Visualforce page named Custom...Lookup is the starting point of this test method.

Test.setCurrentPage(pageRef);

//Instantiate and construct the controller class.

customContactLookupController controller = new customContactLookupController();

//Instantiate a new controller with all parameters in the page
controller = new customContactLookupController();

contact c = new Contact();

//calling an Action method. Same as calling any other Apex method.
//Normally this is executed by a user clicking a button or a link from the Visualforce
//page, but in the test method, just test the action method the same as any
//other method by calling it directly.

//get parameters to page URL
ApexPages.currentPage().getParameters();

//The .getURL will return the page url the Search method returns.

controller.searchString = null;
// String srchPage = controller.search().getUrl();
// System.assertEquals('/apex/customcontactlookup', srchPage);

//Example of calling the 'setter' method for several properties.
//but in a test method, just call the setter method directly.

controller.Contact.LastName = 'Test Last Name';
controller.Contact.FirstName = 'Test First Name';

String newPage = controller.saveContact().getUrl();

//Verify that the success page displays
System.assertEquals('/apex/customcontactlookup', newPage);

controller.contact.Description = 'Test Desc';
String editPage = controller.saveContact().getUrl();

//Verify that the success page displays
System.assertEquals('/apex/customcontactlookup', editPage);
// Next line ERROR - System.NullPointerException: Attempt to de-reference a null object
String srchPage = controller.search().getUrl();
System.assertEquals('/apex/customcontactlookup', srchPage);

}
}

 

THE CONTROLLER IS:

 

public with sharing class CustomContactLookupController {

public CustomContactLookupController(ApexPages.StandardController controller) {

}

public Contact contact {get;set;} // new account to create
public List<Contact> results{get;set;} // search results
public string searchString{get;set;} // search keyword
public Boolean IsNew { get; set; }
public String NewTitle { get; set; }

public CustomContactLookupController() {
contact = new Contact();

IsNew = true;
NewTitle = 'Add';

results = new List<Contact>();
// get the current search string
// chgd to below searchString = System.currentPageReference().getParameters().get('lksrch');
searchString = '';
runSearch();
}

// performs the keyword search
public PageReference search() {
runSearch();
return null;
}

// prepare the query and issue the search command
private void runSearch() {
// TODO prepare query string for complex serarches & prevent injections
results = new List<Contact>();
results = performSearch(searchString);
}

// run the search and return the records found.
private List<Contact> performSearch(string searchString) {

String soql = 'select id, Name, Account.Id, Account.Name, Title, Email from contact';
if(searchString != '' && searchString != null)
soql = soql + ' where name LIKE \'%' + searchString +'%\'';
soql = soql + ' limit 25'; // 100';
System.debug(soql);
return database.query(soql);

}

// save the new contact record
public PageReference saveContact() {
if (IsNew == true)
{
insert contact;
IsNew = false;
NewTitle = '* EDIT New Contact *';
}
else
{
upsert contact;
}

searchString = Contact.FirstName = ' ' + Contact.LastName;
runSearch();
return Page.CustomContactLookup;
}

// used by the visualforce page to send the link to the right dom element
public string getFormTag() {
return System.currentPageReference().getParameters().get('frm');
}

// used by the visualforce page to send the link to the right dom element for the text box
public string getTextBox() {
return System.currentPageReference().getParameters().get('txt');
}


}

My test method fails due to a null pointer exception but this does no hapen in the UI runtime.

 

I get this both on the Save Method and Save Override.  If I can fix the Save then I'm sure I can apply it to the override.

 

This is a custom Lookup with a New/Add function.

 

The Test Method  -  the error is noted in a comment above the line.  I also had trouble with the runsearch at the end.

 

Any ideas?  Thanks.

 

/**
* Purpose : This class contains unit tests for the Trip Report controller extension.
*/
@isTest(seeAllData=true)
private class Test_CustomCampaignLkpCtrl{

private static ApexPages.StandardController ctl;
private static CustomCampaignLookupController ext;
private static ApexPages.StandardController ctlWithRecord;
private static CustomCampaignLookupController extWithRecord;

private static User mockAdminUser;

private static Campaign r;


static{

TripRptTestDataUtilityLib.getActiveAdminUserId();

//Build mock data
// setup With Item();

//Instantiate and empty controller.
ctl = new ApexPages.StandardController(new Campaign());

//Instantiate a full controller.
ctlWithRecord = new ApexPages.StandardController(r);
extWithRecord = new CustomCampaignLookupController(ctlWithRecord);
extWithrecord.isNew = true;


ext = new CustomCampaignLookupController(ctlWithRecord);


system.debug('**********************************');
system.debug('ctlWithRecord: ' + ctlWithRecord);
system.debug('extWithRecord: ' + extWithRecord);
system.debug('**********************************');


} // End

public Campaign campaign {get;set;} // new campaign to create
public List<Campaign> results{get;set;} // search results
public string searchString{get;set;} // search keyword

static testMethod void CanTestSaveOverride(){
String saveUrl = ext.SaveCampaign().getUrl();

}

static testMethod void CanTestSave(){
// Campaign c = new Campaign();
//Run the save() and verify:
//1: modified Report and Items
//2: Redirect URL matches the detail page for new report.
// Populate record.
Campaign extRecord = new Campaign();
extRecord = [select id, name from Campaign LIMIT 1];

extRecord.Name = 'Test Method Name';
extRecord.Description = 'Test Meth Desc';
//ERROR System.NullPointerException: Attempt to de-reference a null object Class.Test_CustomCampaignLkpCtrl.CanTestSave: line 67, column 1
extWithRecord.SaveCampaign();

//Verify the Url after the save() method occurred. chg from .Save()
String saveUrl = ext.SaveCampaign().getUrl();
system.debug( 'Save URL: ' + saveUrl );
// system.debug( 'Detail URL: ' + extWithRecord.controller.view().getURL() );

//ERROR not visible ext.runSearch();

}
} // End Class

 

The Controller:

 

/**
* Purpose : This class contains unit tests for the Custom Lookup.
*/
@isTest(seeAllData=true)
private class Test_CustomCampaignLkpCtrl{

private static ApexPages.StandardController ctl;
private static CustomCampaignLookupController ext;
private static ApexPages.StandardController ctlWithRecord;
private static CustomCampaignLookupController extWithRecord;

private static User mockAdminUser;

private static Campaign r;


static{

TripRptTestDataUtilityLib.getActiveAdminUserId();

//Build mock data
// setup With Item();

//Instantiate and empty controller.
ctl = new ApexPages.StandardController(new Campaign());

//Instantiate a full controller.
ctlWithRecord = new ApexPages.StandardController(r);
extWithRecord = new CustomCampaignLookupController(ctlWithRecord);
extWithrecord.isNew = true;


ext = new CustomCampaignLookupController(ctlWithRecord);


system.debug('**********************************');
system.debug('ctlWithRecord: ' + ctlWithRecord);
system.debug('extWithRecord: ' + extWithRecord);
system.debug('**********************************');


} // End

public Campaign campaign {get;set;} // new campaign to create
public List<Campaign> results{get;set;} // search results
public string searchString{get;set;} // search keyword

static testMethod void CanTestSaveOverride(){
String saveUrl = ext.SaveCampaign().getUrl();

}

static testMethod void CanTestSave(){
// Campaign c = new Campaign();
//Run the save() and verify:
//1: modified
//2: Redirect URL matches the detail page for new report.
// Populate record.
Campaign extRecord = new Campaign();
extRecord = [select id, name from Campaign LIMIT 1];

extRecord.Name = 'Test Method Name';
extRecord.Description = 'Test Meth Desc';
//ERROR System.NullPointerException: Attempt to de-reference a null object Class.Test_CustomCampaignLkpCtrl.CanTestSave: line 67, column 1
extWithRecord.SaveCampaign();

//Verify the Url after the save() method occurred. chg from .Save()
String saveUrl = ext.SaveCampaign().getUrl();
system.debug( 'Save URL: ' + saveUrl );
// system.debug( 'Detail URL: ' + extWithRecord.controller.view().getURL() );

//ERROR not visible ext.runSearch();

}
} // End Class

 

The Page:

 

<apex:page controller="CustomCampaignLookupController"
title="Search"
showHeader="false"
sideBar="false"
tabStyle="campaign"
id="pg">

<apex:form >
<apex:pageMessages />
<apex:outputPanel id="page" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
<apex:tabPanel switchType="client" selectedTab="name1" id="tabbedPanel">

<!-- SEARCH TAB -->
<apex:tab label="Search" name="tab1" id="tabOne">

<apex:actionRegion >
<apex:outputPanel id="top" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
<apex:outputLabel value="Search" style="font-weight:Bold;padding-right:10px;" for="txtSearch"/>
<apex:inputText id="txtSearch" value="{!searchString}" />
<span style="padding-left:5px"><apex:commandButton id="btnGo" value="Go" action="{!Search}" rerender="searchResults"></apex:commandButton></span>
</apex:outputPanel>

<apex:outputPanel id="pnlSearchResults" style="margin:10px;height:350px;overflow-Y:auto;" layout="block">
<apex:pageBlock id="searchResults">
<apex:pageBlockTable value="{!results}" var="a" id="tblResults">
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Name</apex:outputPanel>
</apex:facet>
<apex:outputLink value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Name}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Name}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Active</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.isActive}','{!a.Id}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.isActive}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Type</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Type}','{!a.Id}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Type}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Description</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Description}','{!a.Id}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Description}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Expected Revenue</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.ExpectedRevenue}','{!a.Id}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.ExpectedRevenue}</apex:outputLink>
</apex:column>

</apex:pageBlockTable>
</apex:pageBlock>
</apex:outputPanel>
</apex:actionRegion>

</apex:tab>

<!-- NEW campaign TAB -->
<apex:tab label="New campaign" name="tab2" id="tabTwo" onclick="rerender">

<apex:pageBlock id="newcampaign" title="{!NewTitle}" >

<apex:pageBlockButtons location="top" >
<apex:commandButton action="{!savecampaign}" value="Save"/>
</apex:pageBlockButtons>

<apex:pageBlockSection title="Campaign Information" columns="2">
<apex:inputField value="{!campaign.Name}" required="true" rendered="{!IsNew}"/>
<apex:outputField value="{!Campaign.Name}" rendered="{!NOT(IsNew)}"/>
<apex:inputField value="{!campaign.Status}"/>

<apex:inputField value="{!campaign.isActive}"/>

<apex:inputField value="{!campaign.Type}"/>
<apex:inputField value="{!campaign.Description}"/>
</apex:pageBlockSection>

<apex:pageBlockSection title="Planning" columns="2" >
<apex:inputField value="{!campaign.StartDate}"/>
<apex:inputField value="{!campaign.ExpectedRevenue}"/>
<apex:inputField value="{!campaign.EndDate}"/>
<apex:inputField value="{!campaign.BudgetedCost}"/>
<apex:inputField value="{!campaign.NumberSent}"/>
<apex:inputField value="{!campaign.ActualCost}"/>
<apex:inputField value="{!campaign.ExpectedResponse}"/>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:tab>
</apex:tabPanel>
</apex:outputPanel>
</apex:form>
</apex:page>

 

 

I have Custom  Lookups for Contacts and Accounts.  They work great independently when called from a Visualforce Page.

Except, when the calling page is one of the Lookups.

 

In the case of calling the account lookup from the contact lookup to populate the field of a contact add, it won't return to the contact lookup page at all.

 

The Contact Lookup page is below  (Account Lookup is modled after that)

 

<apex:page controller="CustomContactLookupController"
title="Search"
showHeader="false"
sideBar="false"
tabStyle="contact"
id="pg">

<script type="text/javascript">
function openLookup(baseURL, width, modified, searchParam){
var originalbaseURL = baseURL;
var originalwidth = width;
var originalmodified = modified;
var originalsearchParam = searchParam;

var lookupType = baseURL.substr(baseURL.length-3, 3);
if (modified == '1') baseURL = baseURL + searchParam;

var isCustomLookup = false;

// Following "001" is the lookup type for Account object so change this as per your standard or custom object
if(lookupType == "001"){

var urlArr = baseURL.split("&");
var txtId = '';
if(urlArr.length > 2) {
urlArr = urlArr[1].split('=');
txtId = urlArr[1];
}

// Following is the url of Custom Lookup page. You need to change that accordingly
baseURL = "/apex/CustomAccountLookup?txt=" + txtId;

// Following is the id of apex:form control "myForm". You need to change that accordingly
baseURL = baseURL + "&frm=" + escapeUTF("{!$Component.CustomContactLookup}");
if (modified == '1') {
baseURL = baseURL + "&lksearch=" + searchParam;
}

// Following is the ID of inputField that is the lookup to be customized as custom lookup
if(txtId.indexOf('Account') > -1 ){
isCustomLookup = true;
}
}

// jmc added because above does not set it - this will cause all lookups to override
isCustomLookup = true;

if(isCustomLookup == true){
openPopup(baseURL, "lookup", 350, 480, "width="+width+",height=480,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
}
else {
if (modified == '1') originalbaseURL = originalbaseURL + originalsearchParam;
openPopup(originalbaseURL, "lookup", 350, 480, "width="+originalwidth+",height=480,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
}
}
</script>

<apex:form >
<apex:outputPanel id="page" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
<apex:tabPanel switchType="client" selectedTab="name1" id="tabbedPanel">

<!-- SEARCH TAB -->
<apex:tab label="Search" name="tab1" id="tabOne" onclick="!Search" reRender="searchResults">

<apex:actionRegion >
<apex:outputPanel id="top" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
<apex:outputLabel value="Search" style="font-weight:Bold;padding-right:10px;" for="txtSearch"/>
<apex:inputText id="txtSearch" value="{!searchString}" />
<span style="padding-left:5px"><apex:commandButton id="btnGo" value="Go" action="{!Search}" rerender="searchResults"></apex:commandButton></span>
</apex:outputPanel>

<apex:outputPanel id="pnlSearchResults" style="margin:10px;height:350px;overflow-Y:auto;" layout="block">
<apex:pageBlock id="searchResults">
<apex:pageBlockTable value="{!results}" var="a" id="tblResults">
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Name</apex:outputPanel>
</apex:facet>
<apex:outputLink value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Name}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Name}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Account</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Account.Name}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Account.Name}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Title</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Title}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Title}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Email Name</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.email}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.email}</apex:outputLink>
</apex:column>

</apex:pageBlockTable>
</apex:pageBlock>
</apex:outputPanel>
</apex:actionRegion>

</apex:tab>

<!-- NEW contact TAB -->
<apex:tab label="New contact" name="tab2" id="tabTwo" >

<apex:pageBlock id="newcontact" title="New contact" >

<apex:pageBlockButtons location="top">
<apex:commandButton action="{!savecontact}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageMessages />

<apex:pageBlockSection columns="2">
<apex:inputField value="{!contact.LastName}" required="true"/>
<apex:inputField value="{!contact.FirstName}" required="true"/>
<apex:inputField value="{!contact.Title}"/>
<apex:inputField value="{!contact.Email}"/>
<apex:inputField value="{!contact.AccountId}"/>
<apex:inputField value="{!contact.Department}"/>
<apex:inputField value="{!contact.Phone}"/>
<apex:inputField value="{!contact.MobilePhone}"/>

<apex:inputField value="{!contact.Fax}"/>
<apex:inputField value="{!contact.ReportsToId}"/>
<apex:inputField value="{!contact.AssistantName}"/>
<apex:inputField value="{!contact.AssistantPhone}"/>
<apex:inputField value="{!contact.Description}"/>
<apex:inputField value="{!contact.BirthDate}"/>
<apex:inputField value="{!contact.Date_of_Last_Personal_Contact__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>

</apex:tab>
</apex:tabPanel>
</apex:outputPanel>
</apex:form>
</apex:page>

 

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

I modeled this after code that was better than the Standard Lookups but inherited a few of the pesky behavors.

Such as:

-- On initial call from a populated field - populated search field with the existing field and instigating that search.

---- I wanted a full search instigated without the user clearing the search field and pressing GO.

--On Add  - not calling that specific search for selection

 

The comments are for those purposes.

 

It does, however, not show an error on add when required field is missing because it's jumping back to the search w/o  validating.  If you select the add tab again, you'll see it's still there.  I just haven't put in the error checking yet.  If that comes to you easily, you can share, but I'm not especially concerned wit it yet.

 

You'll love these processes so it's worth you debugging and sharing with me.

 

I'm glad to be able to payback for all the help you guys have given me.

 

Thanks.

  

 

 

 

I have a wrapper class for Opportunities associated to a Custom Object.  The query includes related fields for display only.

This is functioning for existing Custom Object record associations as it comes from the database.  The problem is that the display of related fields need to come from a query on the related objects so that I get data for new and record changes.

 

I have that query also but I haven't figured out how to merge that data into the wrapper items or just reference the query in the Visualforce page for this. When I attempt the latter, I get an error stating that it's not a part of the controller (Custom Object).  My page declares the Custom Object Standard controller and an extenstion that includes the above queries.

 

i think the latter concept is the cleanest solution but I have to fiqure out how to gett the system to understand these processes.

 

The Page:  It does not include the attempts to add the events

 

<apex:page standardController="Trip_Report__c" extensions="TripRptExt" showHeader="false"><apex:sectionHeader title="Trip Report" subtitle="Step 3 of 5 - Opportunities"/>

<apex:form >
<apex:PageMessages id="pageMessage" showDetail="false"/>
<apex:pageBlock title="Trip Information">
<apex:pageBlockButtons location="both">
<apex:commandButton value="Cancel" action="{!cancel}"/>
<apex:commandButton value="Prev" action="{!step2}" />
<apex:commandButton value="Next" action="{!step4}" />
</apex:pageBlockButtons>
<apex:PageBlockSection title="Information" columns="2" collapsible="false" >
<apex:outputField value="{!tripReport.Unique_Name__c}" />
<apex:outputField value="{!tripReport.Date_of_Meeting__c}" />
<apex:outputField value="{!tripReport.Campaign__c}" />
<apex:outputField value="{!tripReport.Company__c}" />
<apex:outputField value="{!tripReport.Location_of_Meeting__c}" />
</apex:PageBlockSection>
</apex:PageBlock>

<apex:PageBlock id="opportunityItemBlock" title="Opportunities" mode="Edit">
<apex:PageMessage id="itemsMessage" summary="{!reportItemsMessage}" severity="error" strength="2" rendered="{!NOT(IsNull(reportItemsMessage))}" />
<apex:pageBlockButtons location="top">
<apex:commandButton value="Add Opportunity" immediate="true" action="{!addOpportunity}" status="addStatus" rerender="opportunityItemBlock" />
&nbsp;
<apex:actionStatus id="addStatus" startText="wait..."/>
</apex:pageBlockButtons>
<apex:PageblockTable id="itemList" value="{!opportunityItemListNotDeleted}" var="item" >
<apex:column width="40px" >
<apex:commandLink immediate="true" action="{!removeOpportunity}" status="removeStatus" rerender="opportunityItemBlock" type="image/png" >
<apex:image value="{Remove}" />
<apex:param name="lineno" assignTo="{!selectLineNumber}" value="{!item.lineNumber}"/>
</apex:commandLink>
&nbsp;<apex:actionStatus id="removeStatus" startText="wait..."/>
</apex:column>

<apex:column width="50px" >
<apex:facet name="header" >
<apex:outputText value="Line#" />
</apex:facet>
<apex:outputText value="{!item.lineNumber}" />
</apex:column>

<apex:column >
<apex:facet name="header" >
<apex:outputText value="Opportunity" />
</apex:facet>
<apex:InputField value="{!item.opportunity.Opportunity__c}" />
</apex:column>

<apex:column rendered="true">
<apex:facet name="header" >
<apex:outputText value="Company" />
</apex:facet>
<apex:OutputField value="{!item.opportunity.Opportunity__r.Account.Name}" rendered="true" />
</apex:column>

<apex:column rendered="true" >
<apex:facet name="header" >
<apex:outputText value="Type" />
</apex:facet>
<apex:OutputField value="{!item.opportunity.opportunity__r.Type}" rendered="true"/>
</apex:column>

<apex:column rendered="true" >
<apex:facet name="header" >
<apex:outputText value="Stage" />
</apex:facet>
<apex:OutputField value="{!item.opportunity.opportunity__r.StageName}" rendered="true"/>
</apex:column>

<apex:column rendered="true" >
<apex:facet name="header" >
<apex:outputText value="Amount" />
</apex:facet>
<apex:OutputField value="{!item.opportunity.opportunity__r.Amount}" rendered="true" />
</apex:column>

</apex:PageblockTable>

</apex:PageBlock>

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

 

Wrapper Class:

 

/**
* Purpose : This class is a supporting Data Transfer Objects for the Trip Report custom UI.
*/
public class OpportunityLineItem {

public Integer lineNumber{ get; set; }
public Boolean isDeleted{ get; set; }
public tripOpportunityAssociation__c opportunity { get; set;}

public opportunityLineItem(){
opportunity = new tripOpportunityAssociation__c();
lineNumber = 0;
isDeleted = false;
}

public OpportunityLineItem(Integer pLineNumber, tripOpportunityAssociation__c pOpportunityItem){
opportunity = pOpportunityItem;
lineNumber = pLineNumber;
isDeleted = false;
}
}

 

Snipets from Controller Extension:

 

/**
* Purpose : This class is a controller Extension for the Trip Report custom UI.
*/
public with sharing class TripRptExt {

public TripRptExt() {

}

 

.....

 

private List<TripOpportunityAssociation__c> opportunityList {
get{
List<TripOpportunityAssociation__c> returnValue = new List<TripOpportunityAssociation__c>();
if(opportunityList == null && reportId != null) {
returnValue = TripRptManager.getOpportunitiesForReport(reportId);
}
return returnValue;
}
set;
}

//List of wrapper objects.
private List<OpportunityLineItem> opportunityLineItemList{
get{
if (opportunityLineItemList == null){
opportunityLineItemList = new List<opportunityLineItem>();

//Only loaded on isUpdate.
if (isUpdate){

for(TripOpportunityAssociation__c opportunity : opportunityList ){
opportunityLineCount ++;
OpportunityLineItem lineItem = new OpportunityLineItem( opportunityLineCount , opportunity);
opportunityLineItemList.add(lineItem);
}
}
}
return opportunityLineItemList;
}
set;
}

 

.....

 

The TripRptManager methods called are:

 

//Returns a list of Opportunity Associations for a trip report.
// di not Change the relalationship name between the
//TripOpportunityAssociation__c and the Trip_Report__c back to the default.
//The parent lookup field on the child should be named:
//Trip_Report__c NOT Trip_Opportunity__c This is the report field
public static List<TripOpportunityAssociation__c> getOpportunitiesForReport(Id reportId){

return [SELECT
Id
,Trip_Opportunity__c
,Opportunity__c
,Opportunity__r.name
,Opportunity__r.Type
,Opportunity__r.Amount
,Opportunity__r.Account.Name
,Opportunity__r.StageName
//,Opportunity.EstimatedCloseDate__c
FROM
TripOpportunityAssociation__c
WHERE
Trip_Opportunity__c = :reportId
];
}

...  The one for the prefered approach but not incorporated yet due to syntax errors on page

 

public static List<Opportunity> refreshOpportunities(Id opportunityId){

return [SELECT
Id
,Name
,Type
,Amount
,Account.Name
,StageName
FROM
Opportunity
WHERE
Opportunity.Id = :opportunityId
];
}

 

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

 

If you have any suggestions or just a model of something similar, I would greatly appreciate it.

 

Thanks.

 

 

 

My Test method covered the wrapper class at only 63%:  Lines 11 - 14 were not covered.

My Test Method calls this ref via the controller extenstion.  Why are these lines omitted?  Thanks

 

Some extension excerpts are:

 

public List<OpportunityLineItem> getOpportunityItemListNotDeleted(){
//List for display on the view.
List<OpportunityLineItem> listToDisplay = new List<OpportunityLineItem>();
for (OpportunityLineItem item : opportunityLineItemList){
if (item.isDeleted != true){
listToDisplay.add(item);
}
}

return listToDisplay;
}

 

---

 

private List<TripOpportunityAssociation__c> opportunityList {
get{
List<TripOpportunityAssociation__c> returnValue = new List<TripOpportunityAssociation__c>();
if(opportunityList == null && reportId != null) {
returnValue = TripRptManager.getOpportunitiesForReport(reportId);
}
return returnValue;
}
set;
}

//List of wrapper objects.
private List<OpportunityLineItem> opportunityLineItemList{
get{
if (opportunityLineItemList == null){
opportunityLineItemList = new List<opportunityLineItem>();

//Only loaded on isUpdate.
if (isUpdate){

for(TripOpportunityAssociation__c opportunity : opportunityList ){
opportunityLineCount ++;
OpportunityLineItem lineItem = new OpportunityLineItem( opportunityLineCount , opportunity);
opportunityLineItemList.add(lineItem);
}
}
}
return opportunityLineItemList;
}
set;
}

//Renumber the lines in the list.
private void renumberOpportunityLineItemList(){
opportunityLineCount = 0;
for ( OpportunityLineItem item : opportunityLineItemList ){
item.lineNumber = 0;
if (item.isDeleted == false){
opportunityLineCount++;
item.lineNumber = opportunityLineCount;
}
}
}

 

 

The class is:

 

/**
 3   * Purpose : This class is a supporting Data Transfer Objects for the Trip Report custom UI.
 4   */
 5  public class OpportunityLineItem {
 6  
 7   public Integer lineNumber{ get; set; }
 8   public Boolean isDeleted{ get; set; }
 9   public tripOpportunityAssociation__c opportunity { get; set;}
 10  
 11   public opportunityLineItem(){
 12   opportunity = new tripOpportunityAssociation__c();
 13   lineNumber = 0;
 14   isDeleted = false;
 15   }
 16  
 17   public OpportunityLineItem(Integer pLineNumber, tripOpportunityAssociation__c pOpportunityItem){
 18   opportunity = pOpportunityItem;
 19   lineNumber = pLineNumber;
 20   isDeleted = false;
 21   }
 22  }

I have a custom Lookup that I'm trying to use to replace the Standard Lookup on a Visualforce page.  The code requires reference to the lookup type to associate it to the screen field.  ie  Account is 001.  I got that from a code sample but in order to do this for others, I need to know these codes.  Is there a reference for this?

 

Thanks

I have a lookup method in my controller extension for a custom object to the Campaign.Type field of Campaign.

my visualforce page references the custom object controller and Extension.

 

How do I reference this field on the page?

 

Excerpts are:

 

Extension -

 

private Trip_Report__c tripReport;
private Campaign campaignInfo;

 

// get display data
if (tripReport.Campaign__c != null) {
campaignInfo = TripRptManager.getCampaign(tripReport.Campaign__c);
}

in The Utility Lib referenced above - 

 

// Display fields

public static Campaign getCampaign(Id campaign){
         
        return [SELECT 
                    Id
                    ,Name
                    ,Type
                  FROM 
                    Campaign
                WHERE
                    Id = :campaign
                ];      
    }

 

 

Page -

 

<apex:page standardController="Trip_Report__c" extensions="TripRptExt" showHeader="false">

 

<apex:outputField value="{!campaignInfo.Type }" /> 

 

The ERROR 

Error: Unknown property 'Trip_Report__cStandardController.campaignInfo'

 

I also tried !relatedTo.Campaign__r.Type  and get the error on 'relatedTo'

 

Any ideas?  Thanks

 

My Test Method results in the above error on a number of lines.  I'm thinking it's one thing tripping it all up.  What is in common on all of them is that they are references to my controller extension.  

 

Excerpts from the Test Class are:

 

@isTest(seeAllData=true)
private class Test_TripRpt_Ext{

private static ApexPages.StandardController ctl; 
private static TripRptExt ext; 
private static ApexPages.StandardController ctlWithReport; 
private static TripRptExt extWithReport; 

private static User mockAdminUser; 
private static User mockManagerUser; 
private static User mockEmployeeUser; 
private static User mockContractorUser; 

private static Trip_Report__c r; 

//private static List<Attendee_Item__c> eil;
private static List<AttendeeLineItem> ail;   
private static List<OpportunityLineItem> oil;  
 
static{

  //Build mock data 
  setupReportWithItem();

  //Instantiate and empty controller. 
  ctl = new ApexPages.StandardController(new Trip_Report__c()); 
  ext = new TripRptExt(ctl); 

  //Instantiate a full controller. 
  ctlWithReport = new ApexPages.StandardController(r); 
  extWithReport = new TripRptExt(ctlWithReport);
  extWithReport.isUpdate = true;

 }

 

------

The ERROR Lines:

 

system.assertEquals( null, ext.getReportItemsMessage() );

 

 

system.assertEquals( new Trip_Report__c(), ext.getTripReport() ); 

 

for(AttendeeLineItem lineItem : extWithReport.getAttendeeItemListNotDeleted() ){

 system.debug( 'Item: ' + lineItem ); 

 

and so on - all are ext. or extWithReport. items.

 

I'd greatly appreciate any clues on this.  Thanks

 

 

 

 

I have a fully functioning cross object update trigger but my tests fail with:

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateAccountPartsSurveyDate: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.UpdateAccountPartsSurveyDate: line 6, column 1: 

 

The Trigger:

 

trigger UpdateAccountPartsSurveyDate on TIMBASURVEYS__Recipient__c (after update, after insert) {

Account myAccount = new Account();
TIMBASURVEYS__Recipient__c Recipient = trigger.new[0];

myAccount = [SELECT
Id
,Name
,Date_of_Last_Parts_Survey_Sent__c
FROM
Account
WHERE
Id = :Recipient.TIMBASURVEYS__RelatedAccount__c
];
// Truncate Date
Datetime dt = Recipient.TIMBASURVEYS__DateSendInvitation__c;
Date dateval = date.newInstance(dt.year(), dt.month(), dt.day());

if (myAccount.Date_of_Last_Parts_Survey_Sent__c == null || myAccount.Date_of_Last_Parts_Survey_Sent__c < dateval)
{
myAccount.Date_of_Last_Parts_Survey_Sent__c = dateval;
update myAccount;
}

}

 

The Test Class:

 

@isTest private class TestSurveyAcctDateTrigger {

static testMethod void TestSurveyAcctDateTrigger () {
Account account = new Account();
TIMBASURVEYS__Recipient__c recipient = new TIMBASURVEYS__Recipient__c();
recipient.Name = 'This is a trigger test';
recipient.TIMBASURVEYS__DateSendInvitation__c = date.PARSE('07/11/2012');
insert recipient;
}
}

Hi,  I am trying to populate 'private static User mockAdminUser'  with the data of the current user.  Of the UserInfo methods I don't see anything that returns the entire object.

 

The code snippet with commented error is:

 

// Error: Compile Error: Illegal assignment from String to SOBJECT:User at line 520 column 2
mockAdminUser = UserInfo.getUserId();

 

It's obviously not the id I need anyway.  Any other approaches.

 

Thanks.

My Test Method returned the error  ' Error: Compile Error: Variable is not visible: opportunityLineItemList at line 62 column 38'  This is a reference to a wrapper class that's handled in my controller extension.  This code is fully functional.  The other (non-wrapper)  fields are available. so I think my build of the extension reference is good.

Any ideas.  Thanks.

 

The code excerps are:

 

Test Method:

 

Note - line 62 is the for loop 

 

PageReference addOpportunity;

// Error: Compile Error: Variable is not visible: opportunityLineItemList at line 62 column 38
for(OpportunityLineItem item : controller.opportunityLineItemList) {
item.Opportunity__c = [SELECT id FROM Opportunity WHERE Opportunity = 'Great Opportunity'];
}

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

The wrapper class:

 

/**
* Purpose : This class is a supporting Data Transfer Objects for the Trip Report custom UI.
*/
public class OpportunityLineItem {

public Integer lineNumber{ get; set; }
public Boolean isDeleted{ get; set; }
public tripOpportunityAssociation__c opportunity { get; set;}

public opportunityLineItem(){
opportunity = new tripOpportunityAssociation__c();
lineNumber = 0;
isDeleted = false;
}

public OpportunityLineItem(Integer pLineNumber, tripOpportunityAssociation__c pOpportunityItem){
opportunity = pOpportunityItem;
lineNumber = pLineNumber;
isDeleted = false;
}
}

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

 

In the Controller extension:

 

public List<OpportunityLineItem> getOpportunityItemListNotDeleted(){
//List for display on the view.
List<OpportunityLineItem> listToDisplay = new List<OpportunityLineItem>();
for (OpportunityLineItem item : opportunityLineItemList){
if (item.isDeleted != true){
listToDisplay.add(item);
}
}

return listToDisplay;
}

 

 

 

I am trying to populate a wrapper class field in my test method.  I attempted the syntax used in the functional controller extension which populates the key field.  Only I'm hard coding an associated field. The object is a custom junction object for the 1 to many relationship.

 

My error is:  Variable does not exist: Opportunity__c at line 64 column 6

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

The class is:

 

public class OpportunityLineItem {

public Integer lineNumber{ get; set; }
public Boolean isDeleted{ get; set; }
public tripOpportunityAssociation__c opportunity { get; set;}

public opportunityLineItem(){
opportunity = new tripOpportunityAssociation__c();
lineNumber = 0;
isDeleted = false;
}

public OpportunityLineItem(Integer pLineNumber, tripOpportunityAssociation__c pOpportunityItem){
opportunity = pOpportunityItem;
lineNumber = pLineNumber;
isDeleted = false;
}

 

The Controller extension population of the key field is:

 

 PageReference addAttendee;

 

// Populate new opportunity items with report id.

for ( TripOpportunityAssociation__c item : opportunityItemsToUpsert ){
if (item.Trip_Opportunity__c == null){
item.Trip_Opportunity__c = tripReport.id;

}
}

 

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

 

The test method syntax is:

@isTest private class TestTripRptExt3 {
public TestTripRptExt3() {

}
//Public attributes.
public ApexPages.StandardController controller;

public Boolean CancelConfirm = false;
//Private attributes.
private Trip_Report__c tripReport;
private String reportItemsMessage;

private Integer attendeeLineCount = 0;
private Integer opportunityLineCount = 0;

//Controller extension constructor.
public TestTripRptExt3(ApexPages.StandardController stdController) {


static testMethod void testTripRptExt3() {

 

// controller.setUnique_Name & basic fields(
controller.tripReport.Unique_Name__c = 'Test Method Name';
controller.tripReport.Date_of_Meeting__c = date.parse('07/13/2012');
controller.tripReport.Meeting_Notes__c = 'Test Method Note';

 

 

 

PageReference addOpportunity;
for(OpportunityLineItem item : controller.opportunityLineItemList) {
item.Opportunity__c = 'Great Opportunity';
}

}

Any ideas on this?  Thanks


I have fully functional code using wrapper classes.  My trouble is referencing the wrapper class fields for population in the test method.

 

All reference attempts (modeling the controller extension) references to the wrapper elements result in syntax errors.

The most common is 'variable does not exist.

 

It could be the method call because I also could not pass syntax on attendeeLineCount++

 

excepts are:  The problem code is commented out and the error copied to begining comment line marked with ***

 

Any ideas?  Thanks.

 

Wrapper class:

 

/**
* Purpose : This class is a supporting Data Transfer Objects for the Trip Report custom UI.
*/
public class AttendeeLineItem {

public Integer lineNumber{ get; set; }
public Boolean isDeleted{ get; set; }
public tripContactAssociation__c attendeeitem { get; set;}

public attendeeLineItem(){
attendeeitem = new tripContactAssociation__c();
lineNumber = 0;
isDeleted = false;
}

public AttendeeLineItem(Integer pLineNumber, tripContactAssociation__c pAttendeeItem){
attendeeitem = pAttendeeItem;
lineNumber = pLineNumber;
isDeleted = false;
}
}

 

-----

 

Reference int the controller extension:  

 


public List<AttendeeLineItem> getAttendeeItemListNotDeleted(){
//List for display on the view.
List<AttendeeLineItem> listToDisplay = new List<AttendeeLineItem>();
for (AttendeeLineItem item : attendeeLineItemList){
if (item.isDeleted != true){
listToDisplay.add(item);
}
}

return listToDisplay;
}

--

public Integer selectLineNumber{ 
get{
if (selectLineNumber == null) {
selectLineNumber = 0;

return selectLineNumber;
}
set; 
}

 

--

//List of wrapper objects.
private List<AttendeeLineItem> attendeeLineItemList{
get{
if (attendeeLineItemList == null){
attendeeLineItemList = new List<AttendeeLineItem>();

//Only loaded on isUpdate.
if (isUpdate){

for(TripContactAssociation__c attendee : attendeeList ){
attendeeLineCount ++;
AttendeeLineItem lineItem = new AttendeeLineItem( attendeeLineCount , attendee);
attendeeLineItemList.add(lineItem);
}
}
}
return attendeeLineItemList;
}
set;
}

//Renumber the lines in the list.
private void renumberAttendeeLineItemList(){
attendeeLineCount = 0;
for ( AttendeeLineItem item : attendeeLineItemList ){
item.lineNumber = 0;
if (item.isDeleted == false){
attendeeLineCount++;
item.lineNumber = attendeeLineCount;
}
}
}

--

//Action method to add a new attendee item in the view.
public PageReference addAttendee(){

reportItemsMessage = null;
ApexPages.getMessages().clear();

if ( attendeeLineCount < MAX_ATTENDEE_ITEM_NUM ){
//Add a new empty row to the list.
attendeeLineCount++;
attendeeLineItemList.add(new AttendeeLineItem( attendeeLineCount, new TripContactAssociation__c( Attendee__c = reportId ) ));
reportItemsMessage = null;
} else {
//Display a message.
reportItemsMessage = 'No more than ' + String.valueOf(MAX_ATTENDEE_ITEM_NUM) + ' attendees are permitted.';
}

return null;
}

 

--

//Action method to remove an attendee item from display by issuing a soft delete.
public PageReference removeAttendee(){

reportItemsMessage = null;
ApexPages.getMessages().clear();

if (selectLineNumber != Null ){

//Soft delete the line and renumber.
for ( AttendeeLineItem item : attendeeLineItemList ){
if (item.lineNumber == selectLineNumber){
item.isDeleted = true;
break;
}
}
renumberAttendeeLineItemList();
}

reportItemsMessage = null;
return null;
}

 

--

   In the save method -

 

List<TripContactAssociation__c> attendeeItemsToDelete = new List<TripContactAssociation__c>();
List<TripContactAssociation__c> attendeeItemsToUpsert = new List<TripContactAssociation__c>();

//Loop thru the lines and capture those needing deletion or upsert.
//There may be some to ignore - newly added and subsequently removed,
for ( AttendeeLineItem item : attendeeLineItemList ){
if (item.isDeleted == true && item.attendeeitem.id != null){
attendeeItemsToDelete.add(item.attendeeitem);
}
if (item.isDeleted == false){
attendeeItemsToUpsert.add(item.attendeeitem);
}
}

 

--

 

//Save the items.
//Populate new attendee items with report id.
for ( TripContactAssociation__c item : attendeeItemsToUpsert ){
if (item.Attendee__c == null){
item.Attendee__c = tripReport.id;
}
}

tripReport = TripRptManager.getTripReportId(tripReport.unique_Name__c);

//Items upsert should follow to insure report ids.
if (attendeeItemsToUpsert.size() > 0 ){

//Save the new or changed items.
try{
upsert attendeeItemsToUpsert;
} catch (system.Exception e) {
//Abandon.
Database.rollback(sp);
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Error saving Attendee items.'));
return Page.TripRptStep2;
}
}

 

NOW The test method:

 

@isTest private class TestTripRptExt1 {
Trip_Report__c tripReport = new Trip_Report__c();
ApexPages.StandardController thecontroller = new ApexPages.StandardController(tripReport);

TripRptExt controller = new TripRptExt(thecontroller);
static testMethod void testTripRptExt() {

PageReference pageRef = Page.TripRptStep1;
Test.setCurrentPage(pageRef);

//set the field values of details
//all the field values those are entered in VF page has to be set here
Trip_Report__c tripReport = new Trip_Report__c();

//Instantiate and construct the controller class.


ApexPages.StandardController thecontroller = new ApexPages.StandardController(tripReport);

TripRptExt controller = new TripRptExt(thecontroller);

// controller.setUnique_Name & basic fields(
tripReport.Unique_Name__c = 'Test Method Name';
tripReport.Date_of_Meeting__c = date.parse('07/13/2012');
tripReport.Meeting_Notes__c = 'Test Method Note';

//The .getURL will return the page url method returns.

String nextPage = controller.Step2().getUrl();

PageReference pageRefN2 = Page.TripRptStep2;
Test.setCurrentPage(pageRefN2);

// test Cancel functions
String cancel = controller.cancel().getUrl();
String nocancel = controller.nocancel().getUrl();

Test.setCurrentPage(pageRefN2);

// PageReference List<AttendeeLineItem>;

PageReference addAttendee;

PageReference removeAttendee;

PageReference pageRefN3 = Page.TripRptStep3;
Test.setCurrentPage(pageRefN3);

PageReference addOpportunity;

PageReference removeOpportunity;

PageReference pageRefN4 = Page.TripRptStep4;
Test.setCurrentPage(pageRefN4);
String TripRptStep5 = controller.savereport().getUrl();

PageReference pageRefN6 = Page.TripRptStep6;
Test.setCurrentPage(pageRefN6);

PageReference pagePdfN = Page.TripRptPdf;
Test.setCurrentPage(pagePdfN);

String done = controller.done().getUrl();

// save should have errored on no attendees. Add 1 & save

PageReference pageRefN2b = Page.TripRptStep2;
Test.setCurrentPage(pageRefN2b);
Test.setCurrentPage(pageRefN2b);


TripRptManager.getAttendeesForReport('');


// Public List<AttendeLineItem>getAttedeeItemListNotDeleted;

PageReference addAttendee2;


// attendeeLineCount++;
// done in add function attendeeLineItemList.add(new AttendeeLineItem( 1, new TripContactAssociation__c( Attendee__c = '', Contact__c = 'Craig' ) ));

/* *** ERROR IS Variable does not exist: attendeeLineItemList at line 86 column 31

for(AttendeeLineItem item: attendeeLineItemList) {
item.Contact__c = 'Craig';
}
*/
PageReference pageRefN5 = Page.TripRptStep5;
Test.setCurrentPage(pageRefN5);
String TripRptStep5b = controller.savereport().getUrl();



//Check that the save() method returns the proper URL
// System.assertEquals('/apex/failure?error=noParam', nextPage);

// Next Test update functions
}
}

 

 

 

 

 

I don't believe I grasp the Test Method Function.  I've Added @isTest to my high level class of the controller but when I run the Test function, it returns - 'No Methods found'

 

Is there a resource that would help here?

 

Thanks.

I have queries in my controller that reference page values in the where clause.  They pass syntax but return no rows.

The only page reference I've been able to use successfully is id.

 

A snipet of one:

 

account = [SELECT Name,
( SELECT Contact.Name, Contact.Email
FROM Account.Contacts)
FROM Account
WHERE Name = :ApexPages.currentPage().getParameters().get('company__c')];

 

This is based on an example but changed from Id = :ApexPages.currentPage().getParameters().get('id')];

 

Is there a call I need to make  to make the fields available?  Or is there another approach.

 

Thanks

My procedure needs to filter out converted leads from my lookups.  I've noted that the Lead status field piciklist includes a 

field Labeled Converted but I don't know the coding reference for my SOQL statement.

 

If I filter by the status values that are checked as converted, it still gets one that is not checked on the status.  

 

Id like to understand how this work anyway in order to write clean code because I'm thinking there is another reference that is more reliable.

 

Thanks.

I'm having a problem referencing the class fields (Street, City, etc) of address fields named something other than just address. Ie BillingAddress.  

 

When I use BillingAddress.Street it result in:

 

Didn't understand relationship 'BillingAddress' in field path.

 

Do you know what I'm missing here?  Thanks

My test method fails due to a null pointer exception but this does no hapen in the UI runtime.

 

I get this both on the Save Method and Save Override.  If I can fix the Save then I'm sure I can apply it to the override.

 

This is a custom Lookup with a New/Add function.

 

The Test Method  -  the error is noted in a comment above the line.  I also had trouble with the runsearch at the end.

 

Any ideas?  Thanks.

 

/**
* Purpose : This class contains unit tests for the Trip Report controller extension.
*/
@isTest(seeAllData=true)
private class Test_CustomCampaignLkpCtrl{

private static ApexPages.StandardController ctl;
private static CustomCampaignLookupController ext;
private static ApexPages.StandardController ctlWithRecord;
private static CustomCampaignLookupController extWithRecord;

private static User mockAdminUser;

private static Campaign r;


static{

TripRptTestDataUtilityLib.getActiveAdminUserId();

//Build mock data
// setup With Item();

//Instantiate and empty controller.
ctl = new ApexPages.StandardController(new Campaign());

//Instantiate a full controller.
ctlWithRecord = new ApexPages.StandardController(r);
extWithRecord = new CustomCampaignLookupController(ctlWithRecord);
extWithrecord.isNew = true;


ext = new CustomCampaignLookupController(ctlWithRecord);


system.debug('**********************************');
system.debug('ctlWithRecord: ' + ctlWithRecord);
system.debug('extWithRecord: ' + extWithRecord);
system.debug('**********************************');


} // End

public Campaign campaign {get;set;} // new campaign to create
public List<Campaign> results{get;set;} // search results
public string searchString{get;set;} // search keyword

static testMethod void CanTestSaveOverride(){
String saveUrl = ext.SaveCampaign().getUrl();

}

static testMethod void CanTestSave(){
// Campaign c = new Campaign();
//Run the save() and verify:
//1: modified Report and Items
//2: Redirect URL matches the detail page for new report.
// Populate record.
Campaign extRecord = new Campaign();
extRecord = [select id, name from Campaign LIMIT 1];

extRecord.Name = 'Test Method Name';
extRecord.Description = 'Test Meth Desc';
//ERROR System.NullPointerException: Attempt to de-reference a null object Class.Test_CustomCampaignLkpCtrl.CanTestSave: line 67, column 1
extWithRecord.SaveCampaign();

//Verify the Url after the save() method occurred. chg from .Save()
String saveUrl = ext.SaveCampaign().getUrl();
system.debug( 'Save URL: ' + saveUrl );
// system.debug( 'Detail URL: ' + extWithRecord.controller.view().getURL() );

//ERROR not visible ext.runSearch();

}
} // End Class

 

The Controller:

 

/**
* Purpose : This class contains unit tests for the Custom Lookup.
*/
@isTest(seeAllData=true)
private class Test_CustomCampaignLkpCtrl{

private static ApexPages.StandardController ctl;
private static CustomCampaignLookupController ext;
private static ApexPages.StandardController ctlWithRecord;
private static CustomCampaignLookupController extWithRecord;

private static User mockAdminUser;

private static Campaign r;


static{

TripRptTestDataUtilityLib.getActiveAdminUserId();

//Build mock data
// setup With Item();

//Instantiate and empty controller.
ctl = new ApexPages.StandardController(new Campaign());

//Instantiate a full controller.
ctlWithRecord = new ApexPages.StandardController(r);
extWithRecord = new CustomCampaignLookupController(ctlWithRecord);
extWithrecord.isNew = true;


ext = new CustomCampaignLookupController(ctlWithRecord);


system.debug('**********************************');
system.debug('ctlWithRecord: ' + ctlWithRecord);
system.debug('extWithRecord: ' + extWithRecord);
system.debug('**********************************');


} // End

public Campaign campaign {get;set;} // new campaign to create
public List<Campaign> results{get;set;} // search results
public string searchString{get;set;} // search keyword

static testMethod void CanTestSaveOverride(){
String saveUrl = ext.SaveCampaign().getUrl();

}

static testMethod void CanTestSave(){
// Campaign c = new Campaign();
//Run the save() and verify:
//1: modified
//2: Redirect URL matches the detail page for new report.
// Populate record.
Campaign extRecord = new Campaign();
extRecord = [select id, name from Campaign LIMIT 1];

extRecord.Name = 'Test Method Name';
extRecord.Description = 'Test Meth Desc';
//ERROR System.NullPointerException: Attempt to de-reference a null object Class.Test_CustomCampaignLkpCtrl.CanTestSave: line 67, column 1
extWithRecord.SaveCampaign();

//Verify the Url after the save() method occurred. chg from .Save()
String saveUrl = ext.SaveCampaign().getUrl();
system.debug( 'Save URL: ' + saveUrl );
// system.debug( 'Detail URL: ' + extWithRecord.controller.view().getURL() );

//ERROR not visible ext.runSearch();

}
} // End Class

 

The Page:

 

<apex:page controller="CustomCampaignLookupController"
title="Search"
showHeader="false"
sideBar="false"
tabStyle="campaign"
id="pg">

<apex:form >
<apex:pageMessages />
<apex:outputPanel id="page" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
<apex:tabPanel switchType="client" selectedTab="name1" id="tabbedPanel">

<!-- SEARCH TAB -->
<apex:tab label="Search" name="tab1" id="tabOne">

<apex:actionRegion >
<apex:outputPanel id="top" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
<apex:outputLabel value="Search" style="font-weight:Bold;padding-right:10px;" for="txtSearch"/>
<apex:inputText id="txtSearch" value="{!searchString}" />
<span style="padding-left:5px"><apex:commandButton id="btnGo" value="Go" action="{!Search}" rerender="searchResults"></apex:commandButton></span>
</apex:outputPanel>

<apex:outputPanel id="pnlSearchResults" style="margin:10px;height:350px;overflow-Y:auto;" layout="block">
<apex:pageBlock id="searchResults">
<apex:pageBlockTable value="{!results}" var="a" id="tblResults">
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Name</apex:outputPanel>
</apex:facet>
<apex:outputLink value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Name}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Name}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Active</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.isActive}','{!a.Id}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.isActive}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Type</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Type}','{!a.Id}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Type}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Description</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Description}','{!a.Id}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Description}</apex:outputLink>
</apex:column>
<apex:column >
<apex:facet name="header">
<apex:outputPanel >Expected Revenue</apex:outputPanel>
</apex:facet>
<apex:outputLink disabled="true" value="javascript&colon;top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.ExpectedRevenue}','{!a.Id}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.ExpectedRevenue}</apex:outputLink>
</apex:column>

</apex:pageBlockTable>
</apex:pageBlock>
</apex:outputPanel>
</apex:actionRegion>

</apex:tab>

<!-- NEW campaign TAB -->
<apex:tab label="New campaign" name="tab2" id="tabTwo" onclick="rerender">

<apex:pageBlock id="newcampaign" title="{!NewTitle}" >

<apex:pageBlockButtons location="top" >
<apex:commandButton action="{!savecampaign}" value="Save"/>
</apex:pageBlockButtons>

<apex:pageBlockSection title="Campaign Information" columns="2">
<apex:inputField value="{!campaign.Name}" required="true" rendered="{!IsNew}"/>
<apex:outputField value="{!Campaign.Name}" rendered="{!NOT(IsNew)}"/>
<apex:inputField value="{!campaign.Status}"/>

<apex:inputField value="{!campaign.isActive}"/>

<apex:inputField value="{!campaign.Type}"/>
<apex:inputField value="{!campaign.Description}"/>
</apex:pageBlockSection>

<apex:pageBlockSection title="Planning" columns="2" >
<apex:inputField value="{!campaign.StartDate}"/>
<apex:inputField value="{!campaign.ExpectedRevenue}"/>
<apex:inputField value="{!campaign.EndDate}"/>
<apex:inputField value="{!campaign.BudgetedCost}"/>
<apex:inputField value="{!campaign.NumberSent}"/>
<apex:inputField value="{!campaign.ActualCost}"/>
<apex:inputField value="{!campaign.ExpectedResponse}"/>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:tab>
</apex:tabPanel>
</apex:outputPanel>
</apex:form>
</apex:page>

 

 

I have a lookup method in my controller extension for a custom object to the Campaign.Type field of Campaign.

my visualforce page references the custom object controller and Extension.

 

How do I reference this field on the page?

 

Excerpts are:

 

Extension -

 

private Trip_Report__c tripReport;
private Campaign campaignInfo;

 

// get display data
if (tripReport.Campaign__c != null) {
campaignInfo = TripRptManager.getCampaign(tripReport.Campaign__c);
}

in The Utility Lib referenced above - 

 

// Display fields

public static Campaign getCampaign(Id campaign){
         
        return [SELECT 
                    Id
                    ,Name
                    ,Type
                  FROM 
                    Campaign
                WHERE
                    Id = :campaign
                ];      
    }

 

 

Page -

 

<apex:page standardController="Trip_Report__c" extensions="TripRptExt" showHeader="false">

 

<apex:outputField value="{!campaignInfo.Type }" /> 

 

The ERROR 

Error: Unknown property 'Trip_Report__cStandardController.campaignInfo'

 

I also tried !relatedTo.Campaign__r.Type  and get the error on 'relatedTo'

 

Any ideas?  Thanks

 

I have a fully functioning cross object update trigger but my tests fail with:

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateAccountPartsSurveyDate: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.UpdateAccountPartsSurveyDate: line 6, column 1: 

 

The Trigger:

 

trigger UpdateAccountPartsSurveyDate on TIMBASURVEYS__Recipient__c (after update, after insert) {

Account myAccount = new Account();
TIMBASURVEYS__Recipient__c Recipient = trigger.new[0];

myAccount = [SELECT
Id
,Name
,Date_of_Last_Parts_Survey_Sent__c
FROM
Account
WHERE
Id = :Recipient.TIMBASURVEYS__RelatedAccount__c
];
// Truncate Date
Datetime dt = Recipient.TIMBASURVEYS__DateSendInvitation__c;
Date dateval = date.newInstance(dt.year(), dt.month(), dt.day());

if (myAccount.Date_of_Last_Parts_Survey_Sent__c == null || myAccount.Date_of_Last_Parts_Survey_Sent__c < dateval)
{
myAccount.Date_of_Last_Parts_Survey_Sent__c = dateval;
update myAccount;
}

}

 

The Test Class:

 

@isTest private class TestSurveyAcctDateTrigger {

static testMethod void TestSurveyAcctDateTrigger () {
Account account = new Account();
TIMBASURVEYS__Recipient__c recipient = new TIMBASURVEYS__Recipient__c();
recipient.Name = 'This is a trigger test';
recipient.TIMBASURVEYS__DateSendInvitation__c = date.PARSE('07/11/2012');
insert recipient;
}
}

I am trying to populate a wrapper class field in my test method.  I attempted the syntax used in the functional controller extension which populates the key field.  Only I'm hard coding an associated field. The object is a custom junction object for the 1 to many relationship.

 

My error is:  Variable does not exist: Opportunity__c at line 64 column 6

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

The class is:

 

public class OpportunityLineItem {

public Integer lineNumber{ get; set; }
public Boolean isDeleted{ get; set; }
public tripOpportunityAssociation__c opportunity { get; set;}

public opportunityLineItem(){
opportunity = new tripOpportunityAssociation__c();
lineNumber = 0;
isDeleted = false;
}

public OpportunityLineItem(Integer pLineNumber, tripOpportunityAssociation__c pOpportunityItem){
opportunity = pOpportunityItem;
lineNumber = pLineNumber;
isDeleted = false;
}

 

The Controller extension population of the key field is:

 

 PageReference addAttendee;

 

// Populate new opportunity items with report id.

for ( TripOpportunityAssociation__c item : opportunityItemsToUpsert ){
if (item.Trip_Opportunity__c == null){
item.Trip_Opportunity__c = tripReport.id;

}
}

 

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

 

The test method syntax is:

@isTest private class TestTripRptExt3 {
public TestTripRptExt3() {

}
//Public attributes.
public ApexPages.StandardController controller;

public Boolean CancelConfirm = false;
//Private attributes.
private Trip_Report__c tripReport;
private String reportItemsMessage;

private Integer attendeeLineCount = 0;
private Integer opportunityLineCount = 0;

//Controller extension constructor.
public TestTripRptExt3(ApexPages.StandardController stdController) {


static testMethod void testTripRptExt3() {

 

// controller.setUnique_Name & basic fields(
controller.tripReport.Unique_Name__c = 'Test Method Name';
controller.tripReport.Date_of_Meeting__c = date.parse('07/13/2012');
controller.tripReport.Meeting_Notes__c = 'Test Method Note';

 

 

 

PageReference addOpportunity;
for(OpportunityLineItem item : controller.opportunityLineItemList) {
item.Opportunity__c = 'Great Opportunity';
}

}

Any ideas on this?  Thanks


I don't believe I grasp the Test Method Function.  I've Added @isTest to my high level class of the controller but when I run the Test function, it returns - 'No Methods found'

 

Is there a resource that would help here?

 

Thanks.

I'm starting to do some research into what it would take to create a Visualforce popup window similar to the standard salesforce lookup windows.  For now, my intention is to try to come up with a stronger lookup window for one of our custom objects, and at the moment I plant to create a link on a visualforce page to bring the popup up.  (This link will be right next to the existing standard salesforce lookup icon.)
 
I figured I'd start by seeing if anyone else has had any success doing something like this.  The items I am going to tackle first are:
 
1.  Create the popup window.  -  Don't expect this to be a problem.
2.  Pass parameters to the popup through the URL - Don't expect this to be a problem.
3.  Emulate the existing functionality of an existing Salesforce lookup, so that the lookup window will disappear automatically if the parent window is reselected - Not sure how to implement this one yet
4.  Pass a value, in this case, an Id back to the parent window - Not sure how I'm going to do this, but I'm going to attempt to pass some sort of callback function into the popup so it can return a value
 
Being able to do something like this leads to the need to be able to override standard Salesforce lookup functionality.  That way this could be easily implemented on standard pages, in addition to VisualForce pages.
 
If anyone has attempted something like this with Visualforce yet, any learnings would be great!
 
Thanks!
 
Jon Keener