• subodh chaturvedi 17
  • NEWBIE
  • 85 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 24
    Questions
  • 21
    Replies
Below class updating the contact field (Account_status_BG__c)from the account field (Membership_Defined__c).
It is only covering 60 %. it is not going under if condition.
public class AccountStatusUpdate {
    
    public static void acntStatusMethod(List<Account> ac,Map<Id,Account> oldAccountMap){
        set<Id> accIds = new set<Id>();
        for(Account acc: ac){
            accIds.add(acc.Id);
        }
        
        if(accIds.size() > 0){
            List<Contact> contactList = [SELECT Id,Account_Status__c, AccountId, Account.Membership_Defined__c FROM Contact WHERE AccountId IN : accIds];
            //Create a list to update the contacts    
            List<Contact> contactToBeUpdate = new List<Contact>();
            for(Contact objCont : contactList){ 
                if(oldAccountMap!= null && String.isNotBlank(objCont.Account.Membership_Defined__c) && objCont.Account.Membership_Defined__c != oldAccountMap.get(objCont.AccountId).Membership_Defined__c){
                    Contact newContact = new Contact();
                    newContact.Id = objCont.Id;
                    newContact.Account_Status_BG__c = objCont.Account.Membership_Defined__c;
                    contactToBeUpdate.add(newContact);
                }
            }
            if(contactToBeUpdate.size() > 0){
                UPDATE contactToBeUpdate;
            }
        }
        
    }
    
}
Hi below is my class but i don't know how to write the  test class of it in Rest api integration. can any one help me in this
public class StatusPageUtility implements Queueable, Database.AllowsCallouts {
    
    public Map<String,String> statusPageUserWithEmailId {get;set;}
    public String email{get;set;}
    public String actionType{get;set;}    
    public String oldContactEmail{get;set;}    
    public StatusPageUtility(String operationType, String conEmail, String oldConEmail){
        this.actionType = operationType;
        this.email = conEmail;
        this.oldContactEmail = oldConEmail;
    }
    
    public void execute(QueueableContext context) {
        getStatusPageUsers(actionType,email,oldContactEmail);
    }
    
    //method to get all the page access users.
    //actionType - add, remove, update, validate
    public void getStatusPageUsers(String actionType,String email, String oldContactEmail)
    {
        statusPageUserWithEmailId = new Map<String,String>();
        HttpRequest req = new HttpRequest();
        Status_Page_Setup__c statusPageSetup = Status_Page_Setup__c.getOrgDefaults();
        req.setEndpoint(statusPageSetup.Status_page_EndPoint__c+'/pages/'+statusPageSetup.Page_ID__c+'/page_access_users' );
        req.setHeader('Content-Type','application/json');
        User usr = [SELECT Id, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() LIMIT 1];
        String userApiKey = String.isNotBlank(usr.User_Status_API_Key__c) ? usr.User_Status_API_Key__c : '';
        if(String.isNotBlank(userApiKey)){
            req.setHeader('authorization', 'OAuth '+userApiKey);
            req.setMethod('GET');
            req.setTimeout(120000);
            HTTP h = new HTTP();
            HTTPResponse res = new HTTPResponse();
            try{
                res = h.send(req);
                if(String.isNotBlank(res.getBody())){
                    System.debug('=====response======'+res.getBody());
                    try{
                        List<PageAccessUsers> statusPageUsers = new List<PageAccessUsers>(); 
                        statusPageUsers = (List<PageAccessUsers>) JSON.deserialize(res.getBody(), List<PageAccessUsers>.class);
                        //iterate over the list of users recieved from Status page and creating a map of email with user id.
                        for(PageAccessUsers pau : statusPageUsers){
                            statusPageUserWithEmailId.put(pau.email,pau.id);
                        }
                        if(actionType == 'validate'){
                            validateStatusPageUsers(email);
                        }
                        if(actionType == 'remove'){
                            deleteStatusPageUsers(email);
                        }
                        if(actionType == 'add'){
                            addStatusPageUsers(email);
                        }
                        if(actionType == 'update'){
                            updateStatusPageUsers(email,oldContactEmail);
                        }
                        System.debug('=====statusPageUsers======'+statusPageUsers);
                    }catch(Exception e){
                        System.debug('==============parsing exception==========='+e.getMessage());
                    }
                    
                }else{
                    System.debug('==============error===========');
                }  
            }catch(CalloutException ce){
                System.debug('===========ce===error==========='+ce.getMessage());
            }
        }else{
            System.debug('===========Invalid User API===========');
        }
        
    }   
    
    
    //method to validate user exist in Status Page.
    public String validateStatusPageUsers(String contactEmail){
        if(statusPageUserWithEmailId != null && String.isNotBlank(contactEmail) && statusPageUserWithEmailId.containsKey(contactEmail)){
            return statusPageUserWithEmailId.get(contactEmail);
        }else{
            return null;
        }        
    }
    
    //method to delete user in Status Page.
    public Boolean deleteStatusPageUsers(String contactEmail){
        String pageAccessUserId = validateStatusPageUsers(contactEmail);
        if(String.isNotBlank(pageAccessUserId)){
            HttpRequest req = new HttpRequest();
            Status_Page_Setup__c statusPageSetup = Status_Page_Setup__c.getOrgDefaults();
            req.setEndpoint(statusPageSetup.Status_page_EndPoint__c+'/pages/'+statusPageSetup.Page_ID__c+'/page_access_users/'+pageAccessUserId);
            req.setHeader('Content-Type','application/json');
            User usr = [SELECT Id, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() LIMIT 1];
            String userApiKey = String.isNotBlank(usr.User_Status_API_Key__c) ? usr.User_Status_API_Key__c : '';
            if(String.isNotBlank(userApiKey)){
                req.setHeader('authorization', 'OAuth '+userApiKey);
                req.setMethod('DELETE');
                req.setTimeout(120000);
                HTTP h = new HTTP();
                HTTPResponse res = new HTTPResponse();
                try{
                    PageAccessUsersDataSet pau = new PageAccessUsersDataSet();
                    PageAccessUser pausr = new PageAccessUser();
                    pausr.email = contactEmail;
                    pausr.page_access_group_ids = new String[]{statusPageSetup.Group_Id__c};
                    pau.page_access_user = pausr;
                    System.debug('======='+JSON.serialize(pau));
                    System.debug('==After=add=JSON.serialize(bodyMap)======'+JSON.serialize(pau));
                    req.setBody(JSON.serialize(pau));
                    res = h.send(req);
                    if(String.isNotBlank(res.getBody())){
                        System.debug('=====response======'+res.getBody());
                    }else{
                        System.debug('====delete=response======'+res.getBody());
                    }
                }catch(CalloutException ce){
                    
                }
            } 
        }else{
            System.debug('====User is not avilable');
        }
        
        return null;
    }
    
    //method to add new user in Status Page.
    public Boolean addStatusPageUsers(String contactEmail){
        String pageAccessUserId = validateStatusPageUsers(contactEmail);
        if(String.isBlank(pageAccessUserId)){
            HttpRequest req = new HttpRequest();
            Status_Page_Setup__c statusPageSetup = Status_Page_Setup__c.getOrgDefaults();
            req.setEndpoint(statusPageSetup.Status_page_EndPoint__c+'/pages/'+statusPageSetup.Page_ID__c+'/page_access_users');
            req.setHeader('Content-Type','application/json');
            User usr = [SELECT Id, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() LIMIT 1];
            String userApiKey = String.isNotBlank(usr.User_Status_API_Key__c) ? usr.User_Status_API_Key__c : '';
            if(String.isNotBlank(userApiKey)){
                req.setHeader('authorization', 'OAuth '+userApiKey);
                req.setMethod('POST');
                PageAccessUsersDataSet pau = new PageAccessUsersDataSet();
                PageAccessUser pausr = new PageAccessUser();
                pausr.email = contactEmail;
                pausr.page_access_group_ids = new String[]{statusPageSetup.Group_Id__c};
                pau.page_access_user = pausr;
                System.debug('======='+JSON.serialize(pau));
                System.debug('==After add==JSON.serialize(bodyMap)======'+JSON.serialize(pau));
                req.setBody(JSON.serialize(pau));
                req.setTimeout(120000);
                HTTP h = new HTTP();
                HTTPResponse res = new HTTPResponse();
                try{
                    res = h.send(req);
                    if(String.isNotBlank(res.getBody())){
                        System.debug('=====response======'+res.getBody());
                    }else{
                        System.debug('====add=response======'+res.getBody());
                    }
                }catch(CalloutException ce){
                    
                }
            } 
        }else{
            System.debug('=====User is not avilable=====');
        }
        
        return null;
    }
    
    //method to update details of user in Status Page.
    public Boolean updateStatusPageUsers(String contactEmail, String oldContactEmail){
        String pageAccessUserId = validateStatusPageUsers(oldContactEmail);
        if(String.isNotBlank(pageAccessUserId)){
            HttpRequest req = new HttpRequest();
            Status_Page_Setup__c statusPageSetup = Status_Page_Setup__c.getOrgDefaults();
            req.setEndpoint(statusPageSetup.Status_page_EndPoint__c+'/pages/'+statusPageSetup.Page_ID__c+'/page_access_users/'+pageAccessUserId);
            req.setHeader('Content-Type','application/json');
            User usr = [SELECT Id, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() LIMIT 1];
            String userApiKey = String.isNotBlank(usr.User_Status_API_Key__c) ? usr.User_Status_API_Key__c : '';
            if(String.isNotBlank(userApiKey)){
                req.setHeader('authorization', 'OAuth '+userApiKey);
                req.setMethod('PUT');
                PageAccessUsersDataSet pau = new PageAccessUsersDataSet();
                PageAccessUser pausr = new PageAccessUser();
                pausr.email = contactEmail;
                pausr.page_access_group_ids = new String[]{statusPageSetup.Group_Id__c};
                pau.page_access_user = pausr;
                System.debug('======='+JSON.serialize(pau));
                System.debug('==After update=delete=JSON.serialize(bodyMap)======'+JSON.serialize(pau));
                req.setBody(JSON.serialize(pau));
                req.setTimeout(120000);
                HTTP h = new HTTP();
                HTTPResponse res = new HTTPResponse();
                try{
                    res = h.send(req);
                    if(String.isNotBlank(res.getBody())){
                        System.debug('=====response======'+res.getBody());
                    }else{
                        System.debug('====update=response======'+res.getBody());
                    }
                }catch(CalloutException ce){
                    
                }
            } 
        }else{
            System.debug('====User is not avilable');
        }
        return null;
    }

