SlideShare a Scribd company logo
1 of 24
Download to read offline
Demo how to create visualforce page and custom controller
via Developer Console
Description: Demo how to create visualforce page and custom controller to load, create and update
standard Account object using Developer Console.
Author: Tuan Vo (tuanv2t@gmail.com)
Version: 1.0
Contents
Create a classic Page.....................................................................................................................................1
Show page on a tab.......................................................................................................................................2
Create controller to get Accounts.................................................................................................................6
Modify Visualforce page to show accounts..................................................................................................9
Create new visualforce page to add New Account Demo ..........................................................................11
Create button New Account on the list......................................................................................................15
Create and page to update existing Account..............................................................................................18
Create a classic Page
Open the Developer Console under Your Name or the quick access menu (Setup gear icon).
The Developer Console opens in a new window.
Click File | New | Visualforce Page.
Enter AccountDemo for the name of the new page, and click OK.
A new, blank Visualforce page opens in the Developer Console.
Modify the content
<apex:page >
<h1>This is my Account Demo page</h1>
</apex:page>
The content will be updated later.
Show page on a tab
Go to Setup, Type Tab -> Create Tabs
Note: Select the Visualforce tab
Now we need to create controller to retrieve accounts from database and show accounts in page with
simple two columns Name and Account Number.
Create controller to get Accounts
File > New > Apex Class
Type: AccountDemoController
Copy and paste this code segment into the AccountDemoController
public class AccountDemoController {
public List<Account> getAccounts(){
List<Account> results = Database.query(
'SELECT Id, Name, AccountNumber ' +
'FROM Account ' +
'ORDER BY Name'
);
return results;
}
}
Now the AccountDemoController looks like this
Modify Visualforce page to show accounts
Back to the page AccountDemo, File > Open Resource
Find AccountDemo.vfp
Modify the source of AccountDemo.vfp as below
<apex:page controller="AccountDemoController">
<apex:pageBlock title="Accounts">
<apex:pageBlockTable value="{!Accounts}" var="account">
<apex:column value="{!account.Name}"/>
<apex:column value="{!account.AccountNumber}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
Now the AccountDmo.vfp looks like this
Now login salesforce, reopen the tab Account Demo and see how it works
Create new visualforce page to add New Account Demo
First, it’s necessary to create a new controller that will take responsibility to create new Account
In this case, controller AccountDemoController is able to reuse to make it simple
Because this is a custom controller, it’s necessary to add new public property to make it become a
model
public Account newAccount {get;set;}
This model must be instanced in the constructor
public AccountDemoController(){
newAccount = new Account();
}
Create a new public method to receive model and create new Account
public PageReference createNewAccount() {
insert newAccount;
return new PageReference('/apex/AccountDemo?id=' + newAccount.Id);
} The return statement will bring user back to the list whenever the new account has been created.
Nex, create a new Visualforce page from Developer Console, this page will be used as a form to create
new Account Demo.
The content of the page looks like this
<apex:page controller="AccountDemoController">
<h1>Add Account Demo</h1>
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection columns="1">
<apex:inputField value="{! newAccount.Name }"/>
<apex:inputField value="{!newAccount.AccountNumber}" />
</apex:pageBlockSection>
<apex:pageBlockButtons>
<apex:commandButton action="{!createNewAccount}" value="Create" />
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
It’s able to access to page directly from url such as
https://c.ap4.visual.force.com/apex/AccountDemoCreate
And here’s how it looks like
Try to enter name, number and click Create
The new created Account will be shown on the list.
The next step is creating a new button on the list, clicking on that button will bring user to the page to
create Account above
Until now, the controller AccountDemoController looks like this
public class AccountDemoController {
public AccountDemoController(){
newAccount = new Account();
}
public List<Account> getAccounts(){
List<Account> results = Database.query(
'SELECT Id, Name, AccountNumber ' +
'FROM Account ' +
'ORDER BY Name'
);
return results;
}
public Account newAccount {get;set;}
public PageReference createNewAccount() {
insert newAccount;
return new PageReference('/apex/AccountDemo?id=' + newAccount.Id);
}
}
There’s no change on the visualforce page AccountDemo
Create button New Account on the list
Modify controller AccountDemoController to add new public method
public PageReference redirectCreateAccountDemo()
{
PageReference pr = new PageReference('/apex/AccountDemoCreate');
return pr;
}
Open Developer console and open the visualforce page of the AccountDemo
Add new script below
<apex:form >
<apex:commandButton action="{!redirectCreateAccountDemo}" value="New Account"/>
</apex:form>
Note, the apex:commandButton must be located inside a apex:form
Now the visualforce page AccountDemo will look like
<apex:page controller="AccountDemoController">
<apex:pageBlock title="Accounts">
<apex:form >
<apex:commandButton action="{!redirectCreateAccountDemo}" value="New Account"/>
</apex:form>
<apex:pageBlockTable value="{!Accounts}" var="account">
<apex:column value="{!account.Name}"/>
<apex:column value="{!account.AccountNumber}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
And the content of controller
public class AccountDemoController {
public AccountDemoController(){
newAccount = new Account();
}
public List<Account> getAccounts(){
List<Account> results = Database.query(
'SELECT Id, Name, AccountNumber ' +
'FROM Account ' +
'ORDER BY Name'
);
return results;
}
public PageReference redirectCreateAccountDemo()
{
PageReference pr = new PageReference('/apex/AccountDemoCreate');
return pr;
}
public Account newAccount {get;set;}
public PageReference createNewAccount() {
insert newAccount;
return new PageReference('/apex/AccountDemo?id=' + newAccount.Id);
}
}
The next step is creating a new page to Update an existing Account
Create and page to update existing Account
First, it’s able to reuse the controller AccountDemoController.
The constructor of the controller will receive the Id of account
Modify AccountDemoController, add new public Account updatedAccount to act as a model in the edit
page ( the edit page will be created soon )
public Account updatedAccount {get;set;}
public AccountDemoController(){
newAccount = new Account();
//https://www.developerforce.com/guides/Visualforce_in_Practice.pdf
if(ApexPages.currentPage().getParameters().get('id')!=null){
updatedAccount = [select Id, Name, AccountNumber from Account where
id=:ApexPages.currentPage().getParameters().get('id')];
}
}
Here’s how the controller looks like
public class AccountDemoController {
public AccountDemoController(){
newAccount = new Account();
//https://www.developerforce.com/guides/Visualforce_in_Practice.pdf
if(ApexPages.currentPage().getParameters().get('id')!=null){
updatedAccount = [select Id, Name, AccountNumber from Account where
id=:ApexPages.currentPage().getParameters().get('id')];
}
}
public List<Account> getAccounts(){
List<Account> results = Database.query(
'SELECT Id, Name, AccountNumber ' +
'FROM Account ' +
'ORDER BY Name'
);
return results;
}
public PageReference redirectCreateAccountDemo()
{
PageReference pr = new PageReference('/apex/AccountDemoCreate');
return pr;
}
public Account newAccount {get;set;}
public PageReference createNewAccount() {
insert newAccount;
return new PageReference('/apex/AccountDemo?id=' + newAccount.Id);
}
public Account updatedAccount {get;set;}
public PageReference updateAccount () {
update updatedAccount;
return new PageReference('/apex/AccountDemo');
}
}
Now create a new visualforce page that will be used to update
Create a new visualforce page , name it AccountDemoUpdate and its content will be
<apex:page controller="AccountDemoController">
<h1>Update Account Demo</h1>
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection columns="1">
<apex:inputField value="{! updatedAccount.Name }"/>
<apex:inputField value="{!updatedAccount.AccountNumber}" />
</apex:pageBlockSection>
<apex:pageBlockButtons>
<apex:commandButton action="{! updateAccount }" value="Save" />
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
Now modify the home AccountDemo page, add new link Edit, clicking on that link will bring user to the
edit page
<apex:pageBlockTable value="{!Accounts}" var="account">
<apex:column>
<apex:outputLink
value="AccountDemoUpdate?id={!account.Id}">
Edit
</apex:outputLink>
</apex:column>
<apex:column value="{!account.Name}"/>
<apex:column value="{!account.AccountNumber}"/>
</apex:pageBlockTable>
So until now, here are the whole AccountDemo looks like
<apex:page controller="AccountDemoController">
<apex:pageBlock title="Accounts">
<apex:form >
<apex:commandButton action="{!redirectCreateAccountDemo}" value="New Account"/>
</apex:form>
<apex:pageBlockTable value="{!Accounts}" var="account">
<apex:column>
<apex:outputLink
value="AccountDemoUpdate?id={!account.Id}">
Edit
</apex:outputLink>
</apex:column>
<apex:column value="{!account.Name}"/>
<apex:column value="{!account.AccountNumber}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
Run it
Click on Edit of an record
Make change something for this account and click Save, user will be brought back to the list

