• Siva@51
  • NEWBIE
  • 65 Points
  • Member since 2015

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 25
    Replies
Hi salesforce family,

followig functionality need to be achieved in below code.Please help me.

current functionality
----------------------------
1.)currently if we uncheck the check boxes of opportunitis and contacts and click submitt button all the contacts and opportunities records related to accounts are getting disappear.

required functionality
-----------------------------
1.)On uncheck the check boxs of opportunities and contacts with out clicking submitt button all the contacts and opportunities records related to accounts need to disappear.

2.)If we select the check boxs of opportunities and contacts with out clicking submitt button all the contacts and opportunities records related to accounts need to dispaly.

please try to achieve required functionality and also provide code coverage.

I here by providing code
=================
Apex class
---------------

public class Acc_con_Opp_Details
{
    
    //list of collection of the wrapper class object
    public list<accountwrapper> actwrap           {set;get;}
    //list of collection of Account,contact and opportunity objects
    public list<Account>        accounts          {set;get;}
    public list<Account>        acts              {set;get;}
    public list<opportunity>    opts              {set;get;}
    public list<opportunity>    sopts             {set;get;}
    public list<contact>        cnts              {set;get;} 
    public list<contact>        snts              {set;get;}
    public boolean oppbox                         {set;get;}//used as check box for opportunity 
    public boolean conbox                         {set;get;}//used as check box for contact
    public boolean flag1                          {set;get;}//used in account page block  
    public boolean flag2                          {set;get;}//used in contact page block 
    public boolean flag3                          {set;get;}//used in opportunity page block
    //this variables are used for pagination purpose
    private integer totalRecs = 0;//stores no.of total records   
    private integer index = 0;//used for tracking offset
    private integer blockSize =5;//for setting size of page
   
    //in this constructor we are setting values to boolean values
    public Acc_con_Opp_Details()
    {
    flag1=true;
    flag2=false;
    flag3=false;
        totalRecs = [select count() from Account];//returns total no.of account records 
       getactwrap();//calling getactwrap method.
    }
    //this method displays first five records
    public void beginning()
    {
        oppbox=false;
        conbox=false;
        index = 0;
        getactwrap();
    }
    //this method displays prevoius records
     public void previous()
    {
        oppbox=false;
        conbox=false;
        index = index-blockSize;
        getactwrap();
    }
    //this method displays next records
   public void next()
    {
        oppbox=false;
        conbox=false;
        index = index+blockSize;
        getactwrap();
    }
    //this method displays last remaining records
 public void end()
    {
        oppbox=false;
        conbox=false;
        index = totalrecs - math.mod(totalRecs,blockSize);
        getactwrap();
    }  
    //this variable is used to enable or disable first and previous buttons
 public boolean prev{get
    {
        if(index == 0)
        return true;
        else
        return false;
    }  set;}
    //this variable is used to enable or disable next and last buttons
 public boolean nxt{get
    {
        if((index + blockSize) > totalRecs)
        return true;
        else
        return false;
    }   set;}
    //used to display opportunities and contacts w.r.t selected accounts
    public void  submit()
    {
        flag1=false;
        acts=new list<Account>();
        for(accountwrapper aw:actwrap)
           {
            if(aw.acflag){
                acts.add(aw.acc);
           }
    }
        
        //if we select contact check box,then it displays contacts for selected accounts 
      if(conbox)
      {
      
              snts=[select id,lastName,Department,account.name from contact where accountid IN:acts];
              if(snts.size()>0)
              {
              flag3=true;
              }
              else
              {
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'contact records are not found for selected Accounts.'));
              }
         } 
        //if we select opportunity check box,then it displays opportunities for selected accounts
      if(oppbox)
        {
        
            
      opts=[select id,name,stageName,leadsource,account.name from opportunity where accountId IN:acts];
      if(opts.size() >0)
      {
      flag2=true;
      }
      else
       {
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'opportunity records are not found for selected Accounts.'));
       }
            } 
    }
   //it hides contacts and dispalys opportunitites on uncheck of contact check box
    public void Hideandshowopp()
    {
     
    if(oppbox==true)
    {
     flag2=true;
    }
    else
    {
     flag2=false;
    }
         
    }
   //  it hides opportunities and dispalys contacts on uncheck of opportunities check box 
     public void HideandshowCon()
    {
    if(conbox==true)
    {
     flag3=true;
    }
    else
    {
     flag3=false;
    }
         
    }
    
    //This method uses a simple SOQL query to return a List of Accounts
     public void getactwrap(){
         accounts = Database.Query('SELECT id,Name,phone FROM Account LIMIT :blockSize OFFSET :index');
         actwrap=new list<accountwrapper>();
       // As each Account is processed we create a new accountwrapper object and add it to the wrapper class(accountwrapper) list.
         for(account a:accounts)
        {
            actwrap.add(new accountwrapper(a));
        }
    }
    // this method  uses dml operation to edit the existing opportunities values or to insert new oppt values
    public void saveopps()
    {
        list<opportunity> opps=new list<opportunity>();
        opps.addAll(opts);
        upsert opps;
    }
    //his method  uses dml operation to edit the existing contact values or to insert new contact values
    public void savecons()
    {
       cnts = new list<contact>();
        cnts.addall(snts);
        upsert cnts;
    }
 //This is wrapper class which is collection of other class instances
  //here  wrapper class contains both the standard salesforce object Account and a Boolean value acflag   
 public class accountwrapper{
        public account acc{set;get;}
        public boolean acflag{set;get;}
             //In this contructor When we create a new accountwrapper object we pass a Account that is set to the acc property.
             // We also set the boolean value to false
        public accountwrapper(account a){
            acc=a;
            acflag=false;
        }
        
    }

}

