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
Angela SchloederAngela Schloeder 

How to save just the edited fields and not the whole page?

Hi All,

Just so I'm clear, I am not a developer. I can kind of read it and make small changes, but trying to learn to write it gives me a headache.

I have a vf page that was created for me, but when a Save is done it is saving all fields instead of just the fields that were edited. This is causing issues of data being deleted because the change was made in a record and not on the vf page. I hope that made sense. 

Here is the page and controller. I do hope that someone can help with a small change to this code and a whole new page doesn't have to be created.
I cannot paste all code with the limit of 32,000 characters.

<apex:page controller="MyOpenTasksController">
    <apex:includeScript value="{!$Resource.JS_Busy_Indicator}"/>
    <script>
        function showFilterData(){
            filterData();
        }
        function setUser(){
            setUser();
        }
        var xval;
        function block_viewport() {
            xval=getBusyOverlay('viewport',{color:'black', opacity:0.35, text:'processing...', style:'text-shadow: 0 0 3px black;font-weight:bold;font-size:12px;color:white'},{color:'#fff', size:75, type:'o'});
        }
    </script>
    <apex:form id="frm">
    
    <apex:actionFunction name="filterData" action="{!filterTaskData}" reRender="frm,pgBlock" oncomplete="xval.remove();"/>
    <apex:actionFunction name="setUser" action="{!setCurrentUser}" reRender="frm,pgBlock" oncomplete="xval.remove();"/>
    
    <apex:pageBlock title="My Open Tasks" id="pgBlock">
    
    
        <apex:pageBlockButtons >
            <apex:commandButton onclick="block_viewport();" oncomplete="xval.remove();" value="Update To Tomorrow" action="{!updateToTomorrow}" reRender="frm,pgBlock" disabled="{!Not(taskList.size > 0)}"/>
            <apex:commandButton onclick="block_viewport();" oncomplete="xval.remove();" value="Save" action="{!saveChanges}" reRender="frm,pgBlock" disabled="{!Not(taskList.size > 0)}"/>            
            <apex:commandButton onclick="block_viewport();" oncomplete="xval.remove();" value="Cancel" action="{!cancelChanges}" reRender="frm,pgBlock" disabled="{!Not(taskList.size > 0)}"/>
        </apex:pageBlockButtons>
        <br/>
        <apex:outputPanel >
            
            
