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


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


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

Syntax help please.  I am trying to access the fields in my SOQL search.  I am receiving error message:

`System.SObjectException: Invalid field Parent_Project_if_applicable__r.Implementation_status__c for Case`

I verified Relationship name through WorkBench.

My code is:

List<Case> caseList = [SELECT Id, AccountId, Account.Name,Parent_Project_if_applicable__r.Implementation_status__c,
                       Parent_Project_if_applicable__r.PM_Implementation_Status__c, 
                       Parent_Project_if_applicable__r.RCM_Implementation_Status__c,
                       Parent_Project_if_applicable__r.Client_Advisor_Email__c
                       FROM Case
                       WHERE AccountId IN :AcctIds];

for(Case cl:caseList){ 
    System.debug(cl.get('Parent_Project_if_applicable__r.Implementation_status__c'));
}
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
I’m having trouble with my test class…not sure what I’m doing wrong, but I’m getting the following errors:
Illegal assignment from Map to List (line 6)
Method does not exist or incorrect signature: void getRecTypeId(String) from the type RecordTypeSelector (line 11)

My test class is for a custom record type selector component on my Asset object for my customer object OrderProject__c.

Any help would be appreciated!!
 
@isTest
public class TestRecordTypeSelector {


static testmethod void testFetchRecordTypes() {
    List<String> value = RecordTypeSelector.fetchRecordTypeValues('Asset');
  }

 static testmethod void testgetRecordTypeId() {
    String recordTypeLabel = 'Avaya';
    ID testId = RecordTypeSelector.getRecTypeId(recordTypeLabel);
    System.assert(testId != null);
  }
}

 
I have a validation rule set up that allows the administrator to edit the page after stage and status is changed by a team and the page is locked. I would like to allow another profile to be able to edit the page after the stage and status are changed. 
CURRENT formula: 

AND(

NOT(AND($User.ProfileId = "00e30000000dT2u, 00e40000000rTwW",OR(ISCHANGED(Installation_Stage__c),ISCHANGED(Installation_Status__c)))),

OR(
ISPICKVAL(PRIORVALUE(Installation_Stage__c), "Complete"),
ISPICKVAL(PRIORVALUE(Installation_Status__c), "Sent to GHU")
)

)

Need to add profile "00e40000000rTwW" but syntax error keeps saying I am missing a ). 


 
Hi,


I am trying to complete the code coverage:
below is code(main class and test class)

@RestResource(urlMapping='/leadactivity/getlist/*')
global with sharing  class myActivityTask {
    
    @HttpGet
    global static  list<cust_map> doGetLead(){
        list<task> activityLog=new list<task> ();
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        map<string,string> paramsMap=RestContext.request.params;
        string actdate=paramsMap.get('actdate');
        Datetime dt1 = Datetime.valueOf(actdate);
        list<cust_map> results = new list<cust_map>();        
        list<Task> taskList=[SELECT WhoId,CompletedDateTime,Id,who.type FROM Task where CreatedDate>:dt1];
        for(task str:taskList){
            cust_map obj = new cust_map();
            if(str.who.type!='Lead')
                continue;
            Lead result = [SELECT id FROM Lead WHERE Id = :str.WhoId];
            obj.LeadID =     str.WhoId; 
            obj.CallDateTime = str.CompletedDateTime;
            results.add(obj);
        }
        return results;
    }
    global class cust_map{
        Global String LeadID=null;
        Global String CallCenterAgent=null;
        Global Datetime CallDateTime=null;
        Global String LMSID = null;
    }
}
==========
Test class
=========
@isTest
private class MyActivityTask_Test{
    
    public testmethod static void MyActivityTask(){
        
        // insert lead data
        lead l = new lead();
        l.LastName = 'Test Lead';
        l.Company = 'Test Company';
        l.Status = 'Closed - Converted';
        insert l;
        
        task t = new task();
        t.Subject = 'Test Subject';
        t.Status = 'new';
        t.Priority = 'Normal';
        t.CallType = 'Outbound';
        t.WhoId = l.Id;
        insert t;
     //   List<myActivityTask.cust_map> results1 = myActivityTask.doGetLead();   
        list<task> taskList=[select id,whoId from task where createdDate=today];
           // list<lead> leadResult=[select id from lead where id=:st.whoId]; 
        system.Test.startTest();
        // call custom controller
        myActivityTask mat = new myActivityTask();
        myActivityTask.cust_map wrap = new myActivityTask.cust_map();
        wrap.LeadID = t.WhoId;
        wrap.CallDateTime = t.CompletedDateTime;
        RestResponse res = new RestResponse();
        RestRequest req = new RestRequest();
         req.params.put('actdate', '2019-12-30 23:01:01');
       // datetime actDateTime = System.today()-1;
        //req.params.put('actdate', actDateTime .format('yyyy-MM-dd\'T\'hh:mm:ss\'Z\''));
        req.httpMethod = 'Get';
        req.addHeader('Content-Type', 'application/json'); // Add a JSON Header as it is validated
        req.requestURI = '/services/apexrest/salesforce.com/leadactivity/getlist' ;  
        RestContext.request = req;
        RestContext.response = res;
        List<myActivityTask.cust_map> results = myActivityTask.doGetLead();
        system.Test.stopTest();
 }   
}
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! 

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

 

 

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