0

I have build a lightning component that I want to give some more additional features. By the hit of a button I want the according record to get updated. This is what it looks like as for now:

enter image description here

Unfortunately I am not yet able to pass the record id dynamically to my controller. Here is my code:

Apex Class:

public with sharing class CommunicationTouchpoint {
@AuraEnabled

public static List<Communication_Touchpoint__c> getList (String recordId) {

list<Communication_Touchpoint__c> CT = [

    SELECT Name, F_lligkeitsdatum__c, Art__c,Typ__c,Status__c,Abgeschlossen_am__c, Kategorie__c,Anzeige__c,CampaignId__c
    FROM Communication_Touchpoint__c
    WHERE Account__c = :recordId
    ORDER BY F_lligkeitsdatum__c ASC
    ];
    return CT;
}


@AuraEnabled
public static void closeCT(Communication_Touchpoint__c commtouch){
    commtouch.Status__c = 'Abgeschlossen';
    updateCommunicationTouchpoint (commtouch);
}
@AuraEnabled 
 public static void updateCommunicationTouchpoint (Communication_Touchpoint__c commtouch){
    update commtouch;
}
}

Component:

<aura:component controller="CommunicationTouchpoint" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global">

<aura:attribute name="CT" type="list" />  
<aura:attribute name="CTItem" type="Object" access="global"/> 
<aura:attribute name="currentRecord" type="Object"/>
<aura:attribute name="today" type="Date" />

<force:recordData aura:id="recordLoader"
                  recordId="{!v.recordId}"
                  fields="Name, Id"
                  targetFields="{!v.currentRecord}"
                  targetError="{!v.recordLoadError}"
                  recordUpdated="{!c.handleRecordUpdated}"
                  
                  />


<div class="slds-box slds-theme_default">
    

    <aura:iteration items="{!v.CT}" var="ct">
        
        <ul class="slds-has-dividers_bottom-space">
    <li class="slds-item">
         
        <lightning:tile ><a href="{!'/'+ct.Id}"  target="_blank">{!ct.Name}</a> 
                              
            <aura:set attribute="media">
                   <lightning:avatar fallbackIconName="{!if (ct.Art__c == 'Mail', 'standard:email','standard:log_a_call')}" />
               
            </aura:set>
               
             
            <ul class="slds-list_horizontal slds-has-dividers_right">
                
                <aura:if isTrue = "{!ct.F_lligkeitsdatum__c == v.today}">
                    
                <li class="slds-item">{!ct.Typ__c}</li>
                <li class="slds-item bold" >heute</li>
                <li class="slds-item">{!ct.Status__c}</li>
                <li class="slds-item"><a href="{!'/'+ct.Anzeige__c}"  target="_blank">{!ct.CampaignId__c}</a></li>   
                    
                </aura:if>  
                
                <aura:if isTrue = "{!ct.F_lligkeitsdatum__c != v.today}">
                    
                <li class="slds-item">{!ct.Typ__c}</li>
                <li class="{!if (ct.F_lligkeitsdatum__c >= v.today , 'green slds-item','red slds-item')}" ><lightning:formattedDateTime value = "{!ct.F_lligkeitsdatum__c}"></lightning:formattedDateTime></li>
                <li class="slds-item">{!ct.Status__c}</li>
                <li class="slds-item"><a href="{!'/'+ct.Anzeige__c}"  target="_blank">{!ct.CampaignId__c}</a></li>
                    
                </aura:if>
                
          
                <aura:if isTrue = "{!AND(OR(ct.Kategorie__c == 'Sales Call',ct.Kategorie__c == 'Sales Feedback Call'), ct.Status__c == 'Next')}"> 

                 <lightning:button 
                                   aura:id="CloseCT" 
                                   label="✓" 
                                  onclick="{!c.CloseTouchpoint}" 
                                  
                               />
                </aura:if>

                
            </ul>
        </lightning:tile>
    </li>
  </ul>
    </aura:iteration>
</div>
 </aura:component>

Controller:

