• Suraj Tripathi 47
  • ALL STAR
  • 5483 Points
  • Member since 2020
  • Salesforce Application Architect
  • Cloud Analogy


  • Chatter
    Feed
  • 166
    Best Answers
  • 0
    Likes Received
  • 6
    Likes Given
  • 0
    Questions
  • 1411
    Replies
@testSetup
    static void setup() {
        List<Account> accounts; 
        
        // get some account Ids -- we will just create a couple of dummies
        
        System.debug ('AccountProcessorTest.setup() entered');
        try {
             accounts.add (new Account (name = 'who cares'));
             accounts.add (new Account (name = 'who cares 2'));
             insert accounts;
             System.debug (accounts.size() + ' accounts created');
        }
        catch (Exception e) {
           System.debug('The following exception of type ' + e.getTypeName() + ' has occurred: ' + e.getMessage());
        }

The method consistently fails at the first accounts.add() call.  

09:37:52:002 USER_DEBUG [19]|DEBUG|The following exception of type System.NullPointerException has occurred: Attempt to de-reference a null object

There are no validation rules on account.   I can create this account via the UI supplying nothing but the name.

thanks in advance
public class UpdateOpportunity {
    public static void descriptionUpdate() {
        List<Opportunity> opp = [SELECT  Id,Name,Description From Opportunity WHERE StageName='Closed Won'limit 5];
        System.debug(opp);
        for ( Opportunity opps :opp)
        { 
            if(opps.Description == Null){
                opps.Description = 'This Opportunity is converted into Account';
            }
            else if(opps.Description == ''){
                opps.Description = 'This Opportunity is converted into Account';
            }
        }
              Update opp;
    }
}
  • July 29, 2021
  • Like
  • 0
Hi, 
My requirement is that when an account is created in the Salesforce dashboard, I need to make a rest call-out to an external service to post the account details. 
For this, I have created a trigger with after insert / after update that calls the appropriate apex class (which makes rest callout).
Can someone please confirm if I am going in the right direction?
Any template or reference code for performing this would be very helpful.
Thanks and regards.
Create lightning aura component with an apex controller to retrieve and display all order items related to the order as well as the discount and total order amounts?
  • July 25, 2021
  • Like
  • 0
Hi Everyone,
I am a newbie for creating an apex class. I create an Apex class to update a status. Then, I tried to create a test class. However, I received the below error message.

"Method does not exist or incorrect signature: void Updatestatus(ConsumableSample__c) from the type UpdateStatusController"

Could you please advise?

My Apex Class:

global without sharing class UpdateStatusController {
    @AuraEnabled
    global static Boolean Updatestatus(Id sampleid){
        try{
        
            ConsumableSample__c cs= [Select Id,Name,Process_Status__c from ConsumableSample__c where Id=:sampleid];
            cs.Process_Status__c = 'Cancel';
            update cs; 
            return true;
        }
        catch(Exception e){
            return false;
        }
    }
}


My Apex Test Class:

@isTest
public class UpdateStatusControllerTest {
  static testMethod void test1() {
      Date sDate = Date.newInstance(Date.today().Year(), 1, 1);
        Date eDate = Date.newInstance(Date.today().Year() + 1, 12, 31);
        Integer cnt = sDate.daysBetween(eDate);
        List<OlympusCalendar__c> ocList = new List<OlympusCalendar__c>();
        String cc = 'Singapore';
        for (Integer i=0; i<cnt; i++) {
            ocList.add(new OlympusCalendar__c(Date__c=sDate.addDays(i),Country__c = cc));
        }
        insert ocList;
        
        Date nowWD = Date.today();
        Account hospital = new Account();
        hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and Name='Hospital'].id;
        hospital.Name = '华佗扁鹊孙思邈';
        hospital.Adress__c = '医界仙葩,圣手仁心!';
        insert hospital;
        
        List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.Name = 'GI-Dept'];        
        
        Account dep = new Account();
        dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and Name = 'Gastoro Intestin'].id;
        dep.Name = '救济丸';
        dep.ParentId = strategicDep[0].Id;
        dep.Department_Class__c = strategicDep[0].Id;
        dep.Hospital__c = hospital.Id;
        insert dep;

        ConsumableSample__c request = new ConsumableSample__c(Hospital__c = hospital.Id,
        Expect_Arrive_Date__c = Date.today(),Expect_Use_Date__c = Date.today(),
        PIC__c = Userinfo.getUserId());
        insert new list<ConsumableSample__c> { request };

        test.startTest();
        UpdateStatusController.Updatestatus(request);
        test.stopTest();
  }
}
 
We need a email notification to be sent when a new lead is created for specific campaign.
I could not build a workflow on lead object as there is no campaign field, also campaign history is a related field. Please suggest
hey guys plz help ,how to create role heirarchry   like diretor then manger and executive and then how to assign profile to role plz guide me in deatil srep wise with help of sharing setting
Hello All,
Going in circles over how to resolve this.
I have Object Projects.  
The Project has a lookup to an Account
The account can reside on multiple Projects

So Project 1, Project 2, Project 3 all have the same loopup record 'Account Test'
So if field 'user' is Updated on Project 1.  How can I update the 'user' field on Project 2 and Project 3. 

