• Maharajan C
  • ALL STAR
  • 7720 Points
  • Member since 2015
  • Sr.Associate Consultant
  • Infosys


  • Chatter
    Feed
  • 259
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 13
    Questions
  • 946
    Replies
I have written the following test class and receive error "FATAL_ERROR System.DmlException: Insert failed. First exception on row 0 with id 0015B000015c9L1QAI; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]" when I run it, can anyone tell me what I am doing wrong?

@isTest
private class test_SaveAccountDetails {
    
    static testmethod void SaveAccountDetailTest() {
        Id RecordTypeIdPropAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Property').getRecordTypeId();
        
        Account acctForm = new Account();
        acctForm.RecordTypeId=RecordTypeIdPropAccount;
        acctForm.Name = 'Test Account';
        acctForm.PropertyNumber__c = '123456';
        acctForm.PropertyType__c = 'Retail';
        acctForm.Phone = '8885551212';
        acctForm.PropertyStatus__c = 'Potential Acquisition';
        acctForm.Website = 'www.testsite.com';
        acctForm.Description = 'test account description';
        acctForm.Region__c = 'test region';
        acctForm.PurchaseDate__c = date.parse('2/2/2000');
        acctForm.PurchasePrice__c = 350000;    
        acctForm.DateSold__c = date.parse('2/2/2019');
        acctForm.SalePrice__c = 500000;
        acctForm.BillingCountry = 'United States';   
        acctForm.ShippingCountry = 'United States';
        acctForm.BillingStreet = '1313 Mockingbird Lane';
        acctForm.ShippingStreet = '100 Art Rooney Ave';
        acctForm.BillingCity = 'Springfield';
        acctForm.BillingState = 'Missouri';    
        acctForm.ShippingCity = 'Pittsburgh';
        acctForm.ShippingState = 'Pennsylvania';
        acctForm.BillingPostalCode = '12345';   
        acctForm.ShippingPostalCode = '15212';
        
        insert acctForm;
        
        Test.startTest();        
        SaveAccountDetails.SaveAccountDetail(acctForm);
        Test.stopTest();
            
        
        
    }
}

Here is the class I am trying to provide code coverage for:

public class SaveAccountDetails {
    
    @AuraEnabled
    public static id SaveAccountDetail(Account acctForm){
        //DML operation to save AcctForm Details
        system.debug(acctForm);
        Id recTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Property').getRecordTypeId();
        acctForm.RecordTypeId=recTypeId;
        insert acctForm;
        return acctForm.id;
    }
}

I would really appreciate any help provided!
({
	navigate : function(component, event, helper) {
        var navigateEvent = $A.get("e.force:navigateToComponent");
        navigateEvent.setParams({
            componentDef: "c.RegistrationFormTutorial"
        });
        navigateEvent.fire();
	}
})

I want to navigate from one lightning component to another component (RegistrationFormTutorial). I have written the above code. But I am getting error like this:


" This page has an error. You might just need to refresh it. Action failed: c:HtmlTryout$controller$navigate [Cannot read property 'setParams' of undefined] Failing descriptor: {c:HtmlTryout$controller$navigate} "

Could anyone please help me on this. Thanks in advance.
I have two classes and i am quite puzzle to write their test class and not getting any coverage for them

first Apex Class

global class WS_ZipUtil {

  /**
   * Receive Attachments info from Attachment ParentId
   */
  webService static String getAttachmentById( String sfdcId ){

    if( String.isEmpty( sfdcId ) ) return WS_Util.errorJson('Parameter sfdcId is required.');
    
    List<Attachment> attachmentList =  [SELECT Id, Name, Body, ContentType FROM Attachment WHERE Id = :sfdcId];
    if( attachmentList == null || attachmentList.size() == 0 ) return WS_Util.errorJson('Attachment not found.');
    return wrapAttachmentList( attachmentList );
  }

  //Format JSON String from AttachmentList
  private static String wrapAttachmentList( List<Attachment> attachmentList ){

    List<Object> dataList = new List<Object>();
    for( Attachment at : attachmentList ){
      Map<String, String> atMap = new Map<String, String>();
      //atMap.put( 'Id', at.Id );
      atMap.put( 'Name', at.Name );
      atMap.put( 'Body', EncodingUtil.base64Encode( at.Body ) );
      //atMap.put( 'ContentType', at.ContentType );
      dataList.add( atMap );
    }
    return WS_Util.normalJson( dataList );
  }


}


Second Apex Class

public class WS_Util {

  //Normal Status Code
  private static String API_STATUS_NORMAL = '200';
  //Error Status Code
  private static String API_STATUS_ERROR  = '400';

  /**
   * Normal JSON Response
   */
  public static String normalJson( Object respData ) {
    Map<String, Object> response = new Map<String, Object>();
    response.put('status', API_STATUS_NORMAL);
    if( respData != null ) response.put('data', respData);
    return JSON.serialize( response );
  }

  /**
   * Error JSON Response
   */
  public static String errorJson( String message ) {
    Map<String, Object> response = new Map<String, Object>();
    response.put('status', API_STATUS_ERROR);
    if( message != null ) response.put('error', message);
    return JSON.serialize( response );
  }

}
Hello all,

I'm trying to populate owner's name to Enrollment_Rep__c field on Lead Object based on the profile name.  Everything works till I change the Owner from User to Queue.  I'm running to System.NullPointerException on the trigger.
trigger EnrollmentRep on Lead (before insert, before update) {
    
    Set<Id> ownerIds = new Set<Id>();

    for (Lead newLead : Trigger.new) {
        ownerIds.add(newLead.OwnerId); 
    }

    Map<Id,User> mapUsers = new Map<Id, User>([SELECT Id, Profile.Name, Name FROM User Where Id In :ownerIds]);

    for (Lead newLead : Trigger.new) {
        User oOwner = mapUsers.get(newLead.OwnerId);
        
        if (oOwner.Profile.Name == 'CEO'){
            newLead.Enrollment_Rep__c = oOwner.Name;
        }
    }
}

