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
David OvellaDavid Ovella 

​error message of duplicate values not working well

I am working with a trigger, apex and a visualforce page,
trying to display in my vfpage the error of duplicate values, and it works kind of.
The error message appears in my visual, but it is giving me all the records created in my Factura__c
and not the one of duplicate value. I think is because my trigger it not working well
Example:

In the top of my visual is showing me 3 errors and that is because there 3 records created in my Factura__c
and the only one that it should be displaying it is in the red box.

My object is Factura__c and the custom field that it should not have duplicate values is called Pre_impreso_001_001__c

User-added image


my trigger
trigger MensajeValorDuplicadoCentro on Factura__c (before insert, before update) {

    Map<Decimal, Factura__c> facMap = new Map<Decimal, Factura__c>();

    For (Factura__c factura : System.Trigger.new) {     
        If ((factura.Pre_impreso_001_001__c != null) && (System.Trigger.isInsert ||
        (factura.Pre_impreso_001_001__c != System.Trigger.oldMap.get(factura.Id).Pre_impreso_001_001__c))){            
            facMap.put(factura.Pre_impreso_001_001__c, factura);                
        }                  
    }
  

    For (Factura__c factura : [SELECT Id, Name, Sucursal__c FROM Factura__c]) {  		
        If (factura.Sucursal__c=='Maker Centro'){      	
            For (Factura__c facturace : [SELECT Pre_impreso_001_001__c FROM Factura__c WHERE Pre_impreso_001_001__c IN :facMap.KeySet()]) {                                                                
                Factura__c newFactura = facMap.get(facturace.Pre_impreso_001_001__c);                  
                newFactura.addError('El #Pre-Impreso(001-001) ingresado ya fue utilizado en la Factura:<a href=\'https://cs21.salesforce.com/'+factura.Id+'\'>'+factura.Name+'</a>', false);           
            }       	
        } 
    } 

}


my visual
<apex:page controller="FacturaRapidaController" tabStyle="Factura__c">  
    <script>     
    function confirmarCancelar() {           
        var isCancel = confirm("Estas seguro que desea cancelar la creación de Factura?");        
        if (isCancel)return true;    
        return false;
    } 
    </script>     
    <apex:sectionHeader title="Creación de" subtitle="FACTURA"/>                  
    <apex:form >      
        <apex:pageBlock mode="edit" title="Crear Factura Contado">                
                         
          	<div style="font-size: 12px; color:#FF0000;">                                                                                              
        		<apex:pageMessages id="errMessages" escape="false"/>                                                                  
    		</div>    
            <apex:pageBlockButtons >                          
                <apex:commandButton action="{!guardarFactura}" value="Guardar"/>                                
                <apex:commandButton action="{!cancelarFactura}" value="Cancelar" onclick="return confirmarCancelar()" immediate="true"/>                      
            </apex:pageBlockButtons> 
            
            <apex:pageBlockSection title="Información Básica de la Factura" columns="1">                                     
                <apex:inputField value="{!factura.Pre_Factura__c}"/>                 
                <apex:inputField value="{!factura.Sucursal__c}" required="true"/>                
                <apex:inputField value="{!factura.Caja__c}" required="true"/>                        
                <apex:inputField value="{!factura.Serie__c}" required="true"/>                
            </apex:pageBlockSection>   
                                 
            <apex:pageBlockSection title="Confirmar Factura" columns="1">            
                <apex:inputField value="{!factura.Pre_impreso_001_001__c}"/>                                                                                                                  
            </apex:pageBlockSection>                                      
        </apex:pageBlock>       
    </apex:form>
</apex:page>



my apex
public PageReference guardarFactura(){                  
        try{ 
            insert factura; 
        }
        catch(exception ex) {  
            ApexPages.addMessages(ex);
            return null;
        }

        PageReference FacturaRapidaPage = new ApexPages.StandardController(factura).view();
        FacturaRapidaPage.setRedirect(true);
        return FacturaRapidaPage;
    }




 
Best Answer chosen by David Ovella
Abhishek_DEOAbhishek_DEO
Could be because of 2nd FOR loop.It is iterating on all RECORD

Can you change as given below and see of ot helps?


For (Factura__c factura : [SELECT Id, Name, Sucursal__c FROM Factura__c WHERE Pre_impreso_001_001__c IN :facMap.KeySet()])
{
If (factura.Sucursal__c=='Maker Centro')
{
Factura__c newFactura = facMap.get(facturace.Pre_impreso_001_001__c);
newFactura.addError('El #Pre-Impreso(001-001) ingresado ya fue utilizado en la Factura:<a href=\'https://cs21.salesforce.com/'+factura.Id+'\'>'+factura.Name+'</a>', false);
}


All Answers

Abhishek_DEOAbhishek_DEO
Could be because of 2nd FOR loop.It is iterating on all RECORD

Can you change as given below and see of ot helps?


For (Factura__c factura : [SELECT Id, Name, Sucursal__c FROM Factura__c WHERE Pre_impreso_001_001__c IN :facMap.KeySet()])
{
If (factura.Sucursal__c=='Maker Centro')
{
Factura__c newFactura = facMap.get(facturace.Pre_impreso_001_001__c);
newFactura.addError('El #Pre-Impreso(001-001) ingresado ya fue utilizado en la Factura:<a href=\'https://cs21.salesforce.com/'+factura.Id+'\'>'+factura.Name+'</a>', false);
}


This was selected as the best answer
David OvellaDavid Ovella
thanks Abhishek, it work perfect now.
by any chance, do you know a example of  test code to this trigger?
Abhishek_DEOAbhishek_DEO
You just need to insert a record with an existing value of "Pre_impreso_001_001__c".However, it is little bit tricky


to cover a trigger having addError() method because test class will get fail if you do not handle it properly. 

You may start by looking into below link


http://www.infallibletechie.com/2015/10/how-to-cover-adderror-in-trigger-in.html


and also a similar post (http://salesforce.stackexchange.com/questions/8814/trigger-adderror-on-before-will-not-pass-my-test-class)