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


  • Chatter
    Feed
  • 347
    Best Answers
  • 3
    Likes Received
  • 11
    Likes Given
  • 15
    Questions
  • 1198
    Replies
User cannot change record owner If user is not System Admin, Industry is null and Account created after 1/1/2017
I tried this formula where the Profile Id is for System Administrator  but it fires even if the System Admin is editing the record.
$User.ProfileId  <> "0ei0000001DLN6"&&
 ISCHANGED( OwnerId )&&
 ISBLANK(TEXT(Industry ))&&
  DATEVALUE(CreatedDate) > DATE(2017,01,01)
 
My test case for a before insert/update trigger on Contact should be very simple, which means I am missing something obvious...the trigger itself takes the City, State Code, and Zip and pulls the county name from a custom county object.  This trigger is working as intended and populates the county name with no issue.  

What I can't figure out is why my test class does not return a value for the county after the insert.  (The insert code and requery works perfectly when running in an Execute Anonymous window). 

Below is the code for the insert test.  After inserting a new contact, when I try to requery for the new hed__Mailing_County__c value, the value is null, but it does pull the new contact id.  Any help is much appreciated!  :-)
 
@isTest
private class Contact_County_Test {
    static testMethod void TestInsertContact() {
        // Create contact with city, state, zip populated
        Contact con = new Contact(FirstName = 'TestInsert', 
                                  LastName = 'TestContact', 
                                  MailingCity = 'My City', 
                                  MailingStateCode = 'WI', 
                                  MailingPostalCode = '12345',
                                  MailingCountryCode = 'US',
                                  hed__Mailing_County__c = '');
        Insert con;

        //Requery to pull in new county name
        con = [SELECT hed__Mailing_County__c FROM Contact WHERE Id = :con.Id LIMIT 1];

         //Verify County Name is populated correctly
         System.assertEquals('County Name', con.hed__Mailing_County__c);
    }
}

 
I've successfully plotted the accounts on Google Map with Lightning Component and it works in Sandbox...but don't know how to write a test code for the ApexClass.

I describe the codes below and hope anyone can help with the test code part. Thank you!

Component (MapNearbyAccount.cmp)
<aura:component controller="MapNearbyAccountController" implements="flexipage:availableForAllPageTypes,force:hasRecordId">
    <aura:attribute name="mapMarkers" type="Object"/>
    <aura:attribute name="selectedMarkerValue" type="String" />
    
    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
    
    <div class="slds-box slds-theme--default">
        <lightning:map 
                       mapMarkers="{! v.mapMarkers }"
                       selectedMarkerValue="{!v.selectedMarkerValue}"
                       markersTitle="accounts nearby"
                       listView="auto"
                       showFooter="false"
                       onmarkerselect="{!c.handlerMarkerSelect}" />
    </div>
</aura:component>
Controller (MapNearbyAccount.js)
({
    init: function (cmp, event, helper) {
        var recordId = cmp.get("v.recordId");     
        var action = cmp.get("c.getAccounts");
        action.setParams({recordId :recordId});
        cmp.set('v.mapMarkers', [{location: {}}]);

        action.setCallback(this, function(response){
            
            var accounts = response.getReturnValue();
            var markers = [];
            for(var i = 0; i < accounts.length; i++){
                var acc = accounts[i];
                markers.push({
                    location: {
                        Country : acc.BillingCountry,
                        State : acc.BillingState,
                        City: acc.BillingCity,
                        Street: acc.BillingStreet
                    },
    
                    icon : "standard:account",
                    value: acc.Id,
                    title: acc.Name,
                    description:acc.Description
                });
            }
            
            if(markers.length != 0){
                cmp.set('v.mapMarkers', markers);
            }
        });

        $A.enqueueAction(action);
    },

    handlerMarkerSelect: function (cmp, event, helper) {
        console.log(event.getParam("selectedMarkerValue"));
    }
});
ApexClass (MapNearbyAccountController)
public class MapNearbyAccountController {
    @AuraEnabled
    public static List<Account> getAccounts(String BillingCity, String BillingState, String recordId){
        Account acct = [SELECT Id, Name, BillingCountry, BillingState, BillingCity, BillingStreet, Industry FROM Account WHERE Id =:recordId];
        
        return [SELECT Id, Name, BillingCountry, BillingState, BillingCity, BillingStreet,Description
                FROM Account 
                WHERE BillingState = :acct.BillingState AND BillingCity LIKE :('%' + acct.BillingCity + '%') AND Industry = :acct.Industry LIMIT 10];
    }
}
TestClass
@isTest
public class MapNearbyAccountControllerTest {
@isTest
    static void testMapNearbyAccountController() {
        Account acc1 = new Account();
        acc1.Name='acc1';
        acc1.BillingCity='Shibuya';
        acc1.BillingState='Tokyo';
        insert acc1;
        
        MapNearbyAccountController ctrl = new MapNearbyAccountController();
        
        Test.startTest();
            List<Account> getAccounts = ctrl.getAccounts();
            System.assertEquals(false,getAccounts.isEmpty());
        Test.stopTest();
    }
    
}
I am trying to get code coverage for the class below:
public class redirectToWebinarPageController{
    public pageReference redirectURL(){
        
        //get the external id from the URL
        String externalId = ApexPages.currentPage().getParameters().get('externalId');
        
        //query the record.
        Webinar__c webinarRecord = [select id from Webinar__c where Webinar_Count__c =: externalId];
        
        //redirect to detail page of the above record.
        return new pageReference('/'+webinarRecord.id);
       
    }
}
Here is the test I have and am getting 75% coverage but I would prefer to know how to get 100%
@isTest 
public class redirectToWebinarPageControllerTest {
    public static testMethod void testredirectURL() {
        test.startTest();
        PageReference pageRef = Page.redirectToWebinarDetailPage;
        
        //Your test data logics
        Account testAccount = new Account();
        testAccount.Name = 'Account Name';
        insert testAccount;
        
        Contact testContact = new Contact();
        testContact.LastName = 'Contact';
        testContact.FirstName = 'Test';
        testContact.Email = 'testContact@testing.com';
        insert testContact;
        
        Webinar__c w = new Webinar__c();
        w.Name = 'Test Webinar';
        w.Account__c = testAccount.id;
        w.Communication_Type__c = 'Client 4';
        w.Delivery_Method__c = 'Self Study';
        w.Contact__c = testContact.id;
        insert w;
        
        String testExternalId = w.Webinar_Count__c;

        Test.setCurrentPage(pageRef);
			
			pageRef.getParameters().put('externalId',testExternalId);
			
			redirectToWebinarPageController controller = new redirectToWebinarPageController();
			controller.redirectURL();
        
   		test.stopTest();
     }
}
Thank you in advance, I am really new to writing test classes and would love to know what I am missing here.
Hi I have written below apex method for LWC but i am getting "missing return statement required return type" error when trying to deploy to org.
please help me where i am doing wrong here.

public with sharing class bikeSearchResultController {
@AuraEnabled(cacheable=true)
public static list<Car__c> cardetailsapexmethod(string cartypeid){
    try {
        if(String.isEmpty(cartypeid)){
           return [SELECT Id,Available_For_Rent__c,Build_Year__c,Car_Type__c,Name,Picture__c
                   FROM Car__c];
        }else 
        if(!String.isEmpty(cartypeid)){
            return [SELECT Id,Available_For_Rent__c,Build_Year__c,Car_Type__c,Name,Picture__c
                    FROM Car__c
                    WHERE Car_Type__c=:cartypeid];
        }
    } catch (Exception e) {
        throw new AuraHandledException(e.getMessage());
    }
    
}
}

 

Hi. I found this apex class online (it's super simple). It triggered successfully in my sandbox. When deploying to my production org, I tried validating and received an error: 

Code Coverage Failure: Your code coverage is 0%. 

This is the Apex Class:
public class DeleteUnacceptedQuotes 
{
@InvocableMethod    
public static void QuoteDelete(List<Id> OpportunityIds)    
{        
List<Quote> Quotes =[select id from quote                          
where Opportunity.id in :OpportunityIds                       
and Status != 'Accepted'];        
delete Quotes;   
}
}


Thank you for your help!

for(Schema.FieldSetMember memberObj : SObjectType.Account.FieldSets.rakch__DemoFieldSet.getFields()){
            qwerty += ','+memberObj.getFieldPath();
        }       

 string id1 = IdList.get(0);
        string id2 = IdList.get(1);

        string query1 = qwerty+' from Account where id=' +id1;
        accList2=Database.query(query1);

Im trying to concate id with query but im getting, can some one let me know where i was going wrong.

ERROR: System.QueryException: unexpected token: w00000LEFtiAAH
Hi awesome coders , I am not able to get what is going wrong. when i execute the below class through Annonymous window, I see no results. : AccGroupByIndustry.getAccountGrByIndMap(); 

public class AccGroupByIndustry {

// Get all Accounts with Industry as Key and List of Accounts as value
    public static Map<String,List<Account>> getAccountGrByIndMap() {
    
    Map<String, List<Account>> accountsGroupedByIndustry = new Map<String, List<Account>>();
    // Fetch all accounts with Industry
    List<Account> accountsWithIndustry = [SELECT Id, Name, Industry From Account Where Industry <> Null];
    
        for (Account acc : accountsWithIndustry) 
        {
            List<Account> accountList;
            // Check if map already contains current Industry as KEY
              If(accountsGroupedByIndustry.containsKey(acc.Industry))
              {
                 // Fetch existing list and put it back to Map
                 accountList = accountsGroupedByIndustry.get(acc.Industry);
                 accountList.add(acc);   
              }
            // If key doesn't exist, add account to new List  
            else
            {
                 // Create new List
                 accountList = new List<Account>();
                accountList.add(acc);
            }
            
            // Finally put this List into Map with Industry as Key
            accountsGroupedByIndustry.put(acc.Industry,accountList);
        }  
           return accountsGroupedByIndustry;
    }   
}
  • October 13, 2020
  • Like
  • 0
Hello - I have a LWC with a RecordEditForm and want to set the value of a custom field to today's date upon submit, but can't get the right formatting in the Javascript submit handler. Everything I've tried gives me an invalid date format error. Can someone clue me in on the right format to use? Thanks!
 
handlesubmit(event){
        event.preventDefault();  
        console.log('handle submit');
        const fields = event.detail.fields;
        fields.Travel_Dates_Sent_to_PS__c = false;
        if (this.updatetype=="cancel"){
            let dt = Date.now();
            fields.Travel_End_Date__c=dt;
        }
        this.template.querySelector('lightning-record-edit-form').submit(fields);
    }

 
Hello, I have a snippet of JSON that looks like this:
"dates": [
{
"name": "Service",
"qualifier": "472",
"date": "2020-09-29"
},
{
"name": "Plan Begin",
"qualifier": "346",
"date": "2020-09-01"
},
{
"name": "Issue",
"qualifier": "102",
"date": "2020-06-01"
}
],

I need to be able to get the values from each "object" individually. 
I am getting the list like this:

Map<String, Object> wholeResponse = (Map<String, Object>) JSON.deserializeUntyped(response2.getBody());
Map<String, Object> result = (Map<String, Object>) wholeResponse.get('result');
List<Object> lstdates = (List<Object>) result.get('dates');

But after that I am getting stuck. How would I be able to get the name, qualifier, and date from each object contained in this list? (This may be a basic question, but I am a newbie to json parsing:))
 
