How to get first element of set using Apex in Salesforce?

Sample Code:

Set<String> setStr = new Set<String> {'abc', 'xyz'};
String first = new List<String> (setStr).get(0); //returns abc

Cheers!!!

Trigger to store case's previous status in Salesforce

Sample Trigger:

trigger Case_BU on Case (before update) {
    for(Case cas : trigger.new) {
        if(cas.Status != trigger.oldMap.get(cas.Id).Status) {
            cas.Previous_Case_Status__c = trigger.oldMap.get(cas.Id).Status;
        }
    }
}

Cheers!!!

Salesforce beginners guide

Hi All,
Salesforce.com is really a good CRM tool.

To experience it just create an account in developer edition and enjoy. To create a developer account, kindly use the below link

http://www.infallibletechie.com/2013/01/how-to-signup-for-developer-edition-in.html

Starting from Home page, explore all the tabs, create some records and experience the product.

Then use this link to study more: http://www.salesforce.com/services-training/training_certification/online/

Workbooks:

http://www.infallibletechie.com/2013/01/link-for-creating-warehouse-application.html

http://www.infallibletechie.com/2012/10/recruiting-application-in-salesforce.html

Cheers!!!

How to add parent Id and its child records list to a map in Salesforce?

Sample Code:


Map<Id, List<Contact>> mapAcctIdContactList = new Map<Id, List<Contact>>();
List<Contact> listContact = [SELECT Id, FirstName, AccountId FROM Contact];

for(Contact con : listContact) {
    if(String.isNotBlank(con.AccountId)){
        if(!mapAcctIdContactList.containsKey(con.AccountId)) {
            mapAcctIdContactList.put(con.AccountId, new List<Contact>());
        }
        mapAcctIdContactList.get(con.AccountId).add(con);
    }
}

system.debug(mapAcctIdContactList);


Cheers!!!

How to retrieve pagelayouts using Apache ANT tool from Salesforce?

Sample Package.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">    
<types>
        <members>Account-Account Layout</members>
<members>Contact-Contact Layout</members>
        <members>Employee__c-Employee Layout</members>
        <name>Layout</name>
    </types>
</Package>


To get the pagelayout name:


Cheers!!!

How to call Javascript from Command button in Visuaforce page?

Sample Visualforce page:

<apex:page >
<script>
    function show(){
        alert('Test');
    }
</script>
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockButtons >            
            <apex:commandButton value="Store" onclick="show();"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>
</apex:page>

Output


Cheers!!!

Trigger to find duplicate case by subject and closing it automatically with existing case comments

Apex Class:

public class CommonVariables {
    public Static Boolean caseRepeatCheck = true;
}

Sample Trigger:

trigger CaseTrigger on Case (after insert) {
    if(CommonVariables.caseRepeatCheck) {
        CommonVariables.caseRepeatCheck = false;
        Set<String> caseSubs = new Set<String>();
        Set<Id> caseIds = new Set<Id>();
        List<Case> listCases = new List<Case>();
        List<Case> listUpdateCases = new List<Case>();
        List<CaseComment> listCaseComm = new List<CaseComment>();
        List<CaseComment> listInsertCaseComm = new List<CaseComment>();
        Map<String, Id> mapCasSubId = new Map<String, Id>();
        Map<Id, CaseComment> mapCaseIdCasComm = new Map<Id, CaseComment>();
        
        for(Case cas : trigger.new) {
            caseSubs.add(cas.Subject);
            caseIds.add(cas.Id);
        }
        
        listCases = [SELECT Id, Subject, Description FROM Case WHERE Subject IN : caseSubs AND Id NOT IN : caseIds AND Status = 'Closed'];
            
        if(listCases.size() > 0) {
            caseIds = new Set<Id>();
            for(Case cas : listCases) {
                mapCasSubId.put(cas.Subject, cas.Id);
                caseIds.add(cas.Id);
            } 
             
            listCaseComm = [SELECT Id, CommentBody, ParentId FROM CaseComment WHERE ParentId IN : caseIds];       
                    
            for(CaseComment casComm : listCaseComm) {
                mapCaseIdCasComm.put(casComm.ParentId, casComm);
            }                  
            
            for(Case cas : trigger.new) {
                if(mapCasSubId.containsKey(cas.Subject)) {
                    listUpdateCases.add(new Case(Id = cas.Id, Status = 'Closed'));
                    listInsertCaseComm.add(new CaseComment(ParentId = cas.Id, CommentBody = mapCaseIdCasComm.get(mapCasSubId.get(cas.Subject)).CommentBody));
                }
            }
            
            if(listUpdateCases.size() > 0) {
                update listUpdateCases;
            }
            
            if(listInsertCaseComm.size() > 0) {
                insert listInsertCaseComm;
            }
        }
    }
}

