[SalesForce] How to add a Custom button to a Custom Visualforce page

I have created a custom button that runs JavaScript to update a long text area field in my Opportunity object. This works fine when the custome button is added to the standard Opportunity Page Layout.

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

var note = prompt("Add Note", "");
if (note != null) {
var project = new sforce.SObject("Opportunity");
project.id = "{!Opportunity.Id}";

var date = "{!TODAY()}";
// var user = "{!$User.Alias}";
var user = "{!$User.CommunityNickname}";
var oldnote = "{!JSENCODE(Opportunity.Description)}";
var prepend = date+" "+user+" - "+note+"\n";
var newnote = prepend+oldnote;

project.Description = newnote;

var result = sforce.connection.update([project]);
window.location.reload();
}

I would like to use a custom visualforce page to display the note field to be updated along with the button to trigger the update script. How can I get the button on this page to act the same as the custom button created for the standard layout?

<apex:page standardController="Opportunity" showHeader="false" sidebar="false">
    <apex:form> 
        <apex:pageBlock>
            <apex:pageBlockSection columns="3">
                <apex:outputField label = "Description" value = "{! Opportunity.Description}" />
                <apex:commandButton action="{!Save}" value="Add Note" /> 
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>  
</apex:page>

Best Answer

You can call your method on button click as shown below

<apex:page standardController="Opportunity" showHeader="false" sidebar="false">
<script>
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
//This is your javascript
function SaveNote()
{
    var note = document.getElementById('frmid:pgblk:pgblksection:descriptionfield').value;
    if (note != null) {
    var project = new sforce.SObject("Opportunity");
    project.id = "{!Opportunity.Id}";

    var date = "{!TODAY()}";
    // var user = "{!$User.Alias}";
    var user = "{!$User.CommunityNickname}";
    var oldnote = "{!JSENCODE(Opportunity.Description)}";
    var prepend = date+" "+user+" - "+note+"\n";
    var newnote = prepend+oldnote;

    project.Description = newnote;

    var result = sforce.connection.update([project]);
    window.location.reload();
    return false;
    }

}

</script>
<apex:form id="frmid"> 
    <apex:pageBlock id="pgblk">
        <apex:pageBlockSection columns="3" id="pgblksection">
            <apex:inputfield id="descriptionfield" value = "{! Opportunity.Description}" />
            <apex:commandButton onclick="return SaveNote();" value="Add Note" /> 
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>  

Related Topic