vf page
----------
<apex:page controller="Acc_con_Opp_Details" showHeader="false" docType="html-5.0">
<apex:form >

    <!--This block dispalying account record details-->
    <apex:pageblock rendered="true">
    <apex:pageMessages ></apex:pageMessages>
    <apex:pageblocktable value="{!actwrap}" var="a">
        <apex:column >
    <apex:facet name="header" >Select</apex:facet>
             <apex:inputCheckbox value="{!a.acflag}"/>
        </apex:column>
        <!-- displays id,name and phone number for accounts-->
        <apex:column value="{!a.acc.id}"/>
        <apex:column value="{!a.acc.name}"/>
        <apex:column value="{!a.acc.phone}"/>
         </apex:pageblocktable>
        <!-- this buttons are used to paginate account records-->
        <apex:pageblockButtons >
            <!--displays first five records-->
            <apex:commandButton value="first"  action="{!beginning}" disabled="{!prev}"/>
            <!--displays previous records-->
            <apex:commandButton value="previous"  action="{!previous}" disabled="{!prev}"/>
             <!--displays previous  next records-->
            <apex:commandButton value="next"  action="{!next}" disabled="{!nxt}"/>
            <!-- displays last records-->
            <apex:commandButton value="last"  action="{!end}" disabled="{!nxt}"/>                                    
        </apex:pageblockButtons>
         <!-- check boxs for opportunities and contacts-->
        
     <center>  <apex:inputCheckbox value="{!oppbox}">
     <apex:actionSupport event="onchange" action="{!Hideandshowopp}"  rerender="block"/>
     </apex:inputCheckbox>Opportunities&nbsp;&nbsp;&nbsp;
         <apex:inputCheckbox value="{!conbox}">
         <apex:actionSupport event="onchange" action="{!HideandshowCon}" rerender="block"/>
         </apex:inputCheckbox>Contacts&nbsp;&nbsp;&nbsp;
        <apex:commandButton value="submit" action="{!submit}"/>
       </center>
    </apex:pageblock>
    <!--this block displays opportunity details-->
    <apex:pageblock rendered="{!flag2}" id="block" >
      
   <apex:pageblocktable value="{!opts}" var="o">
        
        <apex:column >
             <apex:facet name="header">Opportunity Id</apex:facet>
            <apex:commandlink value="{!o.id}" Action="{!URLFOR($Action.opportunity.edit,o.Id)}"/>
        </apex:column>
        <apex:column value="{!o.account.name}" />
        <apex:column >
            <apex:facet name="header">Opportunity Name</apex:facet>
       <apex:inputtext value="{!o.name}" />
            </apex:column>
        <apex:column >
           <apex:facet name="header">Opportunity Stage</apex:facet> 
       <apex:inputtext value="{!o.stagename}"/>
        </apex:column>
       <apex:column >
         <apex:facet name="header">Opportunity Leadsource</apex:facet> 
        </apex:column>
        </apex:pageblocktable>
        <apex:commandButton value="Save Opportunities" action="{!saveopps}"/>
    </apex:pageblock>
    <!--this block is used for displaying contact details -->
     <apex:pageblock rendered="{!flag3}">
         
     <apex:pageblocktable value="{!snts}" var="c">
        <apex:column >
            <apex:facet name="header">Contact Id</apex:facet>
            <apex:commandlink value="{!c}" Action="{!URLFOR($Action.contact.edit,c)}"/>
        </apex:column>
         <apex:column value="{!c.account.name}"/>
        <apex:column >
             <apex:facet name="header">Contact Lastname</apex:facet>
            <apex:inputtext value="{!c.lastname}"/>
        </apex:column>
        <apex:column >
        <apex:facet name="header">Contact Department</apex:facet>
            <apex:inputtext value="{!c.Department}"/>
        </apex:column>
        </apex:pageblocktable>
         <apex:commandButton value="Save Contacts" action="{!savecons}"/>
    </apex:pageblock>
   
    </apex:form>