More Related Content

Viewers also liked

mandibular landmarks of radiograph
mandibular landmarks of radiographmandibular landmarks of radiograph
mandibular landmarks of radiographAfsana Kader A
 
мухаметжанова ардак разработка открытого урока
мухаметжанова ардак разработка открытого урокамухаметжанова ардак разработка открытого урока
мухаметжанова ардак разработка открытого урокаoquzaman
 
Glogster docente
Glogster docenteGlogster docente
Glogster docenteriomadrid
 
Çatışma ve Travma ne zaman yararlıdır ?: Psikiyatride travma sonrası ne yapab...
Çatışma ve Travma ne zaman yararlıdır ?: Psikiyatride travma sonrası ne yapab...Çatışma ve Travma ne zaman yararlıdır ?: Psikiyatride travma sonrası ne yapab...
Çatışma ve Travma ne zaman yararlıdır ?: Psikiyatride travma sonrası ne yapab...Bedirhan Ustun
 
мухаметжанова ардак слайд открытый урок
мухаметжанова ардак слайд открытый урокмухаметжанова ардак слайд открытый урок
мухаметжанова ардак слайд открытый урокoquzaman
 
Digital marketing strategies
Digital marketing strategiesDigital marketing strategies
Digital marketing strategiesDEBASIS MALLIK
 

