0

I need to update a lot of record to change their lookup field to null, I tried following code:

public class UpdateContact implements Database.Batchable<sObject>{

public Database.QueryLocator start(Database.BatchableContext BC){

    return Database.getQueryLocator([Select id, Profil__c from Contact__c]);

}
public void execute(Database.BatchableContext BC, List<Contact__c> scope){  
    for(Contact__c contactC:scope){
         contactC.Profil__c = null;
         update ContactC;}}
public void finish(Database.BatchableContext BC){

} }

But this code isn't working, I got the following error: First error: Invalid id:

So Apex is not considering null as an id, but I want to turn that Profil field to empty could you help me to do it ?

Thank you for your answers.

-1

You should Declare Id variable and initialized with as null in top then assign that in for loop like below and do the update in out side the loop.

public class UpdateContact implements Database.Batchable<sObject>
{
  Id profilid = null;
    public Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator([Select id, Profil__c from Contact__c];

    }

    public void execute(Database.BatchableContext BC, List<Contact__c> scope){  
        for(Contact__c contactC:scope)
        {
            contactC.Profil__c = profilid;
        }

        Update scope;

    }  

    public void finish(Database.BatchableContext BC) { }

}
3

You need to change your code somewhat to get it to even compile. Beyond that, you should move your update out of the loop.

public class UpdateContact implements Database.Batchable<sObject>
{
    public Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator([Select id, Profil__c from Contact__c];
        // above line was missing terminating semicolon
    }

    public void execute(Database.BatchableContext BC, List<Contact__c> scope){  
        for(Contact__c contactC:scope)
        {
            contactC.Profil__c = null;
        }
        // moved this closing bracket before the DML
        // so you can update entire collection at once
        update scope;
    }
    // this closing bracket was missing
    // so instead you declared the finish method here
    // which would cause a compile fail

    public void finish(Database.BatchableContext BC) { }
    // you had two closing brackets here
}
  • I did it and it doesn't work, the problem is contactC.Profil__c = null; Profil__c is a lookup field and it must refer to an id, so I got the error invalid ID – Oneal Revellin-Falcoz Aug 6 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.