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
Somasundaram S 1Somasundaram S 1 

afterupdate error

error afterupdate
I got below error
"update failed  Cannot_insert_update_activate_entity samplelotprocess: execution of afterupdate caused by ssytem dmlexception :update failed" 

i noticed error shows in line no 82 at the time of update any idea why please advise me


trigger SampleLotProcess on Sample_Lot__c (after insert, after update) {
    class SampleLotProcessHandler {
        Sample_Lot__c[] oldRows;
        Sample_Lot__c[] newRows;
        Map<Id, Sample_Lot__c> oldMap;
        Map<Id, Sample_Lot__c> newMap;
        
    Map<String, RecordType> rtMap;
        
        
        public void initialize(Sample_Lot__c[] oldRows, Sample_Lot__c[] newRows, Map<Id, Sample_Lot__c> oldMap, Map<Id, Sample_Lot__c> newMap) {
            this.oldRows = oldRows;
            this.newRows = newRows;
            this.oldMap = oldMap;
            this.newMap = newMap;
           
        }

        public void onAfterInsert() {
            createReceipts();
        }
        
        public void onAfterUpdate() {
            createReceipts();
        }   
        
        public void createReceipts() {
            Sample_Lot__c[] filteredRows = new Sample_Lot__c[0];
            Set<Id> transferIds = new Set<Id>();
            for (Sample_Lot__c item : newRows) {
                if (item.Status__c != 'Confirmed') continue;
                if (oldMap != null && item.Status__c == oldMap.get(item.Id).Status__c) continue;
                
                filteredRows.add(item);
                if (item.Original_Transfer_Transaction__c != null) {
                  transferIds.add(item.Original_Transfer_Transaction__c);
                }
            }            
            
            Sample_Transaction__c[] transfers = [select id, Status__c, Transferred_From__c  from Sample_Transaction__c where id in :transferIds];
            Map<Id, Sample_Transaction__c> transferMap;
            if (transfers.isEmpty()) {
                transferMap = new Map<Id, Sample_Transaction__c>();
            } else {
                transferMap = new Map<Id, Sample_Transaction__c>(transfers);
            }
            
            Sample_Transaction__c[] forIns = new Sample_Transaction__c[0];
            
            for (Sample_Lot__c item : filteredRows) {
                if (item.Status__c != 'Confirmed') continue;
                if (oldMap != null && item.Status__c == oldMap.get(item.Id).Status__c) continue;
                
                Sample_Transaction__c newReceipt = new Sample_Transaction__c();
                newReceipt.Transfer_To__c = item.OwnerId;
                newReceipt.Comments__c = item.Comments__c;
                newReceipt.Quantity__c = item.Confirmed_Quantity__c;
                newReceipt.OwnerId = item.OwnerId;
                newReceipt.Transfer_To__c = item.OwnerId;
                
                if (transferMap.containsKey(item.Original_Transfer_Transaction__c)) {
                    newReceipt.Transferred_From__c = transferMap.get(item.Original_Transfer_Transaction__c).Transferred_From__c;
                    transferMap.get(item.Original_Transfer_Transaction__c).Status__c = 'Confirmed';
                }
                
                if (getRtMap().containsKey('Reckitt_Receipt')) {
                    newReceipt.RecordTypeId = getRtMap().get('Reckitt_Receipt').Id;
                }     
                
                newReceipt.Product__c = item.Product_ID__c;
                newReceipt.Sample_Lot_ID__c = item.Id;
                newReceipt.Transaction_Date__c = Date.today();
                
                forIns.add(newReceipt);
            }
            
            if (!forIns.isEmpty()) {
                insert forIns;
            }
            
            if (!transferMap.isEmpty()) {
                update transferMap.values();
            }
        }
        
        public Map<String, RecordType> getRtMap() {
            if (rtMap == null) {
                rtMap = new Map<String, RecordType>();
                
                RecordType[] rtList = [select id, DeveloperName from RecordType where SObjectType = 'Sample_Transaction__c'];
                
                for (RecordType item : rtList) {
                    rtMap.put(item.DeveloperName, item);
                }
            }
            
            return rtMap;
        }
    }
    
    SampleLotProcessHandler handler = new SampleLotProcessHandler();
    handler.initialize(trigger.old, trigger.new, trigger.oldMap, trigger.newMap);
    
    if (trigger.isAfter && trigger.isInsert) {
        handler.onAfterInsert();
    } else if (trigger.isAfter && trigger.isUpdate) {
        handler.onAfterUpdate();
    }
}
Best Answer chosen by Somasundaram S 1
LBKLBK
It needs a good understanding of  your business case to suggest a perfect solution.

