Tuesday, September 25, 2012

To get "probability" field values assigned automatically when selecting "Stage" field on opportunity through VF page

When selecting the "Stage" field on creating new Opportunity record through standard page , "probability" field get values automatically.

But when you access both the fields using inputField in VF page ; it do not gives the values automatically .

For e.g :- just copy\paste this code in VF page and try to select the "Stage" field ; it will not render the value of Probability field.

<apex:page standardController="Opportunity">
<apex:form>

<apex:inputField value="{!Opportunity.StageName}"/>
<apex:inputField value="{!Opportunity.Probability}"/>

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

Resolution :- 


"OpportunityStage" object represents a value in the opportunity stage picklist & provides additional information about the stage of a Opportunity, such as its probability or forecast category.

So I have tried to query the OpportunityStage object on the basis of "MasterLabel " field ,Please follow the below mentioned code for implementing this work in VF page :-

<apex:page standardController="Opportunity">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" />
<script src="/soap/ajax/15.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>

<script>
sforce.connection.sessionId = "{!$Api.Session_ID}";

function processChange(){

var obj = document.getElementById('{!$Component.frm.stageFieldId}');
var p = document.getElementById('{!$Component.frm.probabilityFieldId}');

var qr = sforce.connection.query("Select DefaultProbability From OpportunityStage where MasterLabel = '" + $(obj).val() + "'") ;
records = qr.getArray("records");

for (var i=0; i< records.length; i++) {
var record = records[i];
$(p).val(record.DefaultProbability);
break;
}
return true;
}
</script>

<apex:form id="frm">
<apex:inputField value="{!Opportunity.StageName}" onchange="processChange()" id="stageFieldId" />
<apex:inputField value="{!Opportunity.Probability}" id="probabilityFieldId"/>
</apex:form>
</apex:page>


NOTE :- You can directly copy\save this code without any modifications , however ; as this is a sample code, kindly modify it according to your requirement.

Please refer to below mentioned link to know more about this object.

http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_opportunitystage.htm

6 comments: