• Vegaln1
  • NEWBIE
  • 225 Points
  • Member since 2008

  • Chatter
    Feed
  • 9
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 30
    Questions
  • 69
    Replies
I would like to have a SOQL query to see if a field contains more than 25 characters. The field is defined as a length of 255. Tried various ways with LEN but no joy. Any suggestions on how this can be accomplished

 

Select o.Purchase_Order__c from Opportunity o Where LEN() o.Purchase_Order__c > 25

 

ery to see if there

 

  • September 01, 2010
  • Like
  • 0

I would like to just display a informational message to users at the end of a piece of APEX code to refresh the page. This does not involve a VF page, just a APEX class that creates some child records. Or to avoid this message altogether,  is there a way to refresh the page just from a APEX class and not using a VF page?

 

Regards,

I have  a boolean field I would like to have send a HTTP post to another app when set to true. Is this possible with a t rigger? If so are there some examples I could use to implement this?

 

Regards,

Hello, I have a query to get the Opportunity and associated opportunity line items via the following SOQL which works very well:

OldOpp = [Select Id, name, Probability, StageName, CloseDate, OwnerId, AccountId, Type, Sales_Contact__c, Type_2__c, Sector__c, CurrencyIsoCode, Payment_Terms__c,Lost_Reason__c,HPR_Pipeline_Category__c,HPR_Project_Type__c, OnLine_Order_del__c, Description, NextStep, ELN_Application__c, Quote_Good_Through__c,Quote_FormattedId__c,Additional_Conditions__c,Quote_CreatedDate__c , Quote_LastModifiedDate__c,RecordTypeId,Consortia_Name__c,Client_Legal_Contact__c, LeadSource,Bill_To__c,CampaignId,Winning_Competitor__c,Pilot_Start__c, Pilot_End_FQ__c,Phase__c, (Select Id, OpportunityId , Description, PriceBookEntryId, Quantity, TotalPrice, License_Type__c,Product_Type__c from OpportunityLineItems) from opportunity where id = :OppId ];

 

In another function, I DeepClone the Opportunity line items and set values in the newly created line items, however, I am having trouble setting a value in the new line item from the value in old line item ( OldOpp.OpportunityLineItems). See the APEX snippet below:

 

OpportunityLineItem[] products = OldOpp.OpportunityLineItems.DeepClone(false);
for (OpportunityLineItem each :products) {
each.OpportunityId = NewOpp.id;
each.TotalPrice = 0;
each.Description = '[CLONED]' + each.description;
each.Quantity = 1;
each.License_Type__c = OldOpp.OpportunityLineItem.License_Type__c;
/* I've tried the following to no avail....

each.License_Type__c = OldOpp.OpportunityLineITem__r.License_Type__c;

each.License_Type__c = products.License_Type__c;


  */

 

}
insert products;

 So, what I am trying to accomplish is setting the value of License_Type__c in the cloned Line item to thevalue I queried in the first query.  Any suggestions on how to accomplish this?

 

Regards,

 

 

 

Hello.. I've found  a sample piece of APEX code that would addresses a requirement we have,  however I receive this error when compiling the CaseHistoryCon.cls:

 

Save error: Constructor not defined: [History].<Constructor>(Datetime, Boolean, String, String, String, String, String)    CaseHistoryCon.cls    line 58   

 

 

Any suggestions on how to correct this? I've included the CaseHistoryCon.cls and the History.cls. It appears we're sending the correct number of parameters. This would seem pretty straignt forward but so far the fix has eluded me.

 

Regards,

public class CaseHistoryCon {
public boolean fullComments { get; private set; }
// Property value that controls visibility of related objects which are not visible in the customer portal.
public boolean hidePrivate { get; private set; }
private final Case ca;
public CaseHistoryCon(ApexPages.StandardController controller) {
this.ca = (Case)controller.getRecord();
fullComments = true;
hidePrivate = true;
truncatedCommentLength = 100;
cid = ca.id;
}
// Action method for toggling the fullComments property
public void toggleComments() { fullcomments = !fullcomments; }

// Action method for toggling the visibility control for private related objects.
public void togglePrivate() { hidePrivate = !hidePrivate; }

// Action method for navigating the user back to the case page.
public PageReference backToCase() {
return new ApexPages.StandardController(c).view();
}

// Accessor for retrieving the case object and its related items. If the cid property is null this
// method will return a new, empty case object. The functionality in this method could have been placed
// in the get property accessor for the private property named 'c' below but for simplicity of the page
// author in referencing the current case object this method was created because it is not possible to
// create a variable named 'case' since it is a reserved term in Apex.
public Case getcase() {

if(cid == null) return new Case();
return [SELECT casenumber, subject, contact.name, contact.email,
(SELECT CreatedBy.Name, CreatedDate, CommentBody,IsPublished FROM CaseComments ORDER BY CreatedDate ASC),
(SELECT CreatedBy.Name, CreatedDate, Field, NewValue, OldValue FROM Histories ORDER BY CreatedDate ASC),
(SELECT CreatedBy.Name, CreatedDate, Name FROM Attachments ORDER BY CreatedDate ASC),
(SELECT Owner.Name, ActivityDateTime, Subject, IsVisibleInSelfService FROM Events WHERE ActivityDateTime <= :System.Now() ORDER BY ActivityDateTime ASC),
(SELECT Owner.Name, LastModifiedDate, Subject, IsVisibleInSelfService, Description FROM Tasks WHERE ActivityDate <= :System.Today() // added Description THS 8/2009
AND IsClosed = true ORDER BY LastModifiedDate ASC)
FROM case
WHERE id = :cid];

}

// This accessor provides the page with the ordered collection of history (apex) objects for display in the page.
// it also processes the truncation of case comments as specified by the fullComments property value.
public History[] getHistories() {
History[] histories = new History[]{};
for (CaseComment comment:c.casecomments) {
if (!hidePrivate || comment.ispublished) {
addHistory(histories, new History(comment.createdDate, comment.ispublished, comment.createdby.name,'' ,'Comment Added', '' , truncateValue(comment.commentbody)));
}
}

for (Event e:c.events) {
if (!hidePrivate || e.isvisibleinselfservice) {
addHistory(histories, new History(e.activitydatetime, e.isvisibleinselfservice, e.owner.name, '' , 'Event Completed', '' , e.subject));
}
}

for (Task t:c.tasks) {
if (!hidePrivate || t.isvisibleinselfservice) {
addHistory(histories, new history(t.lastmodifieddate, t.isvisibleinselfservice, t.owner.name, t.Subject , 'Task Completed', '' , t.Description)); //Added Description THS 8/2009 subject
}
}
for (CaseHistory ch:c.histories) {
addHistory(histories, new history(ch.createdDate, true, ch.createdby.name, ch.field + ' Change', String.valueOf(ch.oldvalue), String.valueOf(ch.newvalue)));
system.debug('##################### CaseHistory: ' +ch.oldvalue + ' ' +ch.newvalue);
}

for (Attachment a:c.attachments) {
addHistory(histories, new history(a.createdDate, true, a.createdby.name,'' , 'Attachment Added', '' , a.name));
}

return histories;
}

// This method adds the newHistory object to the given histories collection in the appropriate order.
// The order provided here places the oldest records at the front of the list, i.e. by date ascending.
private void addHistory(History[] histories, History newHistory) {
Integer position = histories.size();
for (Integer i = 0; i < histories.size(); i++) {
if (newHistory.historydt < histories[i].historydt) {
position = i;
break;
}
}

if (position == histories.size()) {
histories.add(newHistory);
} else {
histories.add(position, newHistory);
}
}

// Returns the truncated string value if that is specified in the current state (!fullComments)
// and the current length is greater than the value of the private truncatedCommentLength property.
private String truncateValue(String s) {
if (!fullComments && s.length() > truncatedCommentLength) {
s = s.substring(0,truncatedCommentLength) + '...';
}

return s;
}

// The ID value of the case that will be used by the getCase() method to query for the related
// objects used to generate the ordered history collection. The value will be based on the request
// parameter, if available.
private Id cid {
get {
if(ApexPages.currentPage().getparameters().get('cid') != null) {
cid = ApexPages.currentPage().getparameters().get('cid');
}
return cid;
}
set {
if(value != null) cid = value;
}
}

// The case object set by the getCase method and used by the getHistories method to acquire
// the related records.
private Case c {
get { return getCase(); }
set;
}

// The length of "Short Comments" which is used by the truncateValue method in this class to
// truncate case comments when specified by the user.
private Integer truncatedCommentLength { get; set; }

public PageReference NavigateToPrintablePage() {
//cid = ApexPages.currentPage().getparameters().get('cid');
PageReference pageRef = new PageReference('/apex/caseHistoryPrint');
if(ApexPages.currentPage().getparameters().get('cid') != null) {
cid = ApexPages.currentPage().getparameters().get('cid');
}
return pageRef;

}

}

 

 

