• CharuDutt
  • SMARTIE
  • 1397 Points
  • Member since 2020
  • ACS


  • Chatter
    Feed
  • 48
    Best Answers
  • 0
    Likes Received
  • 5
    Likes Given
  • 1
    Questions
  • 198
    Replies
There is an account and contact which have the relationship. In contact there is a picklist which is mandatory. Say for eg picklist contains states of India. If user selects Maharashtra state, then that user should not allow to create a record in contact. How could I accomplish this. Please provide required coding part.
HI guys help!! I have to create a validation rule that the Contact Lookup should be under the same Account and now I have created a formula but I think it doesn't work right.
So here's my code:
AND( CreatedBy.Contact.AccountId = Contact__c,
     Account__r.Id  = Account__c,
     Account__r.Id <> CreatedBy.Contact.AccountId)


Can you help me find what is wrong about my formula.
Hello,
I have the following apex class and I need to write a test apex class for it. I started writing it but the code coverage is 0% . I am new into this and I don't know how to write it - can somebody help me ? 

APEX Class : 
public class GetAccount {
    
    @AuraEnabled
    public static List<Account> getAccountList(String currentId){
        List<Account> lstAcc = new List<Account>();  
        lstAcc = [Select id,Has_Code_Red_Cases__c,Has_Critical_Situation_Request_Cases__c from Account where id =: currentId];
        return lstAcc;
    }
}
TEST APEX CLASS:

@isTest 
public class GetAccountTest 
{
static testMethod void testMethod1() 
            {
                           Account acc = new Account();
                           acc.Name = 'Test Account';
                           insert acc;         
            }
}
  • April 22, 2021
  • Like
  • 0
I have created a lightning component to insert lead record in Lead object
Need to write test class for that , i am totally new in test class.
Can someone please help me to write a test class 

attaching my js code and Apex controller

InsertLeadRecordsController.js

({
    save : function(component, event, helper) {  
        var birthday = component.find("birthdate").get("v.value");
        var picl;
        //alert("picl");
        if(component.get("v.FieldsToShow")==true){
            picl = component.find("pic").get("v.value");
        //alert("picl");
        if (picl==='choose'){
            picl='';
            component.set('v.leadObj.BIIB_Relationship_With_Patient__c','');
        }
        }
        if(component.get("v.FieldsToShow")==false){
            component.set('v.leadObj.BIIB_Relationship_With_Patient__c','');
        }
        
        var reqfield1 = component.find("doccrm");
        var reqfield2 = component.find("docname");
        var reqfield3 = component.find("ck");
        var reqfield5 = component.find("fname");
        
        reqfield1.showHelpMessageIfInvalid();
        reqfield2.showHelpMessageIfInvalid();
        reqfield3.showHelpMessageIfInvalid();
        reqfield5.showHelpMessageIfInvalid();
        
        if(!reqfield1.checkValidity() || !reqfield2.checkValidity() || !reqfield3.checkValidity() || !reqfield5.checkValidity() ) {
            // Optional message if you want
            alert("Please fill out the required field."); 
            return; // Don't continue past this point
        }
        
        //To Check Email
        var emailField = component.find("email");
        var emailFieldValue = emailField.get("v.value");
        // Store Regular Expression
        var regExpEmailformat = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        
        if(!$A.util.isEmpty(emailFieldValue)){   
            if(emailFieldValue.match(regExpEmailformat))
            {
                emailField.set("v.errors", [{message: null}]);
                $A.util.removeClass(emailField, 'slds-has-error');                
            }else
            {
                $A.util.addClass(emailField, 'slds-has-error');
                emailField.set("v.errors", [{message: "Please Enter a Valid Email Address"}]);               
            }
        }
        
        if($A.util.isEmpty(component.find("lname").get("v.value"))){
            //component.set("v.hasError", true);
            alert('Last Name is required');
            return false;
        }
        
        if($A.util.isEmpty(component.find("email").get("v.value"))){
            //component.set("v.hasError", true);
            alert('Email is required');
            return false;
        }
        if($A.util.isEmpty(component.find("phone").get("v.value"))){
            //component.set("v.hasError", true);
            alert('Phone is required');
            return false;
        }
        if($A.util.isEmpty(component.find("birthdate").get("v.value"))){
            //component.set("v.hasError", true);
            alert('Birth Date is required');
            return false;
        }
        
        // it will accept two types of format yyyy-mm-dd and yyyy/mm/dd
        var optimizedBirthday = birthday.replace(/-/g, "/");
        //set date based on birthday at 01:00:00 hours GMT+0100 (CET)
        var myBirthday = new Date(optimizedBirthday);
        // set current day on 01:00:00 hours GMT+0100 (CET)
        var currentDate = new Date().toJSON().slice(0,10)+' 01:00:00';
        // calculate age comparing current date and borthday
        var myAge = ~~((Date.now(currentDate) - myBirthday) / (31557600000));
        alert(myAge);
        //var today = $A.localizationService.formatDate(Date.now(currentDate), "YYYY-MM-DD");
        var dateValue = component.get("v.leadObj.HealthCloudGA__BirthDate__c");
        if(dateValue >= currentDate){
            alert('You can not enter grater than today!');
            return false; 
        }

        if(component.get("v.FieldsToShow")==true){

        if (myAge<18 && component.find("Fulname").get("v.value")== undefined) 
        {        
            alert("Full Name Responsible is required");
            return false;  
        }
        if (myAge<18 && component.find("cpfname").get("v.value")== undefined) 
        {        
            alert("CPF Of The Person In charge is required");
            return false;  
        }

        if (myAge<18 && picl==='')
        {
            alert('Please fill the Relationship With Patient');
            return false; 
        }
        if (myAge<18 &&component.find("ck1").get("v.value")== undefined)
        {
            alert('Please Select Declaration Of Legal Responsibility');
            return false; 
        }
        }
        
        if(component.get("v.FieldsToShow1")==true){
            
            if (myAge>18 && component.find("cpfpatient").get("v.value")== undefined) 
            {        
                alert("CPF Patient is required");
                return false;  
            }
        }
    
        
        var action = component.get("c.saveLead");
        action.setParams({"leadObj":component.get("v.leadObj")});
        action.setCallback(this,function(result){
            var state = result.getState();
            if(state === 'SUCCESS'){
                // component.set("v.isShow",false);
                var leadId = result.getReturnValue();
                alert('leadId'+leadId);
                //component.reinit();
                //component.find('form').value = '';
                // component.find("FirstName").set("v.value", '');
                // component.find("birthdate").set("v.value", '');
                //alert('leadId'+leadId);
                
                window.location.href = 'https://hcdev2021-latamchatbot.cs90.force.com/Thankyoupage';
            }
  
        });

        $A.enqueueAction(action);
    },
    doInit: function(cmp) {
        var pickvar = cmp.get("c.getPickListValuesIntoList");
        pickvar.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS'){
                var list = response.getReturnValue();
                cmp.set("v.picvalue", list);
            }
            else if(state === 'ERROR'){
                //var list = response.getReturnValue();
                //component.set("v.picvalue", list);
                alert('ERROR OCCURED.');
            }
        })
        $A.enqueueAction(pickvar);
        
    },
    
    changeDate : function(component, event, helper) {
        var birthday = component.find("birthdate").get("v.value");
        var optimizedBirthday = birthday.replace(/-/g, "/");
        //set date based on birthday at 01:00:00 hours GMT+0100 (CET)
        var myBirthday = new Date(optimizedBirthday);
        // set current day on 01:00:00 hours GMT+0100 (CET)
        var currentDate = new Date().toJSON().slice(0,10)+' 01:00:00';
        // calculate age comparing current date and borthday
        var myAge = ~~((Date.now(currentDate) - myBirthday) / (31557600000));
        alert(myAge);
        
        if(myAge < 18){
            component.set("v.FieldsToShow",true);    
        }
        else if(myAge > 18){
            component.set("v.FieldsToShow",false);    
        }
        
         if(myAge > 18){
         component.set("v.FieldsToShow1",true);    
        }
         else if(myAge < 18){
         component.set("v.FieldsToShow1",false);    
        }
        
    },
    
    
    handleCheck : function(component, event, helper) {
        var newCheckBoxValue = component.find("ck").get("v.checked");
        component.set('v.leadObj.BIIB_Consent__c',newCheckBoxValue);
        console.log(newCheckBoxValue);
    },
    handleCheck1 : function(component, event, helper) {
        var newCheckBoxValue1 = component.find("ck1").get("v.checked");
        component.set('v.leadObj.BIIB_Declaration_Of_Legal_Responsibility__c',newCheckBoxValue1);
        console.log(newCheckBoxValue1);
    }
})



