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


  • Chatter
    Feed
  • 251
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 13
    Questions
  • 917
    Replies
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


 
Hi Everyone,

I wrote a simple trigger that concatenates some fields into a key__c, and now I am trying to test it. I am having trouble getting it to return the tested inputs. Also, I was thinking of doing some bulk testing as well, should I write a loop? Here is what I have so far: 
Trigger 
trigger Composite_Key on Purchases__c (before insert, before update) {
    if(Trigger.isBefore)
    {
        for(Purchases__c purchase : trigger.new)
        {
            String eventName = String.isBlank(purchase.Event_name__c)?'':purchase.Event_name__c+'-';
            String section = String.isBlank(purchase.section__c)?'':purchase.section__c+'-';
            String row = String.isBlank(purchase.row__c)?'':purchase.row__c+'-';
            String seat = String.isBlank(String.valueOf(purchase.seat__c))?'':String.valueOf(purchase.seat__c)+'-';
            String numseats = String.isBlank(String.valueOf(purchase.number_of_seats__c))?'':String.valueOf(purchase.number_of_seats__c)+'-';
            String adddatetime = String.isBlank(String.valueOf(purchase.add_datetime__c))?'':String.valueOf(purchase.add_datetime__c);
            purchase.Key__c = eventName + section + row + seat + numseats + adddatetime;
        }
    }
}

Test so far
@isTest
private class CompositeKeyTest {
    
    static testMethod void testPurchase() {
        //create a purchase to fire the trigger
        Purchases__c purchase = new Purchases__c(Event_name__c = 'test', section__c='test',row__c='test', seat__c=1,number_of_seats__c='test',add_datetime__c='test');
        
        insert purchase;
        System.Assert(purchase.Key__c=='testtesttest1testtest');
    }
}

 
Hi everyone,
I'm working with a lightning component and it's working cool but I want to know if it's possible to disable certain days from a datepicker (weekends).
I did something similar but just for past days. 

I've reading that could be possible using jQuery but I can't find a good "documentation" about that, 

Thanks. 
Regards. 
Hello,

I'm trying to test the trigger below, however my test is not passing in the IF condition.

Trigger
trigger ValidateLead on Lead (before insert, before update){

	if (Trigger.isBefore) {
    	for(Lead led : trigger.new){

    		Lead leds = [SELECT Id, Name FROM Lead WHERE id=: led.Id];
    		
    			if(ValidaDocumento.isCNPJ(led.CNPJ__c))
    				led.CNPJ__c = ValidaDocumento.imprimeCNPJ(led.CNPJ__c);
    			else
    				led.addError('O CNPJ informado é Inválido');
	    }
    }
}

test class:
public static testMethod void createLead() {
	    
	    Lead prospect = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = 'teste',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		ValidaDocumento.isCNPJ(prospect.CNPJ__c);
		ValidaDocumento.imprimeCNPJ(prospect.CNPJ__c);
		insert prospect;
		
		Lead prospect2 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '68119173000167',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		ValidaDocumento.isCNPJ(prospect2.CNPJ__c);
		insert prospect2;
		
		Lead prospect3 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '00000000000000',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		insert prospect3;
		ValidaDocumento.isCNPJ(prospect3.CNPJ__c);
		
		Lead prospect4 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '11111111111111',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		insert prospect4;
		ValidaDocumento.isCNPJ(prospect4.CNPJ__c);
		
		Lead prospect5 = new Lead(
	        
			LastName = 'TestProspect',
			CNPJ__c = '681191730001',
			Company = 'TestCompany',
			Estado__c = 'SP'
		);
		insert prospect5;
	    ValidaDocumento.isCNPJ(prospect5.CNPJ__c);
	}
}
I'm in doubt how to make the test pass through my if conditional.
 
Can anyone let me know if im doing this correctly?

Need a validation rule that prevents a Sales user from updating a picklist to a Certain Value on a Certain Record Type.

For this excample, i want to prevent Sales User from updating picklist to Value1 (and allow all other values for them) for that record type

(AND( $User.ProfileId <> "Sales User",,$RecordType.Name = "Record Type Name",
ISCHANGED(Status__c),
NOT(ISPICKVAL(Status__c, 'Value2')),
NOT(ISPICKVAL(Status__c, 'Value3')),
NOT(ISPICKVAL(Status__c, 'Value4')),
)
)
Hello, 

I have a validation rule where the Picklist value = Yes, the text area field Assets Items should not be blank. The below VR is prompting that "Data Missing" Asset items are missing! when I complete the Assets Items field. 
Any idea how to modify the VR? 
Thank you!
 
AND(
    ISPICKVAL( Assets__c , 'Yes'),
    ISBLANK( Asset_Items__c )
)


 
  • September 16, 2019
  • Like
  • 0
Hello ,

Just got in a new instance and i have a question.
There is an integration with an other system and my instance send notification to it.
I looked into the class that make the call an i can observe that the URL of the other system is not used directly. And parameters also ( authentication , id ..) 
Here a sample of the variables used
public static String API_URL = 'callout:Api'

Where can i find the content of "API"?

Thank you
 
Hey there,

I'm new to APEX and curious about converting Apex Triggers to Apex Classes in order to be in line with the One-Trigger-per-Object pattern. 

Let's say I have the following, very simple Trigger: Whenever an Account gets updated, the number of related contacts gets populated in the custom field Number_of_Contacts__c. The Trigger code looks like this:
 
trigger relatedContacts on Account (before update) {  
   
   List<Contact> relatedContacts = [SELECT Id
                                    FROM   Contact
                                    WHERE  AccountId IN :Trigger.new];
        
   for (Account a : Trigger.new) {
        a.Number_of_Contacts__c = relatedContacts.size();
    }            
    
}
First question: How would the Apex Class for this Trigger look like?

Second question: How shall I reference the Apex Class in the Master Trigger for the Account object? At least I already know where to put it:
trigger MasterOpportunityTrigger on Opportunity (
  before insert, after insert, 
  before update, after update, 
  before delete, after delete) {

  if (Trigger.isBefore) {
    if (Trigger.isInsert) {

    } 
    if (Trigger.isUpdate) {
      // MY TRIGGER WILL GO HERE ;)
    }
    if (Trigger.isDelete) {

    }
  }

  if (Trigger.isAfter) {
    if (Trigger.isInsert) {

    } 
    if (Trigger.isUpdate) {

    }
    if (Trigger.isDelete) {

    }
  }
}

I would highly appreciate if someone could teach me this best practice!

Best, 
David
  • September 11, 2019
  • Like
  • 0
I am trying to create a formula that compares a date field Like Acme_Date__c = TODAY() then display "TODAY" for atext value. 

I'm not sure how to accomplish this result without getting errors 
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.
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! 

global class SendNPSbutton {
    @AuraEnabled
    public static void sendNPSEmail(Id cId)
    {
        EmailTemplate emiailTemp = new EmailTemplate();
        String htmlBody; 
        String plainBody;
        String subject;
        List<String> sendTo = new List<String>();
        contact cc = [select id from contact limit 1];
        
        Closing__c cpps = [SELECT Id,RecordTypeId,RecordType.Name,Seller_Email__c,Buyer_Email__c,Owner.FirstName,
                           Buyer_Account__c,Seller_Account__c,Seller_Account__r.Name,Appointment__r.Name
                           FROM Closing__c where Id=: cId LIMIT 1];
        
        if(cpps.Id != null)
        {
            if(cpps.RecordType.Name =='Listing Team'){
                sendTo.add(cpps.Seller_Email__c);
                emiailTemp = [SELECT Id, Name,Subject, DeveloperName,HtmlValue, Body FROM EmailTemplate where DeveloperName = 'NPS_Survey_npsSeller'];
                subject = emiailTemp.Subject;
                htmlBody= emiailTemp.HtmlValue;
                htmlBody = htmlBody.replace('{!Closing__c.Seller_Account__c}', cpps.Seller_Account__r.name);
                htmlBody = htmlBody.replace('{!Closing__c.OwnerFirstName}', cpps.Owner.FirstName);
                plainBody = emiailTemp.Body;
                plainBody = plainBody.replace('{!Closing__c.Seller_Account__c}', cpps.Seller_Account__c);
                plainBody = plainBody.replace('{!Closing__c.OwnerFirstName}', cpps.Owner.FirstName);
            }else{
                sendTo.add(cpps.Buyer_Email__c);
                emiailTemp = [SELECT Id, Name,Subject, DeveloperName,HtmlValue, Body FROM EmailTemplate where DeveloperName = 'NPS_Survey_nps'];
                subject = emiailTemp.Subject;
                htmlBody= emiailTemp.HtmlValue;
                htmlBody = htmlBody.replace('{!Closing__c.Buyer_Account__c}', cpps.Appointment__r.Name);
                htmlBody = htmlBody.replace('{!Closing__c.OwnerFirstName}', cpps.Owner.FirstName);
                plainBody = emiailTemp.Body;
                plainBody = plainBody.replace('{!Closing__c.Seller_Account__c}', cpps.Seller_Account__c);
                plainBody = plainBody.replace('{!Closing__c.OwnerFirstName}', cpps.Owner.FirstName);
            }
            // process the merge fields
            // String subject = emailTemplate.Subject;
            //  subject = subject.replace('{!Contact.FirstName}', c.FirstName);

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTemplateId(emiailTemp.Id);
            List<String> ccTo = new List<String>();
            ccTo.add('xyz@gomail.com');
            mail.setCcAddresses(ccTo);
            mail.setReplyTo('xyz@gomail.com');
            mail.setSenderDisplayName('XYZ');
            mail.setTargetObjectId(cc.id);
            mail.setTreatTargetObjectAsRecipient(false);
            mail.setWhatId(cpps.Id);
            mail.setToAddresses(sendTo);     
            mail.setBccSender(false);
            mail.setUseSignature(false);
            mail.setHtmlBody(htmlBody);
            mail.setSubject(subject);
            mail.setPlainTextBody(plainBody);
            mail.setSaveAsActivity(false);  
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
           
        }
    }
    
}

 

TEST Class:

@istest(SeeAllData=true)

public class SendNPSButton_test{
    
    static testmethod void testvalidate(){
        List<String> sendTo = new List<String>();
        Account acc = new Account();
        acc.Name = 'Name test';
        insert acc;
        Closing__c cl = new Closing__c();
        //cl.RecordTypeId=Schema.SObjectType.Closing__c.getRecordTypeInfosByName().get('Buying Team').getRecordTypeId();
        cl.Buyer_Email__c = 'ravi.7293@gmail.com';
        cl.Seller_Email__c ='ravi.7293@gmail.com';
        cl.Seller_Account__c = acc.Id;
        insert cl;
       EmailTemplate emiailTemp = [SELECT Id, Name,Subject, DeveloperName,HtmlValue, Body FROM EmailTemplate where DeveloperName = 'NPS_Survey_npsSeller'];
        /*Closing__c cpps = [SELECT Id,RecordTypeId,RecordType.Name,Seller_Email__c,Buyer_Email__c,Owner.FirstName,
                           Buyer_Account__c,Seller_Account__c,Seller_Account__r.Name,Appointment__r.Name
                           FROM Closing__c where Id=: cl.Id LIMIT 1];*/
        system.debug('cl>>: '+ cl);
        Test.startTest();
       // Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
         //   mail.setTemplateId(emiailTemp.Id);
        //mail.setToAddresses(sendTo);
        //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        system.debug('cl11>>: '+ cl.Seller_Email__c);
        system.debug('cID>>: '+ cl.ID);
        SendNPSbutton.sendNPSEmail(cl.Id);
        //Integer emailInvocations = Limits.getEmailInvocations();
        Test.stopTest();
        //system.assertEquals(1, emailInvocations, 'An email should be sent');
        
    }
}

 

 

Hi, I got a question. If we upload data from a .csv file through data loader which has 500 rows and due to some error my data is uploaded till 100th row. Now I want to  upload my data from 101st row without again inserting from the starting. How could I do it?
Dear Team ,

Greetings !!!

I implemented one Lightning Web Component in whicg created one Data Table . I deployed that component to org , command ran successfully but that component not appearing in App Builder . 