Cheers,
P


 
Hi All,
I need to write Test Method for the code which is iteration collection object allSubs(means allSubscriptions) in BOLD.
I am able to write Test code for getConForProduct method but stuck with the later part.
Please help me!!
Thanks in Advance.
Apex Class:
Global class getContactsMatrixOrders {
    public static List<Map<String, Id>> getConForProduct(Map<String, Id> allProducts){
        // This method will return contacts who are eligible for C031 & C041 Testing done
        List<Map<String, Id>> conAndPro = new List<Map<String, Id>>();
        List<OrderApi__Subscription__c> allSubs = [SELECT id , OrderApi__Contact__r.id , OrderAPi__Contact__r.AccountId,OrderApi__Contact__r.apfy_products_received__c 
                                                   , OrderApi__Subscription_Plan__r.Name,OrderApi__Item__r.Name
                                                   FROM OrderApi__Subscription__c 
                                                   WHERE OrderApi__Status__c = 'Active'
                                                   AND OrderApi__Contact__r.CUSTOMER_CLASS__c = 'Member' 
                                                   AND OrderApi__Contact__r.Customer_Status__c = 'Active' 
                                                   AND OrderApi__Contact__r.DonorApi__Spouse__r.CUSTOMER_CLASS__c = 'Member' 
                                                   AND OrderApi__Contact__r.DonorApi__Spouse__r.Customer_Status__c = 'DECEASED'
                                                   AND OrderApi__Sales_Order_Line__r.OrderApi__Sales_Order__r.OrderApi__Source_Code__r.Name = 'WIDOW'];
        System.debug('allSubs'+allSubs);
        
        for(OrderApi__Subscription__c sub : allSubs){
            String itemName = sub.OrderApi__Item__r.Name;
            Id conId = sub.OrderApi__Contact__r.id;
            Id accId = sub.OrderAPi__Contact__r.AccountId;
            String proReceived = sub.OrderApi__Contact__r.apfy_products_received__c;
            List<String> productsReceived = new List<String>();
            if(proReceived!=null){
                productsReceived = proReceived.split(',');
            }
            Map<String,Id> singleCon = new Map<String, Id>();
            if((itemName == 'BASIC Membership for Surviving Spouse' || itemName == 'PREMIUM Membership for Surviving Spouse') && !productsReceived.contains('C031')){
                singleCon.put('conId',conId);
                singleCon.put('accId',accId);
                singleCon.put('proId',allProducts.get('C031'));
                conAndPro.add(singleCon);
            }else if(itemName == 'LIFE Membership for Surviving Spouse' && !productsReceived.contains('C041')){
                singleCon.put('conId',conId);
                singleCon.put('accId',accId);
                singleCon.put('proId',allProducts.get('C041'));
                conAndPro.add(singleCon);

            }
            
        }
        return conAndPro;
    }
    
  
  • July 21, 2021
  • Like
  • 0

I'm trying to fetch datetime in the below format but unable to get it the exact way i need it.

I need it as dd-mm-yyyy, hh:mm AM/PM, I'm using below func "Datetime.NOW().format()" which gives me as "7/19/2021, 6:28 AM". The date is coming as MM/DD/YYYY and time is correct format, but my requirement is DD/MM/YYYY , hh:mm AM/PM.

which func can be used?

Hey guys, what is your best suggested way to delete a record with it's related lists and it's look up fields??

I thought to query all records with SOSL by the record Id, but i found out it is not possible (Or there's a way?).

Another option is quering all related lists (with inner loops) and then loop on all related lists (with getPopulatedFieldsAsMap() and delete them list by list.

I would love to hear your best solution in performence terms.

Thanks!
 
Hi All,
I m new in lightning and try some basic .... can anyone help me out... Output is not showing properly

Component Program
=================
<aura:component >
    <aura:attribute name = "Amt" type = "decimal"/>
    <aura:attribute name = "ROI" type = "decimal"/>
    <aura:attribute name = "Tm" type = "decimal"/>
    <aura:attribute name = "Intr" type = "decimal"/>
    <aura:attribute name = "Toamt" type = "decimal"/>
    <lightning:card title = "Simple and Compound Interest" iconName= "standard:apps">
        <aura:set attribute = "actions">
        <lightning:buttonGroup>
            <lightning:button label = "Simple Interest" onclick = "{!c.simpme}" variant = "success"/>
            <lightning:button label = "Compound Interest" onclick = "{!c.compme}" variant = "brand"/>
        </lightning:buttonGroup>        
        </aura:set>
        <lightning:input label="Amount" value="{!v.Amt}"/>
        <lightning:input label="Rate of Interest" value="{!v.ROI}"/>
        <lightning:input label="Term" value="{!v.Tm}"/>
        <lightning:input label="Interest Accumulated at the End of Term" value="{!v.Intr}"/>
        <lightning:input label="Total Maturity Amount" value="{!v.Toamt}"/>   
    </lightning:card>
</aura:component>

Controller Program
===============
({
    simpme : function(component, event, helper) 
    {
        var P = component.get("v.amt");
        var T = component.get("v.ROI");
        var R = component.get("v.Tm"); 
        var res = (P*T*R)/100;
        component.set("v.intr", res);
        var tamt = parseInt(P)+parseInt(res);
        component.set("v.Toamt", tamt);        
    },    
    compme : function(component, event, helper) 
    {
        var P = component.get("v.amt");
        var T = component.get("v.ROI");
        var R = component.get("v.Tm");
        var res = P*(1+R/100)^T;
        component.set("v.intr", res);
        var tamt = parseInt(P)+parseInt(res);
        component.set("v.Toamt", tamt);
    }
})
#trigger code
trigger AccountTrigger1 on Account (after insert ) {
    if(trigger.isAfter && trigger.isInsert){
        AccountTriggerHandler1.accountDetails(trigger.new);
    }
}


#triggerhandlercode
public without sharing class AccountTriggerHandler1 {
    public static void accountDetails(list<Account> lstAccount)
    {
        list<Contact> lstContact = new list<Contact>();
       // list<Account> lstAccount = new list<Account>();
        set<Id> setAccountIds = new set<Id>();
        for(account acc : lstAccount){
            setAccountIds.add(acc.Id);  
            }
        if(setAccountIds.size() > 0){
            for(account acc : [SELECT Id , Name ,Contacts__c From Account Where Id In : setAccountIds]){
                    List<String> listofcon = acc.Contacts__c.split('\r\n');
           
                for(String con : listofcon){
                  Contact con1 = new Contact();
                     con1.firstname = con.substringBetween('=',',');
                    con1.LastName =con.substringBetween('=',',');
                        
                con1.MobilePhone = con.substringBetween('=',',');
             con1.Email = con.substringAfter('Email=').substringBefore(',');
             con1.AccountId = acc.Id;
              lstContact.add(con1);
             
                
            }
        }
        if(lstContact.size() > 0){ 
            insert lstContact;    
        }
        
  
    }
}
}

#please help me in this i am newbie to salesforce
 
I have a following apex Class for which I need to create a test class
public class GenerateFirstInvoices {
    @InvocableMethod
    public static void fetchOrderItems(List<Id> orderId) {
        List<OrderItem> oproduct = [SELECT Id, OrderId, Next_Billing_Date__c, OriginalOrderItemId, Payment_Term__c, Quantity, Remaining_Amount__c, Contact_Name__c, Contact_Address__c, Contact_Email__c, Contact_Number__c, Trn_Number__c, CRM_Number__c, FAR_or_HHS__c, Description, Created_Date__c FROM OrderItem WHERE OrderId = :orderId];
        Proforma_Invoice__c[] recordsToInsert = new Proforma_Invoice__c[0];
        Map<String, Integer> factors = new Map<String, Integer> {
            'Monthly' => 11,
            '2 Months' => 5,
            'Quarterly' => 3,
            '25%' => 3,
            'Semi Annually' => 1,
            '50%' => 1
        };
        for (OrderItem oitem : oproduct) {
            Integer factor = factors.get(oitem.Payment_Term__c);
            Integer DateInterval = 0;
            for (Integer i = 1; i <= factor; i++) {
                if (factor == 11) {
                    DateInterval = DateInterval + 30;
                } else if (factor == 5) {
                    DateInterval = DateInterval + 60;
                } else if (factor == 3) {
                    DateInterval = DateInterval + 90;
                } else if (factor == 1) {
                    DateInterval = DateInterval + 180;
                } else {
                    DateInterval = DateInterval;
                }
                recordsToInsert.add(new Proforma_Invoice__c(
                    Order__c = oitem.OrderId,
                    Order_Product__c = oitem.Id,
                    Rate__c = oitem.Remaining_Amount__c / factor,
                    Amount__c = oitem.Remaining_Amount__c / factor,
                    Expense_Budget__c = oitem.Remaining_Amount__c / factor,
                    Quantity__c = oitem.Quantity,
                    Status__c = 'Draft',
                    Paid_Status__c = 'No',
                    Contact_Name__c = oitem.Contact_Name__c,
                    Contact_Address__c = oitem.Contact_Address__c,
                    Contact_Email__c = oitem.Contact_Email__c,
                    Contact_Number__c = oitem.Contact_Number__c,
                    TRN_Number__c = oitem.TRN_Number__c,
                    FAR_or_HHS__c = oitem.FAR_or_HHS__c,
                    CRM_No__c = oitem.CRM_Number__c,
                    Created_Date__c = oitem.Created_Date__c + DateInterval
                ));
            }
        }
        insert recordsToInsert;
    }
}

Following is my test class with only 29% code coverage
@isTest
private class GenerateFirstInvoicesTEST {
    @isTest
    private static void fetchOrderItemsTEST() {
        String Payment_Terms = 'Monthly';
        Database.SaveResult dsr;
        OrderItem drOrderItem;
        drOrderItem=new OrderItem(OrderId='802x00000000000AAA',PricebookEntryId='802x00000000000AAA',Quantity=123,Payment_Term__c='Monthly',type__c='Subscription');
        dsr=Database.insert(drOrderItem,false);
        
        Test.startTest();
        try{
        GenerateFirstInvoices.fetchOrderItems(new List<Id>{dsr.getId()});
        }catch(Exception e){}
        try{
        GenerateFirstInvoices.fetchOrderItems(null);
        }catch(Exception e){}
        Test.stopTest();
        
        Test.startTest();
        try{
                //drOrderItem.Payment_Term__c == 'Monthly';
                Proforma_Invoice__c proforma = new Proforma_Invoice__c();            
                proforma.Rate__c = 100;
                proforma.Amount__c = 100;
                proforma.Order_Product__c = '802x00000000000AAA';
                proforma.Quantity__c = 1;
        
                insert proforma;
            
        }catch(Exception e){}
        Test.stopTest();
    }
    @isTest
    private static void GenerateFirstInvoicesTEST(){
        GenerateFirstInvoices obj = new GenerateFirstInvoices();
    }
}

Can anyone please help me create a test class for my apex class & guide me on how to get to the section inside loop using test code.
public class ContactTriggerHandler {
   
     public static void getContactDetails(List<Contact> listOfContacts ,Map<Id,Contact> mapOfContact)
     {
      Set<Id> setAccIds = new Set<Id>();
         for(Contact con: listOfContacts != null ? listOfContacts :mapOfContact.values()){
             if(mapOfContact == null && con.AccountId != null){
                 setAccIds.add(con.AccountId);
             }
            if(listOfContacts  != null && mapOfContact != null 
                     && (con.AccountId != mapOfContact.get(con.Id).AccountId || con.FirstName!=mapOfContact.get(con.Id).FirstName
                         || con.LastName != mapOfContact.get(con.Id).LastName)){            
                if(con.AccountId != null)
            {
                setAccIds.add(con.AccountId);
                
            }
             if(mapOfContact.get(con.Id).AccountId != null)
             {
              setAccIds.add(mapOfContact.get(con.Id).AccountId);   
             }
                         }
             if(listOfContacts == null && con.AccountId != null){
                   setAccIds.add(con.AccountId);
             }
         }   
             if(setAccIds.size() > 0){
                 Map<Id , Account> mapOfAccount = new Map<Id , Account>();
                 for(Contact con1: [SELECT id, AccountId , Name FROM Contact WHERE AccountId IN : setAccIds]){
                     if(!mapOfAccount.containskey(con1.AccountId)){
                         mapOfAccount.put(con1.AccountId, new Account (Id = con1.AccountId , Contact_Details__c =''));
                     }
                         mapOfAccount.get(con1.AccountId).Contact_Details__c += con1.Name + '\n';
                     
                     if(mapOfAccount.size() > 0){
                        update mapOfAccount.values();
                     }
                        
                 }
             }
         
          }
}
    
         

         
Hello, I get an error when I want to build an apex class:
User-added imageCould you give me a guide how I can solve this error?
Hello, I want to build a permission set for a certain group of people to be able to edit the field email, mobile and phone on user details. Could you give me a guide how it can be made?
How can I set Data Security in such a way that I am able to hide particular field of an object, where other user has Standard user profile
Hi everyone,the below is the class which i have written,tried testclass for that class is that crct way of writing testclass for that class.
class:
public class opp_paginationcontroller {
    Public Integer size{get;set;} 
    Public Integer noOfRecords{get; set;} 
    public List<SelectOption> paginationSizeOptions{get;set;}
         
    public opp_paginationcontroller(){
        size=10;
        paginationSizeOptions = new List<SelectOption>();
        paginationSizeOptions.add(new SelectOption('5','5'));
        paginationSizeOptions.add(new SelectOption('10','10'));
        paginationSizeOptions.add(new SelectOption('20','20'));
        paginationSizeOptions.add(new SelectOption('50','50'));
        paginationSizeOptions.add(new SelectOption('100','100'));
    }
     
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {                
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                      [select id,Name,AccountId,Account.name,Amount,StageName,CloseDate,LastModifiedDate from Opportunity]));
                setCon.setPageSize(size);  
                noOfRecords = setCon.getResultSize();
            }            
            return setCon;
        }
        set;
    }
     
    // It Changes the size of pagination
    public PageReference refreshPageSize() {
         setCon.setPageSize(size);
         return null;
    }
 
    // Initialize setCon and return a list of record    
     
    public List<Opportunity> getOpportunities() {
         return (List<Opportunity>) setCon.getRecords();
    }
}
testclass:
@isTest
public class Testopp_paginationcontroller {
@isTest
    static void invoke(){
       opportunity o=new opportunity();
        o.name='testopp';
        o.stageName='prospecting';
        o.closeDate=system.today();
        insert o;
        Test.startTest();
        opp_paginationcontroller opp=new opp_paginationcontroller();
       
        opp.refreshPageSize();
        opp.getOpportunities();
        Test.stopTest();
    }
}

Hi all , 

i have one requiremnt i need to get numaric value from string field how can i get in apex
Eg: String name= 'Auto - New Business - Count;Premium - 500';
from above string name i nedd to fetch 500 how can i do that 
i used one method 
String name= 'Auto - New Business - Count;Premium - 500';
String substr = name.substringAfter('-');
system.debug('substr'+substr);
but hear i am getting - New Business - Count;Premium - 500' total value but i need only 500 .
how can i do that some one help me please 

Thank you 
Surender Reddy

 

Hello, I keep getting an ApexApplication email saying:

Failed to invoke future method 'public static void UploadDocument(String)' on class 'S3Controller' for job id '7073l0000FSMaBy'

caused by: System.LimitException: Query of LOB fields caused heap usage to exceed limit.



The line of code that is causing the error is this:
List<ContentVersion> versions=[SELECT VersionData,Title,ContentDocumentId,FileExtension FROM ContentVersion WHERE ContentDocumentId = :ids AND IsLatest = true];

How can I change my code so that if that error comes up, I still query the files but ONLY query the 1st file (as a way of avoiding the error)?


I TRIED this:

        List<ContentVersion> versions = new list<contentversion>();
        try{
        versions=[SELECT VersionData,Title,ContentDocumentId,FileExtension FROM ContentVersion WHERE ContentDocumentId = :ids AND IsLatest = true];
        }
        catch (exception e){
            versions=[SELECT VersionData,Title,ContentDocumentId,FileExtension FROM ContentVersion WHERE ContentDocumentId = :ids AND IsLatest = true limit 2];
        }

BUT it didn't work. I am still getting the same ApexApplication error email. 
@testSetup
    static void setup() {
        List<Account> accounts; 
        
        // get some account Ids -- we will just create a couple of dummies
        
        System.debug ('AccountProcessorTest.setup() entered');
        try {
             accounts.add (new Account (name = 'who cares'));
             accounts.add (new Account (name = 'who cares 2'));
             insert accounts;
             System.debug (accounts.size() + ' accounts created');
        }
        catch (Exception e) {
           System.debug('The following exception of type ' + e.getTypeName() + ' has occurred: ' + e.getMessage());
        }

The method consistently fails at the first accounts.add() call.  

09:37:52:002 USER_DEBUG [19]|DEBUG|The following exception of type System.NullPointerException has occurred: Attempt to de-reference a null object

There are no validation rules on account.   I can create this account via the UI supplying nothing but the name.

thanks in advance
public class UpdateOpportunity {
    public static void descriptionUpdate() {
        List<Opportunity> opp = [SELECT  Id,Name,Description From Opportunity WHERE StageName='Closed Won'limit 5];
        System.debug(opp);
        for ( Opportunity opps :opp)
        { 
            if(opps.Description == Null){
                opps.Description = 'This Opportunity is converted into Account';
            }
            else if(opps.Description == ''){
                opps.Description = 'This Opportunity is converted into Account';
            }
        }
              Update opp;
    }
}
  • July 29, 2021
  • Like
  • 0
public with sharing class StackItCalculationInfo 
{
       public class UserInput
       {
        @InvocableVariable(required = true)
        public String ItemId;
        @InvocableVariable(required = true)
        public String ClientId;
        @InvocableVariable(required = true)
        public String QuoteId;

    }
     
    

    @InvocableMethod(label='Calculation Info')
    public static void CalcInfo(List<UserInput> userInputs)
    {
           UserInput userInput = userInputs[0];
           string jsonData = JSON.serialize('{"ItemId":' + userInput.ItemId + ', "ClientId":' + userInput.ClientId + ', "QuoteId":' + userInput.QuoteId +'}');
        doCalloutFromFuture(jsonData);
               
    }
    
    @future(callout=true)
    public static void doCalloutFromFuture(string jsonData){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
           request.setTimeout(25000);
        request.setEndpoint('https://endpoint');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Set the body as a JSON object
        request.setBody(jsonData);
        HttpResponse response = http.send(request);
        
        // Parse the JSON response
        if (response.getStatusCode() != 200) 
        {

            System.debug('The status code returned was not expected: ' +
            response.getStatusCode() + ' ' + response.getStatus());
        } 
        else 
        {

            System.debug(response.getBody());
        }
    }


}
public static void countContactDetails(List<Contact> listContacts, Map<Id,Contact> mapOldContacts){
     Set<Id> setAccountId = new Set<Id>();
     Map<Id,Account> mapOfAccount = new Map<Id,Account>();
        if( mapOldContacts == null || mapOldContacts.isEmpty() ) {
            for( Contact objCont : listContacts ) {
                if( objCont.AccountId != null ) {
                    setAccountId.add( objCont.AccountId );
                }
            }
        }
        else if( mapOldContacts != null && !mapOldContacts.isEmpty()) {
            for( Contact objCont : listContacts ) { 
                if( objCont.AccountId != null 
                && mapOldContacts.get( objCont.Id ).AccountId != objCont.AccountId ) {
                    setAccountId.add( objCont.AccountId );
                    if( mapOldContacts.get( objCont.Id ).AccountId != null ) {
                        setAccountId.add( mapOldContacts.get( objCont.Id ).AccountId );
                    }
                }
                else if( objCont.AccountId == null && mapOldContacts.get( objCont.Id ).AccountId != objCont.AccountId ) {
                    setAccountId.add( mapOldContacts.get( objCont.Id ).AccountId );
                }
            }
        }
        if( !setAccountId.isEmpty() ) {
            List<Account> listAccount = new List<Account>();
            for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount 
                                       FROM Contact
                                       WHERE AccountId in: setAccountId 
                                       GROUP BY AccountId]){
                                           Account a = new Account();
                                           a.Id = (Id) ar.get('AcctId');
                                           a.Total_Contacts__c = (Integer) ar.get('ContactCount');
                                           listAccount.add(a);

            
        }
   if( !listAccount.isEmpty() ) {
                update listAccount;
            }  
 }
    
             if( !setAccountId.isEmpty() ) {
                  List<Account> listAccount1 = new List<Account>();
            List<AggregateResult> results = [Select AccountId ,Count(Id) ContactCount, Contact_Status__c str from Contact  WHERE AccountId in: setAccountId GROUP BY AccountId, Contact_Status__c];
                  Integer activecount = 0;
                  Integer inactivecount = 0;
                 for (AggregateResult ar : results)  {
                    if(ar.get('str')=='Active'){
                           
                        activecount += (Integer)ar.get('ContactCount');
                     }
                      if(ar.get('str')=='Inactive'){
                          inactivecount = (Integer)ar.get('ContactCount');  
                     }
                     //a.Total_Contacts__c = (Integer) ar.get('ContactCount');
                    // mapOfAccount.put((ID)ar.get('AccountId') , new Account(Id = (Id)ar.get('AccountId'),Total_Active_Contacts__c = activecount ,Total_Inactive_Contacts__c = inactivecount));
                      Account a1 = new Account();
                       a1.Id = (Id) ar.get('AccountId');
                       a1.Total_Active_Contacts__c = activecount;
                     a1.Total_Inactive_Contacts__c = inactivecount;
                  listAccount1.add(a1);
                 }

system.debug('Mapofaccount=='+ listAccount1);
    
 }
    } 
<apex:page controller="Registrationcontroller" id="theRepeat" sidebar="false" showHeader="true">
    <apex:form >
        <apex:pageBlock id="pg1" >
            <apex:messages />
            <apex:pageBlockSection columns="1" >
                <apex:inputField label="FirstName" value="{!reg1.FirstName__c}"/>
                <apex:inputField label="LastName" value="{!reg1.LastName__c}"/>
                <apex:inputField label="Email" value="{!reg1.Email__c}"/>
                <apex:inputField label="Hotel Commands" value="{!hotel.Hotel_Commands__c}"/>
                <apex:inputField label="Air Commands" value="{!air.Air_Commands__c}"/>
                <apex:inputField label="CheckInDate" value="{!hotel.Check_In_Date__c}"/>
                <apex:inputField label="CheckOutDate" value="{!hotel.Check_Out_Date__c}"/>
                <apex:inputField label="Arrival" value="{!air.Arrival__c}"/>
                <apex:inputField label="Departure" value="{!air.Departure__c}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton value="save" action="{!saveaction}" rerender="pg1,theTable" />
                
            </apex:pageBlockButtons> 
        </apex:pageBlock>
        <apex:pageBlock >
            <apex:dataTable value="{!registerlist}" var="regvalue" id="theTable" width="100%">
                <apex:facet name="caption">Registration List</apex:facet>
                <apex:column headerValue="Reg ID"><apex:outputText value="{!regvalue.Name}" /> </apex:column>
                <apex:column headerValue="FirstName"><apex:outputText value="{!regvalue.FirstName__c}" /> </apex:column>
                <apex:column headerValue="LastName"><apex:outputText value="{!regvalue.LastName__c}" /> </apex:column>
                <apex:column headerValue="Email"><apex:outputText value="{!regvalue.Email__c}" /> </apex:column>
                <apex:repeat value="{!regvalue.Hotels__r}" var="c">
                    <apex:column headerValue="Hotel ID"> <apex:outputText value="{!c.Name}"/></apex:column>
                    <apex:column headerValue="CheckInDate"> <apex:outputText value="{!c.Check_In_Date__c}"/></apex:column>
                    <apex:column headerValue="CheckOutDate"><apex:outputText value="{!c.Check_Out_Date__c}"/></apex:column>
                    <apex:column headerValue="Hotel Commands"><apex:outputText value="{!c.Hotel_Commands__c}"/></apex:column>
                </apex:repeat>
                <apex:repeat value="{!regvalue.AirTravels__r}" var="d">
                    <apex:column headerValue="Air ID"><apex:outputText value="{!d.Name}"/></apex:column>
                    <apex:column headerValue="Arrival"><apex:outputText value="{!d.Arrival__c}"/></apex:column>
                    <apex:column headerValue="Departure"><apex:outputText value="{!d.Departure__c}"/></apex:column>
                    <apex:column headerValue="Air Commands"><apex:outputText value="{!d.Air_Commands__c}"/></apex:column>
                </apex:repeat>
                <apex:column >
                    <apex:pageBlock>
                        <apex:pageBlockButtons>
                            <apex:commandButton action="{!ProcessSelected}" value="Show Selected accounts" reRender="block2"/>
                        </apex:pageBlockButtons>
                        <apex:pageBlockSection columns="2">
                           <apex:pageBlockTable value="{!wraplist}" var="wrapl">
                               <apex:column>
                                   <apex:facet name="header">
                                       <apex:inputCheckbox />
                                   </apex:facet>
                                   <apex:inputCheckbox value="{!wrapl.isSelected}" id="InputId"/>
                               </apex:column>
                               <apex:column value ="{!wrapl.reg4.Name}"/>
                               <apex:column value ="{!wrapl.reg4.FirstName__c}"/>
                               <apex:column value ="{!wrapl.reg4.LastName__c}"/>
                               <apex:column value ="{!wrapl.reg4.Email__c}"/>
                               <apex:repeat value="{!wrapl.Hotels__r}" var="hotelwrap">
                                <apex:column value ="{!hotelwrap.reg4.Name}"/>
                               <apex:column value ="{!hotelwrap.reg4.Check_In_Date__c}"/>
                               <apex:column value ="{!hotelwrap.reg4.Check_Out_Date__c}"/>
                               <apex:column value ="{!hotelwrap.reg4.Hotel_Commands__c}"/>
                                </apex:repeat>   
                               <apex:repeat value="{!wrapl.AirTravels__r}" var="airwrap"> 
                               <apex:column value ="{!airwrap.reg4.Name}"/>
                               <apex:column value ="{!airwrap.reg4.Arrival__c}"/>
                               <apex:column value ="{!airwrap.reg4.Departure__c}"/>
                               <apex:column value ="{!airwrap.reg4.Air_Commands__c}"/>
                               </apex:repeat>
                               
                            </apex:pageBlockTable>
                            <apex:pageBlockTable value="{!selectedRegistration}" var="sa" id="block2">
                                <apex:column value="{!sa.Name}"/>
                                <apex:column value="{!sa.FirstName}"/>
                                <apex:column value="{!sa.LastName}"/>
                                <apex:column value="{!sa.Email}"/>
                                <apex:repeat value="{!sa.Hotels__r}" var="hotelsa"> 
                                <apex:column value="{!hotelsa.Name}"/>
                                    <apex:column value="{!hotelsa.Check_In_Date__c}"/>
                                    <apex:column value="{!hotelsa.Check_Out_Date__c}"/>
                                    <apex:column value="{!hotelsa.Hotel_Commands__c}"/>
                                </apex:repeat> 
                                <apex:repeat value="{!sa.AirTravels__r}" var="airsa"> 
                                <apex:column value="{!airsa.Name}"/>
                                    <apex:column value="{!airsa.Arrival__c}"/>
                                    <apex:column value="{!airsa.Departure__c}"/>
                                    <apex:column value="{!airsa.Air_Commands__c}"/>
                                </apex:repeat> 
                               
                              
                            
                                
                            </apex:pageBlockTable>
                            
                        </apex:pageBlockSection>
                    </apex:pageBlock>
                   
                    <apex:commandLink value="Edit" action="{!editfunction}" rerender="pg1">
                        <apex:param name="cid" value="{!regvalue.id}" assignto="{!editid}"/>
                    </apex:commandLink> || 
                    <apex:commandLink value="Delete" action="{!deletefunction}" rerender="pg1,theTable">
                        <apex:param name="cid" value="{!regvalue.id}" assignto="{!editid}"/>
                    </apex:commandLink> 
                </apex:column>
            </apex:dataTable>
        </apex:pageBlock>
    </apex:form>         
</apex:page>




------------------------------ APEX CLASS-------------------------------------------

public class Registrationcontroller {
    public Registration1__c reg1 {get;set;}
    public String editid {get;set;}
    public Hotel__c hotel {get;set;}
    public AirTravel__c air {get;set;}
    public list<regwrapper> wraplist {get;set;}
    public list<Registration1__c> reglist {get;set;}
    public list<Hotel__c> hotellist {get;set;}
    public list<AirTravel__c> airlist {get;set;}
    public list<Registration1__c> selectedRegistration {get;set;}
    public Registrationcontroller()
    {
        reg1 = new Registration1__c();
        hotel = new Hotel__c();
        air = new AirTravel__c();
        
        if(wraplist == null)
          {
            wraplist = new list<regwrapper>();
            for(Registration1__c reg3:[SELECT id,Name,FirstName__c,LastName__c,Email__c, (SELECT Id,Name, Check_In_Date__c, Check_Out_Date__c, Hotel_Commands__c FROM Hotels__r),
                                       (SELECT Id,Name, Arrival__c, Departure__c, Air_Commands__c FROM AirTravels__r) FROM Registration1__c])
                                       {
                                           wraplist.add(new regwrapper(reg3));
                                       
                                       }
       
          
          }
        
        
        
    }
    
    public void processSelected(){
        selectedRegistration = new list<Registration1__c>();
        for(regwrapper wrapobj:Wraplist){
            if(wrapobj.isSelected==true)
            {
                selectedRegistration.add(wrapobj.reg4);
               }
        }
    }
        
    
   
    
    public class regwrapper{
        public Registration1__c reg4{get;set;}
        
        public boolean isSelected{get;set;}
        
        public regwrapper(Registration1__c reg3)
        {
            reg4 = reg3;
            isselected = false;
        }
        
        
    }
    
    
    
    public List<Registration1__c> getregisterlist(){
        List<Registration1__c> listreg= new List<Registration1__c>();
        listreg=[SELECT Id, Name, FirstName__c, LastName__c, Email__c, (SELECT Id,Name, Check_In_Date__c, Check_Out_Date__c, Hotel_Commands__c FROM Hotels__r),
                 (SELECT Id,Name, Arrival__c, Departure__c, Air_Commands__c FROM AirTravels__r) FROM Registration1__c];
        return listreg;
    }
  public void editfunction() {
        system.debug('editfunction inside===>'+editid);
                reg1=[SELECT Id,Name, FirstName__c, LastName__c, Email__c, (SELECT Id,Name, Check_In_Date__c, Check_Out_Date__c, Hotel_Commands__c FROM Hotels__r),
                 (SELECT Id,Name, Arrival__c, Departure__c, Air_Commands__c FROM AirTravels__r)
              FROM Registration1__c where id=:editid];
       
        
        }
    public void deletefunction() {
        system.debug('editfunction inside===>'+editid);
        
        List<Registration1__c>  reg2=[SELECT Id, Name, FirstName__c, LastName__c, Email__c
                                      FROM Registration1__c  where id=:editid];
       delete reg2;
       ApexPages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.INFO,'Record deleted successfully'));
    }
    
    
    public void saveaction()
    {
        system.debug('saveaction inside===>'+reg1);
        try{
            upsert reg1;
            if(reg1.Id !=null){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.INFO,'Record saved successfully'));
                
                if(hotel != null)
                {
                    hotel.Registration1__c = reg1.id;
                    upsert hotel;
                }
                if(air != null)
                {
                    air.Registration1__c = reg1.id;
                    upsert air;
                }
                
            } else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.ERROR,'Record not saved')); 
            }
            reg1 = new Registration1__c();
            hotel = new Hotel__c();
            air = new AirTravel__c();
        }
        Catch(Exception e)  
        {
            System.debug(e.getMessage());
        }
    }
}