However, you need perfect your transferMap preparation logic to work with your Lookup filter output.

You may want to put some debug statements in the code which reads and writes to transferMap map object to see where exactly the road block is.

Hope this helps.

All Answers

LBKLBK
Can you please post your code using "Add a Code Sample" option?

And, please post your Trigger and Helper classes in different code blocks, so that it will be easy for us to debug.
Somasundaram S 1Somasundaram S 1
Please see below the details
when user login we load the below VF and 
<apex:page controller="MySamplesController">
    <apex:includeScript value="https://code.jquery.com/jquery-2.1.1.min.js"/>
    
    <apex:sectionHeader title="My Samples" subtitle="Home"/>
    

    <style>
        .columnA {
            width: 30%;
            font-weight: bold;
        }
        
        .columnB {
            width: 70%;
        }
    </style>         
    
    <script>
        $j = jQuery.noConflict();
        var rowid;

        function jsConfirmReceipt(aRowId) {
            rowid = aRowId;

            var pp = $j("#pSource div");
            showPopup('Confirm Receipt', pp.html(), 400, 300);
            
            if (receipts) {
                item =  $j.grep(receipts, function(e){ return e.Id == rowid; });
                if (item && item.length != 0) {
                    popupbox = $j("#" + window.box.id);
                    //popupbox.find('[data-id="from"]').text(item[0].Original_Transfer_Transaction__r.Owner.Name);
                    popupbox.find('[data-id="expirationDate"]').text(item[0].Expiration_Date__c);
                    popupbox.find('[data-id="lotName"]').text(item[0].Name);
                    popupbox.find('[data-id="shipmentDate"]').text(item[0].Shipped_Date__c);
                    popupbox.find('[data-id="product"]').text(item[0].Product_ID__r.Name);
                    popupbox.find('[data-id="quantity"]').text(item[0].Shipped_Quantity__c);

                }
                console.log(item);
            }            
        }
    
        SimpleDialog.prototype.setHeight = function(h) {        
            var b = this.getContentElement();
            b.style.height = h + "px"
        };    
               
        function showPopup(stitle, sbody, pWidth, pHeight){

          
            if (!pWidth) pWidth = 500;
            if (!pHeight) pHeight = 300; 
    
            if (window.box) {
                box = window.box;
            } else {
                box = new SimpleDialog("Test"+Dialogs.getNextId(), false);          
                box.allowKeyboardEsc = true;   
                box.createDialog(); 
                window.box = box; 
            }
            
            box.setTitle(stitle); 
            box.setContentInnerHTML(sbody);    
            box.setupDefaultButtons();
            //box.setHeight(pHeight); 
            box.setWidth(pWidth);
            box.show();    
        }

        function saveDialog() {
            popupbox = $j("#" + window.box.id);
            q = popupbox.find('[data-id$="itemquantity"]');
            c = popupbox.find('[data-id$="itemcomment"]');
            console.log(rowid, q.val(), c.val());
            
            confirmReceipt(rowid, q.val(), c.val());
            
            window.box.hide();
        }
    
        function hideDialog(){      
            window.box.hide();
        }    
    </script>
    
    <apex:form id="theForm">
        <apex:actionFunction action="{!confirmReceipt}" name="confirmReceipt" status="statusFilter" rerender="receiptBlock,theTables">
            <apex:param name="recid" value=""></apex:param>
            <apex:param name="quantity" value=""></apex:param>
            <apex:param name="comment" value=""></apex:param>
        </apex:actionFunction>
        
        <apex:pageBlock title="My Samples" mode="edit">
            <apex:pageBlockSection title="Sample Transactions" columns="1" collapsible="false">
                <p>
                    Use the sample transaction links below to record sample movements, adjustments, or inventories.
                </p>
                <apex:outputLink title="View Transactions" value="{!URLFOR('/a0i?fcf=00B240000051O0j')}">My Transactions</apex:outputLink>
                <apex:outputLink title="View Orders" value="{!URLFOR('/a0i?fcf=00B240000051O0i')}">My Orders</apex:outputLink>
                <apex:outputLink title="New Transfer" value="{!URLFOR($Action.Sample_Transaction__c.Edit, $ObjectType.Sample_Transaction__c, [RecordType=rtTransfer])}">New Transfer</apex:outputLink>
                <apex:outputLink title="New Return" value="{!URLFOR($Action.Sample_Transaction__c.Edit, $ObjectType.Sample_Transaction__c, [RecordType=rtReturn])}">New Return</apex:outputLink>
                <apex:outputLink title="Sample Inventory Report" value="{!URLFOR('/00O24000000fWDV')}">Sample Inventory Report</apex:outputLink>
            </apex:pageBlockSection>
    
            <apex:pageBlockSection title="Sample Storage Location" columns="1" collapsible="false">
                <apex:outputPanel rendered="{!IF(ISBLANK($User.Sample_Storage_Location__c), TRUE, FALSE)}">
                    No Sample Storage Location information is available.
                </apex:outputPanel>
                <apex:outputPanel rendered="{!IF(ISBLANK($User.Sample_Storage_Location__c), FALSE, TRUE)}">
                    {!$User.Sample_Storage_Location__c}
                </apex:outputPanel>
                
            </apex:pageBlockSection>
    
            <apex:pageBlockSection title="Pending Sample Receipts" columns="1" collapsible="false" id="receiptBlock">
                
                <apex:outputPanel rendered="{!pendingLots.size != 0}">
                    <div>
                        The following samples have been transferred to you. Please click the link to confirm the quantity received.
                    </div>                
                    
                    <script>
                        var receipts = JSON.parse('{!JSENCODE(jsonReceipts)}');
                        console.log(receipts);
                    </script>
                    
                    <apex:pageBlockTable value="{!pendingLots}" var="item">
                        <apex:column headerValue="Action">
                            <apex:outputLink value="#" onclick="jsConfirmReceipt('{!item.Id}');">Confirm</apex:outputLink>
                        </apex:column>
                        <apex:column headerValue="{!$ObjectType.Product__c.fields.Name.label}" value="{!item.Product_ID__r.Name}"/>
                        <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Name.label}" value="{!item.Name}"/>
                        <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Expiration_Date__c.label}" value="{!item.Expiration_Date__c}"/>                        
                        <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Shipped_Quantity__c.label}" value="{!item.Shipped_Quantity__c}"/>    
                        <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Shipped_Date__c.label}" value="{!item.Shipped_Date__c}"/>
                    </apex:pageBlockTable>            
                </apex:outputPanel>
                <apex:outputPanel rendered="{!pendingLots.size == 0}">
                    No Pending Receipt
                </apex:outputPanel>
            </apex:pageBlockSection>
    
            
            <apex:pageBlockSection title="Sample Lots" columns="1" collapsible="false">
                <!--apex:outputLink title="Add Sample Lots" value="{!URLFOR($Action.Sample_Lot__c.New)}">Add Sample Lot</apex:outputLink>
                <apex:outputLink title="View Sample Lots" value="{!URLFOR($Action.Sample_Lot__c.Tab, $ObjectType.Sample_Lot__c)}">View Sample Lots</apex:outputLink-->
                <p>
                    <b>Active Sample Lots</b>            
                </p>
                <apex:outputPanel id="theTables">
                    <apex:outputPanel >
                        <apex:pageBlockTable value="{!sampleLots}" var="item">
                            <apex:column headerValue="{!$ObjectType.Product__c.fields.Name.label}" value="{!item.Product_ID__r.Name}"/>
                            <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Name.label}" value="{!item.Name}"/>
                            <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Expiration_Date__c.label}" value="{!item.Expiration_Date__c}"/>
                            <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Active__c.label}">
                                <apex:inputCheckbox value="{!item.Active__c}">
                                    <apex:actionSupport event="onclick" action="{!saveLot}" status="statusFilter" rerender="theTables"/>
                                </apex:inputCheckbox>
                            </apex:column>
                            
                            
                        </apex:pageBlockTable>
                    </apex:outputPanel>
                    
                    <p>
                        <b>Inactive Sample Lots</b>
                    </p>
                    <apex:outputPanel >      
                        <apex:pageBlockTable value="{!inactiveSampleLots}" var="item">
                            <apex:column headerValue="{!$ObjectType.Product__c.fields.Name.label}" value="{!item.Product_ID__r.Name}"/>
                            <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Name.label}" value="{!item.Name}"/>
                            <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Expiration_Date__c.label}" value="{!item.Expiration_Date__c}"/>
                            <apex:column headerValue="{!$ObjectType.Sample_Lot__c.fields.Active__c.label}">
                                <apex:inputCheckbox value="{!item.Active__c}">
                                    <apex:actionSupport event="onclick" action="{!saveLot}" status="statusFilter" rerender="theTables"/>
                                </apex:inputCheckbox>
                            </apex:column>                            
                            
                        </apex:pageBlockTable>
                    </apex:outputPanel> 
                </apex:outputPanel>
            </apex:pageBlockSection>          
         
            <apex:actionStatus id="statusFilter">
                <apex:facet name="start">
                    <div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0.25; z-index: 1000; background-color: black;">
                        &nbsp;
                    </div>
                    <div style="position: fixed; left: 0; top: 0; bottom: 0; right: 0; z-index: 1001; margin: 15% 50%">
                        <div style="display: inline-block; padding: 2px; background-color: #fff; width: 125px;">
                            <img src="/img/loading.gif" style="float: left; margin: 8px;" />
                            <span style="display: inline-block; padding: 10px 0px;">Processing...</span>
                        </div>
                    </div>
                </apex:facet>
            </apex:actionStatus> 
            
        </apex:pageBlock>
        
        
        <div id="pSource" style="display: none;">
            <div>              
                <apex:panelGrid columns="2" columnClasses="columnA,columnB" style="width:100%">                
                    <!--apex:outputLabel value="{!$ObjectType.Sample_Transaction__c.fields.Transferred_From__c.label}"></apex:outputLabel>
                    <span data-id="from">
                        
                    </span-->                    
                    <apex:outputLabel value="{!$ObjectType.Product__c.fields.Name.label}"></apex:outputLabel>
                    <span data-id="product">
                        
                    </span>

                    <apex:outputLabel value="{!$ObjectType.Sample_Lot__c.fields.Name.label}"></apex:outputLabel>
                    <span data-id="lotName">
                        
                    </span>
                    <apex:outputLabel value="{!$ObjectType.Sample_Lot__c.fields.Expiration_Date__c.label}"></apex:outputLabel>
                    <span data-id="expirationDate">
                        
                    </span>                  

                    <apex:outputLabel value="{!$ObjectType.Sample_Lot__c.fields.Shipped_Quantity__c.label}"></apex:outputLabel>
                    <span data-id="quantity">
                        
                    </span>                  
                    <apex:outputLabel value="{!$ObjectType.Sample_Lot__c.fields.Shipped_Date__c.label}"></apex:outputLabel>
                    <span data-id="shipmentDate">
                        
                    </span>                    
                    <apex:outputLabel value="{!$ObjectType.Sample_Lot__c.fields.Confirmed_Quantity__c.label}"></apex:outputLabel>
                    <apex:inputField html-data-id="itemquantity" value="{!receipt.Confirmed_Quantity__c}" />
                    <apex:outputLabel value="{!$ObjectType.Sample_Lot__c.fields.Comments__c.label}"></apex:outputLabel>
                    <apex:inputField html-data-id="itemcomment" value="{!receipt.Comments__c}" style="width:100%"/>
                </apex:panelGrid>
                <span style="display: inline-block; padding: 10px 31%;">
                    
                    <apex:commandButton value="Confirm" action="{!confirmReceipt}" onclick="saveDialog();"/>
                    <apex:commandButton value="Cancel" onclick="hideDialog();"/>
                </span>
            </div>
        </div>   
        
    </apex:form>
    
  
    
    
