+ Start a Discussion
aKallNVaKallNV 

Problems with saving records coming from a wrapper class in a map

I have been struggling with this VF page for a while now. Here is the scenario. 

I have a custom object(I will refer to it as 'swpl') that I have set up a many-to-many relationship with on a few other objects...2 custom objects, contacts and cases to be exact. So what my VF page does is allows you to enter data for a new swpl record and then use a Multi-tab vf page to click of the various records that you want to relate the record to. So you can picture 4 tabs one for each of the custom objects and one for contacts and the fourth for cases. For each one of these tabs I have written wrapper classes so that the records can be clicked by the user and then saved as a junction record. So all seems to be ok except for one of my custom objects. I know it has something to do with the fact that I tried to make things more complicated with the particular tab. In this case the custom object is the child of another record. Therefore I tried to set up the list on the vfPage so that each child object is grouped by a it's parent record...rather than repeating the Parent record name for each Child Object.

 

Somehow the maps that I use to genarate this is causing some strange save behavior that I have not been able to find a pattern for.  So i am posting the code hoping that some brilliant person can spot what i am doing wrong. the problem is that not all of the records that are checked are saved, and what is even more strange is that it will save records that were not checked.

 

I have added some underlined text to the code to help get you in the right spot. I you're interested, and have left out the bits of code that arent' pertinent.

 

