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


  • Chatter
    Feed
  • 486
    Best Answers
  • 4
    Likes Received
  • 49
    Likes Given
  • 15
    Questions
  • 1620
    Replies
Hello everyone I have a problem with a field formula field named Space_Cost.

Formula

(Space_Count__c - 1) *  Additional_Space_Rate__c

the problem is if the field is Null or empty I get a negative number 
For example, if the space count is null or 0 or 1 I want the field to equal 0.00 if the field equals anything else do the formula above since the first space is free. 

any help would be much appreciated.
public class DelteContactController {
    public account acc {get; set;}
    public List<ContactInfoWrapper> ContactsWrapper {get; set;}
    public DelteContactController(ApexPages.StandardController controller)
    {}
    public List<ContactInfoWrapper> getAccObj(){
        Id id = apexpages.currentpage().getparameters().get('id');
         acc = [SELECT id from account where Id =:id];
        list<contact> conList=[SELECT Id,Account.Name,Name, Email FROM Contact where AccountId=:acc.id];
        ContactsWrapper = new List<ContactInfoWrapper>();
        for(Contact con:conList){
            ContactsWrapper.add(new ContactInfoWrapper(con,false));
        }
        return ContactsWrapper;
    }
    
    
    
    
    //Wrapper class
    public class ContactInfoWrapper
    {
        public Contact sObj{get;set;}
        public Boolean checked {get;set;}
        public ContactInfoWrapper(Contact con,boolean selectedBox)
        {
            sObj = con;
            checked=selectedBox;
        }
        
    }
   
    
    //Delete
    
    public pageReference deletecontact()
    {
        list<Contact> conlist = new list<Contact>();
        for(ContactInfoWrapper c : ContactsWrapper)
        {
            if(c.checked == true)
            {
                
                conlist.add(c.sObj);
            }
        }
        if(conlist.size()>0)
        {
           Delete conlist ;
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Contact Deleted Successfully !!!'));
        }
        pageReference pr = new pageReference('/lightning/o/Account/list?'+acc.id);
        return pr ;
        
        
    }
    
  

}
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;
            }
        }   
    }
}
Hello,
I have created a batch with a method that returns a json in a specific format (key-value pair)
 
private String prettyPrintLayoutFields(Map<String,String> layoutFieldMap){
        String result;
        result = layoutFieldMap.toString(); 
        System.debug('String result ' +result);
        return result;
    }
The value parsed into the field looks like this:
{Performance_Level__c=Performance Level, CreatedById=Created By, CreatedDate=Created By, LastModifiedById=Last Modified By, LastModifiedDate=Last Modified By, Name=Sub-Step Name, Level_of_details__c=Level of details, OwnerId=Owner, RecordTypeId=Record Type, ...}
How can I update this method to only print the key separated by a comma.
It looks like that I should use something like that:
string.join(map.keyset(),',');
But not quite on how to write it in my method
Could someone help?
Thanks

 
Hello, everyone. 

I am new to Salesforce (I've began studying it about 1 month ago). 

There are some projects that I intend to implement on my Salesforce Professional Edition, but I am stuck due to some limitations. Since I don't have much experience with the platform, I wonder if the community of developpers could help me confirm if, in fact, my edition doesn't allow me to develop them, and if I need to upgrade my edition.

The implementations are described below:

1) Send scheduled email alerts

We want to send e-mail alerts when expiration dates of opportunities' contracts are approaching. In this context, we want to send weekly emails corresponding to each opportunity.

I've tried to do this by using Flow and Process Builder. Nevertheless, I always get the error message shown on this topic https://trailhead.salesforce.com/trailblazer-community/feed/0D54S00000BuOazSAF (bear with me...the french community seamed more active, so I tried to ask for help in french :) - google translator required). 

TL DR.: Error message = "insufficient access rights on cross-reference id"

2) Build a list of e-mails

The objective here is to make the sending of email messages more transparent. For example, if a sales representant sends an email to an opportunity, we want to make this message visible on Salesforce. At each opportunity page, there would be a "e-mails" tab, where we could show these messages.

3) Access data from external sources 

We want to access data contained on Google Cloud Big Query and Google Sheets. Note: We don't have access to Salesforce API on Professional Edition.


Actually, I think that the main question here is: 

What can developpers do on Salesforce Professional Edition? 

As a begginer, I am finding a lot of barriers. The things I was able to do so far are the following:

Change Pages' Layouts
Create New Objects and Fields
Create Email Alerts

Things I identified that I can't do:

Create Apex Classes
Create Customized Metadata
Access external API's
 
I have an wrapper class , whose list is returned in the method. how to sort this list based on a checkbox field ( in my case it is My target field)? I want to sort it as all records with  My target =false must show up first.

Wrapper class:
public class tsfwrapper {
        
        @AuraEnabled
        public string accountName{get;set;}
        @AuraEnabled
        public string TSFId{get;set;}
        @AuraEnabled
        public Id accountId{get;set;}
        @AuraEnabled
        public string territoryName{get;set;}
        @AuraEnabled
        public decimal YTDActivity{get;set;}
        @AuraEnabled
        public date lastActivityDate{get;set;}
        @AuraEnabled
        public boolean alignmentRequest{get;set;}
        @AuraEnabled
        public boolean myTarget{get;set;}
          @AuraEnabled
        public string preferredAddress{get;set;}
        @AuraEnabled
        public string preferredLocation{get;set;}
    }