Viewers also liked (8)

mandibular landmarks of radiograph
mandibular landmarks of radiographmandibular landmarks of radiograph
mandibular landmarks of radiograph
 
мухаметжанова ардак разработка открытого урока
мухаметжанова ардак разработка открытого урокамухаметжанова ардак разработка открытого урока
мухаметжанова ардак разработка открытого урока
 
Glogster docente
Glogster docenteGlogster docente
Glogster docente
 
Codigo etico
Codigo eticoCodigo etico
Codigo etico
 
Law of motion
Law of motionLaw of motion
Law of motion
 
Çatışma ve Travma ne zaman yararlıdır ?: Psikiyatride travma sonrası ne yapab...
Çatışma ve Travma ne zaman yararlıdır ?: Psikiyatride travma sonrası ne yapab...Çatışma ve Travma ne zaman yararlıdır ?: Psikiyatride travma sonrası ne yapab...
Çatışma ve Travma ne zaman yararlıdır ?: Psikiyatride travma sonrası ne yapab...
 
мухаметжанова ардак слайд открытый урок
мухаметжанова ардак слайд открытый урокмухаметжанова ардак слайд открытый урок
мухаметжанова ардак слайд открытый урок
 
Digital marketing strategies
Digital marketing strategiesDigital marketing strategies
Digital marketing strategies
 

Similar to Demo how to create visualforce page and custom controller via developer console

Demo how to create visualforce and apex controller to update, delete custom o...
Demo how to create visualforce and apex controller to update, delete custom o...Demo how to create visualforce and apex controller to update, delete custom o...
Demo how to create visualforce and apex controller to update, delete custom o...tuan vo
 
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docxLab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docxsmile790243
 
TechSupportCh 21 project.doc1Projects.doc Project 21-.docx
TechSupportCh 21 project.doc1Projects.doc Project 21-.docxTechSupportCh 21 project.doc1Projects.doc Project 21-.docx
TechSupportCh 21 project.doc1Projects.doc Project 21-.docxmattinsonjanel
 
Oracle apex hands on lab#2
Oracle apex hands on lab#2Oracle apex hands on lab#2
Oracle apex hands on lab#2Amit Sharma
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right wayThibaud Desodt
 
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docxCSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docxruthannemcmullen
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAlfa Gama Omega
 