I'm new to the trigger and I'm not sure where to use IF statement Lead Owner != Queue.

Any suggestions will be helpful.

Thanks!
​​​​​​​John
 
Hello everyone,
I have 3 custom objects. Car__c, Service__c, Action__c,
I would really like to know how to get a list of all cars where Action__c.category = 'SOME VALUE'.
Link mapping looks like this
User-added image
Hi All,

I am facing an issue with Custom Link in Lightning, as it is working absoultely fine in Classic. I have created a custom link report and added to the page layout. When clicking in Classic view it is showing records as per the fliter criteria, but the same link in Lightning view is not showing records as per the filter criteria. Not sure why in Lightning view  unable to see the report result accurately.
User-added image

But in Classic view based on the filter it is returning the correct values.

Thanks in advance
Hi,

I am getting this error: 
Uncaught Error in $A.getCallback() [Cannot read property 'Product_Version__c' of undefined]
Callback failed: apex://dynamicCardController/ACTION$getCaseDetails

I have a lightning component on the page that uses an Apex Controller to Grab Account Detials and Display on the Case Page.

I am only getting this error when the case does not have an account. I tired only to display the component when there is an account but still getting these errors.

End Goal is for me not to get the error on the page, since there would be no way to display the data without an account on the case.

Helper Code:
({
    getCaseDetails : function(cmp, event) {
        var recordId = cmp.get('v.recordId');
        var getCaseDetails = cmp.get('c.getCaseDetails');
        getCaseDetails.setParams({
            recordId : recordId
        })
        getCaseDetails.setCallback(cmp, function(response) {
            var state = response.getState();
            if (state === 'SUCCESS') {
                var results = response.getReturnValue();
                cmp.set('v.AccountId', results.AccountId);
                cmp.set('v.ProductVersion', results.Account.Product_Version__c);
                
            } else 
                console.log(response);
            
        })
        $A.enqueueAction(getCaseDetails);
    }
})

 
Execute Anonymous: Variable does not exist
Hey Guys, 
I'm stuck on trying to debug this piece of code in Anonymous Window. I set the variables using a map on the Opportunity object, but the child object "Payment__c" is not recognizing the lookup to Opportunity record maps. It's a master-detail relationship. The error message I'm seeing when I try executing is: Line: 41, Column: 30. Variable does not exist: BudBeer. Which is not making sense to me, is there something I'm not seeing? 
I'm sure it's something very silly, here's the code:
 
/* Insert Account Map */
             Map<String, Account> Accts= new Map<String, Account>{};
                Accts.put('BudweiserFac', new Account(Name='Budweiser Co'));
                Accts.put('SamAdams', new Account(Name='Sam Adams Co'));  
            insert Accts.values(); 
         
        /* Insert Contact Map */
            Map<String, Contact> Con= new Map<String, Contact>{};
                Con.put('JohnSmith', new Contact(FirstName='John',LastName='Smith',AccountId=Accts.get('SamAdams').Id));
                Con.put('TakuBurutsa', new Contact(FirstName='Taku',LastName='Burutsa',AccountId=Accts.get('BudweiserFac').Id));
            insert Con.values(); 
            
        /* Instantiate Opportunity Record Type variables */
                Id GrantId = Schema.SObjectType.Opportunity.getRecordTypeInfosByDeveloperName().get('Grant').getRecordTypeId();
                    System.debug('Grant RecTypeId = '+GrantId);

                Id GiftId = Schema.SObjectType.Opportunity.getRecordTypeInfosByDeveloperName().get('Gift').getRecordTypeId();
                    System.debug('Gift RectypeId ='+GiftId);
 
        /* Insert Opportunity Map */
  
            Map<String,Opportunity> Opptys=new Map<String,Opportunity>{};
                Opptys.put('SamBeer', new Opportunity(Name='Sam Beer $',CloseDate=date.parse('07/17/2019'),StageName='Closed',
                	Amount=100,AccountId=Accts.get('SamAdams').Id,Primary_Contact__c=Con.get('TakuBurutsa').Id,RecordTypeId=GiftId));
                Opptys.put('BudBeer', new Opportunity(Name='Bud Beer $',CloseDate=date.parse('07/17/2019'),StageName='Closed',
                    Amount=100,AccountId=Accts.get('BudweiserFac').Id,
                    Primary_Contact__c=Con.get('JohnSmith').Id,
                    RecordTypeId=GrantId)); 
            insert Opptys.values();
System.debug('Gift RectypeId ='+GiftId);
/* Insert Payment Map */
            Map<String,Payment__c> Pmts=new Map<String,Payment__c>{};
                Pmts.put('BudPmt1', new Payment__c(Paid__c=TRUE,Refund__c=FALSE,Payment_Method__c='Credit Card',
                Check_Date__c=date.parse('07/17/2019'),Cash_Received_Date__c=date.parse('07/17/2019'),Payment_Amount__c=100,
                CONTRIBUTION__C=Opptys.get('BudBeer').Id));

				Pmts.put('SamPmt1', new Payment__c(Paid__c=TRUE,Refund__c=FALSE,Payment_Method__c='Credit Card',
                Check_Date__c=date.parse('08/17/2019'),Cash_Received_Date__c=date.parse('08/17/2019'),Payment_Amount__c=100,
                CONTRIBUTION__C=Opptys.get('SamBeer').Id));
            insert Pmts.values();  
                System.debug(BudBeer);
		System.debug(SamBeer);

 
Trying to create a validation rule on the Case object that checks to see if there is at least one Case Team member before allowing the user to change the Status field to a specific value. Anyone have any ideas? Any help would be amazing! 
At a lost, I don't know where to start on the testing for this Class.  I don't know the next steps.  Any assistance moving on with the test for this class is appreciated.
 
public class caseTriggerHandlerCount{
    public static void CaseCounter(){

        List<AggregateResult> AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co
                            FROM Case
                            WHERE CreatedDate = LAST_N_DAYS:50
                            GROUP BY AccountId, Account.Name
                            HAVING COUNT(Id)  >=1];

        for(AggregateResult aggr:AggregateResultList){ 
                
                    // Send Email to Implementation Coordinator
                Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
                    message.toAddresses = new String[] { 'test@test.com' };   
                    message.subject = 'Subject Test Message';
                    message.plainTextBody = 'Account name: ' + aggr.get('name') + ' has ' + (Integer)aggr.get('co') + ' cases opened in the last 8 days.';
                Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
                Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
            System.debug('Account Name: ' + aggr.get('name'));
            
            
        }

} 

}

I have created a Test Factory:
 
@isTest
public class TestDataFactoryCases {
    public static List<Case> createCasesData(Integer numConts) {
        List<Case> lConts = new List<Case>();
        
        for(Integer i=0;i<numConts;i++) {
            Case cse = new Case();
                    cse.status = 'Escalated';
                    cse.origin = 'Community';
                    cse.AccountId = '0013000000qLB9MAAW';
                    cse.Description = 'test ' + i;
            lConts.add(cse);
        }
        insert lConts;

        return lConts;
    }
}

My test Class So far:
 
@isTest
private class TestCaseCountAlert {
    @isTest static void TestPositiveResult() {
        // Test data setup
        
        Case[] cases = TestDataFactoryCases.createCasesData(10);
        
        // Perform test
        Test.startTest();
        
        Test.stopTest();
        
        
    }        
}

​​​​​​​

Hi everyone,

I'm new to Salesforce and Apex coding. I'm making a function so that user can upload a csv file to generate opportunity and contact. However, it hit the SOQL queries limit, I was able to upload maximum 12 rows.

I need to insert Contact first, in order to get an Contact Id and put it in Opportunity. Since I put the queries inside For loops plus other triggers, it exceeded the queries limit.

I'm planning to create an Apex Batch Process, but not sure if it will solve the problem.

Below is the Apex code and Visualforce page:

Apex:

public class FileUploader {
    private ApexPages.StandardController std;
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    public Date closeDate {get;set;}
    public Id recordType {get;set;}
    public Id ownerId {get; set;}
    public List<opportunity> opplist{get;set;}
    public Contact con {get; set;}
    public Opportunity opp {get; set;}
    
    private final String integrationName = 'Inquiry Import';
    String campaignlookup;
    String[] filelines = new String[]{};
        
    public List<SelectOption> repSelectOptions {get {
        List<SelectOption> repSelectOptions = new List<SelectOption> {new SelectOption('','Select One')};
        for (User u : [SELECT Id, Name
                       FROM User 
                       WHERE UserType = 'Standard' AND 
                       IsActive = true
                       ORDER BY Name asc]) {
        	repSelectOptions.add(new SelectOption(u.Id, u.Name));
        }
        return repSelectOptions;
    }}
    
    public List<SelectOption> recordOptions {get {
        List<SelectOption> recordOptions = new List<SelectOption>{new SelectOption('','Select One')};
        
        for (RecordType r : [SELECT Id, Name FROM RecordType WHERE sobjecttype = 'Opportunity']) {
            recordOptions.add(new SelectOption(r.Id, r.Name));
        }
        return recordOptions;
    }}
    
    {
        initializeObjects();
    }
            
    public void initializeObjects() {
        con = new Contact();
        opp = new Opportunity();
    }
    
    public FileUploader() {
		opplist = New List<Opportunity>(); 
	}
    
    /***This function reads the CSV file and inserts records into objects. ***/
    public Pagereference ReadFile()
    {
        opplist.clear();
        try{
                //Convert the uploaded file which is in BLOB format into a string
                nameFile =blobToString( contentFile,'ISO-8859-1');
                
                //Now sepatate every row of the csv file
                filelines = nameFile.split('\n');
                
                //Iterate through every line and create a Record for each row
                for (Integer i=1; i<filelines.size(); i++)
                {                                       
                    String[] inputvalues = new String[]{};
                    inputvalues = filelines[i].split(',');
                    
                    con.FirstName = inputvalues[0] ;             
                 	con.LastName = inputvalues[1];
                 	con.MobilePhone = inputvalues[2];
                 	con.Personal_Email__c = inputvalues[3];
                 	con.OwnerId = this.ownerId;
                 	con.Integration__c = this.integrationName;
                 	insert con;
                 
                 	Contact queriedCon = [SELECT Id, FirstName, LastName, AccountId FROM Contact WHERE Id = :con.Id];
                 	opp.CloseDate = this.closeDate;
                 	opp.RecordTypeId = this.recordType;
                 	opp.OwnerId = this.ownerId;
				 	opp.Contact__c = queriedCon.Id;
				 	opp.AccountId = queriedCon.AccountId;
				 	opp.Name = queriedCon.FirstName + ' ' + queriedCon.LastName;
                 	opp.Program_of_Interest__c = inputvalues[4];
                    campaignlookup = inputvalues[5];
                    Campaign[] campaignId = [SELECT Id FROM Campaign WHERE Name = :campaignlookup];
                    if (campaignId.size() > 0) {
                        opp.CampaignId = campaignId[0].Id;
                    }
                 	opp.StageName = 'New';
        		 	opp.Integration__c = this.integrationName;
                 	insert opp;
                    opplist.add(opp);
                 
                 	Integration_Origin__c origin = new Integration_Origin__c();
        		 	origin.Contact__c = queriedCon.id;
        		 	origin.Opportunity__c = opp.id;
        		 	origin.Integration__c = [SELECT Id FROM Integration__c WHERE Name = :this.integrationName].Id;
        		 	insert origin;
                 
                 	initializeObjects();
                    campaignlookup = null;
                }
         }
         catch(Exception e){
             	initializeObjects();
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file '+e.getMessage());
                ApexPages.addMessage(errormsg);
         }               
        return null;
    }
    