please checkit and tellme how to create it
when i check in schema builder then also i don't see any relationship between OpportunityLineItem and PriceBookEntry

But in object manager, when i check OpportunityLineItem object it doesn't have any field or relationship named PricebookEntryIdUser-added image
Trying to write a trigger for below need.
- Have a custom pick field on Lead - (Campaign_Type__c. ----- values - Webinar, Tradeshow, Events). This custom field is replica of Type field on Campagin. 
- Campaign - Standard pick Field - Type (Values - Webinar, Tradeshow, Events)

Whenever a lead is created a its gets associated to a campaign, i need the Type pickvalue from Campaign to be copied to Campaign_Type__c field on Lead for the associated Campagin. 
There can be cases where the campaign is assoicated to multiple campaigns, in such cases the lastest associated campaign Type should be updated on Campaign_Type__C on Lead. 

Here is something i am trying, any help is much appreciated!

```
trigger UpdateCampaignTypeonLead on CampaignMember (after insert) {

for(CampaignMember camMember : Trigger.New){
        campaignMemberIdSet.add(camMember.id);
    }

{
        set<Id> leadIds = new set<Id>();        
       list<Lead> leadList = new list<Lead>();
        set<Id> campIds = new set<Id>();
        map<Id, CampaignMember> leadCampaign = new map<Id, CampaignMember>();   
        
        // Iterate through the list of new Campaign Members
        for (CampaignMember camMember : System.Trigger.New)
        {
            // Add Lead to set to be queried
            leadIds.add(camMember.LeadId);
            
            //Add Campaign Ids to the campIds set
            campIds.add(camMember.CampaignId);
            
            // Add Lead and CampaignMember to map
            leadCampaign.put(camMember.LeadId, camMember);
        
        }
{
map<Id,Campaign> campmap = new map <Id,Campaign>([select Id, Type from Campaign where id in: campIds]);
for(Lead thisLead : [Select Id, Campaign_Type__c from Lead where Id in : leadIds and isConverted=false])

Campaign camp = campmap.get(leadCampaign.get(thisLead.Id).CampaignId); 
 thisLead.Campagin_Type__c = camp.Type

}
}

```
Hello, 

I am trying to come up with a trigger but no luck. The logic is on the account object which parent accounts cannot have parent accounts and child accounts cannot have child accounts.

Any help would be great!

Thank you
public class ProductLighting {
 @AuraEnabled
    public static Opportunity fetchOpportunityLineItem(String opId) {
        Opportunity returnContactList = new Opportunity();
        
        returnContactList = [Select Id,StageName,(SELECT Id,UnitPrice,Quantity,Discount__c, From OpportunityLineItems Where Approved_c=True) from Opportunity Where Id=:opId];
        
        return returnContactList ;
    }
    
    
    @AuraEnabled
    public static List < String > Records(List < String > lstRecordId) {
        List < String > Msg = new List < String > ();
        List < OpportunityLineItem > lstDeprecateRec = [select Id,Product_Deprecated__c from OpportunityLineItem where id IN: lstRecordId];
        for(OpportunityLineItem ord:lstDeprecateRec)
        {
            ord.Product_Deprecated__c=True;
        }
        allowupdateopplineitem__c obj = allowupdateopplineitem__c.getInstance('isallowed');
        
        obj.allowupdate__c = true;
        update obj;
        Database.SaveResult[] DR_Dels = Database.update(lstDeprecateRec, false);
         obj.allowupdate__c = false;
        update obj;
        for (Database.SaveResult dr: DR_Dels) {
            if (dr.isSuccess()) {
                system.debug('successful Deprecate Opportunity Line Items');
            } 
            }
        return Msg;
        
    }
}
 
While uploading two small contentassets with sfdx I get a "storage limit exceeded". But the storage usage looks good
User-added image
How can this happen? How can I upload my files?
Hi,
I added a lwc in a package. How to remove it now? I want to delete it.
Hi,
I want to load 20000 accounts and 20000 contacts in my developer org but I get: 
storage limit exceeded error ..
I deleted all the other data present in the org and still have this issue
is there a way to have this amount of data ( 20000 accounts and 20000 contacts) 
in a developer org  please ?
Hey all,
I wanna delete custom object from a managed released package. How can I make it possible. ?
Your little help would be enough.
thank you all in advance.
 
I am mapping accout with a custom object In a trigger. how can I access custom object fields from Account. 
Here is my code..

Map<ID, Account> mapaccounts = new Map<ID, Account>([SELECT Id, Name, phone FROM Account]);
    List<custom_object__c> RecodList = new List<custom_object__c>();
    RecodList.add( new custom_object__c(Name=mapaccounts.get().Name,  Phone__c =mapaccounts.get().Phone, custom_field__c =mapaccounts.get().account_field__c ))
We have a public site and we want to get the site logo from the document. The associated Document record is not returned on querying by a guest user with user license "Guest User". But it returns a row if internal SF user queries for the same. Can you please suggest a solution for the same?
Hi Team,

I have an object called Leave Tracker, where users enter the leave date, reason, and number of hours, user can create more than one record in a day with different hours, ex: 1 entry with 2 hours and another entry with 4 hours. but my request is that we should not allow a user to create/update a leave tracker record if the leave hours are more than 8 in a single day per user?

any help is appreciated.

Thanks,
Madhu