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


  • Chatter
    Feed
  • 502
    Best Answers
  • 4
    Likes Received
  • 54
    Likes Given
  • 15
    Questions
  • 1657
    Replies
Hi,
I am trying to update a record via API request, I have added everything as needed but I always end up getting a 404 error.
User-added imageI am getting the Object ID value from here:
User-added imageAny help is highly appreciated. 

Thank you. 
Hi everyone, I'm  new on LWC . and  I'm doing  this example to generate a PDF https://santanuboral.blogspot.com/2020/10/lwc-generate-pdf.html
everything works fine  but now Im trying to save the PDF to  the  correspondet contact depending on the ID,  any idea of how I can do that?   this is my code as we can see Im hard coding the id 

 
public with sharing class DisplayRichTextHelper {
    @AuraEnabled
public static Attachment generatePDF(String txtValue){

        Pagereference pg = Page.renderAsPDF;
        pg.getParameters().put('displayText', txtValue);

        Contact con = new Contact(Id='0035f000008RNWCAA4');

        Attachment objAttachment = new Attachment();
        objAttachment.Name = 'J2S.pdf';
        objAttachment.ParentId = con.Id;
        objAttachment.Body = pg.getContentaspdf();
        objAttachment.IsPrivate = false;
        insert objAttachment;
        return objAttachment;
    }
}
 

And i want to change for some like this:
 ApexPages.currentPage().getParameters().get('id');
Fairly new to Salesforce and am trying to wrap my head around the system as well as importing data. I don't understand why fields don't match up between accounts and contacts. E.g. contact has a field for "mobile" while account has "phone" and "phone other" and no field for "mobile" or "cell". Also contact has "street 1", "street 2" address while account has "mailing address" and "shipping address". Why don't the fields match up between these two objects? And would it make sense to have them match?

Thanks. 
  • December 28, 2022
  • Like
  • 1
Class Controller:
public with sharing class controllerquoteVisual {
    
    public String title {get;set;}
    public Quote quote {get;set;}
    public List<quoteLineItem> qliList {get;set;}
    //public List<Product2> products {get; set;}
    
    //Capturar Nombre de familia y lista de productos
    public Map<String,List<ObjectWrapper>> mapFamily {get;set;}
    //public Map<String,List<QuoteLineItem>> mapFamilyqli {get;set;}
    //Captutar Nombre de familia y recuento de Productos que se mostrarán
    public Map<String, Integer> FamilyCountMap{get;set;}
	//Capturar Lista de nombres de familia de productos 
    public List<String> FamilyList {get;set;}
    //ProductList o products ya con los productos que se requieren mostrar
    
    public controllerquoteVisual(){
        
        Id id = ApexPages.currentPage().getParameters().get('id');
        
        //Obtener quote mediante el Id que arroja la visualforce desde quote
        quote = [SELECT Id, Name, TotalPrice, GrandTotal, ExpirationDate, AccountId, Total_Hours__c, OpportunityId, QuoteNumber   
                FROM quote WHERE Id=:id LIMIT 1];
        
        Opportunity opportunity = [SELECT Name FROM Opportunity WHERE Id=:quote.OpportunityId LIMIT 1];
        
        title = opportunity.Name.split('\\|')[0] + opportunity.Name.split('\\|')[1];
        
        Apexpages.currentPage().getHeaders().put('content-disposition', 'inline; filename='+title+ ' - ' +quote.QuoteNumber );
        
        //Obtener lista de quoteLineItems de la actual quote
        qliList = [SELECT Id, Product2Id, Quantity  
                    FROM quoteLineItem WHERE quoteId=:Id];
       
        ///////////////////////////////////////////////
        //Separar productos por tipo de familia 
        mapFamily = new Map<String, List<ObjectWrapper>>(); 
        FamilyCountMap = new Map<String, Integer>();
        FamilyList = new List<String>();
        
        List<quoteLineItem> finalqliList = new List<QuoteLineItem>();
        finalqliList = qliList;
        
        //Agrupar por nombre de familia y preparar los map
        for(QuoteLineItem qq: finalqliList){
            Product2 famObj = [SELECT Id, Name, Family, Description
                   FROM Product2 WHERE Id=:qq.Product2Id];
            if(famObj.Family == null){
                famObj.Family= 'Sin clasificación';
            }
            
            //List<QuoteLineItem> qq = qliList;
            List<ObjectWrapper> proList = new List<ObjectWrapper>();
            //Verificar si el map ya contiene el mismo nombre por familia
            if(mapFamily.containsKey(famObj.Family)){
            	//Recuperar lista de productos existentes
            	proList = mapFamily.get(famObj.Family);
            	//Meter el nuevo producto a la lista
                proList.add(new ObjectWrapper(qq, famObj));
                    
                mapFamily.put(famObj.Family, proList);
                    
                //Almacenar filas por nombre de familia
                FamilyCountMap.put(famObj.Family, proList.size());
            }
            else{
            	//crear nuevo map del nombre de familia //.fammily,name,etc
                //proList.add(famObj);
                proList.add(new ObjectWrapper(qq, famObj));
                mapFamily.put(famObj.Family, proList); 
                    
                //Almacenar filas por nombre de familia
                FamilyCountMap.put(famObj.Family, proList.size());
            }
        	FamilyList = new List<String>(mapFamily.keySet());
    	}
        
    }
    
    public class ObjectWrapper{
        //Campos QuoteLineItems
        //Public Id QliId{get;set;}
        Public Decimal Quantity{get;set;}
        
        //Campos Producto
        Public String Name{get;set;}
        Public String Family{get;set;}
        Public String Description{get;set;}
        
        public ObjectWrapper(QuoteLineItem ql, Product2 pr){
            //this.QliId = ql.Id;
            this.Quantity = ql.Quantity;
            
            this.Name = pr.Name;
            this.Family = pr.Family;
            this.Description = pr.Description;
        }  
    }
}

Test Class (68%, wrapper class is missing)
@isTest
public class TestControllerquoteVisual{
	@isTest
    static void testControllerVFP(){
        
        Pricebook2 pb = new Pricebook2(Name = 'Standard Price Book', 
                                       Description = 'Price Book Products', IsActive = true );
        insert pb;
        
        Product2 prod = new Product2(Name = 'Test Product', Description = 'Descripción Test', 
                                     Family = 'Salesforce Service Cloud', IsActive = true);
        insert prod;
        
        List<Pricebook2> standardPbList = [select id, name, isActive from Pricebook2 
                                           where IsStandard = true ];
 
    	List<PricebookEntry> listPriceBook = new List<PricebookEntry>();
     	for(Pricebook2 p : standardPbList ){
      		PricebookEntry pbe = New PricebookEntry ();
      		pbe = new PricebookEntry(Pricebook2Id = p.Id, Product2Id = prod.Id, 
                                     UnitPrice = 10000, IsActive = true, UseStandardPrice = false);
       		listPriceBook.add(pbe);
     	}
        insert listPriceBook;
        
        Opportunity opp = new Opportunity(Name = 'Test Opportunity', 
                                          StageName = 'Discovery', Product_Families__c='Salesforce Service Cloud' ,CloseDate = system.today());
        insert opp;
        
        Quote quttest = new Quote (Name = 'Quote Test' , OpportunityId = opp.id , Pricebook2Id = pb.id );
        insert quttest;
        
        List<QuoteLineItem> listval = new List<QuoteLineItem>();
        for(PricebookEntry pricebook : listPriceBook){
            QuoteLineItem qutlineitemtest = new QuoteLineItem ();
            qutlineitemtest = new QuoteLineItem(QuoteId = quttest.id, Quantity = 3.00,UnitPrice = 12, PricebookEntryId = pricebook.id);
            
            listval.add(qutlineitemtest);
        }
        insert listval;    
            
        QuoteLineItem qlitem = new QuoteLineItem(Quantity = 3.00, UnitPrice = 12 );
        
        
        Test.startTest();
            ApexPages.currentPage().getParameters().put('id', String.valueOf(quttest.Id));
            controllerquoteVisual controllerVfp= new controllerquoteVisual();
            //controllerVfp = new controllerquoteVisual();
        
            controllerquoteVisual.ObjectWrapper wrapper = new controllerquoteVisual.ObjectWrapper(qlitem, prod);
            
            wrapper.Quantity = 3.00;
                
            wrapper.Name = prod.Name;
            wrapper.Description = prod.Description;
            wrapper.Family = prod.Family;
        
        Test.stopTest();
        
    }

}

 
I am struggleing understanding how to write test units for this class. 
 
//@RestResource(urlMapping='/Google/*') is used to tell the class that it is a REST resource used for POST GET etc
@RestResource(urlMapping='/Google/*')
global with sharing class GoogleWebHookListener {
    //HttpPost tells the method that it will be a POST method
    @HttpPost
    global static void handlePost() {
        
        //set up varibles for the Lead
        String name;
        String phone;
        String email;
        String postCode;
        String firstName;
        String lastName;
        
        //try to do the JSON deserialization and Lead Creation
        //******EXAMPLE JSON AT BOTTOM*****
        try
        {
            // This gets the body of the webhook makes the body a string and sets the string to the variable 'jsonString'
            String jsonString = RestContext.request.requestBody.toString();
            //This deserializes the JSON based on the the properties setup in the Class GoogleJsonLeadExample
            GoogleJsonLeadExample g = (GoogleJsonLeadExample)JSON.deserialize(jsonString, GoogleJsonLeadExample.class);
            
            //This tests the JSON to see if it is legit.
            if(g.google_key == ''){
                
                //This loops through the JSON array set up in the Class GoogleJsonLeadExample
                
               for(GoogleJsonLeadExample.userData d : g.user_column_data)
               {
                   if(d.column_name == 'Full Name')
                   {
                       //The JSON has Full Name, this breaks Full Name into First and Last Names
                        name = d.string_value;
                        List<String> names = name.split(' ');
                       	firstName = names[0];
                        lastName = names[1];
                           
                   }
                   if(d.column_name == 'User Phone')
                   {
                        phone = d.string_value;
                   }
                   if(d.column_name == 'User Email')
                   {
                        email = d.string_value;
                   }
                   if(d.column_name == 'Postal Code')
                   {
                       postCode = d.string_value;
                   }
               }
              
                //This creates the Lead                 
            Lead detail = new Lead();
            detail.LastName = lastName;
            detail.FirstName = firstName;
            detail.Phone = phone;
            detail.Company = name;
            detail.Email = email;
            detail.OwnerId = '0051Q00000GrANL'; // This Id is the user Hubspot.
            insert detail;
           
            }
                                        
        }
        catch (DMLException e)
        {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }

}

 
I am creating an attachment, but I want to check if it does not exist with the same name.
a = (Opportunity)standardPageController.getRecord();
 PageReference pdfPage = new PageReference('/apex/myPage');
        Opportunity b =[select Id, Name Invoice_Number__c from Opportunity where Id=:a.id];
        Blob pdfBlob;

Attachment attach = new Attachment(
        parentId = a.Id,
        Name = b.Name +'.pdf', 
        body = pdfBlob); //create the attachment object
        insert attach;

 
Hi, I'm trying to use a standardcontroller in the Visualforce page in order to use it in a custom button. But I'm having this error:
Unknown constructor 'CarController.CarController(ApexPages.StandardController controller)'
I believe that I need to add something to the controller, but I could not find a solution that worked for me(I tried all the solutions that I found online)...

So, this is the code:
<apex:page  standardController="Case" extensions="CarController" lightningStylesheets="true" title="test">
    <apex:form>
        <apex:pageMessages/>
        <apex:pageBlock >    
            <apex:pageBlockSection columns="2">
                <apex:inputField value="{!abc.Name__c}"/> 
                <apex:inputField value="{!abc.License_Number__c}"/>
                <apex:inputField value="{!abc.Manufacturer__c}"/>
            </apex:pageBlockSection>
            
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Save" action="{!save}" styleClass="slds-button slds-button_brand"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
public class CarController{

    public Car__c abc {Get;Set;}

    public CarController() {     
        abc = new Car__c();
    }
    
    public PageReference save(){
    	try{
        	INSERT abc;
        }
        catch (exception e){
            
        }
        return null;
    }
    
}
P.S. I'm not a developer, just try to learn in order to get there one day... so I'll be happy to understand what is missing.

Thanks!



 
The formula field needs to function like this.
It looks at one PL field (ChempaxDB), and then look at a 2nd PL field, and based on the vales of the 2 PL fields, populate with a specific value.
An example would be, (1st PL Field) ChempaxDB = CASE, and (2nd PL Field) Division = 01, the Divisoin Name Field (this is the formula field) populates with "01 - Chemical Raw Materials".
This is what I have come up with but can;t get the formula to work:

OR (IF ( ISPICKVAL( Chempax_DB__c , "CASE"),
CASE( Division__c  ,
"01", "01 - CHEMICAL RAW MATERIALS",
"10", "10 - Azelis CASE, LLC - Garland",
"15", "15 - FOOD PRODUCTS",
"19", "19 - Azelis CASE Garland Direct",
"20", "20 - Azelis CASE - Houston",
"21", "21 - Azelis CASE Bulk",
"29", "29 - Azelis CASE Houston - Direct",
"30", "30 - Azelis CASE - Phoenix",
"31", "31 - Azelis CASE Denver",
"39", "39 - Azelis CASE Direct - Phoenix",
"40", "40 - Azelis Americas CASE, LLC",
"45", "45 - INTERCO ORDERS/TRANSFERS CASE",
"50", "50 - Azelis Americas CASE, LLC",
"51", "51 - Azelis Construction Solutions",
"52", "52 - Azelis CASE Fulton",
"54", "54 - CASE HOUSE ACCOUNTS",
"55", "55 - Azelis CASE, LLC - Atlanta",
"56", "56 - Azelis CASE, LLC - Greenville",
"57", "57 - Azelis CASE, LLC - Meredith",
"58", "58 - FINE INGREDIENTS GROUP",
"59", "59 - Ribelin Atlanta - Direct",
"60", "60 - Azelis CASE, LLC- Orlando",
"61", "61 - Azelis CASE, LLC - Whitaker",
"69", "69 - Azelis CASE Orlando - Direct",
"70", "70 - GMZ - SW",
"88", "88 - DL Trading Duty Drawback",
"89", "89 - Azelis CASE, LLC - IC",
"90", "90 - Azelis CASE, LLC - IC",
"91", "91 - ACS - Intercompany",
"92", "92 - Azelis CASE, LLC - IC",
"94", "94 - GMZ SW COMMISSIONS",
"95", "95 - OPERATIONS",
"96", "96 - COMMISSIONS - CHEMICAL",
"97", "97 - COMMISSIONS - CONTAINERS",
"98", "98 - COMMISSIONS",
"99", "99 - Azelis CASE, LLC - Supplier",
                    null),  

IF ( ISPICKVAL( Chempax_DB__c ,"DeWolf" ),
CASE( Division__c ,
"10", "10 - DeWolf - Industrial Line HI&I",
"20", "20 - DeWolf - Personal Care Line",
"23", "23 - Dewolf - Color Cosmetics",
"89", "89 - DeWolf Intercompany Sales",
null),            

IF ( ISPICKVAL( Chempax_DB__c ,"Glenn" ),
CASE( Division__c ,
"03", "03 - Cosmetic",
"04", "04 - Reseller",
"06", "06 - CAS Number"
"10", "10 - Industrial and Institutional",
"20", "20 - Personal Care",
"23", "23 - Color Cosmectics",
"89", "89 - Glenn Intercompany Sales",
"90", "90 - Glenn Sales To DeWolf",
null),
                
IF ( ISPICKVAL( Chempax_DB__c ,"Marcor" ),
CASE( Division__c ,
"30", "30 - KDG CORPORATE",
"80", "80 - MARCOR DEVELOPMENT",
"89", "89 - INTERCOMPANY SALES",
null),
                
IF ( ISPICKVAL( Chempax_DB__c ,"Monson" ),
CASE( Division__c ,
"01", "01 - INDUSTRIAL SPECIALTIES",
"05", "05 - PIGMENTS AND PLASTICIZERS
"10", "10 - GENERAL INDUSTRIAL",
"15", "15 - FINE INGREDIENTS",
"20", "20 - NON-TOXIC",
"24", "24 - FOCUSED INDUSTRIAL",
"51", "51 - MONSON CO CHEMICAL DIV",
"52", "52 - MONSON CO LMW DIVISION",
"61", "61 - COMMISSION PRODUCTS ISG",
"62", "62 - GIG COMMISSION PRODUCTS",
"63", "63 - PWT COMMISSIONS",
"64", "64 - COMMISSIONS - P&P",
"70", "70 - AUTOMOTIVE/FREEZE PROTECT",
"75", "75 - ICE MELTERS",
"88", "88 - FRT CLAIMS FOR CARRIERS",
"89", "89 - INTERCOMPANY",
"95", "95 - OPERATIONS, SERV WHS, MISC",
"98", "98 - MONSON COMPANIES FREIGHT",
"99", "99 - COMMISSIONS RECEIVABLE",
null),
                    
IF ( ISPICKVAL( Chempax_DB__c ,"Ross" ),
CASE( Division__c ,
"10", "10 - Ross Organic",
"20", "20 - Ross - Personal Care Line",
"23", "23 - Color Cosmetics",
"89", "89 - Ross Intercompany Sales",
null),
null))

Thank you,
Shawn

Hello, I have build a task datatable component and added the Who.Name as a column. It is working fine when the Who.Name field has content in it, otherwise I get an error message when leaving the field empty. Could you give me a solution for it?

User-added image


My code:

APEX
//ÜBERFÄLLIG - Abfrage Tasks, wo das Activity Date abgelaufen und der Status "Not Completed" ist//
@AuraEnabled
public static List<Task> loadTasks(Id recordId){
    string userId = UserInfo.getUserId();
    return[SELECT Subject, Who.Name, WhoId, ActivityDate, Status FROM Task WHERE ActivityDate< TODAY AND OwnerId=:userId AND Status !='Completed'];
}


JS
 
component.set('v.mycolumns', [
            {label: 'Thema', fieldName: 'SubjectName', type: 'url',
            typeAttributes: {label: { fieldName: 'Subject' }, target: '_blank'}},
                 {label: 'Name', fieldName: 'whoName', type: 'text',
            typeAttributes: {label: { fieldName: 'Who.Name' }, target: '_blank'}},
        ]);
        var action = component.get("c.loadTasks");
            action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var records =response.getReturnValue();
                records.forEach(function(record){
                   
                    record.SubjectName = '/'+record.Id;
                    record.whoName = record.Who.Name
                });
                component.set("v.tasks", records);
            }
        });
        $A.enqueueAction(action);

 
I tried this code but not working. Can any one help me on this?

trigger Contactduplicaterecord on Contact (before insert, before update) 
{
  set<string> EmaPho=new set<string>();
    
    for(Contact Con:trigger.new)
    {
        EmaPho.add(Con.Phone);
        EmaPho.add(Con.Email);
     }
    if(EmaPho.size()>0 )
    {
    List<Contact> lstContact=[Select Phone,Email from Contact where Phone in:EmaPho or Email in:EmaPho];
    Map<string, Contact> MapEmaPhowisecontact=new Map<string, Contact>();
    
    for(Contact Con:lstContact)
    {
        MapEmaPhowisecontact.put(Con.Phone, Con);
        MapEmaPhowisecontact.put(Con.Email, Con);
    }
    for(Contact Con:trigger.new)
    {
        if(MapEmaPhowisecontact.containsKey(Con.Phone))
        {
            Con.Phone.addError('Phone Number already Exist');
        }
        if(MapEmaPhowisecontact.containsKey(Con.Email))
        {
            Con.Email.addError('Email already Exist');
        }
    }
    }
}
Apex Class
.........................
public class NewAndExistingController {
    public Case Casea { get; public set; }
    public NewAndExistingController() {
        Id id = ApexPages.currentPage().getParameters().get('id');
        casea = (id == null) ? new Case() : 
            [SELECT AccountId,Description,Status,Subject FROM Case WHERE Id = :id];
    }
    public PageReference save() {
        try {
            insert(Casea);
        } catch(System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }
        PageReference redirectSuccess = new ApexPages.StandardController(Casea).view();
        return (redirectSuccess);
    }
     public PageReference cancel() {
        try {
            insert(Casea);
        } catch(System.DMLException e) {
            ApexPages.addMessages(e);
            return null;
        }
        PageReference redirectSuccess = new ApexPages.StandardController(Casea).view();
        return (redirectSuccess);
    }}
...............................................................................................
Test class
..............
@isTest
public class TestClass {
    @isTest
    public static void testMethod1(){

        NewAndExistingController nEC = new NewAndExistingController();
        nEC.save();
        nEC.cancel();
        
        
    }
      
}
I have this error when save text:


Insert failed. First exception on row 0 with id 0035f000008gFMYAA2; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Error is in expression '{!save}' in component <apex:commandButton> in page mensaje: Class.mensajeController.save: line 25, column 1
An unexpected error has occurred. Your development organization has been notified.

User-added image
<apex:page controller="mensajeController"  >
<apex:form >
 <apex:pageBlock >
 <apex:pageBlockButtons >
   <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="test"/>
  </apex:pageBlockButtons>
  <apex:pageBlockTable value="{!contacts}" var="c" >
   <apex:column >
    <apex:inputCheckbox value="{!c.selected}"/>
   </apex:column>
    <apex:column value="{!c.con.Name}" />
    <apex:column value="{!c.con.Email}" />
    <apex:column value="{!c.con.Phone}" />
  </apex:pageBlockTable>
 </apex:pageBlock>
    <apex:pageBlock >
        <!--<p>Current description: {!mensajeContenido}</p>-->
        <p>Current description: {!oMessageDescription}</p>
        <p>Change description to:</p> 
        <!--<apex:inputTextarea id="newDesc" value="{!mensajeContenido}"/><p/>-->
        <apex:inputTextarea id="newDesc" value="{!oMessageDescription}"/><p/>
        
        <apex:commandButton value="Save" action="{!save}"/>
    </apex:pageBlock>
 <apex:pageBlock id="test">
  Total No of Selected Records :<apex:outputText value="{!value }"/>
  <apex:pageBlockTable value="{!SelectedContacts}" var="c" >
    <apex:column value="{!c.Name}" />
    <apex:column value="{!c.Email}" />
    <apex:column value="{!c.Phone}" />
  </apex:pageBlockTable>
 </apex:pageBlock>
 </apex:form>
</apex:page>
User-added image
I’m saving a text in a vf
but don’t save that text

I have to do this: 
 enter a description of the message and finally be able to save

 when saving what the controller must do is create a message object, with the description that we have entered, for each of the selected accounts
trigger sendMailToContactTrigger on Contact (after insert) {
    set<String> emailSet = new Set<String>();
    EmailTemplate temp=[Select id,Body from EmailTemplate where name='contact text email template'];
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    if(Trigger.IsAfter && Trigger.IsInsert){
        for(Contact Con : Trigger.new){
            if(Con.Email != Null){
                 Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
                singleMail.setHtmlBody(temp.Body);
                singleMail.setToAddresses(new List<String>{con.Email});
                singleMail.setTargetObjectId(con.Id);
                singleMail.setTemplateId(temp.Id);
                emails.add(singleMail);
            }
        }
    }
    if(emails.Size()>0){
    Messaging.sendEmail(emails);
    }
}
I have the following validation rule that is working when Primary Partner field has a value it is showing error to update Partner Detail field, however the error is also being given anytime the Opportunity is edited. I need the formula below to only show error when the Primary Technology Partner field has a value and the Partner Type field is blank. Does anyone have any suggestions on how to make this error show just based off the two fields in formula and not when the opportunity is edited. Thanks.
 
AND(
OR(
INCLUDES(Primary_Technology_Partner_Involved__c, "Achilles"),
INCLUDES(Primary_Technology_Partner_Involved__c, "Adopt - Pendo"),
INCLUDES(Primary_Technology_Partner_Involved__c, "Bureau Van Dijk"),
INCLUDES(Primary_Technology_Partner_Involved__c, "Commerce Decisions"),
ISBLANK(TEXT(Partner_Type__c))),
OR(
$Profile.Name = 'Jaggaer Sales Partner Group',
$Profile.Name = 'Jaggaer Sales',
$Profile.Name = 'Sales Salesforce Super User' ))
String baseURL =  'https://' + System.URL.getSalesforceBaseUrl().getHost();
                String queryStr = 'SELECT+NumLinesCovered,ApexClassOrTriggerId,ApexClassOrTrigger.Name,NumLinesUncovered,Coverage+FROM+ApexCodeCoverageAggregate';
                String ENDPOINT = baseURL + '/services/data/v40.0/tooling/';
               
                HttpRequest req = new HttpRequest();
                req.setEndpoint(ENDPOINT + 'query/?q=' + queryStr);
               
                req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID() );
                req.setHeader('Content-Type', 'application/json');
                req.setMethod('GET');
                req.setTimeout(80000);
                system.debug('end'+req);
            Http http = new Http();
            HTTPResponse res = http.send(req);
           


getting error  [{"message" :"This session is not valid for use with the REST API","errorCode":"INVALID_SESSION_ID"}] while calling tooling api  from LWC


I have also used Connected app and named credential its not working while called from lwc. but, working as expected while I call it using annoynomous apex  

 
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

 
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.
Hi,
I am trying to update a record via API request, I have added everything as needed but I always end up getting a 404 error.
User-added imageI am getting the Object ID value from here:
User-added imageAny help is highly appreciated. 

Thank you. 
Hi there, I'm seeing some solutions to my question, but they're not exactly what I'm looking for. I am trying to convert the entry on a currency field to a text formula field. The below formula gets me the closest to what I need, but it seems to eliminate decimal places. i.e. $1.00 changes to $1. Is it possible to retain the decimals without rounding? Thanks in advance!

"$"&
 TEXT( UnitPrice )
I have an object that has a long text field. When I add the field to the page layout, the text gets truncated. I am using standard salesforce functionality. So I would like to know what I need to do next.

Please find images of the salesforce object and the lightning record page.

salesforce object.

page layout
Hi everyone, I'm  new on LWC . and  I'm doing  this example to generate a PDF https://santanuboral.blogspot.com/2020/10/lwc-generate-pdf.html
everything works fine  but now Im trying to save the PDF to  the  correspondet contact depending on the ID,  any idea of how I can do that?   this is my code as we can see Im hard coding the id 

 
public with sharing class DisplayRichTextHelper {
    @AuraEnabled
public static Attachment generatePDF(String txtValue){

        Pagereference pg = Page.renderAsPDF;
        pg.getParameters().put('displayText', txtValue);

        Contact con = new Contact(Id='0035f000008RNWCAA4');

        Attachment objAttachment = new Attachment();
        objAttachment.Name = 'J2S.pdf';
        objAttachment.ParentId = con.Id;
        objAttachment.Body = pg.getContentaspdf();
        objAttachment.IsPrivate = false;
        insert objAttachment;
        return objAttachment;
    }
}
 

And i want to change for some like this:
 ApexPages.currentPage().getParameters().get('id');
Hi everyone,

I have a formula field that aims to return the text - "Progressing Towards Expectations", "Meeting Expectation", or "Exceeding Expectations".

This field is dependant on two things - the picklist value (Age_Grade_c) that specifies an age group (i.e., "1-2 years") and a number field (Total_Social_Emotional_Score_c) that includes a raw score. Depending on the age and score, the formula should tell us whether the child is Progressing, Meeting, or Exceeding expectations. 

Any idea on how this should be adjusted? I'm getting a syntax error.

[This project is to build in Teaching Strategies Gold (TS Gold) scoring rubric into Salesforce.]

-----

AND(case(Age_Grade__c,

“Birth to year 1"),

IF(Total_Social_Emotional_Score__c <4, "Progressing Towards Expectations”,
IF(AND(Total_Social_Emotional_Score__c >3,(Total_Social_Emotional_Score__c <17)),"Meeting Expectations",
IF(Total_Social_Emotional_Score__c >16,"Exceeding Expectations",null),

“1 to 2 years”),

IF(Total_Social_Emotional_Score__c <14,"Progressing Towards Expectations",
IF(AND(Total_Social_Emotional_Score__c >13,(Total_Social_Emotional_Score__c <31)),"Meeting Expectations",
IF(Total_Social_Emotional_Score__c >30,"Exceeding Expectations",null),

"2 to 3 years”),

IF(Total_Social_Emotional_Score__c <24,"Progressing Towards Expectations",
IF(AND(Total_Social_Emotional_Score__c >23,(Total_Social_Emotional_Score__c <40)),
"Meeting Expectations",
IF(Total_Social_Emotional_Score__c >39,"Exceeding Expectations",null),

“Preschool 3 class/grade”),

IF(Total_Social_Emotional_Score__c <34,"Progressing Towards Expectations",
IF(AND(Total_Social_Emotional_Score__c >33,(Total_Social_Emotional_Score__c <51)),
"Meeting Expectations",
IF(Total_Social_Emotional_Score__c >50,"Exceeding Expectations",null),

“Pre-K 4 class/grade”),

IF(Total_Social_Emotional_Score__c <46,"Progressing Towards Expectations",
IF(AND(Total_Social_Emotional_Score__c >45,(Total_Social_Emotional_Score__c <62)),
"Meeting Expectations",
IF(Total_Social_Emotional_Score__c >61,"Exceeding Expectations",null)

)
)
)
)
)
)
{ label: 'Hospital', fieldName: 'Hospital__r', type: 'Name' },
  { label: 'Material number', fieldName: 'Product__r.Mtrl_nbr__c', type: 'Text' },
 { label: 'Product', fieldName: 'Product__r.Name', type: 'Text' }

I am getting blank values in the above field in the lightning data table. Pls help how to show the relation in lightning data table
Fairly new to Salesforce and am trying to wrap my head around the system as well as importing data. I don't understand why fields don't match up between accounts and contacts. E.g. contact has a field for "mobile" while account has "phone" and "phone other" and no field for "mobile" or "cell". Also contact has "street 1", "street 2" address while account has "mailing address" and "shipping address". Why don't the fields match up between these two objects? And would it make sense to have them match?

Thanks. 
  • December 28, 2022
  • Like
  • 1
Class Controller:
public with sharing class controllerquoteVisual {
    
    public String title {get;set;}
    public Quote quote {get;set;}
    public List<quoteLineItem> qliList {get;set;}
    //public List<Product2> products {get; set;}
    
    //Capturar Nombre de familia y lista de productos
    public Map<String,List<ObjectWrapper>> mapFamily {get;set;}
    //public Map<String,List<QuoteLineItem>> mapFamilyqli {get;set;}
    //Captutar Nombre de familia y recuento de Productos que se mostrarán
    public Map<String, Integer> FamilyCountMap{get;set;}
	//Capturar Lista de nombres de familia de productos 
    public List<String> FamilyList {get;set;}
    //ProductList o products ya con los productos que se requieren mostrar
    
    public controllerquoteVisual(){
        
        Id id = ApexPages.currentPage().getParameters().get('id');
        
        //Obtener quote mediante el Id que arroja la visualforce desde quote
        quote = [SELECT Id, Name, TotalPrice, GrandTotal, ExpirationDate, AccountId, Total_Hours__c, OpportunityId, QuoteNumber   
                FROM quote WHERE Id=:id LIMIT 1];
        
        Opportunity opportunity = [SELECT Name FROM Opportunity WHERE Id=:quote.OpportunityId LIMIT 1];
        
        title = opportunity.Name.split('\\|')[0] + opportunity.Name.split('\\|')[1];
        
        Apexpages.currentPage().getHeaders().put('content-disposition', 'inline; filename='+title+ ' - ' +quote.QuoteNumber );
        
        //Obtener lista de quoteLineItems de la actual quote
        qliList = [SELECT Id, Product2Id, Quantity  
                    FROM quoteLineItem WHERE quoteId=:Id];
       
        ///////////////////////////////////////////////
        //Separar productos por tipo de familia 
        mapFamily = new Map<String, List<ObjectWrapper>>(); 
        FamilyCountMap = new Map<String, Integer>();
        FamilyList = new List<String>();
        
        List<quoteLineItem> finalqliList = new List<QuoteLineItem>();
        finalqliList = qliList;
        
        //Agrupar por nombre de familia y preparar los map
        for(QuoteLineItem qq: finalqliList){
            Product2 famObj = [SELECT Id, Name, Family, Description
                   FROM Product2 WHERE Id=:qq.Product2Id];
            if(famObj.Family == null){
                famObj.Family= 'Sin clasificación';
            }
            
            //List<QuoteLineItem> qq = qliList;
            List<ObjectWrapper> proList = new List<ObjectWrapper>();
            //Verificar si el map ya contiene el mismo nombre por familia
            if(mapFamily.containsKey(famObj.Family)){
            	//Recuperar lista de productos existentes
            	proList = mapFamily.get(famObj.Family);
            	//Meter el nuevo producto a la lista
                proList.add(new ObjectWrapper(qq, famObj));
                    
                mapFamily.put(famObj.Family, proList);
                    
                //Almacenar filas por nombre de familia
                FamilyCountMap.put(famObj.Family, proList.size());
            }
            else{
            	//crear nuevo map del nombre de familia //.fammily,name,etc
                //proList.add(famObj);
                proList.add(new ObjectWrapper(qq, famObj));
                mapFamily.put(famObj.Family, proList); 
                    
                //Almacenar filas por nombre de familia
                FamilyCountMap.put(famObj.Family, proList.size());
            }
        	FamilyList = new List<String>(mapFamily.keySet());
    	}
        
    }
    
    public class ObjectWrapper{
        //Campos QuoteLineItems
        //Public Id QliId{get;set;}
        Public Decimal Quantity{get;set;}
        
        //Campos Producto
        Public String Name{get;set;}
        Public String Family{get;set;}
        Public String Description{get;set;}
        
        public ObjectWrapper(QuoteLineItem ql, Product2 pr){
            //this.QliId = ql.Id;
            this.Quantity = ql.Quantity;
            
            this.Name = pr.Name;
            this.Family = pr.Family;
            this.Description = pr.Description;
        }  
    }
}

Test Class (68%, wrapper class is missing)
@isTest
public class TestControllerquoteVisual{
	@isTest
    static void testControllerVFP(){
        
        Pricebook2 pb = new Pricebook2(Name = 'Standard Price Book', 
                                       Description = 'Price Book Products', IsActive = true );
        insert pb;
        
        Product2 prod = new Product2(Name = 'Test Product', Description = 'Descripción Test', 
                                     Family = 'Salesforce Service Cloud', IsActive = true);
        insert prod;
        
        List<Pricebook2> standardPbList = [select id, name, isActive from Pricebook2 
                                           where IsStandard = true ];
 
    	List<PricebookEntry> listPriceBook = new List<PricebookEntry>();
     	for(Pricebook2 p : standardPbList ){
      		PricebookEntry pbe = New PricebookEntry ();
      		pbe = new PricebookEntry(Pricebook2Id = p.Id, Product2Id = prod.Id, 
                                     UnitPrice = 10000, IsActive = true, UseStandardPrice = false);
       		listPriceBook.add(pbe);
     	}
        insert listPriceBook;
        
        Opportunity opp = new Opportunity(Name = 'Test Opportunity', 
                                          StageName = 'Discovery', Product_Families__c='Salesforce Service Cloud' ,CloseDate = system.today());
        insert opp;
        
        Quote quttest = new Quote (Name = 'Quote Test' , OpportunityId = opp.id , Pricebook2Id = pb.id );
        insert quttest;
        
        List<QuoteLineItem> listval = new List<QuoteLineItem>();
        for(PricebookEntry pricebook : listPriceBook){
            QuoteLineItem qutlineitemtest = new QuoteLineItem ();
            qutlineitemtest = new QuoteLineItem(QuoteId = quttest.id, Quantity = 3.00,UnitPrice = 12, PricebookEntryId = pricebook.id);
            
            listval.add(qutlineitemtest);
        }
        insert listval;    
            
        QuoteLineItem qlitem = new QuoteLineItem(Quantity = 3.00, UnitPrice = 12 );
        
        
        Test.startTest();
            ApexPages.currentPage().getParameters().put('id', String.valueOf(quttest.Id));
            controllerquoteVisual controllerVfp= new controllerquoteVisual();
            //controllerVfp = new controllerquoteVisual();
        
            controllerquoteVisual.ObjectWrapper wrapper = new controllerquoteVisual.ObjectWrapper(qlitem, prod);
            
            wrapper.Quantity = 3.00;
                
            wrapper.Name = prod.Name;
            wrapper.Description = prod.Description;
            wrapper.Family = prod.Family;
        
        Test.stopTest();
        
    }

}

 
Hi, I have a lightning aura component and i am using one button in .cmp

 <aura:attribute name="showthisButton" type="boolean" default="false"/>
 <aura:attribute name="state" type="String" />
<aura:attribute name="response" type= "String" />
<lightning:button variant="brand" label="Yes" class="slds-align_absolute-center"
                            title="Payment" onclick="{!c.sendEmailNow}"
                             />

In Controller:
 sendEmailNow: function(component, event, helper){
        helper.sendEmailNow(component, event, helper);

In Helper:

sendEmailNow : function(component,event,helper) {
      var accountId = component.get("v.accountId");
      console.log('in here----'+accountId);
      
      var action = component.get('c.getdetails');//apex class method
      action.setParams({ 'AccountId' : accountId });
      
      action.setCallback(this, function(response){  
          var state = response.getState();
          var error= response.getError();
          
           if (state === "SUCCESS") {
               
            component.set('v.showthisButton',false); 
        
          } else if (state === "INCOMPLETE") {
              
            
              alert ("Failed ");
          }else if (state === "ERROR") {
              var errors = response.getError();
              if (!errors) {
                  errors = [{"message" : "Unknown Error Occured"}];
              }
              alert ("Error occured"+errors);
          }
         
        
          
         
     });
      $A.enqueueAction(action); 
     
  }
I am struggleing understanding how to write test units for this class. 
 
//@RestResource(urlMapping='/Google/*') is used to tell the class that it is a REST resource used for POST GET etc
@RestResource(urlMapping='/Google/*')
global with sharing class GoogleWebHookListener {
    //HttpPost tells the method that it will be a POST method
    @HttpPost
    global static void handlePost() {
        
        //set up varibles for the Lead
        String name;
        String phone;
        String email;
        String postCode;
        String firstName;
        String lastName;
        
        //try to do the JSON deserialization and Lead Creation
        //******EXAMPLE JSON AT BOTTOM*****
        try
        {
            // This gets the body of the webhook makes the body a string and sets the string to the variable 'jsonString'
            String jsonString = RestContext.request.requestBody.toString();
            //This deserializes the JSON based on the the properties setup in the Class GoogleJsonLeadExample
            GoogleJsonLeadExample g = (GoogleJsonLeadExample)JSON.deserialize(jsonString, GoogleJsonLeadExample.class);
            
            //This tests the JSON to see if it is legit.
            if(g.google_key == ''){
                
                //This loops through the JSON array set up in the Class GoogleJsonLeadExample
                
               for(GoogleJsonLeadExample.userData d : g.user_column_data)
               {
                   if(d.column_name == 'Full Name')
                   {
                       //The JSON has Full Name, this breaks Full Name into First and Last Names
                        name = d.string_value;
                        List<String> names = name.split(' ');
                       	firstName = names[0];
                        lastName = names[1];
                           
                   }
                   if(d.column_name == 'User Phone')
                   {
                        phone = d.string_value;
                   }
                   if(d.column_name == 'User Email')
                   {
                        email = d.string_value;
                   }
                   if(d.column_name == 'Postal Code')
                   {
                       postCode = d.string_value;
                   }
               }
              
                //This creates the Lead                 
            Lead detail = new Lead();
            detail.LastName = lastName;
            detail.FirstName = firstName;
            detail.Phone = phone;
            detail.Company = name;
            detail.Email = email;
            detail.OwnerId = '0051Q00000GrANL'; // This Id is the user Hubspot.
            insert detail;
           
            }
                                        
        }
        catch (DMLException e)
        {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }

}

 
Please correct my code and advice me on what I am doing wrong.
public List<Account> sortingMethod1() {
            List<Account> accList= new List<Account>();
            accList.add(new Account(Name= 'a'));
            accList.add(new Account(Name= 'z'));
            accList.add(new Account(Name= 'c'));
            accList.add(new Account(Name= 'd'));
            accList.add(new Account(Name= 'p'));
            accList.add(new Account(Name= 'n'));
            INSERT accList;
    
            List<Account> reversedList= new LIst<Account>();
            for(integer I= accList.size()-1; i>=0; i--){
                reversedList.add(accList.get(I));
            }
    
            return reversedList;
        }

 
I am creating an attachment, but I want to check if it does not exist with the same name.
a = (Opportunity)standardPageController.getRecord();
 PageReference pdfPage = new PageReference('/apex/myPage');
        Opportunity b =[select Id, Name Invoice_Number__c from Opportunity where Id=:a.id];
        Blob pdfBlob;

Attachment attach = new Attachment(
        parentId = a.Id,
        Name = b.Name +'.pdf', 
        body = pdfBlob); //create the attachment object
        insert attach;

 
Hi All,
i have written sample aura component to fetch contacts . but from controller.js not able invoke apex method. getting 
SecureAction: [object Object]{ key: {"namespace":"c"} } error.
below is my code :
component:

<aura:component controller="contactlistcontroller">
    
    <aura:attribute  name="contacts" type="contact[]"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <aura:iteration items="{!v.contacts}" var ="con">
        <p> {!con.name} </p> <br></br>
        <p> {!con.lastname} </p>
    </aura:iteration>
</aura:component>


controller.js

 ({
    doInit : function(component, event, helper) {
        var action = component.get("c.findAll");
        
        $A.enqueueAction(action);
        action.setCallback(this,function(response){
            alert(""+response);
            var state= response.getState();
            if(state ==="SUCCESS"){
                var responsestate = response.getReturnValue();
                component.set("v.contacts",responsestate);
            }
            
        });
        
    }
})



apex class:
public class contactlistcontroller {
    
    @AuraEnabled
    public static list<contact> findAll(){
        
        return[select name,lastname from contact limit 50];
    }
    
    @AuraEnabled
    public static list<contact> findByName(string searchkey){
        string name = '%' +searchkey +'%';
        return[select name,lastname from contact where name like :name limit 50];
        
    }
    @AuraEnabled
    public static contact findById(string contactid){
        return[select id,name,lastname from contact where id =:contactid];
    }

}

Regards,
Harsha
Hi, I'm trying to use a standardcontroller in the Visualforce page in order to use it in a custom button. But I'm having this error:
Unknown constructor 'CarController.CarController(ApexPages.StandardController controller)'
I believe that I need to add something to the controller, but I could not find a solution that worked for me(I tried all the solutions that I found online)...

So, this is the code:
<apex:page  standardController="Case" extensions="CarController" lightningStylesheets="true" title="test">
    <apex:form>
        <apex:pageMessages/>
        <apex:pageBlock >    
            <apex:pageBlockSection columns="2">
                <apex:inputField value="{!abc.Name__c}"/> 
                <apex:inputField value="{!abc.License_Number__c}"/>
                <apex:inputField value="{!abc.Manufacturer__c}"/>
            </apex:pageBlockSection>
            
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Save" action="{!save}" styleClass="slds-button slds-button_brand"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
public class CarController{

    public Car__c abc {Get;Set;}

    public CarController() {     
        abc = new Car__c();
    }
    
    public PageReference save(){
    	try{
        	INSERT abc;
        }
        catch (exception e){
            
        }
        return null;
    }
    
}
P.S. I'm not a developer, just try to learn in order to get there one day... so I'll be happy to understand what is missing.

Thanks!



 
Hi! I am looking to trigger a record creation when a task is created.  I would like it to work for if I task is manually created or if it is created through using 'Email to Salesforce'  My code is below but nothing happens when I create task with a status of completed.  Is there something I'm missing?  Appreciate the guidance!
 
trigger createGAActivityonTask on Task (after insert) {
    
    List <RGS_Activity__c> vehToInsert = new List <RGS_Activity__c> ();
    
    
    for (Task o : Trigger.new) {
        
        
        
        if (o.Status == 'Completed') {
        
        RGS_Activity__c v = new RGS_Activity__c (); 
        
        v.Account__c = '001G000001zaW9M';
        v.Contact__c = '00379000004n82q';
        v.Activity__c = 'Email - 1:1'; 
        
        vehToInsert.add(v);
        
        
        }
        
    }
    try {
        insert vehToInsert; 
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    
}

 
Hi everyone, I'm  new on LWC . and  I'm doing  this example to generate a PDF https://santanuboral.blogspot.com/2020/10/lwc-generate-pdf.html
everything works fine  but now Im trying to save the PDF to  the  correspondet contact depending on the ID,  any idea of how I can do that?   this is my code as we can see Im hard coding the id 

 
public with sharing class DisplayRichTextHelper {
    @AuraEnabled
public static Attachment generatePDF(String txtValue){

        Pagereference pg = Page.renderAsPDF;
        pg.getParameters().put('displayText', txtValue);

        Contact con = new Contact(Id='0035f000008RNWCAA4');

        Attachment objAttachment = new Attachment();
        objAttachment.Name = 'J2S.pdf';
        objAttachment.ParentId = con.Id;
        objAttachment.Body = pg.getContentaspdf();
        objAttachment.IsPrivate = false;
        insert objAttachment;
        return objAttachment;
    }
}
 

And i want to change for some like this:
 ApexPages.currentPage().getParameters().get('id');
Fairly new to Salesforce and am trying to wrap my head around the system as well as importing data. I don't understand why fields don't match up between accounts and contacts. E.g. contact has a field for "mobile" while account has "phone" and "phone other" and no field for "mobile" or "cell". Also contact has "street 1", "street 2" address while account has "mailing address" and "shipping address". Why don't the fields match up between these two objects? And would it make sense to have them match?

Thanks. 
  • December 28, 2022
  • Like
  • 1
Class Controller:
public with sharing class controllerquoteVisual {
    
    public String title {get;set;}
    public Quote quote {get;set;}
    public List<quoteLineItem> qliList {get;set;}
    //public List<Product2> products {get; set;}
    
    //Capturar Nombre de familia y lista de productos
    public Map<String,List<ObjectWrapper>> mapFamily {get;set;}
    //public Map<String,List<QuoteLineItem>> mapFamilyqli {get;set;}
    //Captutar Nombre de familia y recuento de Productos que se mostrarán
    public Map<String, Integer> FamilyCountMap{get;set;}
	//Capturar Lista de nombres de familia de productos 
    public List<String> FamilyList {get;set;}
    //ProductList o products ya con los productos que se requieren mostrar
    
    public controllerquoteVisual(){
        
        Id id = ApexPages.currentPage().getParameters().get('id');
        
        //Obtener quote mediante el Id que arroja la visualforce desde quote
        quote = [SELECT Id, Name, TotalPrice, GrandTotal, ExpirationDate, AccountId, Total_Hours__c, OpportunityId, QuoteNumber   
                FROM quote WHERE Id=:id LIMIT 1];
        
        Opportunity opportunity = [SELECT Name FROM Opportunity WHERE Id=:quote.OpportunityId LIMIT 1];
        
        title = opportunity.Name.split('\\|')[0] + opportunity.Name.split('\\|')[1];
        
        Apexpages.currentPage().getHeaders().put('content-disposition', 'inline; filename='+title+ ' - ' +quote.QuoteNumber );
        
        //Obtener lista de quoteLineItems de la actual quote
        qliList = [SELECT Id, Product2Id, Quantity  
                    FROM quoteLineItem WHERE quoteId=:Id];
       
        ///////////////////////////////////////////////
        //Separar productos por tipo de familia 
        mapFamily = new Map<String, List<ObjectWrapper>>(); 
        FamilyCountMap = new Map<String, Integer>();
        FamilyList = new List<String>();
        
        List<quoteLineItem> finalqliList = new List<QuoteLineItem>();
        finalqliList = qliList;
        
        //Agrupar por nombre de familia y preparar los map
        for(QuoteLineItem qq: finalqliList){
            Product2 famObj = [SELECT Id, Name, Family, Description
                   FROM Product2 WHERE Id=:qq.Product2Id];
            if(famObj.Family == null){
                famObj.Family= 'Sin clasificación';
            }
            
            //List<QuoteLineItem> qq = qliList;
            List<ObjectWrapper> proList = new List<ObjectWrapper>();
            //Verificar si el map ya contiene el mismo nombre por familia
            if(mapFamily.containsKey(famObj.Family)){
            	//Recuperar lista de productos existentes
            	proList = mapFamily.get(famObj.Family);
            	//Meter el nuevo producto a la lista
                proList.add(new ObjectWrapper(qq, famObj));
                    
                mapFamily.put(famObj.Family, proList);
                    
                //Almacenar filas por nombre de familia
                FamilyCountMap.put(famObj.Family, proList.size());
            }
            else{
            	//crear nuevo map del nombre de familia //.fammily,name,etc
                //proList.add(famObj);
                proList.add(new ObjectWrapper(qq, famObj));
                mapFamily.put(famObj.Family, proList); 
                    
                //Almacenar filas por nombre de familia
                FamilyCountMap.put(famObj.Family, proList.size());
            }
        	FamilyList = new List<String>(mapFamily.keySet());
    	}
        
    }
    
    public class ObjectWrapper{
        //Campos QuoteLineItems
        //Public Id QliId{get;set;}
        Public Decimal Quantity{get;set;}
        
        //Campos Producto
        Public String Name{get;set;}
        Public String Family{get;set;}
        Public String Description{get;set;}
        
        public ObjectWrapper(QuoteLineItem ql, Product2 pr){
            //this.QliId = ql.Id;
            this.Quantity = ql.Quantity;
            
            this.Name = pr.Name;
            this.Family = pr.Family;
            this.Description = pr.Description;
        }  
    }
}

Test Class (68%, wrapper class is missing)
@isTest
public class TestControllerquoteVisual{
	@isTest
    static void testControllerVFP(){
        
        Pricebook2 pb = new Pricebook2(Name = 'Standard Price Book', 
                                       Description = 'Price Book Products', IsActive = true );
        insert pb;
        
        Product2 prod = new Product2(Name = 'Test Product', Description = 'Descripción Test', 
                                     Family = 'Salesforce Service Cloud', IsActive = true);
        insert prod;
        
        List<Pricebook2> standardPbList = [select id, name, isActive from Pricebook2 
                                           where IsStandard = true ];
 
    	List<PricebookEntry> listPriceBook = new List<PricebookEntry>();
     	for(Pricebook2 p : standardPbList ){
      		PricebookEntry pbe = New PricebookEntry ();
      		pbe = new PricebookEntry(Pricebook2Id = p.Id, Product2Id = prod.Id, 
                                     UnitPrice = 10000, IsActive = true, UseStandardPrice = false);
       		listPriceBook.add(pbe);
     	}
        insert listPriceBook;
        
        Opportunity opp = new Opportunity(Name = 'Test Opportunity', 
                                          StageName = 'Discovery', Product_Families__c='Salesforce Service Cloud' ,CloseDate = system.today());
        insert opp;
        
        Quote quttest = new Quote (Name = 'Quote Test' , OpportunityId = opp.id , Pricebook2Id = pb.id );
        insert quttest;
        
        List<QuoteLineItem> listval = new List<QuoteLineItem>();
        for(PricebookEntry pricebook : listPriceBook){
            QuoteLineItem qutlineitemtest = new QuoteLineItem ();
            qutlineitemtest = new QuoteLineItem(QuoteId = quttest.id, Quantity = 3.00,UnitPrice = 12, PricebookEntryId = pricebook.id);
            
            listval.add(qutlineitemtest);
        }
        insert listval;    
            
        QuoteLineItem qlitem = new QuoteLineItem(Quantity = 3.00, UnitPrice = 12 );
        
        
        Test.startTest();
            ApexPages.currentPage().getParameters().put('id', String.valueOf(quttest.Id));
            controllerquoteVisual controllerVfp= new controllerquoteVisual();
            //controllerVfp = new controllerquoteVisual();
        
            controllerquoteVisual.ObjectWrapper wrapper = new controllerquoteVisual.ObjectWrapper(qlitem, prod);
            
            wrapper.Quantity = 3.00;
                
            wrapper.Name = prod.Name;
            wrapper.Description = prod.Description;
            wrapper.Family = prod.Family;
        
        Test.stopTest();
        
    }

}

 
I am struggleing understanding how to write test units for this class. 
 
//@RestResource(urlMapping='/Google/*') is used to tell the class that it is a REST resource used for POST GET etc
@RestResource(urlMapping='/Google/*')
global with sharing class GoogleWebHookListener {
    //HttpPost tells the method that it will be a POST method
    @HttpPost
    global static void handlePost() {
        
        //set up varibles for the Lead
        String name;
        String phone;
        String email;
        String postCode;
        String firstName;
        String lastName;
        
        //try to do the JSON deserialization and Lead Creation
        //******EXAMPLE JSON AT BOTTOM*****
        try
        {
            // This gets the body of the webhook makes the body a string and sets the string to the variable 'jsonString'
            String jsonString = RestContext.request.requestBody.toString();
            //This deserializes the JSON based on the the properties setup in the Class GoogleJsonLeadExample
            GoogleJsonLeadExample g = (GoogleJsonLeadExample)JSON.deserialize(jsonString, GoogleJsonLeadExample.class);
            
            //This tests the JSON to see if it is legit.
            if(g.google_key == ''){
                
                //This loops through the JSON array set up in the Class GoogleJsonLeadExample
                
               for(GoogleJsonLeadExample.userData d : g.user_column_data)
               {
                   if(d.column_name == 'Full Name')
                   {
                       //The JSON has Full Name, this breaks Full Name into First and Last Names
                        name = d.string_value;
                        List<String> names = name.split(' ');
                       	firstName = names[0];
                        lastName = names[1];
                           
                   }
                   if(d.column_name == 'User Phone')
                   {
                        phone = d.string_value;
                   }
                   if(d.column_name == 'User Email')
                   {
                        email = d.string_value;
                   }
                   if(d.column_name == 'Postal Code')
                   {
                       postCode = d.string_value;
                   }
               }
              
                //This creates the Lead                 
            Lead detail = new Lead();
            detail.LastName = lastName;
            detail.FirstName = firstName;
            detail.Phone = phone;
            detail.Company = name;
            detail.Email = email;
            detail.OwnerId = '0051Q00000GrANL'; // This Id is the user Hubspot.
            insert detail;
           
            }
                                        
        }
        catch (DMLException e)
        {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }

}

 
Hi there!

I've been asked to restrict the valid Close Dates for Opporunities to the last day of the month when the Stage is not Closed Won/Lost.

I've found a fromula that does a great job restricting the dates in general, but I can't figure out how to add the additional condition that it should only apply the date limitation when the Opportunity is in certain stages.

IF( 
    MONTH( CloseDate ) = 12,
    DATE( YEAR( CloseDate ) + 1, 1, 1 ),
    DATE( YEAR( CloseDate ), MONTH( CloseDate ) + 1, 1 )
  ) - 1 
)

Any help/insight would be greatly appreciated!
Help me Create a Trigger for CheckBox to clone Opportunity and OpportunityLineItem
//This is what i have coded please help resolve this
trigger CloneParentOpportunityTrigger on Opportunity (After insert,After update) 
{
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    Map<Id,Opportunity> OldOppId = new Map<Id,Opportunity>();
    Opportunity newopp = new Opportunity(); 
    if(Trigger.IsAfter)
    {
        if(Trigger.IsInsert || Trigger.IsUpdate)
        {
            if(newopp.Clone_Opportunity__c)
            {
                for(Opportunity opp : Trigger.new)
                { 
                    //opportunity list item
                    newopp.Name = opp.Name;
                    newopp.AccountId = opp.AccountId;
                    newopp.Product_Type__c = opp.Product_Type__c;
                    newopp.CloseDate = opp.CloseDate;
                    newopp.StageName = opp.StageName;
                    newopp.Payment_Frequency__c = opp.Payment_Frequency__c;
                    newopp.Most_Recent_Invoice_Date__c  = opp.Most_Recent_Invoice_Date__c;
                    newopp.Billing_Start_Date__c = opp.Billing_Start_Date__c;
                    newopp.Parent_Opportunity__c = opp.Id;
                    oppsToUpdate.add(newopp);
                    OldOppId.put(opp.id,opp);
                }
                
                insert oppsToUpdate;
                
                Map<Id,Opportunity> NewOppId = new Map<Id,Opportunity>();
                for(Opportunity opp1 : oppsToUpdate)
                {
                    NewOppId.put(opp1.Id, opp1);
                }
                
                List<OpportunityLineItem> oppitemList = new List<OpportunityLineItem>([SELECT Id, Product2Id, Quantity, UnitPrice, OpportunityId FROM OpportunityLineItem Where OpportunityId IN : OldOppId.keyset()]);
                for(OpportunityLineItem oppitem : oppitemList)
                {
                    OpportunityLineItem oli = new OpportunityLineitem();
                    oli.OpportunityId = NewOppId.get(oppitem.OpportunityId).Id;
                    oli.Product2Id = oppitem.Product2Id;
                    oli.Quantity = oppitem.Quantity;
                    oli.UnitPrice = oppitem.UnitPrice;
                    oppitemlist.add(oli);
                }
                insert oppitemList;
            }
        }   
    }
}
Hi..,
I am calling the Child component from the Parent component..so, it is successfully done.
but
along with that i want to pass the Record Id from Parent component to Child component using Aura component.
Thanks
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;
        }
    }
}


 
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