({

handleRecordUpdated : function(c, e, h){
     var today = $A.localizationService.formatDate(new Date(), "YYYY-MM-DD");
c.set('v.today', today);
    
    var eventParams = e.getParams();
    if(eventParams.changeType === "LOADED") {
        // record is loaded (render other component which needs record data value)
        console.log("Record is loaded successfully - Customer Touchpoint.");
        h.getRelatedRecords(c, e, h);
    } else if(eventParams.changeType === "CHANGED") {
        // get the fields that changed for this record
        var changedFields = eventParams.changedFields;
        console.log('Fields that are changed: ' + JSON.stringify(changedFields));
    } else if(eventParams.changeType === "REMOVED") {
        // record is deleted
    } else if(eventParams.changeType === "ERROR") {
        // there’s an error while loading, saving, or deleting the record
    }
    //$A.get('e.force:refreshView').fire();
},

CloseTouchpoint : function(component, event, helper) 
{
    
    
    var action = component.get("c.closeCT");
    action.setParams({
       commtouch : component.get("v.CTItem")[4]
        
    });
    action.setCallback(this, function(a) {
        var toastEvent = $A.get("e.force:showToast");
        // get the response state
        var state = a.getState();
        var errors = a.getError();
       
        //check if result is successfull
        if(state == "SUCCESS"){
            toastEvent.setParams({
                "title": "Erfolg!",
                "message": "Touchpoint erfolgreich geschlossen",
                "mode": 'sticky',
                "type" : "success"
            });
        }
        else if(state === "ERROR") {
            let message = 'Unknown error'; // Default error message
            console.log("CloseCT not Fired");
            // Retrieve the error message sent by the server
            if (errors && Array.isArray(errors) && errors.length > 0) {
                message = errors[0].message;
            }
            toastEvent.setParams({
                "title": "Error!",
                "message": message,
                "mode": 'sticky',
                "type" : "error"
            });
        }
        else{
            console.log('Done nothing ...');
        }
        //helper.hideSpinner(component);
        toastEvent.fire();
        
        var recordLoader = component.find("recordLoader");
        console.log("recordLoader", recordLoader);
        if (Array.isArray(recordLoader)){
            console.log("recordLoader size: ", recordLoader.length);
            var indexToGet = recordLoader.length - 1;
            recordLoader = recordLoader[indexToGet];
        }
        recordLoader.reloadRecord(true);
    });
    $A.enqueueAction(action);
}

})

Helper:

({
getRelatedRecords: function (component, event, helper) {
    var action = component.get("c.getList");
    
    
    console.log("::today:: >", component.get("v.today"))
    
    action.setParams({ 
       
        recordId:           component.get("v.currentRecord.Id")
       
       
    });
    
    action.setCallback(this, function (response) {
        if (response.getState() === "SUCCESS") {
            component.set("v.CT", response.getReturnValue());
            component.set("v.CTItem", response.getReturnValue());  
            console.log("::yes::::");
        } else {
            console.log("::some error::::");
        }
        this.hideSpinner(component);
    });
    $A.enqueueAction(action);
},

hideSpinner : function(component){
    var spinnerContainer = component.find("spinnerContainer");
    console.log("spinnerContainer", spinnerContainer);
    if (Array.isArray(spinnerContainer)){
        console.log("spinnerContainer size: ", spinnerContainer.length);
        var indexToGet = spinnerContainer.length - 1;
        spinnerContainer = spinnerContainer[indexToGet];
    }
    $A.util.addClass(spinnerContainer, 'slds-hide');
    component.set("v.pickDisabled", false);
} 
});

For now I have hardcoded this part inside the controller:

  var action = component.get("c.closeCT");
    action.setParams({
       commtouch : component.get("v.CTItem")[4]
        
    });

This will always update the "5th" record in my list. Which is obviously not what I want. I did not figure out how to pass in the Id here of the record who's button was hit.

Any help would be appreciated.

Thanks! Jan

1 Answer 1

1

You need to wrap your button inside div and use data-value attribute to get its value in controller. In this way you can get dynamic id.

<div onclick="{!c.CloseTouchpoint}" data-value="{!ct.Id}">
        <lightning:button 
                          aura:id="CloseCT" 
                          label="✓" 
                          onclick="{!c.CloseTouchpoint}" 
                          
                          />
    </div>

Controller code-

var id_str = event.currentTarget.dataset.value;
var action = component.get("c.closeCT");
    action.setParams({
       commtouch : id_str
        
    });

Another approach could be and I think its the best one-

Give value attribute to your button and access in controller

<lightning:button 
                              aura:id="CloseCT" 
                              label="✓" 
                              onclick="{!c.CloseTouchpoint}" 
                              value="{!ct.Id}"
                              />

Controller code-

var id_str = event.getSource().get('v.value');
    var action = component.get("c.closeCT");
        action.setParams({
           commtouch : id_str
            
        });
9
  • Thanks for answering @darkshadowrule. I understand the generell approach and it all makes sense now. Unfortunetaly when hitting the button (2nd solution) I run into "Invalid literal value [1, 1]: 'a3X7a000001b3CoEAI'" - is that because {!ct.Id} is an object and id_str a string? how could i fix that?
    – Jan Tonnet
    Nov 24, 2022 at 10:40
  • Debug id_str and show me what you are getting in console. Nov 24, 2022 at 10:53
  • Also add button code where you added value attribute.Probably you made some mistake in adding value attribute. Some extra quotes might be there Nov 24, 2022 at 10:54
  • Hi, when I use console.log("::id_str:: >", event.getSource().get("v.value")) it returns ::id_str:: > a3X7a000001b3CoEAI This is the button code: <lightning:button aura:id="CloseCT" label="✓" onclick="{!c.CloseTouchpoint}" value="{!ct.Id}" />
    – Jan Tonnet
    Nov 24, 2022 at 11:11
  • 1
    Thank worked! Thank you so much. I thought going for the Id is what I wanted :D
    – Jan Tonnet
    Nov 24, 2022 at 11:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .