• Azusfdc
  • NEWBIE
  • 5 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 13
    Questions
  • 11
    Replies
Trigger updatetrigger on Account (after update)
{
    helperclassnew.idscaputure(Trigger.new);
    if(Trigger.isupdate)
    helperclassnew.updatechildrec();
}
 
public class helperclassnew{
    

    public static void idscaputure(List<account> acclist,Set<Id> acctids,map<Id,Account> mapaccount)
    {
        for(account acc:acclist)
        {
            acctids.add(acc.id);
            mapaccount.put(acc.id,acc);
        }
    }
    
    
    public static void updatechildrec(list<Contact> listContact,Set<Id> acctids,map<Id,Account> mapaccount)
    {
        listContact = [SELECT MailingStreet, MailingCity,Description,AccountId FROM Contact 
        WHERE AccountId IN : acctIds];
        
        if(listContact.size() > 0) {
        for(Contact con : listContact) {
            con.Phone= mapAccount.get(con.AccountId).Phone;
            con.Description= mapAccount.get(con.AccountId).Description;
        }
        update listContact;
        }           
    }
    
    
}

 
trigger trgset on contact (after insert)
{
    List<Contact> conToUpdate = new List<Contact>() ;
     for(Account acc : [Select Name,(Select id ,LastName from Contacts where id in: trigger.new ) from Account  ] )
     {
         for(Contact con : acc.Contacts)
         {
             con.LastName = acc.Name ;
             conToUpdate.add(con) ;
         }
    }
    if(conTOUpdate.size() > 0)
    {
       update conTOUpdate ;
    }
}
 
Trigger Childtoconupdate on ChildtoContact__c(after insert)
{
	List<ChildtoContact__c> ctlist=new List<ChildtoContact__c>();
	for(contact con:[Select lastname,(select id,name from ChildtoContactsrelation__r where id in:trigger.new)
		from Contact])
	{
		for(ChildtoContact__c ct:con.ChildtoContactsrelation__r)
		{
			ct.name=con.LastName;
			ctlist.add(ct);
		}
	}
	if(ctlist.size()>0)
	{
		Update ctlist;
	}
}

 
Here my scenario is whenever i am adding opp line items to opportunity then mapping with opportunity and opp line items record should  be inserted in junction object History tracking below is the code written only getting opp line items records in History tracking not showing records in opportunity related list
User-added image
User-added image
Trigger OpportunityPrdHisTrack on OpportunityLineItem (after insert){
    
    if(Trigger.isafter && Trigger.isinsert)
    {
        HelperClass_one.opplineiteminsert(Trigger.new);
    }
}
 
public class HelperClass_one{
    public static void opplineiteminsert(List<OpportunityLineItem> opplinelist)
    {
        list<HistoryTracking__c> htlist=new list<HistoryTracking__c>();
        for(OpportunityLineItem oppline:opplinelist)
        {

            HistoryTracking__c ht=new HistoryTracking__c();
            ht.product__c=oppline.ProductId;
            ht.Opportunity__c=null;
            ht.Name=oppline.Name;
            ht.ProductDescription__c=oppline.Description;
            ht.ProductCode__c=oppline.ProductCode;
            htlist.add(ht);
            
        }
        insert htlist;
    }
}

 
Trigger OpportunityPrdHisTrack on OpportunityLineItem (after insert){
    
    if(Trigger.isafter && Trigger.isinsert)
    {
        HelperClass_one.opplineiteminsert(Trigger.new);
    }
}
 
public class HelperClass_one{
    public static void opplineiteminsert(List<OpportunityLineItem> opplinelist)
    {
        list<HistoryTracking__c> htlist=new list<HistoryTracking__c>();
        for(OpportunityLineItem oppline:opplinelist)
        {

            HistoryTracking__c ht=new HistoryTracking__c();
            ht.product__c=oppline.id;
            ht.Name=oppline.Name;
            ht.ProductDescription__c=oppline.Description;
            ht.ProductCode__c=oppline.ProductCode;
            htlist.add(ht);
            
        }
        insert htlist;
    }
}

 
My Requirement is I want to delete the records in account and case object before that need to take backup should be inserted in document with .csv file based on lastmodifieddate and createddate before's last 10 months data i am deleting below is code i am written one is batch apex and normal class?
Batch Apex:
/*
  * @description   Batch class for implementing the Data Retention Rule for record deletion based on the values populated in the DRR record
  */
