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
Firas Taamallah 18Firas Taamallah 18 

How to count number of comma in Text field and then update another field? APEX Trigger

Example : 

Field1 :  BL1,BL2
Field2 : 1
Suraj Tripathi 47Suraj Tripathi 47
Hi Firas Taamallah,
Greetings!

My code is for Account Object, Please change according to your required object.
trigger CountComma on Account(before insert) {
    for(Account acc : trigger.new) {
        if(acc.Field1__c.contains(',')) {
            acc.Field2__c = acc.Field1__c.countMatches(',');
        }
        else {
            acc.Field2__c = 0;
        }
    }
}

If you find your Solution then mark this as the best answer. 

Thank you!

Regards,
Suraj Tripathi
CharuDuttCharuDutt
Hii Firaz
Try Below Code
trigger TestTrigger on Account (before insert , before update) {
if(Trigger.IsBefore && (trigger.IsInsert || trigger.IsUpdate)){
    for(Account acc : trigger.new) {
        if(acc.Field1__c.contains(',')) {
            acc.Field2__c = acc.Field1__c.countMatches(',');
        }
        else {
            acc.Field2__c = 0;
            }
        }
    }
}

OR

It Can Also  Be Done By Formula Field Data Type (Number)

LEN(Field1 ) - LEN( SUBSTITUTE(Field1 , ',', '') )


Please Mark It As Best Answer If It Helps
Thank You!