function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sbarstowsbarstow 

Example for Creating Opportunity And Case From Account

 to do this and I thought others might benefit from the example.  
The business function was to have a button on the account page that would create a new opportunity and case ( for the primary contact ).  I built a controller and page, then hooked it up to the button.  here is the process:
Go to Setup | Develop | Apex Classes
Create a new class and copy the following code into the editor ( it should format I hadcorrectly ):

  I had a customer that wanted to do this and I thought others might benefit from the example.  
The business function was to have a button on the account page that would create a new opportunity and case ( for the primary contact ).  I built a controller and page, then hooked it up to the button.  here is the process:

 

Go to Setup | Develop | Apex Classes


Create a new class and copy the following code into the editor ( it should format correctly ):

 

 

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

*Name :  Account Controller 

*Purpose: acts as the extension for the standard functionality

          Creates a Opportunity with default values

          Creates a Case with default values

          with the primary contact and opp.Name selected by the user

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

public class AccountController {

 

    //-------Private Variables Section------------//

    private final Account account;

    private List<Contact> lstContact;

    private String selectedContactId;

    private Case theCase;

 

    //-------------------Construtor-------------------------------//

    public AccountController(ApexPages.StandardController controller) {

       this.account = (Account)controller.getRecord();

       this.opportunity = new Opportunity();

       PopulateContacts();

    }

 

    //--------------------Public Properties Accessed on VF page-----------//

    public Opportunity opportunity {get;set;}

    public List<Contact> getAccountContacts() {

      return lstContact;

    }

 

    //-----------------------Private Methods--------------------------------//

    private void PopulateContacts() {

        if(this.account.Id == null) {

          this.lstContact = new List<Contact>();

          return;

        }

        //Load all Contact related to this Account,with Name,Title etc

      this.lstContact = [select Id,Name,Title,Email,Phone from Contact where AccountId = :this.account.Id];

    }

 

    //-----------------------------------------------------//

    //Create a Opportunity object, using default values, and current Account,seleccted Contact

    //-----------------------------------------------------//    

    private void CreateOpportunity() {

        this.opportunity.StageName = 'Prospecting';

        this.opportunity.CloseDate = System.today().addDays(14);

        this.opportunity.AccountId = this.account.ID;

        this.opportunity.LeadSource = this.account.AccountNumber;

 

      upsert this.opportunity;

    }

 

    //-----------------------------------------------------//

    //Create a Case object, using default values, and current Account,seleccted Contact

    //-----------------------------------------------------//

    private void CreateCase() {

      theCase = new Case();

      theCase .Origin = 'Web';

      theCase .Status = 'New';

      theCase .AccountId = this.account.Id;

      theCase .ContactId = this.selectedContactId;

      theCase .Subject = 'Case for ' + this.Account.Name;

 

 

      //Case cCase = new Case();

      //cCase.Origin = 'Web';

      //cCase.Status = 'New';

      //cCase.AccountId = this.account.Id;

      //cCase.ContactId = this.selectedContactId;

      //cCase.Subject = 'Case for ' + this.Account.Name;

 

      upsert theCase;

    }

 

    //------------------------Page Reference Methods-------------------------------------------------------// 

    public PageReference SaveOpportunity() {

 

      //Validate Data

      this.selectedContactId = ApexPages.currentPage().getParameters().get('ctRadio');

      if(selectedContactId == null || selectedContactId == '') {

        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'Please select a primary contact'));

        return null;

      }

 

      //Create Opportunity and Case

      try {

         CreateOpportunity();

         CreateCase();

      }

      catch(DmlException ex) {  //If any error occurs during creation of Case,Opportunity

        ApexPages.addMessages(ex);

        return null;

      }

      //Redirect back to the Account Detail page

      return new PageReference('/' + this.theCase.Id);

    }

 

 

    //---------------------------------------------TEST METHOD --------------------------------------------------------------//

    //Test Code coverage 75% required for moving code in Production environment

    //No data is committed or modified during test case execution

    //------------------------------------------------------------------------------------------------------------------------//

 

    @isTest

    private static void TestAccountController() {

      //Generate Sample Test data

      Account account = new Account(Name = 'Hello World');

      insert account;

 

      Contact contact = new Contact(LastName = 'Hello',AccountId = account.Id);

      insert contact;

 

      ApexPages.Standardcontroller stdController = new ApexPages.StandardController(account);

      AccountController ctrl = new AccountController(stdController);

 

      Test.startTest();

      Test.setCurrentPageReference(Page.MyNewPage);

 

      List<Contact> lstContact = ctrl.getAccountContacts();

      //Should contain 1 record

      System.assertEquals(lstContact.size(),1);

 

      ctrl.opportunity.Name = 'Hello world Opportunity';

      PageReference pg = ctrl.SaveOpportunity();

      //Should raise an error,because selected ContactId is not set

      System.assertEquals(null,pg);

 

      ApexPages.currentPage().getParameters().put('ctRadio',contact.Id);

      pg = ctrl.SaveOpportunity();

 

      Test.stopTest();

 

      //Assert that Opportunity and Case created

      Integer cCaseCount = [select count() from Case where AccountId = :account.Id AND ContactId = :contact.Id];

      Integer OpportunityCount = [select count() from Opportunity where AccountId = :account.Id];

 

      System.assertEquals(1,cCaseCount);

      System.assertEquals(1,opportunityCount); 

    }

}

 

