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
Vanitha ManiVanitha Mani 

Trigger for table

Hi i have a link table which when row is selected it should attach to case.as of now multiple attachments can be done..but my requirement is to attach only one rw..when other row selected old attached row should get deleted and new row should be attcahed ..how can i attach this through trigger or any workaround.
My link table code
Controller:
global with sharing class SVC_Problem_Incident_Ctl extends SVC_Link_Ctl_Helper
{
    /**
     * Class controller
     */
    public SVC_Problem_Incident_Ctl()
    {
        // init class
        init();

        // configure assignments object
        if (sourceObjectName == 'Case') {
            configure('SVC_Incident_Problem_Link__c', 'Problem__c', 'Incident__c');
            
        } else if (sourceObjectName == 'SVC_Problem__c') {
            configure('SVC_Incident_Problem_Link__c', 'Incident__c', 'Problem__c');
        }

        if(sourceObjectName == 'Case') {
            // setup filters object
            filters = new Case(
                // set default status to empty value ...
                Status                     = '',
                // emulates from date filter ...
                Due_Date__c                = Date.today().addDays(-60),
                // emulate to date filter ...
                Estimated_Shipment_Date__c = Date.today()
            );

            // restrict to system / product only
            List<SVC_Problem__c> productList = [SELECT System__c, Product__c FROM SVC_Problem__c WHERE Id = :targetObjectId];
            if (!productList.isEmpty()) {
                if (!String.isEmpty(productList.get(0).System__c)) {
                    selectedSystemId  = productList.get(0).System__c;
                }
                if (!String.isEmpty(productList.get(0).Product__c)) {
                    selectedProductId = productList.get(0).Product__c;
                }
            }
        }
        if (sourceObjectName == 'SVC_Problem__c') {
            List<Case> caseList = [SELECT Actual_System__c, Actual_Product__c FROM Case WHERE Id = :targetObjectId];
            if (!caseList.isEmpty()) {
                selectedSystemId  = caseList.get(0).Actual_System__c;
                selectedProductId = caseList.get(0).Actual_Product__c;
            }
        }
    }

    /**
     * Method returns data matching search critieria
     *
     * @param  params Map of parameters
     * @return        DataTableWrapper object
     */
    @RemoteAction
    global static DataTableWrapper getData(Map<String, String> params)
    {
        // pagination related items
        Integer startVal         = params != null && params.containsKey('start') ? Integer.valueOf(params.get('start')) : 0;
        Integer lengthVal        = params != null && params.containsKey('length') ? Integer.valueOf(params.get('length')) : 10;

        // sorting related items
        String orderBy           = params != null && params.containsKey('orderBy') ? params.get('orderBy') : 'Id';
        String orderDir          = params != null && params.containsKey('orderDir') ? params.get('orderDir') : 'asc';

        // config related items
        String sourceObjectName  = params != null && params.containsKey('sourceObjectName') ? params.get('sourceObjectName') : null;
        String targetObjectId    = params != null && params.containsKey('targetObjectId') ? params.get('targetObjectId') : null;
        String fieldSetName      = params != null && params.containsKey('fieldSetName') ? params.get('fieldSetName') : 'Search_List_Columns';
        Integer draw             = params != null && params.containsKey('draw') ? Integer.valueOf(params.get('draw')) : 0;

        // search value
        String searchValue       = params != null && params.containsKey('search') ? params.get('search') : null;

        // custom args
        String selectedSystemId  = params != null && params.containsKey('selectedSystemId')  ? params.get('selectedSystemId') : null;
        String selectedProductId = params != null && params.containsKey('selectedProductId') ? params.get('selectedProductId') : null;

        // extract filter values
        String status            = params != null && params.containsKey('status') ? params.get('status') : null;
        DateTime fromDate        = params != null && params.containsKey('fromDate') ? SVC_Link_Ctl_Helper.getDateTime(params.get('fromDate')) : null;
        DateTime toDate          = params != null && params.containsKey('toDate') ? SVC_Link_Ctl_Helper.getDateTime(params.get('toDate')) : null;

        // Initialize values
        Integer totalCount       = 0;
        Integer filteredCount    = 0;
        String query             = '';

        if (sourceObjectName == 'SVC_Problem__c') {
            query = 'SELECT ';
            query += ' count() ';
            query += ' FROM ' + sourceObjectName;
            query += ' WHERE ';
                query += ' Id NOT IN (SELECT Problem__c FROM SVC_Incident_Problem_Link__c WHERE Incident__c = :targetObjectId) ';
            if (!String.isEmpty(selectedSystemId)) {
                query += ' AND ';
                    query += ' System__c = :selectedSystemId';
                if (!String.isEmpty(selectedProductId)) {
                    query += ' AND ';
                        query += ' Product__c = :selectedProductId';
                }
            }
        } else if (sourceObjectName == 'Case') {
            Id recordTypeId   = [SELECT Id FROM RecordType WHERE DeveloperName = 'Systems_Incident'].get(0).Id;

            List<String> statuses;
            SVC_General_Service_Settings__c config = SVC_General_Service_Settings__c.getInstance();
            if (status == 'Open') {
                statuses = config.Incident_Status_As_Open__c != null ? config.Incident_Status_As_Open__c.split(',') : new List<String>();
            } else if (status == 'Closed'){
                statuses = config.Incident_Status_As_Closed__c != null ? config.Incident_Status_As_Closed__c.split(',') : new List<String>();
            }

            query = 'SELECT ';
            query += ' count() ';
            query += ' FROM ' + sourceObjectName;
            query += ' WHERE ';
                query += ' Id NOT IN (SELECT Incident__c FROM SVC_Incident_Problem_Link__c WHERE Problem__c = :targetObjectId) ';
            query += ' AND ';
                query += ' RecordTypeId = :recordTypeId';

            // add custom params
            if (statuses != null && !statuses.isEmpty()) {
                query += ' AND ';
                    query += ' Status IN :statuses';
            }
            if (fromDate != null) {
                fromDate = fromDate.addDays(-1);
                query += ' AND ';
                    query += ' CreatedDate > :fromDate';
            }
            if (toDate != null) {
                toDate = toDate.addDays(1);
                query += ' AND ';
                    query += ' CreatedDate < :toDate';
            }
            if (!String.isBlank(selectedSystemId)) {
                query += ' AND ';
                    query += ' System__c = :selectedSystemId';
                if (!String.isBlank(selectedProductId)) {
                    query += ' AND ';
                        query += ' Product__c = :selectedProductId';
                }
            }
        }

        // 10000 is max supported
        totalCount = Database.countQuery(query + ' LIMIT 10000');

        // add search conditions based on user input
        query += SVC_Link_Ctl_Helper.buildSearchString(sourceObjectName, fieldSetName, searchValue);

        // 10000 is max supported
        filteredCount = Database.countQuery(query + ' LIMIT 10000');

        query  = query.replace('count()', SVC_Link_Ctl_Helper.getColumnList(sourceObjectName, fieldSetName));
        // order by requested params
        query += ' ORDER BY ' + orderBy + ' ' + orderDir + (orderDir == 'asc' ? ' NULLS FIRST' : ' NULLS LAST');
        // add limit equal to number of records per page multiplied by current page number so we limit number of records to be processed
        query += ' LIMIT ' + String.valueOf(startVal == 0 ? lengthVal : (startVal + 1) * lengthVal);

        // intialize standard controller with query
        ApexPages.StandardSetController setCon = new ApexPages.StandardSetController(Database.getQueryLocator(query));
        setCon.setPageSize(lengthVal);

        // set page number
        setCon.setPageNumber((startVal / lengthVal) + 1);

        // create wrapper
        return new DataTableWrapper (
            draw,
            totalCount,
            filteredCount,
            setCon.getRecords()
        );
    }
}
SubratSubrat (Salesforce Developers) 
Hello ,