</apex:page>

user get the below screen and when user click the confirm button the popup screen open and then he click confirm button in popup then 
User-added image


calling below trigger in an object 
 
trigger SampleLotProcess on Sample_Lot__c (after insert, after update) {
    class SampleLotProcessHandler {
        Sample_Lot__c[] oldRows;
        Sample_Lot__c[] newRows;
        Map<Id, Sample_Lot__c> oldMap;
        Map<Id, Sample_Lot__c> newMap;
        
    Map<String, RecordType> rtMap;
        
        
        public void initialize(Sample_Lot__c[] oldRows, Sample_Lot__c[] newRows, Map<Id, Sample_Lot__c> oldMap, Map<Id, Sample_Lot__c> newMap) {
            this.oldRows = oldRows;
            this.newRows = newRows;
            this.oldMap = oldMap;
            this.newMap = newMap;
           
        }

        public void onAfterInsert() {
            createReceipts();
        }
        
        public void onAfterUpdate() {
            createReceipts();
        }   
        
        public void createReceipts() {
            Sample_Lot__c[] filteredRows = new Sample_Lot__c[0];
            Set<Id> transferIds = new Set<Id>();
            for (Sample_Lot__c item : newRows) {
                if (item.Status__c != 'Confirmed') continue;
                if (oldMap != null && item.Status__c == oldMap.get(item.Id).Status__c) continue;
                
                filteredRows.add(item);
                if (item.Original_Transfer_Transaction__c != null) {
                  transferIds.add(item.Original_Transfer_Transaction__c);
                }
            }            
            
            Sample_Transaction__c[] transfers = [select id, Status__c, Transferred_From__c  from Sample_Transaction__c where id in :transferIds];
            Map<Id, Sample_Transaction__c> transferMap;
            if (transfers.isEmpty()) {
                transferMap = new Map<Id, Sample_Transaction__c>();
            } else {
                transferMap = new Map<Id, Sample_Transaction__c>(transfers);
            }
            
            Sample_Transaction__c[] forIns = new Sample_Transaction__c[0];
            
            for (Sample_Lot__c item : filteredRows) {
                if (item.Status__c != 'Confirmed') continue;
                if (oldMap != null && item.Status__c == oldMap.get(item.Id).Status__c) continue;
                
                Sample_Transaction__c newReceipt = new Sample_Transaction__c();
                newReceipt.Transfer_To__c = item.OwnerId;
                newReceipt.Comments__c = item.Comments__c;
                newReceipt.Quantity__c = item.Confirmed_Quantity__c;
                newReceipt.OwnerId = item.OwnerId;
                newReceipt.Transfer_To__c = item.OwnerId;
                
                if (transferMap.containsKey(item.Original_Transfer_Transaction__c)) {
                    newReceipt.Transferred_From__c = transferMap.get(item.Original_Transfer_Transaction__c).Transferred_From__c;
                    transferMap.get(item.Original_Transfer_Transaction__c).Status__c = 'Confirmed';
                }
                
                if (getRtMap().containsKey('Reckitt_Receipt')) {
                    newReceipt.RecordTypeId = getRtMap().get('Reckitt_Receipt').Id;
                }     
                
                newReceipt.Product__c = item.Product_ID__c;
                newReceipt.Sample_Lot_ID__c = item.Id;
                newReceipt.Transaction_Date__c = Date.today();
                
                forIns.add(newReceipt);
            }
            
            if (!forIns.isEmpty()) {
                insert forIns;
            }
            
            if (!transferMap.isEmpty()) {
                update transferMap.values();
            }
        }
        
        public Map<String, RecordType> getRtMap() {
            if (rtMap == null) {
                rtMap = new Map<String, RecordType>();
                
                RecordType[] rtList = [select id, DeveloperName from RecordType where SObjectType = 'Sample_Transaction__c'];
                
                for (RecordType item : rtList) {
                    rtMap.put(item.DeveloperName, item);
                }
            }
            
            return rtMap;
        }
    }
    
    SampleLotProcessHandler handler = new SampleLotProcessHandler();
    handler.initialize(trigger.old, trigger.new, trigger.oldMap, trigger.newMap);
    
    if (trigger.isAfter && trigger.isInsert) {
        handler.onAfterInsert();
    } else if (trigger.isAfter && trigger.isUpdate) {
        handler.onAfterUpdate();
    }
}
and got error like below  any idea why 
User-added image
please advise me 

thanks
soma
 
LBKLBK
Hi Soma,

From the error screen shot, I believe that this error is caused by either a Validation Rule or a Lookup Filter set on the Sample_Lot__c object.

Can you check if there is a validation rule that shows a message like "Only confirmed Sample Lots are available"?
Somasundaram S 1Somasundaram S 1
wow LBK you are great .
yes one of the field uses below lookup , once i disbale filter it works fine but what could be the best solution without disbale the lookup filter
((Sample Transaction: Record TypeequalsReckitt Transfer, Reckitt Return) and (Sample Lot: StatusequalsConfirmed) and (Sample Lot: Owner IDequalsCurrent User: User ID)) or (Sample Transaction: Record Typenot equal toReckitt Return, Reckitt Transfer)
LBKLBK
It needs a good understanding of  your business case to suggest a perfect solution.

However, you need perfect your transferMap preparation logic to work with your Lookup filter output.

You may want to put some debug statements in the code which reads and writes to transferMap map object to see where exactly the road block is.

Hope this helps.
This was selected as the best answer