-
ChatterFeed
-
529Best Answers
-
4Likes Received
-
60Likes Given
-
15Questions
-
1747Replies
how to convert number to string for a month in visualforce charts?
public with sharing class PieDemoController {
public Campaign camp {get;set;}
public PieDemoController(ApexPages.StandardController std){
camp = (Campaign)std.getRecord();
}
public List<PieWedgeData> getPieData() {
List<PieWedgeData>PieWedgeData = new List<PieWedgeData>();
List<AggregateResult> opps = [SELECT SUM(Amount) monthlyRevenue, COUNT(Name) numOppsClosedWon,
CALENDAR_MONTH(CloseDate) theMonth
FROM Opportunity
WHERE CampaignId =: camp.id
GROUP BY CALENDAR_MONTH(CloseDate)];
for(AggregateResult ar : opps){
String month = String.valueOf(ar.get('theMonth')); //this comes out as a number, not a word value
Integer revenue = Integer.valueOf(ar.get('monthlyRevenue'));
PieWedgeData.add(new PieWedgeData(month, revenue));
}
return PieWedgeData;
}
public class PieWedgeData {
public PieWedgeData(String name, Integer count) {
this.name = name;
this.count = count;
}
public String name { get; set; }
public Integer count { get; set; }
}
}
Thanks in advance
- suji srinivasan
- November 23, 2022
- Like
- 0
- Continue reading or reply
Resolve SOQL inner select field 'Opportunity.Id' cannot have more than one level of relationships
SELECT Id, CloseDate, Name, Owner.Name, Account.Name FROM Opportunity WHERE StageName = 'Closed Won' AND CloseDate = LAST_N_DAYS:30 AND Id NOT IN (SELECT Opportunity.Id FROM OpportunityLineItem WHERE Opportunity.StageName = 'Closed Won' AND Opportunity.CloseDate = LAST_N_DAYS:30 AND Opportunity.CountofProducts__c = 1 AND PricebookEntry.Product2.Name NOT IN ('Product Name 1', 'Product Name 2') )
FYI, I've tried to qualify the sub-select as much as possible to avoid limit errors, and Opportunity.CountofProducts__c is a basic custom Rollup Summary COUNT of Opportunity Products.
I am encountering this error:
MALFORMED_QUERY:
LAST_N_DAYS:30 AND Id NOT IN (SELECT Opportunity.Id FROM OpportunityLineItem
^ (points to the space between SELECT and Opportunity)
ERROR at Row:1:Column:155
The inner select field 'Opportunity.Id' cannot have more than one level of relationships
Any suggestions for how to re-write?
- Randy Miller 35
- May 27, 2022
- Like
- 0
- Continue reading or reply
- Justin Thompson 9
- May 26, 2022
- Like
- 1
- Continue reading or reply
validation rule preventing process builder flow
Deal_Google_Drive_Link__c = Signed_SOW_Link__c
Unfortunately, when trying to save it returns with the following error:
We can't save this record because the “Update Account Status to Customer” process failed. Give your Salesforce admin these details.
This error occurred when the flow tried to update records: FIELD_CUSTOM_VALIDATION_EXCEPTION: The Signed SOW link and the Google Drive link must be different values. You can look up ExceptionCode values in the SOAP API Developer Guide.---
Error ID: 1471332392-127330 (1285127770)
This flow has nothing to do with either of those to fields. Is there another way to prevent my users from entering duplicated URLs?
- Jennifer Cohen 9
- May 17, 2022
- Like
- 0
- Continue reading or reply
Could Anyone Assist Me With Unit Testing This? Thanks.
private final My_Work_Order__c ehs;
public ehsSignatureExtensionController(ApexPages.StandardController controller) {
ehs = (My_Work_Order__c)controller.getRecord();
}
@RemoteAction public static RemoteSaveResult saveSignature(Id ehsId, String signatureBody) {
Attachment a = new Attachment(ParentId=ehsId, name='Signature.png', ContentType='image/png', Body=EncodingUtil.base64Decode(signatureBody));
Database.saveResult result = Database.insert(a,false);
RemoteSaveResult newResult = new RemoteSaveResult();
newResult.success = result.isSuccess();
newResult.attachmentId = a.Id;
newResult.errorMessage = result.isSuccess()?'':result.getErrors()[0].getMessage();
return newResult;
}
public class RemoteSaveResult {
public Boolean success;
public Id attachmentId;
public String errorMessage;
}
public pageReference saveSignature(){
pageReference page = new PageReference('https://cunning-fox-3wdgx9-dev-ed.lightning.force.com/lightning/r/My_Work_Order__c/'+ehs.id +'/view');
page.setRedirect(true);
return page;
}
}
- Edward Foreaker 2
- May 12, 2022
- Like
- 0
- Continue reading or reply
Refreshapex is not working
<template> <div class="slds-p-around_medium lgc-bg"> <lightning-input type="Currency" label="AnnualRevenue Start" value={revenueStart} name="AVStart" onchange={handleChange}></lightning-input> </div> <div class="slds-p-around_medium lgc-bg"> <lightning-input type="Currency" label="AnnualRevenue End" value={revenueEnd} name="AVEnd" onchange={handleChange}> </lightning-input> </div> <div class="slds-p-around_medium lgc-bg"> <template if:true={typeValues.data}> <lightning-combobox name="Type" label="Type" value={value} options={typeValues.data.values} onchange={handleChange}> </lightning-combobox> </template> </div> <div class="slds-p-around_medium lgc-bg"> <template if:true={ratingValues.data}> <lightning-combobox name="Rating" label="Rating" value={value} options={ratingValues.data.values} onchange={handleChange}> </lightning-combobox> </template> </div> <div class="slds-p-around_medium lgc-bg"> <template if:true={industryValues.data}> <lightning-combobox name="Industry" label="Industry" value={value} options={industryValues.data.values} onchange={handleChange}> </lightning-combobox> </template> </div> <lightning-button type="submit" variant="brand" label="Show Accounts" onclick={handleClick}></lightning-button> <template if:true={showSearchComponent}> <lightning-datatable key-field="Id" data={accounts} columns={columns} onsave={handleSave} draft-values={draftValues} hide-checkbox-column="true"></lightning-datatable> </template> <template if:false={accounts}> <p>No data to display</p> </template> <template if:true={loading}> <div class="slds-spinner_container"> <lightning-spinner alternative-text="Loading" variant="brand" size="medium"> </lightning-spinner> </div> </template> </template>
import { LightningElement, wire, track, api } from 'lwc'; import { getPicklistValues } from 'lightning/uiObjectInfoApi'; import Type from '@salesforce/schema/Account.Type'; import Rating from '@salesforce/schema/Account.Rating'; import AnnualRevenue from '@salesforce/schema/Account.AnnualRevenue'; // import ChangeRating__c from '@salesforce/schema/Account.ChangeRating__c'; import { getObjectInfo } from 'lightning/uiObjectInfoApi'; import ACCOUNT_OBJECT from '@salesforce/schema/Account'; import Industry from '@salesforce/schema/Account.Industry'; import getAccountList from '@salesforce/apex/AccountForm.getAccountList'; //import getAccounts from '@salesforce/apex/AccountForm.getAccounts'; import { updateRecord } from 'lightning/uiRecordApi'; import { ShowToastEvent } from 'lightning/platformShowToastEvent'; import { refreshApex } from '@salesforce/apex'; const columns = [ { label: 'Account Name', fieldName: 'AccName', type: 'url', typeAttributes: { label: { fieldName: 'Name' } } }, { label: 'AnnualRevenue', fieldName: 'AnnualRevenue', type: 'currency', editable: true }, { label: 'Industry', fieldName: 'Industry' }, { label: 'Type', fieldName: 'Type', editable: true }, { label: 'Rating', fieldName: 'Rating', type: 'picklist', editable: true }, { label: 'Website', fieldName: 'Website', type: 'url', editable: true }, { label: 'ChangeRating', fieldName: 'ChangeRating__c', type: 'number', editable: true } ]; export default class AccountForm extends LightningElement { @track accounts; @track showSearchComponent = false; @track loading = false; @track revenueStart; @track revenueEnd; @api recordId; columns = columns; draftValues = []; accounts ; error; empty = false; @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT }) accountInfo; nameVal; typeVal; industryVal; @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Type }) typeValues; @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Rating }) ratingValues; @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Industry }) industryValues; handleChange(event) { var fieldname = event.target.label; if (fieldname == 'Rating') { this.nameVal = event.target.value; } else if (fieldname == 'Type') { this.typeVal = event.target.value; } else if (fieldname == 'Industry') { this.industryVal = event.target.value; } else if (fieldname == 'AnnualRevenue Start') { this.revenueStart = event.target.value; } else if (fieldname == 'AnnualRevenue End') { this.revenueEnd = event.target.value; } } handleClick() { // console.log('buttom clicked'); this.showSearchComponent = true; this.loading = true; //console.log('type--> '+this.typeVal+' rating--> '+this.nameVal+' industry--> '+this.industryVal); getAccountList({ type: this.typeVal, rating: this.nameVal, industry: this.industryVal, AnnualRevenueStart: this.revenueStart, AnnualRevenueEnd: this.revenueEnd }) .then(results => { // console.log('account result--> '+JSON.stringify(result)) let tempAccList = []; results.forEach((result) => { let tempAccRec = Object.assign({}, result); tempAccRec.AccName = '/' + tempAccRec.Id; tempAccList.push(tempAccRec); }); this.accounts = tempAccList // this.accounts=result; this.loading = false; }) .catch(error => { console.log('error' + error); this.loading = false; }) } handleSave(event) { const recordInputs = event.detail.draftValues.slice().map(draft => { const fields = Object.assign({}, draft); return { fields }; }); const promises = recordInputs.map(recordInput => updateRecord(recordInput)); Promise.all(promises).then(accounts => { this.dispatchEvent( new ShowToastEvent({ title: 'Success', message: 'Accounts updated', variant: 'success' }) ); // Clear all draft values this.draftValues = []; // Display fresh data in the datatable return refreshApex(this.accounts); }).catch(error => { // Handle error }); } public with sharing class AccountForm { @AuraEnabled public static List<Account> getAccountList(String type,String rating,String industry,Integer AnnualRevenueStart,Integer AnnualRevenueEnd){ String accQuery = 'SELECT Id,Name,Type,Rating,AnnualRevenue FROM Account'; String whereClause = ''; /* if(AnnualRevenueStart>=30000){ whereClause =whereClause +' where AnnualRevenue>=30000'; } if(AnnualRevenueEnd<=100000){ whereClause =whereClause +' AND AnnualRevenue<=100000'; }*/ if(AnnualRevenueStart!=Null){ whereClause=whereClause+' where AnnualRevenue>=:AnnualRevenueStart'; } if(AnnualRevenueEnd!=Null){ if(String.isEmpty(whereClause)){ whereClause=whereClause+' WHERE AnnualRevenue<=:AnnualRevenueEnd'; } else { whereClause=whereClause+' AND AnnualRevenue<=:AnnualRevenueEnd'; } } if(String.isNotEmpty(type)){ if(String.isEmpty(whereClause)){ whereClause =whereClause + ' WHERE Type = :type'; }else{ whereClause =whereClause + ' AND Type = :type'; } } if(String.isNotEmpty(rating)){ if(String.isEmpty(whereClause)){ whereClause =whereClause + ' WHERE Rating = :rating'; }else{ whereClause =whereClause + ' AND Rating = :rating'; } } if(String.isNotEmpty(industry)){ if(String.isEmpty(whereClause)){ whereClause =whereClause + ' WHERE Industry = :industry'; }else{ whereClause =whereClause + ' AND Industry = :industry'; } } String finalquery = accQuery+whereClause; System.debug('finalquery='+finalquery); List<Account> acclist=Database.query(finalquery); return acclist; } }I have build lwc component which show datatable when i give the input in field but when i change field data in row it is also save in datatable but the data is showing after refresh the whole page after saving the field it is not updating in UI Page.....can anyone help me
- jaishri
- May 11, 2022
- Like
- 0
- Continue reading or reply
Converting Process to a Formula field with a syntax error
I am working with cleaning up a lot of legacy things in an org I recently came into. In one case, there is a process that I think will work just as well, if not better, as a regular formula field. However, copying over the formula in it, I am getting a Syntax error. Missing '='
Here is the formula:
IF( OR( ISPICKVAL([Account].CS_Relationship_Health_Score__c, "Red"), ISPICKVAL([Account].CS_Adoption_Health_Score__c , "Red"), ISPICKVAL([Account].CS_Product_Health_Score__c , "Red"), ISPICKVAL([Account].CS_Services_Health_Score__c , "Red"), ISPICKVAL([Account].CS_Support_Health_Score__c , "Red") ) , "Red", IF( OR( ISPICKVAL([Account].CS_Relationship_Health_Score__c, "Yellow"), ISPICKVAL([Account].CS_Adoption_Health_Score__c , "Yellow"), ISPICKVAL([Account].CS_Product_Health_Score__c , "Yellow"), ISPICKVAL([Account].CS_Services_Health_Score__c , "Yellow"), ISPICKVAL([Account].CS_Support_Health_Score__c , "Yellow") ) , "Yellow", "Green" ) )
Can anyone help with clearing up the error?
- N. Weidman
- May 10, 2022
- Like
- 0
- Continue reading or reply
If Email Address dosent exist create a contact and then case
global class inboundEmail implements Messaging.InboundEmailHandler { global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) { Messaging.InboundEmailResult result = new Messaging.InboundEmailresult(); contact con =[SELECT Id,AccountId,Email,FirstName,LastName,Name FROM Contact WHERE email= :email.fromaddress LIMIT 1]; if(con != null){ case cs=new case(); cs.Status='New'; cs.Origin='Phone'; cs.contactid=con.id; cs.subject=email.subject; cs.description=email.plaintextbody; try{ insert cs; result.success=True; }catch(DMLException e){ system.debug('Following error occured'+e); result.success=false; } }else{ /*in place of a print message I would like to create a new contact or a case?*/ System.debug('contact dosent exist'); } return result; } }
- Abdul Subahani BS 8
- May 07, 2022
- Like
- 0
- Continue reading or reply
Hii All ,can anyone help me in increasing the code coverage of this trigger handler test class to 100%?
public with sharing class ChangeOpptyOwnerCtrl {
private string oppId;
public Opportunity oppobj {get;set;}
public boolean isErrInSave {get;set;}
public ChangeOpptyOwnerCtrl(ApexPages.StandardController ctrl){
oppId = ApexPages.currentPage().getParameters().get('oppId');
if(oppId != null)
oppobj = [Select id, Name, OwnerId from Opportunity where id =: oppId limit 1];
}
public void saveOwner(){
isErrInSave = false;
try{
if(oppobj != null)
update oppobj;
}catch(Exception e){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error , e.getMessage()));
isErrInSave = true;
}
}
}
TestClass:
@isTest
public with sharing class ChangeOpptyOwnerCtrlTest {
@testSetup
static void setupTestData(){
Account acc = TestUtility.createAccount('Test A');
insert acc;
Opportunity opp = TestUtility.createOpportunity('@test opp', Date.today(), 'To be Invoiced', acc.id);
opp.Follow_up_Date__c = date.today();
insert opp;
}
testmethod static void saveOwnerTest(){
Opportunity opp = [Select id from Opportunity limit 1];
test.startTest();
Test.setCurrentPageReference(new PageReference('Page.ChangeOpptyOwnerPage'));
System.currentPageReference().getParameters().put('oppId',opp.id);
ApexPages.StandardController sc = new ApexPages.StandardController(opp);
ChangeOpptyOwnerCtrl ctrlObj = new ChangeOpptyOwnerCtrl(sc);
ctrlObj.saveOwner();
test.stopTest();
}
}
can any one help me to cover catch(Exception e) lines
- Rohini Chaudhary 14
- May 06, 2022
- Like
- 1
- Continue reading or reply
LWC Navigate to a New Record Thats Created in Apex
I have a lightning web component that when a button is clicked, an apex method is performed to create a record.
After the record is created within apex, is it possible to get the record id of the new record back into the LWC to be used as part of the NavigationMixin?
Any example would be appreciated.
Thanks
- Andrew Hoban 6
- May 05, 2022
- Like
- 0
- Continue reading or reply
Find Inline edit custom table example
I find Inline edit custom table example. I have find example with datatable https://www.w3web.net/record-save-edit-field-inline-in-lwc/ (https://www.w3web.net/record-save-edit-field-inline-in-lwc/" style="color:#0563c1; text-decoration:underline) and with aura https://sfdcmonkey.com/2017/12/08/lightning-data-table-inline-editing/. I need same but with custom table, not with datatable, not with aura. Please tell me where can I find such an example?
- Mike Tol 1
- May 05, 2022
- Like
- 0
- Continue reading or reply
Cross-Object formula field not populating
Here's the scenario: We have a custom object Project__c. Whenever an Opportunity is set to Closed Won, a record is automatically (via a Flow) created on the Project object. I have created a Lookup relationship field on the Opportunity to the Project__c object called Related Project. My cross-object formula field on the Opportunity is Project Number with a formula of
Related_Project__r.Project_Number__c. The idea is to pull the project number value from the related project record once its entered. It is not populating. My questions are:
- Does a lookup relationship field automatically get populated with the related record when it is created? In this case, does the Related Project field on the Opportunity get populated automatically when the project record is created from the Opp?
- If the Project Number field on the Project__c record is populated at a later time, will this automatically update on the Opportunity in the formula field if the lookup relationship is working?
- Alex Pearson 26
- May 04, 2022
- Like
- 0
- Continue reading or reply
help with this task
[{"lastName" : "Perucci", "firstName" : "John", "title" : "guitarist" },{"lastName" : "LaBrie", "firstName" : "James", "title" : "singer"},{"lastName" : "Mabgini", "firstName" : "Mike", "title" : "drummer"},{"lastName" : "Myung", "firstName" : "John", "title" : "basist"}]
- Mr Woda
- April 23, 2022
- Like
- 0
- Continue reading or reply
Opportunity Trigger not displaying correct value on Parent Account
For that I have written an After Trigger on Opportunity and written below method in trigger Handler class. But my value on the 'Highest_Opportunity_Amount__c' field of that Account is not reflecting the Highest amount.
public static void highestOpportunityinsameAccount(list<Opportunity> lstOpportunity,boolean isInsert,boolean isUpdate, boolean isAfter){
List<Account> lstAccounts = New List<Account>();
set<id> setAccId=new set<id>();
map<id,list<Opportunity>> mapAccIdOpp=new map<id,list<Opportunity>>();
for(Opportunity oppr:lstOpportunity){
setAccId.add(oppr.AccountId);
}
if(setAccId.size()>0){
for (account acc:[SELECT Id,(SELECT ID,Amount FROM Opportunities),Highest_Opportunity_Amount__c FROM Account WHERE Id IN:setAccId]){
mapAccIdOpp.put(acc.id, acc.opportunities);
}}
for(Opportunity NewOppr:lstOpportunity){
decimal amount=0;
if(mapAccIdOpp.containsKey(NewOppr.AccountId)){
for(Opportunity ExistOppr:mapAccIdOpp.get(NewOppr.AccountId)){
amount=amount>ExistOppr.Amount?amount:ExistOppr.Amount;
}
if(NewOppr.Account.Highest_Opportunity_Amount__c!= Null){
NewOppr.Account.Highest_Opportunity_Amount__c=amount;
}
}
}
}
- priyanka mohapatra 10
- April 20, 2022
- Like
- 0
- Continue reading or reply
Apex Trigger and Trigger Helper Class isn't firing
Trigger:
trigger DuplicateMergeTrigger on Lead (after Insert) {
if (Trigger.isInsert){
Set<Id> LeadIds1 = new Set<Id>();
for (Lead myLead : Trigger.New){
if(myLead.Isconverted == FALSE && myLead.College_Corps__c == TRUE && myLead.Status == 'New'){
LeadIds1.add(myLead.Id);
}
if(LeadIds1.size() > 0){
LeadConversionUtils.ConvertLeads(Trigger.new);
}
}
}
}
Helper Class
public class LeadConversionUtils {
public static void ConvertLeads(List<Lead> leadIds){
LeadStatus convertedStatus = [SELECT Id, MasterLabel FROM Leadstatus WHERE IsConverted = TRUE LIMIT 1];
List<Lead> LeadList = new List<Lead>();
LeadList = [SELECT Id, Email FROM Lead WHERE IsConverted = FALSE];
List<String> LeadEmails = new List<String>();
for (Lead VarL : LeadList){
if(VarL.Email != NULL){
LeadEmails.add(VarL.Email);
}
}
List<String> AccountEmails = new List<String>();
List<Id> AccountIds2 = new List<Id>();
for(Account VarA : [SELECT Id, PersonEmail FROM Account WHERE PersonEmail IN :LeadEmails]){
AccountEmails.add(VarA.PersonEmail);
AccountIds2.Add(VarA.Id);
}
if(AccountIds2.size() > 0){
Id AccountId = AccountIds2[0];
for (lead MyLead : leadList){
if(myLead.Email != NULL && !AccountEmails.contains(myLead.Email)){
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(MyLead.Id);
lc.setAccountId(AccountId);
lc.setConvertedStatus(convertedStatus.MasterLabel);
lc.setDoNotCreateOpportunity(TRUE);
}
}
}
}
}
- PhoenixRising12
- April 11, 2022
- Like
- 0
- Continue reading or reply
lightning:recordEditForm display delay
<lightning:recordEditForm aura:id="recordEditForm"
objectApiName="CustomObject__c"
onsubmit="{!c.handleCreate}"
onsuccess="{!c.goToNewRecord}" >
<lightning:inputField fieldName="Name__c" />
<lightning:inputField fieldName="Description__c" />
<lightning:inputField fieldName="Type__c" />
<lightning:inputField fieldName="Related__c" />
<lightning:inputField fieldName="Required__c" />
<lightning:inputField fieldName="Necessary__c" />
<lightning:inputField fieldName="Source__c" />
<lightning:input aura:id="ProjDueDate" name="ProjDueDate" label="Project Due Date" type="date" dateStyle="short" />
<lightning:inputField fieldName="Product_Group__c" />
<lightning:inputField fieldName="Category__c" />
<lightning:inputField fieldName="PLM_Member__c" />
<lightning:inputField fieldName="Sourcing_Member__c" />
<lightning:inputField fieldName="MFG_Member__c" />
<lightning:inputField fieldName="Quality_Member__c" />
<lightning:inputField fieldName="Engineering_Member__c" />
<lightning:inputField fieldName="Sales_Member__c" />
<lightning:inputField fieldName="Application_Member__c" />
<lightning:button class="slds-m-top_small" type="submit" label="Create Project" />
<lightning:button class="slds-m-top_small" variant="neutral" label="Cancel" onclick="{!c.handleCancel}" />
</lightning:recordEditForm>
As you can see, I am using a lightning:input field for the date because the default way lightning:inputField handled my date field was "April 5, 2022" instead of "4/5/2022" and it needed to look consistent with the record page.
After deploying this into a full sandbox for testing, we are noticing a delay in the display. The lightning:input field is displayed first and for a couple of brief seconds its the only field you see, then the remaining of the lightning:inputField fields show up.
Is there a way to keep this delay or handle it more efficiently so that all fields are rendered together?
Or is there a way to control the way the lightning:inputField date is handled to be "mm/dd/yyyy" like the standard record page?
Thanks in advance!
- Rebekah Lilly
- April 05, 2022
- Like
- 0
- Continue reading or reply
lightning component to show users in a card manner
I want to show users like below image. how can i do this in LWC? any suggestions?
- sumit d
- April 05, 2022
- Like
- 1
- Continue reading or reply
Hi guys. Please help me out in writing test class for this HTTP callout code.
@future (callout=true)
public static void makePostCallout(String recId) {
String token;
// System.debug('recorddIdd' + recorddIdd);
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://XXXXXXXXXXXXXXXXXXXX/authenticate');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Set the body as a JSON object
request.setBody('{"email": "XXXXX@XXXX.com","password": "XXXXXX"}');
System.debug('request'+ request);
HttpResponse response = http.send(request);
System.debug('response'+ response);
// Parse the JSON response
if (response.getStatusCode() != 200) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
Map<String, Object> m2 = (Map<String, Object>) results.get('data');
System.debug('results'+ m2.get('jwtToken'));
token = (string)m2.get('jwtToken');
System.debug('token '+ token);
}
makePostCalloutt(recId , token);
}
public static void makePostCalloutt(String recId , String tokenn) {
System.debug('Token >>>'+ tokenn);
String body = recId;
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://XXXXXXXXXXXXXXXX?id='+ body);
request.setMethod('POST');
request.setHeader('Content-Type', 'text');
request.setHeader( 'token', 'Bearer ' + tokenn );
// Set the body as a JSON object
request.setBody(body);
System.debug('request'+ request);
HttpResponse response = http.send(request);
System.debug('response'+ response);
// Parse the JSON response
if (response.getStatusCode() != 200) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}
}
}
- Sandesh Vishwakarma 9
- April 04, 2022
- Like
- 0
- Continue reading or reply
Formula for Multi-level parent relationships
I have an Account formula field called "Finance Parent" that returns the Parent Name if there's no Grandparent or returns the highest level Parent in a hierarchy. This formula does exactly what I want it to do except one thing... if there's NO PARENT, I would like the formula to return the name of the Account itself. Any suggestions are appreciated. Here is the formula:
if (isblank(Parent.Parent.Name),Parent.Name,
(if (isblank(Parent.Parent.Parent.Name),Parent.Parent.Name,
(if (isblank(Parent.Parent.Parent.Parent.Name),Parent.Parent.Parent.Name,Parent.Parent.Name)))))
- Crystal M. Regan
- April 01, 2022
- Like
- 0
- Continue reading or reply
data table records not display.
<template>
<lightning-card title="LWC Related fields">
<template if:true={contactRecord}>
<lightning-datatable record-id={recordId}
data={contactRecord} columns={columns} key-field="Id">
</lightning-datatable>
</template>
</lightning-card>
</template>
/////////////////////////////////////////////////////////////////////////
J.S
import { LightningElement,wire,track,api } from 'lwc';
import getAccountRelatedRecord from '@salesforce/apex/accountController.getAccountRelatedRecord';
export default class DisplayRelatedFieldsOnAccount extends LightningElement {
@api recordId;
@track contactRecord;
@track columns = [
{ label: 'FirstName', fieldName: 'FirstName', type: 'text' },
{ label: 'LastName', fieldName: 'LastName', type: 'text' },
{ label: 'Email', fieldName: 'Email'},
{ label: 'Phone', fieldName: 'Phone', type: 'Phone' }
];
@wire(getAccountRelatedRecord, { recordId: '$recordId'})
wireConRecord({error, data}){
console.log('recordId',this.recordId);
if(data){
this.contactRecord = data;
this.error = undefined;
console.log('recordId',this.contactRecord);
}
else {
this.error = error;
this.contactRecord = undefined;
console.log(error);
}
}
}
////////////////////////////////////////////////////////////////////////////////
WRAPPER CLASS:
public class accountController{
@AuraEnabled(cacheable = true)
public static List<accWrapper> getAccountRelatedRecord(Id recordId){
List<Contact> conlist = new List<Contact>();
List<accWrapper> acclist = new List<accWrapper>();
try{
conlist= [SELECT Id , Lastname,FirstName,Email,Phone FROM Contact WHERE AccountId =: recordId];
system.debug('Showlists>>>>>' + conlist);
List<accWrapper> aclist = new List<accWrapper>();
for (Contact cons : conlist){
accWrapper aw = new accWrapper();
aw.contactRecord = cons;
aclist.add(aw);
}
return aclist;
} catch (Exception e){
throw new AuraHandledException(e.getMessage());
}
}
public class accWrapper{
@AuraEnabled
public Contact contactRecord{get;set;}
}
////////////////////////////////////////////////////////////////////////////////////////////this is my table please help me out of this.
- jishan roy
- March 28, 2022
- Like
- 0
- Continue reading or reply
Emails are not coming from Salesforce developer forum
From last month itself I am not recieving any replies from Salesforce developer forum if i posted answers for someones's questions.
Before a month it's working fine. And also forum page not loading fully only am able to see 10 - 20 Questions. Number of replies and Solved button also not visible in questions.
Any idea how to solve this...
Thanks,
Maharajan.C
- Maharajan C
- September 15, 2020
- Like
- 0
- Continue reading or reply
Add/Remove Records using Lightning Web Components
Add/Remove Records using LWC.
If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post.
Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.
Refer the code in below post...
Like this Post if it's helps to any one !!!
Thanks,
Maharajan.C
- Maharajan C
- April 12, 2020
- Like
- 2
- Continue reading or reply
Hi Experts!!! - i got the error message as myrule_1_A1(Action Call) – We can’t find an action with the name and action type that you specified
It works fine in all orgs but in one org we have the error message like below:
(UpdateAcc-2) myrule_1_A1(Action Call) – We can’t find an action with the name and action type that you specified
The UpdateAcc is the Process builder which call the Apex Class.
In the package also we have these components but we got the Error!!!
Any one please help on this!!!
Thanks,
Raj
- Maharajan C
- January 23, 2018
- Like
- 0
- Continue reading or reply
Salesforce certificates change from Symantec to DigiCert in January and February 2018
Hope some one wil help me:
Salesforce going to update the certificates. Please refer the below Link.
https://help.salesforce.com/articleView?id=000269027&language=en_US&type=1
So Here i have to do the test compatibility in my environment for MiddleWare and Integration:
Can any one please let me know how to perform the below steps:
For Middleware/Integrations
To test the compatibility of an API client that uses SOAP to communicate with Salesforce:
- Set up an API client in a test environment.
- In that test environment, change the API client's login endpoint hostname fromlogin.salesforce.com or [MyDomain].my.salesforce.com tohttps://certtest.force.com.
- As an example, changehttps://login.salesforce.com/services/Soap/u/32.0 to https://certtest.force.com/services/Soap/u/32.0 while leaving the path as-is.
- Log in with that API client.
- If you see an error message that resembles the following: "INVALID_LOGIN: Invalid username, password, security token; or user locked out." or “Content is not allowed in prolog.”, then this test passed and your integration trusts DigiCert-signed certificates.
- The presence of this response means that the underlying TLS connection was successful, despite the higher-level error. The TLS connection is the focus of this test.
- If you instead see an error message that involves TLS or HTTPS, then the test has failed. Your API client will require adjustments to its list of trusted certificate authority certificates to trust DigiCert-signed certificates.
To test the compatibility of an API client that uses REST to communicate with Salesforce:
- Set up an API client in a test environment.
- In that test environment, change the API client's access token retrieval endpoint hostname fromlogin.salesforce.com or [MyDomain].my.salesforce.com to certtest.force.com.
- As an example, changehttps://na1.salesforce.com/services/oauth2/token to https://certtest.force.com/services/oauth2/token while leaving the path as-is.
- Alternatively, it's possible to change the API client's service URL from [instance].salesforce.com or [MyDomain].my.salesforce.com to certtest.force.com.
- As an example, changehttps://na1.salesforce.com/services/data/v32.0/ to https://certtest.force.com/services/data/v32.0 while leaving the path as-is.
- If you see an OAuth error, an "INVALID_SESSION_ID Authorization required" error, or a "400 Bad Request" error, then this test passed.
- The presence of this response means that the underlying TLS connection was successful, despite the higher-level error. The TLS connection is the focus of this test.
- If you instead see an error message that involves TLS or HTTPS, then the test has failed. Your API client will require adjustments to its list of trusted certificate authority certificates to trust DigiCert-signed certificates.
Raj
- Maharajan C
- January 09, 2018
- Like
- 0
- Continue reading or reply
Migrate Chatter Answers to Chatter Questions due to Chatter Answers going to Retire ASAP
Investigated on Q&A Migration App but wanted to know if someone has used this and its outcome. Was there any data impact? If yes, then how can we overcome that?.
What is the alternative? Is data loader an option?
- Maharajan C
- September 25, 2017
- Like
- 0
- Continue reading or reply
Please help me to get a job immediately!!!
Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.
Am ready to join immedialy to any where(Job Location : Any where).
Please some one can help me!!!
i got 50+ best answers in this forum and member from 2015.
Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
- Maharajan C
- August 28, 2017
- Like
- 0
- Continue reading or reply
Please help me to get a job!!!
Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.
Am ready to join immedialy to any where(India or Any Country).
Please some one can help me!!!
i got 50+ best answers in this forum and member from 2015.
Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
- Maharajan C
- August 25, 2017
- Like
- 0
- Continue reading or reply
How to find unused appexchange apps
Can you please help me to find unused apps in my salesforce instance to Metadata Cleanup
Thanks,
Raj
- Maharajan C
- May 02, 2017
- Like
- 0
- Continue reading or reply
Suggestion for APP
Can anyone please give a example third party app name to calculate the Opportunity Stage Duration (inbetween stages also).
Example : Proposal,Qualified,Ready Invoice,Negoatiation,Closed won.
In there i want to calculate the stage duration from Qualified to Closed won.Starting stage must be Qualified End stage Closed won
Qualified to Ready Invoice =?
Ready Invoice to Negoatiation =?
Negoatiation to Closed won =?
And also for Sales vs Quota report third party App.
Thanks,
Raj
- Maharajan C
- September 16, 2016
- Like
- 0
- Continue reading or reply
Test Class help!!
Can you please anyone give a test class for me to the below Apex Class.
Public class AccountDisplatRecClsExtn{
Public id Current_Acc_Id;
public AccountDisplatRecClsExtn(ApexPages.StandardController controller) {
Current_Acc_Id = controller.getRecord().id;
}
public List<Question__c> getcontList(){
List<Question__c> accList = [select id,Name,AssessmentId__c,AssessmentId__r.Name,External_ID__c,Friendly_Name__c,Question_Plain__c,Question_Style__c,Sort_Order__c,(Select Id,Name,Red_Flag__c,Scoring__c from answers__r) from Question__c where AssessmentId__c=:Current_Acc_Id ORDER by Sort_Order__c ASC];
return accList;
}
}
Thanks,
Raj
- Maharajan C
- September 14, 2016
- Like
- 0
- Continue reading or reply
Lead convert create duplicate accounts and contacts same time
In my salesforce org when i convert a lead it creates multiple account,contacts and opportunities at the same time and when i see the created by timings and created by user both are same.
http://docs.releasenotes.salesforce.com/en-us/spring16/release-notes/rn_sales_leads_edit_converted_leads.htm
In above link there is an article i studied about permission set which will enalble us to create multiple account,contacts and opportunities and we can able to view lead again in salesforce detail page but i disabled this options.
Even though i disabled this option i have duplicates created in my salesforce org and i have lead which i can edit on detail page after it converted...I didn't have any trigger.
Please help !!!!!!!!
Thanks,
Raj
- Maharajan C
- July 29, 2016
- Like
- 0
- Continue reading or reply
Lost A Developer Org
Is there any way to retrieve my SF Dev Org Because i lost my Org Due to the Authenticator App in my Mobile i.e, am uninstalled the Authenticator App in my Phone which have a link with my Dev Org.
Thanks,
Raj.
- Maharajan C
- February 18, 2016
- Like
- 1
- Continue reading or reply
Stop Resending an Email in Workflow.
Please Help!!!
Evaluation Criteria : Evaluate the rule when a record is created, and any time it's edited to subsequently meet criteria
Rule Criteria Opportunity : StageEQUALSClosed Won
Workflow Action : Email Alert
>Here First my record meet the above rule criteria based on the evaluation criteria it sends an an Email i.e Opportunity stage equals Closed Won
>After that in that same record i change the Opportunity stage to Need Analysis so now the record dont met the criteria so there is a no Email
>Then i changed that Opportunity record stage to Closed Won now the record meet the criteria so its send an email again but i want to stop the Sending an Email Now.
Thanks in Advance!!!
Raj.
- Maharajan C
- February 16, 2016
- Like
- 0
- Continue reading or reply
Test Code Coverage
Any One please help me to code coverge because i got only 43% coverage
ApexTrigger :-
trigger sendNotificationTrigger on CampaignMember (after insert) {
Set<Id> LeadIds = new Set<ID>();
Lead_Campaign__c tm;//Assinging Custom setting To the variable tm
tm=Lead_Campaign__c.getorgdefaults();
String Template=tm.Email_Template_ID__c;
Decimal Days=tm.Threshold_Days__c;
list <CampaignMember> theCampaignMembers = new list<CampaignMember>();
for(CampaignMember campMem : Trigger.new){//
if(test.isRunningTest()){
Days = 0;
}
if(campMem.leadid != null){
LeadIds.add(campMem.leadid);
theCampaignMembers.add(campMem);
}
// List containing Campaign Member records to be inserted
List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();
for(Lead ld : [select id, Status,Lead_age__c, owner.email from Lead where id IN : LeadIds])
try
{
if(ld.Status!='Qualified'&&ld.Lead_age__c>=Days)
//Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
List<String> sendTo = new List<String>();
sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
mail.setToAddresses(sendTo);
mail.saveAsActivity = false;
mail.setTemplateId(Template);//Using custom setting field template as template id
mail.setTargetObjectId(ld.OwnerId);
mail.setWhatId(ld.id);
mails.add(mail);
Messaging.sendEmail(mails);
}
}
catch (Exception e)
{
ApexPages.addMessages(e);
Profile adminProfile = [Select id From Profile Where Name='System Administrator' Limit 1];
Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
List<String> toAddresses = new List<String>();
toAddresses.add(adminProfile.id);
mail.setToAddresses(toAddresses);
mail.setSenderDisplayName('Apex error message');
mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
mail.setPlainTextBody(e.getMessage());
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}
Test Class -:
@isTest(SeeAllData = true)
public class sendNotificationTrigger
{
static testMethod void sendNotificationTrigger ()
{
Test.startTest(); //Creates Contact to be linked to Campaign Member
Campaign cp = [SELECT Id FROM Campaign LIMIT 1];
//Creates a new campaign memeber, associaites it with 1 campaign
Lead t1 = new Lead(Company= 'TestLead', LastName= 'TestL', Email = 'none@test.com',Status = 'Open' );
insert t1;
CampaignMember newMember = new CampaignMember (LeadId = t1.id, status='Sent', campaignid = cp.id);
insert newMember;
system.assertequals(t1.status,'Open') ;
Test.stopTest();
}
}
Thanks,
Raj.
- Maharajan C
- January 21, 2016
- Like
- 0
- Continue reading or reply
Test Class to Code Coverage
Can any one Please help to write a test class to my Trigger
trigger sendNotificationTrigger on CampaignMember (after insert) {
Set<Id> LeadIds = new Set<ID>();
Test_Setting__c tm;//Assinging Custom setting To the variable tm
tm=Test_Setting__c.getorgdefaults();
String Template=tm.Template__c;
Decimal Days=tm.Threshold_Days__c;
for(CampaignMember campMem : Trigger.new){//
if(campMem.leadid != null){
LeadIds.add(campMem.leadid);
}
List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();
for(Lead ld : [select id, Lead_age__c, Status, owner.email from Lead where id IN : LeadIds])
if(ld.Status!='Qualified'&&ld.Lead_Age_In_days__c>=Days)
//Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
List<String> sendTo = new List<String>();
sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
mail.setToAddresses(sendTo);
mail.saveAsActivity = false;
mail.setTemplateId(Template);//Using custom setting field template as template id
mail.setTargetObjectId(ld.Ownerid);
mails.add(mail);
Messaging.sendEmail(mails);
}
}
}
Thanks
Raj.
- Maharajan C
- January 18, 2016
- Like
- 0
- Continue reading or reply
Add/Remove Records using Lightning Web Components
Add/Remove Records using LWC.
If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post.
Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.
Refer the code in below post...
Like this Post if it's helps to any one !!!
Thanks,
Maharajan.C
- Maharajan C
- April 12, 2020
- Like
- 2
- Continue reading or reply
Lost A Developer Org
Is there any way to retrieve my SF Dev Org Because i lost my Org Due to the Authenticator App in my Mobile i.e, am uninstalled the Authenticator App in my Phone which have a link with my Dev Org.
Thanks,
Raj.
- Maharajan C
- February 18, 2016
- Like
- 1
- Continue reading or reply
I need to show 'no records available' as a table results if I didn't receive any record
- prabhu mohan
- November 25, 2022
- Like
- 0
- Continue reading or reply
Bulkification issue on Contact object
**Issue : For Bulk Operations I am getting an error ‘First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ContactTrigger: execution of AfterInsert’**
• Contact Object Has A Custom Field (checkbox) called “Active”.
• Account Object Has A Custom Field (number) called “Active Contacts”.
**Code Written:**
public class ContactTriggerHandler {
public static void countOfActiveContacts(List<Contact> lstContact){
Set<Id> setAccId=new Set<Id>();
List<Account> lstAccount=new List<Account>();
If(lstContact!=null){
For(Contact cont:lstContact){
setAccId.add(cont.AccountId);
}}
If(setAccId!=null){
For(Account acc:[SELECT Id,Active_Contacts__c,(SELECT AccountId,Id,Active__c FROM Contacts WHERE Active__c =True) FROM Account WHERE Id IN:setAccId]){
acc.Active_Contacts__c=acc.Contacts.size();
lstAccount.add(acc);
}
}
Update lstAccount;
}
}
**My Test Calss Code:**
@isTest
private class ContactTriggerHandlerTest {
@isTest static void countOfActiveContactsBulk() {
Account acct = new Account(Name='Test Account');
insert acct;
List<Contact> lstCont= New List<Contact>();
for(Integer i=0;i<200;i++)
{
Contact cont= new Contact(LastName='cont'+i,
AccountId=acct.Id,
Active__c=True);
lstCont.add(cont)
}
test.startTest();
insert lstCont;
update acct;
test.stopTest();
system.assertEquals(acct.Active_Contacts__c,200);
}
- priyanka mohapatra
- November 23, 2022
- Like
- 0
- Continue reading or reply
how to convert number to string for a month in visualforce charts?
public with sharing class PieDemoController {
public Campaign camp {get;set;}
public PieDemoController(ApexPages.StandardController std){
camp = (Campaign)std.getRecord();
}
public List<PieWedgeData> getPieData() {
List<PieWedgeData>PieWedgeData = new List<PieWedgeData>();
List<AggregateResult> opps = [SELECT SUM(Amount) monthlyRevenue, COUNT(Name) numOppsClosedWon,
CALENDAR_MONTH(CloseDate) theMonth
FROM Opportunity
WHERE CampaignId =: camp.id
GROUP BY CALENDAR_MONTH(CloseDate)];
for(AggregateResult ar : opps){
String month = String.valueOf(ar.get('theMonth')); //this comes out as a number, not a word value
Integer revenue = Integer.valueOf(ar.get('monthlyRevenue'));
PieWedgeData.add(new PieWedgeData(month, revenue));
}
return PieWedgeData;
}
public class PieWedgeData {
public PieWedgeData(String name, Integer count) {
this.name = name;
this.count = count;
}
public String name { get; set; }
public Integer count { get; set; }
}
}
Thanks in advance
- suji srinivasan
- November 23, 2022
- Like
- 0
- Continue reading or reply
Illegal assignment from List<SObject> to List<ProcessInstance>
Illegal assignment from List<SObject> to List<ProcessInstance> (46:31)
public with sharing class ProcessInstance { @AuraEnabled(cacheable=true) public static List<ProcessInstance> getCases( String relatedTo, String submittedDate, String submittedBy ) { String query; String condition = (String.isNotBlank(relatedTo) ? 'TargetObject.name LIKE \'' + '%' + relatedTo + '%\'' : ''); condition += (String.isNotBlank(submittedDate) ? (String.isNotBlank(condition) ? +' AND ' : '') + ' LastModifiedDate LIKE \'' + '%' + submittedDate + '%\'' : ''); condition += (String.isNotBlank(submittedBy) ? (String.isNotBlank(condition) ? +' AND ' : '') + ' SubmittedBy.name LIKE \'' + '%' + submittedBy + '%\'' : ''); System.debug('condition ' + condition); if (String.isNotBlank(condition)) { query = 'SELECT TargetObject.name,LastModifiedDate,SubmittedBy.name FROM ProcessInstance WHERE ' + condition + ' ORDER BY LastModifiedDate'; } else { query = 'SELECT TargetObject.name,LastModifiedDate,SubmittedBy.name FROM ProcessInstance ORDER BY LastModifiedDate LIMIT 200'; } List<ProcessInstance> records = Database.query(query); return records; } }
- Atiqah
- November 23, 2022
- Like
- 0
- Continue reading or reply
Condition Formula For Validation rule
Hello!
I'm having trouble creating this formula for a validation rule. This is what I'm trying to accomplish, If the Engagement plan template's default assignee is blank, then I would like for the contact's "pathway coach" to be assigned. No errors were found, but the engagement plan tasks are assigned to me (the contact owner) despite the default assignee being blank
AND(ISPICKVAL( npsp__Engagement_Plan_Template__r.npsp__Default_Assignee__c ,
"--None--"),
ISNULL( npsp__Assigned_To__r.Contact.Pathway_Coach__c ))
- Nadia Tabbara
- September 21, 2022
- Like
- 0
- Continue reading or reply
Is it possible to write a single trigger on Multiple Objects
I have one custom profile (Test User) and one Custom Object.
This profile having delete access on Opportunity,Contact and this Custom Object.
Now I want to write a trigger to restrict user with ""Test User"" profile from deleting above mentioned 3 object records.
Or a sinlge apex class that will work on these 3 objects.
Thank you in advance
- ipl bcci
- September 21, 2022
- Like
- 0
- Continue reading or reply
Populate "primary contact" on opportunity at lead conversion using before trigger ?
Primary_Contact is Custom field
----------------------------------------------------------------------------------------------
Please Do it in Flows
- Saurabh Bisht 23
- September 21, 2022
- Like
- 0
- Continue reading or reply
Create a RestFul WebService, to Fetch all the Opportunities based on the Specified Account Name? below code is correct? i
global class OpportunityRecord
{
@HttpGet()
global static list<Opportunity> GetOpportunityRelated ()
{
Map<string, string> inputParams = RestContext.request.Params;
list<Opportunity> lstOpportunity = [select id,name, amount, stagename, closedate, accountId, Account.Name
from Opportunity where Account.Name =: inputParams.Get('accName')];
return lstOpportunity;
}
- Raja Narendra 5
- June 23, 2022
- Like
- 0
- Continue reading or reply
Convert a STRING Select statement output to JSON format APEX class
Can anyone please help me convert the below to JSON:
@AuraEnabled
public static List<Energy_Plan__c> getRatePlans(
String brand,
String priceBook,
String commodity,
String utility,
Boolean showPoints
) {
System.debug('Inside getRatePlans');
List<Energy_Plan__c> String query =
'SELECT Id, Name, TermInMonths__c, REP_Per_Usage_Charge1__c, MonthlyFee__c, jurisdiction__c, ProductName__c, ' +
'EFL_ENGLISH_LINK__c, EFL_SPANISH_LINK__c, PenaltyAmount__c, PlanType__c, Price_Units__c, Rateplan_Points__c, ' +
'Monthly_Fee_Total__c, ReportGroupID__c, Commodity__c, Brand__c, EnergyProvide__c,Active__c, UtilityName__c, Total_Fee__c, REPKey1__c, ExternalId__c, ' +
'TOSLINKSTATIC_English__c, TOSLINKSTATIC_Spanish__c,External_Plan_Key__c ' +
'FROM Energy_Plan__c ' +
'WHERE ' +
'Active__c = true ' +
'AND IsCustomPriced__c = False ' +
'AND Brand__c = :brand ' +
'AND RateName__c = :priceBook ' +
'AND Commodity__c = :commodity ' +
'AND UtilityName__c = :utility ';
if (showPoints) {
query += 'ORDER BY Rateplan_Points__c DESC';
} else {
query += 'ORDER BY Name';
}
System.debug('getRatePlans >> ' + Database.query(query));
return Database.query(query);
- PhilM
- June 23, 2022
- Like
- 0
- Continue reading or reply
Change color of lightning:input label
I have an aura component that is sitting on a grey background, so I need the field labels of my lightning:input boxes to have white text. But the text boxes themselves are white, so I need the text entry within the boxes to stay default black. No, I cannot change the background on this page due to branding, etc.
Every solution I've tried so far has changed the text entry in the boxes to white while leaving the labels black, which is the exact opposite of what I need. Any ideas? Thank you!
- Sarah Maze 18
- May 27, 2022
- Like
- 0
- Continue reading or reply
Resolve SOQL inner select field 'Opportunity.Id' cannot have more than one level of relationships
SELECT Id, CloseDate, Name, Owner.Name, Account.Name FROM Opportunity WHERE StageName = 'Closed Won' AND CloseDate = LAST_N_DAYS:30 AND Id NOT IN (SELECT Opportunity.Id FROM OpportunityLineItem WHERE Opportunity.StageName = 'Closed Won' AND Opportunity.CloseDate = LAST_N_DAYS:30 AND Opportunity.CountofProducts__c = 1 AND PricebookEntry.Product2.Name NOT IN ('Product Name 1', 'Product Name 2') )
FYI, I've tried to qualify the sub-select as much as possible to avoid limit errors, and Opportunity.CountofProducts__c is a basic custom Rollup Summary COUNT of Opportunity Products.
I am encountering this error:
MALFORMED_QUERY:
LAST_N_DAYS:30 AND Id NOT IN (SELECT Opportunity.Id FROM OpportunityLineItem
^ (points to the space between SELECT and Opportunity)
ERROR at Row:1:Column:155
The inner select field 'Opportunity.Id' cannot have more than one level of relationships
Any suggestions for how to re-write?
- Randy Miller 35
- May 27, 2022
- Like
- 0
- Continue reading or reply
CASE Debug
We have various Process Builder, Workflow rules and Flow.
We are unable to check how a specific CASE is created and certain fields are updated automitally.
What and which way we can find out how this CASE was generated?
Any help would be great.
Thank you
- Peanut Jame
- May 27, 2022
- Like
- 0
- Continue reading or reply
round robin leads
- Justin Thompson 9
- May 27, 2022
- Like
- 0
- Continue reading or reply
HELP PLEASE! Apex and Validate
Hi!
I need to add gift cards to an opportunity if the checkbox is enabled, otherwise it will throw an error. In this case, the entered card is deactivated. In the future, I don't have the ability to change any of the opportunity field as the validation fires. How can I solve this problem?
public class OpportunityTriggerHandler {
public void afterInsert (List<Opportunity> newOpportunities){
List<String> cardNames = new List<String>();
for(Opportunity oppItem : newOpportunities) {
cardNames.add(oppItem.Gift_Card__c);
}
List<Gift_Card__c> giftCardToUpdate = [SELECT Active__c, Amount__c, Name
FROM Gift_Card__c
WHERE Name IN :cardNames];
for(Gift_Card__c giftCard: giftCardToUpdate ) {
giftCard.Active__c = false;
}
update giftCardToUpdate;
}
public void beforeInsert (List<Opportunity> newOpportunities){
List<String> cardNames = new List<String>();
for(Opportunity oppItem : newOpportunities) {
cardNames.add(oppItem.Gift_Card__c);
}
List<Gift_Card__c> allGiftCards = [SELECT Active__c, Amount__c, Name
FROM Gift_Card__c
WHERE Name IN :cardNames];
for (Opportunity newOpp: newOpportunities) {
for(Gift_Card__c giftCard: allGiftCards ) {
if (giftCard.Active__c == true) {
newOpp.Amount -= giftCard.Amount__c;
} else {
newOpp.Gift_Card__c.addError('Gift Card is inactive');
}
}
}
}
}
- Anastasiya Komar 8
- May 26, 2022
- Like
- 0
- Continue reading or reply
- Justin Thompson 9
- May 26, 2022
- Like
- 1
- Continue reading or reply
- Justin Thompson 9
- May 26, 2022
- Like
- 1
- Continue reading or reply
Hii All ,can anyone help me in increasing the code coverage of this trigger handler test class to 100%?
public with sharing class ChangeOpptyOwnerCtrl {
private string oppId;
public Opportunity oppobj {get;set;}
public boolean isErrInSave {get;set;}
public ChangeOpptyOwnerCtrl(ApexPages.StandardController ctrl){
oppId = ApexPages.currentPage().getParameters().get('oppId');
if(oppId != null)
oppobj = [Select id, Name, OwnerId from Opportunity where id =: oppId limit 1];
}
public void saveOwner(){
isErrInSave = false;
try{
if(oppobj != null)
update oppobj;
}catch(Exception e){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error , e.getMessage()));
isErrInSave = true;
}
}
}
TestClass:
@isTest
public with sharing class ChangeOpptyOwnerCtrlTest {
@testSetup
static void setupTestData(){
Account acc = TestUtility.createAccount('Test A');
insert acc;
Opportunity opp = TestUtility.createOpportunity('@test opp', Date.today(), 'To be Invoiced', acc.id);
opp.Follow_up_Date__c = date.today();
insert opp;
}
testmethod static void saveOwnerTest(){
Opportunity opp = [Select id from Opportunity limit 1];
test.startTest();
Test.setCurrentPageReference(new PageReference('Page.ChangeOpptyOwnerPage'));
System.currentPageReference().getParameters().put('oppId',opp.id);
ApexPages.StandardController sc = new ApexPages.StandardController(opp);
ChangeOpptyOwnerCtrl ctrlObj = new ChangeOpptyOwnerCtrl(sc);
ctrlObj.saveOwner();
test.stopTest();
}
}
can any one help me to cover catch(Exception e) lines
- Rohini Chaudhary 14
- May 06, 2022
- Like
- 1
- Continue reading or reply
Creating formula with Date/Time output through combining a Date and Time field in SF
I want to create a formula to use within a flow that outputs a DATETIME value using seperate inputs from a Date field and Time field.
I have tried various different formulas, but have yet to get it working. For reference, I have been playing around with formulas such as:
DATETIMEVALUE ( TEXT ( DATEFIELD__c) & " " & (TIMEFIELD__c))
However, none have worked thus far. Appreciate any insight or guidance on this one.
Thank you,
R
- R Reay
- April 27, 2022
- Like
- 1
- Continue reading or reply
I'm getting this error message when trying to update a Metadata. Can you help me?
MetadataServiceExamples.MetadataServiceExamplesException: Error occured processing component ***.***@***.***.com. In field: fullName - no Profile named ***.***@***.***.com found (INVALID_CROSS_REFERENCE_KEY).
Below is the code for the method that is causing the problem. I have no idea what could be wrong:
public static void updateFLS(String fieldName, Boolean securityLevel) { MetadataService.MetadataPort portService = MetadataServiceExamples.createService(); MetadataService.Profile profileName = new MetadataService.Profile(); system.debug(profileName.fullName); profileName.fullName = UserInfo.getUserName(); system.debug(profileName.fullName); profileName.custom = securityLevel; MetadataService.ProfileFieldLevelSecurity fieldSecurity = new MetadataService.ProfileFieldLevelSecurity(); fieldSecurity.field = fieldName; fieldSecurity.editable = true; profileName.fieldPermissions = new MetadataService.ProfileFieldLevelSecurity[] {fieldSecurity}; List <MetadataService.SaveResult> results = portService.updateMetadata( new MetadataService.Metadata[] {profileName} ); MetadataServiceExamples.handleSaveResults(results[0]); }
I am using this API:
https://github.com/financialforcedev/apex-mdapi
- Ian Vianna 2
- April 06, 2022
- Like
- 1
- Continue reading or reply
lightning component to show users in a card manner
I want to show users like below image. how can i do this in LWC? any suggestions?
- sumit d
- April 05, 2022
- Like
- 1
- Continue reading or reply
Confused Why Test Methods Failed
trigger CanceledProgram on Program__c (before update) { Program__c pNew = Trigger.new[0]; Program__c pOld = Trigger.oldMap.get(pNew.id); if(pNew.Canceled__c != pOld.Canceled__c && pNew.Canceled__c == true){ System.debug('Updated to True'); System.debug('New value = ' + pNew.Canceled__c); System.debug('Old value = ' + pOld.Canceled__c); if(pOld.Name.length() <= 70){ pNew.Name = 'CANCELED: ' + pNew.Name; System.debug('New name length: '+pNew.Name.length()); System.debug('Old name length: '+pOld.Name.length()); System.debug(pNew.Name); } else if (pOld.Name.length() > 70){ String pNameShort = pNew.Name.substring(0, 65) + '...'; pNew.Name = 'CANCELED: ' + pNameShort; System.debug(pNew.Name); System.debug(pNew.Name.length()); } } else if (pNew.Canceled__c != pOld.Canceled__c && pNew.Canceled__c == false) { System.debug('Updated to False'); System.debug('New value = ' + pNew.Canceled__c); System.debug('Old value = ' + pOld.Canceled__c); if(pNew.Name.startsWith('CANCELED: ')){ pNew.Name = pNew.Name.substring(10); } } else { System.debug('The Canceled Field was not changed'); } if (pNew.Name != pOld.Name && pOld.Name.length() >70){ System.debug(pOld.Name.length()); System.debug(pNew.Name.length()); } }
And see below for the test class. It says I have 100% coverage, but that the 3/4 tests failed. I assume they need to succeed in order to push this class to production. I don't understand why they didn't pass though? In the first test method, I did a little testing, trial, and error with using System.debug to double check the values, and the test should be passing. Can anyone tell me what I'm doing wrong? Thanks for any help you can provide!
@isTest private class CanceledProgramTest { @isTest static void TestCanceledProgramWithShortName() { Program__c p1 = new Program__c(Name='Will not happen'); insert p1; p1 = [SELECT Id, Name, Canceled__c FROM Program__c WHERE Id = :p1.Id]; System.debug(p1); Test.startTest(); p1.Canceled__c = true; update p1; System.assertEquals('CANCELED: Will not happen', p1.Name); Test.stopTest(); } @isTest static void TestCanceledProgramWithLongName() { Program__c p = new Program__c(Name='This program will not happen. I am sorry, but this program just will not happen.'); insert p; p.Canceled__c = true; update p; System.assertEquals('CANCELED: This program will not happen. I am sorry, but this program just w...', p.Name); } @isTest static void TestUnCanceledProgramChangeName() { Program__c p = new Program__c(Name='CANCELED: We will have it after all. Name changes.', Canceled__c = true); insert p; p.Canceled__c = false; update p; System.assertEquals('We will have it after all. Name changes.', p.Name); } @isTest static void TestUnCanceledProgramSameName() { Program__c p = new Program__c(Name='We will have it after all. Name is same.' , Canceled__c = true); insert p; p.Canceled__c = false; update p; System.assertEquals('We will have it after all. Name is same.', p.Name); } }
- Desiree Dixon
- March 10, 2022
- Like
- 1
- Continue reading or reply
How to use id from Record Contact?
everything works fine but now Im trying to save the PDF to the correspondet contact depending on the ID, any idea of how I can do that? this is my code as we can see Im hard coding the id
public with sharing class DisplayRichTextHelper {
@AuraEnabled
public static Attachment generatePDF(String txtValue){
Pagereference pg = Page.renderAsPDF;
pg.getParameters().put('displayText', txtValue);
Contact con = new Contact(Id='0035f000008RNWCAA4');
Attachment objAttachment = new Attachment();
objAttachment.Name = 'J2S.pdf';
objAttachment.ParentId = con.Id;
objAttachment.Body = pg.getContentaspdf();
objAttachment.IsPrivate = false;
insert objAttachment;
return objAttachment;
}
}
And i want to change for some like this:
ApexPages.currentPage().getParameters().get('id');
- Oscar Fernando De la Cruz
- December 28, 2022
- Like
- 1
- Continue reading or reply
Why don’t account and contact fields match up? Should they?
Thanks.
- afar
- December 28, 2022
- Like
- 1
- Continue reading or reply
how can I complete my test class? (68% covered)I'm trying the part of wrapper class
public with sharing class controllerquoteVisual { public String title {get;set;} public Quote quote {get;set;} public List<quoteLineItem> qliList {get;set;} //public List<Product2> products {get; set;} //Capturar Nombre de familia y lista de productos public Map<String,List<ObjectWrapper>> mapFamily {get;set;} //public Map<String,List<QuoteLineItem>> mapFamilyqli {get;set;} //Captutar Nombre de familia y recuento de Productos que se mostrarán public Map<String, Integer> FamilyCountMap{get;set;} //Capturar Lista de nombres de familia de productos public List<String> FamilyList {get;set;} //ProductList o products ya con los productos que se requieren mostrar public controllerquoteVisual(){ Id id = ApexPages.currentPage().getParameters().get('id'); //Obtener quote mediante el Id que arroja la visualforce desde quote quote = [SELECT Id, Name, TotalPrice, GrandTotal, ExpirationDate, AccountId, Total_Hours__c, OpportunityId, QuoteNumber FROM quote WHERE Id=:id LIMIT 1]; Opportunity opportunity = [SELECT Name FROM Opportunity WHERE Id=:quote.OpportunityId LIMIT 1]; title = opportunity.Name.split('\\|')[0] + opportunity.Name.split('\\|')[1]; Apexpages.currentPage().getHeaders().put('content-disposition', 'inline; filename='+title+ ' - ' +quote.QuoteNumber ); //Obtener lista de quoteLineItems de la actual quote qliList = [SELECT Id, Product2Id, Quantity FROM quoteLineItem WHERE quoteId=:Id]; /////////////////////////////////////////////// //Separar productos por tipo de familia mapFamily = new Map<String, List<ObjectWrapper>>(); FamilyCountMap = new Map<String, Integer>(); FamilyList = new List<String>(); List<quoteLineItem> finalqliList = new List<QuoteLineItem>(); finalqliList = qliList; //Agrupar por nombre de familia y preparar los map for(QuoteLineItem qq: finalqliList){ Product2 famObj = [SELECT Id, Name, Family, Description FROM Product2 WHERE Id=:qq.Product2Id]; if(famObj.Family == null){ famObj.Family= 'Sin clasificación'; } //List<QuoteLineItem> qq = qliList; List<ObjectWrapper> proList = new List<ObjectWrapper>(); //Verificar si el map ya contiene el mismo nombre por familia if(mapFamily.containsKey(famObj.Family)){ //Recuperar lista de productos existentes proList = mapFamily.get(famObj.Family); //Meter el nuevo producto a la lista proList.add(new ObjectWrapper(qq, famObj)); mapFamily.put(famObj.Family, proList); //Almacenar filas por nombre de familia FamilyCountMap.put(famObj.Family, proList.size()); } else{ //crear nuevo map del nombre de familia //.fammily,name,etc //proList.add(famObj); proList.add(new ObjectWrapper(qq, famObj)); mapFamily.put(famObj.Family, proList); //Almacenar filas por nombre de familia FamilyCountMap.put(famObj.Family, proList.size()); } FamilyList = new List<String>(mapFamily.keySet()); } } public class ObjectWrapper{ //Campos QuoteLineItems //Public Id QliId{get;set;} Public Decimal Quantity{get;set;} //Campos Producto Public String Name{get;set;} Public String Family{get;set;} Public String Description{get;set;} public ObjectWrapper(QuoteLineItem ql, Product2 pr){ //this.QliId = ql.Id; this.Quantity = ql.Quantity; this.Name = pr.Name; this.Family = pr.Family; this.Description = pr.Description; } } }
Test Class (68%, wrapper class is missing)
@isTest public class TestControllerquoteVisual{ @isTest static void testControllerVFP(){ Pricebook2 pb = new Pricebook2(Name = 'Standard Price Book', Description = 'Price Book Products', IsActive = true ); insert pb; Product2 prod = new Product2(Name = 'Test Product', Description = 'Descripción Test', Family = 'Salesforce Service Cloud', IsActive = true); insert prod; List<Pricebook2> standardPbList = [select id, name, isActive from Pricebook2 where IsStandard = true ]; List<PricebookEntry> listPriceBook = new List<PricebookEntry>(); for(Pricebook2 p : standardPbList ){ PricebookEntry pbe = New PricebookEntry (); pbe = new PricebookEntry(Pricebook2Id = p.Id, Product2Id = prod.Id, UnitPrice = 10000, IsActive = true, UseStandardPrice = false); listPriceBook.add(pbe); } insert listPriceBook; Opportunity opp = new Opportunity(Name = 'Test Opportunity', StageName = 'Discovery', Product_Families__c='Salesforce Service Cloud' ,CloseDate = system.today()); insert opp; Quote quttest = new Quote (Name = 'Quote Test' , OpportunityId = opp.id , Pricebook2Id = pb.id ); insert quttest; List<QuoteLineItem> listval = new List<QuoteLineItem>(); for(PricebookEntry pricebook : listPriceBook){ QuoteLineItem qutlineitemtest = new QuoteLineItem (); qutlineitemtest = new QuoteLineItem(QuoteId = quttest.id, Quantity = 3.00,UnitPrice = 12, PricebookEntryId = pricebook.id); listval.add(qutlineitemtest); } insert listval; QuoteLineItem qlitem = new QuoteLineItem(Quantity = 3.00, UnitPrice = 12 ); Test.startTest(); ApexPages.currentPage().getParameters().put('id', String.valueOf(quttest.Id)); controllerquoteVisual controllerVfp= new controllerquoteVisual(); //controllerVfp = new controllerquoteVisual(); controllerquoteVisual.ObjectWrapper wrapper = new controllerquoteVisual.ObjectWrapper(qlitem, prod); wrapper.Quantity = 3.00; wrapper.Name = prod.Name; wrapper.Description = prod.Description; wrapper.Family = prod.Family; Test.stopTest(); } }
- alxhdez
- December 28, 2022
- Like
- 1
- Continue reading or reply
Apex Code coverage fpr this Class
//@RestResource(urlMapping='/Google/*') is used to tell the class that it is a REST resource used for POST GET etc @RestResource(urlMapping='/Google/*') global with sharing class GoogleWebHookListener { //HttpPost tells the method that it will be a POST method @HttpPost global static void handlePost() { //set up varibles for the Lead String name; String phone; String email; String postCode; String firstName; String lastName; //try to do the JSON deserialization and Lead Creation //******EXAMPLE JSON AT BOTTOM***** try { // This gets the body of the webhook makes the body a string and sets the string to the variable 'jsonString' String jsonString = RestContext.request.requestBody.toString(); //This deserializes the JSON based on the the properties setup in the Class GoogleJsonLeadExample GoogleJsonLeadExample g = (GoogleJsonLeadExample)JSON.deserialize(jsonString, GoogleJsonLeadExample.class); //This tests the JSON to see if it is legit. if(g.google_key == ''){ //This loops through the JSON array set up in the Class GoogleJsonLeadExample for(GoogleJsonLeadExample.userData d : g.user_column_data) { if(d.column_name == 'Full Name') { //The JSON has Full Name, this breaks Full Name into First and Last Names name = d.string_value; List<String> names = name.split(' '); firstName = names[0]; lastName = names[1]; } if(d.column_name == 'User Phone') { phone = d.string_value; } if(d.column_name == 'User Email') { email = d.string_value; } if(d.column_name == 'Postal Code') { postCode = d.string_value; } } //This creates the Lead Lead detail = new Lead(); detail.LastName = lastName; detail.FirstName = firstName; detail.Phone = phone; detail.Company = name; detail.Email = email; detail.OwnerId = '0051Q00000GrANL'; // This Id is the user Hubspot. insert detail; } } catch (DMLException e) { System.debug('The following exception has occurred: ' + e.getMessage()); } } }
- Alex Calder 10
- December 22, 2021
- Like
- 1
- Continue reading or reply
Restricting Close Date to Last Day of the Month When Not Closed Won/Lost
I've been asked to restrict the valid Close Dates for Opporunities to the last day of the month when the Stage is not Closed Won/Lost.
I've found a fromula that does a great job restricting the dates in general, but I can't figure out how to add the additional condition that it should only apply the date limitation when the Opportunity is in certain stages.
IF(
MONTH( CloseDate ) = 12,
DATE( YEAR( CloseDate ) + 1, 1, 1 ),
DATE( YEAR( CloseDate ), MONTH( CloseDate ) + 1, 1 )
) - 1
)
Any help/insight would be greatly appreciated!
- Cody Pierson
- December 01, 2021
- Like
- 1
- Continue reading or reply
Help me Create a Trigger for CheckBox to clone Opportunity and OpportunityLineItem
//This is what i have coded please help resolve this
trigger CloneParentOpportunityTrigger on Opportunity (After insert,After update)
{
List<Opportunity> oppsToUpdate = new List<Opportunity>();
Map<Id,Opportunity> OldOppId = new Map<Id,Opportunity>();
Opportunity newopp = new Opportunity();
if(Trigger.IsAfter)
{
if(Trigger.IsInsert || Trigger.IsUpdate)
{
if(newopp.Clone_Opportunity__c)
{
for(Opportunity opp : Trigger.new)
{
//opportunity list item
newopp.Name = opp.Name;
newopp.AccountId = opp.AccountId;
newopp.Product_Type__c = opp.Product_Type__c;
newopp.CloseDate = opp.CloseDate;
newopp.StageName = opp.StageName;
newopp.Payment_Frequency__c = opp.Payment_Frequency__c;
newopp.Most_Recent_Invoice_Date__c = opp.Most_Recent_Invoice_Date__c;
newopp.Billing_Start_Date__c = opp.Billing_Start_Date__c;
newopp.Parent_Opportunity__c = opp.Id;
oppsToUpdate.add(newopp);
OldOppId.put(opp.id,opp);
}
insert oppsToUpdate;
Map<Id,Opportunity> NewOppId = new Map<Id,Opportunity>();
for(Opportunity opp1 : oppsToUpdate)
{
NewOppId.put(opp1.Id, opp1);
}
List<OpportunityLineItem> oppitemList = new List<OpportunityLineItem>([SELECT Id, Product2Id, Quantity, UnitPrice, OpportunityId FROM OpportunityLineItem Where OpportunityId IN : OldOppId.keyset()]);
for(OpportunityLineItem oppitem : oppitemList)
{
OpportunityLineItem oli = new OpportunityLineitem();
oli.OpportunityId = NewOppId.get(oppitem.OpportunityId).Id;
oli.Product2Id = oppitem.Product2Id;
oli.Quantity = oppitem.Quantity;
oli.UnitPrice = oppitem.UnitPrice;
oppitemlist.add(oli);
}
insert oppitemList;
}
}
}
}
- SFDCIronMan
- December 01, 2021
- Like
- 1
- Continue reading or reply
How to pass Record Id from Parent component to Child component in Aura
I am calling the Child component from the Parent component..so, it is successfully done.
but
along with that i want to pass the Record Id from Parent component to Child component using Aura component.
Thanks
- SFUser
- November 23, 2021
- Like
- 1
- Continue reading or reply
IF Condition on Visualforce Email Template
I want to add IF condition where if a certain picklist value is selected then a certain image is picked through static resource image link.
The image picked should show in the vf email template as per the condition set.
<messaging:emailTemplate subject="Delivery Status for Invoice Number: {!relatedto.Number__c}" recipientType="Contact" relatedToType="Invoice__c"> <messaging:htmlEmailBody > <apex:outputPanel > <img src="my static resource image url" alt="" style="display: block; padding: 0px; text-align: center; height: 100%; width: 100%; border: 0px none transparent;" width="636"> </img> </apex:outputpanel> </messaging:htmlEmailBody> </messaging:emailTemplate>
The shared code is what I have so far on having the image to display but I am stuck in adding the IF condition to display different images as per a selected picklist value.
I'd appreciate any assistance on this.
- Alimali Stephen 15
- November 01, 2021
- Like
- 1
- Continue reading or reply
My task is to get data from api and display it in Table in aura lightning . I am getting the table but data is not inserted in the columns
@AuraEnabled
public static List<string> output(String serviceId, String depositTicker, string withdrawalTicker, integer depositValue ){
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.bestrate.org/api/select-service');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
string body = '{"serviceId":"'+serviceId+'","depositTicker" :"' +depositTicker+'" ,"withdrawalTicker":"'+ withdrawalTicker +'","partnerId":null,"depositValue":"'+depositValue+'" }';
request.setBody(body);
HttpResponse response = http.send(request);
string values = response.getBody();
Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(values);
Map<String, Object> dim = (Map<String, Object>)m.get('result');
system.debug(dim.get('withdrawalValue'));
List<Object> a = (List<Object>)dim.get('fields');
List<string> lsstr= new List<string> ();
// List<string> lsst= new List<string> ();
for(Object b:a){
lsstr.add(String.valueOf(b));
}
system.debug(lsstr);
return lsstr;
}
}
output that is returning from method :
({description=The recipient’s wallet address is the address we send coins bought, once a transaction is finished., name=withdrawalWallet, placeholder=Wallet address, required=true, title=Enter your ETH wallet address}, {defaultValue=user.email, description=Enter your email to start exchange, name=email, placeholder=Email, required=true, title=Enter your email address})
Component:
<aura:component controller="integpost" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<aura:attribute name="serviceId" type="String" />
<aura:attribute name="depositTicker" type="String" />
<aura:attribute name="withdrawalTicker" type="String" />
<!-- <aura:attribute name="partnerId" type="String" />-->
<aura:attribute name="depositValue" type="integer" />
<aura:attribute name="ApiDetail" type="String[]"/>
<aura:attribute name="Detail" type="List" />
<lightning:card>
<lightning:input label="Enter service Id" value="{!v.serviceId}"/><br/>
<lightning:input label="Enter Deposit ticket" value="{!v.depositTicker}"/><br/>
<lightning:input label="Enter Withdrawl Ticket" value="{!v.withdrawalTicker}"/><br/>
<!--<lightning:input label="Enter partnerId" value="{!v.partnerId}"/><br/>-->
<lightning:input label="Enter deposit Value" value="{!v.depositValue}"/><br/>
<lightning:button label="getExchange" onclick="{!c.handleApex}" variant="success"/>
<lightning:datatable data="{!v.ApiDetail}"
columns="{!v.Detail}"
keyField="name"
hideCheckboxColumn="false"/>
</lightning:card>
</aura:component>
js:
({
handleApex : function(component, event, helper) {
var action = component.get('c.output');
var ion = component.get('v.serviceId');
var dt = component.get('v.depositTicker');
var wt = component.get('v.withdrawalTicker');
// var pid = component.get('v.partnerId');
var dv = component.get('v.depositValue');
// var Ad = component.get('v.ApiDetail');
action.setParams({'serviceId': ion, 'depositTicker':dt, 'withdrawalTicker': wt,
'depositValue':dv});
component.set('v.Detail', [
{label: 'title', fieldName:'title', type: 'text',editable: true},
{label: 'name', fieldName: 'name', type: 'text'},
{label: 'placeholder', fieldName: 'placeholder', type: 'text'},
{label: 'description', fieldName: 'description', type: 'text',editable: true},
{label: 'required', fieldName: 'required', type: 'boolean',editable: true}
]);
action.setCallback(this, function(response){
var state = response.getState();
if(state == 'SUCCESS'){
console.log('apex call is done!', response.getReturnValue());
component.set('v.ApiDetail', response.getReturnValue());
}
});
$A.enqueueAction(action);
}
})
- shrayas reddy
- October 31, 2021
- Like
- 1
- Continue reading or reply
parentid is not coming while creating new child record in lwc
My below code is working fine, however, while creating a new child record, parentid is not populating automatically, again I am selecting to add that child record to parent, can anyone help me out. For example, in the account record related list if we create contact record automatically that specific accountid(name) will come on the record detail page of contact. Same functionality I need in my below component. can anyone help me out?
TEmpate: <template> <lightning-card title={titleWithCount} icon-name="standard:record"> <lightning-button label="New" slot="actions" onclick={createNew}></lightning-button> <div slot="footer"> <div if:true={countBool}> <lightning-button label="View All" onclick={navigateToRelatedList}></lightning-button> </div> </div> <div class="slds-m-around_medium"> <div if:true={listRecords}> <template for:each={listRecords} for:item="rec"> <div key={rec.Id} class="slds-box"> <lightning-record-view-form record-id={rec.id} object-api-name={objectName}> <div class="slds-grid"> <div class="slds-col slds-size_1-of-2"> <lightning-output-field field-name={field1}></lightning-output-field> <lightning-output-field field-name={field2}></lightning-output-field> </div> <div class="slds-col slds-size_1-of-2"> <lightning-output-field field-name={field3}></lightning-output-field> <lightning-output-field field-name={field4}></lightning-output-field> </div> </div> </lightning-record-view-form><br/><br/> </div> </template> </div> </div> </lightning-card> </template> JS: import { LightningElement, api, wire, track } from 'lwc'; import fetchRecords from '@salesforce/apex/RelatedListController.fetchRecords'; import { NavigationMixin } from 'lightning/navigation'; export default class RelatedList extends NavigationMixin( LightningElement ) { @api objectName; @api parentObjectName; @api fieldName; @api fieldValue; @api parentFieldAPIName; @api recordId; @api strTitle; @api filterType; @api operator; @api fieldsList; @api relationshipApiName; @track field1; @track field2; @track field3; @track field4; @track listRecords; @track titleWithCount; @track countBool = false; //@api recordid; connectedCallback() { var listFields = this.fieldsList.split( ',' ); console.log( 'Fields are ' + listFields ); this.field1 = listFields[ 0 ].trim(); this.field2 = listFields[ 1 ].trim(); this.field3 = listFields[ 2 ].trim(); this.field4 = listFields[ 3 ].trim(); console.log( 'Field 1 is ' + this.field1 ); console.log( 'Field 2 is ' + this.field2 ); console.log( 'Field 3 is ' + this.field3 ); console.log( 'Field 4 is ' + this.field4 ); } get vals() { return this.recordId + '-' + this.objectName + '-' + this.parentFieldAPIName + '-' + this.fieldName + '-' + this.fieldValue + '-' + this.filterType + '-' + this.operator + '-' + this.fieldsList; } @wire(fetchRecords, { listValues: '$vals' }) accountData( { error, data } ) { if ( data ) { this.listRecords = data.listRecords; console.log(JSON.stringify(this.listRecords)); if ( data.recordCount ) { if ( data.recordCount > 3 ) { this.titleWithCount = this.strTitle + '(3+)'; this.countBool = true; } else { this.countBool = false; this.titleWithCount = this.strTitle + '(' + data.recordCount + ')'; } } } } createNew() { this[NavigationMixin.Navigate]({ type: 'standard__objectPage', attributes: { objectApiName: this.objectName, actionName: 'new' } }); } navigateToRelatedList() { this[NavigationMixin.Navigate]({ type: 'standard__recordRelationshipPage', attributes: { recordId: this.recordId, objectApiName: this.parentObjectName, relationshipApiName: this.relationshipApiName, actionName: 'view' } }); } } Meta: <?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="RelatedList"> <apiVersion>52.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__RecordPage</target> </targets> <targetConfigs> <targetConfig targets="lightning__RecordPage"> <property name="strTitle" type="String" label="Title" description="Enter the title"/> <property name="objectName" type="String" label="Object Name" description="Enter the object name"/> <property name="parentObjectName" type="String" label="Parent Object Name" description="Enter the parent object name"/> <property name="relationshipApiName" type="String" label="Relationship Name" description="Enter the relationship API name"/> <property name="parentFieldAPIName" type="String" label="Parent Field API Name" description="Enter the parent field API Name"/> <property name="fieldName" type="String" label="Field Name" description="Enter the field name"/> <property name="fieldValue" type="String" label="Field Value" description="Enter the field value"/> <property name="filterType" type="String" label="Filter Type" description="Enter the filter type"/> <property name="operator" type="String" label="Operator" description="Enter the operator"/> <property name="fieldsList" type="String" label="Fields List" description="Enter the field API names separated by coma. Do not enter more than 4 fields"/> </targetConfig> </targetConfigs> </LightningComponentBundle>
- The new Learner
- October 21, 2021
- Like
- 1
- Continue reading or reply
Get values in a List from JSON
I'm doing a REST API call to get the global value set and trying to deserialize the JSON result to get the picklist values in a List<String>.
Here is the JSON:
{ "size": 1, "totalSize": 1, "done": true, "queryLocator": null, "entityTypeName": "GlobalValueSet", "records": [ { "attributes": { "type": "GlobalValueSet", "url": "/services/data/v53.0/tooling/sobjects/GlobalValueSet/0Nt59000000AAAAAAA" }, "Metadata": { "customValue": [ { "color": null, "default": false, "description": null, "isActive": null, "label": "USA", "urls": null, "valueName": "USA" }, { "color": null, "default": false, "description": null, "isActive": null, "label": "Canada", "urls": null, "valueName": "Canada" } ], "description": null, "masterLabel": "US States & Territories", "sorted": false, "urls": null }, "Id": "0Nt59000000AAAAAAA" } ] }I need help in fixing the error and also how to get valueNames in a List<String>
Error: System.JSONException: Malformed JSON: Expected '{' at the beginning of an object.
Here is what I have tried so far:
Wrapper: public class GlobalValueSetWrapper{ Metadata metadata; public class Metadata { public List<CustomValue> customValue; } public class CustomValue { public String label; public String valueName; } } Class: //calling API to get the JSON result HttpResponse res = GlobalValueSetAPIHandler.getResponse('Countries'); GlobalValueSetWrapper wrapper = (GlobalValueSetWrapper) JSON.deserialize(res.getBody(), GlobalValueSetWrapper.class);
- RJ12
- September 22, 2021
- Like
- 1
- Continue reading or reply
How to avoid soql from the loop in batch class?
Here is my code for the same please have a look.
Note: My code is working. The only issue is soql which I am executing in the loop. I have commented on the issues in my code for better understanding.
global class BatchAssignment implements Database.Batchable<sObject>{ global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator([SELECT Id, Individual_or_organization__c ,Orgganization_Name__c,First_Name__c,Last_Name__c,Postal_Code__c,Date_Recieved__c,Amount__c,Error_Message__c,Description__c FROM staging__c]); } global void execute(Database.BatchableContext BC, List<staging__c> scope){ List<Opportunity> newOpptyList = new List<Opportunity>(); for(staging__c sc:scope){ system.debug('in for loop'); if(sc != null && sc.Individual_or_organization__c == 'I') { system.debug('in if == I'); // calling custom method that executes soql inside loop and storing output here Account objAccount = searchAccount(sc); if(objAccount != null) { // calling custom method that executes soql inside loop and storing output here List<Contact> linkContactList = searchContact(objAccount, sc); system.debug('contact'+linkContactList); try{ if(linkContactList != null && !linkContactList.isEmpty()) { upsert linkContactList; system.debug('creating opp'); //Create new opportunity; for(Contact objCon : linkContactList) { newOpptyList.add(new Opportunity(Name = objCon.LastName, StageName = 'Prospecting', AccountId = objAccount.Id, ContactId = objCon.Id, CLOSEDATE=Date.today() )); } if(newOpptyList != null && !newOpptyList.isEmpty()) { system.debug('insert opp'); insert newOpptyList; } } }catch(Exception ex) { system.debug('---Exception--' + ex); } } } } } // this method is getting called inside the loop of execute method which is bad private Account searchAccount(staging__c scope) { Account acc= new Account(); if(scope.Orgganization_Name__c != null && scope.Postal_Code__c != null) { system.debug('acc not zero'); acc= [SELECT Id, Name FROM Account WHERE Name = :scope.Orgganization_Name__c AND BillingPostalCode = :scope.Postal_Code__c]; } return acc; } // this method is getting called inside the loop of execute method which is bad private List<Contact> searchContact(Account objAccount, staging__c scope) { List<Contact> linkContactList = new List<Contact>(); if(scope.First_Name__c != null && scope.Last_Name__c != null && scope.Postal_Code__c != null) { List<Contact> existingContactList = [SELECT Id, FirstName, LastName, MailingPostalCode FROM Contact WHERE FirstName = :scope.First_Name__c AND LastName = :scope.Last_Name__c AND MailingPostalCode = :scope.Postal_Code__c]; //For existing contacts system.debug('existing contact'+existingContactList); if(existingContactList.size()>0 ) { for(Contact objCon : existingContactList) { objCon.AccountId = objAccount.Id; linkContactList.add(objCon); } } else { //create new contact system.debug('into else'); linkContactList.add(new Contact(FirstName = scope.First_Name__c, LastName = scope.Last_Name__c, MailingPostalCode = scope.Postal_Code__c, AccountId = objAccount.Id)); system.debug('linked contact2'+linkContactList); } } return linkContactList; } global void finish(Database.BatchableContext BC){ system.debug('finished:::'); } }
- Aishwary
- September 14, 2021
- Like
- 1
- Continue reading or reply
In an Apex REST Endpoint how do I parse parameters sent in a Get request?
/services/apexrest/Endpoint/?subject=test&status=active&priority=1&origin=?subject=test&status=active&priority=1I want to parse the url params in the class below
@HttpGet global static void getStatus() { RestRequest request = RestContext.request; System.debug(request.requestURI); }
Please help!
- Shaolin Master
- September 04, 2021
- Like
- 1
- Continue reading or reply
I receive an empty list of notifications using the Connect REST API endpoint: /connect/notifications
I want to get all the current user's notifications to display them in a LWC component. For this, I tried to make a REST API callout from Salesforce to the same Salesforce org using Connect REST API Resources (/connect/notifications — documentation: https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_resources_notifications_resources.htm)
I tried to make the callout using first Workbench, then an apex class, but I always get the same result, an empty list of notifications. The current user has both custom and standard notifications, so I don't understand why I always get an empty list.
Does anyone have any idea why I receive an empty list of notifications?
- Fota Madalina
- September 03, 2021
- Like
- 1
- Continue reading or reply