I am parsing JSON that is coming back from  REST callout, and when running, it is throwing this error: attempt to de-reference null object. The issue seems to be with how I am parsing the JSON, but I am not sure where I am going wrong. Can someone help?

Here is the snippet of the JSON I am parsing:
"result": {
"first_name": "JOHN",
"last_name": "SMITH",
"id_type": "MI",
"subscriber_id": "1234567",
"gender": "M",
"birthdate": "19601119",
"address": {
"info": "123 Main St.",
"city": "New York",
"state": "NY",
"zip_code": "100000"
},
"county:": {
"value": "14"
},
"office": {
"value": "H78"
},
"recert_month": {
"value": "12",
"name": "December"
},
"dates": [
{
"name": "Service",
"qualifier": "472",
"date": "2020-09-29"
},
{
"name": "Plan Begin",
"qualifier": "346",
"date": "2020-09-01"
},
{
"name": "Issue",
"qualifier": "102",
"date": "2020-06-01"
}
],


Here is how I am parsing it (bold part is causing error):
  
        Map<String, Object> wholeResponse = (Map<String, Object>) JSON.deserializeUntyped(response2.getBody());
            Map<String, Object> result = (Map<String, Object>) wholeResponse.get('result');
                Map<String, Object> residentAddress = (Map<String, Object>) result.get('address');
                   Map<String, Object> county = (Map<String, Object>) result.get('county');
                  Map<String, Object> office = (Map<String, Object>) result.get('office');
                 Map<String, Object> recert_month = (Map<String, Object>) result.get('recert_month');
        
       Eligibility__c newEligRec = new Eligibility__c(); 
        newEligRec.Referral_Name__c = ref.id;
        newEligRec.First_Name__c = string.valueof(result.get('first_name'));
        newEligRec.Last_Name__c = string.valueof(result.get('last_name'));
        newEligRec.Name_Id_Type__c = string.valueof(result.get('id_type'));
        newEligRec.Client_ID__c = string.valueOf(result.get('subscriber_id'));
        newEligRec.Gender__c = string.valueOf(result.get('gender'));
        string birthdate;
              if (string.valueof(result.get('birthdate')) != null){
                  birthdate = string.valueof(result.get('birthdate')).remove('-');
                  string year = birthdate.substring(0,4);
                  string month = birthdate.substring(4,6);
                  string day = birthdate.substring(6,8);
                 birthdate = month + '/' + day + '/' + year;
                    }
        newEligRec.Date_of_Birth__c = birthdate;
        newEligRec.Address_Number_and_Street__c = string.valueOf(residentAddress.get('info')); 
        newEligRec.City__c =  string.valueOf(residentAddress.get('city'));    
        newEligRec.State__c =  string.valueOf(residentAddress.get('state'));    
        newEligRec.Zip_Code__c = string.valueOf(residentAddress.get('zip_code'));
        newEligRec.County__c = string.valueOf(county.get('value'));
        newEligRec.Office__c = string.valueOf(office.get('value'));
        newEligRec.Recertification_Month_value__c = string.valueOf(recert_month.get('value'));
        newEligRec.Recertification_Month__c = string.valueOf(recert_month.get('name'));
HTML TEMPLATE
<template>
    <lightning-card title="Custom Search Functionality in LWC" icon-name="standard:account">
        <div if:true={errorMsg} style="margin-left: 3%;">
            <p style="color: red;">{errorMsg}</p>
        </div>
        <lightning-layout multiple-rows="true" vertical-align="end">
            <lightning-layout-item size="12" small-device-size="10" medium-device-size="8" large-device-size="6" padding="around-small">
                    <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                    <lightning-input type="text" 
                                                     label="Enter Customer Name" name ="cusName"
                                                     onchange={handleCustomerName} ></lightning-input>
                            </div>
                        </div> 
            </lightning-layout-item>
            <lightning-layout-item size="12" small-device-size="2" medium-device-size="2" large-device-size="2" padding="around-small">
                    <lightning-button label="Search" 
                                      variant="brand" 
                                      onclick={handleSearch}></lightning-button>
                </lightning-layout-item>
            </lightning-layout><br/>
            <template if:true={show}>
                <div class="acc-container">
                    {recordId}
                    <lightning-record-view-form record-id={recordId} object-api-name="Client__c">
                        <div class="slds-grid">
                            <div class="slds-col slds-size_1-of-2">
                                <lightning-output-field field-name="Name"></lightning-output-field>
                                <lightning-output-field field-name="Date_of_Birth__c"></lightning-output-field>
                            </div>
                            <div class="slds-col slds-size_1-of-2">
                                <lightning-output-field field-name="Photo__c"></lightning-output-field>
                                <lightning-output-field field-name="Booking_Date__c"></lightning-output-field>
                            </div>
                        </div>
                    </lightning-record-view-form>
                </div>
            </template>
           
      
    </lightning-card>
</template>

js

import { LightningElement, track } from 'lwc';
import getDetail from '@salesforce/apex/PriceFetch.getDetail';
export default class ClientDefinition extends LightningElement {
    cusName;
    @track show = false;
    @track recordId;
    handleCustomerName(event) {
        this.cusName =  event.target.value;
    }
    handleSearch() {
       /* if(this.cusName.equals('')) {
            this.errorMsg = 'Please enter customer name to search.';
          
            return;
        }*/
        alert(this.cusName);
     
        getDetail({ clientName: this.cusName})
          
        
           .then(result => {
            this.show = true;
            alert(result);
            this.recordId = result;
           })
        
           .catch(error => {
                this.error = error;
                alert("FAILURE" + error);
                 //this.error = error;
           });
            
    }
}

Apex controllr class

public with sharing class PriceFetch {
  
    @AuraEnabled
    public static String getDetail(String clientName) {
       
        String search = '%' + clientName + '%';
       
       List<Client__c> clients = new List<Client__c>();
         clients = [
            SELECT Id, Name, Unit__c, Total_cost__c, Remarks__c, Project__c,Profession__r.Name,Photo__c,PAN__c,Father_Spouse__c,Email_id__c,
            Date_of_Birth__c,Contact_Number__c,Communication_address__c,Booking_Date__c,Booking_Amount__c,Agreement_Date__c,Aadhar_Number__c
            FROM Client__c
            WHERE Name LIKE :search
            LIMIT 1];
            if(clients.size() == 0) {
                 throw new AuraHandledException('exceptionText');
            }
            
           return clients.get(0).Id;
        
    }


 
}

Is there any mistake in my code?
Im not getting the recordId.
Hi Gurus,

Plz help in Writing a Test class for below scheduled apex class Mon Tue wed thu 7am
 
global class CopyERTBatchDaily Implements Schedulable
    {
        global void execute(SchedulableContext sc)
        {
            setERTBatch();
        }

        public void setERTBatch()
        {
            //List<Executive_RT> exeList = new List<Executive_RT>();
            List<Executive_RT> exeList = [select Case__c, Level_1__c, Level_2__c,Level_3__c  FROM Executive_RT];
             // process each batch of records
            List<Case_Type__c> listCTD = new List<Case_Type__c>();
        
        for(Executive_RT exe : exeList)
        {        
           	listCTD.add(new Case_Type__c(Case__c=exe.Case__c,Level_1__c=exe.Level_1__c,Level_2__c=exe.Level_2__c,Level_3__c=exe.Level_3__c));
            //System.debug('ERT Case No is =====>' +Case__c);
        }
        try {
        	
            insert listCTD;
        
        } catch(Exception e) {
            System.debug(e);
        }
            
        }
    }

Regards
Fiona​​​​​​​
Hi,
I am having trouble with my Visualforce page and Apex Class. Everything seems to be fine apart from the error Unknown Property 'NFOSDisplayDivisions2Controller.Division_Space2__c'. I can't seem to figure out what is going on, could someone please help me out. Thank you.

Apex Class:
public with sharing class NFOSDisplayDivisions2Controller {
    
    public List<DivisionWrapper> listDivisionWrapper{get;set;}
    public List<Division_Space2__c> selectedDivisions{get;set;}

    public NFOSDisplayDivisions2Controller ()
    {
            listDivisionWrapper = new List<DivisionWrapper>();
            searchRecord();
    }
    
    public void searchRecord()
    {
        listDivisionWrapper.clear();
            for(Division_Space2__c a: [select Id, Name,Number_of_Competitors__c, Availability__c, RecordTypeID ,Active__c from Division_Space2__c limit 30]) 
            {
                listDivisionWrapper.add(new DivisionWrapper(a));
            }
    }

    public void processSelected() 
    {
        selectedDivisions = new List<Division_Space2__c>();
        selectedDivisions.clear();
        for(DivisionWrapper wrapDivisionObj : listDivisionWrapper) 
        {
            if(wrapDivisionObj.selected == true) 
            {
                selectedDivisions.add(wrapDivisionObj.acc);
                // Here you can add the counter or you check the selectedAccounts.size()
            }
        }
    }

    public void ActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c= true;
        }
        update selectedDivisions ;
        searchRecord();
    }

    public void DeActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c = false;
        }
        update selectedDivisions ;
        searchRecord();
    }
    


    // This is our wrapper/container class. 
    public class DivisionWrapper 
    {
        public Division_Space2__c acc {get;set;}
        public Boolean selected {get;set;}
        public DivisionWrapper(Division_Space2__c a) 
        {
            acc = a;
            selected = false;
        }
    }

}