Apex class(WebToLeadController)

public class WebToLeadController{

@AuraEnabled
public static Id saveLead(Lead leadObj){
System.debug('@' +leadObj);
try{
   insert leadObj;
   }
   catch(exception e){
   AuraHandledException ex = new AuraHandledException(e.getMessage());
    ex.setMessage(e.getMessage());
    throw ex;
   }
   return leadObj.id;
   
}
@AuraEnabled
     
    public static List<String> getPickListValuesIntoList(){
        List<String> pickListValuesList = new List<String>();
        Schema.DescribeFieldResult fieldResult = Lead.BIIB_Relationship_With_Patient__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(pickListVal.getLabel());
            System.debug('Values in Rating are: '+pickListValuesList);
        }     
        return pickListValuesList;
    
    }
}
 
my requirement is: 
As a user, i want to be able to enter proper name in First name, Middle name or Last name boxs in Personal details section on an in Salesforce Given that the details can be created manually or can be uploaded from the Backend.
When i try to edit First, middle or Last name on Personal details section in the object  then if i  enter dr/DR/dR/MR/mr/Mr or Test or Clinic or Dummy or any special character or space or numeric input as a Prefix and click on save then it should throw error as: 

 "can't add Dr/Mr or  Test or Clinic or Dummy or any special characer or space or numeric input as prefix or suffix "
Hi All,  I have a requirement to show object's records in nested-accordian view.. It goes Like Customer(Parent) > Customer Product(Child for Customer) > Suites (Child for Customer Product)

Initially I used Accordian, but I was not able to go third-level.. So, I used lightning:tree for this purpose.. But, with this, I cannot get Id of the record.. Can anyone help with this? 

CMP: 
<aura:component controller="TreeController">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="items" type="Object"/>
    <lightning:tree items="{! v.items }" onselect="{!c.handleSelect}"/>
</aura:component>

JS
({
    doInit: function (cmp, event, helper) {
        var action = cmp.get("c.getTreeData");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                cmp.set('v.items', JSON.parse(response.getReturnValue()));
            }
            
        });
        $A.enqueueAction(action);
    },
    
    handleSelect: function (cmp, event, helper) {  
        
        var getId = event.getParam('name');
        console.log('>>> getName' + getId);
	},
    
 })




User-added image

Vignesh
In the below code filter showing accounts list..and accordian also showing account list.. i want to show filter on accordian list only. 


<aura:component implements="flexipage:availableForAllPageTypes" 
                controller="GetAccountChild"
                access="global" >
    
    <aura:attribute name="accList"
                    type="List"/>
    <aura:attribute name="Accounts" type="Account[]"/>
    
    
    <aura:handler name="init"
                  value="{!this}"
                  action="{!c.doInit}"/>
    <lightning:card title="Filtered Accounts">
        <div class="search-field">
            <lightning:input aura:id="nameFilter" label="Filter names" onchange="{!c.handleNameFilterChange}" />
        </div>
        <div class="results">
            <aura:if isTrue="{!v.Accounts.length > 0}">
                <p class="has-results">
                    Showing {!v.Accounts.length} accounts(s):
                </p>
                <ol class="slds-list_dotted">
                    <aura:iteration items="{!v.Accounts}" var="Account">
                        <li>
                            <a class="Account-name" onclick="{!c.handleClickAccountName}" data-sfid="{!Account.Id}">
                                {!Account.Name}
                            </a>
                        </li>
                    </aura:iteration>
                </ol>
                <aura:set attribute="else">
                    <p class="no-results">Nothing to show.</p>
                </aura:set>
            </aura:if>
        </div>
    </lightning:card>
    <aura:attribute name="activeSections" type="List"/>
    <div class="slds-border_bottom">
        <h1>Accounts</h1></div>  
    <div class="slds-scrollable_y">
        <div class="slds-text-longform">
            
            <lightning:accordion activeSectionName="{! v.activeSections }" onsectiontoggle="{! c.handleSectionToggle }">
                <div class="demo-only demo-only--sizing slds-grid slds-wrap">
                    <div class="slds-size_1-of-2">
                        <div class="slds-box slds-box_x-small slds-text-align_left slds-m-around_x-small">
                            
                            <aura:iteration items="{!v.accList}" 
                                            var="acc">
                                
                                <lightning:accordionSection name="{!acc.Name}" 
                                                            label="{!acc.Name}">
                                    
                                    
                                    <div class="slds-scrollable" style="height:10rem;width:24rem">
                                        <div class="slds-text-longform" style="width:150%">
                                            
                                            <lightning:tabset selectedTabId="one">
                                                
                                                <lightning:tab label="Contacts" id="one">
                                                    <aura:iteration items="{!acc.Contacts}" var="con" indexVar="index">
                                                        <li>Contact {!index + 1} Name : {!con.Name}</li>
                                                        <li>Contact Phone :</li>
                                                        <p><lightning:formattedPhone value="{!con.Phone}"></lightning:formattedPhone></p>
                                                        <br></br>
                                                    </aura:iteration>
                                                </lightning:tab>
                                                
                                                <lightning:tab label="Opportunities" id="two">
                                                    <aura:iteration items="{!acc.Opportunities}" var="opp" indexVar="index">
                                                        <li>Opportunities {!index + 1} Name : {!opp.Name}</li>
                                                        <li>ID : {!opp.Id}</li>
                                                        <br></br>
                                                    </aura:iteration>
                                                </lightning:tab>
                                            </lightning:tabset>
                                        </div>
                                    </div>
                                </lightning:accordionSection>
                            </aura:iteration>
                        </div>
                    </div>
                </div>
            </lightning:accordion>
        </div>
    </div>
    
</aura:component>


this code is working properly.. i just want to put filter 
Hi friends, I just learing SF. Help me: I how do i check if name record already exists or not in the database. If record already exists, then do nothing, if not exists insert the record.
And then refresh page if record inserting.
My code:
------------------------------------------------
public class CarGarageController {
        public Car__c car { get; set; }
          public String carName { get; set; }
        public Car_Garage__c carGarage { get; set; }
        
        public CarGarageController () {
            getCars();
        }
    
           public void receiveCarName() {
           String carName=Apexpages.currentPage().getParameters().get('carName');
        }
    
          public PageReference insertCar() {
            carGarage = [
                SELECT Id
                FROM Car_Garage__c
                LIMIT 1
            ];

            car = new Car__c(Car_Garage__c=carGarage.id, Name=carName);
            insert car;
            return null;
        }         
        