    public List<Opportunity> getuploadedOpp () {
        return opplist;
    }
        /**
         This function converts the input CSV file in BLOB format into a string
        @param input    Blob data representing correct string in @inCharset encoding
        @param inCharset    encoding of the Blob data
     */
    public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
            bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }
}

Visualforce Page:
 
<apex:page sidebar="false" controller="FileUploader" docType="html-5.0" lightningStylesheets="true">
    <apex:slds />
   <apex:form >
      <apex:sectionHeader title="Upload data from CSV file"/>
      <apex:pagemessages />
       
      <apex:pageBlock >
          <apex:pageBlockSection id="RequiredBlock" rendered="true" title="Required Information">		            
            <apex:input required="true" type="date" label="Expected Start Date"  value="{!CloseDate}"/>
            <apex:selectList required="true" id="recordtypeSelection" size="1" label="Student Type" value="{!recordType}">
            	<apex:selectOptions value="{!recordOptions}"/>
            </apex:selectList>
            <apex:selectList required="true" id="userSelect" size="1" label="Advisor" value="{!ownerId}">
            	<apex:selectOptions value="{!repSelectOptions}"/>
            </apex:selectList>
          </apex:pageBlockSection>
      </apex:pageBlock> 
       
      <apex:pageBlock >
             <!--  Component to allow user to upload file from local machine -->
             <center>
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:100px;"/>
              <br/> <br/> <font color="red"> <b>Note: Please use the standard template to upload Records. <a href="https://universities.my.salesforce.com/sfc/p/6A000000voho/a/3s000000PTVs/HzZ5Kbu_BdhxG51fDbiHaTMZHguLFRg6gjYC2e75BIg" target="_blank"> Click here </a> to download the template. </b> </font>
             </center>  
       </apex:pageBlock> 
      <!-- After the user clicks the 'Upload File' button, this section displays the inserted data -->
       <apex:pageBlock title="Successfully Imported Students">
      
          <apex:pageblocktable value="{!opplist}" var="opp" rendered="{!NOT(ISNULL(opplist))}">
          <apex:column headerValue="Opportunity ID">
              <apex:outputField value="{!opp.Id}"/>
          </apex:column>
          <apex:column headerValue="Opportunity Name">
              <apex:outputField value="{!opp.Name}"/>
          </apex:column>
          <apex:column headerValue="Expected Starte Date">
              <apex:outputField value="{!opp.CloseDate}"/>
          </apex:column>
          <apex:column headerValue="Campaign Source">
              <apex:outputField value="{!opp.CampaignId}"/>
          </apex:column>
          <apex:column headerValue="Opportunity Owner">
              <apex:outputField value="{!opp.OwnerId}"/>
          </apex:column>
      </apex:pageblocktable>            
       </apex:pageBlock>
           
   </apex:form>   
</apex:page>

 

This is probably a super simple question... I built a lightning component that consists of images and direct you to different pages when you click on them. 
User-added image

The buttons work fine, but the cursor doen't change to a pointer icon when you hover over the image. Please help me update my code:

Component
<aura:component implements="forceCommunity:availableForAllPageTypes" access="global" >
    <div class="c-container">
        <div class="slds-grid slds-grid_align-center">
            <div class="slds-col slds-p-right_xx-large" onclick="{!c.startNewApplication}">
                <img src="{!$Resource.LexPartnerPortalCreateNCA}"/>
            </div>
            <div class="slds-col slds-p-right_xx-large" onclick="{!c.createLendingCircle}">
                <img src="{!$Resource.LexPartnerPortalCreateLC}"/>
            </div>
        </div>
    </div>
</aura:component>

Controller
({
    startNewApplication : function (cmp, event, helper) {
        window.location.href = '/lightningPartners/PublicClientApplication';
    },

    createLendingCircle : function (cmp, event, helper) {
        window.location.href = '/lightningPartners/partnercreatelendingcircle';
    },

    submitACase: function (cmp, event, helper) {
        window.location.href = '/lightningPartners/s/createrecord/NewCase';
    }
})
Hello,

I want to get a token from the end point:
User-added image
For passing parameters in end point i have Authorization, Header and Body.

Ho can i write the code for the Authorization part, Authorization type = basic, User name and password, etc 

I already have written code for header and body

thank you for suggestion !

Hi, 

I am not able to cover this class. Can anybody help me?

public class fileImport {
    public Blob fileBody;
    public String fileName;
    public String templateName;
    public String careProgram;
    public Date fileDate;
    public String importName;
}

Thanks!
 
Hello All, 

I am working on deploying a custom APEX trigger on the Case object that automatically initiates my org's active case assignment rules whenever a new case is created (except cases created with the record type name = "Member Concern"). In our configured org., we are having users create most new cases through Action Buttons, which unfortunately has the limitation that it cannot default the assignment rules and therefore, I require this apex trigger.

Here is my current trigger code that I have tested in my sandbox org: 
trigger AssignmentRulesonCaseTrigger on Case (after insert) {
    List<Id> caseIds = new List<Id>{};
    Id RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Member Concern').getRecordTypeId();
    if(trigger.IsAfter && trigger.isInsert ){
        for (Case theCase:trigger.new)
        {
            if(theCase.RecordTypeId != RecordTypeId)
            {
                caseIds.add(theCase.Id);
            }
        }        
        List<Case> cases = new List<Case>{};
        
        if(caseIds.size() > 0)
        {
            for(Case c : [Select Id from Case where Id in :caseIds])
            {
                Database.DMLOptions dmo = new Database.DMLOptions();
                dmo.assignmentRuleHeader.useDefaultRule = true;
                c.setOptions(dmo);
                cases.add(c);
            }
            Database.upsert(cases);
        }
    }
 }
I am very new to Apex and I am having difficulty navigating the creation of a custom test class that will allow me to deploy the above trigger into Production. Could someone provide me guidance/assistance on how to write a test class that will provide the coverage needed to deploy this trigger?