Visualforce Page:
<apex:page controller= "NFOSDisplayDivisions2Controller">
    
<script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock id="PB1">
            <apex:pageBlockButtons >
                <apex:commandButton value="Add to Grid" action="{!processSelected}" rerender="table2,PB2"/>
            </apex:pageBlockButtons>

            <apex:pageblockSection title="Division Types" collapsible="false" columns="1">
                <apex:pageBlockTable value="{!listDivisionWrapper}" var="accWrap" id="table" title="Division Types">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!Division_Space2__c.acc.Name}" />
                    <apex:column value="{!Division_Space2__c.acc.Number_of_Competitors__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Availability__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Active__c}" />
                </apex:pageBlockTable>


            </apex:pageblockSection>
        </apex:pageBlock>
        
        <apex:pageBlock id="PB2" >
            <apex:pageBlockButtons >
                <apex:commandButton value="Activate" action="{!ActivateData}" rerender="PB1,PB2"/>
                <apex:commandButton value="DeActivate" action="{!DeActivateData}" rerender="PB1,PB2"/>
            </apex:pageBlockButtons>

                <apex:pageBlockTable value="{!selectedDivisions}" var="c" id="table2" title="Selected Divisions">
                    <apex:column value="{!c.Name}" headerValue="Division Type"/>
                    <apex:column value="{!c.Number_of_Competitors__c}" headerValue="Number of Competitors"/>
                    <apex:column value="{!c.Availability}" headerValue="Availability"/>
                    <apex:column value="{!c.Active__c}" headerValue="Active"/>
                </apex:pageBlockTable>
        </apex:pageBlock>

        
    </apex:form>
</apex:page>
Can someone help me with a report formula?  How can I get a net of the PAYMENT - REFUND for each payment type?   



User-added image
I have a custom object which has a list of products, country field and checkbox- inactive.

Use case: 
When I create an opportunity and add OpportunityLineItem, The line item should compare with the products field from the custom object.
Also, the Opportunity should look at Bill to country from the account attached and compare with the country field from the custom object.
And if the record matches and the "Inactive" checkbox from the custom object is true, then it should throw an error and not allow to save the opportunity.

For example,
Custom object:
Product: Pencil
Country: Mexico
Inavtive: True

Opportunity:
OpportunityLineItem: Pencil
Account - Bill to Country: Mexico
ERROR FLAG

Can this be achievable ? If so, can i receive some help on building the trigger ?

Thank you in advance.
Hello! I'm a bit new at writing Apex but I'm attempting to create an invocablemethod batch apex class to rollup multiple currency fields on an "Order Package" object to its parent object of "Order Location". Everything seems to be working as expected but I need to rollup multiple fields and I'm running into issues. Can someone show me how I might be able to include multiple fields in the rollup? I attempted to simply add another field but right now it looks like it's assigning the same amount to both fields I included. This seems to be because I am assigning the same "results" to both fields but I can't figure out how I can assign the aggregate query to multiple fields. Any help is greatly appreciated!
 
global class OrderLocationRollupSummary implements Database.Batchable<sObject>, Schedulable {
    
        //Invocable Method
        @InvocableMethod(label='Rollup All Order Packages to Locations')
        global static void rollupAllorderpackages(List<Order_Location_Package__c> orderpackages) {
            rollupOrderPackages(orderpackages);
        }
    
        //Batchable Methods
        global Database.QueryLocator start(Database.BatchableContext bc) {
            return Database.getQueryLocator([SELECT Id FROM Order_New_Location__c]);
        }
    
        global void execute(Database.BatchableContext context, List<sObject> batch){
            Set<Id> OrderLocationIds = new Set<Id>();
    
            for (sObject ordloc : batch) {
                OrderLocationIds.add(ordloc.Id);
            }
    
            summarizeOrderPackages(OrderLocationIds);
        }
    
        global void finish(Database.BatchableContext context) {}
    
        //Schedulable Methods
        global void execute(SchedulableContext context){
            OrderLocationRollupSummary batchJob = new OrderLocationRollupSummary();
            Database.executeBatch(batchJob);
        }
    
        //Static Methods
        public static void rollupOrderPackages(List<Order_Location_Package__c> orderpackages) {
            Set<Id> OrderLocationIds = new Set<Id>();
    
            //Get Order Location Ids from specified orderpackages
            for (Order_Location_Package__c ordpckg : orderpackages) {
                OrderLocationIds.add(ordpckg.New_Location_Name__c);
            }
    
            if (OrderLocationIds.isEmpty() == false) {
                /*Execute as a future call so that the user doesn't have to wait around for
                the rollup to finish. Unless, already in a future or batch call state then
                just perform the rollup.*/
                if (System.isFuture() == false && System.isBatch() == false) {
                    summarizeOrderPackagesAsync(OrderLocationIds);
                }
                else {
                    new OrderLocationRollupSummary().summarizeOrderPackages(OrderLocationIds);
                }
            }
        }
    
        @future
        public static void summarizeOrderPackagesAsync(Set<Id> OrderLocationIds) {
            new OrderLocationRollupSummary().summarizeOrderPackages(OrderLocationIds);
        }
    
        //Public Methods
        public void summarizeOrderPackages(Set<Id> OrderLocationIds) {
            //Get Order Locations to Update
            List<Order_New_Location__c> orderlocations = queryOrderLocationsById(OrderLocationIds);
    
            Map<Id, double> results = getOrderPackagesAmountsByLocationId(OrderLocationIds);
    
            //Loop Order Locations and set Amounts
            List<Order_New_Location__c> orderlocationsToUpdate = new List<Order_New_Location__c>();
            for (Order_New_Location__c ordloc : orderlocations) {
                double mrf = 0;
                double otf = 0;
    
                if (results.containsKey(ordloc.Id)) {
                    mrf = results.get(ordloc.Id);
                    otf = results.get(ordloc.Id);
                }
    
                //Determine if Amounts have Changed
                if (ordloc.Package_Monthly_Recurring_Fees__c != mrf || 
                    ordloc.Package_One_Time_Fees__c != otf) {
                    
                    ordloc.Package_Monthly_Recurring_Fees__c = mrf;
                    ordloc.Package_One_Time_Fees__c = otf;
                    orderlocationsToUpdate.add(ordloc); //Add location to collection to be updated
                }
            }
    
            if(orderlocationsToUpdate.isEmpty() == false) {
                Database.SaveResult[] saveResults = Database.update(orderlocationsToUpdate, false);
                System.debug(saveResults);
            }
        }
    
        //Private Methods
        public Map<Id, double> getOrderPackagesAmountsByLocationId(Set<Id> OrderLocationIds) {
            Map<Id, double> resultsByOrderLocationId = new Map<Id, double>();
    
            //Summarize Order Package Amounts by Order Location Id
            AggregateResult[] results = aggregateOrderPackageAmounts(OrderLocationIds);
            for (AggregateResult result : results) {
                Id orderlocationId = (Id) result.get('OrderLocation');
                double mrf = (double) result.get('MRFees');
                double otf = (double) result.get('OTFees');
    
                resultsByOrderLocationId.put(orderlocationId, mrf);
                resultsByOrderLocationId.put(orderlocationId, otf);
            }
            return resultsByOrderLocationId;
        }
    
        //Query Methods
        private List<Order_New_Location__c> queryOrderLocationsById(Set<Id> OrderLocationIds) {
            return [SELECT 
                    Id 
                    ,Package_Monthly_Recurring_Fees__c
                    ,Package_One_Time_Fees__c
                FROM 
                    Order_New_Location__c 
                WHERE 
                    Id IN :OrderLocationIds];
        }
    
        private AggregateResult[] aggregateOrderPackageAmounts(Set<Id> OrderLocationIds) {
            return [SELECT 
                     New_Location_Name__c OrderLocation
                    ,SUM(Monthly_Recurring_Fees__c) MRFees
                    ,SUM(One_Time_Fees__c) OTFees
                FROM 
                    Order_Location_Package__c
                WHERE
                    New_Location_Name__c IN :OrderLocationIds
                GROUP BY 
                    New_Location_Name__c];
        }
    
    }

 
Hi, 
I need help with my validation rule.  I need to allow only the 'Intake' profile to edit a record 'status' field when another field 'contact type' = 'Intake' .  So far I have below, but it's not working. 

 
AND
(ISCHANGED(enrtcr__Status__c),
NOT(mntrs_Contact_Type_derived__c = "Intake"),
 $Profile.Name = "Intake")

Hello,

I struggle to cover part of my code.
Could someone help?
Thanks
User-added image
here is my code:

 

trigger AircallTaskTrigger on Task (after insert, after update) {

        List<Case> lstCase = new List<Case>();
     
     	//Get 'Case Concern' RecordType Name
        Id caseConcernRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get(label.Param_Case_Concern).getRecordTypeId();

        Map<Id, Case> caseWithAircallTaskMap = new Map<Id, Case>([SELECT Id, First_Aircall_Logged__c FROM Case WHERE RecordTypeId =:caseConcernRecordTypeId]);                           
        for(Task t : Trigger.New) { 
           
            if(t.whatId != null &&  t.callDisposition!= null && t.callDisposition.containsIgnoreCase('aircall')) {
               System.debug('#### Aircall debug ' + t.whatId != null && t.callDisposition.containsIgnoreCase('aircall'));
                
                Case c = New Case();
                if(caseWithAircallTaskMap != null && caseWithAircallTaskMap.containsKey(t.whatId)){
                
                    c = caseWithAircallTaskMap.get(t.whatId);
                    if(c.first_Aircall_Logged__c == null){
                        c.first_Aircall_Logged__c = t.createdDate;
                        if(t.WhatId == c.Id) {
                            lstCase.add(c); 
                        }              
                    } 
                } 
            }     
        }
     
        if (lstCase.size() > 0) {
        	update lstCase;
     	}  
  }