sbarstowsbarstow

Next, you need to create a new page.  Go to Develop | Pages and create a new page, and paste the following code into the editor:

 

 

<apex:page standardController="Account" extensions="AccountController">
<apex:sectionHeader title="Create a new Opportunity" subTitle="{!Account.Name}" />
<apex:pageMessages />
<apex:form >
  <apex:pageBlock title="Opportunity">
  
    <apex:pageBlockButtons >
      <apex:commandButton value="Save" action="{!SaveOpportunity}" />
      <apex:commandButton value="Cancel" action="{!Cancel}" />
    </apex:pageBlockButtons>
    
    <apex:pageBlockSection title="Opportunity Details" collapsible="false">
      <apex:inputField value="{!Opportunity.Name}" />
    </apex:pageBlockSection>
    
    <apex:pageBlockSection title="Contacts" columns="1" collapsible="false">
      <apex:pageBlockTable value="{!AccountContacts}" var="ctc">
        
        <apex:column >
          <apex:outputPanel rendered="{!IF(AccountContacts.size = 1,false,true)}">
            <input type="radio" name="ctRadio" value="{!ctc.Id}" />
          </apex:outputPanel>
          <apex:outputPanel rendered="{!IF(AccountContacts.size = 1,true,false)}">
            <input type="radio" name="ctRadio" value="{!ctc.Id}" checked="checked" />
          </apex:outputPanel>
        </apex:column>
        
        <apex:column value="{!ctc.Name}"></apex:column>
        <apex:column value="{!ctc.Title}"></apex:column>
        <apex:column value="{!ctc.Email}"></apex:column>
        <apex:column value="{!ctc.Phone}"></apex:column>
      </apex:pageBlockTable>
    </apex:pageBlockSection>
       
  </apex:pageBlock>
  <apex:outputPanel rendered="false">
    {!Account.AccountNumber},{!Account.Name},{!Account.Industry}
  </apex:outputPanel> 
</apex:form>
</apex:page>

 

<apex:page standardController="Account" extensions="AccountController"><apex:sectionHeader title="Create a new Opportunity" subTitle="{!Account.Name}" /><apex:pageMessages />
<apex:form >  <apex:pageBlock title="Opportunity">      <apex:pageBlockButtons >      <apex:commandButton value="Save" action="{!SaveOpportunity}" />      <apex:commandButton value="Cancel" action="{!Cancel}" />    </apex:pageBlockButtons>        <apex:pageBlockSection title="Opportunity Details" collapsible="false">      <apex:inputField value="{!Opportunity.Name}" />    </apex:pageBlockSection>        <apex:pageBlockSection title="Contacts" columns="1" collapsible="false">      <apex:pageBlockTable value="{!AccountContacts}" var="ctc">                <apex:column >          <apex:outputPanel rendered="{!IF(AccountContacts.size = 1,false,true)}">            <input type="radio" name="ctRadio" value="{!ctc.Id}" />          </apex:outputPanel>          <apex:outputPanel rendered="{!IF(AccountContacts.size = 1,true,false)}">            <input type="radio" name="ctRadio" value="{!ctc.Id}" checked="checked" />          </apex:outputPanel>        </apex:column>                <apex:column value="{!ctc.Name}"></apex:column>        <apex:column value="{!ctc.Title}"></apex:column>        <apex:column value="{!ctc.Email}"></apex:column>        <apex:column value="{!ctc.Phone}"></apex:column>      </apex:pageBlockTable>    </apex:pageBlockSection>         </apex:pageBlock>  <apex:outputPanel rendered="false">    {!Account.AccountNumber},{!Account.Name},{!Account.Industry}  </apex:outputPanel> </apex:form></apex:page>

 

Finally

 

Go To Customize | Accounts and create a new custom button.  For the content source, select the VisualForce page you just created.  

 

Add the button to the page layout and you should have a working button