Thanks in advance - any and all help is GREATLY appreciated.

Ricki
 
Hello, I am trying to iterate over a list of SObjects, but I'm not sure how to get it to display.

Here is the controller
public with sharing class RandomRecordAudit {
    @AuraEnabled(cacheable=true)
    public static map<string, string> getAllObjects(){
        map<string, string> objectList = new map<string, string>();
        for ( Schema.SObjectType o : Schema.getGlobalDescribe().values() )
        {
            Schema.DescribeSObjectResult objResult = o.getDescribe();
            objectList.put(objResult.getName(), objResult.getLabel());
        }
        return objectList;
    } 
}

Here is the JS file
import { LightningElement, track } from 'lwc';
import getAllObjects from '@salesforce/apex/RandomRecordAudit.getAllObjects';
export default class SObjectList extends LightningElement {
    
        @track objects;
        @track error;
    
        handleLoad() {
            getAllObjects()
                .then(result => {
                    this.objects = result;
                })
                .catch(error => {
                    this.error = error;
                });
        
    }
}

and here is the HTML
<template>
    <lightning-card title="ApexImperativeMethod" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <template if:true={objects}>
                <template for:each={objects} for:item="object">
                    <p key={object.Id}>{object.Name}</p>
                </template>
            </template>
            <template if:true={error}>
                <p>Error</p>
                <c-error-panel errors={error}></c-error-panel>
            </template>
        </div>
    </lightning-card>
</template>

Any help is greatly appreciated, thanks!​​​​​​​
Hi there,

I am working on deploying a custom APEX trigger on the ContentDocumentLink object that checks a custom checkbox field called Has_Attachment__c on a custom object called "Advice" (Advice__c) when a file has been uploaded within a record. 

Here is my current Trigger code:
trigger ContentDocumentLinkTrigger on ContentDocumentLink ( after insert, after update, after delete ) {

    List<ContentDocumentLink> cdls = ( Trigger.new == null ? Trigger.old : Trigger.new );

    Set<ID> parentIds = New Set<ID>();

    for ( ContentDocumentLink cdl : cdls ) {
        parentIds.add( cdl.LinkedEntityId );
}

    for ( List<Advice__c> adviceToUpdate: [ SELECT Id, ( SELECT Id FROM ContentDocumentLinks LIMIT 1 ) FROM Advice__c WHERE Id IN :parentIds ] ) {
        
        for ( Advice__c q : adviceToUpdate) {
            q.HasAttachment__c = true ;
        }

        update adviceToUpdate;

    }

}
Evidently, now that I am trying to move it into my Production org., I am required to have at least 75% code coverage. I am very new to Apex and I am having difficulty finding the right resources to help me create a test class.

Could anyone provide some assistance with creating an test class for my trigger above that will allow me to deploy it into Production? 

Thanks in advance for any and all help. I really appreciate it.

Ricki
 
Our original SF developer isn't able to help me with this very small project because they only do large projects. The developer created a flow for us to combine contact names with their significant other's name to use for mailing labels. However, at this point we realize the flow needs to be edited and I am not secure enough with flows to edit it myself. Is there someone out here who could do a short-term project to edit this flow?
I am trying to list all my related contracts to an agency X..

Here is my code:
ContractsList component

 <aura:component controller="ContractsController" 
                implements="flexipage:availableForRecordHome,force:hasRecordId" 
                access="global" >
    
    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="Agency" type="ibrahimdevo__Agency__c" />
    <aura:attribute name="Contracts" type="ibrahimdevo__Contract__c" />
    <aura:attribute name="Columns" type="List" />
    <aura:handler name="init" value="{!this}" action="{!c.myAction}" />
    
    <force:recordData aura:id="agencyRecord"
                      recordId="{!v.recordId}"
                      targetFields="{!v.Agency}"
                      layoutType="FULL"
                      />
    <lightning:card iconName="standard:event" title="{! 'Liste de contrats pour ' + v.Agency.ibrahimdevo__agency_name__c}">
        
        <lightning:datatable data="{! v.Contracts}" columns="{! v.Columns }" keyField="Id" hideCheckboxColumn="true"/>
    
    </lightning:card>

ContractsListController
({
    myAction : function(component, event, helper) {
        
        var action = component.get("c.getContracts");
        
        component.set("v.Columns", [
            {label:"Contract Code", fieldName:"ContractCode", type:"text"},
            {label:"Valid From", fieldName:"ValidFrom", type:"Date"},
            {label:"Valid To", fieldName:"ValidTo", type:"Date"},
            {label:"Signed date", fieldName:"SignedDate", type:"Date"}
        ]);

        action.setParams({
            recordID: component.get("v.recordId")
        });
        
        action.setCallback(this, function(data){
            component.set("v.Contracts", data.getReturnValue());
        });
        
        $A.enqueueAction(action);
        
    }
})

ContractsController

@AuraEnabled
    public static List<ibrahimdevo__Contract__c> getContracts(Id recordId) {
        return[Select Name, ibrahimdevo__contract_code__c, ibrahimdevo__date_signed__c, 
                ibrahimdevo__valid_from__c, ibrahimdevo__valid_to__c, ibrahimdevo__details__c 
                From ibrahimdevo__Contract__c Where ibrahimdevo__agency_id__r.id = :recordId];
    }

i am not getting any errors but the list doesn't show up :(
thanks in advance


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

Is there any way to retrieve my SF Dev Org Because i lost my Org Due to the Authenticator App in my Mobile i.e, am uninstalled the Authenticator App in my Phone which have a link with my Dev Org.

Thanks,
Raj.
I have written the following test class and receive error "FATAL_ERROR System.DmlException: Insert failed. First exception on row 0 with id 0015B000015c9L1QAI; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]" when I run it, can anyone tell me what I am doing wrong?

@isTest
private class test_SaveAccountDetails {
    
