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

Create a batch class to update contact field. If contact created date last 30 days then update contact text field as Hello.

Can you please provide the class to update the contact field to hello.
Best Answer chosen by jishan roy
AnkaiahAnkaiah (Salesforce Developers) 
Hi Jishan,

try with below code.
global class contactUpdate implements Database.Batchable<sObject>
{
	    List <Contact> toUpdate = new List <Contact> ();

	global Database.QueryLocator start(Database.BatchableContext BC)
	{
        String query = 'SELECT Id,Text__c from contact where CreatedDate = LAST_N_DAYS:30';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<contact> scope)
    {
        for ( contact c : scope)
        {
           c.Text__c='Hello';
           toUpdate.add(c); 
        }
        update toUpdate;
    }  
    global void finish(Database.BatchableContext BC)
    {
    }
}

Run the batch class in developer console.
Id batchJobId = Database.executeBatch(new contactUpdate(), 200);

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi Jishan,

try with below code.
global class contactUpdate implements Database.Batchable<sObject>
{
	    List <Contact> toUpdate = new List <Contact> ();

	global Database.QueryLocator start(Database.BatchableContext BC)
	{
        String query = 'SELECT Id,Text__c from contact where CreatedDate = LAST_N_DAYS:30';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<contact> scope)
    {
        for ( contact c : scope)
        {
           c.Text__c='Hello';
           toUpdate.add(c); 
        }
        update toUpdate;
    }  
    global void finish(Database.BatchableContext BC)
    {
    }
}

Run the batch class in developer console.
Id batchJobId = Database.executeBatch(new contactUpdate(), 200);

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​
This was selected as the best answer
jishan royjishan roy
Thanks  Ankaiah,
Its working 
jishan royjishan roy
But i need contact created date last 30 days then update contact text field as Hello!
AnkaiahAnkaiah (Salesforce Developers) 
Hi Jishan,

Modify the query like below.
SELECT Id,Text__c from contact where CreatedDate < LAST_N_DAYS:30

Thanks!!
jishan royjishan roy
hii Ankaiah,
now update field had not update hello.
AnkaiahAnkaiah (Salesforce Developers) 
Can you please check the returned the records or not?

Thanks!!