• SteveBower
  • PRO
  • 2594 Points
  • Member since 2005

  • Chatter
    Feed
  • 91
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 25
    Questions
  • 901
    Replies

I have successfully created a page controlled by an Apex Class in my Sandbox and everything works very nicely. Basically it is a report of sorts as the page simply is listing a number of enteries on my opportunity table and a custom payment table. There are not any inputs or buttons the page calls all the information it needs together via URL parameters. My struggle is that I cannot get my test to go through and select any records, therefore my tests are not covering enough of the code and I can't deploy my class and page. Could someone please help me?

 

Here is my class

public class ConfServicesPaymentListing{
    public String prop;
    public String whom;
    public ConfServicesPaymentListing() {
        this.prop = ApexPages.currentPage().getParameters().get('property');
        this.whom = ApexPages.currentPage().getParameters().get('who'); }
    public void setProp(String prop) { this.prop = prop; }
    public void setWhom(String whom) { this.whom = whom; }
    
    public Date tday   = Date.Today();
    public Integer tmonth   = Date.Today().month();
    public Integer tyear    = Date.Today().year();
    public Integer daysThis = Date.daysInMonth(tyear, tmonth);
    public Date LastMonth = Date.Today()-daysThis;
    public Date NextMonth = Date.Today()+daysThis;
    public Date thisStart = Date.Today().toStartOfMonth();
    public Date lastStart = LastMonth.toStartOfMonth();
    public Date thisEnd   = NextMonth.toStartOfMonth();
    //Commissionable Bill Pay
    public Payments__c[] getPaymentBillThisComissionableList() {
        Payments__c[] pbtcl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Commissionable' AND Type__c='Bill Pay' AND Date_Recieved__c>=:thisStart AND Date_Recieved__c<:thisEnd                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pbtcl;
    }
    Payments__c pbtcl2;
    public Payments__c getPbtcl2(){
        pbtcl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pbtc : getPaymentBillThisComissionableList()){
        pbtcl2.Payment__c += pbtc.Payment__c; }
        return pbtcl2;  
    }
    //Commissionable Bill Pay Last Month
    public Payments__c[] getPaymentBillLastComissionableList() {
        Payments__c[] pbtcl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Commissionable' AND Type__c='Bill Pay' AND Date_Recieved__c>=:lastStart AND Date_Recieved__c<:thisStart                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pbtcl;
    }
    Payments__c pblcl2;
    public Payments__c getPblcl2(){
        pblcl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pblc : getPaymentBillLastComissionableList()){
        pblcl2.Payment__c += pblc.Payment__c; }
        return pblcl2;  
    }
    //Commissionable Deposit Pay This Month
    public Payments__c[] getPaymentDepositThisComissionableList() {
        Payments__c[] pdtcl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Commissionable' AND Type__c='Deposit' AND Date_Recieved__c>=:thisStart AND Date_Recieved__c<:thisEnd                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pdtcl;
    }
    Payments__c pdtcl2;
    public Payments__c getPdtcl2(){
        pdtcl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pdtc : getPaymentDepositThisComissionableList()){
        pdtcl2.Payment__c += pdtc.Payment__c; }
        return pdtcl2;  
    }
    //Commissionable Deposits Last Month
    public Payments__c[] getPaymentDepositLastComissionableList() {
        Payments__c[] pdlcl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Commissionable' AND Type__c='Deposit' AND Date_Recieved__c>=:lastStart AND Date_Recieved__c<:thisStart                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pdlcl;
    }
    Payments__c pdlcl2;
    public Payments__c getPdlcl2(){
        pdlcl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pdlc : getPaymentDepositLastComissionableList()){
        pdlcl2.Payment__c += pdlc.Payment__c; }
        return pdlcl2;  
    }
    //Non-Commissionable Bill Pay
    public Payments__c[] getPaymentBillThisNonList() {
        Payments__c[] pbtnl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Non-Commissionable' AND Type__c='Bill Pay' AND Date_Recieved__c>=:thisStart AND Date_Recieved__c<:thisEnd                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pbtnl;
    }
    Payments__c pbtnl2;
    public Payments__c getPbtnl2(){
        pbtnl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pbtn : getPaymentBillThisNonList()){
        pbtnl2.Payment__c += pbtn.Payment__c; }
        return pbtnl2;  
    }
    //Non-Commissionable Bill Pay Last Month
    public Payments__c[] getPaymentBillLastNonList() {
        Payments__c[] pbtnl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Non-Commissionable' AND Type__c='Bill Pay' AND Date_Recieved__c>=:lastStart AND Date_Recieved__c<:thisStart                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pbtnl;
    }
    Payments__c pblnl2;
    public Payments__c getPblnl2(){
        pblnl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pbln : getPaymentBillLastNonList()){
        pblnl2.Payment__c += pbln.Payment__c; }
        return pblnl2;  
    }
    //Non-Commissionable Deposit Pay This Month
    public Payments__c[] getPaymentDepositThisNonList() {
        Payments__c[] pdtnl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Non-Commissionable' AND Type__c='Deposit' AND Date_Recieved__c>=:thisStart AND Date_Recieved__c<:thisEnd                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pdtnl;
    }
    Payments__c pdtnl2;
    public Payments__c getPdtnl2(){
        pdtnl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pdtn : getPaymentDepositThisNonList()){
        pdtnl2.Payment__c += pdtn.Payment__c; }
        return pdtnl2;  
    }
    //Non-Commissionable Deposits Last Month
    public Payments__c[] getPaymentDepositLastNonList() {
        Payments__c[] pdlnl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Non-Commissionable' AND Type__c='Deposit' AND Date_Recieved__c>=:lastStart AND Date_Recieved__c<:thisStart                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pdlnl;
    }
    Payments__c pdlnl2;
    public Payments__c getPdlnl2(){
        pdlnl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pdln : getPaymentDepositLastNonList()){
        pdlnl2.Payment__c += pdln.Payment__c; }
        return pdlnl2;  
    }
    public Opportunity[] getOpportunityList() {
        Opportunity[] opps = [SELECT 
                                  Arrival_Date__c, Look_Up_Contact_Name__c, Arrive_Depart__c, Organization__c, Actual_Amount__c, System_Balance_Due__c, Property__c, Update_Required__c
                              FROM 
                                  Opportunity 
                              WHERE
                                  Password__c=:prop AND 
                                  ((StageName='Event Finalized' AND System_Balance_Due__c>0) OR
                                  ((StageName='GM' OR StageName='Anticipated' OR StageName='Projected') AND Arrival_Date__c<:tday AND Actual_Amount__c<1))
                              ORDER BY Arrival_Date__c
                              ];
        return opps;
    }
    Opportunity opp2;
    public Opportunity getOpp2(){
        opp2 = new Opportunity(Balance_Due__c = 0, Actual_Amount__c = 0, Guarenteed_Minimum_Payment__c = 0);
        for(Opportunity o : getOpportunityList()){
        opp2.Property__c = o.Property__c;
        opp2.Contract_Notes__c = ApexPages.currentPage().getParameters().get('property');
        opp2.Name = ApexPages.currentPage().getParameters().get('who');
        opp2.Balance_Due__c += o.System_Balance_Due__c; }
        return opp2;  
    }
    public pageReference generateReport() {
        PageReference goToNew = Page.ConfServices_PaymentListing;
        goToNew.getParameters().put('property', prop);
        goToNew.getParameters().put('who', whom);
        return goToNew;
    }
    public static testMethod void ConfServices_PaymentListingTest() {
       ConfServicesPaymentListing test = new ConfServicesPaymentListing();
       test.setProp('1234');
       test.setWhom('Zach');
       PageReference testPageReference = Page.ConfServices_PaymentListing;
       testPageReference.getParameters().put('property','1234');
       testPageReference.getParameters().put('who','Zach');
    system.assertEquals(testPageReference.getParameters(), test.generateReport().getParameters());
        Opportunity[] opp = [SELECT Property__c FROM Opportunity WHERE Password__c = '1234'];
        System.assertEquals('Lake Williamson', opp[0].Property__c);
}
}