Method where wrapper list is returned:

for(Account acc: accList)
    {
        Id accIdVar = acc.Id;
        system.debug('*****Account ID'+accIdVar);
        tsfwrapper twrpc = new tsfwrapper();
        if(tsfMap.Keyset().contains(accIdVar)){
        if(tsfMap.get(accIdVar)!=null){
           
                twrpc.TSFId = tsfMap.get(accIdVar).Id;
                twrpc.accountName = tsfMap.get(accIdVar).Account_vod__r.Name;
                twrpc.accountId = tsfMap.get(accIdVar).Account_vod__c;   
                twrpc.territoryName = tsfMap.get(accIdVar).Territory_vod__c;
                twrpc.YTDActivity = tsfMap.get(accIdVar).YTD_Activity_vod__c;
                twrpc.lastActivityDate = tsfMap.get(accIdVar).Last_Activity_Date_vod__c;
                twrpc.alignmentRequest = tsfMap.get(accIdVar).MSD_Alignment_Request__c;
                twrpc.myTarget = tsfMap.get(accIdVar).My_Target_vod__c;
                twrpc.preferredAddress = tsfMap.get(accIdVar).MSD_CORE_My_Last_Used_Address__c;
                twrpc.preferredLocation = tsfMap.get(accIdVar).MSD_CORE_My_Last_Used_Location__c;
        }
        }
        else
        {
            system.debug('******Inside Null List');
                   twrpc.TSFId = '';
                   twrpc.accountName = acc.Name;
                   twrpc.accountId = acc.Id;   
                   twrpc.territoryName = terrName;
                   twrpc.YTDActivity = 0.0;
                   twrpc.lastActivityDate = Null ;
                   twrpc.alignmentRequest = false;
                   twrpc.myTarget = false;
                     twrpc.preferredAddress = '';
                   twrpc.preferredLocation = '';  
                    
         }
        
        twrp.add(twrpc);  
    }
    return twrp; 

 
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>

 
Hi
I am new to salesforce development. 
How can add trigger logic in below helperclass. 

this is the helperclass. 
public class Service_CaseTriggerHelper {
    public static void HelperMethod(List<Case> Caselist) {
    Set<Id> contactIds = new Set<Id>();
    Set<Id> acctIds = new Set<Id>();
    for (Case c : Caselist) {
     contactIds.add(c.ContactId);
     acctIds.add(c.AccountId);
 }
 List <EntitlementContact> entlContacts =
     [Select e.EntitlementId,e.ContactId,e.Entitlement.AssetId
      From EntitlementContact e
      Where e.ContactId in :contactIds
      And e.Entitlement.EndDate >= Today
      And e.Entitlement.StartDate <= Today];
 if(entlContacts.isEmpty()==false){
     for(Case c : Caselist){
         if(c.EntitlementId == null && c.ContactId != null){
             for(EntitlementContact ec:entlContacts){
                 if(ec.ContactId==c.ContactId){
                     c.EntitlementId = ec.EntitlementId;
                     if(c.AssetId==null && ec.Entitlement.AssetId!=null) c.AssetId=ec.Entitlement.AssetId;
                    break;
                 }
             }
         } 
     }

 }else{
     List <Entitlement> entls = [Select e.StartDate, e.Id, e.EndDate,
                                 e.AccountId, e.AssetId
                                 From Entitlement e
                                 Where e.AccountId in :acctIds And e.EndDate >= Today
                                 And e.StartDate <= Today];
     if(entls.isEmpty()==false){
         for(Case c : Caselist){
             if(c.EntitlementId == null && c.AccountId != null){
                 for(Entitlement e:entls){
                     if(e.AccountId==c.AccountId){
                         c.EntitlementId = e.Id;
                         if(c.AssetId==null && e.AssetId!=null)
                             c.AssetId=e.AssetId; break;
                     }
                 }
             }
         }
      }

     }

 }
}
This is the trigger. 
trigger Service_CaseTrigger on Case (Before Insert, Before Update) { 

    Switch on Trigger.operationType {

        when BEFORE_INSERT {

            Service_CaseTriggerHelper.HelperMethod(TRIGGER.NEW);

        }

        when BEFORE_UPDATE {

            Service_CaseTriggerHelper.HelperMethod(TRIGGER.NEW);

        }

    }

}

The below trigger to be add in above helperclass and trigger. 
trigger CompleteResolutionTimeMilestoneopen on Case (after update) {
Id recId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Incident').getRecordTypeId();
    if (UserInfo.getUserType() == 'Standard'){
        DateTime completionDate = System.now(); 
            List<Id> updateCases = new List<Id>();
            for (Case c : Trigger.new){
                    if (((c.RecordTypeId == recId)&&(c.Status == 'open'))&&((c.SlaStartDate 
                        <= completionDate)&&(c.SlaExitDate == null)) )
        updateCases.add(c.Id);
        }
    if (updateCases.isEmpty() == false)
          milestoneUtils.completeMilestone(updateCases,'Initial Response', completionDate);
         
    

    }
}
Controller:public class AppointmentsViewController {


    public List<Doctor__c> doctorList {get;set;}
    public List<SelectOption> doctorSelectOptionList{get;set;}
    public List<Appointment__c> apointmentList{get;set;}
    public String doctorId {get;set;}
    public List<Patient__c> patientList{get;set;}
    public List<SelectOption> patientSelectOptionList{get;set;}
    public Integer noOfRecords{get; set;}
    public Integer size{get;set;}
    
    public AppointmentsViewController() {
       doctorList = [
           SELECT Id, Name, Working_Hours_Start__c, Working_Hours_End__c
           FROM Doctor__c
           ORDER BY Name ASC
       ];
        
        patientList = [
            SELECT Id, Name
            FROM Patient__c
        ];
        
        patientSelectOptionList = new List<SelectOption>();
        
        for(Patient__c item :patientList)
        {
            patientSelectOptionList.add(new SelectOption(item.Id, item.Name));
        }
        doctorId = doctorList.isEmpty() == FALSE ? doctorList[0].Id : NULL;
        
       doctorSelectOptionList = new List<SelectOption>();
        
        for(Doctor__c item :doctorList) {
            doctorSelectOptionList.add(new SelectOption(item.Id, item.Name));
        }
        getAppointments();
       
        
    }
    
    public void getAppointments () {
        apointmentList = [
            SELECT Id, Name, Doctor__c, Patient__c, Appointment_Date__c, Duration_in_minutes__c
            FROM Appointment__c
            WHERE Doctor__r.Id = :doctorId
        ];
    }



    public List<Appointment__c> Appointment { get{

        return (List<Appointment__c>)setCon.getRecords();

    } set; }



    public ApexPages.StandardSetController setCon {

        get{

            if(setCon == null){

                size = 20;

                List<Appointment__c> Appointment = [
                    SELECT Id, Name, Doctor__c, Patient__c, Appointment_Date__c, Duration_in_minutes__c
                    FROM Appointment__c];

                setCon = new ApexPages.StandardSetController(Appointment);

                setCon.setPageSize(size);

                noOfRecords = setCon.getResultSize();

            }

            return setCon;

        }set;

    }






}




Test:
@isTest
private class AppointmentsViewControllerTest {
    
    @isTest static void AppointmentsViewControllerTest1() {
        
        Doctor__c doctor = new Doctor__c(
        );
        
        insert doctor;
        
        AppointmentsViewController controller = new AppointmentsViewController();
        
        Appointment__c Appointment = new Appointment__c(
        );
        insert Appointment;
        
            ApexPages.standardSetController sc = new ApexPages.standardSetController(doctor

        
        
     // ApexPages.StandardSetController standardSetController = new ApexPages.StandardSetController(doctor);
        
    }
    
       
    

}
Hi,
I have added opportunity as a lookup in contact. I want my description on contact to be updated with the related opportunity's stage name. My following code is not working. Please let me know where I went wrong:

trigger populateOppStage on Contact (before insert, before update) {
   Set<ID> opps = New Set<ID>();
    for (contact con:trigger.new){
        opps.add(con.opportunity__r.Id);
    }
    Map<Id, String> mapOppToStage = New Map<Id, String>();
    for(opportunity opp:[SELECT ID, stagename 
                      FROM opportunity WHERE ID IN:opps]){
        mapOppToStage.put(opp.id, opp.stagename);
    }

    for (contact c:trigger.new){
        if(mapOppToStage.containsKey(c.opportunity__r.Id)){
                c.Description= mapOppToStage.get(c.Opportunity__r.id);
        }
    }
}
NOT(

     OR(
   
    Country  = 'US',
    Country  = 'USA',
    Country  = 'United State of America',
     ISBLANK(Country) 

     ) 

     )  
     
 AND(
     LEN(State)= 2,
     CONTAINS(State, "AB"},
     CONTAINS(State, "CD"},
     CONTAINS(State, "EF"}
)
im trying to do the test class for this code

public class Claseprogramadausuario {
    
public static void obtenerinfo(){

List<User> nlist = [SELECT Id, Username, FirstName, LastName, EmployeeNumber, UserRole.Name, Profile.Name, CreatedDate, LastModifiedDate, LastLoginDate, isActive FROM User WHERE Profile.Name != 'SelfService'];
string header = 'Id, Username , FirstName, LastName, EmployeeNumber, UserRole.Name,  Profile.Name, Created Date, LastModifiedDate, LastLoginDate, isActive \n';
string finalstr = header ;
for(User u: nlist)
{

       string recordString = u.id+','+u.Username +',' + u.FirstName +','+ u.LastName +','+ u.EmployeeNumber+','+ u.UserRole.name +','+ u.profile.name +','+ u.CreatedDate +','+ u.LastModifiedDate +','+ u.LastLoginDate +','+ u.IsActive +'\n';

       finalstr = finalstr +recordString;
}

Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(finalstr);
string csvname= 'Userinfo.csv';
csvAttc.setFileName(csvname);
csvAttc.setBody(csvBlob);
Messaging.SingleEmailMessage correo = new Messaging.SingleEmailMessage();
correo.toAddresses = new String[] {'javierandoni@gmail.com', 'dlramirez@izzi.mx'};
correo.subject = 'Clase programada test';
correo.plainTextBody = 'Clase programada test';
Messaging.SingleEmailMessage[] correos =   new List<Messaging.SingleEmailMessage> {correo};
correo.setPlainTextBody('Account CSV ');
correo.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
Messaging.SendEmailResult[] results = Messaging.sendEmail(correos);

if (results[0].success) 
{
System.debug('The email was sent successfully.');
} else 
{
System.debug('The email failed to send: ' + results[0].errors[0].message);
}
}
}

And the test class im trying to do is this

// Test Class
@IsTest
Public class ClaseprogramadausuarioTest {
    @isTest static void testenviomail(){
        string pri= Claseprogramadausuario.obtenerinfo();
        System.assertEquals('The email was sent successfully.', pri);
    }
}

but i get this message: Illegal assignment from void to String.
 
Hi, 
I have an APEX Class that is updating a list and later I am presenting that list via LWC on the Lightning Record Page. 
I would like to write a test Class for the APEX Class. 
APEX Class:
public class PriceBookEntriesFromAccount {
    
    @AuraEnabled
    public static List<BB_Produkt__c> getPriceBookEntries(String artId) {
        List<BB_Produkt__c> bb = 
            [SELECT Name, Id, Berichsartikel__c, Berichsartikel_Copy__c, Produkt__r.Name, Verkostung__c, Kaufinteresse__c, Unternehmen__r.Name, CreatedDate 
             FROM BB_Produkt__c 
             WHERE Unternehmen__r.Id = :[SELECT Unternehmen__r.Name FROM Besuchsbericht__c WHERE Id =:artId].Unternehmen__r.Id
            ORDER BY CreatedDate DESC];
        //Add isAccessible() check
        return bb;
    }
    
    @AuraEnabled
	public static void updateRelatedList(List<BB_Produkt__c> Bblist)
    {
        if(Bblist!= null && Bblist.size()>0)
        {
            update Bblist;
            Bblist.sort();
        }
    }
}
So far this is what I have written, but I am getting 0% code coverage:
@isTest(SeeAllData=true)
public class testPriceBookEntriesFromAccount {
    
    public static testMethod void testBB_Produkt()
	{

		Account createAccount =new Account(Name='TestA');
		insert createAccount;
        
        Product2 createProduct2 =new Product2(Name='TestP');
		insert createProduct2;

		BB_Produkt__c createBB_Produkt =new BB_Produkt__c(Produkt__c=createProduct2.ID, Unternehmen__c=createAccount.Id);
		insert createBB_Produkt;

		createBB_Produkt.Feedback_Verkostung_1_5__c = 2;
		update createBB_Produkt;
	}
}


 
HI,
I have Create a page like account form and add some related contacts
and i want make that contacts editable.
Can someone help i am practicing on it.
code...on standardcontroller
<apex:page standardController="Account">
    <style>
        .s1{Background-Color: LightBlue;}
        .s2{Background-Color: Pink;}
    </style>
    <apex:form >
        <apex:sectionHeader title="Account" subtitle="Account Form"/>
        <apex:pageBlock title="Account Form" >
            <apex:pageBlockSection title="Account Information" columns="2">    
                <apex:inputField value="{!Account.Owner.Name}" styleClass="s1"/>
                <apex:inputField value="{!Account.Rating}" style="BackGround-Color:Pink; color: blue;"/>
                <apex:inputField value="{!Account.Name}" styleClass="s1"/>
                <apex:inputField value="{!Account.Phone}" styleClass="s2"/> 
                <apex:inputField value="{!Account.ParentId}" styleClass="s1"/>
                <apex:inputField value="{!Account.Fax}" styleClass="s2"/> 
                <apex:inputField value="{!Account.AnnualRevenue}" styleClass="s1"/>
                <apex:inputField value="{!Account.NumberOfEmployees}" styleClass="s2"/>  
                <apex:inputField value="{!Account.Ownership}" styleClass="s1"/>
                 <apex:inputField value="{!Account.website}" styleClass="s2"/>  
                
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Additional Information" columns="2">    
                <apex:inputField value="{!Account.Site}" styleClass="s1"/>
                <apex:inputField value="{!Account.AccountNumber}" styleClass="s2"/>
                <apex:inputField value="{!Account.Industry}" styleClass="s2"/>
                <apex:inputField value="{!Account.Type}" styleClass="s1"/> 
            </apex:pageBlockSection>           
            <apex:pageBlockSection title="Address Information" columns="2">  
                <apex:inputField value="{!Account.BillingStreet}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingStreet}" styleClass="s2"/>
                <apex:inputField value="{!Account.BillingState}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingState}" styleClass="s2"/>
                <apex:inputField value="{!Account.BillingCity}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingCity}" styleClass="s2"/>
                <apex:inputField value="{!Account.BillingPostalCode}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingPostalCode}" styleClass="s2"/>
                <apex:inputField value="{!Account.BillingCountry}" styleClass="s1"/>
                <apex:inputField value="{!Account.ShippingCountry}" styleClass="s2"/>
            </apex:pageBlockSection>            
            <apex:pageBlockSection title="Description" columns="2">    
                <apex:inputField value="{!Account.Description}" styleClass="s1"/>
            </apex:pageBlockSection> 
            <apex:pageBlock title="Related Contacts">
    
                <apex:pageBlockTable value="{!Account.contacts}" var="con">
                    <apex:column value="{!con.firstName}"/>
                    <apex:column value="{!con.LastName}"/>
                    <apex:column value="{!con.Phone}"/>
                    <apex:column value="{!con.AccountId}"/>         
                </apex:pageBlockTable>

                </apex:pageBlock>
            
            <apex:pageBlockButtons location="Bottom">
                <apex:commandButton action="{!Save}" value="Save"/>
                <apex:commandButton action="{!Cancel}" value="Cancel"/>          
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

 
  • September 27, 2021
  • Like
  • 0
What is this type of error means: what is possible solution?
trigger ApexTrigger10 on Contact (After insert,After Delete) {
    
    set<id> contactSet = new set<id>();
    List<Account> newAccountList = new List<Account>();
    
    if(trigger.isInsert && trigger.isAfter){
        for(Contact con:trigger.new){
            contactSet.add(con.Account);
         }
    }

    if(trigger.isDelete && trigger.isAfter){
        for(Contact con:trigger.old){
            contactSet.add(con.Account);
         }
    }
    List<Account> Acc= [SELECT id, name,(SELECT id,name from contacts) FROM Account WHERE id IN:contactSet];
    for( Account a : Acc)
    {
        a.Total_number_of_contacts__c= a.contacts.size();
        newAccountList.add(a);
    }
    update newAccountList;
}
 
I have the following requirement. I have to change styles of the second element rendered of this list, i tried a solution to do that but doesn't work, can you help me please?

data = {
                  issues: [
                                  {
                                         'chapter' :  'something1'
                                         'posiion':  '2A'
                                  },
                                 {
                                          'chapter': 'something2',
                                          'position' : '3A'
                                 },
                                 {
                                           'chapter : 'something3',
                                           'position': '4A'
                                 }
                                      ]
             }

html code:

<template for:each={data.issues} for:item="item" for-index="index">
             <h3 class ={dinamicClass} > {index} {item.chaper} </h3>
             <h3 claas ={dinamicClass} >{index} {item.position} </h3>
</template>

output: 
                          0 something1     0 2A
                          1 something2     1 3A
                          2 something3     3 3A

the idea is to modificate the second row, in bold and bigger.

I try this in JS but doesnt not work

@api index;

get dinamicClass(){
  return this.index == 2 ? 'slds_xxxxxxx_large' : slds_xxxxxxx_small'
}


Any idea to can implement to solve this?  Thanks
I have a picklist with values : 5%, 10%, 15%
And I want to use it in the formula field in percent format only like 5/100.
So please suggest what syntax should I write?
 
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.
Hello everyone I have a problem with a field formula field named Space_Cost.

Formula

(Space_Count__c - 1) *  Additional_Space_Rate__c

the problem is if the field is Null or empty I get a negative number 
For example, if the space count is null or 0 or 1 I want the field to equal 0.00 if the field equals anything else do the formula above since the first space is free. 

any help would be much appreciated.
public class DelteContactController {
    public account acc {get; set;}
    public List<ContactInfoWrapper> ContactsWrapper {get; set;}
    public DelteContactController(ApexPages.StandardController controller)
    {}
    public List<ContactInfoWrapper> getAccObj(){
        Id id = apexpages.currentpage().getparameters().get('id');
         acc = [SELECT id from account where Id =:id];
        list<contact> conList=[SELECT Id,Account.Name,Name, Email FROM Contact where AccountId=:acc.id];
        ContactsWrapper = new List<ContactInfoWrapper>();
        for(Contact con:conList){
            ContactsWrapper.add(new ContactInfoWrapper(con,false));
        }
        return ContactsWrapper;
    }
    
    
    
    
    //Wrapper class
    public class ContactInfoWrapper
    {
        public Contact sObj{get;set;}
        public Boolean checked {get;set;}
        public ContactInfoWrapper(Contact con,boolean selectedBox)
        {
            sObj = con;
            checked=selectedBox;
        }
        
    }
   
    
    //Delete
    
    public pageReference deletecontact()
    {
        list<Contact> conlist = new list<Contact>();
        for(ContactInfoWrapper c : ContactsWrapper)
        {
            if(c.checked == true)
            {
                
                conlist.add(c.sObj);
            }
        }
        if(conlist.size()>0)
        {
           Delete conlist ;
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Contact Deleted Successfully !!!'));
        }
        pageReference pr = new pageReference('/lightning/o/Account/list?'+acc.id);
        return pr ;
        
        
    }
    
  

}
Create a formula field that shows an opportunity’s progress:
Field Label: Contribution Level
Field Name: Contribution_Level
Formula Return Type: Text
Return values:
Less than or equal to 10%: Low
Between 10% and 40%: Medium
More than 40%: High
Hint: CASE statements can’t contain Boolean functions. Use IF statements instead.

I am entering below formula:
IF( Contribution_Percentage__c <=10,"Low", 

IF(Contribution_Percentage__c >10 && Contribution_Percentage__c <40,"Medium", 

"High"))

Still its not working....can anyone please help me here?
I have date stamps for different status I have set, the logic is check if date stamp exist for that particular status, if it does you can’t change back to a previous value. I can't figure out a way to do it. 
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;
            }
        }   
    }
}
Hello , 

i want to assign a string to Map value  like ; 
String SA =    String.valueOf(emailConfigMap.get(c.EmailConfiguration__c).Email__c) ;
its throwing  a NullPointerException - 
 
Hello, I have a Visualforce template. I want to use an apex class with PageReference.getContentAsPDF() to create a pdf through a flow with the VF template. Could you give me an example of the Apex class to use for my "Visualforce code" that I can add to a flow to create a pdf. (I want to achive, that the fields of the visualforce like (!Account.Name) are filled with screen flow inputs)

Thank you in advance.
Greetings
Jonathan

My Visualforce code:
<apex:page standardController="Account" renderAs="pdf"  >
    
   
    
    <h1>Welcome to APP!</h1>
        
        <p>Thank you, <b><apex:outputText value=" {!Account.Name}"/></b>, for 
            working with APP.</p>
        
        <p>Your account details are:</p>
        
        <table>
            <tr><th>Account Name</th>
                <td><apex:outputText value="{!Account.Name}"/></td>
            </tr>
            <tr><th>Account Rep</th>
                <td><apex:outputText value="{!Account.Owner.Name}"/></td>
            </tr>
            <tr><th>Customer Since</th>
                <td><apex:outputText value="{0,date,long}">
                    <apex:param value="{!Account.CreatedDate}"/>
                    </apex:outputText></td>
            </tr>
        </table>
       
</apex:page>


 

Hi,

So I have 5 checkboxes that I want to be ticked if a user advances to certain stages - what formula do I need? More info below

Checkbox 1
Checkbox 2
Checkbox 3
Checkbox 4
Checkbox 5

If anyone advances to the below stages I want to make sure they can't if any of the above is unticked

Stage 1
Stage 2
Stage 3
Stage 4
Stage 5
Stage 6

Thanks :)

why I get this error? I think description example4 is not inserted but why? this is the method:

@IsTest
  static void updateLeadsAndTasksTest(){      
    //update lead
    Lead newLead = Build.aLead()
    .withFirstName('rafa3')
    .withLastName('franco3')
    .withDescripcionPersonalizada('description example3')
    .withTextoAuxiliar('aux text3')
    .build();  
    insert newLead;    
    newLead.FirstName = 'rafa4';
    newLead.LastName = 'franco4';
    newLead.Descripcion_personalizada__c = 'description example4';
    newLead.Texto_auxiliar__c = 'aux text4';    
    Test.startTest();
    update newLead;
    Test.stopTest();
    List<Task> tasks = [
        SELECT WhoId, Descripcion_personalizada__c, Texto_auxiliar__c
        FROM Task
        WHERE WhoId = :newLead.id];
        for (Task task : tasks) {
          system.debug(tasks);
          system.debug('tasks');
        }
       // List<lead> leadQuery =[SELECT Descripcion_personalizada__c FROM Lead WHERE ]
    System.assertEquals(newLead.Descripcion_personalizada__c = 'description example4' ,  String.valueOf(tasks.get(0).Descripcion_personalizada__c),'text');
    System.assertEquals(newLead.Texto_auxiliar__c = 'aux text4' ,  String.valueOf(tasks.get(0)),'text');
    //System.assertEquals(expected, actual, msg)
  }
}

I am using TDD


User-added image
we have 2 objects Account and Dsignation
parent object:Account
Child object: Designation
Relationship :Lookup(Field name "Account__C" on Designation object)
If an Account has Designation with Title CEO(Field name="Title__c") then the Account field  "Area__c" cannot be blank
I want to create a validation rule for:

the user can only edit the name field in the contact object if the contact has the status "approved"
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
Hi everyone!

We have a custom integration that is getting the following error:

[
{
"message": "Record Type ID: this ID value isn't valid for the user: 0123F000002c926QAA",
"errorCode": "INVALID_CROSS_REFERENCE_KEY",
"fields": [
"RecordTypeId"
]
}

I understand this may be about permissions, but the integration user for this integration is a Sys Admin. I also searched for the Id noted and can't find it in our Setup. I looked for other processes or workflows that may be doing something and it doesn't appear to be the problem. Any ideas?! thanks so much!

-Brenna
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
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
I want only one value from the json but i'm getting all the values how can i stop iteration or is there any way to show only one row like keeping size please help to find the solution

Thank you in Advance,

<tbody>
                        <aura:iteration items="{!v.jsonValues}" var="item" indexVar="rowIndex">  
                            <tr data-data="{!rowIndex}">
                                <td role="gridcell" tabindex="-1" data-label="Record Type Name">                            
                                    <span class="slds-grid slds-grid_align-spread">
                                        <div class="slds-truncate">                                        
                                            <span class="slds-truncate">{!item.firstName}</span>
                                        </div>
                                    </span>                            
                                </td>
                            </tr>
                        </aura:iteration>
                    </tbody>

Original Output:-
      Ramesh
      Suresh
      Rakesh

Expected Output:-
    Ramesh
  • August 25, 2021
  • Like
  • 1
The AccountTeamMember widget (Lightning Component) displays the Role API Name instead of the Role Label.

How do i change the lightning component so it will display the role label instead of the role API name?

Here is the component code:
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="AccountTeamHelper">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="TeamMembers" type="AccountTeamMember[]" /> 	  
    <lightning:card title="Account Team" iconName="custom:custom103">
        <div style="margin: 0px 5px">
            <p class="slds-p-horizontal_small">
                <aura:if isTrue="{!v.TeamMembers.length > 0}">
                <aura:iteration items="{!v.TeamMembers}" var="member">
                    <!-- <span style="display: inline-block; margin: 3px;"><lightning:avatar src="{!member.User.SmallPhotoUrl}" alternativeText="(Avatar)" fallbackIconName="standard:avatar" variant="circle" /></span> -->
                    <span><a href="{!'/one/one.app#/sObject/' + member.User.Id + '/view'}">{!member.User.FirstName}&nbsp;{!member.User.LastName}</a> - {!member.TeamMemberRole}</span><br/>
                </aura:iteration>
                <aura:set attribute="else">
                    No account team members have been assigned to this account.
                </aura:set>
                </aura:if>
        	</p>
        </div>
    </lightning:card>
</aura:component>

 
public class Api4 {
   public static void api(){
    Http h = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('https://demo1691926.mockable.io/Api12');
req.setHeader('Content-Type', 'application/json');
HttpResponse response = h.send(req);
system.debug('response  : '+response.getBody());
String json1= response.getBody();

       
DesearlizingJson desearilize1=(DesearlizingJson) Json.deserialize(json1,DesearlizingJson.Class);
System.debug('Phone is ' +desearilize1.phone);
System.debug('name is ' +desearilize1.Name);
System.debug('mobile is ' +desearilize1.MobilePhone);
      
 //trying to update deserialized json       
list<contact> lcon= new list<contact>();

List<contact> lcon1 = [select id,Name,MobilePhone,Phone from contact where LastName=:desearilize1.Name];
       for(contact c1:lcon1){
        
        c1.Phone=desearilize1.phone;
           lcon.add(c1);}
        update c1;
       
  }
}

Wrapper class

public class DesearlizingJson {
    public Decimal Phone;
    public String Name;
    public Decimal MobilePhone;

}

Thanks in Advance
if(requestId != null) {
        
               List<GLOBAL_Request__c> requestObj = [select id, business_unit__c, recordtype.developername from GLOBAL_Request__c where id=:requestId AND recordtype.developername = 'Send_Survey' Limit 1];
            if (requestObj != null){        
            List<User> usrRec =[select id, NT_Login_Name__c from User where id=:UserInfo.getUserId() And NT_Login_Name__c != null Limit 1];
                    if(usrRec != null){
                    List<Contact> contactRec = [select id, contactRec.NT_Login_Name__c from contact where NT_Login_Name__c=:usrRec.NT_Login_Name__c ORDER by LastModifiedDate DESC Limit 1];         
                        if (contactRec != null){
                          List<Participant__c> participantRec = [select Id, Name,Survey_Taken_Date__c from Participant__c where Participant__c=:contactRec.Id AND Request__c=:requestObj.Id ORDER by CreatedDate DESC LIMIT 1];
                            if(participantRec != null && participantRec.Survey_Taken_Date__c == null){
                                ParticipantId = participantRec.Id;
                                contactId = contactRec.Id;
                                requestId = requestObj.Id;
                                Participant__c updateSurveyTakenDate = new Participant__c(id = ParticipantId, Survey_Taken_Date__c = System.now());            
                                       upsert updateSurveyTakenDate;  
                            } else if(participantRec != null && participantRec.Survey_Taken_Date__c != null){
                                Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, System.Label.LABS_SF_You_have_already_taken_this_survey));
                                return false;
                            } else {
                                Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, System.Label.LABS_SF_Participant_Not_Part_Of_This_Pool));                    
                                 return false;
                            }
                        }
                    }
            }
        }
  
And I am getting the following error.


1.Variable does not exist: NT_Login_Name__c
2.Variable does not exist: Id
3.Variable does not exist: Survey_Taken_Date__c
4.Variable does not exist: Id
5.Variable does not exist: Survey_Taken_Date__c

Will appreciate your help.

Thanks,
TM
      
Hello- I'm writing a scheduled Apex class that grabs all Accounts that are listed as 'Active' in a custom field, find's the most recent closed won Opportunity and passes a value from a lookup field on that opp back to another lookup on the Account. The class isn't flagging any problems for me, but throws an error when it tries to run upon being scheduled.

The error seems to indicate that it couldn't find any records to update. I verified that there are records that meet the criteria, and when I run the SOQL query in isolation it finds those records. When I try to debug it in the Execute Annonymous window, it also doesn't return any system.debug messages. I appreciate any help figuring out where I'm going wrong! 
The error:
Sandbox

Apex script unhandled exception by user/organization: 0053i000002hKdg/00D1g0000002qa7
Source organization: 00D3i000000ttF8 (null)
Scheduled job 'Se Update2' threw unhandled exception.

caused by: System.QueryException: List has no rows for assignment to SObject

Class.UpdateSEOnAccount.execute: line 8, column 1
The Apex Class:
global class UpdateSEOnAccount implements Schedulable{
    global void execute (SchedulableContext ctx){
        UpdateSE();
    }
    public void UpdateSE(){
        List<Account> Actlst = new list<account>();
        for(Account a : [SELECT Id FROM Account WHERE Customer_Status__c = 'Active']){    
             a.Sales_Engineer__c = [SELECT Id, SE__c, AccountId 
                          FROM Opportunity 
                          WHERE AccountId = : a.id AND StageName = 'Closed Won'
                          ORDER BY CloseDate DESC LIMIT 1].SE__c;
           system.debug('a is '+ a.Id);
           if(a.SE__c <> NULL){
           Actlst.add(a);
           }
            system.debug('size of list is '+ Actlst.size());
        }
        if(Actlst.size()>0){
            update Actlst;
        }
    }
}


 
Unexpectedly werid behavior, I deleted an opportunity on frontend and queried for the deleted opportunity id, the record row was completed deleted from the opportunity table. When I restored the record from Recycle Bin, the row was back. I was expecting instead of record row completely disappearing from the table, the IsDeleted field would be updated. 

 
Hi everyone, can someonehelp how to write testclass for the below class

@RestResource(urlmapping='/v1/Accountmanager/')
global class Integration_Example {
@HttpGet
    //which is used to get the records or query the records
    global static Account doget(){
        //intilaise the object
       Account a=new Account();
        //get the req parameters in map
        map<string,string> paramsmap=Restcontext.request.params;
        //get the id
        string accid=paramsmap.get('Id');
        //query the records
        a=[select id ,name from Account where id=:accid];
        return a;
    }
    @HttpDelete
    global static Account doDelete(){
       RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String AccNumber = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE AccountNumber = :AccNumber ];
        delete result;
        return result;
    }
   @Httppost
    //post method is used to create the record
    global static Account docreate(string name){
        Account a = new Account(name=name);
        insert a;
        return a;
    }
     @Httpput
    global static Account doupdate(string name){
        map<string,string> paramsmap=Restcontext.request.params;
        //get the id
        string accid=paramsmap.get('Id'); 
        Account a = new Account(name=name, id=accid);
        update a;
        return a;
    }
}

Thanks in Advance
  • August 17, 2021
  • Like
  • 1
Hi,

Dear folks,

Here is what i want to do and thankfully was able to get answer using thread below with List
https://developer.salesforce.com/forums/ForumsMain?id=9062I000000BjjoQAC
,but now i am rewriting the same code using Map,but am getting error as 
 
Method does not exist or incorrect signature: void get(String) from the type Map
Here is what the end goal is 
 
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:

Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
Transform #2: 17 ➝ 1 + 7 ➝ 8

Here is code with Map
public class SDASMapConvert {
    

    
    
public static Integer returnInteger(String z, integer k){
        Integer retInt;
        String key = 'abcdefghijklmnopqrstuvwxyz';

        List<String>myAlphabets = z.split('');
        Map<String, String> myMap = new Map<String, String>();
        String strarr = '';

       for (integer i = 0; i < myAlphabets.size(); i += 2) {
        myMap.put(myAlphabets[i], myAlphabets[i + 1]);
    }

    for (String s : myMap.keySet()) {
        System.debug(s + ' is ' + map.get(s));
        strarr += string.valueOf(s);
    }
        
        system.debug('strarr --> ' + strarr);
        String s = '';
        for(integer i = 0; i < k ; i++){
            system.debug(' strarr --> ' + strarr);
            Integer total = 0;
            for(String s1 : strarr.split('')){
                total += integer.valueOf(s1);
            }
            system.debug(' total --> ' + total);
            strarr = string.valueOf(total);
        }
        
        system.debug(' ************* ' + strarr);
        if(!string.isEmpty(strarr))
            retInt = integer.valueOf(strarr);
        
        system.debug(' ************* ' + retInt);
        
        return retInt;
    }
    


}

Regards
Fiona
Dear folks,

Here is what i want to do
 
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:

Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
Transform #2: 17 ➝ 1 + 7 ➝ 8



Hence ,Wrote a apex class for To  convert string into an integer by replacing each letter with its position in the alphabet,but it doesnt seems working,error i get on Anonymus Console Window for below command
is 
Line: 14, Column: 1
System.TypeException: Invalid integer: a
Here is anonymous code
SDSAfterConvert.returnInteger();

Here is apex code
 
public class SDSAfterConvert {
    
    
public static List<Integer> returnInteger(){


List<Integer> inputList = new List<Integer>();
             
String[] myAlphabets = new String[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g'};
 
for (String s1 : myAlphabets) {
   
    System.debug(s1);
    Integer d = integer.ValueOf(s1);
    inputList.add(d);
}
        
return inputList;
             
}
    
}



Regards,
Fiona​​​​​​​
 
I'm using a Lightning Component to update a field called "Observations__c" in Account Object.
User-added image

It's working fine, but when I try to use it inside another component, I receive the following error:

EXCEPTION_THROWN [9]|System.NullPointerException: Attempted to upsert a null list

Component: 

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

<aura:handler name="init" action="{!c.init}" value="{!this}" />
<aura:attribute name="accounts" type="Account" />
<aura:attribute name="recordId" type="Id" />

<ltng:require styles="/resource/slds103/assets/styles/salesforce-lightning-design-system.min.css"/>

 <form>
    <ui:inputText aura:id="client"
                  label="{!$ObjectType.Account.fields.Observations__c.Label}"
                  class="form-control"
                  value="{!v.accounts.Observations__c}"
                  placeholder="Insira, caso necessário, comentários adicionais"
    />
    <br />
    <ui:button class="form-control" aura:id="button" label="Anexar observação" press="{!c.save}"/>
</form>

 </aura:component>

Controller js:
({
init : function(component, event, helper) {
    var accId = component.get("v.recordId");
    var action = component.get("c.getAcct");

    action.setParams({
        "accountId": component.get("v.recordId")
    });

    action.setCallback(this, function(data) {
        component.set("v.accounts", data.getReturnValue());
    });

    $A.enqueueAction(action);
}, 
save : function(component, event, helper) {

    var action = component.get("c.saveAcct");
    var accounts = component.get("v.accounts");

    action.setParams({"act": accounts});
    $A.enqueueAction(action);

    console.log('save ran');

}
})

Apex Controller:
public class getAccount {
    @AuraEnabled 
    public static Account getAcct(Id accountId){
        return (Account) Database.query( ' SELECT Name, Observations__c FROM Account WHERE Id =: accountId LIMIT 1 ' )[0];
    }

    @AuraEnabled 
    public static Account saveAcct(Account act){
        upsert act;
        return act;
    }  
}

I'm calling <c:sparkAccount/> in my second component, but it is not working.
User-added image

What am I doing wrong?