public class History{ // Properties of the class. Changed from history to History to avoid compile errors in other classes/pages. public datetime historydt { get; private set; } public boolean ispublic { get; private set; } public string actorname { get; private set; } public string historyType { get; private set; } public string to { get; private set; } public string fr { get; private set; } // Class constructor public History(Datetime d, boolean p, String actor, String ht, String f, String t) { historydt = d; historydate = d.format(); ispublic = p; actorname = actor; historyType = ht; fr = f; to = t; } // Formatting methods utilized primarily by the CaseHistoryPrint Visualforce page public string historydate { get; set; } public string dtmonthyr { get { return historydt.format('MMMMM yyyy'); } } public string dttime { get { return historydt.format('h:mm a');} } public string dtdayfmt { get { return historydt.format('d - EEEE'); } } public integer dtmonth { get { return historydt.month();} } public integer dtyear { get { return historydt.year();} } public integer dtday { get { return historydt.day();} } }

 


 

 

 

 

Hello, I would like to display the name of the RecordTypeId field in a VF page. If I use the following

<apex:outputField value="{!NewOpp.RecordTypeId}"/>

 I recieve this error : RecordTypeId is a unsupported field value. However,  I can display the actual Id value by using this:

 

<apex:outputText value="Record Type Id :{!NewOpp.RecordTypeId}"/>

 but I want to Display the Name of the RecordType, for Example 'New Oportunity Record Type' and not the 18 character Id. 

 

Any ideas on how to accomplish this?

 

Regards,

 

 

{!URLFOR($Action.Opportunity.Clone, Opportunity.Id, [cloneli=1],true)}

 Is it possible to set a value for Opportunity name, for example, in the URLFOR syntax? If so, what would be the syntax for this example.

 

Regards,

Hello.. I've run into a problem I have not seen before with Eclipse. I have a test case for a simple custom Controller. When I add this code to my test Apex class I get the following error.

Severity and Description Path Resource Location Creation Time Id Save error: Unable to perform save on all files: An unexpected error has occurred. Please try again, or check the log file for details. SFDC-Production/src/classes Tester.cls line 1 1258989848164 3832

 Checking the Eclipse log I see this:

!ENTRY com.salesforce.ide.core 2 0 2009-11-23 07:24:08.117 !MESSAGE WARN [2009-11-23 07:24:08,101] (ProjectService.java:handleDeployResult:1892) - Save failed! !ENTRY com.salesforce.ide.core 2 0 2009-11-23 07:24:08.132 !MESSAGE WARN [2009-11-23 07:24:08,132] (ProjectService.java:handleRetrieveResult:2037) - Nothing to save to project - retrieve result is empty !ENTRY com.salesforce.ide.core 4 0 2009-11-23 07:24:08.148 !MESSAGE ERROR [2009-11-23 07:24:08,148] (BuilderController.java:handleException:134) - Unable to perform save on all files. !STACK 0 java.lang.NullPointerException at com.salesforce.ide.core.services.ProjectService.setRunTestFailureMarker(ProjectService.java:2303) at com.salesforce.ide.core.services.ProjectService.handleRunTestMessages(ProjectService.java:2278) at com.salesforce.ide.core.services.ProjectService.handleRunTestResult(ProjectService.java:2198) at com.salesforce.ide.core.services.ProjectService.handleDeployResult(ProjectService.java:1904) at com.salesforce.ide.core.project.BuilderController.handleSaves(BuilderController.java:118) at com.salesforce.ide.core.project.BuilderController.build(BuilderController.java:95) at com.salesforce.ide.core.project.BuilderController.build(BuilderController.java:75) at com.salesforce.ide.core.project.OnlineBuilder.incrementalBuild(OnlineBuilder.java:79) at com.salesforce.ide.core.project.OnlineBuilder.build(OnlineBuilder.java:49) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:624) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:37) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:166) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:197) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:246) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:37) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:249) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:302) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:334) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:137) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:235) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

 This Test apex class looks like this:

 