Kindly have a look on screenshot and please provide me some solutions .

Thanks & Regards
Sachin BhaleraoImage of Command ran successfully
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>

 

Hi,
I was asked in an interview the below question:
There is a custom object X and there is an Account Object.
Account object and X object do not have any relationship.

Whenever I will create an account record, I need to populate a text field with a value of X object on acccount object. This needs to be acheived using configuration and no customization.
public class LeadHandlerClass {
 public static void createContactRoleType (Map<id,lead> newMapLead, Map<id,Lead> oldMapLead){
        
        Set<Id> setOppId = new Set<Id>();
        Lead oldLead; 
        Lead newLead;
        Map<Id,Lead> mapContLead = new Map<Id,Lead>();
        
        for(Id CRId : newMapLead.keySet()){
            oldLead = OldMapLead.get(CRId);
            newLead = newMapLead.get(CRId);
            if(newLead.IsConverted && !oldLead.IsConverted){
                setOppId.add(newLead.ConvertedOpportunityId);
                mapContLead.put(newLead.ConvertedContactId,newLead);
            }
        }
        
        List<OpportunityContactRole> lsOppCtRole = [select id,ContactId, role from OpportunityContactRole where OpportunityId in: setOppId limit 50000];
        Lead tmpLead ;
        
        for(OpportunityContactRole oppCtRole : lsOppCtRole){
            tmpLead = mapContLead.get(OppCtRole.ContactId);
            OppctRole.Role = tmpLead.NIL_Contact_Type__c;
        }


        System.debug('Ls OppCtRole is ' + lsOppCtRole);
        if(!lsOppCtRole.isEmpty())
        {  
            Database.SaveResult[] results = Database.update(lsOppCtRole, false);
            for (Database.SaveResult res : results) {
                if (res.isSuccess()) {
                    System.debug('Successfully updated: ' + res.getId());
                } 
                else {
                    // This condition will be executed for failed records
                    for(Database.Error objErr : res.getErrors()) {
                        System.debug('The following error has occurred.');
                        // Printing error message in Debug log
                        System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());
                        System.debug('Update failed by the error:' + objErr.getFields());
                    }
                }
            }
        }
        
    }
 
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!
 
I snatched this code off the internet to use with Process Builder to auto convert leads meeting a certain criteria. The class works fine but the I can't seem to get any test coverage. I included the class and test class below. Can anyone tell me what I am doing wrong? 
public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(id currentlead: LeadIds){
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE); //Remove this line if you want to create an opportunity from Lead Conversion 
                MassLeadconvert.add(Leadconvert);
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}







​​​​​​​
@IsTest (SeeAllData=true) private class AutoConvertLead_Test{

    /* This is a basic test which simulates the primary positive case for the 
       Conversion method of a Lead. */

public static testMethod void myUnitTest() {

// create a Lead
Lead lead=new Lead(LastName='TestDoe',FirstName='TestJane',Company='TestUnknown',Status='Warm Prospect',Addy_Account_id__c='1234566');

insert lead;


Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(lead.id);
lc.setDoNotCreateOpportunity(true);
lc.setConvertedStatus('User');

Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());
}}
I am querying timesheets__c and looking to update the contact associated to the timesheet (timecardApprover__c) that is held in the parent object placement__c. I am able to get a list of ids of the contact I need to update but I can't figure out how to to update the field current_timesheet_status__c associated with the contact. 
public with sharing class contFlag {
    public contFlag() {

        List<String> timecardApproverIds = new List<String>();
        Set<Id> setofIds = new Set<Id>();

    for(jstcl__TG_Timesheet__c ts : [SELECT Placement__r.TimecardApprover__c FROM Timesheet__c WHERE Placement__r.Status__c = 'Active' AND Status__c = 'Pending']){
              timecardApproverIds.add(String.valueOf(ts));
        }

    for(String a : timecardApproverIds){
            setofIds.add(Id.valueOf(a));
        }
    for(Id c : setofIds){
        c.Current_Timesheet_Status__c = 'Pending';
        // returns error of variable does not exist due to it not being for the contact object
        }
    }
}


 
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!​​​​​​​

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