0

I have fetched field value on account I want to compare the values like contains function

public class CreateOppExtension 
{
    Opportunity opp{set;get;}
    public string Customergrp; 


    public CreateOppExtension(ApexPages.StandardController stdController)
    {   

        opp = (Opportunity)stdController.getRecord();
        opp.AccountId =apexpages.currentpage().getparameters().get('AccountId');
        opp.Master_Account__c=apexpages.currentpage().getparameters().get('AccountId');
        Customergrp = [select Customer_Group_Trio__c from Account where id = :opp.AccountId limit 1].Customer_Group_Trio__c;  
    }
    public PageReference save()
    { 
        if(Customergrp.IndexOf(opp.Customer_Group_ERP__c) != -1)
        {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Customer_Group_ERP__c Mismatch');
            ApexPages.addMessage(myMsg);
            return null;  

        }
    }
}

Customergrp - "6220 - UNASSIGNED CUSTOMER" and Customer_Group_ERP__c - "6119".

If both the values don't match first four digit it should throw error.

  • Don't forget to vote if it working for you. – NITHESH K Aug 18 '17 at 12:54
1

Actually Apex strings do have a contains method, unlike a lot of programming languages. You use it like so:

Syntax

contains(substring)

Returns true if and only if the String that called the method contains the specified sequence of characters in substring. Signature

public Boolean contains(String substring)

Parameters

substring - Type: String

Return Value - Type: Boolean

Solution

Boolean result=Customergrp.contains(opp.Customer_Group_ERP__c);

It returns true if the sequence of characters appears in the String.

You need to change the Save() function as below mentioned

public PageReference save() { 
if(Customergrp.contains(opp.Customer_Group_ERP__c)){
   ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Customer_Group_ERP__c Mismatch');
   ApexPages.addMessage(myMsg);
   return null;  
 }   
}
  • 1
    Your code could be shortened here. If you're testing a boolean, you don't need to explicitly check to see if it's true or false. if(result == true) could be replaced with if(result). Since the boolean result isn't being used anywhere else, you could skip assigning the result of String.contains(), and just use it directly in the if() like if(Customergrp.contains(opp.Customer_Group_ERP__c)) – Derek F Aug 18 '17 at 13:07

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.