Binding to multiple datasources on a single xPage
Binding to multiple datasources on a single xPageBinding to multiple datasources on a single xPage
Binding to multiple datasources on a single xPagedominion
 
Share Point
Share PointShare Point
Share Pointjimbelo
 
Testing ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyTesting ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyBen Hall
 
Adding a view
Adding a viewAdding a view
Adding a viewNhan Do
 
Dynamics ax 2012 workflow development
Dynamics ax 2012 workflow development Dynamics ax 2012 workflow development
Dynamics ax 2012 workflow development Ahmed Farag
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletMitchinson
 
Please distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdfPlease distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdfneerajsachdeva33
 
SetFocus SQL Portfolio
SetFocus SQL PortfolioSetFocus SQL Portfolio
SetFocus SQL Portfoliogeometro17
 
RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Storiesrahoulb
 
Cis 407 i lab 1 of 7
Cis 407 i lab 1 of 7Cis 407 i lab 1 of 7
Cis 407 i lab 1 of 7helpido9
 
130297267 transformations
130297267 transformations130297267 transformations
130297267 transformationsSunil Pandey
 
Orangescrum Client management Add on User Manual
Orangescrum Client management Add on User ManualOrangescrum Client management Add on User Manual
Orangescrum Client management Add on User ManualOrangescrum
 

Similar to Demo how to create visualforce page and custom controller via developer console (20)

Demo how to create visualforce and apex controller to update, delete custom o...
Demo how to create visualforce and apex controller to update, delete custom o...Demo how to create visualforce and apex controller to update, delete custom o...
Demo how to create visualforce and apex controller to update, delete custom o...
 
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docxLab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
Lab StepsSTEP 1 Login Form1. In order to do this lab, we need.docx
 
TechSupportCh 21 project.doc1Projects.doc Project 21-.docx
TechSupportCh 21 project.doc1Projects.doc Project 21-.docxTechSupportCh 21 project.doc1Projects.doc Project 21-.docx
TechSupportCh 21 project.doc1Projects.doc Project 21-.docx
 
Oracle apex hands on lab#2
Oracle apex hands on lab#2Oracle apex hands on lab#2
Oracle apex hands on lab#2
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docxCSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
CSC139 Chapter 9 Lab Assignments (1) Classes and Obj.docx
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
 
Binding to multiple datasources on a single xPage
Binding to multiple datasources on a single xPageBinding to multiple datasources on a single xPage
Binding to multiple datasources on a single xPage
 
Share Point
Share PointShare Point
Share Point
 
Testing ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using RubyTesting ASP.net Web Applications using Ruby
Testing ASP.net Web Applications using Ruby
 
Adding a view
Adding a viewAdding a view
Adding a view
 
Dynamics ax 2012 workflow development
Dynamics ax 2012 workflow development Dynamics ax 2012 workflow development
Dynamics ax 2012 workflow development
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutlet
 
Please distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdfPlease distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdf
 
SetFocus SQL Portfolio
SetFocus SQL PortfolioSetFocus SQL Portfolio
SetFocus SQL Portfolio
 
RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Stories
 
Cis 407 i lab 1 of 7
Cis 407 i lab 1 of 7Cis 407 i lab 1 of 7
Cis 407 i lab 1 of 7
 
130297267 transformations
130297267 transformations130297267 transformations
130297267 transformations
 
Ajax learning tutorial
Ajax learning tutorialAjax learning tutorial
Ajax learning tutorial
 
Orangescrum Client management Add on User Manual
Orangescrum Client management Add on User ManualOrangescrum Client management Add on User Manual
Orangescrum Client management Add on User Manual
 

Recently uploaded

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