        public List<Car__c> carList { get; set; }
    
        private void getCars() {
        carList = [
                SELECT Id, Name, Car_Garage__c, CreatedByID, CreatedDate
                FROM Car__c
                ORDER BY Name ASC
            ];
        }
}

------------------------------------------------
Thanks for answers!
Hi All,
Please help me on this scenerio.
There is a Lookup field to Asset Object already exists
1. Created a new text field "C1" in Case Object
2. Created a new formula field "A1" in Asset Object

How can I display the data from Case Object's "C1" Field to Asset Object's "A1" field using the formula.

Anyhelp will be appreciated.

Thanks,
JG
 
Hello everyone !

I'm settling in this community as I've recently been given the task of implementing Salesforce for my company.

As I'm learning the ropes of administrating an Org I'm also getting interested in learning APEX.

So I've attempted to write simple triggers, which has worked out quite well until now.

Now, I'm attempting to trigger the creation of a Task whenever a Opportunity is created.

I want to link that task to that opportunity, to do just that I wanna use (api name) WhatID from the task fields.

Although I'm running into an error on that perticuliar line;;
 
trigger CadoSupere on Opportunity (after insert) {
    for (Opportunity opp : trigger.new) {
        Task t          = new Task();
        opp.WhatId      = opp.Id;
        opp.Description = 'Je vous offre un supere cado';
        insert t;
    }
}

Line 4: Variable does not exist

I've checked the field and it seems Field Lever Security is set to visible on that WhatId field.

Is there something obvious I'm missing ?

Thanks a bunch, have a nice day and I hope to help others when I get good :)
  • April 16, 2021
  • Like
  • 0
Hello,
I could use some help on how to create a validation rule that forces users to fomat their text input
For example.  I need the user input to be like 
A.123456.D.54 OR A.789456.E.89
First letter needs to be an A followed by a . followed by 6 digits(numbers only) followed by a . followed by a D or E  then followed by a . and then followed by 2 digits(numbers only)
Can I do this in a validation rule? 
Thank you,
P
 
I have accounts names and their child object name also like,, contacts and opportunity.. 
i want that when i click any account name ,, then a alert is shown on page showing the name of that account name. 
this is my lightning component code,, it is in working condition now i only want to add above feature. 


   
    <aura:attribute name="accList"
                    type="List"/>
    
    <aura:handler name="init"
                  value="{!this}"
                  action="{!c.doInit}"/>
    
    <div class="slds-border_bottom">
        <h1>Accounts</h1></div>  
    <div class="slds-scrollable_y">
        <div class="slds-text-longform">
            
            <lightning:accordion>
                <div class="demo-only demo-only--sizing slds-grid slds-wrap">
                    <div class="slds-size_1-of-2">
                        <div class="slds-box slds-box_x-small slds-text-align_left slds-m-around_x-small">
                            
                            <aura:iteration items="{!v.accList}" 
                                            var="acc">
                                
                                <lightning:accordionSection name="{!acc.Name}" 
                                                            label="{!acc.Name}">
                                    
                                    
                                    <div class="slds-scrollable" style="height:10rem;width:24rem">
                                        <div class="slds-text-longform" style="width:150%">
                                            
                                            <lightning:tabset selectedTabId="one">
                                                
                                                    <lightning:tab label="Contacts" id="one">
                                                        <aura:iteration items="{!acc.Contacts}" var="con" indexVar="index">
                                                            <li>Contact {!index + 1} Name : {!con.Name}</li>
                                                            <li>Contact Phone :</li>
                                                            <p><lightning:formattedPhone value="{!con.Phone}"></lightning:formattedPhone></p>
                                                            <br></br>
                                                        </aura:iteration>
                                                    </lightning:tab>
                                                
                                                    <lightning:tab label="Opportunities" id="two">
                                                        <aura:iteration items="{!acc.Opportunities}" var="opp" indexVar="index">
                                                            <li>Opportunities {!index + 1} Name : {!opp.Name}</li>
                                                            <li>ID : {!opp.Id}</li>
                                                            <br></br>
                                                        </aura:iteration>
                                                    </lightning:tab>
                                            </lightning:tabset>
                                        </div>
                                    </div>
                                </lightning:accordionSection>
                            </aura:iteration>
                        </div>
                    </div>
                </div>
            </lightning:accordion>
        </div>
    </div>
    
</aura:component> 
Hi,

I have develop LWC component which is normally used by normal users. In that lightning web component button is there as below.
<lightning-button slot="actions" label="Deactivate" onclick={DeactivateProcess}> </lightning-button>
The above button should be only be show to System Admin Profile and Business Admin Profile. How to show the button only to those two Profiles without using record types or different page layouts?
I have created lightning component and 6 fields there, one date field is also there
how can we do that if age is more than 18 years then 2 fields shoud be hide.
Can please someone help me on that...

Thanks in advance
I want to create Tab between accordian.
i want to do... when i click on that tab it shows contacts details

basically i am fatching account name and contacts and oppoertunity associted with the account.
>Account name
   Tab1   Tab2
  > contacts details if Tab1 selected
  > oppoertunity deatils if Tab2 selected


 <lightning:accordion>
        <aura:iteration items="{!v.accList}" 
                        var="acc">
            
            <lightning:accordionSection name="{!acc.Name}" 
                                        label="{!acc.Name}">    
                <lightning:accordion>
                    <aura:iteration items="{!acc.Contacts}" 
                                    var="con">
                        <lightning:accordionSection name="{!con.Name}" 
                                                    label="{!con.Name}">
                            
                            <aura:set attribute="body">
                                
                                <p>FirstName : {!con.FirstName}</p>
                                <p>LastName : {!con.LastName}</p>
                                <p>Phone: {!con.Phone}</p>
                            </aura:set>
                        </lightning:accordionSection>
                    </aura:iteration>
                </lightning:accordion> 
                
                <lightning:accordion>
                    <aura:iteration items="{!acc.Opportunities}" 
                                    var="opp">
                        <lightning:accordionSection name="{!opp.Name}" 
                                                    label="{!opp.Name}">
                            
                            <aura:set attribute="body">
                                
                                <p>Id : {!opp.Id}</p>
                                
                            </aura:set>
                        </lightning:accordionSection>
                    </aura:iteration>
                </lightning:accordion>
                
            </lightning:accordionSection>
        </aura:iteration>
    </lightning:accordion>
    

this is working but only need to show details when tab selected
 
Hi, I would like to add the todays date next to the "Heute" title. Could you tell me how to insert it in the code below?
User-added imageUser-added image

Hello folks, 

I am new to Salesforce development. I have not created a LWC before. I am tasked with creating a LWC that will update 5 fields at one time on the Account object if the record meets a certain criteria (or else it's disabled). The values are preset, so they can be hardcoded. Can you please give me pointers on how to go about doing this? An outline would suffice, I have just created a shell of a LWC that has the button and the labels. I want to know where does the conditional logic go to make this LWC appear/disappear and other things I have to keep in mind. 

 

Thank you.

Hi
i have a batch class and i'm wirting a test class for that batch class but the test class is covering only 72% of code. So please help me to write a test class which will cover 100% of batch class code. Thank you in advance.

this is my batch class:-

public class MyBatchable implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([select Id from Account where name like 'acc%' order by Name]);
    }

    public void execute(Database.BatchableContext context, List<Account> scope) {
        try{
        Account[] updates = new Account[] {};
        for (AggregateResult ar : [select AccountId a, count(Id) c from Contact where AccountId in :scope and active__c=true group by AccountId])
        {
            updates.add(new Account(Id = (Id) ar.get('a'), No_of_Active_Contacts__c = (Decimal) ar.get('c')));
        }
        update updates;
    }
        catch(Exception e) {
        System.debug('An exception occurred: ' + e.getMessage());
}
    }

    public void finish(Database.BatchableContext context) {
    }
}

This is the test class i have written:-

@isTest
public class MyBatchableTest {
    static testMethod void testme(){
        Account l = new Account();
        l.name = 'acc1';
        insert l;
        Test.startTest();
        MyBatchable ba= new MyBatchable();
        Id jobid= Database.executeBatch(ba,5);
        Test.stopTest();
        Account acc = [select id from account];
        System.assertEquals(5,acc.no_of_active_contacts__c);
    }
}

Thanks and regards
Sachin Sharma
Hii,
I have have demo lwc component named as DemoLwc
and i have create a new css file in that component called main.css.
But the problem is that it is not working.
can anyone help me how i will use my css file file in that component.
Hello all,

So I have a small lwc where I want to enable a button when an input is not empty but I can not seem to get it to disable the button again if the value in the input field is deleted.

Methods I have tried:
event.target.value == undefined
event.target.value == null
event.target.value.length < 1

I imagine this is possible so I must be missing some key information about event.target.value.

Any help or infromation would be very helpful!

Thanks in advance.
i have 4 checkbox field on an object and 1 pickilist field 



1>    if all four checkbox is checked picklist isequal to all active
2>    if any three checkbox is checked picklist isequal to review
3>    if any two checkbox is checked picklist isequal to approved
4>     if one or none checkbox is checked picklist isequal to rejected
There is an account and contact which have the relationship. In contact there is a picklist which is mandatory. Say for eg picklist contains states of India. If user selects Maharashtra state, then that user should not allow to create a record in contact. How could I accomplish this. Please provide required coding part.
Hi all, I have created dynamic action on my custom page but it is not working as per expectation. 
I have the requirement to hide submit for approval button when the status is approved or rejected so I have created dynamic action for it by providing the following conditions:
User-added image
Whatever criteria I am providing only working for the System Administrator profile but not working for other user profiles.

I am not able to understand what step I am missing in it. Can anyone please help me to resolve this issue.

Thanks in advance
HI guys help!! I have to create a validation rule that the Contact Lookup should be under the same Account and now I have created a formula but I think it doesn't work right.
So here's my code:
AND( CreatedBy.Contact.AccountId = Contact__c,
     Account__r.Id  = Account__c,
     Account__r.Id <> CreatedBy.Contact.AccountId)


Can you help me find what is wrong about my formula.
Hello, I have a datatable with data from a JSON I have parsed, I need to implement a search bar where the user will input a letter and only the values in the table containing that letter will be displayed, can somebody help me? I'm kinda lost
 
<lightning-input type="search" placeholder={placeholder} value={searchKey} onchange={handleSearch}>
      </lightning-input>

          <lightning-datatable key-field="id" 
                                data={mealNames} 
                                columns={columns} 
                                sorted-by={sortBy}
                                sorted-direction={sortDirection}
                                onsort={handleSort}
                                hide-checkbox-column="true"
                                default-sort-direction={defaultSortDirection}>
          </lightning-datatable>
 
import { api, track, wire, LightningElement } from 'lwc';
import getMealData from '@salesforce/apex/MealsRetriever.getMealData';

const columns =[
    {label: 'Meal ID', fieldName: 'idMeal', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'Meal', fieldName: 'strMeal', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'Category', fieldName: 'strCategory', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'Meal Origin', fieldName: 'strArea', editable: false, sortable: true, hideDefaultActions: true},
    {label: 'How to prepare', fieldName: 'strInstructions', editable: false, sortable: true},
];

export default class DataTableWithSortingInLWC extends LightningElement {
    
    @track columns = columns;
    @track sortBy;
    @track sortDirection;
    @track mealNames;
    @api mealSpinner = false;
    @track searchKey;

    @wire(getMealData)
        mealDataResult(result){
            const {data, error} = result;
            if(data){
                this.mealNames = data;
                this.mealSpinner = true;
                this.error = undefined;
            } else if(error){
                this.mealNames = undefined;
                this.error = error;
            }
        }
    
    handleSearch(){
        getMealData(
            {searchKey: '$searchKey'}
        )
        .then(data =>{
            this.mealNames = data;
            this.error = undefined;
        })
        .catch(error =>{
            this.mealNames = undefined;
            this.error = error;
        })
    }

    handleSort(event){
        this.sortBy = event.detail.fieldName;
        this.sortDirection = event.detail.sortDirection;
        this.sortData(this.sortBy, this.sortDirection);
    }

    sortData(fieldname, direction) {
        let parseData = JSON.parse(JSON.stringify(this.mealNames));
        let keyValue = (a) => {
            return a[fieldname];
        };
        let isReverse = direction === 'asc' ? 1: -1;
        parseData.sort((x, y) => {
            x = keyValue(x) ? keyValue(x) : ''; 
            y = keyValue(y) ? keyValue(y) : '';
            return isReverse * ((x > y) - (y > x));
        });
        this.mealNames = parseData;
    }  
}

 
Hello,
I have the following apex class and I need to write a test apex class for it. I started writing it but the code coverage is 0% . I am new into this and I don't know how to write it - can somebody help me ? 

APEX Class : 
public class GetAccount {
    
    @AuraEnabled
    public static List<Account> getAccountList(String currentId){
        List<Account> lstAcc = new List<Account>();  
        lstAcc = [Select id,Has_Code_Red_Cases__c,Has_Critical_Situation_Request_Cases__c from Account where id =: currentId];
        return lstAcc;
    }
}
TEST APEX CLASS:

@isTest 
public class GetAccountTest 
{
static testMethod void testMethod1() 
            {
                           Account acc = new Account();
                           acc.Name = 'Test Account';
                           insert acc;         
            }
}
  • April 22, 2021
  • Like
  • 0
totalmarks(){
        const t=parseInt(this.telugu);
        const h=parseInt(this.hindi);
        const e=parseInt(this.english);
        const m=parseInt(this.maths);
        const s=parseInt(this.science);
        const so=parseInt(this.social);
        this.currentoutput='totalpercentage=' +(t+h+e+m+s+so/600);
    }

Hi all, some time ago we had implemented a formula that should count a number of days between two dates, to not count weekends. We want to count end date as well. Below is a formula, however when I verify this is a website that counds number of days between dates, it is different than what we get in SF:

Formula:

1 +
(
 (End_date_of_project__c - Start_date_of_project__c) * 5 -
 (MOD(Start_date_of_project__c - DATE(1970,1,4),7) - MOD(End_date_of_project__c - DATE(1970,1,4),7)) * 2
) / 7 -
IF(MOD(End_date_of_project__c - DATE(1970,1,4),7) = 6,1,0) -
IF(MOD(Start_date_of_project__c - DATE(1970,1,4),7) = 0,1,0)


In SF, we got the following:
Start date of project: 22/03/2021
End date of project: 31/12/2021

According to this website that counts dates (https://www.calculator.net/date-calculator.html?today=03%2F22%2F2021&ageat=12%2F31%2F2021&calctype=diff&useholiday=1&hdny=1&hdml=1&hdpd=1&hdmd=1&hdid=1&hdld=1&hdcd=1&hdvd=1&hdtx=1&hdxm=1&n0=&m0=&d0=&n1=&m1=&d1=&n2=&m2=&d2=&n3=&m3=&d3=&n4=&m4=&d4=&n5=&m5=&d5=&n6=&m6=&d6=&n7=&m7=&d7=&n8=&m8=&d8=&n9=&m9=&d9=&n10=&m10=&d10=&n11=&m11=&d11=&n12=&m12=&d12=&n13=&m13=&d13=&n14=&m14=&d14=&n15=&m15=&d15=&n16=&m16=&d16=&n17=&m17=&d17=&n18=&m18=&d18=&n19=&m19=&d19=&x=71&y=21), we get 196 days.

But in Salesforce, based on formula, we get 205. Want to figure out - why?

 

Soql query to get 100 records from account.
List<account> acctList = [select id, name from account limit 100]. The retrieved 100 records should save in NEW LIST. How could i accomplish.
HI All,

I am writing a trigger where if the Contact being created is not related to an account, then we should assign this contact to a particular account:
 
trigger trigger_Contact1 on Contact (before insert) {


      List<contact> conlist = new List<contact>(); 
      for(Contact con :trigger.new){
      if(Accountid==null)
      Account.id=0015G00001dSXtWQAW;
      conlist.add(con);
      }
     
    insert conlist;
}

The account id I have mentioned is of an account to which I would like to assign all contacts to in case if the Account is not selected for such contacts at time of insert.
 
I am trying to show stage picklist values of opportunity object through lwc but iit shows error unlnown exception when i deploy code to org

here is my code
<template>
    <div class="side-box">
        <template if:true={StageValues.data}>
           
            <lightning-combobox value={value} label="Opportunity Stage" onchange={handleChange} options={stageValues.data.values}
                name="progress"> </lightning-combobox>
            </template>
    </div>
    
</template>

import OPPORTUNITY_OBJECT from '@salesforce/schema/Opportunity';
import { getPicklistValues } from 'lightning/uiObjectInfoapi';
import Stage from '@salesforce/schema/Opportunity.StageName';
import { getObjectInfo } from 'lightning/uiObjectInfoapi';
import { wire } from 'lwc';
export default class LwcPicklistOppor extends LightningElement {
    @wire(getObjectInfo, { objectApiName : Opportunity_OBJECT})
    opportunityinfo;
    @wire(getPicklistValues,
        {
            recordTypeId: '$opportunityinfo.data.defaultRecordTypeId',
            fieldApiName: Stage
        }
    )
    StageValues;
}
 
i want to show records based on picklist selection..
if i select 2 then .. two accounts show
if select 4 then.. four accounts show.

component....---

<aura:component implements="flexipage:availableForAllPageTypes" 
                controller="GetAccountChild"
                access="global" >
    
    <aura:attribute name="accList"
                    type="List"/>
    <aura:attribute name="Accounts" type="Account[]"/>
     <aura:attribute name="mycolumns" type="List"/>

    
    <aura:handler name="init"
                  value="{!this}"
                  action="{!c.doInit}"/>
    <lightning:select name="cStat" label="select a value" value="New" aura:id="statusPicklist" >
        <option value="2">2</option>
        <option value="4">4</option>
        <option value="10">10</option>
    </lightning:select>

    <br/><br/>
    <lightning:datatable data="{! v.acctList }"
                         columns="{! v.mycolumns }"
                         keyField="id"
                         hideCheckboxColumn="true"/>

    <aura:attribute name="searchResult" type="List" description="use for store and display account list return from server"/>
    <aura:attribute name="searchKeyword" type="String" description="use for store user search input"/>
    <aura:attribute name="activeSections" type="List"/>
    <div class="slds-border_bottom">
        <h1>Accounts</h1></div>  
    <div class="slds-scrollable_y">
        <div class="slds-text-longform">
            <lightning:input value="{!v.searchKeyword}"
                             placeholder="search Accounts.."
                             aura:id="searchField"
                             label="Account Name"/>
            
            <lightning:button onclick="{!c.Search}"
                              variant="brand"
                              label="Search"
                              iconName="utility:search"/>
            
            
            <lightning:accordion allowMultipleSectionsOpen="true" activeSectionName="{! v.activeSections }" onsectiontoggle="{! c.handleSectionToggle }">
                <div class="demo-only demo-only--sizing slds-grid slds-wrap">
                    <div class="slds-size_1-of-2">
                        <div class="slds-box slds-box_x-small slds-text-align_left slds-m-around_x-small">
                            
                            <aura:iteration items="{!v.accList}" 
                                            var="acc">
                                
                                <lightning:accordionSection name="{!acc.Name}" 
                                                            label="{!acc.Name}">
                                    
                                    
                                    <div class="slds-scrollable" style="height:10rem;width:24rem">
                                        <div class="slds-text-longform" style="width:150%">
                                            
                                            <lightning:tabset selectedTabId="one">
                                                
                                                <lightning:tab label="Contacts" id="one">
                                                    <aura:iteration items="{!acc.Contacts}" var="con" indexVar="index">
                                                        <li>Contact {!index + 1} Name : {!con.Name}</li>
                                                        <li>Contact Phone :</li>
                                                        <p><lightning:formattedPhone value="{!con.Phone}"></lightning:formattedPhone></p>
                                                        <br></br>
                                                    </aura:iteration>
                                                </lightning:tab>
                                                
                                                <lightning:tab label="Opportunities" id="two">
                                                    <aura:iteration items="{!acc.Opportunities}" var="opp" indexVar="index">
                                                        <li>Opportunities {!index + 1} Name : {!opp.Name}</li>
                                                        <li>ID : {!opp.Id}</li>
                                                        <br></br>
                                                    </aura:iteration>
                                                </lightning:tab>
                                            </lightning:tabset>
                                        </div>
                                    </div>
                                </lightning:accordionSection>
                            </aura:iteration>
                        </div>
                    </div>
                </div>
            </lightning:accordion>
        </div>
    </div>
    
</aura:component>

controller----

({
    doInit : function(component, event, helper) {
        
        helper.accordHelper(component,event,helper)
        
   
    },
    handleSectionToggle: function (component, event, helper) {
        var openSections = event.getParam("openSections");
        
        if (openSections.length === 0) {
            alert("All sections are closed");
        } else {
            alert(openSections);
        }
    },
     Search: function(component, event, helper) {
            helper.accordHelper(component, event);
     },
     onChange: function (cmp, event, helper) {
        var selectedPicklistValue= component.find("statusPicklist").get("v.value");
        alert("selectedPicklistValue ==>" +selectedPicklistValue)

    }

})



helper..---

({
    accordHelper :function(component, event, helper) {
         component.set('v.mycolumns');
        var action=component.get("c.showAccountsForAccordion");
             action.setParams({ searchKey : component.get("v.searchKeyword") });
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                console.log("allValues--->>> " + JSON.stringify(allValues));
                component.set('v.activeSections', allValues.Name);
                component.set('v.accList', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    }
    
    
})


can anyone help on this
Could you please help me to align right side(close to right side border) toggle button, button and help text. Currently it is showing close to center. Below is the UI of the LWC Component. 

User-added image

Please find the HTML full code. I have used list elements show button in horizontal line.

HTML Code
 
<template>
    <lightning-card   title="User Management" icon-name="standard:user" >
            <div class="slds-col slds-size_10-of-12 slds-p-top_medium">
                <lightning-layout multiple-rows="true" class="slds-m-left_xx-large">
                    <lightning-layout-item size = "12" margin= "around-small">
                           <span style="float: right;">
                        <div style="float: right;">
    
                            <ul class="slds-button-group-row slds-m-left_xx-large" >
                                <!-- <template if:true={hasPrev}>-->
    
                                <li class="slds-button-group-item" >
                                    <template if:true={showToggle}>
                                        <lightning-input type="toggle"
                                                         label="Enable Process"
                                                         onchange ={deactivateProcess}
                                                         checked= "{ToggleChecked}"
                                                         class="slds-m-right_xx-small slds-m-left_xx-large" >
                                        </lightning-input>
                                        </template>
    
                                </li>
                                <li class="slds-button-group-item" >
                                    <lightning-button class="slds-m-right_xxx-small slds-m-top_none slds-m-bottom_xxx-small" slot="actions" label="Submit" onclick={updateRecords}>
                                    </lightning-button>
                                    <lightning-helptext class="slds-m-top_none slds-m-bottom_xxx-small slds-m-right_xx-small " content="The users that will exclude from the de-activation."></lightning-helptext>
    
                                </li>
                                </ul>
    
                  </div>
                                </span>
                        </lightning-layout-item>
                    </lightning-layout>
    
            </div>
        <div class="slds-p-left_medium">
            <div class="slds-col slds-size_12-of-12 slds-p-top_medium">
                <div class="slds-p-around_medium lgc-bg">
                    <lightning-datatable
                            key-field="UserId"
                            columns={columns}
                            data={currentPageData}
                            selected-rows= {allSelectedRows}
                            onrowselection= {rowSelection}
                            sorted-by={sortBy}
                            sorted-direction={sortDirection}
                            onsort={handleSortdata}
                    >
                    </lightning-datatable>
                </div>
                <div class="slds-col slds-size_10-of-12 slds-p-top_medium">
                    <lightning-layout multiple-rows="true">
                        <lightning-layout-item size = "12" margin= "around-small">
                            <div class="slds-align_absolute-center">
                                <ul class="slds-button-group-row">
                                    <!-- <template if:true={hasPrev}>-->
                                    <li class="slds-button-group-item" >
                                            <button class="slds-button slds-button_neutral" onclick ={onFirst} disabled={disabledConditionFirst}> First
                                            </button>
                                    </li>
                                    <li class="slds-button-group-item" >
                                              <button class="slds-button slds-button_neutral" disabled={disabledConditionPrev} onclick ={onPrev}> Prev
                                              </button>
                                    </li>
                                    <li class="slds-button-group-item" >
                                          <button class="slds-button slds-button_neutral" disabled={disabledConditionNext} onclick={onNext} >Next</button>
                                    </li>
                                    <li class="slds-button-group-item" >
                                            <button class="slds-button slds-button_neutral"  onclick ={onLast} disabled={disabledConditionLast}> Last
                                            </button>
                                    </li>
                                    <!--</template>-->
                                </ul>
                            </div>
                            </br>
                            <div class="slds-align_absolute-center" >
                        <span
                                disabled={disabledCondition}>Total Records: {totalRecordCount} </span>
                            </div>
                            <div class="slds-align_absolute-center" >
                                <span disabled={disabledCondition}>Page ({page} of {numberOfPages}) </span>
                            </div>
                        </lightning-layout-item>
                    </lightning-layout>
                </div>
            </div>
        </div>
        <div if:true={showLoadingSpinner}>
            <lightning-spinner alternative-text="Loading" size="large"></lightning-spinner>
        </div>
    </lightning-card>


JS

import { LightningElement, track, wire, api} from 'lwc';
import getUserList from '@salesforce/apex/UserManagementController.getUserList';
import userRecordsUpdate from '@salesforce/apex/UserManagementController.userRecordsUpdate';
import { refreshApex} from '@salesforce/apex';
import { ShowToastEvent} from 'lightning/platformShowToastEvent';
import getProfile from '@salesforce/apex/UserManagementController.getProfile';
import updateUserManagementProcess from '@salesforce/apex/UserManagementController.updateUserManagementProcess';

export default class Usermanagement extends LightningElement {

  //Display Coulmns on Datatable
  @track columns = [

    {
      label: 'Name',
      fieldName: 'recordLink',
      type: 'url',
      typeAttributes: { label: { fieldName: "FullName" }, tooltip:"Name", target: "_blank" },
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 200,
    },
    {
      label: 'Email',
      fieldName: 'Email',
      type: 'text',
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 200,
    },
    {
      label: 'Profile',
      fieldName: 'ProfileName',
      type: 'text',
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 170,
    },
    {
      label: 'Role',
      fieldName: 'RoleName',
      type: 'text',
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 200,
    },
    {
      label: "Last Login Date",
      fieldName: "LastLoginDate",
      type: "date",
      typeAttributes: {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
      },
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 200,
    },
    {
      label: 'isFrozen',
      fieldName: 'isFrozen',
      type: 'text',
      sortable: false,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 100,
    },
    {
      label: 'isDeactivate',
      fieldName: 'isDeactivate',
      type: 'text',
      sortable: false,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 125,
    }

  ];

  // Track Gloabal variables
  @track showLoadingSpinner = false;
  @track error;
  @track page = 1;
  @track perpage = 20;
  @track pages = [];
  @track disabledConditionNext = true;
  @track disabledConditionPrev = true;
  @track disabledConditionFirst = true;
  @track disabledConditionLast = true;
  @track preSelectedRows = [];
  @track totalRecordCount = 0;
  @track numberOfPages = 1;
  @track sortBy;
  @track sortDirection;
  @track ToggleChecked;

  //Gloabal variables
  data = [];
  @api allDeSelectedRows = [];
  pageSlice;
  numOfPreviousPages;
  showToggle = false;
  wiredActivities;
  @track profName;

  //  Initial Method Call
  connectedCallback() {
    console.log('Initial' );
    this.init();
  }

  //Enable Deactivate Process button for Admins based on profile
  @wire(getProfile)
  wiredActivities({ error, data }) {
    if (data){
      console.log('profName==> '+JSON.stringify(data));

      this.profName = data;
      if(this.profName == 'System Administrator'){
        this.showToggle = true;
      }else{
      this.showToggle = false;
}
      console.log(this.profName);
      this.error = undefined;
     } else if (error) {
      this.error = error;
      this.data = undefined;

  }
}

  // Initial Method Call - Populate data on UI
  async init() {
    try {
      this.disabledConditionNext = true;
      this.disabledConditionPrev = true;
      this.disabledConditionFirst = true;
      this.disabledConditionLast = true;
      this.showLoadingSpinner = true;
      await getUserList()
        .then((result, error) => {
          console.log('result =' + result);
          var userList = JSON.parse(result);
          if (userList) {
             var tempUserList = [];
             userList.userMngtWrapperList.forEach((record) => {
                 let tempUserRec = Object.assign({}, record);
                 tempUserRec.recordLink = '/' + tempUserRec.UserId;
                 tempUserList.push(tempUserRec);
             });
            this.data = tempUserList;
            this.preSelectedRows = userList.selectedUserIdSet;
            this.ToggleChecked = userList.enableUserMngmtProcess;
            this.allSelectedRows = [];
            //this.data = this.data;
            console.log('this.data new =' + this.data);
            console.log('allSelectedRows =' + this.allSelectedRows);
            console.log('preSelectedRows =' + this.preSelectedRows);
            this.totalRecordCount = this.data.length;
            this.error = undefined;
          } else if (error) {
            console.error(error);
            this.data = undefined;
          }
        });
      this.setPages(this.data);

      if (this.data.length == 0) {
        this.dispatchEvent(
          new ShowToastEvent({
            title: 'No records to Display',
            message: 'No users to de-activates',
            variant: 'info'
          })
        );
      }
      this.showLoadingSpinner = false;

    } catch (error) {
      this.error = error;
    } finally {
      this.showLoadingSpinner = false;
    }
  }

/**
 * Below Methods are to Manipulate Page Load,Navigation and page click
 * pagesList
 * currentPageData
 * pageData
 * setPages
 * onPageClick
 * onNext
 * onPrev
 * onFirst
 * onLast
 * changePage
 */

  // Get Page list
  get pagesList() {
    let mid = Math.floor(this.perpage / 2) + 1;
    if (this.page > mid) {
      return this.pages.slice(this.page - mid, this.page + mid - 1);
    }
    return this.pages.slice(0, this.perpage);
  }

  // Get Data to load to current Page
  get currentPageData() {
    return this.pageData();
  }

 // Get Current Page Data based on page Number
  pageData = () => {
    let numberOfPages = Math.ceil(this.data.length / this.perpage);
    this.numberOfPages = numberOfPages;
    let page = this.page;
    let perpage = this.perpage;
    let startIndex = (page * perpage) - perpage;
    let endIndex = (page * perpage);

    if (this.numberOfPages < 2)
    {
        this.disabledConditionNext = true;
        this.disabledConditionPrev = true;
        this.disabledConditionLast = true;
        this.disabledConditionFirst = true;
    }
    else if (this.page  == this.numberOfPages)
    {
         this.disabledConditionNext = true;
         this.disabledConditionPrev = false;
         this.disabledConditionLast = true;
         this.disabledConditionFirst = false;
    }
    else if (this.page  == 1)
    {
          this.disabledConditionNext = false;
          this.disabledConditionPrev = true;
          this.disabledConditionLast = false;
          this.disabledConditionFirst = true;
    }
    else // if (this.page  < this.numberOfPages)
    {
          this.disabledConditionNext = false;
          this.disabledConditionPrev = false;
          this.disabledConditionLast = false;
          this.disabledConditionFirst = false;
    }

    this.pageSlice = this.data.slice(startIndex, endIndex);
    return this.data.slice(startIndex, endIndex);
  }

  // Get Number of pages need to be visible based on the data amount
  setPages = (data) => {
    let numberOfPages = Math.ceil(data.length / this.perpage);
    this.numOfPreviousPages = numberOfPages;
  }

  // Page Click event
  onPageClick = (e) => {
    this.page = parseInt(e.target.dataset.id, 10);
    }
  }

  // First Page button Click
  onFirst = () => {
    this.changePage(1);
  }

 // Last Page button Click
  onLast = () => {
    this.changePage(this.numberOfPages > 0 ? this.numberOfPages : 1);
  }

  // Page Data Change based on page number
  changePage(pageNumber) {

    let pageData = this.pageData();
    // Preserve rows outside current page and add rows from current page
    this.allSelectedRows = this.allSelectedRows.filter((rowId) => !pageData.find((record) => record.userId === rowId)).concat(this.template.querySelector('lightning-datatable').selectedRows);
    //Distinct the dataset
    this.allSelectedRows = this.allSelectedRows.filter((v, i, a) => a.indexOf(v) == i);
    console.log('changePage-allSelectedRows = ' + this.allSelectedRows);
    this.page = pageNumber;
    pageData = this.pageData();

    console.log('changePage - this.preSelectedRows in current page =' + this.preSelectedRows);
 }

 // On Row Selection - when select/deselect Checkbox
 rowSelection(evt) {
    let deselectedRecs = [];
    this.allSelectedRows = this.allSelectedRows.filter((v, i, a) => a.indexOf(v) == i);
    const selectedRows = evt.detail.selectedRows;
    console.log('rowSelection - Selected Rows are ' + JSON.stringify(selectedRows));
    console.log("rowSelection - selectedRows.length" + selectedRows.length);
    //concat new selected ids to allSelectedRows list
    this.allSelectedRows  = selectedRows
              .map(x => x.UserId)
              .concat(this.allSelectedRows ).filter((v, i, a) => a.indexOf(v) == i);
    console.log("rowSelection - this.allSelectedRows concat new selected ids= " + this.allSelectedRows);
    //remove new selected ids from deselectedRecs list
    this.deselectedRecs = this.pageSlice
        .filter(x => !selectedRows.includes(x))
        .concat(selectedRows.filter(x => !this.pageSlice.includes(x)))
        .map(x => x.UserId).filter((v, i, a) => a.indexOf(v) === i);
    console.log('rowSelection - Deselected Recs are original ' + this.deselectedRecs);
    console.log('rowSelection - deselectedRecs.length ' + this.deselectedRecs.length);
    if (this.deselectedRecs.length > 0) {
        //remove deselected ids from allSelectedRows list
        this.allSelectedRows = this.allSelectedRows.filter(item => !this.deselectedRecs.includes(item)).filter((v, i, a) => a.indexOf(v) === i);
    }
    console.log('rowSelection - Final allSelectedRows= ' + this.allSelectedRows);
  }

  updateRecords(event) {
    console.log('this.allSelectedRows updateRecords'+ this.allSelectedRows);
      console.log('this.preSelectedRows updateRecords'+ this.preSelectedRows);
    this.allDeSelectedRows = this.preSelectedRows
                                  .filter(item => !this.allSelectedRows.some(obj => obj === item))
                                  .filter((v, i, a) => a.indexOf(v) === i);
    if (this.allDeSelectedRows.length > 0) {
      this.showLoadingSpinner = true;
      console.log('this.allDeSelectedRows updateRecords'+ this.allDeSelectedRows);

      userRecordsUpdate({
          deSelectedArrList: this.allDeSelectedRows
        })
        .then(result => {
          if (result) {
            console.log('result userRecordsUpdate ='+ result);
            this.showLoadingSpinner = false;
            this.dispatchEvent(
              new ShowToastEvent({
                title: 'Success',
                message: 'User List updated',
                variant: 'success'
              })
            );
           window.location.reload();
          } else {
             console.log('Update failed.');
             this.dispatchEvent(
                  new ShowToastEvent({
                     title: 'Error updating user records',
                     message: 'Update failed',
                     variant: 'error'
                     }));
          }
        })
        .catch(error => {
          this.showLoadingSpinner = false;
          console.log('Update failed due to - ' + error);
          this.dispatchEvent(
            new ShowToastEvent({
              title: 'Error updating user records',
              message: error,
              variant: 'error'
            }));
        });
    }
    else
    {
        this.dispatchEvent(
        new ShowToastEvent({
            title: 'No records to Update',
            message: 'No users to de-activates',
            variant: 'info'
            })
        );
    }
  }

  deactivateProcess(event) {
        this.showLoadingSpinner = true;
         let chk = event.target.checked;
         console.log("clicked : "+ event.target.checked);

         if (chk != null) {

             updateUserManagementProcess({
                   status: event.target.checked
                 })
                 .then(result => {
                   if (result) {
                     console.log('result updateUserManagementProcess ='+ result);
                     this.showLoadingSpinner = false;

                     if(chk == true)
                     {
                         this.dispatchEvent(
                           new ShowToastEvent({
                             title: 'Success',
                             message: 'User Deactivation is Active',
                             variant: 'success'
                           })
                     );
                     }
                     else
                     {
                          this.dispatchEvent(
                             new ShowToastEvent({
                               title: 'Success',
                               message: 'User Deactivation is Inactive',
                               variant: 'success'
                          })
                       );
                       }


                   } else {
                      console.log('Update failed.');
                      this.dispatchEvent(
                           new ShowToastEvent({
                              title: 'Error updating user management meta-data record',
                              message: 'Update failed',
                              variant: 'error'
                              }));
                   }
                 })
                 .catch(error => {
                   this.showLoadingSpinner = false;
                   console.log('Update failed due to - ' + error);
                   this.dispatchEvent(
                     new ShowToastEvent({
                       title: 'Error updating user management meta-data record',
                       message: error,
                       variant: 'error'
                     }));
                 });
   		}
   else
       {
           this.dispatchEvent(
           new ShowToastEvent({
               title: 'Update Failed',
               message: 'Error updating user management meta-data record',
               variant: 'info'
               })
           );
       }
     }



  // Sorting
   handleSortdata(event) {
          // field name
          this.sortBy = event.detail.fieldName;
          console.log('this.sortBy = '+this.sortBy);
          // sort direction
          this.sortDirection = event.detail.sortDirection;
          console.log('this.sortDirection = '+this.sortDirection);
          // calling sortdata function to sort the data based on direction and selected field
          this.sortData(event.detail.fieldName, event.detail.sortDirection);
      }

      sortData(fieldname, direction) {
          // serialize the data before calling sort function
          let parseData = JSON.parse(JSON.stringify(this.data));
           console.log('this.parseData = '+this.parseData);
           console.log('this.fieldname = '+fieldname);
          // Return the value stored in the field
          let keyValue = (a) => {
              return a[fieldname];
          };

          // cheking reverse direction
          let isReverse = direction === 'asc' ? 1: -1;

          // sorting data
          parseData.sort((x, y) => {
              x = keyValue(x) ? keyValue(x) : ''; // handling null values
              y = keyValue(y) ? keyValue(y) : '';

              // sorting values based on direction
              return isReverse * ((x > y) - (y > x));
          });

          // set the sorted data to data table data
          this.data = parseData;

      }
}

​​​​​​​
Hi,

I have Apex code  output JSON data,

User-added image

I wish to display this json data in my LWC. 
Html:
<template>
    <lightning-card title="Report Data" icon-name="lightning-icon" >
        <div class="slds-m-around_medium">
            <template if:true={lapp}>
                <ul>
               <template for:each={lapp} for:item="app">
                   <li key={app.Id}> {app.Name} </li>
               </template>
            </ul>
           </template>
           <template if:true={error}>
               {error}
           </template>  
        </div>
 </lightning-card>
</template>

Js:
import { LightningElement, wire, track} from 'lwc';
import getURL from '@salesforce/apex/CreateReport.reportgen';
export default class RedirecctedURL extends LightningElement {
       @track lapp;
       @track data;
       @track error;
       wiredActivities;
     @wire(getURL,{
     }
     )
     wiredCases(value){
     this.wiredActivities = value;
     const { data, error } = value;
     
     if(data){
       this.lapp = JSON.stringify(data);
       console.log(JSON.stringify(data));
     
     }else if(error){
       console.log(error);
       this.error = error;
     }
     }
}

Any help??
 

Hi Everyone!

I want a list of account using Lightning-datatable. But it is not displaying the list of accounts.
HTML:

<template>
    <lightning-card title="t">
        <template if:true={accList}>
    <lightning-datatable
    key-field="Id"
    data={data}
    columns={columns}>
    </lightning-datatable>
    </template>
    <template if:true={error}>
        {error}
    </template>
</lightning-card>
</template>

JS:

import { LightningElement ,api, wire, track} from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
export default class Test extends LightningElement {
    @track columns = [{
            label: 'Account name',
            fieldName: 'Name',
            type: 'text',
            sortable: true
        },
        {
            label: 'Type',
            fieldName: 'Type',
            type: 'text',
            sortable: true
        },
      
    ];
 
    @track error;
    @track accList ;
    @wire(getAccountList)
    wiredAccounts({
        error,
        data
    }) {
        if (data) {
            this.accList = data;
            alert(JSON.stringify(accList));
            alert(JSON.stringify(data));
        } else if (error) {
            this.error = error;
        }
    }
}

Apex Class: 

public with sharing class AccountHelper {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Type, Rating,
                Phone, Website, AnnualRevenue
            FROM Account LIMIT 10];
    }
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        
            <target>lightning__AppPage</target>
            <target>lightning__RecordPage</target>
            <target>lightning__HomePage</target>
        
    </targets>