Controller:
public with sharing class MyOpenTasksController {

    public String eventObject { get; set; }
    public Integer recordsSize {get;set;}
    public Integer totalNumberOfPages { get; set; }
    public Integer pageNumber {get;set;}
    public Boolean hasNext {get;set;}
    public Boolean hasPrevious {get;set;}
    
    public List<SelectOption> contactAttendeeList{get;set;}
    public List<SelectOption> mailingStateList{get;set;}
    public List<SelectOption> activeUsersList{get;set;}
    public Id selectedUserId {get;set;}
    public boolean showUserPicklist {get;set;}
    public String selectedAttendee{get;set;}
    public String selectedState{get;set;}
    public string selectedPriority {get;set;}
    public string selectedTimezone {get;set;}
    
    public List<Task> taskList {get;set;}
    
    private List<Id> taskListWithAllRecords;
    private Integer noOfRecordsPerPage = 50;
    
    public MyOpenTasksController(){
        activeUsersList = new List<SelectOption>();
        
        showUserPicklist = false;
        for(User_Information__c usrInfo : User_Information__c.getAll().values()){
            if(usrInfo.User_Id__c == String.valueOf(UserInfo.getUserId()).substring(0,15)){
                showUserPicklist = true;
            }
        }
        selectedUserId = UserInfo.getUserId();
        activeUsersList.add(new SelectOption(UserInfo.getUserId(),'Current User'));
        for(User usr : [Select Id, Name from User where IsActive = true]){
            if(usr.id != UserInfo.getUserId()){
                activeUsersList.add(new SelectOption(usr.Id,usr.Name));
            }
        }
        populateSelectOptions();
        populateTaskData();
    }
    
    private void populateTaskData(){
        recordsSize = 0;
        totalNumberOfPages = 0;
        pageNumber = 0;
        hasNext = false;
        hasPrevious = false;
        
        //taskList = new List<Task>();
        taskListWithAllRecords = new List<Id>();
        // String Query to have a list of cases for a respective End-user.
        //String soql = 'Select ActivityDate, Status, Priority, Atendee__c, Dummy_Contact__c, WhatId,Dummy_Contact__r.Name,What.Name, Description, Dummy_Contact__r.Title, Dummy_Contact__r.Key_Exec__c, Dummy_Contact__r.Exec_Type__c, Dummy_Contact__r.Direct_Dial__c, Dummy_Contact__r.MobilePhone, Dummy_Contact__r.Phone, Dummy_Contact__r.MailingState, Dummy_Contact__r.Timezone__c, Dummy_Contact__r.Task_Attendee__c from Task where IsClosed = false AND OwnerID =:selectedUserId';
        
        String soql = 'Select id from Task where IsClosed = false AND OwnerID =:selectedUserId';
        if(selectedPriority == null && selectedTimezone == null  && selectedAttendee == null  && selectedState == null){
            
        }
        else if (selectedPriority != null && selectedTimezone == null  && selectedAttendee == null  && selectedState == null){
            soql = soql + ' AND Priority = :selectedPriority '; 
        }
        else if(selectedPriority == null && selectedTimezone != null  && selectedAttendee == null  && selectedState == null){
            soql = soql + ' AND Dummy_Contact__r.Timezone__c = :selectedTimezone '; 
        }
        else if(selectedPriority == null && selectedTimezone == null  && selectedAttendee != null  && selectedState == null){
            soql = soql + ' AND Attendee__c = :selectedAttendee '; 
        }
        else if(selectedPriority == null && selectedTimezone == null  && selectedAttendee == null  && selectedState != null){
            soql = soql + ' AND Dummy_Contact__r.MailingState = :selectedState '; 
        }
        else if(selectedPriority != null && selectedTimezone != null  && selectedAttendee == null  && selectedState == null){
            soql = soql + ' AND Priority = :selectedPriority AND Dummy_Contact__r.Timezone__c = :selectedTimezone '; 
        }
        else if(selectedPriority == null && selectedTimezone != null  && selectedAttendee != null  && selectedState == null){
            soql = soql + ' AND Dummy_Contact__r.Timezone__c = :selectedTimezone AND Attendee__c = :selectedAttendee '; 
        }
        else if(selectedPriority != null && selectedTimezone == null  && selectedAttendee != null  && selectedState == null){
            soql = soql + ' AND Priority = :selectedPriority AND Attendee__c = :selectedAttendee ';
        }
        else if(selectedPriority != null && selectedTimezone == null  && selectedAttendee == null  && selectedState != null){
            soql = soql + ' AND Priority = :selectedPriority AND Dummy_Contact__r.MailingState = :selectedState ';
        }
        else if(selectedPriority == null && selectedTimezone != null  && selectedAttendee == null  && selectedState != null){
            soql = soql + ' AND Dummy_Contact__r.Timezone__c = :selectedTimezone AND Dummy_Contact__r.MailingState = :selectedState ';
        }
        else if(selectedPriority == null && selectedTimezone == null  && selectedAttendee != null  && selectedState != null){
            soql = soql + ' AND Attendee__c = :selectedAttendee AND Dummy_Contact__r.MailingState = :selectedState ';
        }
        else if(selectedPriority != null && selectedTimezone != null  && selectedAttendee != null  && selectedState == null){
            soql = soql + ' AND Priority = :selectedPriority AND Dummy_Contact__r.Timezone__c = :selectedTimezone AND Attendee__c = :selectedAttendee ';
        }
        else if(selectedPriority != null && selectedTimezone != null  && selectedAttendee == null  && selectedState != null){
            soql = soql + ' AND Priority = :selectedPriority AND Dummy_Contact__r.Timezone__c = :selectedTimezone AND Dummy_Contact__r.MailingState = :selectedState ';
        }
        else if(selectedPriority != null && selectedTimezone == null  && selectedAttendee != null  && selectedState != null){
            soql = soql + ' AND Priority = :selectedPriority AND Attendee__c = :selectedAttendee AND Dummy_Contact__r.MailingState = :selectedState ';
        }
        else if(selectedPriority == null && selectedTimezone != null  && selectedAttendee != null  && selectedState != null){
            soql = soql + ' AND Dummy_Contact__r.Timezone__c = :selectedTimezone AND Attendee__c = :selectedAttendee AND Dummy_Contact__r.MailingState = :selectedState ';
        }
        else{
            soql = soql + ' AND Priority = :selectedPriority AND Dummy_Contact__r.Timezone__c = :selectedTimezone AND Attendee__c = :selectedAttendee AND Dummy_Contact__r.MailingState = :selectedState ';
        }
        
        // Passing the String array to a list with Selected field sorting.
        for(Task tsk : Database.query(soql + ' order by ' + sortExpression + ' ' + sortDirection  + ' NULLS LAST')){
            taskListWithAllRecords.add(tsk.id);
        }
        
        recordsSize = taskListWithAllRecords.size();
        if(Math.mod(recordsSize,noOfRecordsPerPage) != 0){
            totalNumberOfPages = (recordsSize / noOfRecordsPerPage) + 1;
        }
        else{
            totalNumberOfPages = recordsSize / noOfRecordsPerPage;
        }
        Set<Id> taskIds = new Set<Id>();
        if(recordsSize > noOfRecordsPerPage){
            for(Integer i=pageNumber*noOfRecordsPerPage ; i<noOfRecordsPerPage ; i++){
                taskIds.add(taskListWithAllRecords[i]);
            }
            hasNext = true;
        }
        else{
            taskIds.addAll(taskListWithAllRecords);
        }
        pageNumber++;
        
        String soqlQuery = 'Select ActivityDate, Status, Priority, Attendee__c, Dummy_Contact__c, WhatId,Dummy_Contact__r.Name,What.Name, Description, Dummy_Contact__r.Title, Dummy_Contact__r.Key_Exec__c, Dummy_Contact__r.Exec_Type__c, Dummy_Contact__r.Direct_Dial__c, Dummy_Contact__r.MobilePhone, Dummy_Contact__r.Phone, Dummy_Contact__r.MailingState, Dummy_Contact__r.Timezone__c, Dummy_Contact__r.Attendee_Contact__c, Dummy_Contact__r.Task_Attendee__c from Task where Id In :taskIds order by ' + sortExpression + ' ' + sortDirection  + ' NULLS LAST';
        taskList = new List<Task>();
        taskList = Database.query(soqlQuery);
    }
    
    private void populateSelectOptions(){
        contactAttendeeList = new List<SelectOption>();
        contactAttendeeList.add(new SelectOption('','---None---'));
        
        mailingStateList = new List<SelectOption>();
        mailingStateList.add(new SelectOption('','---None---'));
        Set<String> setOfAttendee = new Set<String>();
        Set<String> setOfStates = new Set<String>();
        for(Task tsk : [Select Attendee__c,Dummy_Contact__r.Task_Attendee__c, Dummy_Contact__r.MailingState from Task where IsClosed = false AND OwnerID =:selectedUserId]){
            if(tsk.Attendee__c != null){
                setOfAttendee.add(tsk.Attendee__c);
            }
            if(tsk.Dummy_Contact__r.MailingState != null){
                setOfStates.add(tsk.Dummy_Contact__r.MailingState);
            }
        }
        if(setOfAttendee.size() > 0){
            List<String> sortedListOfAttendee = new List<String>();
            sortedListOfAttendee.addAll(setOfAttendee);
            sortedListOfAttendee.sort();
            for(String attendee : sortedListOfAttendee){
                contactAttendeeList.add(new SelectOption(attendee,attendee));
            }
        }
        if(setOfStates.size() > 0){
            List<String> sortedListOfStates = new List<String>();
            sortedListOfStates.addAll(setOfStates);
            sortedListOfStates.sort();
            for(String state : sortedListOfStates){
                mailingStateList.add(new SelectOption(state, state ));
            }
        }
    }
    
    // returns the previous page of records
    public void previous() {
        hasNext = true;
        //taskList = new List<Task>();
        Set<Id> taskIds = new Set<Id>();
        pageNumber--;
        for(Integer i= (pageNumber-1)*noOfRecordsPerPage; i<noOfRecordsPerPage*pageNumber ; i++){
            taskIds.add(taskListWithAllRecords[i]);
        }
        if(pageNumber > 1){
            hasPrevious = true;
        }
        else{
            hasPrevious = false;
        }
        
        String soqlQuery = 'Select ActivityDate, Status, Priority, Attendee__c, Dummy_Contact__c, WhatId,Dummy_Contact__r.Name,What.Name, Description, Dummy_Contact__r.Title, Dummy_Contact__r.Key_Exec__c, Dummy_Contact__r.Exec_Type__c, Dummy_Contact__r.Direct_Dial__c, Dummy_Contact__r.MobilePhone, Dummy_Contact__r.Phone, Dummy_Contact__r.MailingState, Dummy_Contact__r.Timezone__c, Dummy_Contact__r.Attendee_Contact__c, Dummy_Contact__r.Task_Attendee__c from Task where Id In :taskIds order by ' + sortExpression + ' ' + sortDirection  + ' NULLS LAST';
        taskList = new List<Task>();
        taskList = Database.query(soqlQuery);
    }

    // returns the next page of records
    public void next() {
        hasPrevious = true;
        //taskList = new List<Task>();
        Set<Id> taskIds = new Set<Id>();
        if((pageNumber+1)*noOfRecordsPerPage < taskListWithAllRecords.size()){
            for(Integer i = pageNumber*noOfRecordsPerPage ; i<(pageNumber+1)*noOfRecordsPerPage ;i++){
                taskIds.add(taskListWithAllRecords[i]);
            }
        }
        else{
            for(Integer i=pageNumber*noOfRecordsPerPage ; i<recordsSize ;i++){
                taskIds.add(taskListWithAllRecords[i]);
            }
            hasNext = false;
        }
        pageNumber++;
        
        String soqlQuery = 'Select ActivityDate, Status, Priority, Attendee__c, Dummy_Contact__c, WhatId,Dummy_Contact__r.Name,What.Name, Description, Dummy_Contact__r.Title, Dummy_Contact__r.Key_Exec__c, Dummy_Contact__r.Exec_Type__c, Dummy_Contact__r.Direct_Dial__c, Dummy_Contact__r.MobilePhone, Dummy_Contact__r.Phone, Dummy_Contact__r.MailingState, Dummy_Contact__r.Timezone__c, Dummy_Contact__r.Attendee_Contact__c, Dummy_Contact__r.Task_Attendee__c from Task where Id In :taskIds order by ' + sortExpression + ' ' + sortDirection  + ' NULLS LAST';
        taskList = new List<Task>();
        taskList = Database.query(soqlQuery);
    }
    
    public void sortData() {
        // simply toggle the direction
        sortDirection = sortDirection.equals('asc') ? 'desc' : 'asc';

        populateTaskData();
    }
    
    // the current sort direction. defaults to asc
    public String sortDirection {
        // To set a Direction either in ascending order or descending order.
        get  { if (sortDirection == null) {  sortDirection = 'asc'; } return sortDirection;}
        set;
    }

    // the current field to sort by. defaults to last name
    public String sortExpression {
        // To set a Field for sorting.
        get  { if (sortExpression == null) {sortExpression = 'ActivityDate'; } return sortExpression;  }
        set;
    } 
    
    public PageReference filterTaskData() {
        populateTaskData();
        return null;
    }
    
    public PageReference updateToTomorrow() {
        DateTime dateToBeChanged = system.Today().addDays(1);
        
        Datetime dt = DateTime.newInstance(System.today(), Time.newInstance(0, 0, 0, 0));
        String dayOfWeek=dt.format('EEEE');
        
        if(dayOfWeek == 'Friday'){
            dateToBeChanged = system.Today().addDays(3);
        }
        else if(dayOfWeek == 'Saturday'){
            dateToBeChanged = system.Today().addDays(2);
        }
        List<Task> listOfTaskToUpdate = new List<Task>();
        for(Task tsk : [Select ActivityDate from Task where IsClosed = false AND OwnerID =:selectedUserId]){
            if(tsk.ActivityDate <= system.today()){
                tsk.ActivityDate = Date.valueOf(dateToBeChanged);
                listOfTaskToUpdate.add(tsk);
            }
        }
        
        if(listOfTaskToUpdate.size() > 0){
            update listOfTaskToUpdate;
        }
        return null;
    }
    
    public PageReference cancelChanges() {
        return null;
    }
    
    public PageReference saveChanges() {
        Set<Id> conIds = new Set<Id>();
        Set<Contact> setOfContacts = new Set<Contact>();
        List<Contact> listOfContactToUpdate = new List<Contact>();
        
        for(Task tsk : taskList){
            if(tsk.Dummy_Contact__c != null){
                conIds.add(tsk.Dummy_Contact__c);
            }
        }
        for(Contact con : [Select Name,Title, Key_Exec__c, Exec_Type__c, Direct_Dial__c, MobilePhone, Phone, MailingState, Timezone__c, Attendee_Contact__c, Task_Attendee__c from Contact where id in :conIds]){
            for(Task tsk : taskList){
                if(tsk.Dummy_Contact__c == con.id){
                    con.Title = tsk.Dummy_Contact__r.Title;
                    con.Key_Exec__c = tsk.Dummy_Contact__r.Key_Exec__c;
                    con.Exec_Type__c = tsk.Dummy_Contact__r.Exec_Type__c;
                    con.Direct_Dial__c = tsk.Dummy_Contact__r.Direct_Dial__c;
                    con.MobilePhone = tsk.Dummy_Contact__r.MobilePhone;
                    con.Phone = tsk.Dummy_Contact__r.Phone;
                    con.MailingState = tsk.Dummy_Contact__r.MailingState;
                    con.Timezone__c = tsk.Dummy_Contact__r.Timezone__c;
                    setOfContacts.add(con);
                }
            }
        }
        if(setOfContacts.size() > 0){
            listOfContactToUpdate.addAll(setOfContacts);
            update listOfContactToUpdate;
        }
        
        if(taskList.size() > 0){
            update taskList;
        }
        return null;
    }
    public PageReference setCurrentUser() {
        populateSelectOptions();
        populateTaskData();
        return null;
    }
}
David Zhu 8David Zhu 8
You can focus on "Savechanges" function. Specifically in this block by removing some of the lines.
ie. if you don'w want phone number changed. remove/comment line:
on.Phone = tsk.Dummy_Contact__r.Phone;

Hope this helps.
for(Task tsk : taskList){
                if(tsk.Dummy_Contact__c == con.id){
                    con.Title = tsk.Dummy_Contact__r.Title;
                    con.Key_Exec__c = tsk.Dummy_Contact__r.Key_Exec__c;
                    con.Exec_Type__c = tsk.Dummy_Contact__r.Exec_Type__c;
                    con.Direct_Dial__c = tsk.Dummy_Contact__r.Direct_Dial__c;
                    con.MobilePhone = tsk.Dummy_Contact__r.MobilePhone;
                    con.Phone = tsk.Dummy_Contact__r.Phone;
                    con.MailingState = tsk.Dummy_Contact__r.MailingState;
                    con.Timezone__c = tsk.Dummy_Contact__r.Timezone__c;
                    setOfContacts.add(con);
            }

 
Angela SchloederAngela Schloeder
Yeah, they need to sometimes make changes to any of these fields in the page.

Isn't it possible to just save only the fields that were edited?
surya kanadhipatlasurya kanadhipatla
Angela Schloeder,
You can do this by comparing old field values with new field values using trigger.oldmap

Please see the below link:

http://salesforce.stackexchange.com/questions/11191/just-update-when-a-specific-field-changes

 
surya kanadhipatlasurya kanadhipatla
Angela Schloeder,
I just realized its not a trigger, its a VF page :)
surya kanadhipatlasurya kanadhipatla
Please see below:

01                for(Task tsk : taskList){
02                if(tsk.Dummy_Contact__c == con.id){
                      if(  con.Title != tsk.Dummy_Contact__r.Title)
03                    con.Title = tsk.Dummy_Contact__r.Title;
                         if(  con.Key_Exec__c != tsk.Dummy_Contact__r.Key_Exec__c)
04                    con.Key_Exec__c = tsk.Dummy_Contact__r.Key_Exec__c;
                           if(  con.Exec_Type__c != tsk.Dummy_Contact__r.Exec_Type__c)                     
05                    con.Exec_Type__c = tsk.Dummy_Contact__r.Exec_Type__c;
                           if(    con.Direct_Dial__c != tsk.Dummy_Contact__r.Direct_Dial__c)
06                    con.Direct_Dial__c = tsk.Dummy_Contact__r.Direct_Dial__c;
                      if( con.MobilePhone != tsk.Dummy_Contact__r.MobilePhone)
07                    con.MobilePhone = tsk.Dummy_Contact__r.MobilePhone;
                          if(  con.Phone != tsk.Dummy_Contact__r.Phone)
08                    con.Phone = tsk.Dummy_Contact__r.Phone;
                            if( con.MailingState != tsk.Dummy_Contact__r.MailingState)
09                    con.MailingState = tsk.Dummy_Contact__r.MailingState;
                              if( con.Timezone__c != tsk.Dummy_Contact__r.Timezone__c)
10                    con.Timezone__c = tsk.Dummy_Contact__r.Timezone__c;
11                    setOfContacts.add(con);
12            }
 
Angela SchloederAngela Schloeder
Thank you Surya, but that didn't change anything.
If I update a field on a contact in a separate tab and then go back to the vf page and save anything without first refreshing the page and the field I updated in the contact is blank on the vf page it deletes the field value I had updated in the contact.
Angela SchloederAngela Schloeder

Wondering if anyone can help me with this. A friend gave me this, but I'm not sure how do do this.

You'll just add it as an extension on the page: apex:page standardController="blah" extensions="UpdateChangedFieldsController
And just call the savechanges method to save the changes.

 UpdateChangedFieldsController.cls

public class UpdateChangedFieldsController {
 SObject oldRecord, currentRecord;
 public class UpdateChangedFieldsController(ApexPages.StandardController controller) {
  oldRecord = controller.getRecord().clone();
  currentRecord = controller.getRecord();
 }
 public PageReference saveChanges() {
  SObject newClone = record.getSObjectType().newSObject(record.Id);
  Map<String, Object> 
   oldValues = oldRecord.getPopulatedFieldsAsMap(),
   newValues = currentRecord.getPopulatedFieldsAsMap();
  for(String key: newValues) {
   if(newValues.get(key) != oldValues.get(key)) {
    newClone.put(key, newValues.get(key));
   }
  }
  try {
   upsert newClone;
   return new ApexPages.StandardController(newClone).view();
  } catch(Exception e) {
   return null;
  }
 }
}