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
vo2maxvo2max 

Visualforce page for new objects

I have been successful with creating VF pages that are used to override a 'Edit' buttons for a few objects within Salesforce. I would like to do  the same to override the 'New' button. I've used the same code, as a starting point. I find that the standard controller attempts to retrieve a record from the database based on the record Id found in the request, and made it available to the Visualforce page (automatically). And if the retrieval is a success, the page displays as it should. 

 

When using a standard controller and I do not have an Id for the object, as it is when a user clicks 'New', how can I present the same form/layout that one would see with the standard page? Is this possible?

 

Thanks much.

Best Answer chosen by Admin (Salesforce Developers) 
Alok_NagarroAlok_Nagarro

Hi,

 

Plz refer code given below, i refered account in this example ,u can refer your object.

 

//--------------controller class------------------

public class MyExtension
{
 public Account acc{get; set;}
 String accId;
 public MyExtension(ApexPages.StandardController stdcon)
 {
  accId=ApexPages.CurrentPage.getParameters().get('id');     // access the account id from url
  if(accId != null && accId!='')                             // if id is in url means record is for edit
   acc= (Account)stdcon.getRecord();
  else                                                      // else you r gonna create new record
   acc=new Account();  
 }
 
 public PageReference save()
 {
  if(accId != null && accId!='')
   update acc;
  else
   insert acc;
  return null;   
 }
 
 public PageReference Cancel()
 {
  return null;
 }
}

//-----------visualforce page-------------------

<apex:page standardController="Account" extensions="MyExtensions"/>
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockButton>
              <apex:commandButton value="Save" action="{!save}"/>
              <apex:commandButton value="Cancel" action="{!cancel}"/>
            <apex:pageBlockButton>
        
        
            <apex:pageBlockSection>
                <apex:pageBlockSectionItem>
                 <apex:inputField value="{!acc.name}"/>
                
                 <!-- like above field you can bind other fields of account here -->
                
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

All Answers

Alok_NagarroAlok_Nagarro

Hi,

 

You want to use single Visualforce page for both purpose edit as well as new, as i unterstood.For that you need to create a controller class as extension and check in the controllers's constructor whether you r getting id or not, If you get id then intialize the object with this id else create new object and bind that object in the page.

Devendra@SFDCDevendra@SFDC

 

You dont need ID when you are creating New Record.

 

Override New button with visualforce page keeping your stanadard controller for that Object.

 

User action as {!save}  for command button "Save", As it will invoke default save methodof standard controller, and new record will be created.

 

Thanks,

Devendra

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

 

 

vo2maxvo2max

Thanks, Alok.

 

How do I check for the id and initialize if it is there? And how do I create a new object (if the id is not there) and bind the object to the page? Do you mind providing a short example?

 

Thanks!

Devendra@SFDCDevendra@SFDC

Hi,

 

Controller Code
public with sharing class AccountCreateController
{
	// the account record you are adding values to
	public Account acc
	{
		get
		{
			if(acc==NULL)
				acc=new Account();
			return acc;
		}
		set;
	}

	public AccountCreateController()
	{
		// blank constructor
	}

	// save button
	public PageReference save()
	{
		try
		{
			insert acc;
		}	
		catch(DMLException e)
		{
			ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error creating new Account'));	
			return NULL;
		}
	}
}

// VF page

<apex:page controller="AccountCreateController">
  <apex:sectionHeader title="Visualforce Example" subtitle="Create a Account"/>
 
  <apex:form >
    <apex:pageMessages /> <!-- this is where the error messages will appear -->
    <apex:pageBlock title="Contact Info">
 
      <apex:pageBlockButtons >
        <apex:commandButton action="{!save}" value="Save"/>
      </apex:pageBlockButtons>
 
      <apex:pageBlockSection showHeader="false" columns="2">
        <apex:inputField value="{!acc.Name}" />
      </apex:pageBlockSection>
 
    </apex:pageBlock>
  </apex:form>
</apex:page>

 

Thanks,

Devendra

Alok_NagarroAlok_Nagarro

Hi,

 

Plz refer code given below, i refered account in this example ,u can refer your object.

 

//--------------controller class------------------

public class MyExtension
{
 public Account acc{get; set;}
 String accId;
 public MyExtension(ApexPages.StandardController stdcon)
 {
  accId=ApexPages.CurrentPage.getParameters().get('id');     // access the account id from url
  if(accId != null && accId!='')                             // if id is in url means record is for edit
   acc= (Account)stdcon.getRecord();
  else                                                      // else you r gonna create new record
   acc=new Account();  
 }
 
 public PageReference save()
 {
  if(accId != null && accId!='')
   update acc;
  else
   insert acc;
  return null;   
 }
 
 public PageReference Cancel()
 {
  return null;
 }
}

//-----------visualforce page-------------------

<apex:page standardController="Account" extensions="MyExtensions"/>
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockButton>
              <apex:commandButton value="Save" action="{!save}"/>
              <apex:commandButton value="Cancel" action="{!cancel}"/>
            <apex:pageBlockButton>
        
        
            <apex:pageBlockSection>
                <apex:pageBlockSectionItem>
                 <apex:inputField value="{!acc.name}"/>
                
                 <!-- like above field you can bind other fields of account here -->
                
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

This was selected as the best answer
vo2maxvo2max

Perfect. Thanks!

 

One final question...

 

Is it possible to display the same form that is displayed when the 'Standard Salesforce Page' is used vs. inserting each of the form fields myself in the Visualforce Page? For example:

 

My Visualforce Page:

 

                <apex:inputField value="{!Call__c.Inquiry_Type__c}"/>
                <apex:inputField value="{!Call__c.Subject__c}"/>
                <apex:inputField value="{!Call__c.Call_Summary__c}"/>
                <apex:inputField value="{!Call__c.Due_By__c}"/>

 

All of these are insterted dynamically via the standard page. Can I access that standard form in my VF page?

 

 

Alok_NagarroAlok_Nagarro

Hi,

 

No you cant, you need to insert every field yourself.

Devendra@SFDCDevendra@SFDC

 

Thanks Alok_vibrant!!

 

Thanks,

Devendra

BjoernBjoern

Actually, you can "auto-create" records for standard objects without having to create a trigger or a controller extension class. If you want the VF page to create a record you can use the "save_new" parameter. See this exampe. Override the "new" button or simply create a new button with this url; /apex/AutoCreateOpportunity?save_new=1

And then write the AutoCreateOpportunity.page like this;

 

<apex:page standardController="Opportunity">
<apex:form >
<input type="hidden" name="isPostBack" id="isPostBack" value="1"/>
<apex:outputPanel id="oppPage">
<apex:pageMessages />
<apex:messages />
<apex:pageBlock mode="edit">
<apex:inputfield value="{!opportunity.Name}" label="{!$ObjectType.Opportunity.fields.Name.label}" id="oppName"/>
<apex:inputfield value="{!opportunity.CloseDate}" label="{!$ObjectType.Opportunity.fields.CloseDate.label}" id="oppCloseDate"/>
<apex:inputfield value="{!opportunity.StageName}" label="{!$ObjectType.Opportunity.fields.StageName.label}" id="oppStageName" />
<apex:commandButton action="{!save}" value=" Save " />
</apex:pageBlock>

<apex:pageBlock mode="detail">
<apex:outputfield value="{!opportunity.Name}" label="{!$ObjectType.Opportunity.fields.Name.label}"/>
<apex:outputfield value="{!opportunity.CloseDate}" label="{!$ObjectType.Opportunity.fields.CloseDate.label}" />
<apex:outputfield value="{!opportunity.StageName}" label="{!$ObjectType.Opportunity.fields.StageName.label}" />
<apex:commandButton action="{!edit}" value=" Edit " rerender="oppPage"/>
</apex:pageBlock>
</apex:outputPanel>

<script type="text/javascript">
function getApexFieldByValue(value) {
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++) {
if (elements[i].value != value) continue;
return elements[i];
}
return null;
}

function getApexFieldById(tagName, id) {
var elements = document.getElementsByTagName(tagName);
for (var i = 0; i < elements.length; i++) {
var parts = elements[i].id.split(":");
if (parts.length == 0) continue;
if (parts[parts.length -1 ] != id) continue;
return elements[i];
}
return null;
}

function getApexFieldByValue(value) {
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++) {
if (elements[i].value != value) continue;
return elements[i];
}
return null;
}

function getToday() {
var d = new Date();

var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();

return dString = curr_year + "-" + curr_month + "-" + curr_date;
}

var isPostBack = "{!$CurrentPage.parameters.isPostBack}";

if (isPostBack != "1") {
getApexFieldById("input", "oppName").value = "Test";
getApexFieldById("input", "oppCloseDate").value = getToday();
getApexFieldById("select", "oppStageName").value = "Closed Won";
setTimeout(function () { getApexFieldByValue(" Save ").click(); }, 3000);
}
</script>
</apex:form>
</apex:page>

 

Now, when this URL is called it will "auto-create" an opportunity. You can pass parameters and fetch them with javascript and then populating the fields before save. This will be a client-side version of an apex trigger. Say you want to "auto-create" a record of a standard object when another object is saved, updated or deleted. Then you can create another VF page overriding the edit/detail of that object and then calling this URL upon save. Passing arguments in URL and handling them in the "auto-create" page will make it a conditional client-side trigger :)    ... all achievable with Professional edition.

Well, endless of possibilities...

mustafatopmustafatop

Hi Bjoern


Expression value does not resolve to a field Error is in expression '{!opportunity.Account}' in component <apex:inputField> in page addopp


I'm getting
the this error when i use account field of Opportunity object in your code. How to add a lookup field in apex:pageblock? Can you help me please?

 

<apex:pageBlock mode="edit">
<apex:inputfield value="{!opportunity.Name}" label="{!$ObjectType.Opportunity.fields.Name.label}" id="oppName"/>
<apex:inputfield value="{!opportunity.CloseDate}" label="{!$ObjectType.Opportunity.fields.CloseDate.label}" id="oppCloseDate"/>
<apex:inputfield value="{!opportunity.StageName}" label="{!$ObjectType.Opportunity.fields.StageName.label}" id="oppStageName" />
<apex:inputfield value="{!opportunity.Account}" label="{!$ObjectType.Opportunity.fields.Account.label}" id="oppAcc" />
<apex:commandButton action="{!save}" value=" Save " />
</apex:pageBlock>

<apex:pageBlock mode="detail">
<apex:outputfield value="{!opportunity.Name}" label="{!$ObjectType.Opportunity.fields.Name.label}"/>
<apex:outputfield value="{!opportunity.CloseDate}" label="{!$ObjectType.Opportunity.fields.CloseDate.label}" />
<apex:outputfield value="{!opportunity.StageName}" label="{!$ObjectType.Opportunity.fields.StageName.label}" />
<apex:inputfield value="{!opportunity.Account}" label="{!$ObjectType.Opportunity.fields.Account.label}" />
<apex:commandButton action="{!edit}" value=" Edit " rerender="oppPage"/>
</apex:pageBlock>