static testMethod void testCPcontrollerApex() { Contact con = [select Id, Name from Contact where Id = '0035000000VnUZk']; User u = [select Id, ContactId from User where ContactId = :con.Id]; u = [SELECT id, UserName, CompanyName, Email FROM User WHERE Id=:u.id]; System.assertEquals('Tom.Sample@company.com',u.UserName);// Test to make sure the case was inserted. System.assertEquals('Tom.Sample@company.com',u.Email); PageReference pageRef = Page.CP_Welcome_Message2; // Get the VF Page that uses this controller. ApexPages.currentPage().getParameters().put('Id', u.id); //Do this first so controller has a user Id to work with. CPcontroller controller = new CPcontroller(); controller = new CPcontroller(); // Instantiate the new controller.. controller.getUser(); controller.getContact(); }

 This same test class works fine in my sandbox environment.  I can save other apex class changes fine, only this piece of code fails to save. Any ideas what the problem is?

 

Regards,

 

 


 

Under the section of 'Test Coverage Warnings' how do you tell what trigger is assocated with the warning Message:

 

 

Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required

 

Is it entirely going through each trigger manually or is spelled out it the test results some where. We have several triggers and the list of debug information is quiet long.

 

Regards

Hello, This custom controller is attempting to read data from the User and Contact object  from  a Case record but the  VF fails to compile with 'Unknown constructior CPcontroller.CPcontroller().'

 

I think the main issue is I'm not able to get the Case Id correctly in the controller when I try to use the Apex.Pages.StandardController.

How can I retrieve the Case Id of my current record using this custom controller.

 

VF and Controller code is as follows:

 

public class CPcontroller {
private final Case ca;
public CPcontroller(ApexPages.StandardController controller) {
this.ca = (Case)controller.getRecord();
cid = ca.id;
conid = ca.ContactId;
system.debug('cid is :' +cid);
}
public User getUser() {
return [select id,Name,ContactId,TimeZoneSidKey,Account_Sharing__c, Title, CompanyName,Phone,Extension,Fax,MobilePhone,
Email,Street,City,State,Country,PostalCode,CurrencyIsoCode from User where ContactId =
:conid];
}
public Contact getContact() {
return [select id, Name,Email,Phone,Fax,MailingStreet,MailingCity,MailingState,MailingPostalCode,MailingCountry,Title,
ContactAccountName__c from Contact where Id = :conid];
}
private Id cid { // Get the Case Id
get {
if(ApexPages.currentPage().getparameters().get('cid') != null) {
cid = ApexPages.currentPage().getparameters().get('cid');
}
return cid;
}
set {
if(value != null) cid = value;
}
}
private Id conid { // Get the Contact Id
get {
if(ApexPages.currentPage().getparameters().get('conid') != null) {
conid = ApexPages.currentPage().getparameters().get('conid');
}
return cid;
}
set {
if(value != null) conid = value;
}
}

}

 

<apex:page controller="CPcontroller" tabStyle="User"> <apex:form > <apex:pageBlock > <apex:pageBlockSection title="User Info"> <apex:outputField value="{!User.Name}"/> <apex:outputField value="{!User.Title}"/> <apex:outputField value="{!User.CompanyName}"/> <apex:outputField value="{!User.Phone}"/> <apex:outputField value="{!User.Extension}"/> <apex:outputField value="{!User.Fax}"/> <apex:outputField value="{!User.MobilePhone}"/> <apex:outputField value="{!User.Email}"/> <apex:outputField value="{!User.Street}"/> <apex:outputField value="{!User.City}"/> <apex:outputField value="{!User.State}"/> <apex:outputField value="{!User.PostalCode}"/> <apex:outputField value="{!User.Country}"/> <apex:outputField value="{!User.CurrencyIsoCode}"/> <apex:outputField value="{!User.TimeZoneSidKey}"/> <apex:outputField value="{!User.Account_Sharing__c}"/> <apex:outputLabel value="Enter your name: "/> </apex:pageBlockSection> <apex:pageBlockSection title="Contact Info"> <apex:outputField value="{!User.Contact.Name}"/> <apex:outputField value="{!User.Contact.Email}"/> <apex:outputField value="{!User.Contact.MailingStreet}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>

 

 

 

 

Hello... this is my first attempt at a custom controller. The purpose is to get  user and contact information from a Custom Controller based on the User object. I recieve the following error:

 

'System.QueryException: List has no rows for assignment to SObject'

 

 at the ' private final User user; ' statement. This was pretty much out of the Apex Developer guide for Custom Controllers  but I'm obviously missing something because I can't get past this error. 

 

Thanks for looking.

 

Regards,

public class CPcontroller {
private final User user;
private final Contact contact;
private final Case c;
public CPcontroller() {


user = [select id,Name,ContactId,TimeZoneSidKey,Account_Sharing__c, Title, CompanyName,Phone,Extension,Fax,MobilePhone,
Email,Street,City,State,Country,PostalCode,CurrencyIsoCode from User where Id =
:ApexPages.currentPage().getParameters().get('Id') ];
contact = [select id, Name,Email,Phone,Fax,MailingStreet,MailingCity,MailingState,MailingPostalCode,MailingCountry,Title,
ContactAccountName__c from Contact where Id = :user.Contactid] ;

}

public User getUser() {
return user;
}

public Contact getContact() {
return contact;

}
public PageReference save() {
update user;
update contact;
return null;
}


}

 

In CustomerPortal there's a narrow window ( left side)  that Welcomes the CP user and shows the user his Profile and allows the user to Log out. In the My Profile screen there are two buttons that allow the user to edit their profile  and change their pasword. How can I remove or hide these buttons?

 

Regards,

Hello I currently have a button that executes a VF page that calls a extension controller on the Case Object. This button provides the Case history for this Case Id when a user is logged in via Customer Portal. Everything works fine except..... when the button is pressed a new browser window is opened. When I click the tab to return to the case it returns to the newly opened window not the original window. If the user presses this button several times the users is left with several windows open.

 

Is there some parameter/argument ( in either the VF page or the controller extension)  that I can use that when VP button is pressed it uses the same browser window? 

 

Regards,

I need to create  a UserRole record as part of test class. The field 'PortalType' is a picklist defined field. I've seen several examples of reading the values from the picklist but no examples of how to create a new record containing a picklist field. not a new value, but a existing value within the picklist for this note new UserRole record. For example, this snippet will result in the error :'Field PortalType is not writable'. What is the correct procedure?

 

Regards,

 

 

UserRole r = new UserRole(RollupDescription =a.Name + ' Customer Manager',PortalType = 'Customer Portal', PortalRole = 'Manager', PortalAccountId = a.Id); insert r;

 

  • September 29, 2009
  • Like
  • 0

I would like to use a if statement in a trigger that checks if the User Profile is like 'ABC Customer Portal'. The following snippet doesn't like the use of the 'Like' keyword. I have also tried  ' += ' but that results in a error that 'And can be used only with boolean expressions'.

 

What is the proper syntax for using a like contition withn a If statement?

 

Regards,

 

String pf = u.ProfileId; Profile pfName = [select Name from profile where id = :pf]; String UserId = u.Id; if (contactId!=null && contactId!='' && (pfName.Name LIKE '%ABC Customer Portal%')) { . . . }

 

  • September 25, 2009
  • Like
  • 0

I have a VF page ( VF page1)  that is using a extention Controller to display case history. I have another VF page ( VF page2 )  that will render a printable version of the Case history. I would like to add a command button ( <apex:commandButton) to allow VF page1 to call VF Page2. Is this possible or is there a better way to acomplish this?

 

Regards,

Hello, Is there a way to determine the Profile of a user that has 'tripped' a trigger? I would like to know if the current user is NOT a Sys admin profile then execute a certain portion of a trigger. If the person is a Sys admin profile, then execute a different piece of code in the trigger. An example would be very helpful. Thanks.

 

Regards,

 

Hello ... I have a very simple VF page that uses a standard controller extension. The Apex class returns a list of records that is populated in VF page. At present, I'm at a loss as to writting a test method for the APEX class.

 

Notice that in the apex I'm getting the record that has been selected by the user. So, in this simple case I'm returning to the VF page this selected record only. Can someone advise me how I can do a test method. Currently I'm creating a Account, opportunity, contract and assets in the test method. I don't  believe I'm defining the controller correctly since I always see 0% code covered in 'Run all tests' under Apex classes. So what do I need to do to get a valid test method written? Any help would be appreciated.

Regards,

 

Test Method:

     static testMethod void testToolsAEApex()  
    {
        Test.setCurrentPageReference(new PageReference('Page.ToolsAE'));
          ApexPages.standardController controller = new ApexPages.standardController(new Asset_Entitlement__c());
        Account a = new Account(Name='Becky Test');
        insert a;
        
        Opportunity  opp = new Opportunity();
        opp.Name='Test';
        opp.CurrencyIsoCode = 'USD';    
        opp.AccountId = a.Id;
        opp.Type = 'Term';
        opp.Type_2__c = 'Tools';
        opp.Sector__c = 'Academic';
        opp.CloseDate = system.today();
        opp.StageName = 'Proposal';
        opp.ForecastCategoryName = 'Pipeline';
        opp.OwnerId = '00550000000n1k8';
        
        insert opp;
        
        Contracts__c  con = new Contracts__c();
        con.Contract_Name__c='Test';
        con.CurrencyIsoCode = 'USD';
        con.Opportunity__c = opp.Id;    
 
        insert con;
        
        Asset_Entitlement__c asset = new Asset_Entitlement__c();  
        asset.Account_del__c = opp.AccountId;              
        asset.Opportunity_Owner__c = opp.OwnerId;      
        asset.CurrencyIsoCode = opp.CurrencyIsoCode;       
        //asset.Product__c = pricebookMap.get(oppLines.PricebookEntryId).Product2.Id;                               
        asset.End_Date__c = system.today() - 10;        
        asset.Invoice_Date__c = system.today();        
        asset.Unit_Price__c = 12;        
        asset.Opportunity__c = opp.Id;
        asset.Start_Date__c = system.today();                   
        asset.Status__c = 'Expired';
        asset.Entitlement_Status__c = 'Current';
        asset.Term__c = 12;        
        asset.RecordTypeId = '012500000001C2f';
        asset.Contracts__c = con.Id;                 
        asset.Quantity__c = 1;
        asset.DNR__c = false;
        asset.Renew_Flag__c = false;  
        asset.Part_Number__c = '2091Test-MNT';  

        asset.License_Type__c = 'Term';  
        insert asset;
        ApexPages.currentPage().getParameters().get(con.Id);

 

 

Here's the APEX Class:

 

public class ToolsAE {
  private final Asset_Entitlement__c AE;
  String i = '' ;
  String conId ='';
  String noRec = 'N';
  public ToolsAE(ApexPages.StandardSetController controller)
  {   
       List<Asset_Entitlement__c> aeId = (List<Asset_Entitlement__c>) controller.getSelected();
    Parent_Opty_Aggregate__c, Group_Number__c,  from Asset_Entitlement__c where id IN :aeId]; //IN :aeId
    for(Asset_Entitlement__c j:aeId)
    {
     i = j.Id;
    }
     if(i == null || i ==''){
          noRec = 'Y';
          conId = ApexPages.currentPage().getParameters().get('id'); // If no records get the current Contract to return to.
     }
   }
 
  public List <Asset_Entitlement__c> aeList
  {
     get {
         List<Asset_Entitlement__c> aeList = new List<Asset_Entitlement__c>();
         for (Asset_Entitlement__c a:[select id, Contracts__c, Name, Parent_Opty_Aggregate__c, Group_Number__c,
            Account_del__c, Entitlement_Status__c,Distrib_Method__c, Start_Date__c, End_Date__c,Term__c,Unit_Price__c,Total_Price__c
               from Asset_Entitlement__c where id  = :i])
        {
              aeList.add(a);
              conId = a.Contracts__c; //Grab the Contract Id so we can use it later to return to
        }
        if (noRec == 'Y')
       {
          ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'No Header Aggregate Records  were selected.');
           ApexPages.addMessage(myMsg);
           return null;
       }
         else
        return aeList;
     }
     set;
   
 } 
 
   public PageReference ret() {
          PageReference conPage = new PageReference('/' + conId);//Return to Contract Page
          conPage.setRedirect(true);
          return conPage;
     }
}