</apex:page>
==============================================================================
 
I am stuck trying to get the Group query to get the territory name, could someone let me know what I am doing wrong here, I get this error message
'Initial term of field expression must be a concrete SObject: List<AccountShare>'

VF:
 
<apex:page controller="DisplayQueryList"> 
    <apex:pageBlock title="My Content"> 
        <apex:pageBlockTable value="{!Recs}" var="Record"> 
            <apex:column > 
                <apex:facet name="header">User</apex:facet> 
                  <apex:outputText value="{!Record.Id}"/> 
                    </apex:column>
<apex:column > 
                <apex:facet name="header">UserID or Group</apex:facet> 
                  <apex:outputText value="{!Record.UserOrGroupId}"/> 
                    </apex:column>

          
            
          
          
                        
        </apex:pageBlockTable> 
    </apex:pageBlock> 
</apex:page>



Apex:
 
public with sharing class TestDisplayQueryList{ 
public List<AccountShare> Recs {get; set;} 
public DisplayQueryList(){ 

Rec = [Select Id, UserOrGroupId from AccountShare where (RowCause ='Territory' OR RowCause = 'TerritoryManual' )And AccountId='001i0000009Rmz5' ];    
Group grp =[select id from Group where id IN :Records.id ];
   


} 
}

 
Hi all,

We have standard salesforce Activate button on Contract.  It worked fine until we deploy our new changes. We never touched the page of that contract or the code that deals with those pages but still it is giving us an error when we clicked on Activate button.

Error says:
Fix these errors before activating.
The page you submitted was invalid for your session. Please click Save again to confirm your change.


Any help is greatly appreciated!!!

Thanks
<apex:actionRegion >
            <apex:inputField value="{!Standard_Controller__c.Text_InputField__c}" style="width:40px">
                <apex:actionSupport event="onchange" reRender="fields"/>
            </apex:inputField>
 </apex:actionRegion>


Thanks in advance.
  • September 15, 2015
  • Like
  • 0
Hi,
When I am editing a record, a field is updating itself coz of workflow. I have also a visual force page used on that record, but it is not updating itself when I hit save. Again I have to refresh my page for that VF page to update (VF page has command buttons that are rendereing fields). So, How Can my record completely refreshes itself upon a field update?

Thanks,
 
  • September 03, 2015
  • Like
  • 0
<apex:outputpanel id="abc">
    <apex:pageBlockSection rendered="{!ObjectName.Field_Name__c=='xyz'}">
         <apex:inputField required = "true" value="{!ObjectName.Choose__c}">
             <apex:support immediate = "true" event="onchange" reRender="c1,c2"/>
         </apex:inputField>
    <apex:inputField id="c1" value="{!ObjectName.Text_Area1__c}" required="{!ObjectName.Choose=='Yes'}"/>
    <apex:inputField id="c2" value="{!ObjectName.Text_Area2__c}" required="{!ObjectName.Choose=='Yes'}"/>
    </apex:pageBlockSection>
</apex:outputpanel>

 

Date.Today().MONTH()+'_'+Date.Today().Day()

From the above how can i get the first 3 letters of a month from the current date Date.Today().MONTH() (example: this should be as Nov, as this is Nov 3, 2016)

From the above how can i get the first 2 letters of the day from the current date Date.Today().Day() (example: This should be as 03, as today is Nov 3, 2016).

Can anyone provide their inputs to the code, which would be really helpful.


 

Hi,
I created a piece of schedulable Apex code but encountered the "scheduled apex class getting Too many DML rows: 10001 error" as one of the queries exceeded the row limit.  I am relatively new to Force and was aware of the governere limits but this has caught me out but after a bit of reading understand why. 

I think my solution is to adapt my code to use the batch interface and then create a new schedulable piece of code to then call this. My problem is re-cutting my code into a batchable form - would anyone be able to suggest how I can re-structure this?

The original code is:
 
