3

My visualforce page contains a modal with a new contact form. When saved, the new record is correctly added to the contact list on the page. However, if you reopen the modal, the input fields still contain the values from the recently-saved record. How can I reset the form after each save to allow multiple uses?

I tried rerendering the form, but then realized this doesn't affect the controller. I know this can be achieved through a page refresh (via redirect), but am hoping there might be a better solution. Any ideas?

Markup:

<apex:form>

    <apex:inputField id="newContactName" value="{!newContact.Name}"/>
    <apex:inputField id="newContactAddress" value="{!newContact.Address}"/>

    <button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
    <apex:commandButton value="Save" action="{!saveContact}"/>

</apex:form>

Apex:

public class custom_extension {
    public Customer__c customer;
    public Contact__c newContact {get; set;}

    public custom_extension(ApexPages.StandardController controller) {
        this.customer = (Customer__c)controller.getRecord();
        newContact = new Contact__c();
    }

    public PageReference saveContact() {
        newContact.Customer_Vendor__c = ApexPages.currentPage().getParameters().get('id');
        insert newContact;
        return null;
    }    
 }
4

Made some small changes to your code.

  1. Added an id to the <apex:form>.
  2. Changed <apex:commandButton> to rerender the form.
  3. Modified saveContact() such that it re-instantiates the contact after saving.

Visualforce

<apex:form id="theForm">

    <apex:inputField id="newContactName" value="{!newContact.Name}"/>
    <apex:inputField id="newContactAddress" value="{!newContact.Address}"/>

    <button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
    <apex:commandButton value="Save" action="{!saveContact}" rerender="theForm" />

</apex:form>

Apex

public class custom_extension {
    //other stuff...

    public PageReference saveContact() {
        newContact.Customer_Vendor__c = ApexPages.currentPage().getParameters().get('id');
        insert newContact;
        newContact = new Contact();
        return null;
    }    
}
  • Beautiful. Reinstantiating the object did it. I'm not sure if rerendering is needed since the fields get their values from the controller. – geeljire Apr 17 '13 at 22:50
1

You can add this to your button oncomplete="formReset()"

and then with JavaScript

<script>
function formReset()
{
document.getElementById("yourformid").reset();
}
</script>

Since I guess you are using jQuery to create the modal, you could call this on 'oncomplete'

$('yourformclass').reset();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.