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
sksfdc221sksfdc221 

Check if current record value present in other records

I have a requirement, where account name and account number if do not match with any other records, a custom field called alert_text__c will be updated with some text.

Below is the code snippet:
 
List<Account_Codes__c> records = [SELECT ID, Account_Name__c, Account_Number__c from Account_Codes__c where Account_Name__c != Null AND Account_Number__c != Null]; 

final String accName = newPPAs[0].Account_Name__c;
final String accNum = newPPAs[0].Account_Number__c;
for (Account_Codes__c record : records)
{
    if (record.Account_Name__c != accName && record.Account_Number__c != accNum)
    {
        record.Alert_Text__c = 'Account Number and Account Names are different';
    }
}

Now, the above logic is not working as expected and even when i provide different Account Name and Account Numbers, I am not able to populate the text in Alert_text__c field.

Can anyone please suggest changes in the above code so that i can get this done.

Thanks!
Abhishek BansalAbhishek Bansal
Hi,

You need to update the records after adding the value in this field. You can use the code below:
List<Account_Codes__c> records = [SELECT ID, Account_Name__c, Account_Number__c from Account_Codes__c where Account_Name__c != Null AND Account_Number__c != Null]; 

final String accName = newPPAs[0].Account_Name__c;
final String accNum = newPPAs[0].Account_Number__c;

List<Account_Codes__c> updateList = new List<Account_Codes__c>();
for (Account_Codes__c record : records)
{
    if (record.Account_Name__c != accName && record.Account_Number__c != accNum)
    {
        record.Alert_Text__c = 'Account Number and Account Names are different';
		updateList.add(record);
    }
}

if(updateList.size() > 0) {
	update updateList;
}

Let me know if you need more help.

Thanks,
Abhishek Bansal.
sksfdc221sksfdc221
@Abhishek Bansal,

The suggest logic didnt work. I didnt get any error but the warning message isnt getting displayed.

I have updated the logic and even then it didnt work. Below is my updated logic
List<Account_Codes__c> records = [SELECT ID, Account_Name__c, Account_Number__c from Account_Codes__c where Account_Name__c != Null AND Account_Number__c != Null]; 

final String accName = records[0].Account_Name__c;
final String accNum = records[0].Account_Number__c;

List<Account_Codes__c> updateList = new List<Account_Codes__c>();
for (Account_Codes__c record : records)
{
    if (record.Account_Name__c != accName && record.Account_Number__c != accNum)
    {
        record.Alert_Text__c = 'Account Number and Account Names are different';
		updateList.add(record);
    }
}

if(updateList.size() > 0) {
	update updateList;
}

Could you please suggest the changes if possible?