global class BATCH_DataRetention implements Database.Batchable<SObject> {
    
    private static final String COMP = 'Completed';
    private String queryString = null;
    private String queryParentString = null;
    private Boolean callScheduler = false;
    private List<Data_Retention_Rule__c> drrListChildRules = new List<Data_Retention_Rule__c>();
    //Keep a reference to the Data Retention Batch record that is being used to run this batch
    private DataRetentionBatch__c drbObject = new DataRetentionBatch__c();
    
    global BATCH_DataRetention(String query, List<Data_Retention_Rule__c> listChildRules, DataRetentionBatch__c drbObj, Boolean callSchedulerClass) {
        
        drrListChildRules = listChildRules;
        
        if(drrListChildRules != null && !drrListChildRules.isEmpty()) {
            queryParentString = query;
            queryString = 'SELECT Id ' + query.substring(query.lastIndexOf('FROM'),query.length());
            
            system.debug('query string-->'+queryString+'--main query--'+queryParentString);
        }
        else {
            queryString = query;
        }
        
        drbObject = drbObj;
        callScheduler = callSchedulerClass;
    }
    
    /**
      * @description       This method queries the soql query and passes the List of records obtained to the execute method.
      * @param             Database.BatchableContext object
      * @return            Database.QueryLocator
      * @throws            NA
      */
    global Database.QueryLocator start(Database.BatchableContext ctx) {
        return Database.getQueryLocator(queryString + ' LIMIT 50000000');
    }
    
    /**
      * @description       Method executes the query and return the QueryLocator Object
      * @param             Database.BatchableContext object
      * @param             scope
      * @return            NA
      * @throws            NA
      */
    global void execute(Database.BatchableContext ctx, List<sObject> scope) {
        List<sObject> sObjectList = new List<sObject>();
        List<sObject> sObjectParentList = new List<sObject>();
        List<Case> cs = new List<Case>();
        Document d = new Document();
        string header = ' \' '+queryParentString.substring(queryParentString.lastIndexOf('FROM')) + ' \' ';
        string finalstr = header;
        system.debug('scope size--->'+scope.size());
        // for each child rule query, check the related records for each item in the batch of parent records,
        // if the parent qualifies for archival/deletion, take the action immediately
        if(drrListChildRules != null && !drrListChildRules.isEmpty()) {
            sObjectParentList = Database.query(queryParentString + ' AND Id IN: scope LIMIT ' + scope.size());
            sObjectList = DataRetentionQueryBuilder.qualifyRecordsToBeDeleted(sObjectParentList,drrListChildRules);
             Boolean result = queryParentString.contains('Account');
              if(result == true){
              // acc.add(sObjectList);
              }
              else{
              // cs.add((ID)sObjectParentList.get('Case'));
              }
        }
        else {
            sObjectList = DataRetentionQueryBuilder.qualifyRecordsToBeDeleted(scope,drrListChildRules);
        }
        
        // delete the parent records that qualify for archival/deletion
        if(sObjectList != null && !sObjectList.isEmpty()) {
            Database.DeleteResult[] drList = Database.delete(sObjectList, false);
        }
    }
    
    /**
      * @description       Finish method to update the Data Retention Batch record with the 
      * @param             Database.BatchableContext object
      * @return            void
      * @throws            NA
      */
    global void finish(Database.BatchableContext ctx) {
        try {
            AsyncApexJob asyJob = [SELECT Status FROM AsyncApexJob WHERE Id =: ctx.getJobId() LIMIT 1];
            
            // if job finished successfully update the drb record status to completed
            if(COMP.equalsIgnoreCase(asyJob.Status)) {
                drbObject.Status__c = COMP;
            }
            
            // update the try count for tracking purpose
            drbObject.Try_Count__c += 1;
            update drbObject;
            
            if(callScheduler) {
                //Build the system time of now + 30 minutes to schedule the batch apex again
                Datetime sysTime = System.now();
                
                // to be able to catch Async Exception in test class
                if(!Test.isRunningTest()) { sysTime = sysTime.addMinutes(30); }
                
                String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();
                SCH_DataRetention schDR = new SCH_DataRetention();
                //Schedule the next job, and give it the system time so name is unique
                System.schedule('scheduleDataRetentionRuleJobs' + sysTime.getTime(),chron_exp,schDR);
            }
        }
        // since it is not possible to catch a query exception in the test class, however, the system might throw an exception,
        // hence adding a generic exception block
        catch (Exception e) { /* Log the exception in a custom object */ }
    }
}
 
/**
  * @description   This class acts as a helper class for the scheduler SCH_DateRetention and batch BATCH_DataRetention
  */