here is the Test class
 
@isTest
public class AircallTaskTriggerTest {
    @isTest static void testAircallDateUpdate() {
        
        Contact con = new Contact (FirstName = 'First Name',LastName = 'Test');
        insert con;
        
        Case c = new Case(Status = 'New',ContactId = con.Id,Phone_Number__c = '123456789');
        insert c;
               
        Task t = new Task(Subject = 'Test', WhatId = c.Id, CreatedDate = System.today(), callDisposition = 'aircall');
        insert t;
        
        c.Id = t.WhatId;
        c.First_Aircall_Logged__c = null;
        //System.assertEquals(t.CreatedDate,  c.First_Aircall_Logged__c);
        update c;
       
    }
    
}

 
Hello,

I need help please, how do I prevent the case from being created in the first condition?
 
public Case generateLog(AccountHistory event) {

               if(OldValue_c.equals(NewValue_c)){ //Help                      
                    Case log = new Case();                        
        			return log;

    			}else{   
                     Case log = new Case();
                         log.RecordTypeId     = recordTypePrevention;
                         log.AccountId        = event.AccountId;           
                         log.Origin           = 'Phone';           
                     return log;
		}
}

 
Hi Guys,

From last month itself I am not recieving any replies from Salesforce developer forum if i posted answers for someones's questions.

Before a month it's working fine. And also forum page not  loading fully only am able to see 10 - 20 Questions. Number of replies and Solved button also not visible in questions.

Any idea how to solve this...

Thanks,
Maharajan.C
Hi All,

Add/Remove Records using LWC.

If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post. 

Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.

Refer the code in below post...

Like this Post if it's helps to any one !!!

Thanks,
Maharajan.C
We have the managed package which is created by us so we are try to install this package  some other org.

It works fine in all orgs but in one org we have the error message like below:

 (UpdateAcc-2) myrule_1_A1(Action Call) – We can’t find an action with the name and action type that you specified

The UpdateAcc is the Process builder which call the Apex Class.

In the package also we have these components but we got the Error!!!

Any one please help on this!!!

Thanks,
Raj
Hi Experts,

Hope some one wil help me:

Salesforce going to update the certificates. Please refer the below Link.

https://help.salesforce.com/articleView?id=000269027&language=en_US&type=1

So Here i have to do the test compatibility  in my environment for MiddleWare and Integration:

Can any one please let me know how to perform the below steps: 

For Middleware/Integrations
To test the compatibility of an API client that uses SOAP to communicate with Salesforce:
  • Set up an API client in a test environment.
  • In that test environment, change the API client's login endpoint hostname fromlogin.salesforce.com or [MyDomain].my.salesforce.com tohttps://certtest.force.com.
  • As an example, changehttps://login.salesforce.com/services/Soap/u/32.0 to https://certtest.force.com/services/Soap/u/32.0 while leaving the path as-is.
  • Log in with that API client.
  • If you see an error message that resembles the following: "INVALID_LOGIN: Invalid username, password, security token; or user locked out." or “Content is not allowed in prolog.”, then this test passed and your integration trusts DigiCert-signed certificates.
    • The presence of this response means that the underlying TLS connection was successful, despite the higher-level error. The TLS connection is the focus of this test.
  • If you instead see an error message that involves TLS or HTTPS, then the test has failed. Your API client will require adjustments to its list of trusted certificate authority certificates to trust DigiCert-signed certificates.
 
To test the compatibility of an API client that uses REST to communicate with Salesforce: Thanks,
Raj

 
We are using the chatter answers in community which is going to retire after Winter 18 release. Wanted some suggestions to perform the migration...below are the research...
Investigated on Q&A Migration App but wanted to know if someone has used this and its outcome. Was there any data impact? If yes, then how can we overcome that?.
What is the alternative? Is data loader an option?
Hi All,

Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.

Am ready to join immedialy to any where(Job Location : Any where).

Please some one can help me!!!

i got 50+ best answers in this forum and member from 2015.

Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
Hi All,

Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.

Am ready to join immedialy to any where(India or Any Country).

Please some one can help me!!!

i got 50+ best answers in this forum and member from 2015.

Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
 
Hi All,

Can you please help me to find unused apps in my salesforce instance to Metadata Cleanup

Thanks,
Raj
Hi All,

Can anyone please give a example third party app name to calculate the Opportunity Stage Duration (inbetween stages also).
Example : Proposal,Qualified,Ready Invoice,Negoatiation,Closed won.
In there i want to calculate the stage duration from Qualified to Closed won.Starting stage must be Qualified End stage Closed won
Qualified to Ready Invoice =?
Ready Invoice to Negoatiation =?
Negoatiation to Closed won =?

And also for Sales vs Quota report third party App.

Thanks,
Raj
Hi All,

Can you please anyone give a test class for me to the below Apex Class.

Public class AccountDisplatRecClsExtn{
Public id Current_Acc_Id;
    public AccountDisplatRecClsExtn(ApexPages.StandardController controller) {
Current_Acc_Id = controller.getRecord().id;
    }
     

  public List<Question__c> getcontList(){
   List<Question__c> accList = [select id,Name,AssessmentId__c,AssessmentId__r.Name,External_ID__c,Friendly_Name__c,Question_Plain__c,Question_Style__c,Sort_Order__c,(Select Id,Name,Red_Flag__c,Scoring__c from answers__r) from Question__c where AssessmentId__c=:Current_Acc_Id ORDER by Sort_Order__c ASC];
   return accList;
  
  }
    }

Thanks,
Raj
 
Hi,

In my salesforce org when i convert a lead it creates multiple account,contacts and opportunities at the same time and when i see the created by timings and created by user both are same.

http://docs.releasenotes.salesforce.com/en-us/spring16/release-notes/rn_sales_leads_edit_converted_leads.htm

In above link there is an article i studied about permission set which will enalble us to create multiple account,contacts and opportunities and we can able to view lead again in salesforce detail page but i disabled this options.

Even though i disabled this option i have duplicates created in my salesforce org and i have lead which i can edit on detail page after it converted...I didn't have any trigger.

Please help !!!!!!!!

Thanks,
Raj
Hi Friends,

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

Thanks,
Raj.
Hi All,

Please Help!!!
Evaluation Criteria : Evaluate the rule when a record is created, and any time it's edited to subsequently meet criteria
Rule Criteria Opportunity :  StageEQUALSClosed Won
Workflow Action : Email Alert

>Here First my record meet the above rule criteria based on the evaluation criteria it sends an an Email i.e Opportunity stage equals Closed   Won
>After that in that same record i change the Opportunity stage to Need Analysis so now the record dont met the criteria so there is a no        Email
>Then i changed that Opportunity record stage to Closed Won now the record meet the criteria so its send an email again but i want to stop    the Sending an Email Now.


Thanks in Advance!!!
Raj.
Hi All,

Any One  please help me to code coverge because i got only 43% coverage

ApexTrigger :-
trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Lead_Campaign__c tm;//Assinging Custom setting To the variable tm
    tm=Lead_Campaign__c.getorgdefaults();
    String Template=tm.Email_Template_ID__c;
    Decimal Days=tm.Threshold_Days__c;
     
    list <CampaignMember> theCampaignMembers = new list<CampaignMember>();
    for(CampaignMember campMem : Trigger.new){//
    if(test.isRunningTest()){
        
        Days = 0;
    }
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
            theCampaignMembers.add(campMem);
         
            }
    // List containing Campaign Member records to be inserted  
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Status,Lead_age__c, owner.email from Lead where id IN : LeadIds])
    try
    {

    if(ld.Status!='Qualified'&&ld.Lead_age__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
 
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
      mail.setTargetObjectId(ld.OwnerId);    
      mail.setWhatId(ld.id);
      mails.add(mail);
      Messaging.sendEmail(mails);
  
}
}
 catch (Exception e)
{

  ApexPages.addMessages(e);
  Profile adminProfile = [Select id From Profile Where Name='System Administrator' Limit 1];

     Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
     List<String> toAddresses = new List<String>();
     toAddresses.add(adminProfile.id);
     mail.setToAddresses(toAddresses);
     mail.setSenderDisplayName('Apex error message');
     mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
     mail.setPlainTextBody(e.getMessage());
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
  
}
}


Test Class -:

@isTest(SeeAllData = true)
public class sendNotificationTrigger
{
static testMethod void sendNotificationTrigger ()
{
     Test.startTest();      //Creates Contact to be linked to Campaign Member
Campaign cp =  [SELECT Id FROM Campaign LIMIT 1];
       //Creates a new campaign memeber, associaites it with 1 campaign
 Lead t1 = new Lead(Company= 'TestLead', LastName= 'TestL', Email = 'none@test.com',Status = 'Open' );
 insert t1;
 CampaignMember newMember = new CampaignMember (LeadId = t1.id, status='Sent', campaignid = cp.id);
 insert newMember;
 system.assertequals(t1.status,'Open')  ;

  
 
   
 Test.stopTest();
 }


Thanks,
Raj.
Hi All,

Can any one Please help to write a test class to my Trigger


trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Test_Setting__c tm;//Assinging Custom setting To the variable tm
    tm=Test_Setting__c.getorgdefaults();
    String Template=tm.Template__c;
    Decimal Days=tm.Threshold_Days__c;
     
    
    for(CampaignMember campMem : Trigger.new){//
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
         
            }
            
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Lead_age__c, Status, owner.email from Lead where id IN : LeadIds])
    if(ld.Status!='Qualified'&&ld.Lead_Age_In_days__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
       mail.setTargetObjectId(ld.Ownerid);                           
      mails.add(mail);
  Messaging.sendEmail(mails);
}
}
}

Thanks
​Raj.
Hi All,

Add/Remove Records using LWC.

If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post. 

Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.

Refer the code in below post...

Like this Post if it's helps to any one !!!

Thanks,
Maharajan.C
Hi Friends,

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

Thanks,
Raj.
User cannot change record owner If user is not System Admin, Industry is null and Account created after 1/1/2017
I tried this formula where the Profile Id is for System Administrator  but it fires even if the System Admin is editing the record.
$User.ProfileId  <> "0ei0000001DLN6"&&
 ISCHANGED( OwnerId )&&
 ISBLANK(TEXT(Industry ))&&
  DATEVALUE(CreatedDate) > DATE(2017,01,01)
 
Hi, i have written trigger on opportunity while inset or update. this logic compare opp with already existed prodcuts on org. if it maches we are throughing an error message on opp record. but i am getting null pointer excpetion. please any help

trigger helloOppTrg on Opportunity (after insert,after update) {
    
    list<Id>accIdlst          = new list<Id>();
    list<string>oppOrdernolst = new list<string>();
    for (Opportunity objOpp : Trigger.new) {
        oppOrdernolst.add(objOpp.OrderNumber__c);
        accIdlst.add(objOpp.AccountId);
    }
    system.debug('opp order no entering'+oppOrdernolst);
    system.debug('account id entering'+accIdlst);
    list<Opportunity> oppwithaccount = new list<Opportunity>();
    oppwithaccount = [SELECT Id,AccountId,OrderNumber__c,Account.Name FROM Opportunity WHERE AccountId=:accIdlst];
    list<string>accname= new list<string>();
    for(Opportunity acc:oppwithaccount){
        accname.add(acc.Account.Name);
    }
    system.debug('account name'+accname);
    list<Product2> matchProduct = new list<Product2>();
    matchProduct = [SELECT Id, IsActive, ProductCode, Name FROM Product2
                    WHERE ProductCode =:oppOrdernolst AND Name =:accname];
    system.debug('product records'+matchProduct);
    
    for(Opportunity objOpp:oppwithaccount) {
        system.debug('opp id top'+objOpp.id);
     
        for(Product2 proloop : matchProduct) {
            system.debug('inside second loop');
            if(proloop.IsActive==false && proloop.ProductCode==objOpp.OrderNumber__c
               && proloop.Name==objOpp.Account.Name){
                   system.debug('inside third loop');
                   system.debug('opp id'+objOpp.id); // Id value is showing properly
                    Opportunity oppfromtriggernewmap = Trigger.newMap.get(objOpp.id); // but here it reurns null value
                    system.debug('just opp before error msg'+oppfromtriggernewmap); // Null
                   oppfromtriggernewmap.OrderNumber__c.addError('check is false so can not update/insert record MACHED');// Null pointer exception 
               }
        }
    }
    
}
My test case for a before insert/update trigger on Contact should be very simple, which means I am missing something obvious...the trigger itself takes the City, State Code, and Zip and pulls the county name from a custom county object.  This trigger is working as intended and populates the county name with no issue.  

What I can't figure out is why my test class does not return a value for the county after the insert.  (The insert code and requery works perfectly when running in an Execute Anonymous window). 

Below is the code for the insert test.  After inserting a new contact, when I try to requery for the new hed__Mailing_County__c value, the value is null, but it does pull the new contact id.  Any help is much appreciated!  :-)
 
@isTest
private class Contact_County_Test {
    static testMethod void TestInsertContact() {
        // Create contact with city, state, zip populated
        Contact con = new Contact(FirstName = 'TestInsert', 
                                  LastName = 'TestContact', 
                                  MailingCity = 'My City', 
                                  MailingStateCode = 'WI', 
                                  MailingPostalCode = '12345',
                                  MailingCountryCode = 'US',
                                  hed__Mailing_County__c = '');
        Insert con;

        //Requery to pull in new county name
        con = [SELECT hed__Mailing_County__c FROM Contact WHERE Id = :con.Id LIMIT 1];

         //Verify County Name is populated correctly
         System.assertEquals('County Name', con.hed__Mailing_County__c);
    }
}

 
I've successfully plotted the accounts on Google Map with Lightning Component and it works in Sandbox...but don't know how to write a test code for the ApexClass.

I describe the codes below and hope anyone can help with the test code part. Thank you!

Component (MapNearbyAccount.cmp)
<aura:component controller="MapNearbyAccountController" implements="flexipage:availableForAllPageTypes,force:hasRecordId">
    <aura:attribute name="mapMarkers" type="Object"/>
    <aura:attribute name="selectedMarkerValue" type="String" />
    
    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
    
    <div class="slds-box slds-theme--default">
        <lightning:map 
                       mapMarkers="{! v.mapMarkers }"
                       selectedMarkerValue="{!v.selectedMarkerValue}"
                       markersTitle="accounts nearby"
                       listView="auto"
                       showFooter="false"
                       onmarkerselect="{!c.handlerMarkerSelect}" />
    </div>
</aura:component>
Controller (MapNearbyAccount.js)
({
    init: function (cmp, event, helper) {
        var recordId = cmp.get("v.recordId");     
        var action = cmp.get("c.getAccounts");
        action.setParams({recordId :recordId});
        cmp.set('v.mapMarkers', [{location: {}}]);

        action.setCallback(this, function(response){
            
            var accounts = response.getReturnValue();
            var markers = [];
            for(var i = 0; i < accounts.length; i++){
                var acc = accounts[i];
                markers.push({
                    location: {
                        Country : acc.BillingCountry,
                        State : acc.BillingState,
                        City: acc.BillingCity,
                        Street: acc.BillingStreet
                    },
    
                    icon : "standard:account",
                    value: acc.Id,
                    title: acc.Name,
                    description:acc.Description
                });
            }
            
            if(markers.length != 0){
                cmp.set('v.mapMarkers', markers);
            }
        });

        $A.enqueueAction(action);
    },

    handlerMarkerSelect: function (cmp, event, helper) {
        console.log(event.getParam("selectedMarkerValue"));
    }
});
ApexClass (MapNearbyAccountController)
public class MapNearbyAccountController {
    @AuraEnabled
    public static List<Account> getAccounts(String BillingCity, String BillingState, String recordId){
        Account acct = [SELECT Id, Name, BillingCountry, BillingState, BillingCity, BillingStreet, Industry FROM Account WHERE Id =:recordId];
        
        return [SELECT Id, Name, BillingCountry, BillingState, BillingCity, BillingStreet,Description
                FROM Account 
                WHERE BillingState = :acct.BillingState AND BillingCity LIKE :('%' + acct.BillingCity + '%') AND Industry = :acct.Industry LIMIT 10];
    }
}
TestClass
@isTest
public class MapNearbyAccountControllerTest {
@isTest
    static void testMapNearbyAccountController() {
        Account acc1 = new Account();
        acc1.Name='acc1';
        acc1.BillingCity='Shibuya';
        acc1.BillingState='Tokyo';
        insert acc1;
        
        MapNearbyAccountController ctrl = new MapNearbyAccountController();
        
        Test.startTest();
            List<Account> getAccounts = ctrl.getAccounts();
            System.assertEquals(false,getAccounts.isEmpty());
        Test.stopTest();
    }
    
}
I have a trigger that works, but I want to add criteria.
If the Sales Engineering Request “Status” does not equal “Approved” or “Unable to Meet Request”, then trigger this.
How do I modify this? Thank you for your help.

My Trigger:
trigger FeedCommentTest on FeedComment (after insert) 
{
    for(FeedComment f : Trigger.New)
    {
        if(UserInfo.getProfileId()  == '00e6w000000FjiUAAS')
        {
            Sales_Engineering_Request__c SalesEngineeringRequestToUpdate = [SELECT ID FROM SALES_ENGINEERING_REQUEST__c WHERE ID =: f.ParentId];
            SalesEngineeringRequestToUpdate.Status__c = 'Approved';
            Update SalesEngineeringRequestToUpdate;
        }          
    }
}
I am new to Salesforce and I am struggling to write a simple test class. I haven't written one before though I have been doing a lot of trailhead on it but can't seem to wrap my head around this test class for a trigger.

I have this trigger that Autofills a lookup field called Staff whenever a value is selected from the Appointment_with__c picklist field. It only auto-fills whenever the event is saved:

trigger Autofill on Event (before insert, before update) {
    { 
        for (Event e : Trigger.new) 
        {
            
            String [] str = e.Appointment_with__c.split(' ');
            
            
            List<Contact> cont = [SELECT Id FROM Contact WHERE FirstName =:str[0] AND LastName =:str[1]];               
            
            
            e.Staff__c = cont[0].Id;
        }
    }
}

Any ideas on how to create a test class for this? 

Thank you in advance for your help
 
Hello,

I have a trigger that is failing on integration from our database because of an older CRM Id. The field was re-purposed for SFDC uses but still contains the old CRM data. When an older record with one of these Id's is integrated over, it cannot match the Id to a valid record. The older Id's start with "AUBA-" so I attempted to say only records starting with '500'. However it's still erroring on the old Id number.

Here is the full error: "CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:OrderTrigger: execution of BeforeInsertcaused by: System.StringException: Invalid id: AUBA-51M7HJExternal entry pointTrigger.OrderTrigger: line 12, column 1:--"

Can someone help me find where I'm going wrong here, and how I can allow the old Id to be passed through without firing off the Trigger?

Trigger:
trigger OrderTrigger on Order (before insert) {
    List<String> orderRequestIds = new List<String>();
    for (Order o : Trigger.new) {
        if (o.CRM_Sales_Order_Number__c != null && !o.CRM_Sales_Order_Number__c.startsWith('500')){
            orderRequestIds.add(o.CRM_Sales_Order_Number__c);
        }
    }
    if (Trigger.isBefore) {
        if (Trigger.isInsert) {
            OrderTriggerHandler.orderInsertHandling(Trigger.new, orderRequestIds);
        }
    }
}
Class:
public with sharing class OrderTriggerHandler {
    public static void orderInsertHandling(List<Order> scope, List<String> orderRequestIds) {
        List<Quota__c> rbmQuotas = [SELECT Id, Sales_Office__c, Quota_Date__c FROM Quota__c WHERE Active__c = true AND RecordType.DeveloperName = 'RBM_Quota'];
        List<Quota__c> salesGroupQuotas = [SELECT Id, Sgrp__c, Quota_Date__c FROM Quota__c WHERE Active__c = true AND RecordType.DeveloperName = 'ISC_Direct_Quota'];
        Map<Id,Case> orderRequests = new Map<Id, Case>([SELECT Id, CreatedById, CreatedBy.Region__c FROM Case WHERE Id IN :orderRequestIds]);


        for (Order o : scope) {
            Case relatedOrderRequest = orderRequests.get(o.CRM_Sales_Order_Number__c);
            if(relatedOrderRequest != null) {
                o.Related_Inquiry__c = relatedOrderRequest.Id;
                o.OwnerId = relatedOrderRequest.CreatedById;
            }

            for (Quota__c q : salesGroupQuotas) {
                if (q.Sgrp__c == o.Sales_Group__c && q.Quota_Date__c.month() == o.EffectiveDate.month() && q.Quota_Date__c.year() == o.EffectiveDate.year()) {
                    o.Sales_Group_Quota__c = q.Id;  
                }
            }

            /* for (Quota__c q : rbmQuotas) {
                if(relatedOrderRequest != null) {
                    if (q.Region__c == relatedOrderRequest.CreatedBy.Region__c && q.Quota_Date__c.month() == o.EffectiveDate.month() && q.Quota_Date__c.year() == o.EffectiveDate.year()) {
                        o.Quota__c = q.Id;
                    }
                }
            } */
            for (Quota__c q : rbmQuotas) {
                if (q.Sales_Office__c == o.Sales_Office__c && q.Quota_Date__c.month() == o.EffectiveDate.month() && q.Quota_Date__c.year() == o.EffectiveDate.year()) {
                    o.Quota__c = q.Id;
                }
            }
        }
    }
}

Thank you.
 
I am trying to create a Flow that adds a Note entry to an activity of a certain record type.  I thought I had this pointed to the right parent ID, but even though I see what I expect in the error, it will not save.

We can't save this record because the “Dev Notes” process failed. Give your Salesforce admin these details. This error occurred when the flow tried to create records: FIELD_INTEGRITY_EXCEPTION: Parent ID: id value of incorrect type: 00T1J00004CQhV5UAL. You can look up ExceptionCode values in the SOAP API Developer Guide. Error ID: 972685901-36874 (-1691690686)

User-added image

Can we not append a Note to a Task using flow?
I am trying to get code coverage for the class below:
public class redirectToWebinarPageController{
    public pageReference redirectURL(){
        
        //get the external id from the URL
        String externalId = ApexPages.currentPage().getParameters().get('externalId');
        
        //query the record.
        Webinar__c webinarRecord = [select id from Webinar__c where Webinar_Count__c =: externalId];
        
        //redirect to detail page of the above record.
        return new pageReference('/'+webinarRecord.id);
       
    }
}
Here is the test I have and am getting 75% coverage but I would prefer to know how to get 100%
@isTest 
public class redirectToWebinarPageControllerTest {
    public static testMethod void testredirectURL() {
        test.startTest();
        PageReference pageRef = Page.redirectToWebinarDetailPage;
        
        //Your test data logics
        Account testAccount = new Account();
        testAccount.Name = 'Account Name';
        insert testAccount;
        
        Contact testContact = new Contact();
        testContact.LastName = 'Contact';
        testContact.FirstName = 'Test';
        testContact.Email = 'testContact@testing.com';
        insert testContact;
        
        Webinar__c w = new Webinar__c();
        w.Name = 'Test Webinar';
        w.Account__c = testAccount.id;
        w.Communication_Type__c = 'Client 4';
        w.Delivery_Method__c = 'Self Study';
        w.Contact__c = testContact.id;
        insert w;
        
        String testExternalId = w.Webinar_Count__c;

        Test.setCurrentPage(pageRef);
			
			pageRef.getParameters().put('externalId',testExternalId);
			
			redirectToWebinarPageController controller = new redirectToWebinarPageController();
			controller.redirectURL();
        
   		test.stopTest();
     }
}
Thank you in advance, I am really new to writing test classes and would love to know what I am missing here.
The current code coverage is 25% 

BATCH CLASS

global class SendMembershipRenewalEmail30Days implements Database.Batchable<SObject>, schedulable {
    
    public Database.QueryLocator start(Database.BatchableContext bc){
        
        Date oneMonthFromToday  = Date.today().addDays(30); // Date 30 days from today
        return Database.getQueryLocator([select id, name, Organisation__r.npe01__one2onecontact__r.Email,regular_payment__c  FROM Membership__c WHERE Expiry_Date__c =: oneMonthFromToday and (regular_payment__r.npsp4hub__Payment_Method__c = 'cash' or regular_payment__r.npsp4hub__Payment_Method__c = 'Direct Debit' )]);
    }
    
    public void execute(Database.BatchableContext bc, list<Membership__c> scope){
        
        list <EmailTemplate> templateIds = new list <EmailTemplate> ([Select id from EmailTemplate where (name = 'Organisation Membership Renewals Direct Debit' OR name = 'Organisation Membership Renewals Not Direct Debit') ORDER BY name asc]);
        for(membership__c ta : (List<membership__c>)scope) {
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(new String[] {ta.Organisation__r.npe01__one2onecontact__r.Email});
            email.setSaveAsActivity(false);
            email.setTargetObjectId(ta.OwnerId);
            email.setTemplateId(ta.regular_payment__c == null ? templateIds[1].id : templateIds[0].id);
            email.setWhatId(ta.Id);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        }
    }
    
    public void finish(Database.BatchableContext bc){
        
        
    }
    
    global void execute(SchedulableContext SC) {
        database.executebatch(new SendMembershipRenewalEmail30Days());
    }
}


TEST CLASS 

@isTest(seeAllData = false)
private class Test_SendMembershipRenewalEmail30Days {
    
    static testMethod void unitTest_SendMembershipRenewalEmail30Days()
    {
        Test.startTest();
        Account acc = new Account(name ='test name');
        insert acc;
        
        Contact cont = new Contact();
        cont.FirstName ='Test';
        cont.LastName ='Test';
        cont.email ='Test@Test.com';
        cont.accountid = acc.id;
        insert cont;
        
        Id oppRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Membership').getRecordTypeId();
        Opportunity opp = new Opportunity();
        opp.amount = 10.00;
        opp.Name = 'test name';
        opp.StageName = 'Closed Won';
        opp.RecordTypeId = oppRecordTypeId;
        opp.CloseDate = date.today();
        insert opp;
        
        
        
        
        
        SendMembershipRenewalEmail30Days obj = new SendMembershipRenewalEmail30Days();
        Database.executeBatch(obj);
        Test.stopTest();
        
    }
    
    
    
}
Lightning Data Table issue :

i have a LWC component on Inquiry Obj (Parent) which is having look up relation with the child (Relavent Proprties).
My component will display all the child records of the parent obj with inline edit functionality.
Also i have "create relavent Proprty" standerd quick action button that craetes a New relevent Prop record.

Problem is that , when a new record is created from quick action button . my data table is not getting refreshed. data table shuld show all the values in the Db. why so 

Please help 

JavaScript : 
import { LightningElement, wire, api,track  } from 'lwc';
import getRelProp from '@salesforce/apex/selectRelPropController.getRelProp';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import updateRelProp from '@salesforce/apex/selectRelPropController.updateRelProp';
import { getRecordNotifyChange } from 'lightning/uiRecordApi';
const COLS = [
    { label: 'SL.No', 
    fieldName: "recordLink", 
    type: 'url',
    typeAttributes: { label: { fieldName: "Name" }, tooltip:"Relavent Property", target: "_blank" }
    
    },
    { label: 'Property Name',
     fieldName: 'recordLinkProp',
     type: 'url',
     typeAttributes: { label: { fieldName: "PropertyRel" }, tooltip:"Property", target: "_blank" }
    
    },
    { label: 'Price', fieldName: 'Price__c' ,  type: 'currency' },
    { label: 'Created Date', fieldName: 'CreatedDate' , type: 'date' },
    { label: 'Include this in PDF', fieldName: 'Include_This_in_PDF__c' , editable: true, type: 'boolean' }
    
    
];


export default class DatatableUpdate extends LightningElement {
    @api recordId;
    columns = COLS;
    draftValues = [];
    @track wiredPropList = [];
    error;  
    @track relList = [];
    
      @wire(getRelProp, { accId: '$recordId' })
    getRelPropList(result) { 
        this.wiredPropList = result;
     if (result.data) { 
         
        console.log(result.data.length);
      var temprelList = [];  
      for (var i = 0; i < result.data.length; i++) {  
       let tempRecord = Object.assign({}, result.data[i]); //cloning object  
       tempRecord.recordLink = "/" + tempRecord.Id;       
       tempRecord.PropertyRel =  tempRecord.Property__r.Name;
       tempRecord.recordLinkProp = "/" + tempRecord.Id;       
       temprelList.push(tempRecord); 
       console.log(temprelList) ;
      }  
      this.relList = temprelList;  
      this.error = undefined;  
     } else if (result.error) {  
      this.error = error;  
      this.relList = undefined;  
     }  
    }
     
    async handleSave(event) {
        const updatedFields = event.detail.draftValues;
        console.log("chk1" +JSON.stringify(updatedFields));
        // Prepare the record IDs for getRecordNotifyChange()
        const notifyChangeIds = updatedFields.map(row => { return { "recordId": row.Id } });
        console.log("chk2" +JSON.stringify(notifyChangeIds));
    
       // Pass edited fields to the updateContacts Apex controller
        await updateRelProp({data: updatedFields})
        .then(result => {
            console.log(JSON.stringify("Apex update result: "+ result));
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Included for PDF Generation',
                    variant: 'success'
                })
            );
    