Demo how to create visualforce page and custom controller via developer console

  • 1. Demo how to create visualforce page and custom controller via Developer Console Description: Demo how to create visualforce page and custom controller to load, create and update standard Account object using Developer Console. Author: Tuan Vo (tuanv2t@gmail.com) Version: 1.0 Contents Create a classic Page.....................................................................................................................................1 Show page on a tab.......................................................................................................................................2 Create controller to get Accounts.................................................................................................................6 Modify Visualforce page to show accounts..................................................................................................9 Create new visualforce page to add New Account Demo ..........................................................................11 Create button New Account on the list......................................................................................................15 Create and page to update existing Account..............................................................................................18 Create a classic Page Open the Developer Console under Your Name or the quick access menu (Setup gear icon). The Developer Console opens in a new window. Click File | New | Visualforce Page. Enter AccountDemo for the name of the new page, and click OK. A new, blank Visualforce page opens in the Developer Console.
  • 2. Modify the content <apex:page > <h1>This is my Account Demo page</h1> </apex:page> The content will be updated later. Show page on a tab Go to Setup, Type Tab -> Create Tabs
  • 3. Note: Select the Visualforce tab
  • 4.
  • 5.
  • 6. Now we need to create controller to retrieve accounts from database and show accounts in page with simple two columns Name and Account Number. Create controller to get Accounts File > New > Apex Class
  • 8. Copy and paste this code segment into the AccountDemoController public class AccountDemoController { public List<Account> getAccounts(){ List<Account> results = Database.query( 'SELECT Id, Name, AccountNumber ' + 'FROM Account ' + 'ORDER BY Name' ); return results; } } Now the AccountDemoController looks like this
  • 9. Modify Visualforce page to show accounts Back to the page AccountDemo, File > Open Resource Find AccountDemo.vfp
  • 10. Modify the source of AccountDemo.vfp as below <apex:page controller="AccountDemoController"> <apex:pageBlock title="Accounts"> <apex:pageBlockTable value="{!Accounts}" var="account"> <apex:column value="{!account.Name}"/> <apex:column value="{!account.AccountNumber}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page> Now the AccountDmo.vfp looks like this
  • 11. Now login salesforce, reopen the tab Account Demo and see how it works Create new visualforce page to add New Account Demo First, it’s necessary to create a new controller that will take responsibility to create new Account In this case, controller AccountDemoController is able to reuse to make it simple Because this is a custom controller, it’s necessary to add new public property to make it become a model public Account newAccount {get;set;} This model must be instanced in the constructor public AccountDemoController(){ newAccount = new Account(); }
  • 12. Create a new public method to receive model and create new Account public PageReference createNewAccount() { insert newAccount; return new PageReference('/apex/AccountDemo?id=' + newAccount.Id); } The return statement will bring user back to the list whenever the new account has been created. Nex, create a new Visualforce page from Developer Console, this page will be used as a form to create new Account Demo. The content of the page looks like this <apex:page controller="AccountDemoController"> <h1>Add Account Demo</h1> <apex:form> <apex:pageBlock> <apex:pageBlockSection columns="1">
  • 13. <apex:inputField value="{! newAccount.Name }"/> <apex:inputField value="{!newAccount.AccountNumber}" /> </apex:pageBlockSection> <apex:pageBlockButtons> <apex:commandButton action="{!createNewAccount}" value="Create" /> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page> It’s able to access to page directly from url such as https://c.ap4.visual.force.com/apex/AccountDemoCreate And here’s how it looks like
  • 14. Try to enter name, number and click Create The new created Account will be shown on the list. The next step is creating a new button on the list, clicking on that button will bring user to the page to create Account above Until now, the controller AccountDemoController looks like this public class AccountDemoController { public AccountDemoController(){ newAccount = new Account(); } public List<Account> getAccounts(){
  • 15. List<Account> results = Database.query( 'SELECT Id, Name, AccountNumber ' + 'FROM Account ' + 'ORDER BY Name' ); return results; } public Account newAccount {get;set;} public PageReference createNewAccount() { insert newAccount; return new PageReference('/apex/AccountDemo?id=' + newAccount.Id); } } There’s no change on the visualforce page AccountDemo Create button New Account on the list Modify controller AccountDemoController to add new public method public PageReference redirectCreateAccountDemo() { PageReference pr = new PageReference('/apex/AccountDemoCreate'); return pr; } Open Developer console and open the visualforce page of the AccountDemo Add new script below <apex:form >
  • 16. <apex:commandButton action="{!redirectCreateAccountDemo}" value="New Account"/> </apex:form> Note, the apex:commandButton must be located inside a apex:form Now the visualforce page AccountDemo will look like <apex:page controller="AccountDemoController"> <apex:pageBlock title="Accounts"> <apex:form > <apex:commandButton action="{!redirectCreateAccountDemo}" value="New Account"/> </apex:form> <apex:pageBlockTable value="{!Accounts}" var="account"> <apex:column value="{!account.Name}"/> <apex:column value="{!account.AccountNumber}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>
  • 17. And the content of controller public class AccountDemoController { public AccountDemoController(){ newAccount = new Account(); } public List<Account> getAccounts(){ List<Account> results = Database.query( 'SELECT Id, Name, AccountNumber ' + 'FROM Account ' + 'ORDER BY Name' ); return results;
  • 18. } public PageReference redirectCreateAccountDemo() { PageReference pr = new PageReference('/apex/AccountDemoCreate'); return pr; } public Account newAccount {get;set;} public PageReference createNewAccount() { insert newAccount; return new PageReference('/apex/AccountDemo?id=' + newAccount.Id); } } The next step is creating a new page to Update an existing Account Create and page to update existing Account First, it’s able to reuse the controller AccountDemoController. The constructor of the controller will receive the Id of account Modify AccountDemoController, add new public Account updatedAccount to act as a model in the edit page ( the edit page will be created soon ) public Account updatedAccount {get;set;} public AccountDemoController(){ newAccount = new Account(); //https://www.developerforce.com/guides/Visualforce_in_Practice.pdf if(ApexPages.currentPage().getParameters().get('id')!=null){ updatedAccount = [select Id, Name, AccountNumber from Account where id=:ApexPages.currentPage().getParameters().get('id')];
  • 19. } } Here’s how the controller looks like public class AccountDemoController { public AccountDemoController(){ newAccount = new Account(); //https://www.developerforce.com/guides/Visualforce_in_Practice.pdf if(ApexPages.currentPage().getParameters().get('id')!=null){ updatedAccount = [select Id, Name, AccountNumber from Account where id=:ApexPages.currentPage().getParameters().get('id')]; } } public List<Account> getAccounts(){ List<Account> results = Database.query( 'SELECT Id, Name, AccountNumber ' + 'FROM Account ' + 'ORDER BY Name' ); return results; } public PageReference redirectCreateAccountDemo() { PageReference pr = new PageReference('/apex/AccountDemoCreate'); return pr; }
  • 20. public Account newAccount {get;set;} public PageReference createNewAccount() { insert newAccount; return new PageReference('/apex/AccountDemo?id=' + newAccount.Id); } public Account updatedAccount {get;set;} public PageReference updateAccount () { update updatedAccount; return new PageReference('/apex/AccountDemo'); } } Now create a new visualforce page that will be used to update Create a new visualforce page , name it AccountDemoUpdate and its content will be <apex:page controller="AccountDemoController"> <h1>Update Account Demo</h1> <apex:form> <apex:pageBlock> <apex:pageBlockSection columns="1"> <apex:inputField value="{! updatedAccount.Name }"/> <apex:inputField value="{!updatedAccount.AccountNumber}" /> </apex:pageBlockSection>
  • 21. <apex:pageBlockButtons> <apex:commandButton action="{! updateAccount }" value="Save" /> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page> Now modify the home AccountDemo page, add new link Edit, clicking on that link will bring user to the edit page <apex:pageBlockTable value="{!Accounts}" var="account"> <apex:column> <apex:outputLink value="AccountDemoUpdate?id={!account.Id}"> Edit </apex:outputLink> </apex:column> <apex:column value="{!account.Name}"/> <apex:column value="{!account.AccountNumber}"/> </apex:pageBlockTable> So until now, here are the whole AccountDemo looks like <apex:page controller="AccountDemoController">
  • 22. <apex:pageBlock title="Accounts"> <apex:form > <apex:commandButton action="{!redirectCreateAccountDemo}" value="New Account"/> </apex:form> <apex:pageBlockTable value="{!Accounts}" var="account"> <apex:column> <apex:outputLink value="AccountDemoUpdate?id={!account.Id}"> Edit </apex:outputLink> </apex:column> <apex:column value="{!account.Name}"/> <apex:column value="{!account.AccountNumber}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page> Run it
  • 23. Click on Edit of an record
  • 24. Make change something for this account and click Save, user will be brought back to the list