public without sharing class narrativeWizard_Controller {        
        
        public SchoolWorkPlanLog__c swpn { get; set; }
        public String accountId;
        public String theUserUnit;//strings for setting up Dynamic SOQL
        public String theUserDept;//string for setting up Dynamic SOQL
        public List<UniversalJoin__c> juncObs { get; set; }
        public List<cAIS> theWrappers { get; set; } 
        public Map<ID,List<cAIS>> theWrapperMap { get; set; }
        public List<DeployedStrategy__c> theDSs { get; set; }
        public Map<Id,DeployedStrategy__c> theVFDSs { get; set; }
        public List<Goal__c> theGoals { get; set; }
        public List<cGS> theGoalWrappers { get; set; }        
        public Set<String> unitOptions = new Set<String>();
        public String selectedUnit { get; set; }
        public List<cCONS> theConWrappers { get; set; }
        public Set<String> caseRTOptions = new Set<String>(); //for case record type options
        public String selectedCaseRT { get; set; }
        public List<Case> theCases { get; set; }
        public List<cCASES> theCaseWrappers { get; set; }
        public User theUser { get; set; }
        public Set<String> goalUnitOptions = new Set<String>();
        public String selectedGoalUnit { get; set; }
        public boolean showAll { get; set; } //controls wether or not only priority Action Items or all Action items are shown.  
        public datetime fromDate;
        
        
        
                
        //CONSTRUCTOR
        public narrativeWizard_Controller(ApexPages.StandardController swpnController) {
            this.swpn = (SchoolWorkPlanLog__c)swpnController.getRecord();
            this.swpn.Account__c = ApexPages.currentPage().getParameters().get('aID');
            this.accountId = ApexPages.currentPage().getParameters().get('aID');
            this.setUptheUser();
            this.selectedUnit = setUptheUser().Unit__c;
            this.showAll = false; 
            this.fromDate = datetime.newInstance(2011,5,1);//for Case Query Criteria
            this.makesStrategyWrappers();
            this.makesGoalWrappers();
            this.makesContactWrappers();
            this.makesCaseWrappers();
            this.getStratyUnits();
            //this.makeCaseRTOptions();
            this.getAllGoals(); 
        }
        
              
        //pulls the user who initiated the log so that lists can be filtered to the Unit they belong to. I need to make this return a User object so that I can reference more fields.
        public User setUpTheUser() {
                ID UP = Userinfo.getUserId();
                User userX = [select ID, Name, Email, Department__c, Unit__c from User where ID =:UP];
                this.theUserUnit = userX.Unit__c;
                this.theUserDept = userX.Department__c;                 
                return userX;
        }
       
        
        public void getStratyUnits() {
                
            theUser = setUptheUser();                
                
            for (DeployedStrategy__c ds : [select ID, Name, Principle__c, Category__c, Unit__c from DeployedStrategy__c where Account__c = :this.swpn.Account__c And Status__c = 'Active']) {
                unitOptions.add(ds.Unit__c);
            }
              
        }
        
       public String getStrategyQuery() {
            
            String losFilters = '';
            
           
            if(this.selectedUnit != 'All' && (this.selectedUnit != 'Charter' && this.selectedUnit != 'Cross Unit: Coach' && this.selectedUnit != 'Not Applicable')) {
                losFilters += ' AND Unit__c =:selectedUnit';
            } else if(this.selectedUnit == 'Charter' ){
                losFilters += ' AND Department__c =:theUserDept';               
            }else if((this.selectedUnit == 'Not Applicable' && this.theUserDept != 'Not Applicable') || this.selectedUnit == 'Cross Unit: Coach') {
                losFilters += ' AND Department__c = :theUserDept';
            }else if(this.selectedUnit == 'Not Applicable' && this.theUserDept == 'Not Applicable') {
                losFilters += '';
            } else if(this.selectedUnit == 'All') {             
                losFilters += '';
            } else {
                losFilters += '';
            }
            
            return 'select ID, Name, Status__c, Principle__c, Strategy__r.FullName__c, Strategy__r.Name,Strategy__r.Category__r.Name, Strategy__r.Category__r.Principle__r.Name, EndDate__c, Unit__c, StartDate__c, (select ID, Name, Name__c, Status__c, Stage__c, ActionItemName__r.ActionItemFullName__c, SequenceNumber__c, ItemNumber__c, DeployedStrategy__r.Strategy__r.Name, EndDate__c, LatestRating__c from DeployedActionItem__r where Stage__c != \'Not Needed\'  Order By ItemNumber__c ASC) from DeployedStrategy__c where Account__c = :accountId And Status__c != \'Inactive\''+losFilters+' ORDER BY Unit__c, StartDate__c ASC';
        }
        
        //attempt at Dynamic Query
        public void makesStrategyWrappers() {
                
            theDSs = new List<DeployedStrategy__c>();
            theVFDSs = new Map<Id,DeployedStrategy__c>();
            List<cAIS> cAIS1 = new List<cAIS>();  
            theWrappers = new List<cAIS>();
            theWrapperMap = new Map<Id, List<cAIS>>();
            
            String queryString = this.getStrategyQuery();
            theDSs = Database.query(queryString);
                        
            if(theDSs.size() > 0) {
                    for(DeployedStrategy__c ds : theDSs) {
                        
                        if(ds.DeployedActionItem__r.size() > 0) {
                                for(DeployedActionItems__c actI : ds.DeployedActionItem__r) {
                                        if((actI.Status__c == 'Priority' || actI.Status__c == 'Overdue Priority') && actI.Stage__c != 'Completed' && !this.showAll) {                                           
                                           
                                            theVFDSs.put(ds.id,ds); This is the map that I use to create the Parent Headings in the VF page  
                                            
                                            cAIS1 = theWrapperMap.get(ds.Id); This is the Map that makes up the child records in the VFpageif(null == cAIS1) {       
                                                    cAIS1 = new List<cAIS>();
                                                    theWrappers.add(new cAIS(actI)); 
                                                    theWrapperMap.put(ds.Id, cAIS1);                              
                                            }
                                            cAIS1.add(new cAIS(actI));
                                        }
                                        if(this.showAll){
                                            theVFDSs.put(ds.id,ds);
                                            cAIS1 = theWrapperMap.get(ds.Id);
                                    
                                            if(null == cAIS1) {       
                                                    cAIS1 = new List<cAIS>();
                                                    theWrappers.add(new cAIS(actI)); 
                                                    theWrapperMap.put(ds.Id, cAIS1);                              
                                            }
                                            cAIS1.add(new cAIS(actI));
                                        }
                                }
                        }
                    }
                }            
        }
        
       public List<DeployedStrategy__c> getKeys() {
        
        return theVFDSs.values();
       }      
       
         
        
        
        //Method called by Save Button
        public PageReference processSelected() {  
            
            //insert new Log                     
            SchoolWorkPlanLog__c newLog = this.swpn;
                insert newLog;
            
            
            //insert new Junction Records    
            List<UniversalJoin__c> newJuncObjs1 = new List<UniversalJoin__c>();
            List<DeployedActionItems__c> selectedAIs = new List<DeployedActionItems__c>();
            List<Contact> selectedCons = new List<Contact>();
            LIst<Case> selectedCases = new List<Case>();
            List<Goal__c> selectedGs = new List<Goal__c>();
            
            //List<ActionItemRating__c> newRatings = new List<ActionItemRating__c>();
                           
            for(DeployedStrategy__c ds : this.theVFDSs.values()) {
                for(cAIS ai : this.theWrapperMap.get(ds.ID)) {
                    //system.assert(false,'Your Results '+this.theWrapperMap.get(ds.ID));
                    if(ai.selected == true) {This is where the problmes start. It's putting the wrong values in the selectedAIs list.
                             selectedAIs.add(ai.wAI);
                    }
                }  
            }            
         
            if(selectedAIs.size() > 0) {
                
                for(DeployedActionItems__c ds2 : selectedAIs) {
                    UniversalJoin__c newJuncOb = new UniversalJoin__c(
                    SchoolWorkPlanLog__c = newLog.Id,
                    ActionItem__c = ds2.Id,
                    RecordTypeId = '012Q0000000CwfBIAS');
                    
                    newJuncObjs1.add(newJuncOb);
                }
<apex:page sidebar="false" showHeader="true" standardController="SchoolWorkPlanLog__c" extensions="narrativeWizard_Controller" id="tt1">
    <apex:form >
      <apex:pageBlock id="pb1" mode="edit">  
      <apex:pageBlockSection title="{!swpn.Account__r.Name}" columns="1">
              <apex:inputField value="{!swpn.Subject__c}"/>
              <apex:inputField value="{!swpn.InteractionDate__c}"/>
              <apex:inputField value="{!swpn.HoursSpent__c}"    />
               <apex:inputField value="{!swpn.CategoryofWork__c}"  />
              <!--<apex:inputField value="{!getLog.PreEngagementPlan__c}"/>--> 
              <apex:inputField value="{!swpn.Narrative__c}" style="width:90%"/>  
      </apex:pageBlockSection>
      <!--<apex:pageBlockSection columns="1" collapsible="true" title="Next Steps">
          <b><apex:outputLabel value="Use the following fields to define your next step. Upon saving this record a new Log will be created with the Date and Plan that you specify here."/></b>
          <apex:inputField value="{!getLog.NextStepDate__c}"/>
          <apex:inputField value="{!getLog.NextStepPlan__c}"/>
      </apex:pageBlockSection>-->
      <!--<apex:pageBlockSection columns="1" id="pbs1" title="Off-Plan?">
          <apex:outputPanel >
              <b><apex:outputLabel value="Check the box to indicate that none of the options below are appropriate:"/></b>
              <apex:actionRegion >
                  <apex:inputField value="{!getLog.OffPlan__c}">
                      <apex:actionSupport event="onclick" reRender="catField, pb2"/>
                  </apex:inputField>
              </apex:actionRegion>
          </apex:outputPanel>
      </apex:pageBlockSection>
      <apex:outputPanel id="catField">
      <apex:pageBlockSection rendered="{!showAIandGoal = false}" columns="1">
          <b><apex:outputText value="Find a category that best classifies this narrative:"/></b>
          <apex:inputField value="{!swpn.Category__c}"/>
      </apex:pageBlockSection>    
      </apex:outputPanel> -->     
      </apex:pageBlock> 
      <apex:pageBlock id="pb2">
          <apex:pageBlockButtons >
              <apex:commandButton action="{!processSelected}" value="Save"  />
              <apex:commandButton action="{!cancelButton}" value="Cancel" />
          </apex:pageBlockButtons>    
      <apex:pageBlockSection title="Select the Work Plans, Goals, Cases and Contacts that this Entry pertains to." collapsible="false"  columns="1">
          <apex:tabPanel switchType="client" selectedTab="tab1" >
              <apex:tab label="Work Plans" id="tab1">
              <apex:pageBlockSection columns="1" id="pbs1" title="Off-Plan?">
                  <apex:outputPanel >
                  <b><apex:outputLabel value="Check the box to indicate that none of the options below are appropriate:"/></b>
                      <apex:actionRegion >
                      <apex:inputField value="{!swpn.OffPlan__c}">
                      <apex:actionSupport event="onclick" reRender="catField, workplans"/>
                      </apex:inputField>
                  </apex:actionRegion>
                  </apex:outputPanel>
              </apex:pageBlockSection>
              <apex:outputPanel id="catField">
              <apex:pageBlockSection rendered="{!showAIandGoal = false}" columns="1">
                  <b><apex:outputText value="Find a category that best classifies this narrative:"/></b>
                  <apex:inputField value="{!swpn.Category__c}"/>
              </apex:pageBlockSection>    
              </apex:outputPanel>      
              <apex:outputPanel id="workplans">
              <apex:pageBlockSection collapsible="false" columns="3" rendered="{!showAIandGoal}" id="filters" title="">
              <apex:pageBlockSectionItem >
                  <apex:outputLabel value="Check to Show All. Uncheck to Show Only Priorities"/>
                  <apex:actionRegion >                
                      <apex:inputCheckbox value="{!showAll}"/>
                      <apex:actionSupport event="onclick" action="{!makesStrategyWrappers}" reRender="table1"/>
                  </apex:actionRegion>                
              </apex:pageBlockSectionItem>                       
              <apex:pageBlockSectionItem >
               <apex:outputLabel value="Filter by Unit"/>
                   <apex:selectList value="{!selectedUnit}" size="1" id="uniList">
                      <apex:selectOptions value="{!Units}"/>
                      <apex:actionSupport event="onchange" reRender="princyList"  status="UnitStatus" />                      
                   </apex:selectList>                   
              </apex:pageBlockSectionItem>
              <apex:pageBlockSectionItem >
                  <apex:commandButton action="{!makesStrategyWrappers}" reRender="table1" value="Filter">
                      <apex:actionSupport event="onchange" status="buttonStatus"/>
                      <apex:actionStatus id="buttonStatus" startText="Diving for Records..."/>
                  </apex:commandButton>
              </apex:pageBlockSectionItem>       
             
              </apex:pageBlockSection>
                  <apex:pageBlockSection collapsible="false" columns="1"  id="table1" rendered="{!showAIandGoal}">
                      <apex:pageBlockSectionItem >
                          <apex:outputPanel layout="block" style="overflow:auto;width:1180px;height:400px" >
                          <apex:pageBlockTable value="{!Keys}" var="d" cellspacing="15px"> calls getKeys Method
                              <apex:column headerValue="Strategy">
                                  <b>{!d.Strategy__r.FullName__c }</b>
                              </apex:column>
                              <apex:column headerValue="Unit">
                                  <b>{!d.Unit__c}</b>
                              </apex:column>
                              <apex:column headerValue="Principle">
                                  <b>{!d.Principle__c}</b>
                              </apex:column>
                              <apex:column headerValue="Status">
                                  <b>{!d.Status__c}</b>
                              </apex:column>
                              <apex:column headerValue="Start Date" width="125">
                                  <b><apex:outputText value="{0,date,MM-dd-yyyy}">
                                      <apex:param value="{!d.StartDate__c}"/>
                                  </apex:outputText></b>                  
                              </apex:column>
                              <apex:column breakBefore="true" colspan="5" >
   child records                <apex:dataTable value="{!theWrapperMap[d.id]}" var="a" width="100%" border="5px" cellspacing="10px">
                                      <apex:column >
                                          <apex:inputCheckbox value="{!a.selected}"/>
                                      </apex:column>
                                      <apex:column headerValue="Action Items">
                                          {!a.wAI.ActionItemName__r.ActionItemFullName__c}
                                      </apex:column>
                                      <apex:column headerValue="Item Number">
                                          {!a.wAI.ItemNumber__c}
                                      </apex:column>
                                      <apex:column headerValue="Status">
                                          {!a.wAI.Status__c}
                                      </apex:column>
                                      <!--<apex:column headerValue="Current Rating" width="110">
                                          {!a.wAI.LatestRating__c}
                                      </apex:column>
                                      
                          </apex:pageBlockTable>
                          </apex:outputPanel>
                      </apex:pageBlockSectionItem>
                  </apex:pageBlockSection>
                  </apex:outputPanel>
                  </apex:tab>....