        // Refresh LDS cache and wires
        getRecordNotifyChange(notifyChangeIds);
    
        // Display fresh data in the datatable
        refreshApex(this.wiredPropList).then(() => {
            // Clear all draft values in the datatable
            console.log();
            this.draftValues = [];
          });
    
        
       })
        .catch(error => {
         this.dispatchEvent(
              new ShowToastEvent({
                  title: 'Error updating or refreshing records',
                  message: error.body.message,
                  variant: 'error'
              })
          );
      });
       
    }
}

Component : 

<template>
    <lightning-card title="Relevant Properties" icon-name="custom:custom63">
    
       
     <div > 
        <template if:true={relList}>
            <lightning-datatable
                key-field="Id"
                data={relList}
                columns={columns}
                onsave={handleSave}
                show-row-number-column
                draft-values={draftValues}>
            </lightning-datatable>  
        </template>
        
        <template if:true={relList.error}>
            <!-- handle Apex error -->
        </template>
    </div>
        
    </lightning-card>
    </template>

User-added image

apex controller : 

public with sharing class selectRelPropController {
    
    @AuraEnabled(cacheable=true)
    public static List<Relevant_Property__c> getRelProp(String accId) {
        
        return [
            SELECT Id, Name, Property__r.Name , Property__c, Price__c , Include_This_in_PDF__c ,CreatedDate 
            FROM Relevant_Property__c
            WHERE Inquiry__c  = :accId
            WITH SECURITY_ENFORCED
        ];
    }
    
    @AuraEnabled
    public static string updateRelProp(Object data) {
        List<Relevant_Property__c> relPropRecForUpdate = (List<Relevant_Property__c>) JSON.deserialize(
            JSON.serialize(data),
            List<Relevant_Property__c>.class
        );
        try {
            system.debug('Records' +relPropRecForUpdate);
            update relPropRecForUpdate;
            return 'Success: pls click on Generate PDF Button to generate the Document';
        }
        catch (Exception e) {
            return 'The following exception has occurred: ' + e.getMessage();
        }}
}

pls helpppppppppp
Hi I have written below apex method for LWC but i am getting "missing return statement required return type" error when trying to deploy to org.
please help me where i am doing wrong here.

public with sharing class bikeSearchResultController {
@AuraEnabled(cacheable=true)
public static list<Car__c> cardetailsapexmethod(string cartypeid){
    try {
        if(String.isEmpty(cartypeid)){
           return [SELECT Id,Available_For_Rent__c,Build_Year__c,Car_Type__c,Name,Picture__c
                   FROM Car__c];
        }else 
        if(!String.isEmpty(cartypeid)){
            return [SELECT Id,Available_For_Rent__c,Build_Year__c,Car_Type__c,Name,Picture__c
                    FROM Car__c
                    WHERE Car_Type__c=:cartypeid];
        }
    } catch (Exception e) {
        throw new AuraHandledException(e.getMessage());
    }
    
}
}

 

Hi. I found this apex class online (it's super simple). It triggered successfully in my sandbox. When deploying to my production org, I tried validating and received an error: 

Code Coverage Failure: Your code coverage is 0%. 

This is the Apex Class:
public class DeleteUnacceptedQuotes 
{
@InvocableMethod    
public static void QuoteDelete(List<Id> OpportunityIds)    
{        
List<Quote> Quotes =[select id from quote                          
where Opportunity.id in :OpportunityIds                       
and Status != 'Accepted'];        
delete Quotes;   
}
}


Thank you for your help!

for(Schema.FieldSetMember memberObj : SObjectType.Account.FieldSets.rakch__DemoFieldSet.getFields()){
            qwerty += ','+memberObj.getFieldPath();
        }       

 string id1 = IdList.get(0);
        string id2 = IdList.get(1);

        string query1 = qwerty+' from Account where id=' +id1;
        accList2=Database.query(query1);

Im trying to concate id with query but im getting, can some one let me know where i was going wrong.

ERROR: System.QueryException: unexpected token: w00000LEFtiAAH
Hi awesome coders , I am not able to get what is going wrong. when i execute the below class through Annonymous window, I see no results. : AccGroupByIndustry.getAccountGrByIndMap(); 

public class AccGroupByIndustry {

// Get all Accounts with Industry as Key and List of Accounts as value
    public static Map<String,List<Account>> getAccountGrByIndMap() {
    
    Map<String, List<Account>> accountsGroupedByIndustry = new Map<String, List<Account>>();
    // Fetch all accounts with Industry
    List<Account> accountsWithIndustry = [SELECT Id, Name, Industry From Account Where Industry <> Null];
    
        for (Account acc : accountsWithIndustry) 
        {
            List<Account> accountList;
            // Check if map already contains current Industry as KEY
              If(accountsGroupedByIndustry.containsKey(acc.Industry))
              {
                 // Fetch existing list and put it back to Map
                 accountList = accountsGroupedByIndustry.get(acc.Industry);
                 accountList.add(acc);   
              }
            // If key doesn't exist, add account to new List  
            else
            {
                 // Create new List
                 accountList = new List<Account>();
                accountList.add(acc);
            }
            
            // Finally put this List into Map with Industry as Key
            accountsGroupedByIndustry.put(acc.Industry,accountList);
        }  
           return accountsGroupedByIndustry;
    }   
}
  • October 13, 2020
  • Like
  • 0
hello All, 

I have created a custom user history object to store the old and new value for the updates or changes made in the user object.
my code is working for first and last name fields but not for all other fields and getting this error "

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger UserTrigger caused an unexpected exception, contact your administrator: UserTrigger: execution of AfterUpdate caused by: System.DmlException: In
apex code - 



public class UserTriggerHandler {
    public static void onAfterUpdate (List<User> userList, Map<Id, User> oldUserMap){
        CreateUserHistoryRecords(userList,oldUserMap);
    }
    
    public static void CreateUserHistoryRecords(List<User> userList, Map<Id, User> oldUserMap){
       List<string> fieldList = new List<String> ();
        List<Schema.FieldSetMember> fieldSetMemberList =  readFieldSet('User_History_Fields','User');
        for(Schema.FieldSetMember fieldSetMemberObj : fieldSetMemberList)
        {
            fieldList.add(fieldSetMemberObj.getFieldPath());
            
        } 
    List<User_History__c> userHistoryRecords = new List<User_History__c>();
        for(User newrec : userList){
            User oldrec = oldUserMap.get(newrec.Id);
            for(String FieldName : fieldList){
                if(oldrec.get(FieldName)!=newrec.get(FieldName)){
                  
                    User_History__c uhrec = new User_History__c();
                    uhrec.Field__c = FieldName;
                    uhrec.NewValue__c =(String)newrec.get(FieldName);
                    uhrec.OldValue__c = (String)oldrec.get(FieldName);
                    uhrec.User_ID__c = newrec.Id;
                    userHistoryRecords.add(uhrec);            
                }
            }
        }
        if(!userHistoryRecords.isEmpty())
        {
            insert userHistoryRecords;
    }
    }
    
     public static List<Schema.FieldSetMember> readFieldSet(String fieldSetName, String ObjectName)
    {
        System.debug(fieldSetName);
        System.debug(ObjectName);
        Map<String, Schema.SObjectType> GlobalDescribeMap = Schema.getGlobalDescribe(); 
        Schema.SObjectType SObjectTypeObj = GlobalDescribeMap.get(ObjectName);
        Schema.DescribeSObjectResult DescribeSObjectResultObj = SObjectTypeObj.getDescribe();
        
        system.debug('====>' + DescribeSObjectResultObj.FieldSets.getMap());
        
        Schema.FieldSet fieldSetObj = DescribeSObjectResultObj.FieldSets.getMap().get(fieldSetName);
        
        //List<Schema.FieldSetMember> fieldSetMemberList =  fieldSetObj.getFields();
        //system.debug('fieldSetMemberList ====>' + fieldSetMemberList);  
        if(fieldSetObj!=null){
            return fieldSetObj.getFields(); 
        }
        else{
            return null;
        }
    }  
    
}






Trigger - 

1
2
3
4
5
6
7
8
9
trigger UserTrigger on User (after update) {
    
    if ( trigger.isAfter ) {
        if ( trigger.isUpdate ) {
            UserTriggerHandler.onAfterUpdate(trigger.new, trigger.oldMap);
        }
    }
    
}

sert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): User_History__c, original object: User: []: Class.UserTriggerHandler.CreateUserHistoryRecords: line 31, column 1
can anyone please check and let me know where to change 
Trying to find out if i can rotate an image once the visualforce page is rendered as a PDF, when it is rendered as HTML the image shows correctly the way you take the image also the css below works with it on HTML but not PDF which is strange because the other style is working for the page when it is in PDF. 
<style type="text/css" media="print">
			@page {
				size: landscape
			}
.imageClass {
				-webkit-transform: rotate(90deg);
				-moz-transform: rotate(90deg);
				-o-transform: rotate(90deg);
				-ms-transform: rotate(90deg);
				transform: rotate(90deg);
				height: 200px;
				width: 200px;
			}

<img src="{!'/sfc/servlet.shepherd/version/download/' + Document_Id__c}" alt="before photo" class="imageClass"


-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
Hi! I am working on a lightning component action to update a checkbox if the opportunity is won. The button is working fine, but there is an extra blank pop up with the alert message. I need to show just the alert message, not the blank screen. Can anyone help. Thank you!

({
 doInit : function(component,event,helper){
        $A.get("e.force:closeQuickAction").fire();
      var id = component.get("v.recordId");
      var action = component.get("c.updateOpportunity");
        action.setParams({
               "opportunityId" : id
        });
        
        action.setCallback(this, function(response) {
            if (response.getState() == "SUCCESS") {
                console.log("Save completed successfully.");
               //$A.get("e.force:closeQuickAction").fire();
                alert('Contracted!!Please refresh your screen');
             $A.get("e.force:closeQuickAction");
                  $A.get('e.force:refreshView').fire();
            }else{
                alert('Opportunity is not won!!!');
            }
             var dismissActionPanel = $A.get("e.force:closeQuickAction");
             dismissActionPanel.fire();
        });   
             $A.enqueueAction(action);
      },
     cancel : function(component, event, helper){  
     //$A.get('e.force:refreshView').fire();
      $A.get("e.force:closeQuickAction").fire();
}, 
})