When I look at the results after running the test each of the lines that start like the following two entries come out red, basically nothing will select, even through there are records to select in the sandbox and the main system. I have even tried createing records via the test, but nothing I have tried will improve these scores.

    public Payments__c[] getPaymentBillThisComissionableList() {
        Payments__c[] pbtcl = [SELECT
    Payments__c pbtcl2;
    public Payments__c getPbtcl2(){

I appreciate anyone's input.

  • September 09, 2012
  • Like
  • 0

I have an object say A containing 15 fields , when  I add a new record to object A only 10 fields out of 15 should be visible and I must be able to enter values into it and save the record.Now after I open this saved record ,all the 15 fields should be visible to me and I should be able to enter values into it.

              Is this possible using standard functionality of salesforce and how?If not how can it be done using  Visualforce page?

I have created a trigger which simply fails to update a field and I can't see why.

 

The tirgger looks at a new task coming in and compares the phone number on the task (t.Five9__Five9DNIS__c) with a phone number on the contact.  If they don't match.  Then it sets a custom field on the task.

 

I have have set up a test.   When I run it I use debug statements in the trigger to verify:  

* the trigger correctly identifies the mismatch

* the value of the field is changed.

 

However, the assertEquals (the final line in the test) fails!

 

What gives?

 

The Trigger:

 

trigger CheckPhoneMatch on Task (before insert, before update) {

    list<id> contactIds = new list<id>();
    for (Task t : trigger.new)
    {
        contactIds.add(t.whoid);
    }
    
    map<id,contact> contactMap = new map<id,contact>([Select Id, FirstName, LastName, DonorId__c, Phone from contact Where Id in :contactIds ]);
    // list<task> updatedTasks = new list<task>();
    
    for (Task t : trigger.new)
    {
        contact c = contactMap.get(t.whoid);
        
        System.Debug('/n/n*******       Phone ' + c.Phone + ' DNIS: ' + t.Five9__Five9DNIS__c + '       ********');
        
        
        if (c != null)
        {                        
            if (t.Five9__Five9DNIS__c != c.Phone)
            {
                System.Debug('DNIS DOES NOT MATCH');
                t.MismatchPhone__c = true;
                System.Debug('VAL IS: ' + t.MismatchPhone__c);                
            }                                    
        }
    }
}

 

The Test (only the final block of code is relevant):

 

@istest
private class TriggerTests {

   static testMethod void contactBeforeUpdate()
   {
     contact c = new contact();
     c.lastname = 'Smith';
     insert c;
     
     c.address1__c = '123 Main Street';
     c.email = 'test@company.com';
     c.Phone = '1234567890';
     update c;

        
     user u2 = [select id from user where isactive = true limit 1];
   
     task t = new task();
     t.ownerid = u2.id;
     t.whoid = c.id;
     t.subject = 'test';
     t.CallDisposition = 'Yes - Gift Info Acquired';
     t.Five9__Five9DNIS__c = '1234567890';
     
     insert t; 
          
     System.assertEquals(false, t.MismatchPhone__c);

     <OMITTING IRRELEVANT TESTS>               
     
     task t3 = new task();
     t3.ownerid = u2.id;
     t3.whoid = c.id;
     t3.subject = 'test2';
     t3.CallDisposition = 'Callback';   
     t3.Five9__Five9DNIS__c = '0987654321';
 
     insert t3;
     
     // THIS LINE FAILS!!!!!
     System.assertEquals(true, t3.MismatchPhone__c);
 
   }

}

 

 

Hello all,

I'm an APEX noob, so please help. It would be appreciated!

We have a custom button on the Opportunities page, "Create Contract."  The button opens a window for a new Contract and pulls certain fields from the Opportunity into the new Contract.

We have recently begun to use both Opportunity and Contract record types. We need to select the Contract record type based on the Opportunity record type.

Mapping examples:
Opportunity Record Type A - Contract Record Type A (this is the default Contract type)
Opportunity Record Type B - Contract Record Type A
Opportunity Record Type C - Contract Record Type A
Opportunity Record Type D - Contract Record Type B
Opportunity Record Type E - Contract Record Type C

I have succeeded in passing a single record type, but I am having trouble in setting up the IF- ELSE statement in the button code to handle multiple record types.

The code is below. I am 100% certain that my IF statement syntax is incorrect somewhere, because it appears that the program never enters the code.  The new Contracts page always opens with user's default contract page view.

If I replace the below IF statement with the line:

 

&RecordType=012M00000000AcK 

 


then that record type is used, and the Contracts page opens with the page view associated with that Contract Record Type.

If any of you could help me with the syntax for a two-part IF-ELSE statement then I can build out the rest of the scenarios. Thanks!

 

 

/800/e?retURL=%2F800%2Fo

&if ({!Opportunity.RecordTypeId}==012C00000003okgIAA){
// Do this if the condition is true 
RecordType=012M00000000AcK   
} else {
// Do this if the condition is not true 
RecordType=012800000003buxAAA
}

&ctrc7_lkid={!Opportunity.AccountId}
&00N80000003uEo4={!Opportunity.Country__c}
&CF00N80000003VFS3={!Opportunity.Name}
&00N80000003uEsV={!Opportunity.CloseDate}
&00N80000003uEn1={!Opportunity.Policy__c}
&ctrc5={!Opportunity.Contract_Start_Date__c}
&00N80000003uEnk={!Opportunity.ExPat__c}
&00N80000003uEnl={!Opportunity.ASO__c}
&00N80000003udsE={!Opportunity.Cross_Marketing__c}
&00N80000003uErI={!Opportunity.Type}
&00N80000003uEsG={!Opportunity.Pooled__c}
&00N80000004ILAP={!Opportunity.Insurance_Company__c}
&00N80000004ILAA={!Opportunity.Bill_Type__c}
&00N80000004CNNe={!Opportunity.Expat_Account_Manager__c}
&00N80000003uEmr={!Opportunity.LOB_Expat__c}
&00N80000003uEmh={!Opportunity.LOB_del__c}
&00N80000003uEui={!Opportunity.Quoted_Due_Date__c}
&00N80000003uEww={!Opportunity.Quoted_Received_Date__c}
&00N80000003uEnm={!Opportunity.Quoted_Release_Date__c}
&00N80000003uErJ={!Opportunity.Decline_Options__c}
&00N80000003uExV={!Opportunity.Lost_Options__c}
&00N80000003uEsH={!Opportunity.Currency__c}
&00N80000003uEn3={!Opportunity.Life_Premium__c}
&00N80000003uEn2={!Opportunity.of_Employees__c}
&00N80000003uEn4={!Opportunity.Medical_Premium__c}
&00N80000003uEo1={!Opportunity.Disability_Premium__c}
&00N80000003uEuh={!Opportunity.Dental_Premium__c}
&00NC0000004yFM1={!Opportunity.Business_Travel_Medical_Premium__c}
&00N80000004ENTC={!Opportunity.LTD_Premium__c}
&00N80000004ENTH={!Opportunity.Other_Premium__c}
&00N80000003uEmi={!Opportunity.Total_Premium__c}
&00N80000003uEsp={!Opportunity.Collected_Contribution__c}
&00N80000003uEo5={!Opportunity.Collected_ATO__c}
&00N80000003uEsv={!Opportunity.Total_Collected_Contribution__c}
&00N80000003uErE={!Opportunity.Est_Annual_Contribution__c}
&00N80000003uEtO={!Opportunity.Est_ATO__c}
&00N80000003uEtT={!Opportunity.Total_Est_Contribution__c}
&00N80000003uEtY={!Opportunity.Assets_Under_Mgmt__c}
&00N80000003uEsw={!Opportunity.Total_Atlas_Premium__c}
&Description={!Opportunity.Description}
&00NM0000000H3dR={!Opportunity.Discount_Percentage__c}

 

  • September 27, 2011
  • Like
  • 0

Hello, I am creating an VF for override "new" button of an custom object's home tab.

 I am trying to create a menu selection to control fields values ​​of the new page. 

After some operations, I need return to  standard "New" Page. For this,  I  make  a pagereference to new's url (Pagereference ('/a0G/e?retURL=/a0G/'))

But "new" button was overriding with this VF, so I can not use. How Can I resolve this?
Thanks in advance.

I want a VF web tab to navigate to a specific record, and so I defined the VF page ("TestNameExperiment") like this:

 

<apex:page standardController="My_Custom_Object__c"

                              action="{!URLFOR('/apex/TestNameExperiment?id=a0bE0000000PCIC')}" >

 

where a0bE0000000PCIC is the record ID.

 

This caused an infinite loop in which the VF page loads over and over again, which makes sense in hindsight.

 

What's the proper way to do this?

 

 

So, I have a trigger that retrieves a bunch of data from other objects and based on that updates a field on the record to be inserted, so I need a before insert trigger, right? right. But then I also need to create some junction objects between the inserted record and some other objects, so I need an after insert trigger. Now the idea of having to duplicate all of that code to do the fetching twice (I am talking performance here) does not give a warm fuzzy feeling. So anyone know a way I can generate the list of junction objects in the before trigger and store that list until the after trigger, add the missing ids, and insert? Or am I doomed to running through all this code twice? Thanks, Dovid

Hi!

 

You know that first inputField on the page gets focus on page load? So when the first inputField is a date field then the date picker annoyingly pops up automatically. Does anyone know a way to prevent this?

 

Thanks!

  • August 11, 2011
  • Like
  • 0

 

Hi All,

  

      How can I Control Visibility  of a button  present in  visual force page based on user's profile.

 

                     For e.g    The Button " save" should be Visible to System Admin profile and should'nt be visible to any other logged user profile.

                        

 

Thanks,

Ramana

Hi,

 

Is there any way touse substring and/or regular expressions in SOQL Select statements? The query I would like to do is something like:

new List<Account>([SELECT Id, Store_ID__c FROM Account WHERE Website = :domain_query])

Where domain_query is a stripped version of the domain. ie: google.com would be google

The Website field should therefor be stripped from http://, the country suffix and possibly www if it is there. http://www.google.com -> google

 

I could use a LIKE comparison and then use a loop to check for equality but that isn't a nice solution...

 

Any ideas?

public class abcd
     {
      public void m1()
      {
      Attachment myAttach = new Attachment();
      myAttach.ParentId = '001900000063kAB';//Id of the object to which the page is attached
      myAttach.name = 'attachment';
      PageReference myPdf = Page.one;//myPdfPage is the name of your pdf page
      myAttach.body = myPdf.getContentAsPdf();
      insert myattach;  
      }
      
      static testmethod void testm1()
      {
          abcd obj1=new abcd();
          obj1.m1();
      }
     }

 

Hi how can i conver the red marked line.



  • July 19, 2011
  • Like
  • 0

I have a simple visualforce page that I've added to a standard Opportunity page layout inline.  The query can return more records than what fits in the inline section of the page layout.

 

Is there a way I can add vertical scrollbars to view all the records that are returned?  Or, perhaps there is some JS that can manipulate the DOM and adjust the height of the inline section (that is probably a clumsy way to do it).  Or, maybe there is a paging mechnisim to elegantly page thru all the records?  Has anyone encountered this issue and what are the options and best solution?

 

Here is my VF page:

 

<apex:page standardController="Opportunity" extensions="SalesCoachActivityController">
	<apex:form >
		<apex:pageBlock >
			<apex:pageBlockTable value="{!SalesCoachActivity}" var="sca">
				<apex:column >
                	<apex:facet name="header">
                    	Sales Coach Activity
                	</apex:facet>
                	<apex:outputLink value="{!sca.Content_URL__c}" >{!sca.Name}</apex:outputLink>
            	</apex:column>
			</apex:pageBlockTable>
		</apex:pageBlock>
	</apex:form>
</apex:page>

 Here is my controller:

 

public class SalesCoachActivityController {
	
	private final Opportunity opp;
	private String stage;
	
	public SalesCoachActivityController(ApexPages.StandardController stdController) {
		this.opp = (Opportunity)stdController.getRecord();
		Opportunity o = [Select StageName From Opportunity Where Id =: opp.Id];
		stage = o.StageName;	
	}
	
	public List<Sales_Coach_Activity__c> getSalesCoachActivity() {
		String soql = 'Select Name, Content_URL__c From Sales_Coach_Activity__c Where Stage__c = \'' + stage  + '\' Order By Sequence_Number__c ASC';
		return Database.query(soql);
	}

}

 Also, in my constructor, I get the opportunity record id and then I have to run a query to get the stagename value that I use as a filter in the dynamic query in the getSalesCoachActivity() method.

 

Is there a way to eliminate the first query and get the stagename without having to query the opportunity?  It would be nice to reduce the queries to just one, if possible?

 

Thanks for any help.

I have created the following VF Page and controller extension to create, what is basically, a pop up of the comments field for logging a call.  This is assigned to a button as a URL on the Account page.  The idea is that everything is assigned within the controller while displaying just the comment box to enter info from the call.  Right now as it is currently written I can fill in everything I need except the account that the "log a call" is related to.  I am passing the account id through the URL in the button.  Any suggestions on how to grad the account id from the URL and make that the account it is related to would be great.

 

VF Page

<apex:page standardController="Task" extensions="LogACallControllerExtension" showHeader="false" sidebar="false">
    <apex:sectionHeader title="Log A Call" />
    <apex:form id="pageForm">
        <apex:pageBlock title="Call Edit" mode="edit">
            <apex:pageBlockButtons location="both">
                <apex:commandButton value="Save" action="{!save}" />
                <apex:commandButton value="Cancel" action="{!cancel}" />
            </apex:pageBlockButtons>
            <br />
            <apex:pageBlockSection title="Call Information" columns="1" collapsible="false">
                <apex:inputField value="{!Task.Description}" style="width:400px;height:100px;" />
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

 Controller Extension

public with sharing class LogACallControllerExtension {

    public Task task;
    ApexPages.Standardcontroller controller;
    
                public Account getAccount() {
                    return [SELECT Id, Name from Account where Id=:ApexPages.currentPage().getParameters().get('what_id')];
                }

    public LogACallControllerExtension(ApexPages.StandardController controller) {
            this.task = (Task)controller.getRecord();
            this.task.subject = 'Service Call';
            this.task.type = 'Call';
            this.task.status = 'Completed';
            this.task.activitydate = system.today();
            this.controller = controller;
    }
    public PageReference save() {
          return controller.save();
    }

}

 Button URL

/apex/Log_a_Call_in_Chatter?title=Call&what_id={!Account.Id}&followup=1&tsk5=Service Call&retURL=%2F{!Account.Id}&tsk3={!Account.Name}&tsk10=Call

 I have tried pulling the name from the URL that is assigned to 'tsk3', but it is giving me an error trying to assign a 'name' to a 'string'.

 

I am also wondering if it would be possible to take what is entered in the comment field and post that as a feed in the related account.

Hi all,

We built an interface to an external system using SOAP Callouts that trigger upon update on a certain object ('object1'). In order to successfully do the SOAP callout, we needed to put the callout in an @Future context, because callouts are only allowed from @Future classes.

 

This works fine, but....

 

We also have some processes in place that, whenever a certain other object ('object2') is updated, updates the matching object1. Since there can be a lot (thousands)  of matches, we also made this an @Future method. 

 

The problem, however, is that @Future methods cannot call @Future methods, so whenever object1 gets updated because of an update on object2, the export callout does not get triggered.

 

We've tried multiple solutions:

- using Outbound Messages instead. This is not an option since the object that gets exported also draws data from child objects when composing the SOAP message 

- I tried creating a static variable that checks whether an @Future method was already started, and proactively determines whether or not to run the callout as another @Future, but that doesn't help because the system tells me "Callout from triggers are currently not supported." (there is not @Future between the trigger on the object and the callout).

 

Any other suggestions? We'd want the interface to stay as 'online' as possible, so we will only try time-based workflow or batch apex if nothing else helps..

 

Many thanks!

Guy 

 

Hi,

 

I got the error:

 

Failure Message: "System.StringException: Invalid id: xx", Failure Stack Trace: "Class.take_ownership.test: line 13, column 90 External entry point"

 

the field, is a look up = Project_Milestone__c

 

so I have written in the test:

 

Project_Milestone__c= 'xx'

 

but then I´ve got the error.

 

How should I set the look up field ID for the test method?

 

Thank you!

Hello,

 

Can anyone help me in code coverage for the below sample code. Its really urgent for the Production. The code is fine in Sandbox :

 

Main class :

 

/************************************************************************************************************************

 

global class NotificationScheduledFor40Hours implements Schedulable {

//public static String userProfileID = '';

    global void execute(SchedulableContext ctx) {       
      
         sendEmail();
    }
   
    private void sendEmail(){   
           
        for( User  u : [SELECT id,ProfileId,FirstName,Email,Total_hours_of_week__c FROM User WHERE User.Total_hours_of_week__c <: 40.00 limit 1000] ){
       
                String email = u.Email;
                String userProfileID = u.ProfileId;
                String userEmail = u.Email;
        }
    }

}

 

/************************************************************************************************************************

 

Test class as below :

 

 

/************************************************************************************************************************

 @istest
private class EmailTestClass {

static testmethod void EmailTest(){
   
    List<User> userList = new List<User>();
   
    Profile profile = [select id from profile where name='Consultant User'];
    User u = new User(alias = 'cons', email='standarduserEmail@testorg.com',
        emailencodingkey='UTF-8', lastname='nameL', languagelocalekey='en_US',
        localesidkey='en_US', profileid = profile.Id,
        timezonesidkey='America/Los_Angeles', username='standardusername@testorg.com');
   
    insert u;
   
    u.put('FirstName', 'nameF');   
    u.put('Total_hours_of_week__c',10.00);
   
    update u;
   
    userList.add(u);
   
    System.assert(true,userList);
   
    if ( userList.isEmpty()) system.debug('No user found');
   
    else {
   
    System.assert(true,u);
    System.assertEquals(u.FirstName, 'nameF');
    System.assertEquals(u.Email, 'standarduserEmail@testorg.com');
    System.assertEquals(u.ProfileId, '00e80000000l0tQAAQ');
   
    String firstName = u.FirstName;
    String uProfileId = u.ProfileId;
    String email = u.Email;   
   
    System.debug('firstName : ' + firstName);
    System.debug('Profile id : ' + uProfileId);
    System.debug('email : ' + email);
    }
}
}

/************************************************************************************************************************



Please let m eknow hat i am missing.

I have written a trigger to copy the opportunity line item as a quote line item, but the trigger is only copying one record, not all of the opportunity line items attached to the opportunity. How do I add a loop to copy as many opportunity line items to quote line items as are attached to the opportunity?

 

Trigger:

 

trigger NewQuoteLineItems on Quote (After Insert) {

    Set<Id> qid = new Set<Id>();
    for(Quote q : Trigger.new){
        System.debug('**** 0 q id : '+q.Opportunityid); 
        qid.add(q.opportunityid);
    }
    System.debug('****1 : q Id size '+ qId.size());
    
    List<quote> qu = new List<Quote>([select id, opportunityid
             from quote where opportunityid in:qid]);
    
    List<Opportunity> o = new List<Opportunity>([select id, Pricebook2Id from opportunity
            where id in:qid]);
    
    List<OpportunityLineItem> oli = new List<OpportunityLineItem>([select id, opportunityid, pricebookentryid,
        Quantity, UnitPrice 
        from OpportunityLineItem where opportunityid = :qid]);

    System.debug('****2 : q Id size '+ qId.size());
   
   List<QuoteLineItem> qli = new List<QuoteLineItem>();   
       System.debug('****2 : qli Id size '+ qli.size());
    for(Quote quote : System.Trigger.new){
           if(Quote.id != null) {
        
            qli.add(New QuoteLineItem (
            quoteid = qu[0].id,
            pricebookentryid = oli[0].pricebookentryid,
            UnitPrice = oli[0].UnitPrice,
            Quantity = oli[0].Quantity));
            
            }
    }
    insert qli;
}

 

Thank you

Hello all! 

 

I have a visualforce page that has a user pick something from a selectList, then calls an Apex method called doSelect when the user hits the button on a form. However, for some reason the method isn't getting called when the user presses the button. I'm guessing I've made a mistake in the visualforce code somewhere, but I can't spot it. I'm a little suprised as I've done this many times before.

 

Here's the code:

 

<apex:page controller="PickerCon" action="{!autoRun}">
<apex:sectionHeader title="Purchase"/>
<apex:outputPanel id="msg">
    This item will be sent to: &nbsp;<apex:outputText value="{!email}"/> 


<apex:form >
<apex:pageBlock mode="edit">
<apex:pageblockSection title="Select an Item">
<apex:selectList value="{!selecteditem}">
            <apex:selectOptions value="{!items}"/>
        </apex:selectList>
</apex:pageblockSection>
<apex:pageBlockButtons >
          <apex:commandButton value="Purchase" action="{!doSelect}" rerender="msg"/>
          <apex:commandButton value="Cancel"/>
</apex:pageBlockButtons>

</apex:pageBlock>
</apex:form>
</apex:outputPanel>
</apex:page>

 

 

trigger OrgOnAccount on Organization_Structure__c (after insert, after update) {

 for(Organization_Structure__c Org:Trigger.New){
 
    Organization_Structure__c[] OSC = [Select Id,Sales_Organization_Des__c,
    Sales_Person_Name__c,AccountID__c From Organization_Structure__c Where Id=:Org.id];
    
    for(Organization_Structure__c O:OSC ){
    Account[] Acc =[Select Id,Chlor_Alkali_Domestic__c,Chlor_Alkali_Exports__c,
    Epoxy_Domestic__c,Epoxy_Exports__c,Peroxide_Domestic__c,Peroxide_Exports__c,
    Phosphates_Domestic__c,Phosphates_Exports__c,Sulphites_Domestic__c,Sulphites_Exports__c,
    Sale_Chlor_Alkali_Domestic__c,Sale_Chlor_Alkali_Exports__c,Sale_Epoxy_Domestic__c,
    Sale_Epoxy_Exports__c,Sale_Peroxide_Domestic__c,Sale_Peroxide_Exports__c,Sale_Phosphates_Domestic__c,
    Sale_Phosphates_Exports__c,Sale_Sulphites_Domestic__c,Sale_Sulphites_Exports__c 
    From Account Where Id=:O.AccountId__c];
    
        for(Account A:Acc){
        
        if(O.Sales_Organization_Des__c=='Epoxy Domestic'){
        A.Epoxy_Domestic__c = true;
        A.Sale_Epoxy_Domestic__c = O.Sales_Person_Name__c; 
        }
         if(O.Sales_Organization_Des__c=='Epoxy Exports'){
        A.Epoxy_Exports__c = true;
        A.Sale_Epoxy_Exports__c = O.Sales_Person_Name__c; 
        }        
        if(O.Sales_Organization_Des__c=='Chlor-Alkali Domestic'){
        A.Chlor_Alkali_Domestic__c = true;
        A.Sale_Chlor_Alkali_Domestic__c = O.Sales_Person_Name__c; 
        }
         if(O.Sales_Organization_Des__c=='Chlor-Alkali Exports'){
        A.Chlor_Alkali_Exports__c = true;
        A.Sale_Chlor_Alkali_Exports__c = O.Sales_Person_Name__c; 
        }
        if(O.Sales_Organization_Des__c=='Phosphates Domestic'){
        A.Phosphates_Domestic__c = true;
        A.Sale_Phosphates_Domestic__c = O.Sales_Person_Name__c; 
        }
         if(O.Sales_Organization_Des__c=='Phosphates Exports'){
        A.Phosphates_Exports__c = true;
        A.Sale_Phosphates_Exports__c = O.Sales_Person_Name__c; 
        }
        if(O.Sales_Organization_Des__c=='Peroxide Domestic'){
        A.Peroxide_Domestic__c = true;
        A.Sale_Peroxide_Domestic__c = O.Sales_Person_Name__c; 
        }
         if(O.Sales_Organization_Des__c=='Peroxide Exports'){
        A.Peroxide_Exports__c = true;
        A.Sale_Peroxide_Exports__c = O.Sales_Person_Name__c; 
        }
        if(O.Sales_Organization_Des__c=='Sulphites Domestic'){
        A.Sulphites_Domestic__c = true;
        A.Sale_Sulphites_Domestic__c = O.Sales_Person_Name__c; 
        }
         if(O.Sales_Organization_Des__c=='Sulphites Exports'){
        A.Sulphites_Exports__c = true;
        A.Sale_Sulphites_Exports__c = O.Sales_Person_Name__c; 
        }
        update Acc;
    }
    
    }
    
 }

}

 

Only 50% I want more :mansad:

 

 

 

@isTest
private class TestOrgOnAccount {

    static testMethod void myUnitTest() {
        Account obj = new Account();
        obj.name = 'test';
        obj.Country__c = 'Afghanistan ';
        obj.Zone__c = 'PZ';
        insert obj;
        
        Organization_Structure__c Org = new Organization_Structure__c();
            Org.Sales_Person_Name__c = 'test';
            Org.Sales_Organization_Des__c = 'Epoxy Domestic';
            Org.name = 'test';
         insert Org;
        
        if(Org.Sales_Organization_Des__c == 'Epoxy Domestic'){
        Account obj2 = new Account(Id=obj.id,name = 'test',Country__c = 'Afghanistan',
        Zone__c = 'PZ',Epoxy_Domestic__c = true,Sale_Epoxy_Domestic__c = Org.Sales_Person_Name__c);
        
        update obj2;
        }
    }
}

 

Thak for heolp

 

I have a visualforce page that is composed of several components. I set the controller for each component and the <apex:page> to the same class. I insert one of the instance objects into the database in one of the components. When I try to access the object ID of the object in another component, it is null. 

 

I get the feeling that each component is using a separate instantiation of the controller class. Is this the case? And more importantly, is there a way to allow separate components to share the same controller context?

 

Thanks.

Can anybody tell me why this is the case, or is it just a compiler bug?

 

This line fails during compile with the error

 

         <apex:column headerValue="XXX" value="{!if(rel.Child__c==null,'Contact','Child')}"/>

 

Save error: Syntax error.  Missing ')'.

 

(rel.child__c is a valid object, valid field, etc. that's not the problem.  )

 

If I change rel.child__c to a constant value, it compiles correctly.  (albeit it's sort of a meaningless thing to do)

If I leave rel.child__c in place and remove the header_value='XXX', it compiles correctly.

Lastly, if I change the line to:

 

         <apex:column headerValue="XXX" value="{!if(rel.Child__c==null,'Contact','Child')}PEANUTS"/>

 

it compiles correctly.  It doesn't have to be "PEANUTS", adding anything, even a space let's it compile.

 

Clearly there's something wrong.  And, regardless, it's a really bad error message.   I'd file a bug but I wonder if someone has a logical explanation like it does something when evaluating the Value that's different depending on if it's within a formula or without, etc.  Strange.

 

Best, Steve.

 

 

I have a Class which does a query, with "order by CreatedDate Desc Null Last Limit 1".  E.g. giving me the most recently created record.

 

When writing test code I first create a bunch of records, run the class and check the results.  It fails because since the test records are all created within a second of each other in the testing code, the sort order is sometimes incorrect and I'm not always getting the most recently created record.

 

I want to do this in my testing code:

 

List<A__c> theAs = new List<A__c>{new A__c(Name='first'), new A__c(Name='second'), new A__c(Name='third, etc.')};

insert theAs;

 

 

But, the only way I can see to make this work is to force the CreatedDates of the test data to be more than one second apart with a construct like: (I'm simplifying, leaving out all data, etc.)

 

A__c a1 = new A__c(Name='or even this one...');

insert a1;

killsometime();

A__c a2 = new A__c(Name='but I sometimes get this one');

insert a2;

killsometime();

A__c a3 = new A__c(Name='I want this one');

insert a3

etc..

 

where killsometime() just burns cpu:

 

public String killsometime() { String s;for (Integer i=0; i<3000;i++) s = s + i; return s);

 

So, this solution works, but it's butt-ugly and I'm wondering if there are any better solutions out there?

 

Thanks, best, Steve.

 

 

I'm being lazy/clever here and just wondering if anybody has build a generic VF page for building simple and complex SOSL queries.   E.G. something that lets the user specify AND/OR, parenthesis grouping of terms, etc.  If so, and they would share the code, that would be great!  I'm just trying to not start from scratch.

 

Thanks, Steve.

This seems like a bug to me.  

 

(Note: there are other long running threads on this however as near as I can tell it still has no resolution.)

 

 

1. Create a custom object called "A".  (No fields needed, etc.)

 

2. Create a custom object called "B".  Give it two custom fields, both Lookups, one to "A", and one to Contact.

 

3. Create an A record, a Contact record, and a few B records that lookup to both of them.

 

4. Create the VF Page and Controller below. 

 

5. On the B object definition create a List Button, allow multi-record selection, using the VF page.  (I called mine "Show Multiple Bs")

 

6. On the A custom object add the Button to the Related List for B. 

 

7. On the Contact object add the Button to the Related List for B.

 

 

Now when you select a few B checkboxes and launch this from your A record  it will work and display the B record ID's (as that's the only thing in there.)

 

When you launch it from the Contact record, it will give you the error:  Invalid variant 'parent': value 'Contact'

 

Any help or suggestions are appreciated.  Thanks, Steve.

<apex:page standardController="B__c" recordSetVar="GetFromController" extensions="Controller_ShowMultipleBs">

<apex:form >

<apex:pageBlock >

<apex:pageBlockButtons >

<apex:commandButton action="{!cancel}" value="Done"/>

</apex:pageBlockButtons>

<apex:pageBlockSection >

<apex:pageBlockTable value="{!theBs}" var="oneB" columns="1">

<apex:column value="{!oneB}" />

</apex:pageBlockTable>

</apex:pageBlockSection>

</apex:pageBlock>

</apex:form>

</apex:page>

 

 

public with sharing class Controller_ShowMultipleBs {

public List<B__c> theBs {get; set;}

public Controller_ShowMultipleBs(ApexPages.StandardSetController stdSetController) {

theBs = (List<B__c>)stdSetController.getSelected();

}

}

 

Thanks.

 

p.s. In another thread there is a reference to a Bug number W-672711.  I called support today and the guy was unable to find *any* sign of this bug number, Open, closed, etc.  So, I don't know what's up with that. 

 

Message Edited by SteveBower on 02-09-2010 02:35 AM

Hi, from the VF doc on the <apex:include> tag I get:

 

pageNameThe Visualforce page whose content should be inserted into the current page. For this value, specify the name of the Visualforce page or use merge-field syntax to reference a page or PageReference.ApexPages.PageReferenceYes

 

So, I'm trying to use a Merge field to reference a pageReference.  I am brought to a blank screen with this message:

 

You cannot use a URL for this attribute. <apex:include pageName>. Please set the attribute to a Visualforce page name.

 

Here is my test code: 

 

VisualForce page:  Try_IncludeWithPageReference.page

 

 <apex:page Controller="Try_IncludeWithPageReference">

        <apex:include pageName="{!editPageRef}"/>
 </apex:page>

 

 

 Apex Controller: Try_IncludeWithPageReference.cls

 

 public with sharing class Try_IncludeWithPageReference {
    public pageReference editPageRef {get; set;}
    public Try_IncludeWithPageReference() {
        editPageRef = new pageReference('/001');
    }
}

 

 

Am I just not understanding the documentation, is this a bug, or something else? 

 

I'd appreciate any input.  Thanks, Steve.

 

This is a knowledge repository sort of posting.  No help is needed.  I put it here because it would have been nice to find it when I was trying to figure out what was happening.

 

If you're coding Apex in Eclipse and you make a change to an Object via the Salesforce UI and you forget to refresh the Object in your Eclipse workspace, you may get a message with this obscure reference to a MetadataELAdapter which I presume has something with Metadata elements.

 

In my case I was passing an instance of the object to a constructor of another class.  There may be other circumstances which give rise to this message, but that's what I was trying to do and I couldn't understand why it was failing.  Note, that it compiled fine, and the VF page started up fine, etc.  I ran into this in the Controller constructor where I was pre-loading data.

 

So, just refreshing the Object in Eclipse clears it all up.  Unclear to me why the state of the Eclipse object should effect code that's being uploaded and then compiled on the server, but...

 

Either way, I hope this saves someone some time.  Steve.

 

 

A small note I'll toss up here because I ran into it.  This is just informational.

 

The few lines of sample code for an HttpRequest call using a username/password was nice to have in the documentation.  It was just what I needed, and it was already done for me.  No thinking required.  :-)

 

 

Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);

 However, I was integrating with a service which has strictly implemented basic authentication and thus they deny the string "BASIC" and require the string "Basic" which is what I believe is in the Spec: http://tools.ietf.org/html/rfc2617.  Of course they didn't document that anywhere.

 

So, I post this just because if someone else had posted it I wouldn't have wasted an hour making sure every other darn thing was perfect before I figured this out.

 

Hope it helps someone, Steve.

 

 

 

In a controller class I have:

p = new PageReference('/apex/CreateContactUpdateRecordStep1?original=' + original.id +
'&contact=' + contact.id + '&id=' + indoubt.id);

In a testing class I have:
String url = nextPage.getUrl();
...
System.assertEquals(url,
'/apex/CreateContactUpdateRecordStep1' +
'?original=' + control.original.id +
'&contact=' + control.contact.id +
'&id=' + control.indoubt.id);

The data is all correct, however the assertion fails because the order of the parameters in the string
returned from the getURL call is different from the order specified in the new PageReference call.

The URL returns '/apex/CreateContactUpdateRecordStep1?contact=xxxxx&id=yyyyy&original=zzzzz'

It's as if the parameters were reordered alphabetically? (Might this be because I'm adding my parameters as part of a string instead of using p.getParameters().put('original',zzzzz) etc?

Now that I write this, I'll test with the put() method... I'll bet the url is returned by dumping the alphabetically ordered parameter Map. (If so, it might help if it were documented somewhere so others
could avoid it.)

-Steve.
Hello, we have a managed package that has been installed into about 40 customer Salesforce accounts.

One of the fields in a custom object has been set up with the Unique constraint.   This was a mistake and we find that we need to remove that constraint.

As near as we can see, if you go back to the DE account where the package was created, you are not allowed to change that option.   And, there is no way to change that option in the customer accounts where the package has been installed.


Is there any way around this?


Clearly we could change our code to do something different, however that too would require changes to the Managed Package.

Clearly we could create a new DE, and a new Managed Package done *without* that constraint, but a) that's a pain, and b) it doesn't help our current customers.

I'm looking for something other than the obvious ones above.  Backdoors, etc.  I've filed a support question with this as well.

Thanks, Steve.   sforce@stevebower.com


p.s. One thought was for future customers to create a package with the custom object with just the one field set up as non-unique.  If a user installs that, and then installs the current package on top of it, that would give us what we want, but I don't know if the conflict resolution done when installing a new package is granular enough to allow the rest of the install to proceed even if that one particular field can't be installed.  ?




Given the new security features, I might want users who install my managed package to automatically be set up to trust an IP range I define in the package.

This way as soon as you install the package, my servers can log into your account using only a username/password.

Can that be done with the new security features?   Or is that considered data instead of schema?

Thanks, Steve.

   
I have a client and they are faced with a "Heavily modify an extensive 3.3Beta Ajax solution" vs. "Rewrite it using the current versions" decision.

One factor that might contribute to the discussion is when will the old endpoint no longer be supported?  When will their current application die anyway?

Do we have any official words on that?

Thanks, Steve.

Summary: API Documentation uses the *labels* for various AccessLevel fields as opposed to the *values* of those fields.  Ex. Says "Read/Write", should say "Edit".


Detail:

In many places in the API documentation there are descriptions of the various "xxxShare" objects.  Account Share, AccountTerritoryShare, LeadShare, etc.  Each of these objects has one or more "AccessLevel" fields.  For example, AccountShare has AccountAccessLevel, CaseAccessLevel, etc.

The documentation says that these access level should be set to some value and in the description has:
Level of access that the User or Group has to the Account. One of the following values:

* Owner - User or Group cannot access the Account.
* Read Only - User or Group can only view the Account.
* Read/Write - User or Group can view or edit the Account.A value (Private, Read Only or Read/Write) that represents
the type of access granted to the target group for all child cases
of the account.

* All - User or Group can view, edit, delete, and share the Account with other User. This value is not valid for create or update calls.

AccountTerritoryShare has CaseAccessLevel documented as:

A value (Private, Read Only or Read/Write) that represents the type of access granted to the target group for all child cases of the account.



The bug, I believe, is that these aren't the correct values for these fields.  These are the *Labels*, the values that you need to put into the fields in the objects are actually "All", "Edit", "Read", etc.

I filed a documentation bug, case # 01354639

Thanks, Steve.





 


From an S-control I'd like to build up and e-mail message and send it to someone along with one or more attachments. 

These attachments could be attached to an object or a document. As near as I can see, this can't be done with the current API call.   (IdeaExchange request is HERE )

Does anybody have any suggestions as to how to workaround this?

I suppose I could create a contact with the e-mail address (it's always going to be the same one in this usage), and a template with a blank text and blank Brand Template.

Then in my dynamic code, I could add the Body, add attachments to the template, send a Mass e-mail to that one recipient using the template and then clear out the body and delete the attachments for the next usage.

But, the messages I send this way will have the attachments as HTML links instead of true attachments.

And, it's a pain in the butt.

Any other thoughts anybody?   Thanks, Steve.

P.S. Does emailAuthor.jsp suffer from the same limitations?  I can't find documentation on that so I presume it's unsupported?
Are there known problems with using the PHP toolkit from an account hosted by GoDaddy?

I see other people with similar problems, but no resolution.

I'm no PHP expert, but my phpinfo result (www.stevebower.com/phpinfo.php) seems to show CURL, OpenSSL, and SOAP as all enabled.

However, I still get the "Could not connect to host" message from login.php 

(http://www.stevebower.com/sforce-php/samples/login.php)

I'd appreciate any thoughts and experience with GoDaddy's configuration.

Thanks, Steve.   

e-mail: sforce@stevebower.com

We're at a point where we can implement something with the standard OpportunityContactRole's, or, with Spring '07 we could create a custom lookup relationship between Contacts and Opportunities ourselves.

Aside from the loss of cascading deletes, and the security model, does anybody see any advantages going one way or another?  (Or both in some twisted world.)


A different question is:  What is Salesforce's long term plan for these mapping objects like OpportunityContactRoles.  Will they die?  Live forever and expand?, or gently fade into the long dark night?

Thanks, Steve.




Has anybody experienced a goofy situation where, running IE, the salesforce screen will change to a sort of "Black and White" color pattern?

I've written s-controls using the .css files from salesforce, and everything works wonderfully on Firefox.  Most of the time, (98%) things are perfect on IE as well.

However, once in a blue moon (I can't find a pattern), when exiting from an S-control it will go back to Salesforce and it will be in this strange mode almost as if some aspects of the .css file are no longer being taken into consideration.

If you refresh it doesn't help.  If you clear the cache and refresh with Ctrl-F5 it will correct itself.

Any thoughts?

I have another .css question as well.  If anybody out there has done a lot with the sfdc provided style sheets, I'd love a five minute conversation to bounce some thoughts around. 

Thanks, Steve.


If we dig through the now *production* product, Call Scripting, and we look through the Javascript that is behind it, I see a bunch of code for talking to the version 8.0 endpoint, managing Contexts, Graphics, and some compatability stuff for maintaining a V7, V8 world.  As well as helpers that some of us have been using for a long time like the QueryString stuff, etc.

Can we start using this V8 stuff and count on it as part of the production environment since it's part of a production product?  Or am I digging too far into the implementation and it's not to be relied on (as I expect) for external use.


I've also got quite a library now of Bug fixes to the 3.3 Beta release which has been Beta for a "long" time.

Can we have a glimpse of the master plan?  When V8 comes out will it be upwards compatible with the V7 stuff, or, since this has been "Beta", is that not guaranteed?

Thanks, Steve




I'm posting a lot of code here, and I have comments in the code to explain what to try.  This is a goofy one to me (or perhaps it's just too late and I need sleep).  Either way, if you can take the S-Control below and throw it into a Custom Link somewhere (anywhere, just so you can launch it), I'd appreciate any explanations.

Note that this is IE specific and I'm using IE 6.0.2900...

In a different s-control, IE throws an Object exception error on this line in the loadSelectElement function:

            opt.appendChild(adoc.createTextNode(df));

But, even though the bug is repeatable in the larger s-control, I'm unable to get exactly that error in this smaller sample.  However I get other strange behavior.

I appreciate any feedback, Steve Bower.

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<script src="https://www.salesforce.com/services/lib/ajax/beta3.3/sforceclient.js—browser=true"
 type="text/javascript"></script>
 

<script type="text/javascript">
// If I don't have this fix, I get a Secure/Insecure warning box every time I execute the s-control.
 Sforce.Client.prototype.createWait = function() {
 var w = Sforce.doc.getElementById("sfdc_waiter");
 if (w != undefined) {
  return w;
 } else {
  w = Sforce.doc.createElement("iframe");
  w.style.overflow = "visible";
  w.frameBorder = "no";
  //w.style.backgroundColor = "transparent";
  w.allowTransparency = true;
  w.id = "sfdc_waiter";
  w.name = "sfdc_waiter";
  w.src = "javascript:false;";  // This is the added line.
  return w;
 }
};
</script>

<script type="text/javascript">
// Don't know why, but if I include browser=true, the page never stops loading.
// In the sense that the loading icon never stops spinning.  However, turning off
// the busybox does the trick, so it must be related to that, but I'm not going
// to bother figuring out why.
Sforce.Client.prototype.busyboxenabled = false;
</script>


<script type="text/javascript">
Sforce.QueryResult.prototype.SBower_loadSelectElement = function(selectElement, sorted, valueField, displayField, formatString) {
 this.sortf = function(x, y) {
  if (x.text < y.text) {
   return -1;
  } else if (x.text == y.text) {
   return 0 ;
  } else {
   return 1;
  }
 };
 if (selectElement.options == undefined) {
  var sel = Sforce.doc.getElementById(selectElement);
 } else {
  var sel = selectElement;
 }
 sel.options.length = 0;
 if (sel.ownerDocument != undefined) {
  var adoc = sel.ownerDocument;
 } else {
  var adoc = sel.document;
 }
 if (this.size > 0) {
  var options = new Array();
  for (var i=0;i<this.records.length;i++) {
   var vf = this.records[i].get(valueField);
   if (Sforce.Util.dltypeof(displayField).toLowerCase() == "array") {
    var df = formatString;
    for (var j=0;j<displayField.length;j++) {
     var regex = new RegExp(displayField[j], "g");
     if (formatString == undefined) {
// I also think this is goofy and would be better with:
      //df = this.records[i].get(displayField[j]);    // Old
      // Start of New.
      if (j==0) {
       df = this.records[i].get(displayField[j]);
      } else {
       df = df + " " + this.records[i].get(displayField[j]);
      }
      // End of New.
      
     } else {
      df = df.replace(regex, this.records[i].get(displayField[j]));
     }
    }
   } else {
    var df = this.records[i].get(displayField);
   }

/* This is the old code:
   var opt = adoc.createElement("OPTION");
   opt.value = vf;
   //opt.text = df;
   opt.appendChild(adoc.createTextNode(df));
   opt.record = this.records[i];
   options.push(opt);
*/
// Replaced with this line:
   options.push(new Option(df,vf));
  }
  if (sorted && sorted == true) {
   options = options.sort(this.sortf);
  }
  for (key in options) {
/* This is the old code:
   sel.appendChild(options[key]);
*/
// Replaced with this line.
   sel.options[sel.length] = options[key];
  }
  return;
 } else {
  return;
 }
};
</script>


 <script language="javascript">