To achieve the requirement of attaching only one row from the link table to the case and removing the previously attached row if a new one is selected, you can handle this logic in the Apex controller or in a trigger. I'll provide you with an example of how to implement it in the Apex controller.

Add a new custom field to the Case object to store the Id of the attached row from the link table. Let's call this field Attached_Row__c (you can change the name as per your preference).
Update the controller class to handle the attachment logic:
public with sharing class SVC_Problem_Incident_Ctl extends SVC_Link_Ctl_Helper {
    // ... Existing code ...

    // Method to handle attaching a row from the link table to the case
    @RemoteAction
    global static String attachRowToCase(Id caseId, Id rowId) {
        try {
            Case caseRecord = [SELECT Attached_Row__c FROM Case WHERE Id = :caseId];
            
            if (caseRecord.Attached_Row__c != null) {
                // Detach the previously attached row
                detachRowFromCase(caseId, caseRecord.Attached_Row__c);
            }

            // Attach the new row to the case
            caseRecord.Attached_Row__c = rowId;
            update caseRecord;

            return 'SUCCESS';
        } catch (Exception ex) {
            return 'ERROR';
        }
    }

    // Method to handle detaching a row from the case
    @RemoteAction
    global static String detachRowFromCase(Id caseId, Id rowId) {
        try {
            Case caseRecord = [SELECT Attached_Row__c FROM Case WHERE Id = :caseId];
            
            if (caseRecord.Attached_Row_c != null && caseRecord.Attached_Row_c == rowId) {
                // Detach the row from the case
                caseRecord.Attached_Row__c = null;
                update caseRecord;
            }

            return 'SUCCESS';
        } catch (Exception ex) {
            return 'ERROR';
        }
    }

    // ... Rest of the controller code ...
}
Modify the Lightning component to call the new Apex methods:
Update the handleClick function in the Lightning component to call the new Apex methods for attaching and detaching the rows.
({
    handleClick: function (component, event, helper) {
        var action = component.get('c.attachRowToCase');
        var recordId = component.get("v.recordId");
        var rowId = event.getSource().get("v.value");

        action.setParams({
            caseId: recordId,
            rowId: rowId
        });

        action.setCallback(this, function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                if (result === "SUCCESS") {
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        "title": "Success!",
                        "message": "Row attached to case",
                        "type": "success"
                    });
                    toastEvent.fire();
                } else {
                    var toastEvent = $A.get("e.force:showToast");
                    toastEvent.setParams({
                        "title": "Error!",
                        "message": "Error attaching row to case",
                        "type": "error"
                    });
                    toastEvent.fire();
                }
            } else {
                // Handle the error state
                var errors = response.getError();
                if (errors) {
                    for (var i = 0; i < errors.length; i++) {
                        console.error("Error: " + errors[i].message);
                    }
                } else {
                    console.error("Unknown error");
                }
            }
        });

        $A.enqueueAction(action);
        $A.get('e.force:refreshView').fire();
    },

    // ... Rest of the controller code ...
})
With these modifications, your Lightning component will now allow attaching only one row from the link table to the case. If a new row is selected, the previously attached row will be automatically detached, and the new row will be attached. The Attached_Row__c field on the Case object will store the Id of the currently attached row from the link table.

Thank you.