Tag Archives: Apex Class

Invoke Apex Class from Trigger

You can create static or instance methods on your Apex Class. In your trigger you can then have code that calls these classes. This is very similar to the way method calling works in other languages. Here is a simple example.

Apex Class:

public class SampleClass
{
    public void SampleMethod(List<Account> listAccount, Map<Id, Account> mapAccount){
        
    }
}

Apex Trigger:

trigger SampleAccount on Account (before insert) 
{
    for(Account a : trigger.New){
        SampleClass obj = new SampleClass(Trigger.New, Trigger.NewMap);
        obj.SampleMethod();
    }
}

Insert Record by Using Visualforce Page and Apex Class

In below example I’m inserting Account object record using Visualforce Page and Apex Class.

Visualforce Page:

<apex:page controller="CreateAccountController">
    <apex:form>
        <apex:pageblock>
            <apex:pageblocksection>
                <apex:inputfield value="{!acc.Name}"/>
                <apex:inputfield value="{!acc.Accountnumber}"/>
            </apex:pageblocksection>
            <apex:commandbutton action="{!SaveMethod}" value="Save"/>
        </apex:pageblock>
    </apex:form>
</apex:page>

Apex Class:

public class CreateAccountController{
    
    //Prpoerties
    public Account acc {get;set;}
    
    //Constructor 
    public CreateAccountController(){        
        //Instances        
        acc = new Account();
    }
    
    //Save Method 
    public PageReference SaveMethod(){
        Insert acc;
        return null;
    }
}