    static testmethod void SaveAccountDetailTest() {
        Id RecordTypeIdPropAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Property').getRecordTypeId();
        
        Account acctForm = new Account();
        acctForm.RecordTypeId=RecordTypeIdPropAccount;
        acctForm.Name = 'Test Account';
        acctForm.PropertyNumber__c = '123456';
        acctForm.PropertyType__c = 'Retail';
        acctForm.Phone = '8885551212';
        acctForm.PropertyStatus__c = 'Potential Acquisition';
        acctForm.Website = 'www.testsite.com';
        acctForm.Description = 'test account description';
        acctForm.Region__c = 'test region';
        acctForm.PurchaseDate__c = date.parse('2/2/2000');
        acctForm.PurchasePrice__c = 350000;    
        acctForm.DateSold__c = date.parse('2/2/2019');
        acctForm.SalePrice__c = 500000;
        acctForm.BillingCountry = 'United States';   
        acctForm.ShippingCountry = 'United States';
        acctForm.BillingStreet = '1313 Mockingbird Lane';
        acctForm.ShippingStreet = '100 Art Rooney Ave';
        acctForm.BillingCity = 'Springfield';
        acctForm.BillingState = 'Missouri';    
        acctForm.ShippingCity = 'Pittsburgh';
        acctForm.ShippingState = 'Pennsylvania';
        acctForm.BillingPostalCode = '12345';   
        acctForm.ShippingPostalCode = '15212';
        
        insert acctForm;
        
        Test.startTest();        
        SaveAccountDetails.SaveAccountDetail(acctForm);
        Test.stopTest();
            
        
        
    }
}

Here is the class I am trying to provide code coverage for:

public class SaveAccountDetails {
    
    @AuraEnabled
    public static id SaveAccountDetail(Account acctForm){
        //DML operation to save AcctForm Details
        system.debug(acctForm);
        Id recTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Property').getRecordTypeId();
        acctForm.RecordTypeId=recTypeId;
        insert acctForm;
        return acctForm.id;
    }
}

I would really appreciate any help provided!
({
	navigate : function(component, event, helper) {
        var navigateEvent = $A.get("e.force:navigateToComponent");
        navigateEvent.setParams({
            componentDef: "c.RegistrationFormTutorial"
        });
        navigateEvent.fire();
	}
})

I want to navigate from one lightning component to another component (RegistrationFormTutorial). I have written the above code. But I am getting error like this:


" This page has an error. You might just need to refresh it. Action failed: c:HtmlTryout$controller$navigate [Cannot read property 'setParams' of undefined] Failing descriptor: {c:HtmlTryout$controller$navigate} "

Could anyone please help me on this. Thanks in advance.
I have two classes and i am quite puzzle to write their test class and not getting any coverage for them

first Apex Class

global class WS_ZipUtil {

  /**
   * Receive Attachments info from Attachment ParentId
   */
  webService static String getAttachmentById( String sfdcId ){

    if( String.isEmpty( sfdcId ) ) return WS_Util.errorJson('Parameter sfdcId is required.');
    
    List<Attachment> attachmentList =  [SELECT Id, Name, Body, ContentType FROM Attachment WHERE Id = :sfdcId];
    if( attachmentList == null || attachmentList.size() == 0 ) return WS_Util.errorJson('Attachment not found.');
    return wrapAttachmentList( attachmentList );
  }

  //Format JSON String from AttachmentList
  private static String wrapAttachmentList( List<Attachment> attachmentList ){

    List<Object> dataList = new List<Object>();
    for( Attachment at : attachmentList ){
      Map<String, String> atMap = new Map<String, String>();
      //atMap.put( 'Id', at.Id );
      atMap.put( 'Name', at.Name );
      atMap.put( 'Body', EncodingUtil.base64Encode( at.Body ) );
      //atMap.put( 'ContentType', at.ContentType );
      dataList.add( atMap );
    }
    return WS_Util.normalJson( dataList );
  }


}


Second Apex Class

public class WS_Util {

  //Normal Status Code
  private static String API_STATUS_NORMAL = '200';
  //Error Status Code
  private static String API_STATUS_ERROR  = '400';

  /**
   * Normal JSON Response
   */
  public static String normalJson( Object respData ) {
    Map<String, Object> response = new Map<String, Object>();
    response.put('status', API_STATUS_NORMAL);
    if( respData != null ) response.put('data', respData);
    return JSON.serialize( response );
  }

  /**
   * Error JSON Response
   */
  public static String errorJson( String message ) {
    Map<String, Object> response = new Map<String, Object>();
    response.put('status', API_STATUS_ERROR);
    if( message != null ) response.put('error', message);
    return JSON.serialize( response );
  }

}
Hi,
I have created a modal to create new lead using lightning Edit form and have included the required fields. When i am taking <lightning:inputField fieldName="Name" /> to enter the name the data gets saved but since i have a custom requirement i am using different API to enter the First Name but after clicking SAVE, the data is not getting saved and throwing an error:
"An error occured when trying to update the the record. please try again."
Please help me resolve the issue to save the whole record with Firstname as well.
 