How to include number of records in button name in Visualforce Page?

Sample Code:

Visualforce page:

<apex:page controller="SampleController">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockTable value="{!empList}" var="e">
            <apex:column value="{!e.Name}"/>
        </apex:pageBlockTable>
        <apex:pageBlockButtons >            
            <apex:commandButton value="Convert All {!empCount} Records"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Controller:

public class SampleController {
    public List<Employee__c> empList {get;set;}
    public Integer empCount {get;set;}
    public SampleController() {
        empList = [SELECT Id, Name FROM Employee__c];
        empCount = empList.size();
    }
}

Output:



Mindtree openings for freshes

Mindtree is hosting a MEGA off-campus recruitment event in Bangalore and Chennai. The first recruitment event starts early September.

Help spread the word. Share this link http://careers.mindtree.com/freshers with all the 2014 freshers you know so they can apply with us.


Cheers!!!

Salesforce opening

Title: SFDC Developer
Duration: 1+ Year
Location: Bangalore, INDIA
What you’ll be doing…
 Primary responsibility for SF solution design including preparation and analysis of
solution object models and mapping of solutions to standard and/or custom SF
objects.
 Responsible for designing and implementing integration architectures for data and
process integration with other nonSF systems.
 Collaborate with Stakeholders and Architect team to understand the
implementation requirements and deliver with quality
 Participate in the full application life cycle from technical design to development.
 SFDC production support.
 Ongoing project based development and enhancements.
What you should have…
 Deep SFDC and Force.com experience, and able to think through solutions of
concepts
 Ability to map out to process flows and objects in SFDC
 Salesforce.com Developer and Admin certifications
 2 - 3+ yrs. Apex development experience on the Force.com platform including the
ability       
 to write triggers and develop Visualforce pages
 Strong platform experience - must understand and be able to implement
Salesforce.com  
 configuration changes
What else we’d like you to have…
 Passionate about current technology and new trends
 Excellent Communication skills
 Willing to work on rotational shifts
 Good Attitude.
Experience Level:
 3+  years of experience
To whom you need to send resume : rv.phani@eslabs.net

Source:

How to schedule a Visualforce page using Apex in Salesforce?

Visualforce page:

<apex:page controller="PDFController">
    <apex:pageBlock >
        <apex:pageBlockTable value="{!listEmployees}" var="e">
            <apex:column value="{!e.Name}"/>
            <apex:column value="{!e.Age__c}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Apex Controller:

public class PDFController {
    public List<Employee__c> listEmployees {get;set;}
   
    public PDFController() {
        listEmployees = new List<Employee__c>();
        listEmployees = [SELECT Name, Age__c FROM Employee__c];
    }
}

Scheduler Class:

global class EmailSchedule implements Schedulable {
    global void execute(SchedulableContext sc) {
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
        attach.setContentType('application/pdf');
        attach.setFileName('Employee.pdf');
       
        pagereference Pg = Page.PDFPage;
        Blob body = pg.getcontentAsPdf();

        attach.Body = body;
               
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] { 'your email address' });
        mail.setSubject('PDF Generation');
        mail.setHtmlBody('PFA');
        mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });    
       
        mails.add(mail);
       
        if(!mails.isEmpty()) {
            Messaging.SendEmail(mails);
        }
    }
}

Schedule the Scheduler class to receive emails. Kindly use the  below link if you are not aware of scheduling apex classes.

http://www.infallibletechie.com/2012/05/apex-scheduler.html

Cheers!!!

apex:outputText not showing decimal places issue?

If apex:outputText not showing decimal places issue, kindly check the initialization of variables.

Sample code:

If it is Double, Double a = 0.0;

If it is Decimal, Decimal d = 0.00;

Cheers!!!

How to avoid particular block of code to be avoided by test class in Salesforce?

Test.isRunningTest() is used to define whether the code is executed by test class.

Sample Code:

if(!Test.isRunningTest()) {
    ...................................
    ...................................
    ...................................
}

Cheers!!!

How to fetch report name and format using SOQL in Salesforce?

Sample SOQL:

SELECT Name, Format FROM Report

here
Name - Name of the report.
Format - Format of the report(Tabular, Summary, Matrix, MultiBlock(Joined report)).

Cheers!!!

How to get the batch status using Apex in Salesforce?

Sample Code:

Batch_Class_Name obj = new Batch_Class_Name();
Id batchId = Database.executeBatch();

AsyncApexJob job = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID =: batchId];

Cheers!!!

What is the difference between Freeze and Inactivating the user in Salesforce?

Freeze:
If an user is freezed,

1. He will not be able to login.
2. User license of that user will not be released.

This is mainly used if you want to restrict an user to login during any activity.

Check the below link for Freezing and Unfreezing.

http://www.infallibletechie.com/2013/10/freeze-button-in-salesforce-user-detail.html

Inactivate:
If an user is inactivated,

1. He will not be able to login.
2. Report will not run, if he/she is set as running user.
3. Web to lead and web to case will not work, if he is set as the default creator.
4. User license of the inactivates user will be free for other user.

This is mainly done, when the user leaves the organization.

Cheers!!!

How to install Force.com IDE for Luna Eclipse?

1. Go to Help --> Install New Software.


2. Click "Add" button.


3. Enter the details as mentioned below and click "Ok" button.

URL: http://media.developerforce.com/force-ide/eclipse42


4. Select "Force.com IDE" and click "Next" button.


5. Click "Next" button.


6. Accept the Agreement and click "Finish" button.


7. Restart the eclipse and go to Window --> Open Perspective --> Other.


8. Select "Force.com".


9. Go to File --> New --> Force.com Project.


Difference between Clone and DeepClone in Apex in Salesforce

Clone
DeepClone
If a list is cloned, it duplicates it and has reference.
If a list is DeepCloned, it duplicates and doesn’t have any reference.
Primitive data types are supported.
Primitive data types are not supported.
Parameters:
Not applicable
Parameters:
Boolean opt_preserve_id – Whether cloned sObjects records ids are maintained.

Boolean opt_preserve_readonly_timestamps– Whether cloned sObjects records read only system fields like createdDate, LastModifiedDtate, etc are   maintained.

Boolean opt_preserve_autonumbe– Whether cloned sObjects records auto number fields are maintained.
Sample Code:
Account Account1= new Account(Name='Test1');
Account Account2= new Account(Name='Test2');
List<Account> AccountList = new List<Account>{Account1, Account2};

List<Account> listDuplicate = new List<Account>();
listDuplicate = AccountList.clone();

AccountList.get(0).Name = 'Testing1';
system.debug(AccountList.get(0).Name + ',' + listDuplicate.get(0).Name);

Now AccountList.get(0).Name and listDuplicate get(0).Name will be ‘Testing1’.

listDuplicate.get(0).Name = 'Testing2';
system.debug(AccountList.get(0).Name + ',' + listDuplicate.get(0).Name);

Now AccountList.get(0).Name and listDuplicate get(0).Name will be ‘Testing2’.
Sample Code:
Account Account1= new Account(Name='Test1');
Account Account2= new Account(Name='Test2');
List<Account> AccountList = new List<Account>{Account1, Account2};

List<Account> listDuplicate = new List<Account>();
listDuplicate = AccountList.deepClone();

AccountList.get(0).Name = 'Testing1';
system.debug(AccountList.get(0).Name + ',' + listDuplicate.get(0).Name);

Now AccountList.get(0).Name will be ‘Testing1’ and listDuplicate get(0).Name will be ‘Test1’.

listDuplicate.get(0).Name = 'Testing2';
system.debug(AccountList.get(0).Name + ',' + listDuplicate.get(0).Name);

Now AccountList.get(0).Name will be ‘Testing1’ and listDuplicate get(0).Name will be ‘Testing2’.
list1 = list2 is same as clone();

Cheers!!!

How can I get a list of records where two fields have the same or different values using SOQL?

1. Create a formula field

IF(Field1__c != Field2__c, 1, 0)

2. Write a SOQL as mentioned below

SELECT Id from Account WHERE FormulaField__c = 1

Cheers!!!

How to delete components from Salesforce organization using Apache ANT Tool?

Package.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <version>30.0</version>
</Package>

DestructiveChanges.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
        <members>Test</members>
        <name>ApexComponent</name>
    </types>
    <version>30.0</version>
</Package>

Build.xml:

<project name="Sample usage of Salesforce Ant tasks" default="test" basedir="." xmlns:sf="antlib:com.salesforce">

    <property file="build.properties"/>
    <property environment="env"/>

<target name="undeploy">
<sf:deploy
username="${sf.mydevusername}"
password="${sf.mydevpassword}"
serverurl="${sf.serverurl}"
deployroot="Target"/>
</target>

</project>

Command:



Note:
1. In DestructiveChanges.xml, * is not allowed.
2. The Package.xml should be blank without any components for deployment as mentioned above.

Cheers!!!

How to create checkboxes in Visualforce page in Salesforce?

Sample Code:

<apex:page >
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >Name<apex:inputText /></apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >Age:
                <apex:selectRadio >
                    <apex:selectOption itemLabel="Male" itemValue="m"/>
                    <apex:selectOption itemLabel="Female" itemValue="f"/>           
                </apex:selectRadio>     
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >Skills:
                <apex:selectcheckboxes layout="pageDirection">
                    <apex:selectOption itemLabel="C" itemValue="f"/>
                    <apex:selectOption itemLabel="C++" itemValue="cpp"/>    
                    <apex:selectOption itemLabel="JAVA" itemValue="j"/>
                    <apex:selectOption itemLabel="HTML" itemValue="h"/>  
                    <apex:selectOption itemLabel="JAVASCRIPT" itemValue="js"/>
                    <apex:selectOption itemLabel="VC++" itemValue="vcpp"/>         
                </apex:selectcheckboxes>     
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem>Active?<apex:inputCheckbox/></apex:pageBlockSectionItem>
        </apex:pageBlockSection>
        <apex:pageBlockButtons >
            <apex:commandButton value="Store"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>
</apex:page>

Output:



How to create Radio Button in Visualforce page in Salesforce?

Sample Code:

<apex:page >
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >Name<apex:inputText /></apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem >Age:
                <apex:selectRadio >
                    <apex:selectOption itemLabel="Male" itemValue="m"/>
                    <apex:selectOption itemLabel="Female" itemValue="f"/>           
                </apex:selectRadio>     
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
        <apex:pageBlockButtons >
            <apex:commandButton value="Store"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>
</apex:page>

Output:


How to hide the tabs using Visualforce page?

Sample Code:

<apex:page wizard="true">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >Name<apex:inputText /></apex:pageBlockSectionItem>
        </apex:pageBlockSection>
        <apex:pageBlockButtons >
            <apex:commandButton value="Store"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>
</apex:page>

Output:



How to fetch records form recycle bin in Salesforce?

"ALL ROWS" keyword is used to fetch records form recycle bin in Salesforce

Sample SOQL:

SELECT Id, AccountId FROM Contact WHERE IsDeleted = true ALL ROWS

Cheers!!!

Merge trigger example in Salesforce

When merge event occurs, in the deleted records, MasterRecordId field will be populated with the winning record id. The winning record will be updated with the values selected.

In the below trigger, when accounts are merged, then deleted record's Name and Website will be stored in Account Backup custom object.

Sample Trigger:

trigger AccountMergeTrigger on Account (after delete) {
    List<Account_Backup__c> listAccountBackup = new List<Account_Backup__c>();
    for(Account acct : trigger.old) {
        if(String.isNotBlank(acct.MasterRecordId)) { 
            listAccountBackup.add(new Account_Backup__c(Name = acct.Name, Website__c = acct.Website));  
        }         
    }
    if(listAccountBackup.size() > 0) {
        insert listAccountBackup;
    }    
}

Cheers!!!

How to create and view Visualforce page in Salesforce?

To create and view Visualforce page in Salesforce, follow the below steps

1. Go to Setup --> Develop --> Pages and click "New" button.


2. Click "Preview" button to view it.


Deleting checked rows using apex in Salesforce?

Sample Code:

Visualforce page:

<apex:page controller="DeletingCheckedRowsController">
<apex:pagemessages />
    <apex:form >
        <apex:pageBlock id="pg">
           <apex:pageBlockTable value="{!listWrapper}" var="w">
               <apex:column > 
                   <apex:facet name="header">
                       <apex:inputCheckbox value="{!allBool}">
                           <apex:actionSupport reRender="pg" action="{!selectAll}" event="onchange"/>
                       </apex:inputCheckbox>
                   </apex:facet>
                   <apex:inputCheckbox value="{!w.checked}"/>
               </apex:column>
               <apex:column value="{!w.emp.Name}"/>
               <apex:column value="{!w.emp.Age__c}"/>
            </apex:pageBlockTable> 
            <apex:pageBlockButtons >
                <apex:commandButton value="Delete" action="{!del}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>


Controller:

public class DeletingCheckedRowsController {
    public List<WrapperClass> listWrapper {get;set;}
    public Boolean allBool {get;set;}
    
    public DeletingCheckedRowsController() {
        listWrapper = new List<WrapperClass>();
        List<Employee__c> listEmp = [SELECT Id, Name, Age__c FROM Employee__c];
        if(listEmp.size() > 0) {
            for(Employee__c emp : listEmp) {
                listWrapper.add(new WrapperClass(emp));
            }
        }
    }
    
    public class WrapperClass {
        public Boolean checked {get;set;}
        public Employee__c emp {get;set;}
        public WrapperClass(Employee__c emp) {
            this.emp = emp;
        }
    }
    
    public void del() {
        List<Employee__c> listEmpForDel = new List<Employee__c>();
        List<WrapperClass> listTempWrapper = new List<WrapperClass>();
        for(WrapperClass w : listWrapper) {
            if(w.checked) {
                listEmpForDel.add(w.emp);
            } else {
                listTempWrapper.add(w);
            }
        }
        if(listEmpForDel.size() > 0) {
            delete listEmpForDel;
            listWrapper = listTempWrapper;
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Select atleast one employee to delete'));
        }
    }
    
    public void selectAll() {
        if(allBool) {
            for(WrapperClass w : listWrapper) {
                w.checked = true;
            }
        } else {
            for(WrapperClass w : listWrapper) {
                w.checked = false;
            }
        }
    }
}

Output:



How to fetch Campaign information from Lead in Salesforce?

Sample SOQL:

SELECT Id, (SELECT Id FROM CampaignMembers) FROM lead

Cheers!!!

Conditional roll up summary field in Salesforce?

In order to create a conditional roll up summary field in Salesforce, select "Only records meeting certain criteria should be included in the calculation" option as pointed in the below screenshot.


Cheers!!!

How to get all the trigger names from Salesforce organization?

Sample SOQL:

SELECT Id, Name FROM ApexTrigger

Cheers!!!

How to find whether two dates are same using apex in Salesforce?

Sample Code:
DateTime:
datetime myDate = datetime.now();
datetime dueDate = 
datetime.newInstance(2008, 1, 30);
boolean dueNow = myDate.isSameDay(dueDate);//return true if myDate and dueDate are same else return false

Date:
date myDate = date.today();
date dueDate = date.newInstance(2008, 1, 30);
boolean dueNow = myDate.isSameDay(dueDate);//return true if myDate and dueDate are same else return false

Cheers!!!

Credit Note

Credit Note is nothing but a form or letter issued by the seller to the buyer. If the purchaser paid extra money to the goods purchased, the seller will provide a Credit Note.

For example, if discount is not applied during the purchase, if goods have damages, if goods are returned, etc...

Cheers!!!

Debit Note

Debit Note is nothing but a form or letter issued by the seller to the buyer. If the purchaser didn't pay the full  amount for the goods purchased, the seller will provide a Debit Note.

The Debit Note is issued mainly in Business to Business transactions where the purchaser usually pays the payment after the goods shipment.

Cheers!!!

TCS Walkin


Check the below link

http://newsletter.monsterindia.com/files/060814_Vijeth_060814-133425960_MI


Cheers!!!

Freshers - 2014 passouts - Bosch


Dear Boschler,

We have few open positions for CSc/ IT fresher - 2014 pass outs  only. These positions require candidates with exceptional track record.
Please share your references -  if they fulfill all the below mentioned criteria:

1.       You have the conviction that your reference can be a top performer at RBEI
2.       Candidate must have graduated from any of the following colleges
o   Amrita College of Engg, Coimbatore
o   BIT, Bangalore
o   NIE, Mysore
o   BMS, Bangalore
o   BVB, Hubli
o   College of Engg., Trivandrum
o   SDM, Dharwad
o   MSRIT, Bangalore
o   PESIT, Bangalore
o   PSG, Coimbatore
o   RVCE, Bangalore
o   SIT, Tumkur
o   SJCE, Mysore
o   Vellore Institute of Technology
o   Manipal Institute of Technology
o   UVCE, Bangalore
o   MVIT, Bangalore

Or other reputed engineering colleges.

3.       Eligibility criteria :
o   Min. 70% in the academics (10th, 12th and BE) with no history of backlogs
o   Specialized in Computer Science & Information Science branches only

4.       Other guidelines :
o   Those who have attended/participated our selection process in the past are NOT eligible to re-apply
o   Candidates with offer from other companies can also apply.
o   Employee referral scheme is not applicable for these positions
o   Only shortlisted candidates will be intimated with feedback
o   Referral email should carry the subject line mentioning the college name + engg. specialization

Please rush your references to fixed-term.sumitha.figarado@in.bosch.com latest by Tuesday05/08/2014.

Referral details:

Please write to fixed-term.sumitha.figarado@in.bosch.com for referrals (with your CV) or for any queries.
Timeline : Before  Tuesday, 05/08/2014 COB/EOD.


Cheers!!!

How to update child records when parent record is updated in Salesforce?

Sample trigger:

trigger ContactUpdate on Account (after update) {
    Map < Id,  Account > mapAccount = new Map < Id, Account >();
    List<Contact> listContact = new List<Contact>();
   
    for(Account acct : trigger.new)
        mapAccount.put(acct.Id, acct);
   
    listContact = [ SELECT MailingStreet, MailingCity, AccountId FROM Contact WHERE AccountId IN : mapAccount.keySet() ];
   
    if ( listContact.size() > 0 ) {
        for ( Contact con : listContact ) {
            con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;
            con.MailingCity = mapAccount.get(con.AccountId).BillingCity;
        }
        update listContact;
    }
}


Cheers!!!

How to delete the records in sobject that are 3 days old records in Salesforce?

Sample Batch:

global class OldRecordDeleteBatch implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date threeDaysBefore = System.today().addDays(-3);
        String SOQL = 'SELECT Id FROM Employee__c WHERE CreatedDate = : threeDaysBefore';
        return Database.getQueryLocator(SOQL);
    }
    
    global void execute(Database.BatchableContext bc, List <Employee__c> listEmp) {
        delete listEmp;
    }
    
    global void finish(Database.BatchableContext bc) {
    }
}

Cheers!!!

How to create a chatter post using trigger in Salesforce?

Sample Code:

trigger PostFeed on Opportunity(after insert, after update) {
    List<FeedItem> FIList = new List<FeedItem>();
    Map<Id, Opportunity> oldMap = trigger.oldMap;
    for(Opportunity oppty: trigger.new) {
        FeedItem FI = new FeedItem();
        if(trigger.isInsert && oppty.StageName == 'Closed Won') {
            FI.Body = 'Opportunity is closed successfully on ' + system.today() + ' by ' + UserInfo.getName();
        } else if(trigger.isUpdate) {
            Opportunity tempOppty = oldMap.get(oppty.Id);
            if(tempOppty.StageName != oppty.StageName && oppty.StageName == 'Closed Won') {
                FI.Body = 'Opportunity is closed successfully on ' + system.today() + ' by ' + UserInfo.getName();
            }
        }
        FI.ParentId = oppty.Id;
        if(String.isNotBlank(FI.Body)){
            FIList.add(FI);
        }
    }
    if(FIList.size() > 0) {
        insert FIList;
    }
}


Output: