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
AB003AB003 

Validation Error due to Apex Class

Hi All,

 

I have a Apex Class. THis is used in creating new cases. THe problem is if I create a validation rules it throw an error  when new cases is created. I am not sure why this is happening as I didn't write this code. Any help is appreciated.

 

Error: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Please select Type and Category:

Error is in expression '{!insertAndRedirect}' in component <apex:page> in page cases_new

 

An unexpected error has occurred. Your development organization has been notified

 

Code:

public with sharing class cases_Extension {

    public case thisCase {get;set;}
    public List<Case> theseCases {get;set;}
    
    public cases_Extension(ApexPages.StandardController controller){
        this.thisCase = (Case) controller.getRecord();
        this.theseCases = new List<Case>();
    }
    
    public cases_Extension(ApexPages.StandardSetController controller){
        this.theseCases = (List<Case>) controller.getRecords();
    }


    public PageReference insertAndRedirect(){
        //If DID__c is populated, Query DIDs
        if ( thisCase.Did__c != null && (thisCase.AccountId == null || thisCase.ContactId == null )){
            List<DID__c> didQuery = [Select Id, Account__c, Contact__c from DID__c where Id = :thisCase.Did__c limit 1];
            if ( didQuery.size() > 0 ){
                DID__c thisDid = didQuery[0];
                if ( thisCase.AccountId == null && thisDID.Account__c != null ){
                    thisCase.AccountId = thisDID.Account__c;
                } 
                if ( thisCase.ContactId == null && thisDID.Contact__c != null ){
                    thisCase.ContactId = thisDID.Contact__c;
                } 
            } 
        }


        insert thisCase;
        String url = '/'+thisCase.id+'/e?retURL=' + EncodingUtil.urlEncode('/500/o','UTF-8');
        PageReference p = new PageReference(url);
        return p;
    }

    public PageReference getNextCase(){
        //Determine current user
        Id userId = userinfo.getUserId();
        Set<Id> listQueueIds = new Set<id>();
        Set<Id> myQueueIds = new Set<id>();
        List<Case> caseQuery = new List<Case>();
        
        if ( theseCases.size() > 0 ){
            for ( Case c : theseCases ){
                if ( string.valueOf(theseCases[0].OwnerId).subString(0,3) != '005' ){
                    myQueueIds.add( theseCases[0].OwnerId );
                }
            }
            if ( myQueueIds.size() > 0 ){
                caseQuery = [Select Id, CreatedDate, IsClosed from Case where OwnerId in :myqueueIds and IsClosed != TRUE order by CreatedDate asc limit 1];
            }
        }

        if ( caseQuery.size() == 0){
            for ( GroupMember gm : [Select UserOrGroupId, Group.Type, Group.RelatedId, Group.Name, GroupId From GroupMember where Group.Type = 'Queue' and UserOrGroupId = :userId]){
                listQueueIds.add(gm.GroupId);
            }
            caseQuery = [Select Id, CreatedDate, IsClosed from Case where OwnerId in :listQueueIds and IsClosed != TRUE order by CreatedDate asc limit 1];
        }

        if ( caseQuery.size() > 0 ){
            thisCase = caseQuery[0];
            thisCase.OwnerId = userId;
            update thisCase;
            PageReference p = new PageReference('/'+thisCase.id);
            return p;
        } else {
            PageReference p = new PageReference('/500/o');
            return p;
        }
    }

    public PageReference replyToCase(){
        if ( string.valueOf(thisCase.OwnerId).subString(0,3) != '005' ){
            thisCase.OwnerId = userInfo.getUserId();
            update thisCase;
        }
        String templateId = '00X60000000xlFf';  //Sandbox
//      String templateId = '00XR0000000MJWr';  //Production
        
        PageReference p = new PageReference('/_ui/core/email/author/EmailAuthor?p2_lkid='+ thisCase.ContactId + '&p3_lkid=' +  thisCase.Id + '&rtype=003&template_id=' + templateId + '&p26=' + thisCase.From__c + '&retURL=%2F' + thisCase.Id);
        p.setRedirect(true);
        return p;
    }

}

Best Answer chosen by Admin (Salesforce Developers) 
aj2taylo2aj2taylo2

Just glancing at the error, my guess is the Type and Category fields aren't being set.  Can you set default values for these if not set before inserting?

 

 

All Answers

Jeff MayJeff May

The key is that this code is creating a Case without setting the Type and Category fields (those are the fields referenced in the VALIDATION error message.  If you want to add those validation rules, you'll need to update the Apex code to make sure any cases created pass the validation.

aj2taylo2aj2taylo2

Just glancing at the error, my guess is the Type and Category fields aren't being set.  Can you set default values for these if not set before inserting?

 

 

This was selected as the best answer
avijchakavijchak

Required valus are missing while inserting record. deactivate the rule and check

 

@avijit Capgemini Developer

AB003AB003

Hi THanks for reply.

 

Yes deactivating the rule will work. But I dont want deactivate the VR.

 

Also, I set default values for type and category and it worked. But since I don't want to set any default for these field is there any alternative way? Because everytime I create some new valdiation rules, I cannot set a default value everytime for the corresponding fields I used in the rules. How to avoid this error in the code itself?

 

Thanks

Abhishek

aj2taylo2aj2taylo2

You can't have it both ways;  if the validation rules are there and the field values aren't set, you'll get errors.  Using defaults is the easiest way to get around this.

 

 

avijchakavijchak

It can be done in two ways

1) ADD NOT(ISNEW()) to the validation rule only work no one is creating the record from UI.
2) Add one checkbox field to the object From_APEX__C
   OR
   (
        AND (
                ISNEW(),
                From_APEX__C = TRUE
            ),
        AND (
                NOT(ISNEW()),
                ISCHANGED(From_APEX__C )
            )
                
   
   )
   
   Hope this help , If it satisfied your requirment then mart it helpful

 

@vijit Capgemini Developer

avijchakavijchak
It shod be NOT(ISCHANGED()) and change every time when you want to by pass validation rule it worked for me many times
avijchakavijchak

It should be NOT(ISCHANGED()) and change every time when you want to by pass validation rule it worked for me many times