function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Prema -Prema - 

how can i achieve this through apex When Account is marked as Inactive (Custom Checkbox) then mark all related contacts as inactive.Can anyone please tell me the sourcecode with vf page not through process builder or any workflows please help me.

Best Answer chosen by Prema -
Karan Shekhar KaulKaran Shekhar Kaul
I missed that.Try this.



public class AccountInactiveController {
    
    private Account acc;
    public AccountInactiveController(ApexPages.StandardController controller) {
        
        acc =  (Account)controller.getRecord();
        
    }
    
    public pageReference save(){
        system.debug('*acc**'+acc.InActive__c);
        if(acc.InActive__c){
            update acc ;
            inActiateContacts(acc);
        }
        
        return new pagereference('/'+acc.Id);
        
    }
    
    private void inActiateContacts(Account acc){
    
         List<Contact> contactList = new List<Contact>();
        
        for(Contact conObj: [Select id,InActive__c from contact where AccountId =:acc.Id ]){
            
            conObj.InActive__c = true;
            contactList.add(conObj);
        }
        
        if(!contactList.isEmpty()){
            update contactList;
        }
    }

}

All Answers

Karan Shekhar KaulKaran Shekhar Kaul
Hi Prema,

You can achieve this by formula field as well. Create a custom formula field on contact with return type as checkbox & refer Account's inactive checkbox.

Still if you need code, here it is
Access this page with this URL:

https://<serverUrl>.visual.force.com/apex/<page name>?id=<Account Id>

VF page:
<apex:page standardController="Account" extensions="AccountInactiveController" >
<apex:form >
<apex:pageBlock >

<apex:pageBlockSection >
 <apex:inputField value="{!account.InActive__c}"/>
</apex:pageBlockSection>
<apex:commandButton value="save" action="{!save}"/>
</apex:pageBlock>
   
</apex:form>
</apex:page>


controller:

public class AccountInactiveController {
    
    private Account acc;
    public AccountInactiveController(ApexPages.StandardController controller) {
        
        acc =  (Account)controller.getRecord();
        
    }
    
    public pageReference save(){
        system.debug('*acc**'+acc.InActive__c);
        if(acc.InActive__c)
        inActiateContacts(acc);
        return new pagereference('/'+acc.Id);
        
    }
    
    private void inActiateContacts(Account acc){
    
         List<Contact> contactList = new List<Contact>();
        
        for(Contact conObj: [Select id,InActive__c from contact where AccountId =:acc.Id ]){
            
            conObj.InActive__c = true;
            contactList.add(conObj);
        }
        
        if(!contactList.isEmpty()){
            update contactList;
        }
    }

}
Karan Shekhar KaulKaran Shekhar Kaul

Hi Prema,

Please mark correct answer if this helps.

Regards,

Karan

Prema -Prema -
Hello Karan,

Thankyou so much for your valuable response,it's working fine but the account's checkbox is not getting check however the contact's inactive checkbox is getting checked..Can you tell me why this is happening?

Thanks & Regards,
Prema
Karan Shekhar KaulKaran Shekhar Kaul
I missed that.Try this.



public class AccountInactiveController {
    
    private Account acc;
    public AccountInactiveController(ApexPages.StandardController controller) {
        
        acc =  (Account)controller.getRecord();
        
    }
    
    public pageReference save(){
        system.debug('*acc**'+acc.InActive__c);
        if(acc.InActive__c){
            update acc ;
            inActiateContacts(acc);
        }
        
        return new pagereference('/'+acc.Id);
        
    }
    
    private void inActiateContacts(Account acc){
    
         List<Contact> contactList = new List<Contact>();
        
        for(Contact conObj: [Select id,InActive__c from contact where AccountId =:acc.Id ]){
            
            conObj.InActive__c = true;
            contactList.add(conObj);
        }
        
        if(!contactList.isEmpty()){
            update contactList;
        }
    }

}
This was selected as the best answer
Prema -Prema -
and can you please tell me how can i do this through trigger.I will mark your answer as the best answer because it helped me alot but i just want to do this through trigger as noone is going to mark inactive through vf pafe.Also when i am marking the inactive checkbox as unchecked then the contact is not getting updated..Please help..
Karan Shekhar KaulKaran Shekhar Kaul
Hi Prema,

Below is Account trigger & helper class. You might need to write trigger on contact to ensure when new contact is being created for inactive accounts, that contact is also updated as inactive contact. This is just a raw implementation. You can consider using Trigger framework as well.
Hope this helps. Handle rest of the scenarios in same way.

Trigger:

trigger UpdateContactInActiveFlag on Account (before update) {
    
    Map<Id,Boolean> accIDToActiveFlagMap= new Map<Id,Boolean>();
    for(Account acc :trigger.new){
        
        if(trigger.oldMap.get(acc.Id).Active__c != acc.InActive__c ){
            accIDToActiveFlagMap.put(acc.id,acc.Active__c );
        }
    }
    system.debug('**accIDToActiveFlagMap****'+accIDToActiveFlagMap);
    AccountTriggerHelper.UpdateActiveFlagOnContacts(accIDToActiveFlagMap);
    
    
}

Apex class:

public with sharing class AccountTriggerHelper {

    
    public static void UpdateActiveFlagOnContacts(Map<Id,Boolean> accIdToFlagMap){
        
        List<Contact> listOfContactsToUpdate = new List<Contact>();
        try{
            List<Contact> contactsToUpdate = [Select id,InActive__c,AccountId  from Contact where AccountId IN :accIdToFlagMap.keySet()];
            if(contactsToUpdate != null && contactsToUpdate.size()>0 ){
            
                for(Contact conObj : contactsToUpdate ){
                    conObj.InActive__c  = accIdToFlagMap.get(conObj.AccountId);
                }
            }
            update contactsToUpdate ;
        }catch(Exception excp){
            
            system.debug('Exception occured while updating active flag on Account'+excp.getMessage()+excp.getStackTraceString());
        }
       
    }
}
Prema -Prema -
Thanks karan you are wonderful
Prema -Prema -
Can I also get all the account @karan ? so that I can select the account and make it inactive from the checkbox on record & it should get updated.Can I do this?
Karan Shekhar KaulKaran Shekhar Kaul
Hi Prema,