I have a small trigger that will not allow a contact to be deleted if the contact is part of a active Ship_To for a entitlement. If the contact.Id is found to be in a active  record then prevent the deletion by calling the addError() to notify the user.

 

The problem is writting a test method. If my test method actually tries to delete the contact then, of course, the addError is called but then the test class fails because of the addError. If I change the test method not to try and delete the contact then, of course, that section of code is never execute... BUT the % of covered code is only 40%. Is there away to boost the %  ? I can add a bunch of extra lines like; Integer Count2 etc... to rais ethe %  but it seems there should be a better way.


trigger ValidateContact on Contact (before delete) {
// This trigger prevents the deletion of any Contact that
// has an associated ShipTo.
// Trigger.oldMap is a trigger context variable that maps Ids to every
// Contact that is about to be deleted.
// Create a list of associated ShipTo's:



Integer Count = 1;
for (Ship_To__c s : [select Contact__c, Contract_Number__c,Contact_Salutation_First_and_Last_Name__c, Entitlement_Status__c from Ship_To__c
where Contact__c in :Trigger.oldMap.keySet() ]) {

// For every ShipTo that is active, retrieve the related ShipTo
// from Trigger.oldMap and prevent it from being deleted by placing
// an error message on the Contact.
if(s.Entitlement_Status__c == 'Current' ||s.Entitlement_Status__c == 'In Progress' ||s.Entitlement_Status__c == 'Expired' )
{
Trigger.oldMap.get(s.Contact__c).addError(
'Cannot delete this contact: ' + s.Contact_Salutation_First_and_Last_Name__c + ' because they are specified as a ShipTo Contact in a Current, In Progress or Expired Asset or Entitlement. Contract = '+ s.Contract_Number__c + '. Number of Entitlements found for this Contact: ' + Count);

Count++;
}
}
}

  Here's the Test method:

static testMethod void testValidateContactTrig()
    {
        Account a = new Account(Name='Helen Account Trigger Test');
        insert a;
       
        Contact c = new Contact(accountid=a.Id, lastname='MyLastName', Status__c='Active');
        insert c;
       
       Opportunity  opp = new Opportunity();
        opp.Name='Test';
        opp.CurrencyIsoCode = 'USD';   
        opp.AccountId = a.Id;
        opp.Type = 'Term';
        opp.Type_2__c = 'Tools';
        opp.Sector__c = 'Academic';
        opp.CloseDate = system.today();
        opp.StageName = 'Proposal';
        opp.ForecastCategoryName = 'Pipeline';
        opp.OwnerId = '00550000000n1k8';
        insert opp;
       
      Contracts__c  con = new Contracts__c();
        con.Contract_Name__c='Test';
        con.CurrencyIsoCode = 'USD';
        con.Opportunity__c = opp.Id;
        con.Status__c = 'In Progress'; 
        con.Contract_Type__c = 'Renewal'; 
 
        insert con;
               
      Asset_Entitlement__c asset = new Asset_Entitlement__c(); 
        asset.Account_del__c = opp.AccountId;             
        asset.Opportunity_Owner__c = opp.OwnerId;     
        asset.CurrencyIsoCode = opp.CurrencyIsoCode;      
        //asset.Product__c = pricebookMap.get(oppLines.PricebookEntryId).Product2.Id;                              
        asset.End_Date__c = system.today() - 10;       
        asset.Invoice_Date__c = system.today();       
        asset.Unit_Price__c = 12;       
        asset.Opportunity__c = opp.Id;
        asset.Start_Date__c = system.today();                  
        asset.Status__c = 'Expired';
        asset.Entitlement_Status__c = 'In Progress';
        asset.Term__c = 12;       
        asset.RecordTypeId = '012500000001C2f';
        asset.Contracts__c = con.Id;                
        asset.Quantity__c = 1;
        asset.DNR__c = false;
        asset.Renew_Flag__c = false; 
        asset.Part_Number__c = '2091Test-MNT';   //THS 3/5/2009
        asset.License_Type__c = 'Term'; 
        insert asset;
       Ship_To__c ST = new Ship_To__c();
         ST.Asset_Entitlement__c = asset.Id;
         ST.Contact__c = c.Id;
         ST.Contact_Touch_Count__c = null;
         insert ST;
        //delete c; // try to delete contact that
    }
   

In order to avoid a DML governor limitiation,I'm trying to bulk update a custom object field using Maps. In the Debug log I see the values populating the field yet it is never 'updated' in the UI. I'm missing a step. The purpose of this trigger is when a Contracts__c.Status__c is set to 'Current', also set the associated entitlement records 'Entitlement_Status__c' record to the same value.

 

Thanks.

 

This is the trigger:

 

trigger ContractUpdateAEs on Contracts__c (after update)
{
    Integer i = 0;
    Map<ID,Contracts__c> conMap = new Map<ID,Contracts__c>(Trigger.old);
    Set<ID> conSet = conMap.keySet();    
    List<Contracts__c> conList  = [select Id, Status__c  from Contracts__c where Id IN :conSet];
      
    Map<String,Asset_Entitlement__c> aeMap = new Map<String,Asset_Entitlement__c> ([select Id, Entitlement_Status__c, Contracts_Status__c, Contracts__c from Asset_Entitlement__c where Contracts__c IN :conSet]);
    Set<String> aeSet = aeMap.keySet(); 
    Contracts__c old_c = Trigger.old[i]; //Contains image before change
    Contracts__c new_c = Trigger.new[i]; // Contains image of change to be committed
    if(old_c.Status__c != 'Current' && new_c.Status__c == 'Current')
    {      
          
      for(Asset_Entitlement__c aes :aeMap.Values())
      {
        aes.Entitlement_Status__c = aeMap.get(aes.Id).Contracts_Status__c;
        system.Debug('!!!!!!!!!:aes.Entitlement_Status__c  ' + aes.Entitlement_Status__c + '          AE Id is: ' + aes.Id);//These values look correct in debug log.   
      }     
 
    }
 
   
}

I would like to have a SOQL query to see if a field contains more than 25 characters. The field is defined as a length of 255. Tried various ways with LEN but no joy. Any suggestions on how this can be accomplished

 

Select o.Purchase_Order__c from Opportunity o Where LEN() o.Purchase_Order__c > 25

 

ery to see if there

 

  • September 01, 2010
  • Like
  • 0

I would like to just display a informational message to users at the end of a piece of APEX code to refresh the page. This does not involve a VF page, just a APEX class that creates some child records. Or to avoid this message altogether,  is there a way to refresh the page just from a APEX class and not using a VF page?

 

Regards,

I have  a boolean field I would like to have send a HTTP post to another app when set to true. Is this possible with a t rigger? If so are there some examples I could use to implement this?

 

Regards,

Hello, I have a query to get the Opportunity and associated opportunity line items via the following SOQL which works very well:

OldOpp = [Select Id, name, Probability, StageName, CloseDate, OwnerId, AccountId, Type, Sales_Contact__c, Type_2__c, Sector__c, CurrencyIsoCode, Payment_Terms__c,Lost_Reason__c,HPR_Pipeline_Category__c,HPR_Project_Type__c, OnLine_Order_del__c, Description, NextStep, ELN_Application__c, Quote_Good_Through__c,Quote_FormattedId__c,Additional_Conditions__c,Quote_CreatedDate__c , Quote_LastModifiedDate__c,RecordTypeId,Consortia_Name__c,Client_Legal_Contact__c, LeadSource,Bill_To__c,CampaignId,Winning_Competitor__c,Pilot_Start__c, Pilot_End_FQ__c,Phase__c, (Select Id, OpportunityId , Description, PriceBookEntryId, Quantity, TotalPrice, License_Type__c,Product_Type__c from OpportunityLineItems) from opportunity where id = :OppId ];

 

In another function, I DeepClone the Opportunity line items and set values in the newly created line items, however, I am having trouble setting a value in the new line item from the value in old line item ( OldOpp.OpportunityLineItems). See the APEX snippet below:

 

OpportunityLineItem[] products = OldOpp.OpportunityLineItems.DeepClone(false);
for (OpportunityLineItem each :products) {
each.OpportunityId = NewOpp.id;
each.TotalPrice = 0;
each.Description = '[CLONED]' + each.description;
each.Quantity = 1;
each.License_Type__c = OldOpp.OpportunityLineItem.License_Type__c;
/* I've tried the following to no avail....

each.License_Type__c = OldOpp.OpportunityLineITem__r.License_Type__c;

each.License_Type__c = products.License_Type__c;


  */

 

}
insert products;

 So, what I am trying to accomplish is setting the value of License_Type__c in the cloned Line item to thevalue I queried in the first query.  Any suggestions on how to accomplish this?

 

Regards,

 

 

 

Hello.. I've found  a sample piece of APEX code that would addresses a requirement we have,  however I receive this error when compiling the CaseHistoryCon.cls:

 

Save error: Constructor not defined: [History].<Constructor>(Datetime, Boolean, String, String, String, String, String)    CaseHistoryCon.cls    line 58   

 

 

Any suggestions on how to correct this? I've included the CaseHistoryCon.cls and the History.cls. It appears we're sending the correct number of parameters. This would seem pretty straignt forward but so far the fix has eluded me.

 

Regards,

public class CaseHistoryCon {
public boolean fullComments { get; private set; }
// Property value that controls visibility of related objects which are not visible in the customer portal.
public boolean hidePrivate { get; private set; }
private final Case ca;
public CaseHistoryCon(ApexPages.StandardController controller) {
this.ca = (Case)controller.getRecord();
fullComments = true;
hidePrivate = true;
truncatedCommentLength = 100;
cid = ca.id;
}
// Action method for toggling the fullComments property
public void toggleComments() { fullcomments = !fullcomments; }

// Action method for toggling the visibility control for private related objects.
public void togglePrivate() { hidePrivate = !hidePrivate; }

// Action method for navigating the user back to the case page.
public PageReference backToCase() {
return new ApexPages.StandardController(c).view();
}

// Accessor for retrieving the case object and its related items. If the cid property is null this
// method will return a new, empty case object. The functionality in this method could have been placed
// in the get property accessor for the private property named 'c' below but for simplicity of the page
// author in referencing the current case object this method was created because it is not possible to
// create a variable named 'case' since it is a reserved term in Apex.
public Case getcase() {

if(cid == null) return new Case();
return [SELECT casenumber, subject, contact.name, contact.email,
(SELECT CreatedBy.Name, CreatedDate, CommentBody,IsPublished FROM CaseComments ORDER BY CreatedDate ASC),
(SELECT CreatedBy.Name, CreatedDate, Field, NewValue, OldValue FROM Histories ORDER BY CreatedDate ASC),
(SELECT CreatedBy.Name, CreatedDate, Name FROM Attachments ORDER BY CreatedDate ASC),
(SELECT Owner.Name, ActivityDateTime, Subject, IsVisibleInSelfService FROM Events WHERE ActivityDateTime <= :System.Now() ORDER BY ActivityDateTime ASC),
(SELECT Owner.Name, LastModifiedDate, Subject, IsVisibleInSelfService, Description FROM Tasks WHERE ActivityDate <= :System.Today() // added Description THS 8/2009
AND IsClosed = true ORDER BY LastModifiedDate ASC)
FROM case
WHERE id = :cid];

}

// This accessor provides the page with the ordered collection of history (apex) objects for display in the page.
// it also processes the truncation of case comments as specified by the fullComments property value.
public History[] getHistories() {
History[] histories = new History[]{};
for (CaseComment comment:c.casecomments) {
if (!hidePrivate || comment.ispublished) {
addHistory(histories, new History(comment.createdDate, comment.ispublished, comment.createdby.name,'' ,'Comment Added', '' , truncateValue(comment.commentbody)));
}
}

for (Event e:c.events) {
if (!hidePrivate || e.isvisibleinselfservice) {
addHistory(histories, new History(e.activitydatetime, e.isvisibleinselfservice, e.owner.name, '' , 'Event Completed', '' , e.subject));
}
}

for (Task t:c.tasks) {
if (!hidePrivate || t.isvisibleinselfservice) {
addHistory(histories, new history(t.lastmodifieddate, t.isvisibleinselfservice, t.owner.name, t.Subject , 'Task Completed', '' , t.Description)); //Added Description THS 8/2009 subject
}
}
for (CaseHistory ch:c.histories) {
addHistory(histories, new history(ch.createdDate, true, ch.createdby.name, ch.field + ' Change', String.valueOf(ch.oldvalue), String.valueOf(ch.newvalue)));
system.debug('##################### CaseHistory: ' +ch.oldvalue + ' ' +ch.newvalue);
}

for (Attachment a:c.attachments) {
addHistory(histories, new history(a.createdDate, true, a.createdby.name,'' , 'Attachment Added', '' , a.name));
}

return histories;
}

// This method adds the newHistory object to the given histories collection in the appropriate order.
// The order provided here places the oldest records at the front of the list, i.e. by date ascending.
private void addHistory(History[] histories, History newHistory) {
Integer position = histories.size();
for (Integer i = 0; i < histories.size(); i++) {
if (newHistory.historydt < histories[i].historydt) {
position = i;
break;
}
}

if (position == histories.size()) {
histories.add(newHistory);
} else {
histories.add(position, newHistory);
}
}

// Returns the truncated string value if that is specified in the current state (!fullComments)
// and the current length is greater than the value of the private truncatedCommentLength property.
private String truncateValue(String s) {
if (!fullComments && s.length() > truncatedCommentLength) {
s = s.substring(0,truncatedCommentLength) + '...';
}

return s;
}

// The ID value of the case that will be used by the getCase() method to query for the related
// objects used to generate the ordered history collection. The value will be based on the request
// parameter, if available.
private Id cid {
get {
if(ApexPages.currentPage().getparameters().get('cid') != null) {
cid = ApexPages.currentPage().getparameters().get('cid');
}
return cid;
}
set {
if(value != null) cid = value;
}
}

// The case object set by the getCase method and used by the getHistories method to acquire
// the related records.
private Case c {
get { return getCase(); }
set;
}

// The length of "Short Comments" which is used by the truncateValue method in this class to
// truncate case comments when specified by the user.
private Integer truncatedCommentLength { get; set; }

public PageReference NavigateToPrintablePage() {
//cid = ApexPages.currentPage().getparameters().get('cid');
PageReference pageRef = new PageReference('/apex/caseHistoryPrint');
if(ApexPages.currentPage().getparameters().get('cid') != null) {
cid = ApexPages.currentPage().getparameters().get('cid');
}
return pageRef;

}

}

 

 

public class History{ // Properties of the class. Changed from history to History to avoid compile errors in other classes/pages. public datetime historydt { get; private set; } public boolean ispublic { get; private set; } public string actorname { get; private set; } public string historyType { get; private set; } public string to { get; private set; } public string fr { get; private set; } // Class constructor public History(Datetime d, boolean p, String actor, String ht, String f, String t) { historydt = d; historydate = d.format(); ispublic = p; actorname = actor; historyType = ht; fr = f; to = t; } // Formatting methods utilized primarily by the CaseHistoryPrint Visualforce page public string historydate { get; set; } public string dtmonthyr { get { return historydt.format('MMMMM yyyy'); } } public string dttime { get { return historydt.format('h:mm a');} } public string dtdayfmt { get { return historydt.format('d - EEEE'); } } public integer dtmonth { get { return historydt.month();} } public integer dtyear { get { return historydt.year();} } public integer dtday { get { return historydt.day();} } }

 


 

 

 

 

Hello, I would like to display the name of the RecordTypeId field in a VF page. If I use the following

<apex:outputField value="{!NewOpp.RecordTypeId}"/>

 I recieve this error : RecordTypeId is a unsupported field value. However,  I can display the actual Id value by using this:

 

<apex:outputText value="Record Type Id :{!NewOpp.RecordTypeId}"/>

 but I want to Display the Name of the RecordType, for Example 'New Oportunity Record Type' and not the 18 character Id. 

 

Any ideas on how to accomplish this?

 

Regards,

 

 

{!URLFOR($Action.Opportunity.Clone, Opportunity.Id, [cloneli=1],true)}

 Is it possible to set a value for Opportunity name, for example, in the URLFOR syntax? If so, what would be the syntax for this example.

 

Regards,

Hello.. I've run into a problem I have not seen before with Eclipse. I have a test case for a simple custom Controller. When I add this code to my test Apex class I get the following error.

Severity and Description Path Resource Location Creation Time Id Save error: Unable to perform save on all files: An unexpected error has occurred. Please try again, or check the log file for details. SFDC-Production/src/classes Tester.cls line 1 1258989848164 3832

 Checking the Eclipse log I see this:

!ENTRY com.salesforce.ide.core 2 0 2009-11-23 07:24:08.117 !MESSAGE WARN [2009-11-23 07:24:08,101] (ProjectService.java:handleDeployResult:1892) - Save failed! !ENTRY com.salesforce.ide.core 2 0 2009-11-23 07:24:08.132 !MESSAGE WARN [2009-11-23 07:24:08,132] (ProjectService.java:handleRetrieveResult:2037) - Nothing to save to project - retrieve result is empty !ENTRY com.salesforce.ide.core 4 0 2009-11-23 07:24:08.148 !MESSAGE ERROR [2009-11-23 07:24:08,148] (BuilderController.java:handleException:134) - Unable to perform save on all files. !STACK 0 java.lang.NullPointerException at com.salesforce.ide.core.services.ProjectService.setRunTestFailureMarker(ProjectService.java:2303) at com.salesforce.ide.core.services.ProjectService.handleRunTestMessages(ProjectService.java:2278) at com.salesforce.ide.core.services.ProjectService.handleRunTestResult(ProjectService.java:2198) at com.salesforce.ide.core.services.ProjectService.handleDeployResult(ProjectService.java:1904) at com.salesforce.ide.core.project.BuilderController.handleSaves(BuilderController.java:118) at com.salesforce.ide.core.project.BuilderController.build(BuilderController.java:95) at com.salesforce.ide.core.project.BuilderController.build(BuilderController.java:75) at com.salesforce.ide.core.project.OnlineBuilder.incrementalBuild(OnlineBuilder.java:79) at com.salesforce.ide.core.project.OnlineBuilder.build(OnlineBuilder.java:49) at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:624) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:37) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:166) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:197) at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:246) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:37) at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:249) at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:302) at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:334) at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:137) at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:235) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

 This Test apex class looks like this:

 