Component-

<aura:component controller="generateContractClass" implements="flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickActionWithoutHeader" access="global">
    <aura:attribute name="recordId" type="String" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>     
   </aura:component>

Blank pop up that I need to remove-
Blank Screen
 
Trying to find out if i can rotate an image once the visualforce page is rendered as a PDF, when it is rendered as HTML the image shows correctly the way you take the image also the css below works with it on HTML but not PDF which is strange because the other style is working for the page when it is in PDF. 
<style type="text/css" media="print">
			@page {
				size: landscape
			}
.imageClass {
				-webkit-transform: rotate(90deg);
				-moz-transform: rotate(90deg);
				-o-transform: rotate(90deg);
				-ms-transform: rotate(90deg);
				transform: rotate(90deg);
				height: 200px;
				width: 200px;
			}

<img src="{!'/sfc/servlet.shepherd/version/download/' + Document_Id__c}" alt="before photo" class="imageClass"


-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
I am parsing JSON that is coming back from  REST callout, and when running, it is throwing this error: attempt to de-reference null object. The issue seems to be with how I am parsing the JSON, but I am not sure where I am going wrong. Can someone help?

Here is the snippet of the JSON I am parsing:
"result": {
"first_name": "JOHN",
"last_name": "SMITH",
"id_type": "MI",
"subscriber_id": "1234567",
"gender": "M",
"birthdate": "19601119",
"address": {
"info": "123 Main St.",
"city": "New York",
"state": "NY",
"zip_code": "100000"
},
"county:": {
"value": "14"
},
"office": {
"value": "H78"
},
"recert_month": {
"value": "12",
"name": "December"
},
"dates": [
{
"name": "Service",
"qualifier": "472",
"date": "2020-09-29"
},
{
"name": "Plan Begin",
"qualifier": "346",
"date": "2020-09-01"
},
{
"name": "Issue",
"qualifier": "102",
"date": "2020-06-01"
}
],


Here is how I am parsing it (bold part is causing error):
  
        Map<String, Object> wholeResponse = (Map<String, Object>) JSON.deserializeUntyped(response2.getBody());
            Map<String, Object> result = (Map<String, Object>) wholeResponse.get('result');
                Map<String, Object> residentAddress = (Map<String, Object>) result.get('address');
                   Map<String, Object> county = (Map<String, Object>) result.get('county');
                  Map<String, Object> office = (Map<String, Object>) result.get('office');
                 Map<String, Object> recert_month = (Map<String, Object>) result.get('recert_month');
        
       Eligibility__c newEligRec = new Eligibility__c(); 
        newEligRec.Referral_Name__c = ref.id;
        newEligRec.First_Name__c = string.valueof(result.get('first_name'));
        newEligRec.Last_Name__c = string.valueof(result.get('last_name'));
        newEligRec.Name_Id_Type__c = string.valueof(result.get('id_type'));
        newEligRec.Client_ID__c = string.valueOf(result.get('subscriber_id'));
        newEligRec.Gender__c = string.valueOf(result.get('gender'));
        string birthdate;
              if (string.valueof(result.get('birthdate')) != null){
                  birthdate = string.valueof(result.get('birthdate')).remove('-');
                  string year = birthdate.substring(0,4);
                  string month = birthdate.substring(4,6);
                  string day = birthdate.substring(6,8);
                 birthdate = month + '/' + day + '/' + year;
                    }
        newEligRec.Date_of_Birth__c = birthdate;
        newEligRec.Address_Number_and_Street__c = string.valueOf(residentAddress.get('info')); 
        newEligRec.City__c =  string.valueOf(residentAddress.get('city'));    
        newEligRec.State__c =  string.valueOf(residentAddress.get('state'));    
        newEligRec.Zip_Code__c = string.valueOf(residentAddress.get('zip_code'));
        newEligRec.County__c = string.valueOf(county.get('value'));
        newEligRec.Office__c = string.valueOf(office.get('value'));
        newEligRec.Recertification_Month_value__c = string.valueOf(recert_month.get('value'));
        newEligRec.Recertification_Month__c = string.valueOf(recert_month.get('name'));
Hi,
I am having trouble with my Visualforce page and Apex Class. Everything seems to be fine apart from the error Unknown Property 'NFOSDisplayDivisions2Controller.Division_Space2__c'. I can't seem to figure out what is going on, could someone please help me out. Thank you.

Apex Class:
public with sharing class NFOSDisplayDivisions2Controller {
    
    public List<DivisionWrapper> listDivisionWrapper{get;set;}
    public List<Division_Space2__c> selectedDivisions{get;set;}

    public NFOSDisplayDivisions2Controller ()
    {
            listDivisionWrapper = new List<DivisionWrapper>();
            searchRecord();
    }
    
    public void searchRecord()
    {
        listDivisionWrapper.clear();
            for(Division_Space2__c a: [select Id, Name,Number_of_Competitors__c, Availability__c, RecordTypeID ,Active__c from Division_Space2__c limit 30]) 
            {
                listDivisionWrapper.add(new DivisionWrapper(a));
            }
    }

    public void processSelected() 
    {
        selectedDivisions = new List<Division_Space2__c>();
        selectedDivisions.clear();
        for(DivisionWrapper wrapDivisionObj : listDivisionWrapper) 
        {
            if(wrapDivisionObj.selected == true) 
            {
                selectedDivisions.add(wrapDivisionObj.acc);
                // Here you can add the counter or you check the selectedAccounts.size()
            }
        }
    }

    public void ActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c= true;
        }
        update selectedDivisions ;
        searchRecord();
    }

    public void DeActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c = false;
        }
        update selectedDivisions ;
        searchRecord();
    }
    


    // This is our wrapper/container class. 
    public class DivisionWrapper 
    {
        public Division_Space2__c acc {get;set;}
        public Boolean selected {get;set;}
        public DivisionWrapper(Division_Space2__c a) 
        {
            acc = a;
            selected = false;
        }
    }

}

Visualforce Page:
<apex:page controller= "NFOSDisplayDivisions2Controller">
    
<script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock id="PB1">
            <apex:pageBlockButtons >
                <apex:commandButton value="Add to Grid" action="{!processSelected}" rerender="table2,PB2"/>
            </apex:pageBlockButtons>

            <apex:pageblockSection title="Division Types" collapsible="false" columns="1">
                <apex:pageBlockTable value="{!listDivisionWrapper}" var="accWrap" id="table" title="Division Types">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!Division_Space2__c.acc.Name}" />
                    <apex:column value="{!Division_Space2__c.acc.Number_of_Competitors__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Availability__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Active__c}" />
                </apex:pageBlockTable>


            </apex:pageblockSection>
        </apex:pageBlock>
        
        <apex:pageBlock id="PB2" >
            <apex:pageBlockButtons >
                <apex:commandButton value="Activate" action="{!ActivateData}" rerender="PB1,PB2"/>
                <apex:commandButton value="DeActivate" action="{!DeActivateData}" rerender="PB1,PB2"/>
            </apex:pageBlockButtons>

                <apex:pageBlockTable value="{!selectedDivisions}" var="c" id="table2" title="Selected Divisions">
                    <apex:column value="{!c.Name}" headerValue="Division Type"/>
                    <apex:column value="{!c.Number_of_Competitors__c}" headerValue="Number of Competitors"/>
                    <apex:column value="{!c.Availability}" headerValue="Availability"/>
                    <apex:column value="{!c.Active__c}" headerValue="Active"/>
                </apex:pageBlockTable>
        </apex:pageBlock>

        
    </apex:form>
</apex:page>
Can someone help me with a report formula?  How can I get a net of the PAYMENT - REFUND for each payment type?   



User-added image
trigger Opps_trigger1 on Opportunity (after insert) {
List<Contact>conlist=new List<Contact>();
List<Opportunity>oppslist=new List<Opportunity>([SELECT Id,Name,CloseDate FROM Opportunity WHERE AccountID IN:Trigger.new]);
for(Opportunity o:Trigger.new)
{
c.AccountID=o.AccountID;
c.FirstName='aryan';
c.LastName='jha';
conlist.add(c);
}
insert conlist;
}
I have a custom object which has a list of products, country field and checkbox- inactive.

Use case: 
When I create an opportunity and add OpportunityLineItem, The line item should compare with the products field from the custom object.
Also, the Opportunity should look at Bill to country from the account attached and compare with the country field from the custom object.
And if the record matches and the "Inactive" checkbox from the custom object is true, then it should throw an error and not allow to save the opportunity.

For example,
Custom object:
Product: Pencil
Country: Mexico
Inavtive: True

Opportunity:
OpportunityLineItem: Pencil
Account - Bill to Country: Mexico
ERROR FLAG

Can this be achievable ? If so, can i receive some help on building the trigger ?

Thank you in advance.
I'm getting the following error when attempting to created this custom formula field on the Opportunity object:

LMS Opportunity Owner Auto-Poulate = 
IF(
INCLUDES(Products_of_interest__c, "Learning Management System (LMS)"),
INCLUDES(Products_of_interest__c, "Schoology LMS"), 
Account.LMS_Account_Owner__c)

Conditions are to set the LMS Opportunity Owner to the LMS Account Owner if Opprotunity Products of Interest = Learning Management System (LMS) or Schoology LMS.

The formula above is giving me the following error:  Incorrect parameter type for function 'IF()'. Expected Boolean, received Lookup(User)

What am I doing wrong?

Hi, folks!

Could you please help me with the following scenario?

I have created a <lightning-datatable> tag in my <template> and I need to hidden the dropdown list with the options Wrap Text and Clip Text.

Screenshot:

As far as I know, there isn't any OOTB class that could help me with that.

When trying to apply a custom style, nothing happens:

.THIS slds-button slds-button_icon-baree{
    display: none ;
}

Has anyone any idea of how to solve that?

Thanks in advance.

 

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