public with sharing class DataRetentionQueryBuilder {
    
    /**
      * @name             populateMapParentChildListRules
      * @description      Method is called to populate a map with the parent rule as key and list of child rules as values
      * @param            Set<String>
      * @return           Map<sObject,List<sObject>>
      * @throws           NA
      */
    public static Map<Data_Retention_Rule__c,List<Data_Retention_Rule__c>> populateMapParentChildListRules(Set<String> drrSetParentIds) {
    
        Map<Data_Retention_Rule__c,List<Data_Retention_Rule__c>> mapParentChildListRules = new Map<Data_Retention_Rule__c,List<Data_Retention_Rule__c>>();
        
        try {
            List<Data_Retention_Rule__c> parentDrrList = new List<Data_Retention_Rule__c>();
            // get the list of parent records from the set of ids passed as parameters
            parentDrrList = [SELECT Key_Field__c, Months__c, Object__c, Record_Type__c
                             FROM Data_Retention_Rule__c WHERE Id IN: drrSetParentIds AND Parent_Data_Retention_Rule__c = null
                             LIMIT: Limits.getLimitQueryRows() - Limits.getQueryRows()];
            
            if(!parentDrrList.isEmpty()) {
                // prepare a map of parent records and list of child records
                for(Data_Retention_Rule__c drrChild: [SELECT Key_Field__c, Months__c, Record_Type__c,
                                                      Parent_Data_Retention_Rule__c, Child_Relationship_Name__c
                                                      FROM Data_Retention_Rule__c WHERE Parent_Data_Retention_Rule__c != null
                                                      AND Parent_Data_Retention_Rule__c IN: drrSetParentIds
                                                      LIMIT: Limits.getLimitQueryRows() - Limits.getQueryRows()]) {
                    for(Data_Retention_Rule__c drrParent: parentDrrList) {   
                        if(String.valueOf(drrParent.id).equals(String.valueOf(drrChild.Parent_Data_Retention_Rule__c))) {
                            if(mapParentChildListRules.containsKey(drrParent)) {
                                List<Data_Retention_Rule__c> listChildRules = mapParentChildListRules.get(drrParent);
                                listChildRules.add(drrChild);
                                mapParentChildListRules.put(drrParent,listChildRules);
                              system.debug('>>>>listChildRules>>>>>>>>>>>>>>>>>'+listChildRules);
                            system.debug('>>>>drrParent>>>>>>>>>>>>>>>>>'+drrparent);   
                            
                            }
                                                   
                            
                            else{
                                mapParentChildListRules.put(drrParent,new List<Data_Retention_Rule__c>{drrChild});
                            }
                            break;
                        }
                    }
                }
                
                // for parent rules that do not have any child rules associated to them
                for(Data_Retention_Rule__c drrParent: parentDrrList) {
                    if(!mapParentChildListRules.containsKey(drrParent)) {
                        mapParentChildListRules.put(drrParent,null);
                    }
                }
            }
        }
        catch (QueryException qExcp) { /* Log exception to a custom object */ }
        
        return mapParentChildListRules;
    }
    
    
    
    /**
      * @name             buildFinalQueryFromRule
      * @description      Method is called to build a final query which will be passed to the Database.queryLocator
      *                   to retrieve the list of records to be deleted
      * @param            sObject record
      * @param            List<sObject> records
      * @return           String (final query String)
      * @throws           NA
      */
    public static String buildFinalQueryFromRule(Data_Retention_Rule__c parentRule, List<Data_Retention_Rule__c> listChildRules) {
        String finalQuery = null;
        if(parentRule.Object__c == 'Account'){
        finalQuery = 'SELECT Id,Name,Industry,Phone,AccountSource';
        system.debug('======================='+finalQuery);
        }
        else{         
        finalQuery = 'SELECT Id,type,Status,Priority,Origin';
        system.debug('======================='+finalQuery);
        }
        
        // if any child record exists, add the inner query string as part of the final query string being built
        if(listChildRules != null && !listChildRules.isEmpty()) {
            for(Data_Retention_Rule__c childRule: listChildRules) {
                finalQuery += buildQueryFromChildRule(childRule);
            }
        }
        
        finalQuery += ' FROM ' + parentRule.Object__c + ' WHERE ';
        
        if(String.isNotBlank(parentRule.Record_Type__c)) {
            finalQuery += 'RecordType.Name = \'' + parentRule.Record_Type__c + '\' AND ';
        }
        
        finalQuery += parentRule.Key_Field__c + ' < ' + writeDate(parentRule.Months__c);
        
        return finalQuery;
    }
    
    /**
      * @name             buildQueryFromChildRule
      * @description      Method is called to form a query string based on the values input in the Data_Retention_Rule record
      * @param            sObject - Data_Retention_Rule__c
      * @return           String
      * @throws           NA
      */
    private static String buildQueryFromChildRule(Data_Retention_Rule__c rule) {
        String query = null;
        
        query = ', (SELECT Id,type,Status,Priority,Origin FROM ' + rule.Child_Relationship_Name__c + ' WHERE ';
        
        if(String.isNotBlank(rule.Record_Type__c)) {
            query += 'RecordType.Name = \'' + rule.Record_Type__c + '\' AND ';
        }
        
        query += rule.Key_Field__c + ' > ' + writeDate(rule.Months__c) + ')';
        
        return query;
    }
    
    /**
      * @name             qualifyRecordsToBeDeleted
      * @description      Method is called to check if the list of sObjects qualify the criteria for archival/deletion
      * @param            List<sObject>
      * @param            sObject - Data_Retention_Rule__c
      * @param            List<sObject> - List<Data_Retention_Rule__c>
      * @return           List<sObject>
      * @throws           NA
      */
    public static List<sObject> qualifyRecordsToBeDeleted(List<sObject> sObjectList, List<Data_Retention_Rule__c> listChildRules) {
        
        // create a set of sObjects and populate it with the list of parent sObjects
        Set<sObject> sObjectSet = new Set<sObject>();
        sObjectSet.addAll(sObjectList);
        
        // for each child rule query, check the related records for each item in the batch of parent records,
        // if the parent qualifies for archival/deletion, take the action immediately
        if(listChildRules != null && !listChildRules.isEmpty()) {
            for(sObject sObj: sObjectSet) {
                for(Data_Retention_Rule__c drr: listChildRules) {
                    // check for each list of child records
                    // if any list of child records is not null, the parent does not qualify to be deleted
                    if(sObj.getSObjects(drr.Child_Relationship_Name__c) != null && sObj.getSObjects(drr.Child_Relationship_Name__c).size() > 0) {
                        // remove the parent record from the set
                        sObjectSet.remove(sObj);
                        // move on to next parent record
                        break;
                    }
                }
            }
        }
        // clear the sObject List
        sObjectList.clear();
        // add the values that still remain in the sObject set to the sObject list so that these can be passed back for deletion
        sObjectList.addAll(sObjectSet);
        
        return sObjectList;
    }
    
    /**
      * @name             writeDate
      * @description      Method returns a date time value of the present date minus the number of months input in the Data_Retention_Rule record
      * @param            Decimal
      * @return           DateTime
      * @throws           NA
      */
    private static String writeDate(Decimal ruleMonths) {
        String comparisonDt = String.valueOf(DateTime.now().addMonths(-1*(Integer)ruleMonths));
        
        String finalCompareDate = comparisonDt.split(' ')[0] + 'T' + comparisonDt.split(' ')[1] + '.000Z';
        
        return finalCompareDate;
    }
}
Object Exp
 
public class Helperclass
{
    public static void user_coninsertupdated()
    {       
    }
    
    public static void oppnameupdatewithacnamelastmodifyclsdate(List<Opportunity> opp)
    {
    set<id> accountid=new set<id>();
    set<id> ownerid=new set<id>();
    string opname;
    for(opportunity opp1:opp)
    {
    accountid.add(opp1.accountid);
    ownerid.add(opp1.ownerid);
    }
    map<id,account> accmap=new map<id,account>
    ([select id,name from account where id in:accountid]);
    map<id,user> usermap=new map<id,user>
    ([select id,lastmodifiedby.name from user where id in:ownerid]);
    
    for(opportunity opp2:opp)
    {   
    opname=accmap.get(opp2.accountid).name+' '+opp2.closedate+' '+usermap.get(opp2.ownerid).lastmodifiedby.name;
    if(opp2!=null)
    opp2.name=opname;
    }
    
    }
}
 
trigger accnameclsdatemodifydate  on Opportunity (before insert,before update) {

    if(trigger.isbefore && trigger.isinsert)
    {
    Helperclass.oppnameupdatewithacnamelastmodifyclsdate(trigger.new);
    }
    
    if(trigger.isbefore && trigger.isupdate)
    {
    Helperclass.oppnameupdatewithacnamelastmodifyclsdate(trigger.new);
    }
}

 
public class Daterangefetch {

    public list<Account> alist{set;get;}
    
    public list<Contact> clist{set;get;}
    
    public list<Opportunity> olist{set;get;}

    
    public list<wrapperlist> allvalues{set;get;} 
                