<aura:component implements="lightning:actionOverride,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    <aura:attribute name="isOpen" type="boolean" default="true"/>
    <aura:attribute name="activeSections" type="List" default="['Pre-Enquiry Information','Scoring and Rating','Additional Information','System Information']" />
    
    <!--Use "slds-m-around_xx-large" class to add standard X-Large padding to the component--> 
    <div class="slds-m-around_xx-large">
        
        <!--Use aura:if tag to display Model Box, on the bese of conditions. [isOpen boolean attribute] -->   
        <aura:if isTrue="{!v.isOpen}">
            
            <!-- MODAL BOX Start --> 
            <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
                <div class="slds-modal__container">
                    <!-- MODAL BOX HEADER Start -->
                    <header class="slds-modal__header">
                        <lightning:buttonIcon iconName="utility:close"
                                              onclick="{! c.closeModel }"
                                              alternativeText="close"
                                              variant="bare-inverse"
                                              class="slds-modal__close"/>
                        <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">New Pre-Enquiry</h2>
                    </header>
                    <!-- MODAL BOX BODY Part Start -->
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <lightning:recordEditForm aura:id ="newPreEnquiry" recordId="{!v.recordId}" objectApiName="Lead" onsuccess="{!c.handleSuccess}">
                            <lightning:accordion allowMultipleSectionsOpen="true" activeSectionName="{!v.activeSections}">
                                <lightning:accordionSection name="Pre-Enquiry Information" label="Pre-Enquiry Information">
                                    <lightning:messages />
                                    <!-- Forming a grid of two equal columns -->
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="Salutation" />
                                            <lightning:inputField fieldName="FirstName" required="true"/>
                                            <lightning:inputField fieldName="LastName" />
                                            <lightning:inputField fieldName="Name" class="slds-hide"/>
                                            <!--<lightning:inputField fieldName="Name" />-->
                                        </div>
                                        <div class="slds-size_1-of-2">
                                                
                                            <div style="padding-top: 25px"><lightning:inputField fieldName="LX_Other_Title__c" /></div>
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Location__c" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="MobilePhone" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="Email" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Other_Pre_Enquiry_Source__c" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Generated_By__c" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Category__c" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_PreEnquiry_Source__c" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="Company" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Customer_Type__c" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Other_Preferred_Mode_of_Contact__c" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Enquiry_Type__c" />
                                        </div>
                                    </p>
                                </lightning:accordionSection>
                            </lightning:accordion>
                        </lightning:recordEditForm>
                    </div>
                    <!--###### MODAL BOX FOOTER Part Start ######-->
                    <footer class="slds-modal__footer">
                        <lightning:button variant="neutral" 
                                          label="Cancel"
                                          title="Cancel"
                                          onclick="{!c.closeModel}"/>
                        <lightning:button variant="brand" 
                                          type="submit"
                                          name="save"
                                          label="Save"
                                          onclick="{!c.onRecordSubmit}"/>
                    </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
            <!--###### MODAL BOX Part END Here ######-->
            
        </aura:if>
    </div>   
</aura:component>

JS controller:
({
    myAction : function(component, event, helper) {
        
    },
    openModel: function(component, event, helper) {
        // for Display Model,set the "isOpen" attribute to "true"
        component.set("v.isOpen", true);
    },
    
    closeModel: function(component, event, helper) {
        // for Hide/Close Model,set the "isOpen" attribute to "False"  
        component.set("v.isOpen", false);
    },
    
    onRecordSubmit: function(component, event, helper) {
        event.preventDefault(); // stop form submission
        var eventFields = event.getParam("fields");
        component.find('newPreEnquiry').submit(eventFields);
    },
    
    /*handleSubmit : function(cmp, event, helper) {
        event.preventDefault();       // stop the form from submitting
        const fields = event.getParam('fields');
        fields.LastName = 'My Custom Last Name'; // modify a field
        cmp.find('myRecordForm').submit(fields);
    },*/
    
    handleSuccess : function(component, event, helper) {
        var preEnquiryRecord = event.getParams().response;
        var navEvt = $A.get("e.force:navigateToSObject");
        navEvt.setParams({
            "recordId": preEnquiryRecord.id,
            "slideDevName": "related"
        });
        navEvt.fire();
        
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            title : 'Success!',
            message: 'Pre-Enquiry record created.',
            duration:' 1000',
            key: 'info_alt',
            type: 'success',
            mode: 'dismissible'
        });
        toastEvent.fire();
    }
})
Hello all,

I'm trying to populate owner's name to Enrollment_Rep__c field on Lead Object based on the profile name.  Everything works till I change the Owner from User to Queue.  I'm running to System.NullPointerException on the trigger.
trigger EnrollmentRep on Lead (before insert, before update) {
    
    Set<Id> ownerIds = new Set<Id>();

    for (Lead newLead : Trigger.new) {
        ownerIds.add(newLead.OwnerId); 
    }

    Map<Id,User> mapUsers = new Map<Id, User>([SELECT Id, Profile.Name, Name FROM User Where Id In :ownerIds]);

    for (Lead newLead : Trigger.new) {
        User oOwner = mapUsers.get(newLead.OwnerId);
        
        if (oOwner.Profile.Name == 'CEO'){
            newLead.Enrollment_Rep__c = oOwner.Name;
        }
    }
}

I'm new to the trigger and I'm not sure where to use IF statement Lead Owner != Queue.

Any suggestions will be helpful.

Thanks!
​​​​​​​John
 
I need to do certification maintenance for platform developer summer 19.

Has anyone done this already?

Pls tell me how to proceed.

Thanks
Tina

 
Hi everyone,

I'm getting this error on line 58:
ystem.NullPointerException: Attempt to de-reference a null object

Below is the code. I'm planning to put this code on Process Builder. This code will transfer the opportunity to other representatives when the opportunity has been touched for 4 days. Before transferring away, it will create a record on Round Robin Record object. Record Distribution is the list of teams. Record Distribution Mapping is the list of Representatives with a lookup field to Record Distribution object.
 
public class RoundRobinOpp {
    public class RRRequest {
        @InvocableVariable
        public String opportunityName;
        
        @InvocableVariable
        public String distributionName;
        
        @InvocableVariable
        public Id opportunityId;
        
        @InvocableVariable
        public Id ownerId;   
    }
    
    public static List<Record_Distribution_Mapping__c> getRepsByDistribution(String distributionName) {
        return [select User__r.id, CreatedDate, Record_Distribution__c, Record_Distribution__r.Number_of_RR__c 
                from Record_Distribution_Mapping__c 
                where Record_Distribution__r.Name = :distributionName
                order by CreatedDate asc];
    }
    