Global class RefreshScheduleMirror  implements Schedulable {

      global void execute(SchedulableContext SC) {

      RefreshSchedule();
   }

    public void RefreshSchedule()  {
    
    /// Delete the old mirror records ///

	ScheduleMirror__c[] doomedMirrors = [SELECT Name FROM ScheduleMirror__c]; 
		try {
    	delete doomedMirrors;
	} catch (DmlException e) {
    // Process exception here
	}
    /// Create the current schedulve list and query and query to populate it
    OpportunityLineItemSchedule[] allSchedules = [ SELECT CurrencyIsoCode, OpportunityLineItemId, ScheduleDate, Revenue,  Quantity, Type, Description FROM OpportunityLineItemSchedule];
     
    /// Create list for the product instance records and query to populate it

    OpportunityLineItem[] AlllineItems = [ SELECT ID, Name, OpportunityId, Product2Id, ProductCode  FROM OpportunityLineItem];
        
     // Create new list to store the records ( based on the structure defined by the custom object Schedule Mirror )
        List<ScheduleMirror__c> newmirrors = new List<ScheduleMirror__c>();
        
        /// Loop around each line item schedule record - create variable 'myschedule' for each iteration through array 'allSchedules'
        for (OpportunityLineItemSchedule myschedule : allSchedules) {
             // inner loop around the Opportunity Product 
            for (OpportunityLineItem mylineitem : AlllineItems)  {
                 // 
                if (mylineitem.ID == myschedule.OpportunityLineItemId)  {
                    // create variable 'mymirror' to hold the record values 
                    ScheduleMirror__c mymirror = new ScheduleMirror__c(); 
                    
                    mymirror.CurrencyIsoCode = myschedule.CurrencyIsoCode;
                    mymirror.Name = myschedule.ScheduleDate.year() + '-' + myschedule.ScheduleDate.month() + '-' + mylineitem.Name;
                    mymirror.LineItemID__c = myschedule.OpportunityLineItemId;
                    mymirror.Opportunity__c = mylineitem.OpportunityId;
                    mymirror.Schedule_Amount__c = myschedule.Revenue;
                    mymirror.Schedule_Date__c = myschedule.ScheduleDate;
                    mymirror.Schedule_Description__c = myschedule.Description;
  					mymirror.Schedule_Quantity__c = myschedule.Quantity;
                    mymirror.Schedule_Type__c = myschedule.Type;
                    mymirror.ProductID__c = mylineitem.Product2Id;
                    mymirror.Product_Code__c = mylineitem.ProductCode;
                    
            		// Update the list with all the records retrieved in the for loop
            		newmirrors.add(mymirror);
                
                // update database     
                upsert newmirrors;   
                }
            }
        }
    }
}
What I have so far....
1 - I split the clear out of the custom object into a separate batch;
Global class PurgeOldMirrorsBatch implements Database.Batchable<sObject> 
{

  global Database.QueryLocator start(Database.BatchableContext BC)
      
       {       
            String query ='SELECT Name FROM ScheduleMirror__c';
	        return Database.getQueryLocator(query);
	   } 
    
    global void execute(Database.BatchableContext BC, List<ScheduleMirror__c> scope){
	    delete scope; 
       }
        
    global void finish(Database.BatchableContext BC){
       }
}

2 - I then 'tried' to create a batchable piece of Apex code to do the main processing but cannot get my head around how I transfer my query results into my list and then update my custom object.
 
Global class RefreshScheduleMirrorBatch implements Database.Batchable<sObject> 
{

  global Database.QueryLocator start(Database.BatchableContext BC)
      
      /// Grab the data upfront 
  	 {       
            String query ='SELECT CurrencyIsoCode, OpportunityLineItemId, ScheduleDate, Revenue,  Quantity, Type, Description, OpportunityLineItem.ID, OpportunityLineItem.Name, OpportunityLineItem.OpportunityId, OpportunityLineItem.Product2Id, OpportunityLineItem.ProductCode  FROM OpportunityLineItemSchedule';
	        return Database.getQueryLocator(query);
	   } 
    
      global void execute(Database.BatchableContext BC, List<sObject> scope) {
         
        // Create new list to store the records ( based on the structure defined by the custom object Schedule Mirror )
        List<ScheduleMirror__c> newmirrors = new List<ScheduleMirror__c>();
         
         // This is the section I am having issues getting my head around - how to build up the records to populate my list from my query results.  
        for( ScheduleMirror__c myschedule : scope)  
        {
                if (myschedule.ID == myschedule.OpportunityLineItemId)  {
                    // create variable 'mymirror' to hold the record values 
                    ScheduleMirror__c mymirror = new ScheduleMirror__c(); 
                    
                    mymirror.CurrencyIsoCode = myschedule.CurrencyIsoCode;
                    mymirror.Name = myschedule.ScheduleDate.year() + '-' + myschedule.ScheduleDate.month() + '-' + myschedule.Name;
                    mymirror.LineItemID__c = myschedule.OpportunityLineItemId;
                    mymirror.Opportunity__c = myschedule.OpportunityId;
                    mymirror.Schedule_Amount__c = myschedule.Revenue;
                    mymirror.Schedule_Date__c = myschedule.ScheduleDate;
                    mymirror.Schedule_Description__c = myschedule.Description;
  					mymirror.Schedule_Quantity__c = myschedule.Quantity;
                    mymirror.Schedule_Type__c = myschedule.Type;
                    mymirror.ProductID__c = myschedule.Product2Id;
                    mymirror.Product_Code__c = myschedule.ProductCode;
                    
            		// Update the list with all the records retrieved in the for loop
            		newmirrors.add(mymirror);
                
                // update database     
                upsert newmirrors;   
                }
            }
        }
}

3 - The idea was then to call both of these from the scheduble code i.e
 
Global class RefreshScheduleMirrorExec  implements Schedulable 
{
      global void execute(SchedulableContext SC) 
      {
          PurgeOldMirrorsBatch  Purge = new PurgeOldMirrorsBatch();
          
          database.executeBatch(Purge);
          
          RefreshScheduleMirrorBatch MirrorBatch = new RefreshScheduleMirrorBatch();
          
          database.executeBatch(MirrorBatch);

      }
}

Am I way off the mark in my approach? Any help would be appreciated.

Thanks
Dave
  • October 12, 2016
  • Like
  • 0
Hi,
below is my apex class:
public class CampaignMember_List {
    
    private Id CampaignId{get; set;}
    private final ApexPages.StandardController sc;   
    public CampaignMember_List (ApexPages.StandardController stdController) {    
        this.CampaignId = stdController.getId();
        this.sc = stdController;
    }

    public List<CampaignMember> cms {get;set;}
    
    public String sortField {get; set;}
    public String previousSortField {get; set;}
    
    public List<CampaignMember> getMembers() {
        if(cms == null){
            cms = [SELECT Id, Contact.OptedOutOfShire__c, Phone, Mapping_City_State__c,  Lead.OptedOutOfShire__c  ,ContactId, LeadId, FirstName, LastName, Type__c, 
                   Status, Is_Guest__c, Contact.MailingCity, Contact.MailingState, Contact.Phone, Lead.Phone, Lead.City, Lead.State FROM CampaignMember 
                   WHERE Campaign.Id =: CampaignId];
        }

        return cms;
    }


    public void doSort(){
        String order = 'asc';
        
        /*This checks to see if the same header was click two times in a row, if so 
it switches the order.*/
        if(previousSortField == sortField){
            order = 'desc';
            previousSortField = null;
        }else{
            previousSortField = sortField;
        }
        
        //To sort the table we need to use this one line
        superSort.sortList(cms,sortField,order);
    }
}
this is the test class:
@istest
    static void testsortmethod()
    {                             
        
        Campaign program = new Campaign(Name='Test');
        insert program;
        
        Lead l1 = new Lead(Firstname='First', LastName='Last',company='nav');
        insert l1;
        
        Lead l2 = new Lead(Firstname='First', LastName='Last',company='van');
        insert l2;
        
        CampaignMember cm1 = new CampaignMember(CampaignId=program.Id, LeadId=l1.Id);
        insert cm1;
        CampaignMember cm2 = new CampaignMember(CampaignId=program.Id, LeadId=l2.Id);
        insert cm2;
        
        List <CampaignMember> members = [SELECT Id, ContactId, LeadId, FirstName, LastName, Type__c, 
                                         Status, Lead.Phone, Lead.City, Lead.State FROM CampaignMember 
                                         WHERE Campaign.Id =: program.Id ] ; 
       
        CampaignMember cm = new CampaignMember();
        ApexPages.StandardController sc = new ApexPages.StandardController(cm);
        CampaignMember_List ms = new CampaignMember_List(sc);
        ms.getMembers();
        system.assert(members.size() > 0);
        
    	  if(members.size() > 0){
            string order = 'asc';
            ms.sortField='FirstName';
        
              ms.doSort();
            superSort.sortList(members,'FirstName','asc');
            
      } 
    }
I am getting 89% coverage but the test class is failing at ms.dosort();
Any ideas??
Thanks for your time

 
I am having a hard time getting the test class to fire part of the code.  I think the problem is with the owner of the custom object Territory__c, but can't figure out how to resolve it.  Any help will be greatly appreciated...

Here is the class:
public class TestScoreReviewClass {
/***************
 * When a new ACT or SAT test score is created, if
 * the student application decision is Decision Pending
 * or Postponed, create a task for the recruiter to
 * review the test scores
 ****************/
    Public static void sendTestScoreTask(Test_Score__c[] test_score){
        // Select the Contact.Id that ties to the Test_Score__c
        
        Set<string> contactId = new Set<string>();
        Set<ID> recID = new Set<ID>();
        
        for (Test_Score__c tz : test_score){
            if(tz.Contact__c != NULL) {
                contactid.add(tz.Contact__c);
            }
        }
        // Select the latest application tied to the new test score  
        Map<ID,Application__c> ApplInfo = new Map<ID,Application__c>([select Id, Student__c, Counselor_Id__c
                                  from application__c 
                                 where Student__r.Domestic_Or_International__c = 'Domestic' 
                                   and Application_Decision__c in ('Decision Pending','Postponed') 
                                   and Student__c in :contactid
                                 order by Entry_Term__c desc, Application_Date__c desc
                                  limit 1]);
      
   Date dt = Date.today();

   List<Task> followupTasks = new List<Task>();
// Generate a list of tasks to be generated

   Map<ID, List<Task> > tsks = New Map<ID, List<Task> >();
   
        
   List<Task> tsksadd = New List<Task>();
        
   For (Application__c c : ApplInfo.Values() )
   {
      //system.debug(c.Counselor_Id__c);
      recID.add(c.Counselor_Id__c);
       
      if (c.Student__c != null && c.Counselor_Id__c != null) 
      {
      
         List<Task> taskss = tsks.Get(c.Student__c);
         If (taskss == null)
         {

            Task tasks = new Task(
            WhoId = c.Student__c,
            OwnerId = c.Counselor_Id__c,
            Priority = 'Normal',
            Type = 'Email',
            ActivityDate = (dt.addDays(1)),
            Status = 'Not Started',
            Subject = 'Review New Test Score (ACT or SAT)');
      
            followupTasks.add(tasks);

          }
      }
   }

// insert the entire list
   if (followupTasks.size() > 0) {
      //system.debug(followupTasks.size());
      insert followupTasks;
   }
    }
}

Here is the test class:
@isTest
private class TestScoreReviewTest {

    static testMethod void myUnitTest() {        
    // Test Task
      test.startTest();
        
      Profile p = [SELECT Id FROM Profile WHERE Name='SNC Counselor Plus'];
      User u1 = new User(Alias = 'standa', Email='saplingstandarduser@testorg.com',
      EmailEncodingKey='ISO-8859-1', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Mexico_City', UserName='saplingstandarduser@testorg.com');
       
        System.runAs(u1){
                
    // Create Territory
        Territory__c tr1 = new Territory__c(
                                Code__c = 'TestTerr',
                                County__c = 'Brown',
                                State__c = 'WI',
                                OwnerId = u1.Id);
        insert tr1;
        
    // Create Student
        Contact c1 = new Contact(
                    FirstName = 'Test',
                    LastName = 'TestStudent',
                    Domestic_Or_International__c = 'Domestic',
                    Territory__c = [Select t.Id from Territory__c t where t.Code__c = 'TestTerr' limit 1].Id);
            
        insert c1;    
        
    // Create Application
        Application__c a1 = new Application__c(
            Student__c = [Select c.Id from Contact c where c.LastName = 'TestStudent' limit 1].Id,
            Student_Type__c = 'First Time UG',
            Full_or_Part_Time__c = 'Full-Time',
            Active_Application__c = true,
            Application_Date__c = Date.today(),
            Application_Status__c = 'Decision Pending');
             
      insert a1;
        
    // Create Test_Score
        Test_Score__c t1 = new Test_Score__c(
            Contact__c = [Select c.Id from Contact c where c.LastName = 'TestStudent' limit 1].Id,
            Test_Date__c = '09/01/2016',
            Test_Type__c = 'School',
            ACT_Composite__c = 30,
            ACT_English__c = 16,
            ACT_Math__c = 16,
            ACT_Reading__c = 16,
            ACT_Science__c = 16
        );
        
        insert t1;
      
        test.stopTest();
        }
    }
}

Thank you for your time.

Darlene Blaney
St Norbert College
(920)403-3953
Hi salesforce family,

followig functionality need to be achieved in below code.Please help me.

current functionality
----------------------------
1.)currently if we uncheck the check boxes of opportunitis and contacts and click submitt button all the contacts and opportunities records related to accounts are getting disappear.

required functionality
-----------------------------
1.)On uncheck the check boxs of opportunities and contacts with out clicking submitt button all the contacts and opportunities records related to accounts need to disappear.

2.)If we select the check boxs of opportunities and contacts with out clicking submitt button all the contacts and opportunities records related to accounts need to dispaly.

please try to achieve required functionality and also provide code coverage.

I here by providing code
=================
Apex class
---------------

public class Acc_con_Opp_Details
{
    
    //list of collection of the wrapper class object
    public list<accountwrapper> actwrap           {set;get;}
    //list of collection of Account,contact and opportunity objects
    public list<Account>        accounts          {set;get;}
    public list<Account>        acts              {set;get;}
    public list<opportunity>    opts              {set;get;}
    public list<opportunity>    sopts             {set;get;}
    public list<contact>        cnts              {set;get;} 
    public list<contact>        snts              {set;get;}
    public boolean oppbox                         {set;get;}//used as check box for opportunity 
    public boolean conbox                         {set;get;}//used as check box for contact
    public boolean flag1                          {set;get;}//used in account page block  
    public boolean flag2                          {set;get;}//used in contact page block 
    public boolean flag3                          {set;get;}//used in opportunity page block
    //this variables are used for pagination purpose
    private integer totalRecs = 0;//stores no.of total records   
    private integer index = 0;//used for tracking offset
    private integer blockSize =5;//for setting size of page
   
    //in this constructor we are setting values to boolean values
    public Acc_con_Opp_Details()
    {
    flag1=true;
    flag2=false;
    flag3=false;
        totalRecs = [select count() from Account];//returns total no.of account records 
       getactwrap();//calling getactwrap method.
    }
    //this method displays first five records
    public void beginning()
    {
        oppbox=false;
        conbox=false;
        index = 0;
        getactwrap();
    }
    //this method displays prevoius records
     public void previous()
    {
        oppbox=false;
        conbox=false;
        index = index-blockSize;
        getactwrap();
    }
    //this method displays next records
   public void next()
    {
        oppbox=false;
        conbox=false;
        index = index+blockSize;
        getactwrap();
    }
    //this method displays last remaining records
 public void end()
    {
        oppbox=false;
        conbox=false;
        index = totalrecs - math.mod(totalRecs,blockSize);
        getactwrap();
    }  
    //this variable is used to enable or disable first and previous buttons
 public boolean prev{get
    {
        if(index == 0)
        return true;
        else
        return false;
    }  set;}
    //this variable is used to enable or disable next and last buttons
 public boolean nxt{get
    {
        if((index + blockSize) > totalRecs)
        return true;
        else
        return false;
    }   set;}
    //used to display opportunities and contacts w.r.t selected accounts
    public void  submit()
    {
        flag1=false;
        acts=new list<Account>();
        for(accountwrapper aw:actwrap)
           {
            if(aw.acflag){
                acts.add(aw.acc);
           }
    }
        
        //if we select contact check box,then it displays contacts for selected accounts 
      if(conbox)
      {
      
              snts=[select id,lastName,Department,account.name from contact where accountid IN:acts];
              if(snts.size()>0)
              {
              flag3=true;
              }
              else
              {
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'contact records are not found for selected Accounts.'));
              }
         } 
        //if we select opportunity check box,then it displays opportunities for selected accounts
      if(oppbox)
        {
        
            
      opts=[select id,name,stageName,leadsource,account.name from opportunity where accountId IN:acts];
      if(opts.size() >0)
      {
      flag2=true;
      }
      else
       {
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'opportunity records are not found for selected Accounts.'));
       }
            } 
    }
   //it hides contacts and dispalys opportunitites on uncheck of contact check box
    public void Hideandshowopp()
    {
     
    if(oppbox==true)
    {
     flag2=true;
    }
    else
    {
     flag2=false;
    }
         
    }
   //  it hides opportunities and dispalys contacts on uncheck of opportunities check box 
     public void HideandshowCon()
    {
    if(conbox==true)
    {
     flag3=true;
    }
    else
    {
     flag3=false;
    }
         
    }
    
    //This method uses a simple SOQL query to return a List of Accounts
     public void getactwrap(){
         accounts = Database.Query('SELECT id,Name,phone FROM Account LIMIT :blockSize OFFSET :index');
         actwrap=new list<accountwrapper>();
       // As each Account is processed we create a new accountwrapper object and add it to the wrapper class(accountwrapper) list.
         for(account a:accounts)
        {
            actwrap.add(new accountwrapper(a));
        }
    }
    // this method  uses dml operation to edit the existing opportunities values or to insert new oppt values
    public void saveopps()
    {
        list<opportunity> opps=new list<opportunity>();
        opps.addAll(opts);
        upsert opps;
    }
    //his method  uses dml operation to edit the existing contact values or to insert new contact values
    public void savecons()
    {
       cnts = new list<contact>();
        cnts.addall(snts);
        upsert cnts;
    }
 //This is wrapper class which is collection of other class instances
  //here  wrapper class contains both the standard salesforce object Account and a Boolean value acflag   
 public class accountwrapper{
        public account acc{set;get;}
        public boolean acflag{set;get;}
             //In this contructor When we create a new accountwrapper object we pass a Account that is set to the acc property.
             // We also set the boolean value to false
        public accountwrapper(account a){
            acc=a;
            acflag=false;
        }
        
    }

}

vf page
----------
<apex:page controller="Acc_con_Opp_Details" showHeader="false" docType="html-5.0">
<apex:form >

    <!--This block dispalying account record details-->
    <apex:pageblock rendered="true">
    <apex:pageMessages ></apex:pageMessages>
    <apex:pageblocktable value="{!actwrap}" var="a">
        <apex:column >
    <apex:facet name="header" >Select</apex:facet>
             <apex:inputCheckbox value="{!a.acflag}"/>
        </apex:column>
        <!-- displays id,name and phone number for accounts-->
        <apex:column value="{!a.acc.id}"/>
        <apex:column value="{!a.acc.name}"/>
        <apex:column value="{!a.acc.phone}"/>
         </apex:pageblocktable>
        <!-- this buttons are used to paginate account records-->
        <apex:pageblockButtons >
            <!--displays first five records-->
            <apex:commandButton value="first"  action="{!beginning}" disabled="{!prev}"/>
            <!--displays previous records-->
            <apex:commandButton value="previous"  action="{!previous}" disabled="{!prev}"/>
             <!--displays previous  next records-->
            <apex:commandButton value="next"  action="{!next}" disabled="{!nxt}"/>
            <!-- displays last records-->
            <apex:commandButton value="last"  action="{!end}" disabled="{!nxt}"/>                                    
        </apex:pageblockButtons>
         <!-- check boxs for opportunities and contacts-->
        
     <center>  <apex:inputCheckbox value="{!oppbox}">
     <apex:actionSupport event="onchange" action="{!Hideandshowopp}"  rerender="block"/>
     </apex:inputCheckbox>Opportunities&nbsp;&nbsp;&nbsp;
         <apex:inputCheckbox value="{!conbox}">
         <apex:actionSupport event="onchange" action="{!HideandshowCon}" rerender="block"/>
         </apex:inputCheckbox>Contacts&nbsp;&nbsp;&nbsp;
        <apex:commandButton value="submit" action="{!submit}"/>
       </center>
    </apex:pageblock>
    <!--this block displays opportunity details-->
    <apex:pageblock rendered="{!flag2}" id="block" >
      
   <apex:pageblocktable value="{!opts}" var="o">
        
        <apex:column >
             <apex:facet name="header">Opportunity Id</apex:facet>
            <apex:commandlink value="{!o.id}" Action="{!URLFOR($Action.opportunity.edit,o.Id)}"/>
        </apex:column>
        <apex:column value="{!o.account.name}" />
        <apex:column >
            <apex:facet name="header">Opportunity Name</apex:facet>
       <apex:inputtext value="{!o.name}" />
            </apex:column>
        <apex:column >
           <apex:facet name="header">Opportunity Stage</apex:facet> 
       <apex:inputtext value="{!o.stagename}"/>
        </apex:column>
       <apex:column >
         <apex:facet name="header">Opportunity Leadsource</apex:facet> 
        </apex:column>
        </apex:pageblocktable>
        <apex:commandButton value="Save Opportunities" action="{!saveopps}"/>
    </apex:pageblock>
    <!--this block is used for displaying contact details -->
     <apex:pageblock rendered="{!flag3}">
         
     <apex:pageblocktable value="{!snts}" var="c">
        <apex:column >
            <apex:facet name="header">Contact Id</apex:facet>
            <apex:commandlink value="{!c}" Action="{!URLFOR($Action.contact.edit,c)}"/>
        </apex:column>
         <apex:column value="{!c.account.name}"/>
        <apex:column >
             <apex:facet name="header">Contact Lastname</apex:facet>
            <apex:inputtext value="{!c.lastname}"/>
        </apex:column>
        <apex:column >
        <apex:facet name="header">Contact Department</apex:facet>
            <apex:inputtext value="{!c.Department}"/>
        </apex:column>
        </apex:pageblocktable>
         <apex:commandButton value="Save Contacts" action="{!savecons}"/>
    </apex:pageblock>
   
    </apex:form>
</apex:page>
==============================================================================