• Alain Cabon
  • ALL STAR
  • 11225 Points
  • Member since 2016

  • Chatter
    Feed
  • 356
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 2235
    Replies
Hello
I wrote a lightning/aura component. This component lists all the orders associated with a case. When I running a SOQL query, I am getting 5 unique orders for a particular case, for example. But when I am looking at the lightning component, its displaying the same order 5 times. So I am thinking that the aura component is not iterating the apex list properly. I have the code below. Can anyone pinpoint, where I might have gone wrong?

Apex controller:
public class CC_OrderListController {
    
    @AuraEnabled
    public static List <Order> getOrders(Id caseId) {
        Case c = [select ContactId from Case where Id = :caseId LIMIT 1];
        Id con = c.ContactId;
        system.debug(con);
        
        List<Order> result = [SELECT Id, BillToContact.Email, EffectiveDate, Sub_Total__c, External_Order_URL__c FROM Order where BillToContactId = :con ORDER BY createdDate DESC LIMIT 20];
        system.debug(result);
        return (result == null ? new List<Order>() : result);
    }
    
}

Aura component:
<aura:component implements="flexipage:availableForAllPageTypes,force:hasRecordId" controller="CC_OrderListController" access="global">
    
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>

    <aura:handler name="init" value="{! this }" action="{! c.init }"/>


    <div style="min-height: 200px;">
        <lightning:datatable
                keyField="id"
                data="{! v.data }"
                columns="{! v.columns }"
                hideCheckboxColumn="true"/>
    </div>
    
</aura:component>

Aura JS controller:
({
    init : function(component, event, helper) {
        
        component.set('v.columns', [
            {label: 'Email', fieldName: 'Email', type: 'text'},
            {label: 'Order Date', fieldName: 'EffectiveDate', type: 'Date'},
            {label: 'Sub Total', fieldName: 'Sub_Total__c', type: 'currency'},
            {label: 'Order Link', fieldName: 'orderLink', type: 'url'}
        ]);

        var fetchData = {
            Email: "",
            EffectiveDate : "",
            Sub_Total__c : "",
            orderLink: ""
        };


        helper.fetchData(component,fetchData);
        
    }
})

JS Helper method:
({
    fetchData : function(component, fetchData) {
        var action = component.get('c.getOrders');
        action.setParams({ "caseId" : component.get('v.recordId') });
        
        var self = this;
        var results = [];
        action.setCallback(this, function(actionResult) {
            var res = actionResult.getReturnValue();
            for(var i = 0; i < res.length;i++){
                fetchData.Email = res[i].BillToContact.Email;
                fetchData.EffectiveDate = res[i].EffectiveDate;
                fetchData.Sub_Total__c = res[i].Sub_Total__c;
                fetchData.orderLink = res[i].External_Order_URL__c;
                
                results.push(fetchData);
            }
            
            component.set('v.data', results)
        });
        $A.enqueueAction(action);
    }
})

Should I use aura iteration tag ? Any help would be greatly appreciated. Thank you
Hi dev team,

I have created a custom object with questions and corresponding marks detailed in several text and number fields to be displayed in a specific graph. The request is to create a Spider Chart.
Is there a existing Ligtning component for this sort of chart?
Or do you advise anything else?

Thank you.
Best Regards,
Ludivine
Hello friends, 

Please help me with a simple query to get records if data A is > date B. I tried this soql query in query builder but it give error. 

Select Forecast_Handover__c,Name,Site__c,Forecast_Sales_Date__c from Cbd_plot__c where  Forecast_Handover__c > Forecast_Sales_Date__c

both these forecast date fields are date fields in salesforce I am getting error 'Unknown error parsing query'

but at the same time is I try 

Select Forecast_Handover__c,Name,Site__c,Forecast_Sales_Date__c from Cbd_plot__c where  Forecast_Handover__c > TODAY

its returning me records. 

Many thanks in advance
Hi,
my challenge when doing the above mentioned module fails with the following error:

"The test method doesn’t insert an opportunity with the correct fields. Double check the Name, StageName, and CloseDate and try again."

The requirement is as follows:
In the test method, create an opportunity with the following fields.
Name: 'Sell 100 Widgets'
StageName: 'Prospecting'
CloseDate: Date.today().addMonths(3)


And the code is this:
    Opportunity opp =  new Opportunity(Name='Sell 100 Widgets',
           CloseDate=System.Date.today().addMonths(3),
           StageName='Prospecting');
    insert opp;


Any idea what could be wrong?

 
Hi all,
I have just started in a new company with an old very customize Salesforce instance. I have just discovered that an object has 25.000 new records created each week.
My question is how can I find which process / workflow / trigger or Apex is created these records? 
Thank you for your help.
Sylvie
 
I am working on validation for IPV4 and IPV6 to validate their input.
This IP input fields should also accept the subnet mask.

Valid input in IPV4 field can be :
172.16.0.0
172.16.0.0/8
172.16.0.0/192
213.248.89.98/31

Valid input in IPV6 field can be :
2001:db8:abcd:0012::0/64
2001:db8:abcd:0012:0000:0000:0000:0000
2001:2000:3080:001D::2/126

Is it something possible with regex or custom code? I tried couple of regex solutions but its not working. 
I am new to Sales force API integration with .NET and came accross this issue - can't seem to get the sObject id from QueryResult - the id is null, even though a valid record is returned, and I can see the Name field. Any suggestions?
See my query below:

  string queryStr = $"SELECT id, Name FROM Account Where Name = '{name}'";
                QueryResult qResult = _service.query(queryStr);
                bool done = false;

                if (qResult.size > 0)
                {
                    while(!done)
                    {
                        sObject[] records = qResult.records;

                        for(int i = 0; i < records.Length; i ++)
                        {
                            accountId = records[i].id; // record id is null here
                        }

                        if (qResult.done)
                        {
                            done = true;
                        }
                        else
                        {
                            qResult =
_service.queryMore(qResult.queryLocator);
                        }
                    }            
                }
I have a method called getAccountIds, that is successfully returning a set of Account Ids. I second method that is countContacts(List<Id>acctIds). But when I return the acctIds, it doesn't get added picked up by the second method.
I'm calling the class from an execute anonymous window like this --> 
AccountProcessor.getAccountIds(); 
AccountProcessor.countContacts();



Actual Class and methods. 
 
public class AccountProcessor {
    
    public static List<Id> getAccountIds(){
        List<Id> acctIds = new List<Id>(); 
        For(Account a:[SELECT Id FROM Account LIMIT 200] ){
            acctIds.add(a.Id);
        }
        System.debug('The list of Ids = ' + acctIds); 
        System.debug('The size of List = ' +acctIds.size());
        return acctIds; 
        
    }
   
    
    @future
  
    
    public static void  countContacts(List<Id> acctIds){
       	//Declare Variables.
       	Account accountToUpdate; 
        List<Account> accountsToUpdate = new List<Account>(); 
       	Integer totalContacts = 0; 
        System.debug('Size of List =' + acctIds.size());
        List<Contact> cons = [SELECT Id, AccountId FROM Contact WHERE AccountId IN: acctIds]; 
        System.Debug('Contact List = ' + cons.size()); 
		
        //Loop through the contacts and sum the account Id for each contact. 
        for( Id a : acctIds){
            
            System.Debug('Account Ids on Contact = ' + a); 
          	Contact[] contactIdArray = new List<Contact>();  
                   for(Contact c : cons){
                      // System.debug('Enter Contact Loop ');
                      // System.Debug('Account Id = ' + a);
                       Boolean resultType = a.equals(c.AccountId);
                       //System.Debug('ResultType is ? ' + resultType); 
                        
                      	If(a==c.AccountId){
                             contactIdArray.add(c);
                          	
                       		}
                       
					
	        }
             
             
             accountToUpdate = [SELECT Id FROM Account WHERE Id =: a LIMIT 1]; 
             totalContacts = contactIdArray.size();
             accountToUpdate.Number_of_Contacts__c = totalContacts; 
             accountsToUpdate.add(accountToUpdate); 
             System.debug('Total Contacts = ' + totalContacts);
             System.debug('Total Update Accounts = ' + accountsToUpdate.size());
            
        }
       update accountsToUpdate; 
        
    }
	 	
}

 
Hi...

We want to share a scratch org between two developers. How could we do?

Thanks
Trying to replicate this https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_flows_lightningruntime.htm
 but getting error here is my code. 

App:
<aura:application access="global"  extends="ltng:outApp" implements="ltng:allowGuestAccess">
	<aura:dependency resource="lightning:flow"/>
</aura:application>
VF Page: 
<apex:page >
   <html>
      <head>
         <apex:includeLightning />
      </head>
      <body class="slds-scope">
          
         <div id="flowContainer"/>
         <script>
            var statusChange = function (event) {
               if(event.getParam("status") === "FINISHED") {
                  // Control what happens when the interview finishes
 
                  var outputVariables = event.getParam("outputVariables");
                  var key;
                  for(key in outputVariables) {
                     if(outputVariables[key].name === "myOutput") {
                        // Do something with an output variable
                     }
                  }
               }
            };
            $Lightning.use("c:FlowVFPage", function() {
               // Create the flow component and set the onstatuschange attribute
               $Lightning.createComponent("lightning:flow", {"onstatuschange":statusChange},
                  "flowContainer",
                  function (component) {
                     // Set the input variables
                      
                     
                     // Start an interview in the flowContainer div, and 
                     // initializes the input variables.
                     component.startFlow("New_Customer", inputVariables);
                  }
               );
            });
         </script>
      </body>
   </html>
</apex:page>

How to solve this error? thanks in Advance. 


 
Hi everyone. I work with small project and ran into a problem. I need to display the most popular genre of the song in the mix object and the second after it, how can I do it using the main syntax of SOQL. If you give SOQL code or example it would be cool.
User-added image
Hi everyone

I build a custom lightning web component (lwc) with a datatable and a wire-function with an apex-controller.
If i place the lwc on the lightnig record page an error appears:

Looks like there's a problem.

Unfortunately, there was a problem. Please try again. If the problem continues, get in touch with your administrator with the error ID shown here and any other related details. An internal server error has occurred Error ID: 747686150-78663 (1184503911)

Here is a screenshot with the error: https://i.imgur.com/3Ov7PnQ.png

No error in debug log and no error is shown up in browser-console.
I have no reason why this happen. Has anyone some suggestions?

rssFeed.html:
<template>
    <div class={flexipageRegionWidth}>
        <div class="slds-m-top_medium slds-m-bottom_x-large">

            <!-- Simple -->
            <template if:true={data}>
                <div class="slds-p-around_medium lgc-bg">
                    <lightning-datatable
                        key-field="id"
                        data={data}
                        columns={columns}
                        is-loading={tableLoadingState}
                        hide-checkbox-column={hideCheckboxColumn}>
                    </lightning-datatable>
                </div>
            </template>
        </div>
        
        <!-- Data failed to load -->
        <template if:false={data}>
            <div class="slds-text-color_error">
                An error occurred while loading.
            </div>
        </template>
    </div>
</template>

rssFeed.js:
import { LightningElement, wire, track, api } from 'lwc';

import { getObjectInfo } from 'lightning/uiObjectInfoApi'; // https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.reference_wire_adapters_object_info
import RSSFEED_OBJECT from '@salesforce/schema/RSSFeed__c';

import getFilteredRssFeeds from '@salesforce/apex/RssFeedController.getFilteredRssFeeds';

export default class RssFeed extends LightningElement {
    @api flexipageRegionWidth; // https://developer.salesforce.com/docs/component-library/documentation/lwc/use_width_aware
    @api recordId;// Public property. Id of brand-record.
    @api columnNames = undefined; // Public property. Set by lightning app builder.
    objectInfo = undefined; // 

    hideCheckboxColumn = true; // If true, the checkbox column for row selection is hidden.

    @track data;
    @track error;

    @track columns;
    @track tableLoadingState = true;
   

    @wire(getObjectInfo, { objectApiName: RSSFEED_OBJECT })
    wireObjectInfo({error, data}){
        console.log('>>>wireObjectInfo called.');

        if (data) {
            console.log('>>>data: ' + JSON.stringify(data, null, '\t'));
            this.objectInfo = data;
            this.error = undefined;

            this._prepareTableColumns();
        } else if (error) {
            console.error('>>>error: ' + JSON.stringify(error, null, '\t'));

            this.error = error;
            this.objectInfo = undefined;
        }
    }
    
    @wire(getFilteredRssFeeds, { brandId: '$recordId' })
    wiredFilteredRssFeeds({error, data}){
        console.log('>>>wiredFilteredRssFeeds called.');

        if (data) {
            console.log('>>>' + JSON.stringify(data, null, '\t'));
            this.data = data;
            this.error = undefined;
        } else if (error) {
            console.error('>>>' + JSON.stringify(error, null, '\t'));
            this.error = error;
            this.data = undefined;
        }
    }

    _prepareTableColumns(){
        console.log('>>>_prepareTableColumns called.');
        this.columns.forEach(column => {
            let columnLabel = ((this.objectInfo) ? this.objectInfo.fields[column.fieldName].label : '');
            column.label = columnLabel;
            console.log('>>>column' + JSON.stringify(column, null, '\t'));
        });
    }

    /**
    * https://developer.salesforce.com/docs/component-library/documentation/lwc/create_lifecycle_hooks_dom.html
    * The connectedCallback() lifecycle hook fires when a component is inserted into the DOM.
    */
    async connectedCallback() {
        console.log('>>>async connectedCallback called.');
        this.tableLoadingState = false;
        console.log('>>>this.columnNames: ' + this.columnNames);

        this.columns = JSON.parse(this.columnNames);
        console.log('>>>this.columns: ' + JSON.stringify(this.columns, null, '\t'));
    }
}

rssFeed.js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="RssFeed">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <property default="[{ 'label': 'Title', 'fieldName': 'Title__c' },{ 'label': 'Description', 'fieldName': 'Description__c' },{ 'label': 'Link', 'fieldName': 'Link__c', 'type': 'url', 'fixedWidth': 200 },{ 'label': 'Date', 'fieldName': 'Date__c', 'type': 'date', 'fixedWidth': 100 }]" description="Specifies which columns are displayed." label="Column Names" name="columnNames" required="true" type="String"/>
            <objects>
                <object>Brand__c</object>
            </objects>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Here is the apex-controller:
/**
* Is used for lightning web component (lwc) named rssFeed.
* Query relevant rss feed filtered by Id of Brand (Brand__c).
*
* @author: <Christian Schwabe> (Christian.Schwabe@colliers.com)
*
* @history:
* version		    | author				                                | changes
* ====================================================================================
* 0.1 08.05.2019	| Christian Schwabe (Christian.Schwabe@colliers.com)	| initial version.
*/
public with sharing class RssFeedController {

    /**
    * Query RSS-Feed records filtered by Id for Brand (Brand__c).
    *
    * @param  brandId          Id for Brand (Brand__c)
    *
    * @return List<Brand__>
    */
    @AuraEnabled(cacheable=true)
    public static List<RSSFeed__c> getFilteredRssFeeds(Id brandId){
        List<RSSFeed__c> listOfRssFeed = new List<RSSFeed__c>();
        for(RSSFeed__c rssFeed : [SELECT Id, Link__c, Title__c, Author__c, Description__c, Date__c FROM RSSFeed__c WHERE Brand__c = :brandId]){
            rssFeed.Description__c = String.valueOf(rssFeed.Description__c).stripHtmlTags();

            listOfRssFeed.add(rssFeed);
        }

        return listOfRssFeed;
    }
}


 
So I have object Account.name which I need to take the last word of the string and place it at the beginning. For example, I have John and Jamie Jones and I need the custom field to read: Jones, John and Jamie
Hi,

I'm trying to accomplish OpportunityChangeTrigger challenger from trailhead but I found one error and I don't know how to address it.
The error is:
The trigger doesn't create the expected task for opportunities whose stage has been updated to 'Closed Won'.

This is my code for the trigger:
 
trigger OpportunityChangeTrigger on OpportunityChangeEvent (after insert) {
    List<Opportunity> opps = new List<Opportunity>();
    List<Task> taskList = new List<Task>();
    for(OpportunityChangeEvent event : Trigger.New){
        EventBus.ChangeEventHeader header = event.ChangeEventHeader;
        if(header.changeType == 'UPDATE' && event.isWon){
			Task task = new Task();
            task.subject = 'Follow up on won opportunities: ' +header.recordIds;
            tasklist.add(task);
        }
    }
    if(taskList.size()>0){
        insert taskList;
    }

}

And this is the  test class
@isTest
public class TestOpportunityChangeTrigger {
    @isTest static void testCreateAndUpdateEmployee(){
        Test.enableChangeDataCapture();
        insert new Opportunity(Name='Sell 100 Widgets', StageName='Prospecting', CloseDate=Date.today().addMonths(3));
        Test.getEventBus().deliver();
        Opportunity[] oppList = [SELECT Id,StageName FROM Opportunity];
        for (Opportunity opp : oppList){
          opp.StageName = 'Closed Won';
          update opp;
          Test.getEventBus().deliver();
      }
        Task[] taskList = [SELECT Id FROM Task];
        System.assertEquals(1, taskList.size(),'The change event trigger did not create the expected task.');
    }
}



 
Hi all, 

I am still learning writing apex code and could use some help on a controller I am writing for a visualforce email template. 

What I am trying to do is use a visualforce component to list all active contracts related to an account when a case is declined. 

Everything seems to work EXCEPT the component lists EVERY active contract not just those associated with the account. 

Any help would be greatly appreciated!!

Thanks,
Tasia

My controller looks like this: 

public class FindActiveContracts {
    private final List<Contract> contracts;
    public FindActiveContracts(){
        contracts = [select Name from Contract where status='Activated' AND EndDate > TODAY AND StartDate < TODAY AND AccountId IN (SELECT Id from Account Where Id =:case.accountId)];
        }
    public List<Contract> getActiveContracts() {
        return contracts;
    }
}

My component looks like this: 
<apex:component controller ="FindActiveContracts" access="global">
    <apex:dataTable value="{!ActiveContracts}" var="s_contract">
    <apex:column>
    <apex:facet name="header">Service Name</apex:facet>
        {!s_contract.Name}
    </apex:column>
</apex:dataTable>
</apex:component>

My email template looks like this: 
<messaging:emailTemplate subject="Your Ask E Source request on {!relatedTo.Subject}"
recipientType="Contact" 
relatedToType="Case"
replyTo="emily_hunsicker@esource.com">
<messaging:htmlEmailBody >        
    <html>
        <body>
         <STYLE type="text/css">
               TH {font-size: 11px; font-face: arial;background: #CCCCCC; border-width: 1;  text-align: center } 
               TD  {font-size: 11px; font-face: verdana } 
               TABLE {border: solid #CCCCCC; border-width: 1}
               TR {border: solid #CCCCCC; border-width: 1}
         </STYLE>
                  <font face="arial" size="2">
    <p>Hi {!recipient.Name},</p>
    <p>Thanks for your recent Ask E Source request on {!relatedTo.Subject}. We have done research about this topic as part of our E Source {!relatedTo.ProductLookup__r.Name}. Unfortunately, {!recipient.Account_Name__c} is not a member of that service, so we will not be able to answer your question at this time.</p>
        <p>Our <a href="https://www.esource.com/questions-faq">Ask E Source FAQ</a> describes the general topics that are covered under each of our services; you currently have access to these services:</p>
        <c:SetActiveContracts />                 
       <p>If you’d like a personal overview of your membership, please <a href="{!recipient.CSD_Calendly_Link__c}">contact us</a> to sign up for a 30-minute walk-through with your Customer Success Director, {!recipient.CSD_Name__c}. I have copied both {!recipient.CSD_First_Name__c} and {!recipient.BDD_Name__c}, your sales contact, on this message. 
 </p> 
       <p> Best,</p>
       <p> Emily Hunsicker</p>
       <p> Customer Success Coordinator, E Source</p>       
 </font>
       
        </body>
    </html>
Hi. I am trying to implement an interface that will perform the following filter on input records.

- Do not include any record that has the field “Deleted__c” as true. (I have already created this custom field in the Account object)
- Do not include any record that is newer than 24 hours.
- Do not include any record that has an address outside of Japan.

Unfortunately, when I try the unit tests I created,  there are some System.AssertException errors. Having searched all over the internet for possible solutions, I am at a loss at what I am doing wrong. Please have a look at my code and guide me on what I should change. Any help would be greatly appreciated. Many thanks in advance.

INTERFACE
public interface IFilter {
List<Account> filter(List<Account> records);
}

IMPLEMENTATION
public class AccountFilterJapanOnly implements IFilter{

    public List<Account> filter(List<Account> records)
    {
        DateTime twentyFourHoursAgo = DateTime.now().addHours(-24);
        List<String> jpCountry = new List<String>{'Japan', 'JP'};
        
        List<Account> returnedAccountsList = new List<Account>();
        
        for( Account matchingAccount : [SELECT Name, AccountNumber, BillingAddress, Deleted__c, CreatedDate
                                        FROM Account
                                        WHERE Deleted__c != TRUE AND 
                                             CreatedDate < :twentyFourHoursAgo AND
                                            BillingCountry IN :jpCountry])
        {
            System.debug(matchingAccount);
            returnedAccountsList.add(matchingAccount);
        }
        
        return returnedAccountsList;
    }    
}

UNIT TESTS
@isTest
public class AccountFilterJapanOnlyTest {

    //NOT WORKING AS EXPECTED
    @isTest static void testDeletedField()
    {
        Account testAccDelTrue = new Account(Name='DeletedFieldTrue', Deleted__c=TRUE);
        Account testAccDelFalse = new Account(Name='DeletedFieldFalse', Deleted__c=FALSE);
        Account[] accts = new Account[]{testAccDelTrue, testAccDelFalse};
        //Insert accts;
        
        Test.startTest();
        AccountFilterJapanOnly jpRecords = new AccountFilterJapanOnly();
        List<Account> lst = jpRecords.filter(accts);
        Test.stopTest();
        
        System.assertEquals(1, lst.size());
        System.assertEquals(testAccDelFalse, lst[0]);        
    }
    
    //GIVING CORRECT RESULTS BUT STILL UNSURE IF THIS IS ACCURATE
    @isTest static void testCreatedDate()
    {        
        Account testCreatedDate = new Account(Name='Created Within 24 hours');
        Account[] accts = new Account[]{testCreatedDate};
        Insert accts;
        
        Test.startTest();
        AccountFilterJapanOnly jpRecords = new AccountFilterJapanOnly();
        List<Account> lst = jpRecords.filter(accts);
        Test.stopTest();
        
        System.assertEquals(0, lst.size());        
    }
    
    //NOT WORKING AS EXPECTED
    @isTest static void testLocation()
    {       
        Account testOutsideJapan = new Account(Name='Address Outside Japan', BillingCountry='USA');
        Account testWithinJapan1 = new Account(Name='Address1 Within Japan', BillingCountry='Japan');
        Account testWithinJapan2 = new Account(Name='Address2 Within Japan', BillingCountry='JP');
        Account[] accts = new Account[]{testOutsideJapan,testWithinJapan1,testWithinJapan2};
        Insert accts;
        
        Test.startTest();
        AccountFilterJapanOnly jpRecords = new AccountFilterJapanOnly();
        List<Account> lst = jpRecords.filter(accts);
        Test.stopTest();
        
        System.assertEquals(2, lst.size());
        System.assertEquals(true, lst.contains(testWithinJapan1));
        System.assertEquals(true, lst.contains(testWithinJapan2));
    }
}



 
Hi Friends,

Far from a LWC expert here. and trying to get a Lightning Data Table that is sortable. I feel like I have followed everything in the documentation but when I click the arrow in the table header nothing happens. 

Here is my JS
import { LightningElement, track, wire, api } from 'lwc';
import getRecords from '@salesforce/apex/NewToLiftController.getRecords';
import { getRecord } from 'lightning/uiRecordApi';
import { NavigationMixin } from 'lightning/navigation';

const columns = [
    { label: 'First Name', fieldName: 'FirstName', type: "Text", sortable: true},
    { label: 'Last Name', fieldName: 'LastName', type: "Text", sortable: true },
    { label: 'Email', fieldName: 'Email', type: 'Email', sortable: true },
    { label: 'Role', fieldName: 'Role__c', type: 'Text', sortable: true },
    { label: 'Startup Leadership', fieldName: 'Startup_Leadership__c', type: 'boolean', sortable: true },
    { label: 'Company', fieldName: 'CompanyOrAccount', type: 'Text', sortable: true },
];

export default class DatatableBasic extends LightningElement {
@api recordId;
@track data = [];
@track columns = columns;
@track tableLoadingState = true;
@track rowOffset = 0;

@ wire(getRecords, {recordId: '$recordId'})
    wiredRecordsMethod({error, data}) {
        if (data) {this.data = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.data = undefined;
        }
        this.tableLoadingState = false;
    }
    increaseRowOffset(){this.rowOffset += 1;
    }
    // The method onsort event handler
    updateColumnSorting(event) {
        var fieldName = event.detail.fieldName;
        var sortDirection = event.detail.sortDirection;
        // assign the latest attribute with the sorted column fieldName and sorted direction
        this.sortedBy = fieldName;
        this.sortedDirection = sortDirection;
        this.data = this.sortData(fieldName, sortDirection);        
    }
}
And here is the HTML
 
<template>
            <lightning-card title='First Time Campaign Memebers' icon-name="standard:contact">
                <lightning-datatable
                        key-field="id"
                        data={data}
                        show-row-number-column
                        row-number-offset={rowOffset}
                        hide-checkbox-column
                        columns={columns}
                        sorted-by={sortedBy}
                        sorted-direction={sortedDirection}
                        onsort={updateColumnSorting}
                        is-loading={tableLoadingState}>
                </lightning-datatable>
            </lightning-card>
</template>

 
Hi All, 

I'm trying to explore Data Loader to Use the Bulk API. I am following the Data Loader Guide and when I try to run encrypt.bat -g sometext I am having an error like this.


C:\Users\User\dataloader\bin>encrypt -g myKey
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/salesforce/dataloader/security/EncryptionUtil has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

What are the ways to solve this issue?

Thank you so much in advance.
Hi all,

in the documentation (https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/documentation) a way is documented to preselect rows programmatically.
For this reason you should use "selected-rows"-attribut on lightning-datatable.

DOCUMENTATION

The selected-rows attribute enables programmatic selection of rows, which is useful when you want to preselect rows.
<lightning-datatable
    columns={columns}
    data={data}
    key-field="id"
    selected-rows={selectedRows}>
</lightning-datatable>
<lightning-button
    label="Select"
    onclick={handleSelect}>
</lightning-button>

To select a row programmatically, pass in the row key-field value.
// Load data via init handler first
// then handle programmatic selection
handleSelect() {
   const rows = ['a'];
   this.selectedRows = rows;
}

My component looks (simplfied) the following way:
export default class MergeDuplicates extends LightningElement {
    @track preSelectedRows = ['0011x00000KOMiJAAX'];
    
    [...]
}

My html-file (simplified) looks the following way:
<lightning-datatable
       key-field="Id"
       data={data}
       columns={columns}
       onrowselection={handleSelected}
       selected-rows={preSelectedRows}
       is-loading={tableLoadingState}>
</lightning-datatable>

My purpose: Preselect the current account, because the lwc is placed on a lightning record page for account.

My problem: Nothing happens. No checkbox is active.

One of my first ideas was the key-field. I changed it from "id" (lowercase) to "Id" (uppercase) but that don't solve the problem.

I don't know any other simpler way to test the preselect of rows for datatable than my example above.

Any suggestions?
Hi guys,

I'm trying to filter a SOQL query on the LoginHistory object using the Application field. Apprrently, this is not possible since 'Application' is not filterable (curious as to why that is.) I'm wondering if there is any workaround to this limitation, assuming I need to filter the information in Application to achieve my goal.

Thanks!
i tried to personalize the contact update app to spanish. I could do everything, but the date format until shows like this: mm/dd/yyyy and i want dd/mm/yyyy
User-added image
User-added image
User-added imageUser-added imageUser-added image
Hello
I wrote a lightning/aura component. This component lists all the orders associated with a case. When I running a SOQL query, I am getting 5 unique orders for a particular case, for example. But when I am looking at the lightning component, its displaying the same order 5 times. So I am thinking that the aura component is not iterating the apex list properly. I have the code below. Can anyone pinpoint, where I might have gone wrong?

Apex controller:
public class CC_OrderListController {
    
    @AuraEnabled
    public static List <Order> getOrders(Id caseId) {
        Case c = [select ContactId from Case where Id = :caseId LIMIT 1];
        Id con = c.ContactId;
        system.debug(con);
        
        List<Order> result = [SELECT Id, BillToContact.Email, EffectiveDate, Sub_Total__c, External_Order_URL__c FROM Order where BillToContactId = :con ORDER BY createdDate DESC LIMIT 20];
        system.debug(result);
        return (result == null ? new List<Order>() : result);
    }
    
}

Aura component:
<aura:component implements="flexipage:availableForAllPageTypes,force:hasRecordId" controller="CC_OrderListController" access="global">
    
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>

    <aura:handler name="init" value="{! this }" action="{! c.init }"/>


    <div style="min-height: 200px;">
        <lightning:datatable
                keyField="id"
                data="{! v.data }"
                columns="{! v.columns }"
                hideCheckboxColumn="true"/>
    </div>
    
</aura:component>

Aura JS controller:
({
    init : function(component, event, helper) {
        
        component.set('v.columns', [
            {label: 'Email', fieldName: 'Email', type: 'text'},
            {label: 'Order Date', fieldName: 'EffectiveDate', type: 'Date'},
            {label: 'Sub Total', fieldName: 'Sub_Total__c', type: 'currency'},
            {label: 'Order Link', fieldName: 'orderLink', type: 'url'}
        ]);

        var fetchData = {
            Email: "",
            EffectiveDate : "",
            Sub_Total__c : "",
            orderLink: ""
        };


        helper.fetchData(component,fetchData);
        
    }
})

JS Helper method:
({
    fetchData : function(component, fetchData) {
        var action = component.get('c.getOrders');
        action.setParams({ "caseId" : component.get('v.recordId') });
        
        var self = this;
        var results = [];
        action.setCallback(this, function(actionResult) {
            var res = actionResult.getReturnValue();
            for(var i = 0; i < res.length;i++){
                fetchData.Email = res[i].BillToContact.Email;
                fetchData.EffectiveDate = res[i].EffectiveDate;
                fetchData.Sub_Total__c = res[i].Sub_Total__c;
                fetchData.orderLink = res[i].External_Order_URL__c;
                
                results.push(fetchData);
            }
            
            component.set('v.data', results)
        });
        $A.enqueueAction(action);
    }
})

Should I use aura iteration tag ? Any help would be greatly appreciated. Thank you
I built a custom class and method to return the aggregate data to plot a chart using LWC.  For the purpose of example, I hardcode the AccountId for now.
public with sharing class lwcLifetimeSpendingController {
    @AuraEnabled (cacheable=true)
    public static List<AggregateResult> getAccountLifetimeSpending(){
        return [SELECT SUM(Service_Amount__c) Service, SUM(Subscription_Booking__c) Subscription  FROM Opportunity WHERE accountid = '0018000001G9dZUAAZ' and isclosed=true and iswon=true];
    }
}

Here's my JS file.  How do I retrieve the aggregate values from the custom apex controller and use in the JS?  I tried getSObjectValue, but that did not work as it worked only with field data from the return Object.
import { LightningElement,track,wire } from 'lwc';
import { getSObjectValue } from '@salesforce/apex';
import { loadScript } from 'lightning/platformResourceLoader';
import chartjs from '@salesforce/resourceUrl/chart';
import getAccountLifetimeSpending from '@salesforce/apex/lwcLifetimeSpendingController.getAccountLifetimeSpending';

const generateRandomNumber = () => {
    return Math.round(Math.random() * 100);
};

export default class LifetimeSpending extends LightningElement {    
    @wire(getAccountLifetimeSpending) lifetimeAggregateResult;
    @track error;
    
     //getSObjectValue does not work in this scenario
} //end export

Here's the sample of the HTML file
<template>
    <lightning-card title="Lifetime Spending" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            <canvas class="donut" lwc:dom="manual"></canvas>
        </div>
        <template if:true={error}>
            <c-error-panel errors={error}></c-error-panel>
        </template>    
    </lightning-card>
</template>


 
Hi!! 

I have a lightning component that I am using in a flow to search for contacts. It works great on a desktop (see image below) but the search does not work in mobile. 

What am I missing? 

Any help would be greatly appreciated!
Tasia

User-added image

Here is my lightning component code:

Component
<aura:component implements="force:appHostable,lightning:availableForFlowScreens,flexipage:availableForAllPageTypes" access="global">
    <aura:attribute name="Contact" type="String" access="public" />
    <aura:attribute name="ContactLookup" type="String" access="public" />
    <aura:attribute name="ContactLookup__c" type="String" access="public" />
    <aura:attribute name="selectedRecordId" type="String" access="public" />
    
    <lightning:recordEditForm objectApiName="{!v.Contact}">
        <label class="ContactLookup">{!v.ContactLookup}</label>
        <lightning:inputField fieldName="{!v.ContactLookup__c}" onchange="{!c.handleOnChange}" />
    </lightning:recordEditForm>
</aura:component>    

Controller
({
    handleOnChange : function(component, event, helper) {
        component.set( "v.selectedRecordId", event.getParams( "fields" ).value );
    }
})

Style
.THIS label.slds-form-element__label {
    display: none;
}
.THIS .fieldLabel {
    font-size: .75rem;
}​​​​​​​

Design
<design:component>
    <design:attribute name="Contact" />
    <design:attribute name="ContactLookup" />
    <design:attribute name="ContactLookup__c" />
    <design:attribute name="selectedRecordId" />
</design:component>
 
I have writen a Batchable class that works in Sandbox. Im trying to write a test class for this and am really struggling to make headway. 

This is my Class 
global class HealthUpdaterBatchable implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) { 
        String query = 'SELECT Id FROM HealthScore__c';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<HealthScore__c> hsList) {
        for(HealthScore__c hs : hsList)
        {        
            hs.id = hs.id;
        }
        try {
        	
            update hsList;
        } catch(Exception e) {
            System.debug(e);
        }
    }   
    global void finish(Database.BatchableContext BC) {
    	
  }
}
This is my test class so far 
private class HealthUpdaterBatchableTest {

static testmethod void test() {

HealthScore__c[] hsList = new List();
for (Integer i=0;i<200;i++) {
HealthScore__c m = new Healthscore__c();
hsList.add(m);
}
insert hsList;

Test.startTest();
HealthUpdaterBatchable c = new HealthUpdaterBatchable();
Database.executeBatch(c);
Test.stopTest();
    
HealthScore__c[] hsUpdatedList = [SELECT Id FROM HealthScore__c];
System.assert(hsUpdatedList[0]);
}
}
Im getting a few errors
  • Expecting < but was ( -Line 6
  •  Invalid type: HealthScore - Line 18
  •  Method does not exist or incorrect signature: void assert(Healthscore) from the type System. - Line 19.
Any advice or assistance is very much appreciated 
 
  • August 12, 2019
  • Like
  • 0
Hi,

I have  a VF page which displays a list of account team members.  The page uses a controller extension which get the actual list.  I have a test class in which I create an account and the team members. I don't know how to actually test that the team member list is correctly displayed.  

Thank you in advance!!

Here is my VF page:

<apex:page standardController="Account" extensions="AcctTeamMemberController">
    
    <apex:form >

       <apex:pageBlock title="Account Team">
            
            <apex:pageBlockTable value="{!atmList}" var="atm">
                
                <apex:column width="130" value="{!atm.User.Name}"/>
                <apex:column value="{!atm.TeamMemberRole}"/>
            
            </apex:pageBlockTable>
        
        </apex:pageBlock>
    
    </apex:form>

</apex:page>


Here is my controller extension:

public class AcctTeamMemberController {
    public List<AccountTeamMember> atmList {get; set;}
    public AcctTeamMemberController(ApexPages.StandardController controller) {
        Account acc = (Account) controller.getRecord();
        
        atmList = [SELECT Id, AccountId, TeamMemberRole,UserId, 
                   User.Name FROM AccountTeamMember where AccountId =: acc.Id];
    }

}

Here is my test class so far:

@isTest
public class TestAcctTeamMemberController {
    private static testmethod void TestATMController(){
        
        //create an account
        Account Acc = new Account(Name='New Account', Type='Client', OwnerId='005d0000001l4LXAAY');
        insert Acc;
        
        //create account team members 
        AccountTeamMember atm1 = new AccountTeamMember(AccountId=Acc.Id,TeamMemberRole='Imaging System Manager',UserId='005d000000277hpAAA');
        insert atm1;
        
        AccountTeamMember atm2 = new AccountTeamMember(AccountId=Acc.Id,TeamMemberRole='Client Service Manager',UserId='005d000000277hgAAA');
        insert atm2;
        
        AccountTeamMember atm3 = new AccountTeamMember(AccountId=Acc.Id,TeamMemberRole='Receptionist',UserId='005d000000277hhAAA');
        insert atm3;
        
        AccountTeamMember atm4 = new AccountTeamMember(AccountId=Acc.Id,TeamMemberRole='Relationship Manager',UserId='005d000000277haAAA');
        insert atm4;

        
        Test.startTest();
        
        //Inform Test Class to set current page as Page where Extension is used
        Test.setCurrentPage(Page.DisplayAccountTeam);
        
        //Instantiate object of "ApexPages.StandardController" by passing object
        ApexPages.StandardController stdController = new ApexPages.StandardController(Acc);
        ApexPages.currentPage().getParameters().put('id', Acc.Id);
        
        //Create Object of Controller extension by passing object of standardController
        AcctTeamMemberController ext = new AcctTeamMemberController(stdController);
      
//I don't know what to put here to call up the list

        Test.stopTest();

    }
}

 
Hi dev team,

I have created a custom object with questions and corresponding marks detailed in several text and number fields to be displayed in a specific graph. The request is to create a Spider Chart.
Is there a existing Ligtning component for this sort of chart?
Or do you advise anything else?

Thank you.
Best Regards,
Ludivine
I have built a component to override the new action on my Previous_address__c object which is a master detail relationship to the Account object.

When I hit save or cancel, the comonent stays open. I would like it to return to the account record I clicked 'new previous address' on.

Can anyone give me some pointers?

TIA
I am working on cleaning up our Org and we have a ton of inactive workflow rules that need deleting. 
As I launch V.S Code, view a new Terminal session and start working on Dev org/Scartch org and component bundles, I continually receive warnings;
"Java runtime could not be located. Install it and set its location using 'codescan.ls.javaHome' variable in VS Code settings"
I have installed both Jave 8jdk and Java 12jdk in my local PC filing system, noted the mapping e.g
c:Program File (x86)/java/bin/jdk1.8.1_221/bin

Then, within the V.S Code terminal CLI, navigated to;
File>Preferences>Settings>Salesforcedx-vscode-apex>Java: Home
and in the "Edit in Settings.json" file, I mapped the Java 8 runtime location
i.e; 
{
"javascript.updateImportsOnFileMove.enabled": "always"
}
{
"salesforcedx-vscode-apex.java.home": "/Program Files (x86)/Java/jdk1.8.0_221/bin"
}

It then runs ok, but only until I log out of the current V.S Code session, then I get a runtime error again.

What am I missing?
Hi all,
 
we have external objects and a record as test record. When I try to search for any of the values on the used fields, there are no results.
I don't have any experience with global search on external objects. I only have read that for having results you will need a third party tool.
I have configured the Search layout --> Search results on the external objects, enabled search for the objects but no results.
What is your experience? is it possible to find records on external objects using the standard global search?. If yes, how, what should we do in order to get the results in Salesforce the way you can do for internal ones.
How to select/search one object out of 4000+ objects list using apex in visualforce page in salesforce. I already tried with Picklist field but it can have only 1000 values at a time.
I am trying to transfer some fields from accounts to contacts so I can better filter the contacts list. The issue is that this field is a multi-select field type, so I do not know what functions to use. So far my idea has been to do the below when creating a custom field using a formula:

CASE ( INCLUDE (Follow_Up__c, 'abc', 'bcd', 'cde'),
          'abc', 'abc',
          'bcd', 'bcd',
          'cde', 'cde',
          ' ' )
This does not work because the INCLUDE function will not accept multiple string literals. 

What would be the best way to change work with this multi-select picklist field to create a custom field in contacts using it?


 
When I,m following tutorials for creating Lightning Components, some lessons create projects in manifest via the CLI or Ctrl+cmd+P  SFDX: Open Project in Manifest.
What is this and why not just open a normal project?
Hi guys,
We just created a library named R.apex, which helps simplify the common tasks in apex code development by adopting a functional style.
It offers tons of utility functions to work with lists, sets, maps and sobjects, making apex code clean and readable. We were suffering from the pain points of writing similar Apex code to complete trivial tasks once and once again, and that is the reason why we want to stop that and start to write reusable code. Here are some examples of what R.apex can do:
 
// Reverse a list
List<Integer> reversedList = R.of(new List<Integer>{ 1, 2, 3 })
    .reverse()
    .toIntegerList();
 
// Fina specific account
List<Account> accountList = ...;
Account acc = (Account)R.of(accountList)
    .find(R.whereEq.apply(new Map<String, Object>{
        'LastName' => 'Wilson',
        'IsDeleted' => false
    }))
    .toSObject();

Hopefully R.apex can help make your Apex code development easier, and you are always welcome to give feedback so that we can improve it.

R.apex is an open source project hosted at https://github.com/Click-to-Cloud/R.apex/.
You can check it out. Feel free to clone it, make changes or submit a PR.

^_^

When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.  

 

That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it.