static testMethod void testCPcontrollerApex() { Contact con = [select Id, Name from Contact where Id = '0035000000VnUZk']; User u = [select Id, ContactId from User where ContactId = :con.Id]; u = [SELECT id, UserName, CompanyName, Email FROM User WHERE Id=:u.id]; System.assertEquals('Tom.Sample@company.com',u.UserName);// Test to make sure the case was inserted. System.assertEquals('Tom.Sample@company.com',u.Email); PageReference pageRef = Page.CP_Welcome_Message2; // Get the VF Page that uses this controller. ApexPages.currentPage().getParameters().put('Id', u.id); //Do this first so controller has a user Id to work with. CPcontroller controller = new CPcontroller(); controller = new CPcontroller(); // Instantiate the new controller.. controller.getUser(); controller.getContact(); }

 This same test class works fine in my sandbox environment.  I can save other apex class changes fine, only this piece of code fails to save. Any ideas what the problem is?

 

Regards,

 

 


 

Under the section of 'Test Coverage Warnings' how do you tell what trigger is assocated with the warning Message:

 

 

Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required

 

Is it entirely going through each trigger manually or is spelled out it the test results some where. We have several triggers and the list of debug information is quiet long.

 

Regards

Hello, This custom controller is attempting to read data from the User and Contact object  from  a Case record but the  VF fails to compile with 'Unknown constructior CPcontroller.CPcontroller().'

 

I think the main issue is I'm not able to get the Case Id correctly in the controller when I try to use the Apex.Pages.StandardController.

How can I retrieve the Case Id of my current record using this custom controller.

 

VF and Controller code is as follows:

 

public class CPcontroller {
private final Case ca;
public CPcontroller(ApexPages.StandardController controller) {
this.ca = (Case)controller.getRecord();
cid = ca.id;
conid = ca.ContactId;
system.debug('cid is :' +cid);
}
public User getUser() {
return [select id,Name,ContactId,TimeZoneSidKey,Account_Sharing__c, Title, CompanyName,Phone,Extension,Fax,MobilePhone,
Email,Street,City,State,Country,PostalCode,CurrencyIsoCode from User where ContactId =
:conid];
}
public Contact getContact() {
return [select id, Name,Email,Phone,Fax,MailingStreet,MailingCity,MailingState,MailingPostalCode,MailingCountry,Title,
ContactAccountName__c from Contact where Id = :conid];
}
private Id cid { // Get the Case Id
get {
if(ApexPages.currentPage().getparameters().get('cid') != null) {
cid = ApexPages.currentPage().getparameters().get('cid');
}
return cid;
}
set {
if(value != null) cid = value;
}
}
private Id conid { // Get the Contact Id
get {
if(ApexPages.currentPage().getparameters().get('conid') != null) {
conid = ApexPages.currentPage().getparameters().get('conid');
}
return cid;
}
set {
if(value != null) conid = value;
}
}

}

 

<apex:page controller="CPcontroller" tabStyle="User"> <apex:form > <apex:pageBlock > <apex:pageBlockSection title="User Info"> <apex:outputField value="{!User.Name}"/> <apex:outputField value="{!User.Title}"/> <apex:outputField value="{!User.CompanyName}"/> <apex:outputField value="{!User.Phone}"/> <apex:outputField value="{!User.Extension}"/> <apex:outputField value="{!User.Fax}"/> <apex:outputField value="{!User.MobilePhone}"/> <apex:outputField value="{!User.Email}"/> <apex:outputField value="{!User.Street}"/> <apex:outputField value="{!User.City}"/> <apex:outputField value="{!User.State}"/> <apex:outputField value="{!User.PostalCode}"/> <apex:outputField value="{!User.Country}"/> <apex:outputField value="{!User.CurrencyIsoCode}"/> <apex:outputField value="{!User.TimeZoneSidKey}"/> <apex:outputField value="{!User.Account_Sharing__c}"/> <apex:outputLabel value="Enter your name: "/> </apex:pageBlockSection> <apex:pageBlockSection title="Contact Info"> <apex:outputField value="{!User.Contact.Name}"/> <apex:outputField value="{!User.Contact.Email}"/> <apex:outputField value="{!User.Contact.MailingStreet}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>

 

 

 

 

Hello, I am trying to clone a Campaign along with CampaignMemberStatus.

 

In the following code segment, there are two approaches (one commented out) both of which fail with the error: Required fields are missing: [Label]: [Label]

 

Any help appreciated.  Thanks

 

    public PageReference Duplicate() {
        if (selection == '0') {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'Please select a template to use before clicking New.'));
            return null;
        }
        Campaign template = [SELECT Name FROM Campaign WHERE id = :selection];
        Campaign clone = template.clone(false);    // Create a clone without the id.
        clone.Template__c = false;
        clone.IsActive = true;
        clone.Name = 'New Campaign';
        insert clone;
        // Now that the Campaign has been inserted, we need to insert the CampaignMemberStatus list
        // BOTH OF THE FOLLOWING Approaches to insert the cloned list cause the following error:
        // Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Label]: [Label]
        List<CampaignMemberStatus> statuslist = [SELECT Id from CampaignMemberStatus WHERE CampaignId = :selection];
        List<CampaignMemberStatus> clonelist = statuslist.deepClone(false);
        for (CampaignMemberStatus status : clonelist) {
            status.CampaignId = clone.Id;
        }
        // List<CampaignMemberStatus> clonelist = new List<CampaignMemberStatus>();
        // for (CampaignMemberStatus status : statuslist) {
        //     CampaignMemberStatus sclone = status.clone(false);
        //     sclone.CampaignId = clone.Id;    // Point this CampaignMemberStatus to the inserted Campaign
        //     clonelist.add(sclone);
        // }
        insert clonelist;
        PageReference editPage = new ApexPages.StandardController(clone).edit();
        editPage.setRedirect(true); // ???  Do I need to do this?
        return editPage;
    }
 

  • October 22, 2009
  • Like
  • 0

As discussed in Ideas (http://ideas.salesforce.com/article/show/69729) here's a solution we have used for clients to enable customisation of the Clone button on Opportunities. This can be used to selectively choose which fields to copy and set default values:

 

For full details and the code to clone opportunity Line Items please contact me directly. We will be re-writing this in VisualForce over the coming months to make it futureproof.

 

Steps to Implement - Admins only

1. Setup -> Customize -> Opportunity -> Buttons and Links

2. Create new custom button called Clone, behaviour is Execute Javascript, Display Type Detail Page Button.

3. Paste in the code below and edit to match your requirements.

4. Remember to add the new button to the Opportunity page layout(s) and hide the original Clone button.

4. Test!

 

// Copyright 2008 BrightGen Ltd - All Rights Reserved try{ {!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")} // ** EDIT THIS QUERY TO LIST THE FIELDS YOU WANT TO COPY ** var result = sforce.connection.query("Select o.Type, o.StageName, o.Product_Type__c, o.Planned_Opportunity__c, o.MarketSector__c, o.CampaignId, o.Business_Unit__c, o.Amount, o.AccountId From Opportunity o WHERE o.Id = '{!Opportunity.Id}'"); var newOpp = result.getArray("records"); // Reset the Opp Id and reset fields to default values newOpp[0].Id = ''; newOpp[0].Name = "Clone {!Opportunity.Name}"; // ** EDIT THESE FIELDS TO SET DEFAULT ANY VALUES ** newOpp[0].StageName = "1. Prospecting"; newOpp[0].CloseDate = new Date(2099, 0, 1); var saveResult = sforce.connection.create(newOpp); if (saveResult[0].getBoolean("success")) { newOpp[0].id = saveResult[0].id; alert("Opportunity cloned without line items"); } else { alert("Failed to create clone: " + saveResult[0]); } // Refresh the page to display the new oppportunity window.location = newOpp[0].id; } catch (err) { alert (err.description ); }

 

 
Message Edited by bg_richard on 02-05-2009 07:11 AM
Does anyone know a good way to replicate the dependency between the Sales Stage and Probability % that you would have with a standard Opportunity screen if you are creating a custom Opportunity screen in Visual Force?  Just like in an out of the box Opp screen, when the user selects a sales stage, I want to corresponding Prob % to populate.
 
Thanks