</LightningComponentBundle>

Output: 

User-added image

I want the list of accounts.

Thank you in Advance!

Hi,
I have created a drop down menu in lightning web component. But, I want a pop up will appear on click of a menu item. 
I tried this for pop up, But it is not working. On click of a "Rename " Menu item . A pop up will be shown.

button.html

<template>
    <div class="slds-p-around_medium lgc-bg">
        {selectedItemValue}
        {ready}
        <lightning-card title="Drop Down">
            <lightning-button-menu alternative-text="Show menu" variant="border-filled" onselect={handleOnselect}>
                {selectedItemValue}
                <lightning-menu-item value="openinsharepoint" label="Open in SharePoint" prefix-icon-name="utility:new_window"
                    href="#"
                    target="_blank">
                </lightning-menu-item>
                <lightning-menu-item value="rename" label="Rename" prefix-icon-name="utility:edit">
                    <template if:true={ready}>
                        <section role="dialog" tabindex="-1" class="slds-modal slds-fade-in-open slds-modal_small"
                            aria-labelledby="modal-heading-01" aria-modal="true" aria-hidden="true"
                            aria-describedby="modal-content-id-1">
                            <div class="slds-modal__container">
                                <!-- Modal/Popup Box LWC header here -->
                                <header class="slds-modal__header">
                                    <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={closeModal}>
                                        <lightning-icon icon-name="utility:close"
                                            alternative-text="close"
                                            variant="inverse"
                                            size="small" ></lightning-icon>
                                        <span class="slds-assistive-text">Close</span>
                                    </button>
                                    <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Rename LWC Setup.docx</h2>
                                </header>
                                <!-- Modal/Popup Box LWC body starts here -->
                                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                                    <lightning-input type="text" name="folder_name" label="Rename" placeholder="Enter new item name">
                                    </lightning-input>
                                </div>
                                <!-- Modal/Popup Box LWC footer starts here -->
                                <footer class="slds-modal__footer">
                                    <button class="slds-button slds-button_neutral" onclick={closeModal} title="Cancel">Cancel</button>
                                    <button class="slds-button slds-button_brand" onclick={submitDetails} title="Create">Create</button>
                                </footer>
                            </div>
                        </section>
                        <div class="slds-backdrop slds-backdrop_open"></div>
                    </template>
                </lightning-menu-item>
                <lightning-menu-item value="download" label="Download" prefix-icon-name="utility:download">
                </lightning-menu-item>
                <div class="slds-has-divider_top-space" role="separator">
                    <lightning-menu-item value="delete" label="Delet" prefix-icon-name="utility:close"></lightning-menu-item>
                </div>
            </lightning-button-menu>
        </lightning-card>
    </div>
</template>

button.js

import { LightningElement, track } from 'lwc';
export default class ButtonMenuOnselect extends LightningElement {
    @track selectedItemValue;
    @track ready;
    handleOnselect(event) {
        this.selectedItemValue = event.detail.value;
        if(this.selectedItemValue == "rename")
        {
        alert("ready");
        this.ready = true;
        alert("false");
        }
        
    }
}

 

i have 3 fields 
field 1- mr
field 2- bean
in the field 3 i have to show 'mr bean '
basically i have to show the 2 fields value in the 3rd field