<!--
function init()
{
 sforceClient.registerInitCallback(doit);
 var ir = sforceClient.init("{!API_Session_ID}", "{!API_Partner_Server_URL_70}", true);

}
function doit() 
{
    var flds = sforceClient.DescribeSObject("contact").fieldList;
 var contacts = sforceClient.Query("select " + flds + " from contact");
 var t1 = document.getElementById("test1");
 var t2 = document.getElementById("test2"); 
 var t3 = document.getElementById("test3");
 var t4 = document.getElementById("test4"); 

 contacts.loadSelectElement(t1,true,"id","lastname");
 //contacts.SBower_loadSelectElement(t1,true,"id","lastname");    // This will fix it.
 t2.options[0] = new Option("-None-","");   // Works if this is removed...
 
 contacts.loadSelectElement(t3,true,"id","lastname");
 //contacts.SBower_loadSelectElement(t3,true,"id","lastname");
 t4.options[0] = new Option("-None-","");
/*

 
Remember, this is only visible in IE.  In Firefox everything works. 
 
 
So, to Test:  

1. Try this in IE and explain to me why #1 is displayed incorrectly but #3 is correct.
The code is the same, the HTML below is different.

The original loadSelectElement code will work if I get rid of the line setting the second 
select box to "-None-".    But, is a totally valid thing to do.  And, you would think that 
it should have no impact on the first Select box.

2. I believe it has something to do with the way the Option elements are generated, or perhaps something
with the "adoc" way of doing things... 
If you use my modified prototype above, SBower_loadSelectElement, it works properly in both cases, but, since
I don't really know what's going wrong, I hesitate to declare this a solid "fix".

Any input–  Thanks, Steve Bower.


Notes:

In the loadSelectElement code there are several other goofy things:

1. I have no idea why the entire QueryResult Records structure is being copied into the Options array
of the Select element.  Perhaps it's to have it available for use later, but that's kind of overkill.
You'll probably still have the QueryResult object that you used to invoke loadSelectElement kicking around,
and you can refer to it's records with the selectedIndex of the element.  It can make for a huge Options collection
for no reason.

2. The logic/code for the FormatString stuff is clever, but the two lines:
 if (formatString == undefined) {
  df = this.records[i].get(displayField[j]);
Should probably be:
 if (formatString == undefined) {
  if (j==0) {
   df = this.records[i].get(displayField[j]);
  } else {
   df = df + " " + this.records[i].get(displayField[j]);
  }

 Meaning, if there is no formatString defined, use concatenation with a space. Otherwise there is no point going through the loop in the first place, even if the displayfield is an array. Some sample doc would also be helpful, otherwise nobody would ever figure out that what is allowed is: contacts.loadSelectElement(element,true,"id",["lastname","firstname","suffix__c"],"firstname lastname suffix__c"); */ } //--> </script> </head> <body onLoad="init();"> <div> One:<select id="test1"></select><br> Two:<select id="test2"></select> </div> <br><br><br> <div> <table> <tr> <td>Three:</td> <td><select id="test3"></select></td> </tr> <tr> <td>Four:</td> <td><select id="test4"></select></td> </tr> </table> </div> </body> </html>

 






I found myself needing to implement Dependent Picklists in a UI I'm working on.  However, as has been noted in other threads, dependent picklists aren't actually implemented in the Ajax Beta 3.3 Toolkit.  So, I went and got them working.  Here's what I implemented.  I welcome any comments, critiques, suggestions, etc.

Frankly, there have been a lot of bugs and code fixes submitted by people on these boards, I REALLY think it's time for a Beta 4.0, or, god forbid, a Production version of the Ajax toolkit.

I hope this helps some of you, thanks, Steve Bower.


(In general, I make changes by overriding code in sforceClient.js by inserting my own changed code after the "<script src=...sforceClient.js> tag. )

First, this block can be added to the sforceClient.js section where the other prototypes for PicklistEntry are defined.  Somewhere around line 2530.

Note: I know that the sample code for the Java version used a bitmask of 0x80 before shifting it.  That just didn't work for me, it was off by one.  So, it's possible I've done something wrong here, but this code is working fine. 

Code:
Sforce.PicklistEntry.prototype.getValidFor = function() { return this.validFor; }
Sforce.PicklistEntry.prototype.getLabel = function() { return this.label; }
Sforce.PicklistEntry.prototype.getValue = function() { return this.value; }
Sforce.PicklistEntry.prototype.isValidFor = function(n) {
 // ValidFor is a bitmap.  Each bit corresponds to an entry in the controlling 
 // picklist, so if the Controlling field has 0=colors 1=tastes, then this
 // validFor field will have two significant bits indicating if this PicklistEntry
 // is valid for each of the two categories.  Reading left to right, the first
 // bit indicates if this entry is valid for Colors, and the next bit for Tastes.
 //
 // First isolate which number in the array we want to inspect by dividing 
 // the index we're looking for by 8.  (n>>3 is a bitwise divide by 8).
 // Now we have the number, we need to figure out which single bit to mask off.
 // This would be the remainder after the divide by 8.  Build a mask for it.
 // Note: using 0x40 instead of 0x80 seems to work for me.  0x80 was off.
 return (((0x40 >> (n%8)) & (this.validFor[(n>>3)])) != 0);
}

 Now, as someone else noted, the "validFor" value in the picklistEntry's that are being returned in a Sforce.DescribeSObjectResult object appear to be missing.  That's because they are.  So, we need to add some code to the createPicklistValues function that is defined in the DescribeSObjectResult function definition.  I'd say "around" line 2316, however in actuality the entire createPicklistValues function is defined on that one line in one huge run-on line of code.   Either way, you want to add:

Code:
picklistEntry.validFor = [0,0,0,0];
// vFor is a four character string holding the bitset.
var vFor = Sforce.DOM.GetElementValue (node[i], "validFor");
if (vFor != "" && vFor != null ) {
        for (var j=0;j<vFor.length;j++) {
         // Convert the letters to a numeric array so bitwise 
  // operations are possible.
  var n = vFor.charCodeAt(j);
  picklistEntry.validFor[j] = n;
 }
}

into the function. So createPickListValues ends up looking like:

Code:
 createPicklistValues = function(node) {
  if (node.length == 0) {
   return new Array();
  } else {
   var ret = new Array();
   for (var i=0;i<node.length;i++) {
    var picklistEntry = new Sforce.PicklistEntry();
    picklistEntry.active = Sforce.DOM.GetBool(Sforce.DOM.GetElementValue (node[i], "active"));
    picklistEntry.defaultValue = Sforce.DOM.GetBool(Sforce.DOM.GetElementValue (node[i], "defaultValue"));
    picklistEntry.label = Sforce.DOM.GetElementValue (node[i], "label");
    picklistEntry.value = Sforce.DOM.GetElementValue (node[i], "value");
    picklistEntry.validFor = [0,0,0,0];
    // vFor is a four character string holding the bitset.
    var vFor = Sforce.DOM.GetElementValue (node[i], "validFor");
    if (vFor != "" && vFor != null ) {
     for (var j=0;j<vFor.length;j++) {
      // Convert the letters to a numeric array so bitwise 
      // operations are possible.
      var n = vFor.charCodeAt(j);
      picklistEntry.validFor[j] = n;
     }
    }
    ret[i] = picklistEntry;
   }
   return ret;
  }
 };


Ok, so now you have data in the fields and methods to access it.
All you need is a code example which shows how to use it. In the sample
provided for Java, they are building a matrix by going "across" one
picklistEntry at a time and determining it's status for each bit.

All I really wanted was some code to generate a new Options array
for an element depending on the index of the controlling field
which I would pass in. So, yes, I'm expensivly rebuilding my
Options lists whenever needed instead of building a cached array
of Select Option arrays and then referring to them, but this is
fine for this particular usage.

Sample:
function reloadDependentPicklistElement(element,bean,fld,depIndex) {

  /*
  element: the DOM element we are going to create a new Option list for.
  It should be a Select element, we aren't checking that.
  
                bean: the type of bean we are looking at:  "opportunity", "account", etc.
  
                fld: the field in the bean we are building a picklist from.  This should
  obviously be a picklist type field but we aren't checking that.
  
                depIndex: the index into the Controller Picklist that we are testing.
  (Normally this will come from a nearby DOM controllerElement.indexSelected 
  type of construct.)
  
  Returns an Options array loaded into the requested Element.
  */
  var j = bean.fieldMap.getItem(fld);
  var startopt = 0;
  element.options.length = 0; 
  for (var i=0; i < j.picklistValues.length; i++) {
   var plv = j.picklistValues[i];
   if (j.dependentPicklist == true) {
    if (plv.isValidFor(depIndex)) {
     element.options[startopt++] = new Option(plv.label,plv.value);
    }
   } else {
    element.options[startopt++] = new Option(plv.label,plv.value);
   }
   if (plv.defaultValue == true) {
    element.options[startopt-1].selected = true
    element.selectedIndex = startopt-1; // this one.
   }
  }
  element.options.length = startopt;
 }

 
I appreciate any feedback, comments, tips, improvements, etc. Thanks, Steve.

 

Let's say that I'd like to implement some operation in an atomic fashion.  The specific example is that I'd like to implement my own auto-counters that only fire in a specific data-based situation.  So, I have an s-control that the user clicks on to "get next counter".  This can go off to a "counter" custom object, get the current value, increment it, and save it back so the next usage will have the new value.

The problem is that this isn't an atomic operation, and there is no way to implement a critical section across all the potential users of the s-control at the same time.  So, if the timing were really unlucky, two users could get the same value which defeats the purpose.  (Yes, this is unlikely, but...)

The best I could do would be to roll my own with a semaphore custome object of some kind.  But, that means an extra set of calls wrapped around my critical sections as well as browser timeouts, backoffs, etc.  And, it's a pain to code for every situation in different s-controls.

Does Salesforce have any API method for doing this that I'm not aware of?  And, assuming not, can we put in a request for some sort of server-side semaphore object?  Or, perhaps an atomic sort of:

sforceclient.execute("Object Type", "ObjectID","Formula definition"); call.

I envision this doing a Retrieve for all fields on the requested ID, executing the Formula (using the same syntax, rules, etc. as the Formula Field definitions), and then an Update.  All as one server side call.

Example:  sforceClient.execute("Opportunity","00630000002zTEJ","{!Something}={!Something}+1");

Thanks, Steve Bower.

P.S. I only have a developer account, so I don't think I can make the enhancement request myself.



I found myself needing to implement Dependent Picklists in a UI I'm working on.  However, as has been noted in other threads, dependent picklists aren't actually implemented in the Ajax Beta 3.3 Toolkit.  So, I went and got them working.  Here's what I implemented.  I welcome any comments, critiques, suggestions, etc.

Frankly, there have been a lot of bugs and code fixes submitted by people on these boards, I REALLY think it's time for a Beta 4.0, or, god forbid, a Production version of the Ajax toolkit.

I hope this helps some of you, thanks, Steve Bower.


(In general, I make changes by overriding code in sforceClient.js by inserting my own changed code after the "<script src=...sforceClient.js> tag. )

First, this block can be added to the sforceClient.js section where the other prototypes for PicklistEntry are defined.  Somewhere around line 2530.

Note: I know that the sample code for the Java version used a bitmask of 0x80 before shifting it.  That just didn't work for me, it was off by one.  So, it's possible I've done something wrong here, but this code is working fine. 

Code:
Sforce.PicklistEntry.prototype.getValidFor = function() { return this.validFor; }
Sforce.PicklistEntry.prototype.getLabel = function() { return this.label; }
Sforce.PicklistEntry.prototype.getValue = function() { return this.value; }
Sforce.PicklistEntry.prototype.isValidFor = function(n) {
 // ValidFor is a bitmap.  Each bit corresponds to an entry in the controlling 
 // picklist, so if the Controlling field has 0=colors 1=tastes, then this
 // validFor field will have two significant bits indicating if this PicklistEntry
 // is valid for each of the two categories.  Reading left to right, the first
 // bit indicates if this entry is valid for Colors, and the next bit for Tastes.
 //
 // First isolate which number in the array we want to inspect by dividing 
 // the index we're looking for by 8.  (n>>3 is a bitwise divide by 8).
 // Now we have the number, we need to figure out which single bit to mask off.
 // This would be the remainder after the divide by 8.  Build a mask for it.
 // Note: using 0x40 instead of 0x80 seems to work for me.  0x80 was off.
 return (((0x40 >> (n%8)) & (this.validFor[(n>>3)])) != 0);
}

 Now, as someone else noted, the "validFor" value in the picklistEntry's that are being returned in a Sforce.DescribeSObjectResult object appear to be missing.  That's because they are.  So, we need to add some code to the createPicklistValues function that is defined in the DescribeSObjectResult function definition.  I'd say "around" line 2316, however in actuality the entire createPicklistValues function is defined on that one line in one huge run-on line of code.   Either way, you want to add:

Code:
picklistEntry.validFor = [0,0,0,0];
// vFor is a four character string holding the bitset.
var vFor = Sforce.DOM.GetElementValue (node[i], "validFor");
if (vFor != "" && vFor != null ) {
        for (var j=0;j<vFor.length;j++) {
         // Convert the letters to a numeric array so bitwise 
  // operations are possible.
  var n = vFor.charCodeAt(j);
  picklistEntry.validFor[j] = n;
 }
}

into the function. So createPickListValues ends up looking like:

Code:
 createPicklistValues = function(node) {
  if (node.length == 0) {
   return new Array();
  } else {
   var ret = new Array();
   for (var i=0;i<node.length;i++) {
    var picklistEntry = new Sforce.PicklistEntry();
    picklistEntry.active = Sforce.DOM.GetBool(Sforce.DOM.GetElementValue (node[i], "active"));
    picklistEntry.defaultValue = Sforce.DOM.GetBool(Sforce.DOM.GetElementValue (node[i], "defaultValue"));
    picklistEntry.label = Sforce.DOM.GetElementValue (node[i], "label");
    picklistEntry.value = Sforce.DOM.GetElementValue (node[i], "value");
    picklistEntry.validFor = [0,0,0,0];
    // vFor is a four character string holding the bitset.
    var vFor = Sforce.DOM.GetElementValue (node[i], "validFor");
    if (vFor != "" && vFor != null ) {
     for (var j=0;j<vFor.length;j++) {
      // Convert the letters to a numeric array so bitwise 
      // operations are possible.
      var n = vFor.charCodeAt(j);
      picklistEntry.validFor[j] = n;
     }
    }
    ret[i] = picklistEntry;
   }
   return ret;
  }
 };


Ok, so now you have data in the fields and methods to access it.
All you need is a code example which shows how to use it. In the sample
provided for Java, they are building a matrix by going "across" one
picklistEntry at a time and determining it's status for each bit.

All I really wanted was some code to generate a new Options array
for an element depending on the index of the controlling field
which I would pass in. So, yes, I'm expensivly rebuilding my
Options lists whenever needed instead of building a cached array
of Select Option arrays and then referring to them, but this is
fine for this particular usage.

Sample:
function reloadDependentPicklistElement(element,bean,fld,depIndex) {

  /*
  element: the DOM element we are going to create a new Option list for.
  It should be a Select element, we aren't checking that.
  
                bean: the type of bean we are looking at:  "opportunity", "account", etc.
  
                fld: the field in the bean we are building a picklist from.  This should
  obviously be a picklist type field but we aren't checking that.
  
                depIndex: the index into the Controller Picklist that we are testing.
  (Normally this will come from a nearby DOM controllerElement.indexSelected 
  type of construct.)
  
  Returns an Options array loaded into the requested Element.
  */
  var j = bean.fieldMap.getItem(fld);
  var startopt = 0;
  element.options.length = 0; 
  for (var i=0; i < j.picklistValues.length; i++) {
   var plv = j.picklistValues[i];
   if (j.dependentPicklist == true) {
    if (plv.isValidFor(depIndex)) {
     element.options[startopt++] = new Option(plv.label,plv.value);
    }
   } else {
    element.options[startopt++] = new Option(plv.label,plv.value);
   }
   if (plv.defaultValue == true) {
    element.options[startopt-1].selected = true
    element.selectedIndex = startopt-1; // this one.
   }
  }
  element.options.length = startopt;
 }

 
I appreciate any feedback, comments, tips, improvements, etc. Thanks, Steve.

 

So, I couldn't get Documents to work properly (see my previous posts), so I decided to recode it to use several Textarea fields. Turns out that the same issue of "chunking" long return results occurs for either Documents, Textareas, and (although I haven't tested it, probably Attachments) as well.

This small change to the sforceclient.js file solves these problems as well as re-balancing the "base64" datatype so that since you don't encode() your data going in, you don't have to decode() it yourself coming out. 

Thanks, Steve Bower.

Sforce.DOM.ParseVal = function(value, name ,desc) { var fldDef = desc.fieldMap.getItem(name.toLowerCase()); if (fldDef == null) { var cr = desc.childRelationships.getItem(name.toLowerCase()); if (cr != null) { //This is an object definition for a child relationship //This should be a queryResult with all the records of the child object return new Sforce.QueryResult(value); } else { return Sforce.Serialization.DeserializeBean(value); } } else { if (value == null || value.length == 0) { if (fldDef.type == "date" || fldDef.type == "datetime") { return null; } else { return value; } } var fldType = fldDef.type; /* Note remove textarea from this block. */ if (fldType == "string" || fldType == "picklist" || fldType == "multipicklist" || fldType == "combobox" || fldType == "reference" /*|| fldType == "textarea" */|| fldType == "phone" || fldType == "id" || fldType == "url" || fldType == "email") { return value; } else if (fldType == "boolean") { if (value.toLowerCase() == "false") { return false; } else { return true; } } else if (fldType == "currency" || fldType == "double" || fldType == "percent") { return parseFloat(value); } else if (fldType == "date" || fldType == "datetime") { return Sforce.Util.FromIsoDateTime(value); /* Added. Steve Bower. */ } else if (fldType == "textarea" ) { if (typeof value == "object") { return value.textContent; } else { return value; } } else if (fldType == "base64") { var b64 = new Sforce.Util.Base64(); if (typeof value == "object") { return b64.decode(value.textContent); } else { return b64.decode(value); } /**/ } else { return value; } } };

For some reason I cannot get cases to close by setting the status to closed. The "isClosed" checkbox remains unchecked even if I change the status.

 

Here is my code:

 

trigger CloseRelatedOppCases on Opportunity (before update) {

	List<Opportunity> opps = Trigger.new;
	
	for(Opportunity o : opps){
		if(o.StageName == 'Dead/Lost'){
			//Get record type ID of Engineering Engagement Request RT, Credit Verification Request, and Network Qualification Request
			RecordType rt1 = [SELECT id FROM RecordType WHERE Name = 'Engineering Engagement Request' LIMIT 1];
			RecordType rt2 = [SELECT id FROM RecordType WHERE Name = 'Credit Verification Request' LIMIT 1];
			RecordType rt3 = [SELECT id FROM RecordType WHERE Name = 'Network Qualification Request' LIMIT 1];
			
			//Find Associated NDS Cases
			List<Case> engineeringEngagementCases = [SELECT id FROM Case WHERE Opportunity__c = :o.Id AND RecordTypeId = :rt1.Id];
			List<Case> creditVerificationCases = [SELECT id FROM Case WHERE Opportunity__c = :o.Id AND RecordTypeId = :rt2.Id];
			List<Case> networkQualificationCases = [SELECT id FROM Case WHERE Opportunity__c = :o.Id AND RecordTypeId = :rt3.Id];
			
			//Combine All Cases into one list
			List<Case> cases = new List<Case>();
			cases.addall(engineeringEngagementCases);
			cases.addall(creditVerificationCases);
			cases.addall(networkQualificationCases);
			
			//Loop Through Cases and Set Status to Opportunity Dead/
			for(Case c : cases){
					c.Status = 'Opportunity Dead/Lost';
			}
			
			update cases;
		}
	}

}

 

Hi my class is below

 

 

public class SendEmailToCandidates {
    
    public String positionSelected{get; set;}
    //get Positions
    public List<SelectOption> getPositionList()
    {
    List<Selectoption> optns=new List<Selectoption>();       
    List<Position__c> position=[select name,id from Position__c];
            
                for(Position__c pos:position)
                {
                   optns.add(new Selectoption(pos.name,pos.name));
                }   
    System.debug(position);
    return optns;
    
    }

  //constructor
    public SendEmailToCandidates()
    {
    applicantsList=new List<Job_Application__c>();
    positionList=new Position__c();
    }

}

i'm populating positions

but i' m not able to get the positons in the drop down

 

my page is

 

<apex:page controller="SendEmailToCandidates">
<apex:form >
<apex:selectList value="{!positionSelected}" >
<apex:selectOptions value="{!positionList}" >
</apex:selectOptions>
</apex:selectList>
</apex:form>

<apex:page>

 

error is:
Invalid selectOptions found. Use SelectOption type in Apex.

Help me

I have successfully created a page controlled by an Apex Class in my Sandbox and everything works very nicely. Basically it is a report of sorts as the page simply is listing a number of enteries on my opportunity table and a custom payment table. There are not any inputs or buttons the page calls all the information it needs together via URL parameters. My struggle is that I cannot get my test to go through and select any records, therefore my tests are not covering enough of the code and I can't deploy my class and page. Could someone please help me?

 

Here is my class

public class ConfServicesPaymentListing{
    public String prop;
    public String whom;
    public ConfServicesPaymentListing() {
        this.prop = ApexPages.currentPage().getParameters().get('property');
        this.whom = ApexPages.currentPage().getParameters().get('who'); }
    public void setProp(String prop) { this.prop = prop; }
    public void setWhom(String whom) { this.whom = whom; }
    
    public Date tday   = Date.Today();
    public Integer tmonth   = Date.Today().month();
    public Integer tyear    = Date.Today().year();
    public Integer daysThis = Date.daysInMonth(tyear, tmonth);
    public Date LastMonth = Date.Today()-daysThis;
    public Date NextMonth = Date.Today()+daysThis;
    public Date thisStart = Date.Today().toStartOfMonth();
    public Date lastStart = LastMonth.toStartOfMonth();
    public Date thisEnd   = NextMonth.toStartOfMonth();
    //Commissionable Bill Pay
    public Payments__c[] getPaymentBillThisComissionableList() {
        Payments__c[] pbtcl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Commissionable' AND Type__c='Bill Pay' AND Date_Recieved__c>=:thisStart AND Date_Recieved__c<:thisEnd                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pbtcl;
    }
    Payments__c pbtcl2;
    public Payments__c getPbtcl2(){
        pbtcl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pbtc : getPaymentBillThisComissionableList()){
        pbtcl2.Payment__c += pbtc.Payment__c; }
        return pbtcl2;  
    }
    //Commissionable Bill Pay Last Month
    public Payments__c[] getPaymentBillLastComissionableList() {
        Payments__c[] pbtcl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Commissionable' AND Type__c='Bill Pay' AND Date_Recieved__c>=:lastStart AND Date_Recieved__c<:thisStart                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pbtcl;
    }
    Payments__c pblcl2;
    public Payments__c getPblcl2(){
        pblcl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pblc : getPaymentBillLastComissionableList()){
        pblcl2.Payment__c += pblc.Payment__c; }
        return pblcl2;  
    }
    //Commissionable Deposit Pay This Month
    public Payments__c[] getPaymentDepositThisComissionableList() {
        Payments__c[] pdtcl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Commissionable' AND Type__c='Deposit' AND Date_Recieved__c>=:thisStart AND Date_Recieved__c<:thisEnd                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pdtcl;
    }
    Payments__c pdtcl2;
    public Payments__c getPdtcl2(){
        pdtcl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pdtc : getPaymentDepositThisComissionableList()){
        pdtcl2.Payment__c += pdtc.Payment__c; }
        return pdtcl2;  
    }
    //Commissionable Deposits Last Month
    public Payments__c[] getPaymentDepositLastComissionableList() {
        Payments__c[] pdlcl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Commissionable' AND Type__c='Deposit' AND Date_Recieved__c>=:lastStart AND Date_Recieved__c<:thisStart                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pdlcl;
    }
    Payments__c pdlcl2;
    public Payments__c getPdlcl2(){
        pdlcl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pdlc : getPaymentDepositLastComissionableList()){
        pdlcl2.Payment__c += pdlc.Payment__c; }
        return pdlcl2;  
    }
    //Non-Commissionable Bill Pay
    public Payments__c[] getPaymentBillThisNonList() {
        Payments__c[] pbtnl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Non-Commissionable' AND Type__c='Bill Pay' AND Date_Recieved__c>=:thisStart AND Date_Recieved__c<:thisEnd                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pbtnl;
    }
    Payments__c pbtnl2;
    public Payments__c getPbtnl2(){
        pbtnl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pbtn : getPaymentBillThisNonList()){
        pbtnl2.Payment__c += pbtn.Payment__c; }
        return pbtnl2;  
    }
    //Non-Commissionable Bill Pay Last Month
    public Payments__c[] getPaymentBillLastNonList() {
        Payments__c[] pbtnl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Non-Commissionable' AND Type__c='Bill Pay' AND Date_Recieved__c>=:lastStart AND Date_Recieved__c<:thisStart                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pbtnl;
    }
    Payments__c pblnl2;
    public Payments__c getPblnl2(){
        pblnl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pbln : getPaymentBillLastNonList()){
        pblnl2.Payment__c += pbln.Payment__c; }
        return pblnl2;  
    }
    //Non-Commissionable Deposit Pay This Month
    public Payments__c[] getPaymentDepositThisNonList() {
        Payments__c[] pdtnl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Non-Commissionable' AND Type__c='Deposit' AND Date_Recieved__c>=:thisStart AND Date_Recieved__c<:thisEnd                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pdtnl;
    }
    Payments__c pdtnl2;
    public Payments__c getPdtnl2(){
        pdtnl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pdtn : getPaymentDepositThisNonList()){
        pdtnl2.Payment__c += pdtn.Payment__c; }
        return pdtnl2;  
    }
    //Non-Commissionable Deposits Last Month
    public Payments__c[] getPaymentDepositLastNonList() {
        Payments__c[] pdlnl = [SELECT 
                                  Booking_Name_Organization__c, Commissionable__c, Date_Recieved__c, Event_Dates__c, Notes__c, Payment__c, Type__c
                              FROM 
                                  Payments__c
                              WHERE
                                  Password__c=:prop AND Commissionable__c='Non-Commissionable' AND Type__c='Deposit' AND Date_Recieved__c>=:lastStart AND Date_Recieved__c<:thisStart                                  
                              ORDER BY Date_Recieved__c
                              ];
        return pdlnl;
    }
    Payments__c pdlnl2;
    public Payments__c getPdlnl2(){
        pdlnl2 = new Payments__c(Payment__c = 0);
        for(Payments__c pdln : getPaymentDepositLastNonList()){
        pdlnl2.Payment__c += pdln.Payment__c; }
        return pdlnl2;  
    }
    public Opportunity[] getOpportunityList() {
        Opportunity[] opps = [SELECT 
                                  Arrival_Date__c, Look_Up_Contact_Name__c, Arrive_Depart__c, Organization__c, Actual_Amount__c, System_Balance_Due__c, Property__c, Update_Required__c
                              FROM 
                                  Opportunity 
                              WHERE
                                  Password__c=:prop AND 
                                  ((StageName='Event Finalized' AND System_Balance_Due__c>0) OR
                                  ((StageName='GM' OR StageName='Anticipated' OR StageName='Projected') AND Arrival_Date__c<:tday AND Actual_Amount__c<1))
                              ORDER BY Arrival_Date__c
                              ];
        return opps;
    }
    Opportunity opp2;
    public Opportunity getOpp2(){
        opp2 = new Opportunity(Balance_Due__c = 0, Actual_Amount__c = 0, Guarenteed_Minimum_Payment__c = 0);
        for(Opportunity o : getOpportunityList()){
        opp2.Property__c = o.Property__c;
        opp2.Contract_Notes__c = ApexPages.currentPage().getParameters().get('property');
        opp2.Name = ApexPages.currentPage().getParameters().get('who');
        opp2.Balance_Due__c += o.System_Balance_Due__c; }
        return opp2;  
    }
    public pageReference generateReport() {
        PageReference goToNew = Page.ConfServices_PaymentListing;
        goToNew.getParameters().put('property', prop);
        goToNew.getParameters().put('who', whom);
        return goToNew;
    }
    public static testMethod void ConfServices_PaymentListingTest() {
       ConfServicesPaymentListing test = new ConfServicesPaymentListing();
       test.setProp('1234');
       test.setWhom('Zach');
       PageReference testPageReference = Page.ConfServices_PaymentListing;
       testPageReference.getParameters().put('property','1234');
       testPageReference.getParameters().put('who','Zach');
    system.assertEquals(testPageReference.getParameters(), test.generateReport().getParameters());
        Opportunity[] opp = [SELECT Property__c FROM Opportunity WHERE Password__c = '1234'];
        System.assertEquals('Lake Williamson', opp[0].Property__c);
}
}

When I look at the results after running the test each of the lines that start like the following two entries come out red, basically nothing will select, even through there are records to select in the sandbox and the main system. I have even tried createing records via the test, but nothing I have tried will improve these scores.

    public Payments__c[] getPaymentBillThisComissionableList() {
        Payments__c[] pbtcl = [SELECT
    Payments__c pbtcl2;
    public Payments__c getPbtcl2(){

I appreciate anyone's input.

  • September 09, 2012
  • Like
  • 0

Hi all,

 

I've struggled with this for a while and welcome any advice.

 

I want to place a custom button in opportunities (detail page) that, providing the opp stage is 'Closed Won' creates a case, copying a number of opp fields across into the case fields as it does so.

 

I currently have two custom buttons on the page that I'm testing ... both using Onclick Javascript.

 

HERE'S THE CODE BEHIND THE FIRST ONE:

if ("{!Opportunity.StageName}" == 'Closed Won')

{location.href = "/500/e?retURL=%2F500%2Fo

&cas4={!Account.Name}

&cas3={!Opportunity.Opportunity_Contact__c}

&cas5={!Opportunity.Type}

&cas11={!'Converted Opportunity'}

&cas14={!Opportunity.Name}

&cas15={!Opportunity.Requirement__c}

&retURL=/{!Opportunity.Id}&saveURL=/{!Opportunity.Id}";}

else

{alert('Opportunity must be won before a case can be created.'); }

 

What works:

  • The 'new case' page is launched and the fields are populated.

What doesn't work:

  • It doesn't always copy the full content of each field across ... i.e. an opportunity account name of 'ABC Construction Ltd' only populates as 'ABC' in the account name field on the case screen.
  • It requires the user to click the Save button after the fields have been populated.

 

HERE'S THE CODE BEHIND THE SECOND ONE:

{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
var status = "{!Opportunity.StageName}";
var newRecords = [];

if (status == "Closed Won")
{
var c = new sforce.SObject("Case");
c.AccountId = "{!Opportunity.AccountId}";
c.Contact = "{!Opportunity.Opportunity_Contact__c}";   <-------- Problem arises when other fields are included.
//add any other related fields you like

newRecords.push(c);

result = sforce.connection.create(newRecords);
}
else
{
alert ('Opportunity must be won before a case can be created.');
}

 

What works:

  • Providing the line in red is left out, the button works fine.

What doesn't work:

  • As soon as I try to include any additional fields to carry across from the opp to the case, the button no longer works ... no case is created at all.

 

Can anyone tell me which code is best, or provide some guidance as to how to tweak either of the existing codes so that they work in the way I'd like them to?

 

Sorry for the long post!

 

Regards


Steve

 

I need to add a record to a custom object after I insert a record into another custom object.  I have the trigger working for a straight forward insert, but I don't want to insert the record if a record already exists with that customer number.  Here is the code for my existing trigger.  The matching field in both custom objects is JDE_Cust__c; 

 

trigger GetAcctIdTrigger on Sales_History__c (after insert) {
    list <sales_history_comp__c> newshc = new list<sales_history_comp__c>();
    for (Sales_History__c sh : Trigger.new){
    system.debug('GeT SH = ' + sh);
       
    sales_history_comp__c ishc = new sales_History_Comp__c(); 
     ishc.Account__c = sh.Customer__c;
     ishc.JDE_Cust__c = sh.JDE_Cust__c;
     ishc.Customer_Name__c = sh.Cust_Name__c;
     ishc.Sales_History__c = sh.id;
     ishc.Comp_Year_1__c = sh.sales_Year__c;
     ishc.Comp_Year_2__c = '0000';
   system.debug('ISHC RECORDS = ' +ishc);    
     newshc.add(ishc);
      }
insert newshc;     
        }

  • August 20, 2012
  • Like
  • 0

I have an object say A containing 15 fields , when  I add a new record to object A only 10 fields out of 15 should be visible and I must be able to enter values into it and save the record.Now after I open this saved record ,all the 15 fields should be visible to me and I should be able to enter values into it.

              Is this possible using standard functionality of salesforce and how?If not how can it be done using  Visualforce page?

I have created a trigger which simply fails to update a field and I can't see why.

 

The tirgger looks at a new task coming in and compares the phone number on the task (t.Five9__Five9DNIS__c) with a phone number on the contact.  If they don't match.  Then it sets a custom field on the task.

 

I have have set up a test.   When I run it I use debug statements in the trigger to verify:  

* the trigger correctly identifies the mismatch

* the value of the field is changed.

 

However, the assertEquals (the final line in the test) fails!

 

What gives?

 

The Trigger:

 

trigger CheckPhoneMatch on Task (before insert, before update) {

    list<id> contactIds = new list<id>();
    for (Task t : trigger.new)
    {
        contactIds.add(t.whoid);
    }
    
    map<id,contact> contactMap = new map<id,contact>([Select Id, FirstName, LastName, DonorId__c, Phone from contact Where Id in :contactIds ]);
    // list<task> updatedTasks = new list<task>();
    
    for (Task t : trigger.new)
    {
        contact c = contactMap.get(t.whoid);
        
        System.Debug('/n/n*******       Phone ' + c.Phone + ' DNIS: ' + t.Five9__Five9DNIS__c + '       ********');
        
        
        if (c != null)
        {                        
            if (t.Five9__Five9DNIS__c != c.Phone)
            {
                System.Debug('DNIS DOES NOT MATCH');
                t.MismatchPhone__c = true;
                System.Debug('VAL IS: ' + t.MismatchPhone__c);                
            }                                    
        }
    }
}

 

The Test (only the final block of code is relevant):

 

@istest
private class TriggerTests {

   static testMethod void contactBeforeUpdate()
   {
     contact c = new contact();
     c.lastname = 'Smith';
     insert c;
     
     c.address1__c = '123 Main Street';
     c.email = 'test@company.com';
     c.Phone = '1234567890';
     update c;

        
     user u2 = [select id from user where isactive = true limit 1];
   
     task t = new task();
     t.ownerid = u2.id;
     t.whoid = c.id;
     t.subject = 'test';
     t.CallDisposition = 'Yes - Gift Info Acquired';
     t.Five9__Five9DNIS__c = '1234567890';
     
     insert t; 
          
     System.assertEquals(false, t.MismatchPhone__c);

     <OMITTING IRRELEVANT TESTS>               
     
     task t3 = new task();
     t3.ownerid = u2.id;
     t3.whoid = c.id;
     t3.subject = 'test2';
     t3.CallDisposition = 'Callback';   
     t3.Five9__Five9DNIS__c = '0987654321';
 
     insert t3;
     
     // THIS LINE FAILS!!!!!
     System.assertEquals(true, t3.MismatchPhone__c);
 
   }

}

 

 

Hi -

 

I am using an aggregate function for the first time and need help!

I need to find the max(version__C) from the quotes table then increment it by 1.

 

I understand that the results of an aggregate returns an array of AggregateResult objects. AggregateResultis a read-only sObject and is only used for query results.

 

How can I increment it.  I tried converting it to an integer and then adding 1 - but I am getting a run time error of:

 

System.NullPointerException: Attempt to de-reference a null object: Trigger.quoteversioning: line 16, column 34

 

It points to the "i" variable in the statement : insertedquote.version__C = i + 1;

 

Thanks for your help!!!

 

trigger quoteversioning on Quote (before insert) {

integer i;

for (quote insertedquote : system.Trigger.new)
    {
    if (insertedquote.revision_chkbox__c == true)
      {
      AggregateResult[] groupedresults = [select max(version__c) maxversion from quote
                        where quotenumber = :insertedquote.quotenumber
                        and opportunityid = :insertedquote.opportunityid];
      object maxrev = groupedresults[0].get('maxversion');
      
      i=integer.valueof(maxrev);
         
      insertedquote.version__C = i + 1;
      }
    }
}
  • October 07, 2011
  • Like
  • 0

Sorry if this post seems confusing

Hi,

I'm seeing a strange error that I think has to do with the timing of events in salesforce's unit tests.

Essentially all I've built is a trigger that makes the original creator of a Lead auto-follow the chatter feed for the Account and Opportunity after the Lead is converted.

See the following trigger on the opportunity that performs this:

	trigger ChatterAutoFollowOpportunity on Opportunity (after insert) {

    List<ID> opportunityIds = new List<ID>();
    for (Opportunity opp : Trigger.new) {
    	System.debug('opp.Id: ' + opp.Id);
        opportunityIds.add(opp.Id);
    }
    List<EntitySubscription> followAccounts = new List<EntitySubscription>();
    List<EntitySubscription> followOpps = new List<EntitySubscription>();
    for(Lead lead : [SELECT ID, ConvertedOpportunityId, ConvertedAccountId, CreatedById FROM Lead where ConvertedOpportunityId IN :opportunityIds ]){
        EntitySubscription followAccount = new EntitySubscription (
                                 parentId = lead.ConvertedAccountId,
                                 subscriberid = lead.CreatedById);
                                 
        EntitySubscription followOpp = new EntitySubscription (
                                parentId = lead.ConvertedOpportunityId,
                                subscriberid = lead.CreatedById);
        followAccounts.add(followAccount);
        followOpps.add(followOpp); 

    }
    insert followAccounts;
    insert followOpps;
}

 

This trigger works great for us, and I've tested it manually.  The problem comes in when I wrote my unit test for this trigger:

@isTest
private class ProspectConvertTest {
    static testMethod void myUnitTest() {
    //User user = [select id from User where alias = 'itest'];
        Lead newLead = new Lead(Company='My Test Lead', LastName = 'UnitTest');
        //newLead.CreatedById = user.Id;
        insert newLead;
        
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(newLead.Id);
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);
//Lead has been converted.  Check the lead, account, and opportunity
 
 
Lead existingLead = [Select id, isConverted, ConvertedAccountId, ConvertedOpportunityId, createdbyid FROM Lead where id = :newLead.id];
 
List<EntitySubscription> esList = [Select parentId, SubscriberId from EntitySubscription where parentid in (:existingLead.ConvertedAccountId, :existingLead.ConvertedOpportunityId) and SubscriberId = :existingLead.createdbyid];
 
System.assert(existingLead.isConverted);
System.assert(existingLead.ConvertedAccountId != null);
System.assert(existingLead.ConvertedOpportunityId != null);
 
//this is the statement that fails
System.assertEquals(2, esList.size());
    }

 

The last line in that unit test does not assert properly.  When run in a unit test, the EntitySubscriptions that are created in the trigger dont exist.  When I look at the code coverage, it is missing all the lines inside the for loop...which essentially tells me that the ConvertedOpportunityId is not being populated in the trigger.  The odd thing is that the trigger works fine when I convert a Lead using the UI.  Even odder is that If I run this query in the Trigger, it succeeds:

Lead convertedLead = [SELECT ID, ConvertedOpportunityId, ConvertedAccountId, CreatedById FROM Lead where ConvertedOpportunityId = :existingLead.ConvertedOpportunityId ];
System.assert(convertedLead != null);

 

So my problem is, why is the convertedOpportunityId populated in the unit test after the trigger is executed, but not before, and also why does it work when not run in a unit test?
Sorry if this is confusing....I can clarify with any questions.

System.TypeException: Invalid conversion from runtime type SET<String> to SET<Id>

 

getting this error when trying to test future method which takes parameter of SET<ID> and i am passing

SET<ID> only.

 

I dont know whay it happening, can anybody knows it.

 

 

  • October 03, 2011
  • Like
  • 0

Hi all,

    i want to write the edit functionality for detailed page in vf page.any one can u please help this .

 

Thanks in advance.

Hello all,

I'm an APEX noob, so please help. It would be appreciated!

We have a custom button on the Opportunities page, "Create Contract."  The button opens a window for a new Contract and pulls certain fields from the Opportunity into the new Contract.

We have recently begun to use both Opportunity and Contract record types. We need to select the Contract record type based on the Opportunity record type.

Mapping examples:
Opportunity Record Type A - Contract Record Type A (this is the default Contract type)
Opportunity Record Type B - Contract Record Type A
Opportunity Record Type C - Contract Record Type A
Opportunity Record Type D - Contract Record Type B
Opportunity Record Type E - Contract Record Type C

I have succeeded in passing a single record type, but I am having trouble in setting up the IF- ELSE statement in the button code to handle multiple record types.

The code is below. I am 100% certain that my IF statement syntax is incorrect somewhere, because it appears that the program never enters the code.  The new Contracts page always opens with user's default contract page view.

If I replace the below IF statement with the line:

 

&RecordType=012M00000000AcK 

 


then that record type is used, and the Contracts page opens with the page view associated with that Contract Record Type.

If any of you could help me with the syntax for a two-part IF-ELSE statement then I can build out the rest of the scenarios. Thanks!

 

 

/800/e?retURL=%2F800%2Fo

&if ({!Opportunity.RecordTypeId}==012C00000003okgIAA){
// Do this if the condition is true 
RecordType=012M00000000AcK   
} else {
// Do this if the condition is not true 
RecordType=012800000003buxAAA
}

&ctrc7_lkid={!Opportunity.AccountId}
&00N80000003uEo4={!Opportunity.Country__c}
&CF00N80000003VFS3={!Opportunity.Name}
&00N80000003uEsV={!Opportunity.CloseDate}
&00N80000003uEn1={!Opportunity.Policy__c}
&ctrc5={!Opportunity.Contract_Start_Date__c}
&00N80000003uEnk={!Opportunity.ExPat__c}
&00N80000003uEnl={!Opportunity.ASO__c}
&00N80000003udsE={!Opportunity.Cross_Marketing__c}
&00N80000003uErI={!Opportunity.Type}
&00N80000003uEsG={!Opportunity.Pooled__c}
&00N80000004ILAP={!Opportunity.Insurance_Company__c}
&00N80000004ILAA={!Opportunity.Bill_Type__c}
&00N80000004CNNe={!Opportunity.Expat_Account_Manager__c}
&00N80000003uEmr={!Opportunity.LOB_Expat__c}
&00N80000003uEmh={!Opportunity.LOB_del__c}
&00N80000003uEui={!Opportunity.Quoted_Due_Date__c}
&00N80000003uEww={!Opportunity.Quoted_Received_Date__c}
&00N80000003uEnm={!Opportunity.Quoted_Release_Date__c}
&00N80000003uErJ={!Opportunity.Decline_Options__c}
&00N80000003uExV={!Opportunity.Lost_Options__c}
&00N80000003uEsH={!Opportunity.Currency__c}
&00N80000003uEn3={!Opportunity.Life_Premium__c}
&00N80000003uEn2={!Opportunity.of_Employees__c}
&00N80000003uEn4={!Opportunity.Medical_Premium__c}
&00N80000003uEo1={!Opportunity.Disability_Premium__c}
&00N80000003uEuh={!Opportunity.Dental_Premium__c}
&00NC0000004yFM1={!Opportunity.Business_Travel_Medical_Premium__c}
&00N80000004ENTC={!Opportunity.LTD_Premium__c}
&00N80000004ENTH={!Opportunity.Other_Premium__c}
&00N80000003uEmi={!Opportunity.Total_Premium__c}
&00N80000003uEsp={!Opportunity.Collected_Contribution__c}
&00N80000003uEo5={!Opportunity.Collected_ATO__c}
&00N80000003uEsv={!Opportunity.Total_Collected_Contribution__c}
&00N80000003uErE={!Opportunity.Est_Annual_Contribution__c}
&00N80000003uEtO={!Opportunity.Est_ATO__c}
&00N80000003uEtT={!Opportunity.Total_Est_Contribution__c}
&00N80000003uEtY={!Opportunity.Assets_Under_Mgmt__c}
&00N80000003uEsw={!Opportunity.Total_Atlas_Premium__c}
&Description={!Opportunity.Description}
&00NM0000000H3dR={!Opportunity.Discount_Percentage__c}

 

  • September 27, 2011
  • Like
  • 0

Hello,

 

I've just written an Apex Classe in order to modify Opportuniy Name when Stage is greater than a specific values (Order Sent). The code is the following:

 

public class OpportunityAutoTypeName {
 // This method updates the opportunity name at end with (FOG Client Account) w/ Account Name
 public static void addOpportunityAutoTypeName(Opportunity[] accs){
  Set<Id> accId = new Set<Id>();  
  for (Opportunity a:accs){
    if(a.AccountId != null){
      accId.add(a.AccountId);
    }
  }  

  Map<Id,Account> accMap = new Map<Id,Account>([select Id, Name from Account where Id in : accId]);
  for (Opportunity a:accs){
    if(a.StageName >= 'Order Sent'){
    a.Name = a.Name+'-'+accMap.get(a.AccountId).Name+'-'+a.Number_of_hotels_this__c+'H'+'-'+a.Duration_Y__c+'Y'+'-'+a.Type_F__c;
  }
  }
 }
}

Then I wrote a trigger that invoques this class.

All is working but I would like the name changed only once time. How can I avoid that each time the opp is updated the name changes?

 

Can anyone help me?

 

Thanks,

 

Stefano

Hi there,

 

I'm using Visualforce and Google Map API, the page used to work well but now I got an error : "Map key state not found in map. "

 

I'm using Google Map API v3 so it doesn't require an API key, so I suppose it's coming from the visualforce but

after hours searching the code and the web, I can't figure it out.

 

I'm using a customized version of Find Nearby AppExchange application.

 

A hand would be great.

 

Thanks for reading.

  • September 15, 2011
  • Like
  • 0

hey everyone, m new to apex.i dont knw why but m  getting this error:  Incompatible types since an instance of SObject is never an instance of opportunity. plz help.... 

 

 

 

here is a bit of my code:

public with sharing  class opportunityExtensions { 

public opportunity opp;

   public opportunityExtensions(ApexPages.StandardController controller)     {     

  this.opp=(Opportunity)controller.getRecord(); 

     

}


  • September 15, 2011
  • Like
  • 0