    public DateTime startDate{set;get;}
    
    public DateTime endDate{set;get;}
    
    public boolean abool{set;get;}

    public Daterangefetch(){   
    
    }
    
    public void refresh()
    {
    abool=true;
    }
    
    public void display()
    {
    if(startDate!=null && enddate!=null)
    {
     alist=[Select a.name,a.CreatedDate from account a 
            where a.CreatedDate >: startDate and a.CreatedDate <:endDate ORDER BY a.LastModifiedDate limit 3];  
     clist=[Select c.name,c.CreatedDate from contact c 
            where c.CreatedDate>:startDate and c.CreatedDate <:endDate ORDER BY c.LastModifiedDate limit 6]; 
     olist=[Select o.name,o.CreatedDate from opportunity o 
            where o.CreatedDate>:startDate and o.CreatedDate <:endDate ORDER BY o.LastModifiedDate limit 6]; 
        
        
    if(allvalues==null)
    {
    allvalues=new list<wrapperlist>();
    
    for(account a:alist)
    {
    wrapperlist w=new wrapperlist(a);
    allvalues.add(new wrapperlist(a));
    }
    
    for(contact c:clist)
    {
    wrapperlist w=new wrapperlist(c);
    allvalues.add(new wrapperlist(c));
    }
    
    for(opportunity o:olist)
    {
    wrapperlist w=new wrapperlist(o);
    allvalues.add(new wrapperlist(o));
    }
    
    }   
   
    }else{
    Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'Please Select the Date and Time'));
    }    
       
    } 
    
    public class wrapperlist{
    public account a{set;get;}
    public contact c{set;get;}
    public opportunity o{set;get;}
    
    public wrapperlist(account a)
    {
    this.a=a;
    }
    
    public wrapperlist(contact c)
    {
    this.c=c;
    }
    
    public wrapperlist(opportunity o)
    {
    this.o=o;
    }
    
    }
       
}
 
<apex:page controller="Daterangefetch" docType="html-5.0">
     <style>
         .sample{
         border:5px solid #81F79F;
         }
        .all{
        background-color:#AC58FA;
        width:600px;
        height:650px;
        border-radius: 2em;
        padding-left:20px;
        padding-right:30px;
        color:#FFFFFF;
        }
        .one{
        
        background-color:#00BFFF;
        width:600px;
        height:80px;
        border-radius: 2em;
        padding-left:10px;
        color:#FFFFFF;
        }
        .two{
        
        background-color:#00BFFF;
        width:600px;
        height:500px;
        border-radius: 2em;
        padding-left:10px;
        color:#FFFFFF;
        }
    </style>
<apex:form >
    <div class="all"><br/>
    <apex:panelGrid width="600px">
    <apex:pagemessages /> 
    </apex:panelGrid>
    <div class="one">     
    <br/>     
    <apex:outputText ><b>Start Date: </b>
    <apex:input type="datetime-local" value="{!startDate}">
    </apex:input>
    </apex:outputText>    
    <apex:outputText ><b>End Date: </b>
    <apex:input type="datetime-local" value="{!endDate}" >
    </apex:input>
    </apex:outputText>   
    <br/><br/> 
    <apex:commandButton value="Display" action="{!display}" style="margin-left: 7cm;" reRender="t1"/> 
    <br/>
    </div>
    <br/>

    <div class="two">
    <br/><br/>
    <center>
    <apex:outputPanel id="t1">
    <apex:DataTable value="{!allvalues}" var="al" > 
    <apex:column headerValue="Account,Contact,Opportunity">
    <br/>
    {!al.a.name}
    {!al.c.name}
    {!al.o.name}
    </apex:column>
    <apex:column headerValue=". CreatedDate">
    <br/>
    <apex:outputText value="{0,date,dd'/'MM'/'yyyy}">
    <apex:param value="{!al.a.createddate}"/>
    </apex:outputText>

    <apex:outputText value="{0,date,dd'/'MM'/'yyyy}">
    <apex:param value="{!al.c.createddate}"/>
    </apex:outputText>  
    
    <apex:outputText value="{0,date,dd'/'MM'/'yyyy}">
    <apex:param value="{!al.o.createddate}"/>
    </apex:outputText> 
  
    </apex:column>   
    </apex:DataTable>
    </apex:outputPanel>
    </center>
    </div>
    </div>
</apex:form>
</apex:page>

 
public class contactnameupdate
{
    public static void accountmethod(list<account> acclist)
    {
    string s='http://tekslate.com/15-sample-triggers-different-scenarios/';
        for(account a:acclist)
        {
            a.description=s;
        }
    }
    
    public static void contactmethod(list<contact> conlist)
    {
    list<account> accconlist=new list<account>();
    for(contact c:conlist)
    {
    accconlist.add(new account(id=c.accountid,name=c.lastname));
    }
    }

}
 
trigger insertcontact on Account (before insert,after insert,after update) {
    if(trigger.isbefore && trigger.isinsert)
    {
    contactnameupdate.accountmethod(trigger.new);
    }
    
    if(trigger.isafter && trigger.isinsert)
    {
    //contactnameupdate.contactmethod(trigger.new);
    }
}

 
Capture Name below choose file when inserted
<apex:page controller="Fileattachment1">
    <apex:form >
    <apex:pageBlock >
        <b><u><i>Attachment:</i></u></b><apex:inputCheckbox value="{!abool}">
        <apex:actionSupport action="{!upload}" event="onchange"/>
        </apex:inputCheckbox>
        <br/><br/>
        <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file" rendered="{!abool}"/>
        <br/><br/>
        <apex:commandButton value="Save" action="{!Save}" rendered="{!abool}"/>
    </apex:pageBlock>
    </apex:form>
</apex:page>
 
public with sharing class Fileattachment1 {

    public boolean abool{set;get;}
    public boolean bbool{set;get;}
    
    public Attachment attachment {
    get {
    if (attachment == null)
    attachment = new Attachment();
    return attachment;
    }
    set;
    }
    
    
    public void check()
    {
      if(abool == true)
      {
      abool=true;
      }
    }
    
    
    public pagereference save()
    {   
    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = '0012800000JAVhi';
    try {
    insert attachment;
    } catch (DMLException e) {
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));  
    } finally {
    attachment = new Attachment(); 
    }   
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
    return null;
    }
    
        
    public PageReference upload() {
    if(abool == true)
      {
       check();
      }  
    return null;
  }
}

 
User-added image
User-added image
Test Class:
@istest
Public class SalesAggregate_Test
{
    Public static testmethod void SalesAggregate_Test()
    {
    opportunity opp=new opportunity(stagename='test',amount=55);
    SalesAggregate sg = new SalesAggregate();
    
    sg.getResults();
    }

}

Apex Class:
public class SalesAggregate {

    /*************************************************
    Creating Wrapper Class
    *************************************************/
    public list<SalesAgg> arlist{Set;get;}
    
    public list<AggregateResult> groupedResults = new list<AggregateResult>(); 
   
    
    /***************************************************
    Constructor
    ***************************************************/
    public SalesAggregate()
    {
    groupedResults = [SELECT Stagename, SUM(Amount)samount,Count(ID)Sales FROM Opportunity GROUP BY Stagename];
    }
    
    /***************************************************
    Constructor
    ***************************************************/
    public list<SalesAgg> getResults(){
    list<SalesAgg> arlist=new list<SalesAgg>();
    for (AggregateResult ar : groupedResults)  {
    
    SalesAgg sg=new SalesAgg(ar);
    arlist.add(sg);
    System.debug('StageName' + ar.get('Stagename'));
    System.debug('Sum of amount' + ar.get('samount'));
    }
    return arlist;
    }
    
    /*************************************************
    Inner Class defined
    *************************************************/
    public class SalesAgg{
    public string stagename{set;get;}
    public decimal amount{set;get;}
    public integer total{set;get;}
    
   /***************************************************
    Constructor
    ***************************************************/
    public SalesAgg(AggregateResult ar){
    stagename=(string)ar.get('stagename');
    amount=(decimal)ar.get('samount');
    amount=amount.setscale(0);
    total=(integer)ar.get('sales');
    }
    
    }
}


 
User-added image
Public Class AccountRelatedContactCount
{
    Public List<Wrapper> WrapperList{Set;get;}
    
    List<AggregateResult> arlist=new List<AggregateResult>();
    
    Public AccountRelatedContactCount(){
    arlist=[select Account.Name,count(AccountID) Total from contact group by Account.Name];
    }
    
    Public List<Wrapper> getResult()
    {
    List<Wrapper> WrapperList=new List<Wrapper>();
    for(AggregateResult ar:arlist)
    {
    Wrapper wrplist=new Wrapper(ar);
    WrapperList.add(wrplist);
    }
    return WrapperList;
    }
    
    Public Class Wrapper
    {
    Public String AccountName{Set;get;}
    Public Integer Total{Set;get;}
    Public Wrapper(AggregateResult ar){
    AccountName=(String)ar.get('Account.Name');
    Total=(Integer)ar.get('Total');
    }
    }
}
=============================================
<apex:page controller="AccountRelatedContactCount">
    <apex:pageBlock >
    <apex:pageBlockTable value="{!Result}" var="r">
    <apex:column value="{!r.AccountName}" headervalue="Account Name"/>
    <apex:column value="{!r.Total}" headervalue="Number of Contacts"/>
    </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>
