trigger CountingValues on MyObject__c (before insert, before update) {
if (Trigger.isUpdate) {
for (MyObject__c mo : Trigger.new) {
if (mo.Colors__c != Trigger.oldMap.get(mo.Id).Colors__c) {
if (String.isNotBlank(mo.Colors__c) {
List<String> colors = mo.Colors__c.split(';');
mo.ColorsCount__c = colors.size();
} else {
mo.ColorsCount__c = 0;
}
}
}
}
}
If you want to implement it the formula then:
Create a new field on the opportunity object:
Datetype = Formula
Result Type = Number
Formula =
IF(INCLUDES( Multi_Picklist_1__c, "A"), 1,0) +
IF(INCLUDES( Multi_Picklist_1__c, "B"), 1,0) +
IF(INCLUDES( Multi_Picklist_1__c, "C"), 1,0) +
IF(INCLUDES( Multi_Picklist_1__c, "D"), 1,0) +
IF(INCLUDES( Multi_Picklist_1__c, "E"), 1,0) +
IF(INCLUDES( Multi_Picklist_1__c, "F"), 1,0)
Thank you very much for your response. My requirement is to display a message on VF page when user selects more than 4 options from multiselect picklist.
Please check the following sample code:
If you want to implement it the formula then:
Also look into the below URL
http://mysalesforcecode.blogspot.com/2010/06/count-selected-items-in-multipicklist.html
Please let me know if it helps.
Regards,
Mahesh
for (Account Acc : Trigger.new) {
If(acc.Package__c !=null) {
integer count = acc.Package__c.countMatches(';')+1;
acc.Package_Choose__c = count;
}
else {
acc.Package_Choose__c = 0;
}
}
}
trigger CountCounter on Opportunity (before insert,before update) {
for (Opportunity opp : Trigger.new) {
If(opp.POI__c !=null) {
integer count = opp.POI__c.countMatches(';')+1;
opp.PCount__c = count;
}
else {
opp.PCount__c = 0;
}
}
}
Below is my trigger code:
trigger AccountMobileCounter on Account (before insert,before update) {
List<String> mobilesSelected = new List<String>();
Integer counter;
for(Account acc: Trigger.new){
String multiselect = acc.Phones__c;
if(multiselect!=null){
mobilesSelected = multiselect.split(';');
counter = mobilesSelected.size();
acc.Counter__c = counter;
//system.debug(counter);
//system.debug(mobilesSelected);
}else{
acc.Counter__c = 0;
}
}
}
Hope this answer helps you.