    @InvocableMethod
    public static void RoundRobinOpp(List<RRRequest> requests) {
        Set<String> distributionnames = new Set<String>();
        Set<Id> username = new Set<Id>();
        
        for (RRRequest request : requests) {
			distributionnames.add(request.distributionName);
            username.add(request.ownerId);
        }
        
        Map<String, List<Record_Distribution_Mapping__c>> distributionToMappings = new Map<String, List<Record_Distribution_Mapping__c>>();
        Map<String, Record_Distribution__c> relevantDistributions = new Map<String, Record_Distribution__c>();
        Map<String, Record_Distribution_Mapping__c> relevantUser = new Map<String, Record_Distribution_Mapping__c>();
        
        for (Record_Distribution_Mapping__c users : [SELECT User__c, Opportunity_Name_1__c, Opportunity_Name_2__c, Opportunity_Name_3__c, Number_of_Opp__c
                                                     FROM Record_Distribution_Mapping__c WHERE User__c = :username]) {
                                                         relevantUser.put(users.User__c,users);
                                                     }
        
        for (Record_Distribution__c distribution : [select Name, Number_of_RR__c from Record_Distribution__c where name in :distributionnames]) {
			relevantDistributions.put(distribution.name, distribution);
		}
        
        for (String distributionName : distributionnames) {
			distributionToMappings.put(distributionName, getRepsByDistribution(distributionName));
		}      
        
        List<Round_Robin_Record__c> lstRRrecord = new List<Round_Robin_Record__c>();
        List<Opportunity> lstOppsToUpdate = new List<Opportunity>();
        for (RRRequest request : requests) {
            Round_Robin_Record__c newRecord = new Round_Robin_Record__c();
            newRecord.Opportunity_Name__c = request.opportunityName;
            newRecord.User__c = request.ownerId;
            
            Record_Distribution_Mapping__c updateRRnumber = relevantUser.get(request.ownerId);
            updateRRnumber.Number_of_Opp__c++;
            //Might add the opportunity names for reporting
            
            Opportunity reassignedOpp = new Opportunity(id = request.opportunityId);
            Record_Distribution__c TeamDistribution =  relevantDistributions.get(request.distributionName);
            reassignedOpp.OwnerId = distributionToMappings.get(request.distributionName)[Math.mod((Integer) TeamDistribution.Number_of_RR__c,
                                                                                                 distributionToMappings.get(request.distributionName).size())].User__r.id;
            lstRRrecord.add(newRecord);
            TeamDistribution.Number_of_RR__c++;
            lstOppsToUpdate.add(reassignedOpp);
        }
        
        insert lstRRrecord;
        update lstOppsToUpdate;
        update relevantDistributions.values();
        update relevantUser.values();
    }
}

I can't find the reason why the Number_of_Opp__c is empty, I have put 0 in that field for each record already.

Please help! Thanks in advance.
<apex:page standardController="Account">


<script>
function colorPageBlock(pageblock, color) {
if (pageblock != null) pageblock.firstChild.style.cssText = “background-color: ” + color + “;”;

}
</script>


<apex:form>


<apex:pageBlock title="My Content" mode="detail">
<apex:pageBlockSection id="redSection" title="My Content Section" columns="2">
<apex:inputField value="{!account.name}"/>
<apex:inputField value="{!account.site}"/>
<script>colorPageBlock(document.getElementById("{!$Component.redSection}"), "red");</script>
</apex:pageBlockSection>

<apex:pageBlockSection id="greenSection" title="My Content Section" columns="2">
<apex:inputField value="{!account.name}"/>
<apex:inputField value="{!account.site}"/>
<script>colorPageBlock(document.getElementById("{!$Component.greenSection}"), "green");</script>
</apex:pageBlockSection>

<apex:pageBlockSection id="orangeSection" title="My Content Section" columns="2">
<apex:inputField value="{!account.name}"/>
<apex:inputField value="{!account.site}"/>
<script>colorPageBlock(document.getElementById("{!$Component.orangeSection}"), "orange");</script>
</apex:pageBlockSection>
</apex:pageBlock>

</apex:form>

</apex:page>

 
<template>
<div if:false={loggedIn} class="slds-m-around_medium"> <span>Login to Salesforce App</span> <div>
<lightning-input data-username='username' label="Username"></lightning-input>
<lightning-input type="password" data-password='password' label="Password">
</lightning-input> <br/>
<lightning-button variant="brand" label="Login" title="Login" onclick={login}></lightning-button>
</div>
</div>
</template>

JS

import { LightningElement, track } from 'lwc';
export default class App extends LightningElement
{
loggedIn = false;
username = '';
password = '';
login()
{
this.username = this.template.querySelector("lightning-input[data-username]").value;
this.password = this.template.querySelector("lightning-input[data-password]").value
console.log("Username>> ", this.username); console.log("Password>> ", this.password);
}
}
Hello everybody,

do someone know how to change the color of lightning-button-icon to white?

Based on this example (https://lightningdesignsystem.com/components/modals/#Small-Modal) I've build the following modal window:
User-added image

Everything works fine, except the color of the button-icon.
Does someone know how to style this button into white?


Greetings,
Christian
 
I am trying to remove and replace a few strings that are rendering incorrectly for a Rich Text field through an Apex Trigger. Any idea what is incorrect with the following code?
 
trigger removeCharacters on ts2__Job__c (before insert) {
    String str = '\u00A0';
    String str2 = 'Â';
    String replacement = ' ';
    for(ts2__Job__c des : trigger.new){
        if(des.ts2__Job_Advertisement__c.contains(str)){
            des.ts2__Job_Advertisement__c.replace(str, replacement);
        }
        if(des.ts2__Job_Advertisement__c.contains(str2)){
            des.ts2__Job_Advertisement__c.replace(str2, replacement);
        }
    }

}

 
Hello everyone,
I have 3 custom objects. Car__c, Service__c, Action__c,
I would really like to know how to get a list of all cars where Action__c.category = 'SOME VALUE'.
Link mapping looks like this
User-added image

Hello,

Did anyone else notice that the view state limit in Visualforce pages has been increased from 135 to 170 KB in the new release of Spring 2019