• Maharajan C
  • ALL STAR
  • 16444 Points
  • Member since 2015
  • Consultant
  • Infosys


  • Chatter
    Feed
  • 529
    Best Answers
  • 4
    Likes Received
  • 60
    Likes Given
  • 15
    Questions
  • 1747
    Replies
I am gettinf the output of month as number . but i need to convert that as string. can anyone help me?

​​​​​​​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
Hello, trying to compose a SOQL that will retrieve recently Closed Won Opportunities unless the Opportunity has only 1 of 2 specific Products. Here is my last attempt:

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?
 
I am trying to prevent users from copy and pasting the same URL into  two required fields. These fields only need to be entered when changing the status of opportunity. I created a validation rule stating:

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?

public with sharing class ehsSignatureExtensionController {

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;

}
}
<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

 

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?
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;
    }
    
}

 
Apex Class:
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
Hi,

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
Hi!
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?

 
Hi.  I am having problems with a cross-object formula field and its probably because I'm not 100% certain on how lookup relationship fields work.
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:
  1. 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?
  2. 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?
Thanks in advance for any help!
 Create inner class with comparator (by lastName asc) for parsing this json:

[{"lastName" : "Perucci", "firstName" : "John", "title" : "guitarist" },{"lastName" : "LaBrie", "firstName" : "James", "title" : "singer"},{"lastName" : "Mabgini", "firstName" : "Mike", "title" : "drummer"},{"lastName" : "Myung", "firstName" : "John", "title" : "basist"}]
I am trying to find the highest Opportunities' Amount of an Account and want to reflect the value in one of the fields in Account, 'Highest_Opportunity_Amount__c'.
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;
                }
            }
        }
    }
I have an Apex Trigger that's not firing. This Trigger is supposed to call a helper class which then merges Leads into existing accounts if the email already exists in the Salesforce org. I have the trigger and Class here, what can I change to make it work properly without errors? 

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);
        
              
            }

            
        }
            
        }
     
        
    }
   
}
I have a very simple lightning:recordEditForm:
<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!
Hi All,
          I want to show users like below image. how can i do this in LWC? any suggestions?
 User-added image
public class OpportunityToBeSent {
    @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());
        }
        
    }    
}
Hello,

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)))))
HTML:
<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;}
}
////////////////////////////////////////////////////////////////////////////////////////////User-added imagethis is my table please help me out of this.
Hi Guys,

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
Hi All,

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
We have the managed package which is created by us so we are try to install this package  some other org.

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
Hi Experts,

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: Thanks,
Raj

 
We are using the chatter answers in community which is going to retire after Winter 18 release. Wanted some suggestions to perform the migration...below are the research...
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?
Hi All,

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
Hi All,

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
 
Hi All,

Can you please help me to find unused apps in my salesforce instance to Metadata Cleanup

Thanks,
Raj
Hi All,

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
Hi All,

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
 
Hi,

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
Hi Friends,

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.
Hi All,

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.
Hi All,

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.
Hi All,

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.
Hi All,

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
Hi Friends,

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.
I need to show 'no records available' as a table results if I didn't receive any record
Question :To Show The Total Number Of Active Child Contacts On A Parent Account.

**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);  

}



 
I am gettinf the output of month as number . but i need to convert that as string. can anyone help me?

​​​​​​​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
Hi, need your help for this error
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;
    }
}

 
  • November 23, 2022
  • Like
  • 0

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 ))

My Requirement:
 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
Salesforce Flow: Populate "primary contact" on opportunity at lead conversion using before trigger ?
Primary_Contact is Custom field
----------------------------------------------------------------------------------------------
Please Do it in Flows
@RestResource(URLMapping = '/OpportunityService/*')
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;
        
    }
}
Hi,
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);
  • June 23, 2022
  • Like
  • 0

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!

Hello, trying to compose a SOQL that will retrieve recently Closed Won Opportunities unless the Opportunity has only 1 of 2 specific Products. Here is my last attempt:

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?
 
Hello Experts,

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
Is there a way for me to test out a Web-To-Lead form? I'm just creating this is in a Dev Org. I've created a Round Robin Lead Assigment so Web leads will be distributed out fairly. How can I best test this out to make sure to works? Thanks!

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');
                         }
                    }
                }  
            }
        } 

Apex Class:
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
Hello,

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
  • April 27, 2022
  • Like
  • 1
I'm trying to modify the visibility of a field using Apex, but I'm getting the following error when trying to update Metadata:
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
Hi All,
          I want to show users like below image. how can i do this in LWC? any suggestions?
 User-added image
Hello! I'm just now digging into Apex Triggers, and I'm having a little trouble with creating tests. Here's my Apex class:
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);
    }
}

 
Hi everyone, I'm  new on LWC . and  I'm doing  this example to generate a PDF https://santanuboral.blogspot.com/2020/10/lwc-generate-pdf.html
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');
Fairly new to Salesforce and am trying to wrap my head around the system as well as importing data. I don't understand why fields don't match up between accounts and contacts. E.g. contact has a field for "mobile" while account has "phone" and "phone other" and no field for "mobile" or "cell". Also contact has "street 1", "street 2" address while account has "mailing address" and "shipping address". Why don't the fields match up between these two objects? And would it make sense to have them match?

Thanks. 
  • December 28, 2022
  • Like
  • 1
Class Controller:
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();
        
    }

}

 
I am struggleing understanding how to write test units for 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());
        }
    }

}

 
Hi there!

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!
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;
            }
        }   
    }
}
Hi..,
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
  • November 23, 2021
  • Like
  • 1
Hello Team!
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.
public class integpost {
      @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})no output in aura table


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);
    }
})
HI Experts,

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>

 

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);
  • September 22, 2021
  • Like
  • 1
Hi, I have created a class for processing opportunity object based on the custom object "staging__c". But the issue is I'm executing SOQL inside for loop which is a bad practice. Can anyone help me to avoid it?
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:::');
    }
}


 
I want to know how to parse the URL params from a get request
/services/apexrest/Endpoint/?subject=test&status=active&priority=1&origin=?subject=test&status=active&priority=1
I 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!
Hello everyone,
 
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?
User-added imageUser-added image