Hi,
how to write test class for below coding.Plz help asap

global class Batch_to_SentEmailNotify implements Database.Batchable<sObject> 
 {
   global Database.QueryLocator start(Database.BatchableContext BC) 
    {
       string s='Blocked';
        String query = 'Select Resort_Master__r.Name,Executive_Name__r.Email__c,Name_of_the_Guest__c,Company_Name__c,Block_Release_Date__c,Check_In__c,Check_Out__c,Total_Number_of_Rooms_Booked__c,Booking_Status__c,Source__c,Market_Segment__c,Executive_Name__r.Name FROM Non_Member_Booking_Request__c where Booking_Status__c=: s';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<Non_Member_Booking_Request__c> scope) 
    {
         for(Non_Member_Booking_Request__c c : scope)
         {
           system.debug('++++++++++++++system.today ++++++++++++++'+system.today());
            string email = c.Executive_Name__r.Email__c;
            if(email !=null && (system.today() == c.Check_In__c))
            {
              Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
              mail.setUseSignature(false);
              mail.setToAddresses(new String[] { email});
              mail.setSubject('Booking Confirmation ');
              mail.setHtmlBody('Dear Team <br/>'+'Namaste !!!!<br/>'+'Please find the attached payment details of below room reservation.<br/>'+'Please check and confirm the CV with updated payment details.<br/>'
              );
              Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
              system.debug('@@@@@@@@@@@@@@@mail@@@@@@@@@@@@@@@'+mail);
            
           }
         }   
    }
    global void finish(Database.BatchableContext BC) 
    {
    }
}
Regards,
Hareesh
trigger trgset on contact (after insert)
{
    List<Contact> conToUpdate = new List<Contact>() ;
     for(Account acc : [Select Name,(Select id ,LastName from Contacts where id in: trigger.new ) from Account  ] )
     {
         for(Contact con : acc.Contacts)
         {
             con.LastName = acc.Name ;
             conToUpdate.add(con) ;
         }
    }
    if(conTOUpdate.size() > 0)
    {
       update conTOUpdate ;
    }
}
 
Trigger Childtoconupdate on ChildtoContact__c(after insert)
{
	List<ChildtoContact__c> ctlist=new List<ChildtoContact__c>();
	for(contact con:[Select lastname,(select id,name from ChildtoContactsrelation__r where id in:trigger.new)
		from Contact])
	{
		for(ChildtoContact__c ct:con.ChildtoContactsrelation__r)
		{
			ct.name=con.LastName;
			ctlist.add(ct);
		}
	}
	if(ctlist.size()>0)
	{
		Update ctlist;
	}
}

 
Hello all!

I'm trying to create a trigger that updates a custom "IsFrozen" field when a user's record is frozen.

The User object field, IsFrozen__c is supposed to see if the UserLogin object's IsFrozen field is updated to a value of true, and if so, update the user's record to true. I think this will greatly help us with the userdeactivation process.

My code is as follows:
trigger UserIsFrozen on User (before update) {
    
    for(User U: Trigger.new) {
        User oldU = Trigger.oldMap.get(U.Id);
        
        
        if(oldU.IsActive = true) {
            List<UserLogin> ULog = [SELECT Id, IsFrozen from UserLogin where UserId = :U.Id];
            List<UserLogin> newids = new List<UserLogin>();
            
            for(Userlogin USLog : ULog) {
                if(USLog.IsFrozen = true) {
                    U.IsFrozen__c = true;
                    newids.add(USLog);
                }
            }    
            if(newids.isEmpty()== false) {
                update newids;
                update U;
            }
        }
    }
}

The trigger isn't working right now. What am I doing wrong?
Trigger OpportunityPrdHisTrack on OpportunityLineItem (after insert){
    
    if(Trigger.isafter && Trigger.isinsert)
    {
        HelperClass_one.opplineiteminsert(Trigger.new);
    }
}
 