    // A wrapper class to create json structure to send the data to the status page to add/update/remove the user.
    class PageAccessUsersDataSet{
        public PageAccessUser page_access_user{get;set;}
    }
    
    // A wrapper class to create json structure to send the data to the status page.
    class PageAccessUser{
        public String email{get;set;}
        public String []page_access_group_ids{get;set;}
    }
    
    
    // A wrapper class to store the page access member recieved from status Page
    Class PageAccessUsers{
        public String id{get;set;}
        public String page_id{get;set;}
        public String email{get;set;}
        public String external_login{get;set;}
        public String page_access_group_id{get;set;}
    }
}
I have a requirement where I want to send an Email to "Assign To"  when an event is Created.

My event is created Automatically when My Parent Object(Support Request ) Record is approved with the standard Approval process.

I have written a trigger where I am able to create an Event automatically through trigger but at the same time, I want to send an Email to the owner of the Event with a link that event Record is created.

Below is my code :

Public class AutoCreateEvent
{

    Public static void createNewEvent(List<DealSupportRequest__c> dsreq, Map<Id, DealSupportRequest__c> oldDsreqMap)
    {
        
        List<Event> EventRec = new List<Event>();
      
        RecordType SuppReqRecordType = [SELECT Id
                                         FROM RecordType
                                         WHERE SobjectType = 'DealSupportRequest__c' AND DeveloperName = 'PSCUOnsiteSupport'
                                         LIMIT 1];

        for(DealSupportRequest__c ds:dsreq)
        {
            
            if((ds.Is_approved__c==true && ds.RecordtypeId==SuppReqRecordType.Id) && (ds.Is_approved__c != oldDsreqMap.get(ds.Id).Is_approved__c) )
            {
               Event e  = new Event();
                e.WhatId = ds.Account__c;
                e.Type   = 'On-Site at PSCU';
                e.Status__c = 'Scheduled';    
                e.OwnerId = ds.Ownerid;
                e.Subject_Custom__c =ds.Purpose__c; 
                e.Description = ds.OtherPurpose__c;
                e.StartDateTime =ds.StartDateTime__c;
                e.EndDateTime = ds.EndDateTime__c;
                e.LocationCallInInfo__c = ds.CampusLocation__c;
                e.Support_Request__c = ds.Id;
                EventRec.add(e);
                
          }
            
      }
      
        If(EventRec.size()>0)
        Insert EventRec;
        
    List<User> u =[select Id,Name,Email from User where ID=:UserInfo.getUserId()];
        
    List<Messaging.SingleEmailMessage> lst = new List<Messaging.SingleEmailMessage>();
    List<EmailTemplate> template = [select Id,Name,Subject,body from EmailTemplate where name = 'Event Created Confirmation After Support Request Approved'];       
     Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
     semail.setTemplateId(template[0].Id);
       List<String> sendTo = new List<String>();
      sendTo.add(EventRec.ownerId);
      semail.setToAddresses(sendTo);
 
     lst.add(semail);
  
      Messaging.sendEmail(lst); 
    
    }

}


 

Below is the Example provided to make the Authorization with the External system. But I am not sure how to make use of it in Authorization .
 
Passing your API key in an authorization header

The following example authenticates you with the page API. Along with the Page ID listed on the API page, we can fetch your page profile.
curl -H "Authorization: OAuth 89a229ce1a8dbcf9ff30430fbe35eb4c0426574bca932061892cefd2138aa4b1" \ https://api.statuspage.io/v1/pages/gytm4qzbx9t6.json

Passing your API key in a query param
curl "https://api.statuspage.io/v1/pages/gytm4qzbx9t6.json?api_key=89a229ce1a8dbcf9ff30430fbe35eb4c0426574bca932061892cefd2138aa4b1"

Security scheme type: API Key
header parameter name: Authorization
....................................................................................................................................................................................................................................
I am getting an Error :
Illegal string literal: Invalid string literal '\https://api.statuspage.io/v1/pages/gytm4qzbx9t6.json'. Illegal character sequence \h' in string literal.

Below is My code :
public list <contact> conlist= new list<contact>();
    
    public string PageID ='0ypqjmkwgqmh'; 
    
    Public statusPageCallout(list<contact>conlist){
        
        this.conlist = conlist;
        
        
    }
    
    public void execute(QueueableContext context)
    {
list<user> userlist = [SELECT id,name, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() limit 1];
        
        string API = userlist[0].User_Status_API_Key__c;
        system.debug('API------'+API);
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://api.statuspage.io/v1/pages/'+PageID);
        req.setMethod('POST');
        req.SetHeader('Authorization','curl -H "Authorization: OAuth'+API+'\https://api.statuspage.io/v1/pages/gytm4qzbx9t6.json');
        Http http = new Http();
        HTTPResponse res;
        try {
            res = http.send(req);
            System.debug(res.getBody());                
        } catch (Exception e) {
            System.debug('Callout Error:' + e.getMessage());
            
        }
        
}
I mentioned my class with respective test class. please let me know where I am doing wrong.

My class is calling in a trigger which fires when my support Request(object) Record is approved by the approver through the standard approval process. when the record is approved the trigger automatically create an Event record. below is the class with test class .

Public class AutoCreateEvent
{
    Public static void createNewEvent(List<DealSupportRequest__c> dsreq, Map<Id, DealSupportRequest__c> oldDsreqMap)
    {
        
        List<Event> EventRec = new List<Event>();
        RecordType SuppReqRecordType = [SELECT Id
                                         FROM RecordType
                                         WHERE SobjectType = 'DealSupportRequest__c' AND DeveloperName = 'PSCUOnsiteSupport'
                                         LIMIT 1];
        for(DealSupportRequest__c ds:dsreq)
        {
            
            if((ds.Is_approved__c==true && ds.RecordtypeId==SuppReqRecordType.Id) && (ds.Is_approved__c !=          oldDsreqMap.get(ds.Id).Is_approved__c) )
            {
               Event e  = new Event();
                e.WhatId = ds.Account__c;
                e.Type   = 'On-Site at PSCU';
                e.Status__c = 'Scheduled';    
                e.OwnerId = ds.Ownerid;
                e.Subject_Custom__c =ds.Purpose__c; 
                e.Description = ds.OtherPurpose__c;
                e.StartDateTime =ds.StartDateTime__c;
                e.EndDateTime = ds.EndDateTime__c;
                e.LocationCallInInfo__c = ds.CampusLocation__c;
                e.Support_Request__c = ds.Id;
                EventRec.add(e);
              
          }
      }
        If(EventRec.size()>0)
        Insert EventRec;
    }
}

Test class:
@IsTest
public class AutoCreateEvent_Test {

    static testmethod void  CreateEvent(){
      Test.startTest();
        
            User u = new User(
            ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
            LastName = 'last',
            Email = 'puser000@amamama.com',
            Username = 'puser000@amamama.com' + System.currentTimeMillis(),
            CompanyName = 'TEST',
            Title = 'title',
            Alias = 'alias',
            TimeZoneSidKey = 'America/Los_Angeles',
            EmailEncodingKey = 'UTF-8',
            LanguageLocaleKey = 'en_US',
            LocaleSidKey = 'en_US',
            EmployeeNumber='1'
        );
        insert u;
        List<Event> EventRec = new List<Event>();
    
        Account a = new Account(Name='1st Community CU',Membership_Defined__c='Member',Type='Client', ownerid=u.id );
        Insert a;
    
        DealSupportRequest__c dsr = new      DealSupportRequest__c(Account__c=a.Id,StartDateTime__c=system.now(),EndDateTime__c=system.now().addDays(1),ownerid=a.Ownerid);
        Insert dsr;
        
         Event e = new Event();
            e.WhatId=a.Id;
            e.Type   = 'On-Site at PSCU';
            e.Status__c = 'Scheduled';
            e.OwnerId = dsr.Ownerid;
          //  e.Support_Request__c=dsr.Id;
            e.StartDateTime =dsr.StartDateTime__c;
            e.EndDateTime = dsr.EndDateTime__c;
            EventRec.add(e);
        
        insert EventRec;
    Test.stopTest() ;   
    }
}
I have a visual force page where whenever I am trying to create a new record it is giving me an error.
System.QueryException: Apply_Cash_Fees_to_Promo_Transactions__c, AQ_table_ID__c, Charge_Cash_Item_Fees__c ^ ERROR at Row:1:Column:90 invalid ID field: null 
Class.NewTLPController.<init>: line 22, column 1

The above query has parent object fields. For the Existing record, my code works properly But during the creation of new Record, the above error occurs. Below is my class 

public with sharing class NewTLPController
 {
        //Instance Variables 
       public List<TLP_System_Prin__c> TLPList {get;set;}
       public List<TLP_System_Prin__c> TLPAddList {get;set;}
       public TLP__c tlpRecord;
       public List<TLP_System_Prin__c> tlpSysPrinList;
       ApexPages.StandardController controller;
       
        //standard controller constructor
        public NewTLPController(ApexPages.StandardController con) {
            controller =con;  
            tlpRecord = (TLP__c)con.getRecord();
            String queryData = 'SELECT Agent__c,System_Prin__c,MarkedforDeletion__c,TLP__c FROM TLP_System_Prin__c WHERE TLP__c=\''+tlpRecord.Id+'\'';
            TLPList = Database.Query(queryData);
            if(TLPList.size()<=0){
                TLPAddList = new List<TLP_System_Prin__c>();    
            }
            else{
                TLPAddList = new List<TLP_System_Prin__c>();    
                TLPAddList.addAll(TLPList);
            }            
       }
       
       
        
        //Method is used to add the Multiple rows.
        public void AddRow()
        {
            
            TLPAddList.add(new TLP_System_Prin__c());
        }  
        //Method is used to remove the rows.
        public void removerow(){
         
            Integer i = TLPAddList.size();
            
            TLPAddList.remove(i-1);
           
        } 
          
        
       //Method is used to save the TLP record & also save the Multiple row data. 
       public pageReference saveAll()
       {
           TLP__c tlpRec = (TLP__c)controller.getRecord();
           upsert tlpRec;
           for(TLP_System_Prin__c tsp:TLPAddList)
           {
               if(tsp.TLP__c==Null){
                    tsp.TLP__c = tlpRec.Id;    
               }               
           }
           if(TLPAddList.size()>0)
           {
            upsert TLPAddList;    
           }        
           return new PageReference('/'+tlpRec.Id);
       }
       
  }
 

Hello All,

I have queries related to Integration part as I am new to it. I have a requirement where I want to update the two picklists field data of contact (object ) in Salesforce from External System. I want to integrate through rest. can anyone let me know how to do this actions or anyone provide me the sample code to do it? 

What are the pre-requisite Required to do the authentication

Here is my code that i am trying to do.

Public Class statusPageCallout{

    public static void spageCallout(){
    
        List<Contact> con = new List<Contact>();
        con=[select Id,AccountId,System_Status_Request__c,System_Status_Participation_Level__c,email from Contact];
      //  String systemStatusReq =con.System_Status_Request__c;
        String api_Key = '89a229ce1a8dbcf9ff30430fbe35eb4c0426574bca932061892cefd2138aa4b1';
        String token;
        String requestEndpoint = 'https://api.statuspage.io/v1/pages';
      //  requestEndpoint += '?q='+System_Status_Request__c;        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        
        request.setEndpoint(requestEndpoint);
        request.setMethod('Post');
        request.setHeader('Content-Type', 'application/jason; charset=utf-8');
        request.setHeader('Authorization',token);
        request.setheader('Authorization','apikey'+api_Key);
      //  request.setBody();
        HttpResponse response = http.send(request);
        

        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {

           // Deserialize the JSON string into collections of primitive data types.
       Map<String, Object> results = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
       Map<String, Object> mainResults = (Map<String, object>)(results.get('pages'));
      
   /*     System.debug('Received the following animals:');
            for (Object pages: mainResults) {
             //   System.debug(pages);
       }
   */    
       
    }else {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'There was an error retrieving  information.');
           ApexPages.addMessage(myMsg);
        }


}
 

User-added image

This is My snippet Which i need to cover in My test class .
class  :-
Public class UpdateTerritorySectionFields{
Public static Void  ofOnsiteatPSCUInProgressUp(List<Territory_Plan__c> tpe){
           Set<Id> ownerIds =New set<Id>();
           List<Event> evtList = new List<Event>();
           List<Territory_Plan__c > ObjectRec = new List<Territory_Plan__c >(); 
           List<Territory_Plan__c> tpList = new List<Territory_Plan__c>();
           List<Territory_Plan__c > ObjectBList = new List<Territory_Plan__c >();
           List<Opportunity> oppoList = new List<Opportunity>();           
           for(Territory_Plan__c t:tpe){
               ownerIds.add(t.Account_Executive__c);
            }
            Map<Id, Opportunity> oppoMap = new Map<Id, Opportunity>([SELECT Id, StageName, ownerId FROM Opportunity WHERE OwnerId IN : ownerIds]);
            evtList = [SELECT Id, WhatId, Status__c, Type, ownerId FROM Event WHERE Status__c='Scheduled' AND Type='On-Site at PSCU' AND ownerID IN:ownerIds];
            for(Territory_Plan__c tp:tpe){
               for(Event e: evtList){
                    if(tp.Account_Executive__c==e.ownerId && oppoMap.containsKey(e.WhatId) && tp.Account_Executive__c==oppoMap.get(e.WhatId).ownerId){
                       oppoList.add(oppoMap.get(e.WhatId));
                    }
                }    
tp.of_Onsite_at_PSCU_In_Progress__c = oppoList.size();
                tpList.add(tp);
            }
            update tpList;
            }
}

Test class :-
@isTest
public class testUpTerritorySectionFields {
Public Static testMethod Void UpdateTerFromEvent(){
         User u = getUserRecord();
        territory_Plan__c tp = new territory_Plan__c(Account_Executive__c=u.id);
        insert tp;
        
          
        Opportunity opp = new Opportunity(Name='Chicago Patrolmens FCU AFA',PSCU_Opp_Referred_By__c=u.id,StageName='06 - Sale Closed',CloseDate=Date.Today(),Probability=100,PSCU_Contract_Term__c='2',ownerid=u.id );
        Insert opp;
        List<Event> ev =new List<Event>();
        Event e1 =new Event(Type='On-Site at PSCU',Status__c='Scheduled',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2);
            ev.add(e1);
        Event e2 =new Event(Type='On-Site at PSCU',Status__c='Completed',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e2);
        Event e3 =new Event(Type='On-Site at Account',Status__c='Scheduled',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e3);
        Event e4 =new Event(Type='On-Site at Account',Status__c='Completed',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e4);
        Event e5 =new Event(Type='Call/Webinar with CU',Status__c='Completed',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e5);
        Event e6 =new Event(Type='Call/Webinar with CU',Status__c='Scheduled',OwnerId=u.id ,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e6);
        Insert ev;
        
        List<Event> Evnt = [select Type,Status__c,OwnerId,DurationInMinutes,ActivityDateTime from Event Where WhatId=:opp.Id LIMIT 6 ];
        Update Evnt;
        
        
    } 
}

      Public static Void  territoryFinancialsDj(List<Territory_Plan__c> tpe){
           Set<Id> ownerIds =New set<Id>();
           List<Event> evtList = new List<Event>();
           List<Territory_Plan__c > ObjectRec = new List<Territory_Plan__c >(); 
           List<Territory_Plan__c > tpList = new List<Territory_Plan__c >(); 
           List<Territory_Plan__c > ObjectBList = new List<Territory_Plan__c >(); 
            List<Opportunity> oppoList = new List<Opportunity>();
  
           For(Territory_Plan__c t:tpe){
               ownerIds.add(t.Account_Executive__c);
           }
           
           Map<Id, Opportunity> oppoMap = new Map<Id, Opportunity>([SELECT Id, StageName, ownerId FROM Opportunity WHERE OwnerId IN : ownerIds]);
           evtList = [SELECT Id, WhatId, Status__c, Type, ownerId FROM Event WHERE Status__c='Completed' AND Type='On-Site at PSCU' AND ownerID IN:ownerIds ];
               for(Territory_Plan__c tp:tpe){
                               for(Event e: evtList){
                   if(tp.Account_Executive__c==e.ownerId && oppoMap.containsKey(e.WhatId) && tp.Account_Executive__c==oppoMap.get(e.WhatId).ownerId){
                       oppoList.add(oppoMap.get(e.WhatId));
                     
                   }
               }    
             tp.of_Onsite_at_PSCU_YTD__c = oppoList.size();
               tpList.add(tp);
               
           }
           
      }
      
I want to Create a SOQL Query to get the Count of number of Opportunity Records & update in child Object Field
Hi 
I have a requirement Where i want to Query the Records based on the Below Criteria :
Account_Executive is  a Custom Field(User Lookup) field whenever i select a User in Account_Executive field  in Territory_plan__c (object) it should query all the Records of event related to Opportunity  & update in  #of ONsite at xyz - in progress .
#of ONsite at xyz - in progress  : Is a field on Custom Object(Territory_plan__c ) where i want to Update the Count of below criteria

# of Onsite at xyz– In Progress
This field should populate with the number of Opportunity records that meet the following criteria:
The User in the “Account Executive” field in the Territory Plan object is equal to the “Assigned To” in the Event object
The Status for the Event is “Scheduled”
The Type for the Event is “On-Site at xyz”
This is my Class whose test Class i have written But is failing everytime.with error First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Owner ID: owner cannot be blank: [OwnerId] .

public with sharing class CU_Detail_Growth {

    
        Public id accRecId {get;set;}
        public list<Account> accList{get;set;}
        Public Integer size{get;set;}
        Public Integer noOfRecords{get; set;}
      
    /*  public CU_Detail_Growth (){
      
        
      
      }*/
      
   /* public CU_Detail_Growth(ApexPages.StandardController controller) {
       
    }*/
    public CU_Detail_Growth(ApexPages.StandardsetController controller) {  
         accRecId = [select id,Account_Executive__c from Territory_Plan__c where id = :ApexPages.currentPage().getParameters().get('id')].Account_Executive__c;
         system.debug('****'+accRecId); 
        }  
      
    public ApexPages.StandardSetController setCon {
        get{
            if(setCon == null){
                size = 5;
                string queryString = 'select id,OwnerId,Name,Account_Category__c,of_Members__c,Market_Segment__c,Account_Status__c,Action_Plan__c,Relationship_Assessment__c FROM Account Where Account_Category__c =\'Growth\'  AND OwnerId =:accRecId' ;
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
                setCon.setPageSize(size);
                noOfRecords = setCon.getResultSize();
            }
                return setCon;
        }set;
    }
      
    Public List<Account> getAccounts(){
        List<Account> accList = new List<Account>();
            for(Account a : (List<Account>)setCon.getRecords())
                accList.add(a);
            return accList;
    }
        
    public pageReference refresh() {
            setCon = null;
            getAccounts();
            setCon.setPageNumber(1);
            return null;
    }
        
    public Boolean hasNext {
        get {
            return setCon.getHasNext();
            }
        set;
    }
    public Boolean hasPrevious {
        get {
            return setCon.getHasPrevious();
            }
        set;
    }
     
    public Integer pageNumber {
        get {
            return setCon.getPageNumber();
            }
        set;
        }
     
    public void first() {
        setCon.first();
    }
     
    public void last() {
        setCon.last();
    }
     
    public void previous() {
        setCon.previous();
    }
     
    public void next() {
        setCon.next();
    }
}
Test Class:-

@IsTest
Public class TestCU_Detail_Growth {
    
    Public static testMethod Void detailGrowth(){
    
        User u = new User(
     ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
     LastName = 'last',
     Email = 'puser000@amamama.com',
     Username = 'puser000@amamama.com' + System.currentTimeMillis(),
     CompanyName = 'TEST',
     Title = 'title',
     Alias = 'alias',
     TimeZoneSidKey = 'America/Los_Angeles',
     EmailEncodingKey = 'UTF-8',
     LanguageLocaleKey = 'en_US',
     LocaleSidKey = 'en_US'
     
);

         Account acc =new Account(Name='1st Advantage CU ',Account_Category__c ='Growth',OwnerId=u.id);
         Insert acc;
          
        List<Territory_Plan__c> t = new List<Territory_Plan__c>();
        Territory_Plan__c tps = new Territory_Plan__c();
        tps.Account_Executive__c=u.id;
        tps.of_Accounts__c=14;
        tps.Fiscal_Year__c='2018';
        tps.Total_Years_Membership__c=120;
        tps.of_Accounts_with_Bill_Pay__c=12;
        tps.of_Accounts_with_Credit__c=14;
        tps.of_Accounts_with_Debit__c=5;
      //  tps.Account__c=acc.id;
        tps.of_Accounts_with_TMC__c=7;
        
        t.add(tps);
                                                
          Insert t;
    
   Test.StartTest(); 
           PageReference pageRef = Page.CU_Growth; 
  pageRef.getParameters().put('id', String.valueOf(acc.Id));
         Test.setCurrentPage(Page.CU_Growth);
  ApexPages.StandardSetController stdSetController = new ApexPages.StandardSetController(t);
  stdSetController.setSelected(t);
  CU_Detail_Growth  ext = new CU_Detail_Growth (stdSetController);

            
            ext.getAccounts();
            ext.refresh();
            ext.first();
            ext.last();
            ext.previous();
            ext.next(); 

        Test.StopTest();
    
    
    }



}
subodh chaturvedi 17 
how to update a parent field (checkbox) Based on child records field Values.
 i have checkbox field Visa__c In Account & i have a custom Object (Card program ) where i have two fields Cardtype __c & card_processor_status__c, so the requiremnt is when the  cardtype__c=Visa  & Card_processor_Status__c =Active then the Checkbox should get check in Visa__c in account & when the two fields value is other than visa & active the  checkbox should get unchecked.

let suppose we have 10 records in Cardprogram out of 10 if atleast 1 record have fullfill the criteria then also the checkbox should get checked .

Here is the criteria for when the “Visa” field should be TRUE:
There is a Card Program record related to the Account that has at least one single record that meets both the criteria below:
The “Card Type” field is “Visa”
The “Card Processor Status” field is “Active”
 
Hi 
I have a requirement Where
  1. Processed Lines Business is a  Custom Object where I have  a Field  called  “Total LOB Annual Revenue” on the records  & it should be populated with the sum of “Monthly Revenue” which is  also a field on the same record .
       2 If i have 12 Records Then the Sum of all 'Monthly Revenue' should be Populated on the Latest Month Record  ,suppose i have records from Sept-16 to Sept- 17  then on Sept 17 record  the latest 'Total LOB Annual Revenue' get Updated.

3. i am passing the parameter like Credit /debit/ etc so based on the LOB value it is filtering the Record ,so it is taking only those Record Which Lob parameter is passed.

Please let me know where i am doing wrong.



//Batch to update Total Revenue for Processed LOB.
global class BatchUpdateAI implements Database.Batchable<sObject>
{                  
                  
            private String strParameter;
            private List <ProcessedLinesofBusinessDetail__c> pLOBToUpdate = new list<ProcessedLinesofBusinessDetail__c>();

            public BatchUpdateAI(String strParam) 
            {
                strParameter = strParam;
            }
            
            
            global Database.QueryLocator start(Database.BatchableContext BC)
            {
               String query = 'select id, AsofDate__c, AsofDateCalc__c, LOB__c from ProcessedLinesofBusinessDetail__c';
               return Database.getQueryLocator(query);
            }

            global void execute(Database.BatchableContext BC,List<ProcessedLinesofBusinessDetail__c> scope)
            {                 
                  Double totalRev = 0.0;
                  
                  for(Account acc : [select id, (select id, AsofDateCalc__c, TotalAnnualRevenue__c, MonthlyRevenue__c from Processed_Lines_of_Business_Details__r where 
                                            LOB__c =: strParameter and AsofDateCalc__c = LAST_N_MONTHS:12 ) from Account])
                  {
                               totalRev = 0.0;
                               for(ProcessedLinesofBusinessDetail__c plob : acc.Processed_Lines_of_Business_Details__r) 
                               {
                                    if(plob.MonthlyRevenue__c != null)
                                        totalRev = totalRev + plob.MonthlyRevenue__c;
                               }
                               
                               for(ProcessedLinesofBusinessDetail__c temp : acc.Processed_Lines_of_Business_Details__r)
                               {
                                    temp.TotalAnnualRevenue__c = totalRev;
                                    pLOBToUpdate.add(temp);
                               }                  
                   }
                   if(!pLOBToUpdate.isEmpty() && pLOBToUpdate.size()>0)
                            update pLOBToUpdate;                  
            }

            global void finish(Database.BatchableContext BC)
            {
                
            }
 }
Hi ,
can we Update the Records From parent to child & also  from child to parent  (viceversa ) through trigger .
I have a requirement where i have 10-15 Fields In parent Whose values i need to update in child fields &  fields with Same values  i have in child ,If I update any child field values from Child that should Update the values in parent. How We can do this through Trigger when record is Inserted & also While Updated ?  
Hi ,
I have a requirement Where i have a wrapper page  multiple checkboxes with Values  in a vf page & on the same vf page i have a custom Button so when i click on that button the copy of the vf page should open in pdf  but the hurdle is the checkbox is not displaying in pdf  how i can bring the checkboxes  either  Checked & unchecked values of it bcoz it will change based On new Record Open  .   
Hi ,
I want to Generate  my current visualforce page  In Pdf Format when click on a  Custom Button which is on the same page  ,the class  consist a wrapper class which has a checkbox & values , I have created a pagerefernce Method but how to generate in Pdf.

<apex:page standardController="Account" extensions="SolutionParticipationCategoryController" sidebar="False" > 
<head>
<style type="text/css"> 
#rows{
        padding-left:250px;
        padding-Right:250px;
        
}
#cellAlign{
    vertical-align: top;
    border-collapse: collapse;
    border: 1px solid black;
}

 </style>
</head>
    <apex:form >
      <apex:sectionHeader title="Account" subtitle="Key Solutions Inventory "/>
            <apex:pageBlock >
                <apex:pageBlockbuttons >
                    <apex:commandButton value="Open Account" action="{!OpenAccount}"/>
                    <apex:commandButton value="Solution Participation " action="{!SolutionParticipation}" />
                    <apex:commandButton value="Card Program " action="{!cardProgram}" />
                    <apex:commandButton value="View Pdf"  action="{!ViewPDF}"/>
                </apex:pageBlockbuttons>
                                
            
                <table style="border-collapse: collapse;padding:50px;">
                    <tr>
                        <apex:repeat value="{!resultPickValuesMap}" var="M">
                            <td style="vertical-align: top;padding:30px;text-align:left;">
                               <b style="text-align:center;">{!M}</b><br/>
                               <apex:repeat value="{!resultPickValuesMap[M]}" var="temp">
                                   <table>
                                       <tr>
                                           <td style="padding-top:5px;">
                                               <apex:inputCheckbox value="{!temp.isSelected}" disabled="true"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                               <apex:commandLink id="theLink" action="{!solutionList}" target="_blank">
                                                   <apex:param assignTo="{!solName}" value="{!temp.value}" name="solName"/>
                                                   <apex:outputText value="{!temp.value}"/>
                                               </apex:commandLink>
                                            </td>
                                        </tr>
                                   </table>
                               </apex:repeat>
                            </td>
                         </apex:repeat>
                     </tr>
                </table>
            </apex:pageblock>         
    </apex:form>
</apex:page>

controller:-
/* *****
 Date:- 8/1/2018
 Description :- This Class is used to get the Multiselect Values from Account & displayed in New Vf Page on key solution Inventory button & checked 
                If altleast One Solution is Active so the Checkbox get checked. 
*/
public with sharing class SolutionParticipationCategoryController 
{
    public Id acctId{get;set;}
    public String solName{get;set;}
    public Set<String> CategorySelected{get;set;}   
    Public MAP<String,LIST<Account>> accsCategoryByType{get;set;} 
    public Map<String, List<PicklistWrapper>> resultPickValuesMap{get;set;}
    public Set<String> controllKeySet{get;set;}
    public List<PicklistWrapper> enterpriseCardSolutionsList;
    public List<PicklistWrapper> creditList;
    public List<PicklistWrapper> debitList;
    public List<PicklistWrapper> advisorsPlusList;
    Public List<Solution_Participation__c>sp;
    Public Integer count;
    Public Map<String,Integer> checkActMap;
    
    public SolutionParticipationCategoryController(ApexPages.StandardController stdController) 
    {
        acctId = ApexPages.currentPage().getParameters().get('id');
        System.debug('acctId-->'+acctId);
        CategorySelected = new Set<String>();
        resultPickValuesMap = getDependentOptionsImpl();
    }
    public Map<String,List<PicklistWrapper>> getDependentOptionsImpl()
    {
        String objApiName = 'Account';
        String contrfieldApiName = 'Picklist_Independent__c';
        String depfieldApiName = 'Solution_Participation_Category__c';
        String objectName = objApiName.toLowerCase();
        String controllingField = contrfieldApiName.toLowerCase();
        String dependentField = depfieldApiName.toLowerCase();
        
        
        checkActMap = new Map<String,Integer>();
        Map<String,List<PicklistWrapper>> objResults = new Map<String,List<PicklistWrapper>>();
            //get the string to sobject global map
        Map<String,Schema.SObjectType> objGlobalMap = Schema.getGlobalDescribe();
         
        if (!Schema.getGlobalDescribe().containsKey(objectName))
           {
            System.debug('OBJNAME NOT FOUND --.> ' + objectName);
            return null;
           }
        
        Schema.SObjectType objType = Schema.getGlobalDescribe().get(objectName);
        if (objType==null){
            return objResults;
        }
        Bitset bitSetObj = new Bitset();
        Map<String, Schema.SObjectField> objFieldMap = objType.getDescribe().fields.getMap();
        //Check if picklist values exist
        if (!objFieldMap.containsKey(controllingField) || !objFieldMap.containsKey(dependentField)){
            System.debug('FIELD NOT FOUND --.> ' + controllingField + ' OR ' + dependentField);
            return objResults;     
        }
        
        List<Schema.PicklistEntry> contrEntries = objFieldMap.get(controllingField).getDescribe().getPicklistValues();
        List<Schema.PicklistEntry> depEntries = objFieldMap.get(dependentField).getDescribe().getPicklistValues();
         objFieldMap = null;
        List<Integer> controllingIndexes = new List<Integer>();
        for(Integer contrIndex=0; contrIndex<contrEntries.size(); contrIndex++) {            
            Schema.PicklistEntry ctrlentry = contrEntries[contrIndex];
            String label = ctrlentry.getLabel();
            objResults.put(label,new List<PicklistWrapper>());
            controllingIndexes.add(contrIndex);
        }
        List<Schema.PicklistEntry> objEntries = new List<Schema.PicklistEntry>();
        List<PicklistEntryWrapper> objJsonEntries = new List<PicklistEntryWrapper>();
        for(Integer dependentIndex=0; dependentIndex<depEntries.size(); dependentIndex++){            
               Schema.PicklistEntry depentry = depEntries[dependentIndex];
               objEntries.add(depentry);
        } 
        objJsonEntries = (List<PicklistEntryWrapper>)JSON.deserialize(JSON.serialize(objEntries), List<PicklistEntryWrapper>.class);
        List<Integer> indexes;
        Account a = [SELECT Solution_Participation_Category__c,(SELECT Id,solution_name__c,Active__c FROM solution_participations__r) FROM Account WHERE Id =: acctId limit 1];
        List<Solution_Participation__c> mySol = a.solution_participations__r;
        Schema.DescribeFieldResult fieldResult = Account.Solution_Participation_Category__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for(PicklistEntryWrapper pew : objJsonEntries){
        count=0;
            for(Solution_Participation__c solp:mySol){
                if(solp.Active__c==true && solp.solution_name__c==String.valueof(pew.label)){
                    count++;
                    checkActMap.put(String.valueof(pew.label),count);
                }
            }
        }
        if(a.Solution_Participation_Category__c != null )
        {
          
           CategorySelected.addAll(a.Solution_Participation_Category__c.split(';'));
           
        }
       
        //Schema.DescribeFieldResult fieldResult = Account.Solution_Participation_Category__c.getDescribe();
        //List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        
       
        for (PicklistEntryWrapper objJson : objJsonEntries){
            if (objJson.validFor==null || objJson.validFor==''){
                continue;
            }
               indexes = bitSetObj.testBits(objJson.validFor,controllingIndexes);
            sp= [select Id,Active__c, Account__r.Solution_Participation_Category__c From Solution_Participation__c where Account__c =: acctId limit 1];  
            for (Integer idx : indexes)
              {                
                String contrLabel = contrEntries[idx].getLabel();
                
                if(CategorySelected.contains(String.valueof(objJson.label))&&checkActMap.get(String.valueof(objJson.label))>0)
                {
                  
                  
                    objResults.get(contrLabel).add(new PicklistWrapper(objJson.label,true));
                }
                else
                {
                    objResults.get(contrLabel).add(new PicklistWrapper(objJson.label,false));
                }
            }
        }
        objEntries = null;
        objJsonEntries = null;
        system.debug('objResults--->' + objResults);
        return objResults;
    }
    public class PicklistWrapper 
        {
        public String value {get;set;}
        public Boolean isSelected {get;set;}
        
        public PicklistWrapper(String value, Boolean isSelected) 
                {
            this.value = value;
            this.isSelected = isSelected;
        }
    }
    public PageReference solutionList()
    {
        System.debug('SolName-->'+solName);  
        PageReference solutionList = new Pagereference('/apex/SolutionList');
        solutionList.getParameters().put('Id', acctId);
        solutionList.getParameters().put('solName', solName);
        
        solutionList.setRedirect(true);
        
        return solutionList;      
    }
    
  
    public PageReference OpenAccount() 
    {
        Pagereference acc = new Pagereference('/'+acctId);
        acc.setRedirect(true);
        return acc;
    }
    
    Public PageReference SolutionParticipation()
    {
    id ReportId = [Select id from Report where name = 'Solution Participants'].id;
        
    Pagereference sp= new Pagereference('/'+ReportId);
     sp.setRedirect(true);
     return sp;
    
    }
    
    Public PageReference CardProgram()
    {
    id ReportId1 = [Select id from Report where name = 'Card Programs'].id;
    Pagereference cp= new Pagereference('/'+ReportId1);
    cp.setRedirect(true);
    return cp;
    
    }
    
  /*  Public PageReference ViewPDF(){
    pageReference vpdf = page.solutionparticipationPDF;
    vpdf.setRedirect(true);
    return vpdf;
    }*/

}
Test Class methods are passing But but when i am checking the Code Coverage it is giving me 0% coverage  & there is No is Color Code to show test class below  

@isTest
public class TestcardProgramsolparticipationcheck {
 public static testMethod void testRunAs() {
        // Setup test data
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        User u = new User(Alias = 'sysadm', Email='systemuser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, EmployeeNumber='12015',
            TimeZoneSidKey='America/Los_Angeles', UserName='csubodh@pscu.com');

        System.runAs(u) {
            // The following code runs as user 'u' 
            System.debug('Current User: ' + UserInfo.getUserName());
            System.debug('Current Profile: ' + UserInfo.getProfileId()); 
            
           
       }
   }
    Public static testMethod void method1()
     {
         List<Account> acc = new List<Account>();
         for(Integer i=0;i>=200;i++){
             Account a = new account(Name='XYZ'+i);
             acc.add(a);
         }
       
         List<Card_Program__c> cp =new List<Card_Program__c>();
         for(Integer i=0;i>=200;i++){
             Card_program__c cpr =new Card_Program__c(FI__c='12 Financial CU'+i,Card_Processor_Status__c='ACTIVE');
             cp.add(cpr);
         }
         test.starttest();
           Insert acc;
           Insert cp;
        
         List<Solution_Participation__c> spn= new List<Solution_Participation__c>();
         for(Integer i=0;i>=200;i++){
            Solution_Participation__c spr = new Solution_Participation__c(Card_Program__c='11800883',Active__c= true);
     }  
          List<Card_Program__c> cps =new List<Card_Program__c>();
         for(Integer i=0;i>=200;i++){
             Card_program__c cprs =new Card_Program__c(FI__c='12 Financial CU'+i,Card_Processor_Status__c='INACTIVE');
// FI__c is a lookup field from Account.

             cps.add(cprs);
         }
           Insert cps;
        
         List<Solution_Participation__c> sp= new List<Solution_Participation__c>();
         for(Integer i=0;i>=200;i++){
            Solution_Participation__c sprs = new Solution_Participation__c(Card_Program__c='11800884',Active__c= False);
         }
        test.stoptest();     
}
}

Actual Class --
Public class cardProgramsolparticipationcheck{

 Public Static Void checkFieldstatus(List<Card_Program__c> card){
    Map<id,Card_Program__c> programIds = new Map<id,Card_Program__c>();
    for(Card_Program__c cp : card){
    if(cp.card_processor_status__c != null){
        programIds.put(cp.id,cp);
      }
    }
    
    List<Solution_participation__c> updChildrecs = new List<Solution_participation__c>();
    List<Solution_participation__c> childrecs = [select id,Active__c,Card_Program__c from Solution_participation__c where Card_Program__c IN : programIds.keyset()];
    
    if(childrecs.size()>0){
      for(Solution_participation__c sp : childrecs){
        if(programIds.get(sp.Card_Program__c).card_processor_status__c == 'INACTIVE'){
           sp.Active__c = FALSE;
        }else {
           sp.Active__c = TRUE;
         }           
           updChildrecs.add(sp);
      }
      if(updChildrecs.size()>0){
          Update updChildrecs;
      }
     
    
    }



}
}
I have a field on parent (Card Program__c) object i.e  card_processor_status__c  & have a Child (Solution_participation__c) Object which has Active__c checkbox Field I want to Update the Checkbox Field  Whenever the card_processor_status__c   changes to  either Active or Inactive .
I tried to update this with process builder But it is No Success .How we can Update this through Code? 
I have my helper Class But i am not getting how to write the test class Of it.

public class BitSet
 {
   public Map < String, Integer > alphaNumCharCodes {
    get;
    set;
 }
  public Map < String, Integer > base64CharCodes
 {
    get;
    set;
 }

  public BitSet() {
  LoadCharCodes();
 }
 
 //Method loads the character codes for all letters
 public void LoadCharCodes() 
{
  alphaNumCharCodes = new Map < String, Integer > {
   'A' => 65,
   'B' => 66,
   'C' => 67,
   'D' => 68,
   'E' => 69,
   'F' => 70,
   'G' => 71,
   'H' => 72,
   'I' => 73,
   'J' => 74,
   'K' => 75,
   'L' => 76,
   'M' => 77,
   'N' => 78,
   'O' => 79,
   'P' => 80,
   'Q' => 81,
   'R' => 82,
   'S' => 83,
   'T' => 84,
   'U' => 85,
   'V' => 86,
   'W' => 87,
   'X' => 88,
   'Y' => 89,
   'Z' => 90
  };
  base64CharCodes = new Map < String, Integer > ();
  //all lower cases
  Set < String > pUpperCase = alphaNumCharCodes.keySet();
  for (String pKey: pUpperCase) 
  {
   //the difference between upper case and lower case is 32
   alphaNumCharCodes.put(pKey.toLowerCase(), alphaNumCharCodes.get(pKey) + 32);
   //Base 64 alpha starts from 0 (The ascii charcodes started from 65)
   base64CharCodes.put(pKey, alphaNumCharCodes.get(pKey) - 65);
   base64CharCodes.put(pKey.toLowerCase(), alphaNumCharCodes.get(pKey) - (65) + 26);
  }
  //numerics
  for (Integer i = 0; i <= 9; i++) 
  {
   alphaNumCharCodes.put(string.valueOf(i), i + 48);
   //base 64 numeric starts from 52
   base64CharCodes.put(string.valueOf(i), i + 52);
  }
}
 
 public List < Integer > testBits(String pValidFor, List < Integer > nList) 
 {
    List < Integer > results = new List < Integer > ();
    List < Integer > pBytes = new List < Integer > ();
    Integer bytesBeingUsed = (pValidFor.length() * 6) / 8;
    Integer pFullValue = 0;
        if (bytesBeingUsed <= 1)
            return results;
        for (Integer i = 0; i < pValidFor.length(); i++) 
        {
            pBytes.Add((base64CharCodes.get((pValidFor.Substring(i, i + 1)))));
        }
    for (Integer i = 0; i < pBytes.size(); i++) 
    {
        Integer pShiftAmount = (pBytes.size() - (i + 1)) * 6; //used to shift by a factor 6 bits to get the value
        pFullValue = pFullValue + (pBytes[i] << (pShiftAmount));
    }
 
        Integer bit;
        Integer targetOctet;
        Integer shiftBits;
        Integer tBitVal;
        Integer n;
        Integer nListSize = nList.size();
  for (Integer i = 0; i < nListSize; i++) 
  {
        n = nList[i];
        bit = 7 - (Math.mod(n, 8));
        targetOctet = (bytesBeingUsed - 1) - (n >> bytesBeingUsed);
        shiftBits = (targetOctet * 8) + bit;
        tBitVal = ((Integer)(2 << (shiftBits - 1)) & pFullValue) >> shiftBits;
    if (tBitVal == 1)
        results.add(n);
  }
        return results;
 }
}
Hello all,
In My account Record I have a multi select picklist field  which have values & in the same detail page i have a custom button so while clicking on that button  a new Vf page will Open which have all the Values of multiselect picklist with checkbox for that wrapper class is written  , My requirement Is i want to show the header  in 4 columns  & filter the values based on header  from Multiselect values (A,B,C,D suppose is the header name  these are not Fields )   how to set the header     

vf code
<apex:page standardController="Account" extensions="SolutionParticipationCategoryController" sidebar="False" > 
     
   <apex:form >
   <apex:sectionHeader title="Account" subtitle="Key Solutions Inventory "/>
       <apex:pageBlock >
       <apex:pageBlockbuttons >
       <apex:commandButton value="Open Account" action="{!OpenAccount}"/>
       </apex:pageBlockbuttons>
       
        <apex:pageBlockSection columns="3">
        <apex:repeat value="{!PicklistValues}" var="wrapper">     
            <apex:outputPanel layout="block" style="width:100%;float: left;">
                <apex:panelGrid columns="2">
                     <apex:commandLink id="theLink" action="{!solutionList}" target="_blank">
                        <apex:param assignTo="{!solName}" value="{!wrapper.value}" name="solName"/>
                        <apex:inputCheckbox value="{!wrapper.isSelected}" disabled="true"/> 
                        <apex:outputText value="{!wrapper.value}">                            
                        </apex:outputText>
                    </apex:commandLink>  
                </apex:panelGrid>
                
            </apex:outputPanel>
        </apex:repeat>
        </apex:pageBlockSection>
     
        </apex:pageBlock>          
       
    </apex:form>
 </apex:page>
...................................
contoller
public with sharing class SolutionParticipationCategoryController 
{
    public Id acctId{get;set;}
    public String solName{get;set;}
    public Set<String> CategorySelected{get;set;}    
   
    
    public SolutionParticipationCategoryController(ApexPages.StandardController stdController) 
    {
        acctId = ApexPages.currentPage().getParameters().get('id');
        System.debug('In Const-->');
        System.debug('acctId-->'+acctId);
        CategorySelected = new Set<String>();
    }
    
    public class PicklistWrapper {
        public String value {get;set;}
        public Boolean isSelected {get;set;}
        
        public PicklistWrapper(String value, Boolean isSelected) {
            this.value = value;
            this.isSelected = isSelected;
        }
       
    }
    
     public List<PicklistWrapper> getPicklistValues() 
    {
       List<PicklistWrapper> picklistValues = new List<PicklistWrapper>();
       
       Account a = [SELECT Solution_Participation_Category__c FROM Account WHERE Id =: acctId limit 1];
       if(a.Solution_Participation_Category__c != null)
       {
           CategorySelected.addAll(a.Solution_Participation_Category__c.split(';'));
           
       }
        
        Schema.DescribeFieldResult fieldResult = Account.Solution_Participation_Category__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        System.debug('CategorySelected--->'+CategorySelected);
        for( Schema.PicklistEntry f : ple)
        {
               System.debug('PL-->'+String.ValueOf(f));
               if(CategorySelected.contains(String.ValueOf(f.getLabel())))
                   picklistValues.add(new PicklistWrapper(f.getLabel(), true));
                else
                   picklistValues.add(new PicklistWrapper(f.getLabel(), false));          
        }           
        System.debug('picklistValues-->'+picklistValues);
       
        return picklistValues;
         
      
               
    }
    
    
    
    public PageReference solutionList()
    {
        System.debug('SolName-->'+solName);  
        PageReference solutionList = new Pagereference('/apex/SolutionList');
        solutionList.getParameters().put('Id', acctId);
        solutionList.getParameters().put('solName', solName);
        
        solutionList.setRedirect(true);
        
        return solutionList;      
    }
    
  
    public PageReference OpenAccount() 
    {
        Pagereference acc = new Pagereference('/'+acctId);
        acc.setRedirect(true);
        return acc;
    }

}
Below class updating the contact field (Account_status_BG__c)from the account field (Membership_Defined__c).
It is only covering 60 %. it is not going under if condition.
public class AccountStatusUpdate {
    
    public static void acntStatusMethod(List<Account> ac,Map<Id,Account> oldAccountMap){
        set<Id> accIds = new set<Id>();
        for(Account acc: ac){
            accIds.add(acc.Id);
        }
        
        if(accIds.size() > 0){
            List<Contact> contactList = [SELECT Id,Account_Status__c, AccountId, Account.Membership_Defined__c FROM Contact WHERE AccountId IN : accIds];
            //Create a list to update the contacts    
            List<Contact> contactToBeUpdate = new List<Contact>();
            for(Contact objCont : contactList){ 
                if(oldAccountMap!= null && String.isNotBlank(objCont.Account.Membership_Defined__c) && objCont.Account.Membership_Defined__c != oldAccountMap.get(objCont.AccountId).Membership_Defined__c){
                    Contact newContact = new Contact();
                    newContact.Id = objCont.Id;
                    newContact.Account_Status_BG__c = objCont.Account.Membership_Defined__c;
                    contactToBeUpdate.add(newContact);
                }
            }
            if(contactToBeUpdate.size() > 0){
                UPDATE contactToBeUpdate;
            }
        }
        
    }
    
}

Below is the Example provided to make the Authorization with the External system. But I am not sure how to make use of it in Authorization .
 
Passing your API key in an authorization header

The following example authenticates you with the page API. Along with the Page ID listed on the API page, we can fetch your page profile.
curl -H "Authorization: OAuth 89a229ce1a8dbcf9ff30430fbe35eb4c0426574bca932061892cefd2138aa4b1" \ https://api.statuspage.io/v1/pages/gytm4qzbx9t6.json

Passing your API key in a query param
curl "https://api.statuspage.io/v1/pages/gytm4qzbx9t6.json?api_key=89a229ce1a8dbcf9ff30430fbe35eb4c0426574bca932061892cefd2138aa4b1"

Security scheme type: API Key
header parameter name: Authorization
....................................................................................................................................................................................................................................
I am getting an Error :
Illegal string literal: Invalid string literal '\https://api.statuspage.io/v1/pages/gytm4qzbx9t6.json'. Illegal character sequence \h' in string literal.

Below is My code :
public list <contact> conlist= new list<contact>();
    
    public string PageID ='0ypqjmkwgqmh'; 
    
    Public statusPageCallout(list<contact>conlist){
        
        this.conlist = conlist;
        
        
    }
    
    public void execute(QueueableContext context)
    {
list<user> userlist = [SELECT id,name, User_Status_API_Key__c FROM User WHERE ID=:Userinfo.getUserId() limit 1];
        
        string API = userlist[0].User_Status_API_Key__c;
        system.debug('API------'+API);
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://api.statuspage.io/v1/pages/'+PageID);
        req.setMethod('POST');
        req.SetHeader('Authorization','curl -H "Authorization: OAuth'+API+'\https://api.statuspage.io/v1/pages/gytm4qzbx9t6.json');
        Http http = new Http();
        HTTPResponse res;
        try {
            res = http.send(req);
            System.debug(res.getBody());                
        } catch (Exception e) {
            System.debug('Callout Error:' + e.getMessage());
            
        }
        
}
I mentioned my class with respective test class. please let me know where I am doing wrong.

My class is calling in a trigger which fires when my support Request(object) Record is approved by the approver through the standard approval process. when the record is approved the trigger automatically create an Event record. below is the class with test class .

Public class AutoCreateEvent
{
    Public static void createNewEvent(List<DealSupportRequest__c> dsreq, Map<Id, DealSupportRequest__c> oldDsreqMap)
    {
        
        List<Event> EventRec = new List<Event>();
        RecordType SuppReqRecordType = [SELECT Id
                                         FROM RecordType
                                         WHERE SobjectType = 'DealSupportRequest__c' AND DeveloperName = 'PSCUOnsiteSupport'
                                         LIMIT 1];
        for(DealSupportRequest__c ds:dsreq)
        {
            
            if((ds.Is_approved__c==true && ds.RecordtypeId==SuppReqRecordType.Id) && (ds.Is_approved__c !=          oldDsreqMap.get(ds.Id).Is_approved__c) )
            {
               Event e  = new Event();
                e.WhatId = ds.Account__c;
                e.Type   = 'On-Site at PSCU';
                e.Status__c = 'Scheduled';    
                e.OwnerId = ds.Ownerid;
                e.Subject_Custom__c =ds.Purpose__c; 
                e.Description = ds.OtherPurpose__c;
                e.StartDateTime =ds.StartDateTime__c;
                e.EndDateTime = ds.EndDateTime__c;
                e.LocationCallInInfo__c = ds.CampusLocation__c;
                e.Support_Request__c = ds.Id;
                EventRec.add(e);
              
          }
      }
        If(EventRec.size()>0)
        Insert EventRec;
    }
}

Test class:
@IsTest
public class AutoCreateEvent_Test {

    static testmethod void  CreateEvent(){
      Test.startTest();
        
            User u = new User(
            ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
            LastName = 'last',
            Email = 'puser000@amamama.com',
            Username = 'puser000@amamama.com' + System.currentTimeMillis(),
            CompanyName = 'TEST',
            Title = 'title',
            Alias = 'alias',
            TimeZoneSidKey = 'America/Los_Angeles',
            EmailEncodingKey = 'UTF-8',
            LanguageLocaleKey = 'en_US',
            LocaleSidKey = 'en_US',
            EmployeeNumber='1'
        );
        insert u;
        List<Event> EventRec = new List<Event>();
    
        Account a = new Account(Name='1st Community CU',Membership_Defined__c='Member',Type='Client', ownerid=u.id );
        Insert a;
    
        DealSupportRequest__c dsr = new      DealSupportRequest__c(Account__c=a.Id,StartDateTime__c=system.now(),EndDateTime__c=system.now().addDays(1),ownerid=a.Ownerid);
        Insert dsr;
        
         Event e = new Event();
            e.WhatId=a.Id;
            e.Type   = 'On-Site at PSCU';
            e.Status__c = 'Scheduled';
            e.OwnerId = dsr.Ownerid;
          //  e.Support_Request__c=dsr.Id;
            e.StartDateTime =dsr.StartDateTime__c;
            e.EndDateTime = dsr.EndDateTime__c;
            EventRec.add(e);
        
        insert EventRec;
    Test.stopTest() ;   
    }
}
User-added image

This is My snippet Which i need to cover in My test class .
class  :-
Public class UpdateTerritorySectionFields{
Public static Void  ofOnsiteatPSCUInProgressUp(List<Territory_Plan__c> tpe){
           Set<Id> ownerIds =New set<Id>();
           List<Event> evtList = new List<Event>();
           List<Territory_Plan__c > ObjectRec = new List<Territory_Plan__c >(); 
           List<Territory_Plan__c> tpList = new List<Territory_Plan__c>();
           List<Territory_Plan__c > ObjectBList = new List<Territory_Plan__c >();
           List<Opportunity> oppoList = new List<Opportunity>();           
           for(Territory_Plan__c t:tpe){
               ownerIds.add(t.Account_Executive__c);
            }
            Map<Id, Opportunity> oppoMap = new Map<Id, Opportunity>([SELECT Id, StageName, ownerId FROM Opportunity WHERE OwnerId IN : ownerIds]);
            evtList = [SELECT Id, WhatId, Status__c, Type, ownerId FROM Event WHERE Status__c='Scheduled' AND Type='On-Site at PSCU' AND ownerID IN:ownerIds];
            for(Territory_Plan__c tp:tpe){
               for(Event e: evtList){
                    if(tp.Account_Executive__c==e.ownerId && oppoMap.containsKey(e.WhatId) && tp.Account_Executive__c==oppoMap.get(e.WhatId).ownerId){
                       oppoList.add(oppoMap.get(e.WhatId));
                    }
                }    
tp.of_Onsite_at_PSCU_In_Progress__c = oppoList.size();
                tpList.add(tp);
            }
            update tpList;
            }
}

Test class :-
@isTest
public class testUpTerritorySectionFields {
Public Static testMethod Void UpdateTerFromEvent(){
         User u = getUserRecord();
        territory_Plan__c tp = new territory_Plan__c(Account_Executive__c=u.id);
        insert tp;
        
          
        Opportunity opp = new Opportunity(Name='Chicago Patrolmens FCU AFA',PSCU_Opp_Referred_By__c=u.id,StageName='06 - Sale Closed',CloseDate=Date.Today(),Probability=100,PSCU_Contract_Term__c='2',ownerid=u.id );
        Insert opp;
        List<Event> ev =new List<Event>();
        Event e1 =new Event(Type='On-Site at PSCU',Status__c='Scheduled',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2);
            ev.add(e1);
        Event e2 =new Event(Type='On-Site at PSCU',Status__c='Completed',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e2);
        Event e3 =new Event(Type='On-Site at Account',Status__c='Scheduled',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e3);
        Event e4 =new Event(Type='On-Site at Account',Status__c='Completed',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e4);
        Event e5 =new Event(Type='Call/Webinar with CU',Status__c='Completed',OwnerId=u.id,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e5);
        Event e6 =new Event(Type='Call/Webinar with CU',Status__c='Scheduled',OwnerId=u.id ,WhatId =opp.Id,DurationInMinutes=5,ActivityDateTime=Date.TOday()+2,AddressType__c='Mailing Address');
        ev.add(e6);
        Insert ev;
        
        List<Event> Evnt = [select Type,Status__c,OwnerId,DurationInMinutes,ActivityDateTime from Event Where WhatId=:opp.Id LIMIT 6 ];
        Update Evnt;
        
        
    } 
}

      Public static Void  territoryFinancialsDj(List<Territory_Plan__c> tpe){
           Set<Id> ownerIds =New set<Id>();
           List<Event> evtList = new List<Event>();
           List<Territory_Plan__c > ObjectRec = new List<Territory_Plan__c >(); 
           List<Territory_Plan__c > tpList = new List<Territory_Plan__c >(); 
           List<Territory_Plan__c > ObjectBList = new List<Territory_Plan__c >(); 
            List<Opportunity> oppoList = new List<Opportunity>();
  
           For(Territory_Plan__c t:tpe){
               ownerIds.add(t.Account_Executive__c);
           }
           
           Map<Id, Opportunity> oppoMap = new Map<Id, Opportunity>([SELECT Id, StageName, ownerId FROM Opportunity WHERE OwnerId IN : ownerIds]);
           evtList = [SELECT Id, WhatId, Status__c, Type, ownerId FROM Event WHERE Status__c='Completed' AND Type='On-Site at PSCU' AND ownerID IN:ownerIds ];
               for(Territory_Plan__c tp:tpe){
                               for(Event e: evtList){
                   if(tp.Account_Executive__c==e.ownerId && oppoMap.containsKey(e.WhatId) && tp.Account_Executive__c==oppoMap.get(e.WhatId).ownerId){
                       oppoList.add(oppoMap.get(e.WhatId));
                     
                   }
               }    
             tp.of_Onsite_at_PSCU_YTD__c = oppoList.size();
               tpList.add(tp);
               
           }
           
      }
      
subodh chaturvedi 17 
how to update a parent field (checkbox) Based on child records field Values.
 i have checkbox field Visa__c In Account & i have a custom Object (Card program ) where i have two fields Cardtype __c & card_processor_status__c, so the requiremnt is when the  cardtype__c=Visa  & Card_processor_Status__c =Active then the Checkbox should get check in Visa__c in account & when the two fields value is other than visa & active the  checkbox should get unchecked.

let suppose we have 10 records in Cardprogram out of 10 if atleast 1 record have fullfill the criteria then also the checkbox should get checked .

Here is the criteria for when the “Visa” field should be TRUE:
There is a Card Program record related to the Account that has at least one single record that meets both the criteria below:
The “Card Type” field is “Visa”
The “Card Processor Status” field is “Active”
 
Hi ,
I have a requirement Where i have a wrapper page  multiple checkboxes with Values  in a vf page & on the same vf page i have a custom Button so when i click on that button the copy of the vf page should open in pdf  but the hurdle is the checkbox is not displaying in pdf  how i can bring the checkboxes  either  Checked & unchecked values of it bcoz it will change based On new Record Open  .   
Test Class methods are passing But but when i am checking the Code Coverage it is giving me 0% coverage  & there is No is Color Code to show test class below  

@isTest
public class TestcardProgramsolparticipationcheck {
 public static testMethod void testRunAs() {
        // Setup test data
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        User u = new User(Alias = 'sysadm', Email='systemuser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, EmployeeNumber='12015',
            TimeZoneSidKey='America/Los_Angeles', UserName='csubodh@pscu.com');

        System.runAs(u) {
            // The following code runs as user 'u' 
            System.debug('Current User: ' + UserInfo.getUserName());
            System.debug('Current Profile: ' + UserInfo.getProfileId()); 
            
           
       }
   }
    Public static testMethod void method1()
     {
         List<Account> acc = new List<Account>();
         for(Integer i=0;i>=200;i++){
             Account a = new account(Name='XYZ'+i);
             acc.add(a);
         }
       
         List<Card_Program__c> cp =new List<Card_Program__c>();
         for(Integer i=0;i>=200;i++){
             Card_program__c cpr =new Card_Program__c(FI__c='12 Financial CU'+i,Card_Processor_Status__c='ACTIVE');
             cp.add(cpr);
         }
         test.starttest();
           Insert acc;
           Insert cp;
        
         List<Solution_Participation__c> spn= new List<Solution_Participation__c>();
         for(Integer i=0;i>=200;i++){
            Solution_Participation__c spr = new Solution_Participation__c(Card_Program__c='11800883',Active__c= true);
     }  
          List<Card_Program__c> cps =new List<Card_Program__c>();
         for(Integer i=0;i>=200;i++){
             Card_program__c cprs =new Card_Program__c(FI__c='12 Financial CU'+i,Card_Processor_Status__c='INACTIVE');
// FI__c is a lookup field from Account.

             cps.add(cprs);
         }
           Insert cps;
        
         List<Solution_Participation__c> sp= new List<Solution_Participation__c>();
         for(Integer i=0;i>=200;i++){
            Solution_Participation__c sprs = new Solution_Participation__c(Card_Program__c='11800884',Active__c= False);
         }
        test.stoptest();     
}
}

Actual Class --
Public class cardProgramsolparticipationcheck{

 Public Static Void checkFieldstatus(List<Card_Program__c> card){
    Map<id,Card_Program__c> programIds = new Map<id,Card_Program__c>();
    for(Card_Program__c cp : card){
    if(cp.card_processor_status__c != null){
        programIds.put(cp.id,cp);
      }
    }
    
    List<Solution_participation__c> updChildrecs = new List<Solution_participation__c>();
    List<Solution_participation__c> childrecs = [select id,Active__c,Card_Program__c from Solution_participation__c where Card_Program__c IN : programIds.keyset()];
    
    if(childrecs.size()>0){
      for(Solution_participation__c sp : childrecs){
        if(programIds.get(sp.Card_Program__c).card_processor_status__c == 'INACTIVE'){
           sp.Active__c = FALSE;
        }else {
           sp.Active__c = TRUE;
         }           
           updChildrecs.add(sp);
      }
      if(updChildrecs.size()>0){
          Update updChildrecs;
      }
     
    
    }



}
}
I have a field on parent (Card Program__c) object i.e  card_processor_status__c  & have a Child (Solution_participation__c) Object which has Active__c checkbox Field I want to Update the Checkbox Field  Whenever the card_processor_status__c   changes to  either Active or Inactive .
I tried to update this with process builder But it is No Success .How we can Update this through Code? 
I have my helper Class But i am not getting how to write the test class Of it.

public class BitSet
 {
   public Map < String, Integer > alphaNumCharCodes {
    get;
    set;
 }
  public Map < String, Integer > base64CharCodes
 {
    get;
    set;
 }

  public BitSet() {
  LoadCharCodes();
 }
 
 //Method loads the character codes for all letters
 public void LoadCharCodes() 
{
  alphaNumCharCodes = new Map < String, Integer > {
   'A' => 65,
   'B' => 66,
   'C' => 67,
   'D' => 68,
   'E' => 69,
   'F' => 70,
   'G' => 71,
   'H' => 72,
   'I' => 73,
   'J' => 74,
   'K' => 75,
   'L' => 76,
   'M' => 77,
   'N' => 78,
   'O' => 79,
   'P' => 80,
   'Q' => 81,
   'R' => 82,
   'S' => 83,
   'T' => 84,
   'U' => 85,
   'V' => 86,
   'W' => 87,
   'X' => 88,
   'Y' => 89,
   'Z' => 90
  };
  base64CharCodes = new Map < String, Integer > ();
  //all lower cases
  Set < String > pUpperCase = alphaNumCharCodes.keySet();
  for (String pKey: pUpperCase) 
  {
   //the difference between upper case and lower case is 32
   alphaNumCharCodes.put(pKey.toLowerCase(), alphaNumCharCodes.get(pKey) + 32);
   //Base 64 alpha starts from 0 (The ascii charcodes started from 65)
   base64CharCodes.put(pKey, alphaNumCharCodes.get(pKey) - 65);
   base64CharCodes.put(pKey.toLowerCase(), alphaNumCharCodes.get(pKey) - (65) + 26);
  }
  //numerics
  for (Integer i = 0; i <= 9; i++) 
  {
   alphaNumCharCodes.put(string.valueOf(i), i + 48);
   //base 64 numeric starts from 52
   base64CharCodes.put(string.valueOf(i), i + 52);
  }
}
 
 public List < Integer > testBits(String pValidFor, List < Integer > nList) 
 {
    List < Integer > results = new List < Integer > ();
    List < Integer > pBytes = new List < Integer > ();
    Integer bytesBeingUsed = (pValidFor.length() * 6) / 8;
    Integer pFullValue = 0;
        if (bytesBeingUsed <= 1)
            return results;
        for (Integer i = 0; i < pValidFor.length(); i++) 
        {
            pBytes.Add((base64CharCodes.get((pValidFor.Substring(i, i + 1)))));
        }
    for (Integer i = 0; i < pBytes.size(); i++) 
    {
        Integer pShiftAmount = (pBytes.size() - (i + 1)) * 6; //used to shift by a factor 6 bits to get the value
        pFullValue = pFullValue + (pBytes[i] << (pShiftAmount));
    }
 
        Integer bit;
        Integer targetOctet;
        Integer shiftBits;
        Integer tBitVal;
        Integer n;
        Integer nListSize = nList.size();
  for (Integer i = 0; i < nListSize; i++) 
  {
        n = nList[i];
        bit = 7 - (Math.mod(n, 8));
        targetOctet = (bytesBeingUsed - 1) - (n >> bytesBeingUsed);
        shiftBits = (targetOctet * 8) + bit;
        tBitVal = ((Integer)(2 << (shiftBits - 1)) & pFullValue) >> shiftBits;
    if (tBitVal == 1)
        results.add(n);
  }
        return results;
 }
}
global class BatchPopulateSolutionInventory implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
           String soqlQuery = 'select id,Solution_Participation_Category__c from Account';  
           return Database.getQueryLocator(soqlQuery);
    }

    global void execute(Database.BatchableContext BC, List<Account> scope) {    
            /*for(Account a:scope){
                accSet.add(a.Id);
            }*/
            set<String> uniqueSol_Name= new set<String>();
            map<Id, set<String>> mapTest = new map<Id, set<String>>();
            list<account> accupdate = new list<Account>();
            set<Id> accIds = new set<Id>();
            list<Solution_Participation__c> test =[select Id, Solution_Name__c,Account__c from Solution_Participation__c 
                                                  where 
                                                  Account__c IN :scope];
                                                  
            for(Account acc:scope) {          
             
                for(Solution_Participation__c Sol : test) {
                    
                    if(Sol.solution_name__c != null && Sol.Account__c == acc.Id) {
                        uniqueSol_Name.add(Sol.solution_name__c);
                        accIds.add(Sol.Account__c);
                    }                          
                }
                if(accIds.contains(acc.Id)) {
                    mapTest.put(acc.Id, uniqueSol_Name);    
                }           
            }
            system.debug('**mapTest**'+mapTest);
            for(Account acc:scope) {
                string testStr = '';
                boolean flag = true;
                if(mapTest.containskey(acc.Id))
                for(String strObj : mapTest.get(acc.Id)) {
                    if(flag) {
                        testStr = strObj;
                        flag = false;
                    }
                    else {
                        testStr = testStr+';'+strObj;
                    }
                }
                acc.Solution_Participation_Category__c = testStr;
                accupdate.add(acc);
            }
            if(accupdate.size() >0) {
                update accupdate;
            }
     } 
    global void finish(Database.BatchableContext BC){}
}