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
Filipe BaradelliFilipe Baradelli 

How to execute Apex code with a Visualforce Page?

I've created an Apex class to do a test and I need to execute it. I would like to know how to execute it with a button for example (I've created a button that is related with a Visualforce page).
Here is the code that I want to test: 
public class Teste {

    public void teste1(){
        // Insert Product
        Product2 pr = new Product2();
        pr.Name='Moto - G1';
        insert pr;
        // Insert Pricebook
        PriceBook2 customPriceBook = new PriceBook2();
        customPriceBook.Name='Custom Pricebook';
        insert customPriceBook;
        // Query Standard and Custom Price Books
        Pricebook2 customPriceBookRec=[select Id from Pricebook2 where id=:customPriceBook.Id];
        Id stdPriceBookRecId = Test.getStandardPricebookId();
        // Create Standard PriceBookEntry
        PriceBookEntry stdPriceBookEntry = new PriceBookEntry();
        insert stdPriceBookEntry;
        // Create Custom PriceBookEntry
        PriceBookEntry customPriceBookEntry = new PriceBookEntry();
        insert customPriceBookEntry;
        // Create Opportunity
        Opportunity opp = new Opportunity();
        opp.Name = 'Test';
        opp.CloseDate= System.Today();
        insert opp;
        // Add product and Pricebook to the particular opportunity using OpportunityLineItem 
        OpportunityLineItem oppLineItem = new OpportunityLineItem();
        oppLineItem.OpportunityId = opp.Id;
        oppLineItem.PricebookEntryId = customPriceBookEntry.Id;
        oppLineItem.UnitPrice = 7000;
        oppLineItem.Quantity = 5;
        insert oppLineItem;
Could you help me please?
MM SaikumarMM Saikumar

use command button tag and call method
<apex:commandbutton value="something" action="{!methodname}"/>
Filipe BaradelliFilipe Baradelli
Thank you.
I put this: 
<apex:page >
    <apex:form >
        <apex:commandbutton value="Criar Op" action="{!teste1}" />
But does'nt works. It is because of the Visualforce sentence or the cause is the code in apex?
Filipe BaradelliFilipe Baradelli
I did it after, and the problem is the problem is the code, in the part :  Id stdPriceBookRecId = Test.getStandardPricebookId();
I can't create a pricebook and pricebookentry because of the "test".
Thanks by the help, if you can help me in this part, I'll be glad too.