Yes, you can use recordSetVar on <apex:page> to use standard set controller,display all accounts with this checkbox in a pageblocktable & then run same logic to update Accounts & contacts.

This will help.
https://developer.salesforce.com/forums/?id=906F0000000BX9mIAG
Prema -Prema -
But how to relate the inactive checkbox beside every record?Actually I am new to this apex  I don't know much infact you can say 2% out of 10%.If you can help that would be great,I know it seems like i am getting greedy but it's ok if you don't have enough time to make this up..
Thanks.
Prema -Prema -
Also can you please tell me from where I can practice scenarios as I can see you have depth knowledge on apex.I too want to become good developer.Please help.
Karan Shekhar KaulKaran Shekhar Kaul
That is alright. Good to see people's inclination towards learning Salesforce.
Start with trailhead. It is one stop shop for everything you need to know about salesforce. Go through all developer trails.

https://trailhead.salesforce.com/

Some other links to get started with Apex programming. 
https://resources.docs.salesforce.com/sfdc/pdf/salesforce_apex_language_reference.pdf
https://www.tutorialspoint.com/apex/
http://www.sfdc99.com/apex-academy/
 
In the meantime, I will work on the code.



Prema -Prema -
thankyou @karan
Karan Shekhar KaulKaran Shekhar Kaul
Hi Prema,

I did manage to work something out quickly. This serves the purpose. You can beautify it based on your requirement. It will atleast give you an idea on how to start working.

VF page:

<apex:page standardController="Account" extensions="AccountInactiveController"   >
<apex:form >
<apex:pageBlock >

<apex:pageBlockSection columns="1">
<apex:pageBlockTable value="{!accounts}" var="accRecord">
<apex:column headerValue="Account Name" value="{!accRecord.Name}"/>
<apex:column headerValue="Active">
<apex:inputField value="{!accRecord.Active__c}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
<apex:commandButton value="save" action="{!save}"/>
</apex:pageBlock>
   
</apex:form>
</apex:page>

Controller:

public class AccountInactiveController {
    
    private Account acc;
    public AccountInactiveController(ApexPages.StandardController controller) {
        
        acc =  (Account)controller.getRecord();
        
    }
    
       // ApexPages.StandardSetController must be instantiated
    // for standard list controllers
    public ApexPages.StandardSetController setAccount {
        get {
            if(setAccount == null) {
                setAccount = new ApexPages.StandardSetController(Database.getQueryLocator(
                    [SELECT Name,Id,Active__c FROM Account]));
            }
            return setAccount ;
        }
        set;
    }
    // Initialize setCon and return a list of records
    public List<Account> getAccounts() {
   
        return setAccount.getRecords(); 
    }
    
    public pageReference save(){
    
    Map<Id,Boolean> oldAccIdToActiveFlagMap = new Map<Id,Boolean>();
    Map<Id,Boolean> accIdToActiveFlagMap = new Map<Id,Boolean>();
    List<Account> accListToUpdate = new List<Account>();
    
    
    for(Account acc : [Select id,Active__c from Account where ID IN :setAccount.getRecords()]){
        
        oldAccIdToActiveFlagMap .put(acc.Id,acc.Active__c );
    }
    
    
    for(Account acc : (List<Account>)setAccount.getRecords()){
        
        if(oldAccIdToActiveFlagMap .containsKey(acc.id)){
            if(oldAccIdToActiveFlagMap.get(acc.id) != acc.Active__c){
                
                    accIdToActiveFlagMap.put(acc.Id,acc.Active__c);
                    accListToUpdate.add(acc);
            }
        }
    }
    update accListToUpdate;
    AccountTriggerHelper.UpdateActiveFlagOnContacts(accIdToActiveFlagMap);
    return null;    
    }
    


}
Prema -Prema -
I wish I could have a word more than thanks or thankyou.I cannot explain how much you helped me karan.I am very greatful to you.
Prema -Prema -
But I am geting the following error when i run this class i.e Error: AccountInactiveController Compile Error: Variable does not exist: AccountTriggerHelper at line 52 column 5..
Karan Shekhar KaulKaran Shekhar Kaul
I have already given you code for this class

Apex class:

public with sharing class AccountTriggerHelper {

    
    public static void UpdateActiveFlagOnContacts(Map<Id,Boolean> accIdToFlagMap){
        
        List<Contact> listOfContactsToUpdate = new List<Contact>();
        try{
            List<Contact> contactsToUpdate = [Select id,InActive__c,AccountId  from Contact where AccountId IN :accIdToFlagMap.keySet()];
            if(contactsToUpdate != null && contactsToUpdate.size()>0 ){
            
                for(Contact conObj : contactsToUpdate ){
                    conObj.InActive__c  = accIdToFlagMap.get(conObj.AccountId);
                }
            }
            update contactsToUpdate ;
        }catch(Exception excp){
            
            system.debug('Exception occured while updating active flag on Account'+excp.getMessage()+excp.getStackTraceString());
        }
       
    }
}
Prema -Prema -
oh so sorry to bother you,Mistakenly I just forgot that I have to another class as well which you had already discussed.
Prema -Prema -
Thankyou very much,You were very helpful karan.Once again thanks for you help.