0

I have created an aura component to allow client to follow /subscribe to an article. When a user clicks on the button subscribe, a record is created in Salesforce

enter image description here

/Record created in Salesforce/

enter image description here

Until here the code behaves as expected. The problem is when the user has subscribed, he needs to be able to unsubscribe by clicking on the same button

enter image description here

But when clicking on the button I am not able to unsubscribe, the button remains on subscribed

enter image description here

Even worst, anytime I click on the button, a new record is created in salesforce. The idea is to stop the client from subscribing more than once to the same article and be able to unsubscribe when clicking on the button

Please see below my code:

KnownErrorSubscription.comp

<aura:component controller="KnownErrorSubscriptionController" implements="forceCommunity:availableForAllPageTypes,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">
    
        <aura:attribute name="recordId" type="String"/>
        <aura:attribute name="isFollowed" type="Boolean" default="false"/>
        <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
        
        <lightning:buttonStateful
            labelWhenOff="Subscribe"
            labelWhenOn="Subscribed"
            labelWhenHover="Unsubscribe"
            iconNameWhenOff="utility:add"
            iconNameWhenOn="utility:check"
            iconNameWhenHover="utility:close"
            state="{! v.isFollowed }"
            onclick="{! c.handleClick }"/>
        
</aura:component>

KnownErrorSubscriptionController.js

({
   doInit: function(component, event, helper) {
         let search = window.location.pathname;
         let result = search.substring(search.lastIndexOf("/") + 1);
         let action = component.get("c.isRecordExist");

         action.setParams({
                 urlNames : result
          });
          action.setCallback(this, function(data) {
                let result = data.getReturnValue();
                 if(result){
                     component.set('v.isFollowed', 'true');
                  }
         });
         $A.enqueueAction(action);
     },

     handleClick : function(component, event, helper) {

          let search = window.location.pathname;
          let result = search.substring(search.lastIndexOf("/") + 1);
          let action = component.get("c.saveKnownIssue");
          
         action.setParams({
              urlNames : result
         });

         action.setCallback(this, function(data) {
              let result = data.getReturnValue();
              if(result){
                    component.set('v.isFollowed', 'true');
                }
          });
         $A.enqueueAction(action);
   }
})

KnownErrorSubscriptionController.apxc

public class KnownErrorSubscriptionController {

@AuraEnabled
public static Boolean isRecordExist(String urlNames) {
    List<User> userList = [SELECT Id, Name, ContactId, Contact.Name FROM User WHERE Id = :UserInfo.getUserId()];
    List<Knowledge__kav> kavList = new List<Knowledge__kav>();
    if(urlNames != null) {
        kavList = [SELECT Id, LastPublishedDate, Title, ArticleBody__c FROM Knowledge__kav WHERE UrlName =:urlNames];
    }
    
    if(userList.size() > 0 && kavList.size() > 0) {
        List<Known_Error_Subscription__c> kESubscriptionList = [SELECT Contact__c, Knowledge__c FROM Known_Error_Subscription__c
                                                                WHERE Contact__c =:userList[0].ContactId AND Knowledge__c =:kavList[0].Id];
        if(kESubscriptionList.size() > 0) {
            return true;
        } else {
            return false;
        }
            
    } else {
        return false;
    }        
} 

@AuraEnabled
public static Boolean saveKnownIssue(String urlNames, Boolean isFollowed) {
    List<User> userList = [SELECT Id, Name, ContactId, Contact.Name FROM User WHERE Id =:UserInfo.getUserId()];
    List<Knowledge__kav> kavList = new List<Knowledge__kav>();
    
    if(urlNames != null) {
        kavList = [SELECT Id, LastPublishedDate, Title, ArticleBody__c FROM Knowledge__kav WHERE UrlName =:urlNames];
    }
    Known_Error_Subscription__c kes = new Known_Error_Subscription__c();
    if(userList.size() > 0 && userList[0].ContactId != null) {
        kes.Contact__c = userList[0].ContactId;
    }
    
    if(kavList.size() > 0) {
        kes.Knowledge__c = kavList[0].Id;
        kes.Subscribed__c = true;
    }
    
    insert kes;
    return true;
    
}

}
2
  • 1
    You need to toggle the boolean state variable on button click. where do you have logic to unsubscribe? Feb 23 at 19:02
  • hi Axaykumar, I have my logic to unsubscribe here: // To Check / Uncheck checkbox Subscribed__c when client click on button Subscribe / Unsubscribe in community if(!kesList.isempty()) { Known_Error_Subscription__c kes = kesList[0]; if(isFollowed) { kes.Subscribed__c = false; kes.Date_Unsubscribed__c = DateTime.now(); } else { kes.Subscribed__c = true; } update kes; Feb 24 at 10:06
0

I managed to find the answer to my problem. I am posting the solution

here is what I have done:

KnownErrorSubscription.cmp

<aura:component controller="KnownErrorSubscriptionController" implements="forceCommunity:availableForAllPageTypes,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">

<aura:attribute name="recordId" type="String"/>
<aura:attribute name="isFollowed" type="Boolean" default="false"/>

<lightning:buttonStateful
    labelWhenOff="Subscribe"
    labelWhenOn="Subscribed"
    labelWhenHover="Unsubscribe"
    iconNameWhenOff="utility:add"
    iconNameWhenOn="utility:check"
    iconNameWhenHover="utility:close"
    state="{! v.isFollowed }"
    onclick="{! c.handleClick }"/>

</aura:component>

KnownErrorSubscriptionController.js

({
         handleClick : function(component, event, helper) {
              let action = component.get("c.createKnownErrorSubscription");
              action.setParams({
                  recordId : component.get("v.recordId"),
                  isFollowed : component.get("v.isFollowed")
              });

              action.setCallback(this, function(response) {
                  let state = response.getState();
                  if(state === "SUCCESS") {
                        component.set('v.isFollowed', response.getReturnValue());
         
                    } else if(state === "ERROR") {
                         alert('Problem with connection. Please try again');
                    }
              });
              $A.enqueueAction(action);
       }
})

    &amp;lt;span;gt;

KnownErrorSubscriptionController.apxc

public class KnownErrorSubscriptionController {

@AuraEnabled
public static Boolean createKnownErrorSubscription(Id recordId, Boolean isFollowed) {
    
    List<User> userList = [SELECT Id, Name, ContactId, Contact.Name FROM User WHERE Id =:UserInfo.getUserId()];
    List<Knowledge__kav> kavList = new List<Knowledge__kav>([SELECT Id, LastPublishedDate, Title, ArticleBody__c 
                                                             FROM Knowledge__kav WHERE Id =:recordId]);
    try {
        if(!isFollowed) {
            Known_Error_Subscription__c kes = new Known_Error_Subscription__c(Contact__c = userList[0].ContactId, Knowledge__c = kavList[0].Id);
            insert Kes;
        }   
        if(isFollowed) {
            List<Known_Error_Subscription__c> kesList = [SELECT Id, Knowledge__c, Contact__c FROM Known_Error_Subscription__c 
                                                         WHERE Contact__c =: userList[0].ContactId AND Knowledge__c =:kavList[0].Id];
            delete kesList[0];
        }
        return !isFollowed;
        
    } catch (DmlException e) {
        System.debug('A DML exception has occurred ' + e.getMessage());     
    }
    return true;   
} 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.