public class HelperClass_one{
    public static void opplineiteminsert(List<OpportunityLineItem> opplinelist)
    {
        list<HistoryTracking__c> htlist=new list<HistoryTracking__c>();
        for(OpportunityLineItem oppline:opplinelist)
        {

            HistoryTracking__c ht=new HistoryTracking__c();
            ht.product__c=oppline.id;
            ht.Name=oppline.Name;
            ht.ProductDescription__c=oppline.Description;
            ht.ProductCode__c=oppline.ProductCode;
            htlist.add(ht);
            
        }
        insert htlist;
    }
}

 
Capture Name below choose file when inserted
<apex:page controller="Fileattachment1">
    <apex:form >
    <apex:pageBlock >
        <b><u><i>Attachment:</i></u></b><apex:inputCheckbox value="{!abool}">
        <apex:actionSupport action="{!upload}" event="onchange"/>
        </apex:inputCheckbox>
        <br/><br/>
        <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file" rendered="{!abool}"/>
        <br/><br/>
        <apex:commandButton value="Save" action="{!Save}" rendered="{!abool}"/>
    </apex:pageBlock>
    </apex:form>
</apex:page>
 
public with sharing class Fileattachment1 {

    public boolean abool{set;get;}
    public boolean bbool{set;get;}
    
    public Attachment attachment {
    get {
    if (attachment == null)
    attachment = new Attachment();
    return attachment;
    }
    set;
    }
    
    
    public void check()
    {
      if(abool == true)
      {
      abool=true;
      }
    }
    
    
    public pagereference save()
    {   
    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = '0012800000JAVhi';
    try {
    insert attachment;
    } catch (DMLException e) {
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));  
    } finally {
    attachment = new Attachment(); 
    }   
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
    return null;
    }
    
        
    public PageReference upload() {
    if(abool == true)
      {
       check();
      }  
    return null;
  }
}

 
User-added image
User-added image
Test Class:
@istest
Public class SalesAggregate_Test
{
    Public static testmethod void SalesAggregate_Test()
    {
    opportunity opp=new opportunity(stagename='test',amount=55);
    SalesAggregate sg = new SalesAggregate();
    
    sg.getResults();
    }

}

Apex Class:
public class SalesAggregate {

    /*************************************************
    Creating Wrapper Class
    *************************************************/
    public list<SalesAgg> arlist{Set;get;}
    
    public list<AggregateResult> groupedResults = new list<AggregateResult>(); 
   
    
    /***************************************************
    Constructor
    ***************************************************/
    public SalesAggregate()
    {
    groupedResults = [SELECT Stagename, SUM(Amount)samount,Count(ID)Sales FROM Opportunity GROUP BY Stagename];
    }
    
    /***************************************************
    Constructor
    ***************************************************/
    public list<SalesAgg> getResults(){
    list<SalesAgg> arlist=new list<SalesAgg>();
    for (AggregateResult ar : groupedResults)  {
    
    SalesAgg sg=new SalesAgg(ar);
    arlist.add(sg);
    System.debug('StageName' + ar.get('Stagename'));
    System.debug('Sum of amount' + ar.get('samount'));
    }
    return arlist;
    }
    
    /*************************************************
    Inner Class defined
    *************************************************/
    public class SalesAgg{
    public string stagename{set;get;}
    public decimal amount{set;get;}
    public integer total{set;get;}
    
   /***************************************************
    Constructor
    ***************************************************/
    public SalesAgg(AggregateResult ar){
    stagename=(string)ar.get('stagename');
    amount=(decimal)ar.get('samount');
    amount=amount.setscale(0);
    total=(integer)ar.get('sales');
    }
    
    }
}


 
User-added image
Public Class AccountRelatedContactCount
{
    Public List<Wrapper> WrapperList{Set;get;}
    
    List<AggregateResult> arlist=new List<AggregateResult>();
    
    Public AccountRelatedContactCount(){
    arlist=[select Account.Name,count(AccountID) Total from contact group by Account.Name];
    }
    
    Public List<Wrapper> getResult()
    {
    List<Wrapper> WrapperList=new List<Wrapper>();
    for(AggregateResult ar:arlist)
    {
    Wrapper wrplist=new Wrapper(ar);
    WrapperList.add(wrplist);
    }
    return WrapperList;
    }
    
    Public Class Wrapper
    {
    Public String AccountName{Set;get;}
    Public Integer Total{Set;get;}
    Public Wrapper(AggregateResult ar){
    AccountName=(String)ar.get('Account.Name');
    Total=(Integer)ar.get('Total');
    }
    }
}
=============================================
<apex:page controller="AccountRelatedContactCount">
    <apex:pageBlock >
    <apex:pageBlockTable value="{!Result}" var="r">
    <apex:column value="{!r.AccountName}" headervalue="Account Name"/>
    <apex:column value="{!r.Total}" headervalue="Number of Contacts"/>
    </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>