• Abdul Khatri
  • PRO
  • 3811 Points
  • Member since 2015

  • Chatter
    Feed
  • 122
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 1098
    Replies
I have created a lookup field on the content version object that I am trying to auto populate whenever a file is uploaded on that object.

I created a trigger but it only works sometimes, and other times it doesn't.

This is the code that I have:

trigger UpdateCVLookup on ContentVersion (after insert) {
    
    Set<Id> contentDocumentIdSet = new Set<Id>();
    
    for(ContentVersion cv:trigger.new)
    {
        if(cv.ContentDocumentId != null)
        {
            contentDocumentIdSet.add(cv.ContentDocumentId);
        }
    }
    
    ContentDocumentLink cdl = [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet LIMIT 1];
 
    // Project__c can be replaced with the object that has the lookup relationship.

    List<Project__c> upList = [SELECT Id, name FROM Project__c where Id =:cdl.LinkedEntityId];   
    
    //In the following line, make sure to replace Project__c(The lookup field name) with the api name of the lookup field on the content version object.
    List<ContentVersion> cvList = [SELECT Id, Project__c, ContentDocumentId FROM ContentVersion where Id IN: Trigger.newMap.keySet()];
    
    for(ContentVersion cv:cvList)
    {
        if(upList.size() > 0)
        {//In the next line Project__c is referring to the lookup object.
            for(Project__c p : upList){
                //The following line Project__c is referring to the lookup field on Content Versions.
                cv.Project__c = p.Id; 
            }
        }
        else if(upList.size() > 0){
            //The next two lines containing Project__c are referring to the lookup field on Content Versions
            cv.Project__c = cdl.LinkedEntityId;
        } else {
            //This line below is required so that files can still be uploaded to other objects.
            cv.Project__c = null;
        }
    }
    update cvList;
}
I have a custom object called "Returned Mail". This has a field called "parent record". This is a lookup to Returned Mail record (not itself, a different returned mail record). 
Ex: Test 1 and Test 2 are returned mail records. Test 1 is a lookup on Test 2 and is called as the parent record. When someone creates a new record called Test 3 and tries to set Test 2 as its parent record then, they should be prevented from doing so and the field should populate to Test 1. 

User-added image

User-added image
Hello,

I've been struggling with creating a test class for a custom controller with if statements for a Visualforce page. I have no idea what I'm doing wrong and have looked all over these forums and google for an answer with no luck. If someone could give this a shot and let me know what I am doing wrong that would be amazing.

Here is my controller:
public class SuspectListController {
	public final Account act;
    public SuspectListController(ApexPages.StandardController stdController) {
        this.act = (Account)stdController.getRecord();
    }

    public Id AccountId = ApexPages.currentPage().getParameters().get('id');

    public List<HealthCloudGA__EhrEncounter__c> EHRRecords = [SELECT Name, CreatedDate, HealthCloudGA__HospitalizeDischargeDiagnosis__c
                                                       FROM HealthCloudGA__EhrEncounter__c WHERE HealthCloudGA__Account__c = :AccountId AND CreatedDate = LAST_N_DAYS:365 ORDER BY CreatedDate desc];

    public List<String> RType = new List<String>();
    public List<String> Name = new List<String>();
    public List<String> CDate = new List<String>();
    public List<String> Code = new List<String>();
    public List<String> Description = new List<String>();

    public List<String> getType() {
        for (HealthCloudGA__EhrEncounter__c encounter : EHRRecords) {
             if (!Description.contains(encounter.HealthCloudGA__HospitalizeDischargeDiagnosis__c) && encounter.HealthCloudGA__HospitalizeDischargeDiagnosis__c != null) {
                RType.add('EHR Encounter');
                Name.add(encounter.Name);
                Cdate.add(encounter.CreatedDate.format('MM/dd/yyyy'));
                Code.add('');
                Description.add(encounter.HealthCloudGA__HospitalizeDischargeDiagnosis__c);
            }
        }    
        
        return RType;
    }

    public List<String> getName() {
        return Name;
    }
    
    public List<String> getCDate() {
        return CDate;
    }
    
    public List<String> getCode() {
        return Code;
    }
    
    public List<String> getDescription() {
        return Description;
    }
This controller was created to add field values to a list if they are not on the list already and pass that list to an html table on a Visualforce page (Adding to every list in the first function is a bit funky but it saves from looping through each record in each function). My test class currently passes everything except for the if statement and its contents.

Here is my current test class:
@isTest
private class SuspectListTestClass {
    @testSetup static void testSetup() {
        Account testaccount = new Account();
        testaccount.name = 'Zander Test';
        testaccount.Primary_Insurance__c = 'Test Insurance Company';
        testaccount.Gender__c = 'Male';
        testaccount.County__c = 'Maricopa';
        testaccount.RecordTypeId = '012360000004FEPAA2';
        insert testaccount;
    }

    @isTest static void testEHREncounterPass() {
        Account act = [SELECT Id FROM Account WHERE Name = 'Zander Test' LIMIT 1];
        HealthCloudGA__EhrEncounter__c testencounter1 = new HealthCloudGA__EhrEncounter__c();
        testencounter1.HealthCloudGA__Account__c = act.Id;
        testencounter1.HealthCloudGA__HospitalizeDischargeDiagnosis__c = 'Test';
        insert testencounter1;
        PageReference testpagereference = Page.SuspectList;
        test.setCurrentPage(testpagereference);
        SuspectListController testcontroller = new SuspectListController(new ApexPages.StandardController(act));
        testcontroller.Description.add('');
        String[] record = testcontroller.getType();
        System.assertEquals('EHR Encounter',record[0]);
    }
    
    @isTest static void testEHREncounterFail() {
        Account act = [SELECT Id FROM Account WHERE Name = 'Zander Test' LIMIT 1];
        HealthCloudGA__EhrEncounter__c testencounter2 = new HealthCloudGA__EhrEncounter__c();
        testencounter2.HealthCloudGA__Account__c = act.Id;
        testencounter2.HealthCloudGA__HospitalizeDischargeDiagnosis__c = 'Test';
        insert testencounter2;
        PageReference testpagereference = Page.SuspectList;
        test.setCurrentPage(testpagereference);
        SuspectListController testcontroller = new SuspectListController(new ApexPages.StandardController(act));
        testcontroller.Description.add('Test');
        testcontroller.getType();
    }

    @isTest static void testSuspectListController() {
        Account act = [SELECT Id FROM Account WHERE Name = 'Zander Test' LIMIT 1];
        PageReference testpagereference = Page.SuspectList;
        test.setCurrentPage(testpagereference);
        SuspectListController testcontroller = new SuspectListController(new ApexPages.StandardController(act));
        testcontroller.getName();
        testcontroller.getCDate();
        testcontroller.getCode();
        testcontroller.getDescription();
    }
}
From what I understand you need to have one test where it is meant to pass and one where it is meant to fail. I have made 2 test methods but no matter what I do I can not seem to get one to pass. I get an error from the assertEquals() saying that the index is out of range meaning it did not add "EHR Encounter" to the RType list.

Am I missing something here??
I feel like I have inserted a record that should pass but I guess not.
Please help!

Thanks in advance!

 
Hi All,
         I want to create a validation rule which have conditions below:-
1. When IsReccur__c(checkbox) is true and ReccurWithTime___c(Checkbox) is false and reccurType__c(Picklist) and NumberReccur__c(Picklist) is null than show error :- You cant save record.
2. When IsReccur__c is false and ReccurWithTime___c is also false,
 and EndTime(Date/Time) and startTime(Date/TIme)  is not blank than show error.
3.  When IsReccur__c is True and ReccurWithTime___c is also True,
 and EndTime(Date/Time) and startTime(Date/TIme)  is not blank than show error.
Can anyone help me with this validation?
Hi All,

I am getting system.null pointer exception: attempt to de-reference a null object, when trying to insert a record with null value in date field.
How to resolve this error. Need your assistance to fix this issue.

Below is my Trigger:
Trigger:


trigger insertDailyPractices on Study_Plan__c (after insert) 
{
    System.debug('--- Inside Trigger ---');
    List<Daily_Practice__c> dplist = new List<Daily_Practice__c>();    
    
    for(Study_Plan__c sp : Trigger.New)
    {
            Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c); ----/// Getting error in this line.
            
System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c);
            System.debug('--- Day Count ---' + daycount);
     
        for(integer i=0; i<=daycount; i++)
        {
            Daily_Practice__c dps = new Daily_Practice__c();
            dps.Due_Date__c = sp.Phase_Start_Date__c.addDays(i) + 1;
            dps.StudyPlan__c = sp.Id;
            dps.Status__c = 'Assigned';
            dplist.add(dps);
        }
    }
    
    if(dplist.size() > 0)
    {
        insert dplist;
    }    
    system.debug('--- Inserted Daily Practice ---'+ dplist.size());
}

Thanks
Hello, I am playing with @future method with below code

public class AccountProcessor {
@future
  public static void countContacts(List<Id> recordIds) {
       string AcName = 'United Oil & Gas%';
       List<AggregateResult> ct_contacts = [Select AccountId, Count(Name) from Contact Where Account.Name Like :AcName group by AccountId ];
       List<Account> Upd_Account = new List<Account>();
       
       system.debug('Count - ' + ct_contacts.size());
      
        for (AggregateResult ar : ct_contacts)  {
            Account acc = new Account();
            acc.Id = ((Id)ar.get('AccountId'));
            acc.Number_of_Contacts__c = ((Integer)ar.get('expr0'));
            Upd_Account.add(acc);
            
        }
      update Upd_Account;
  }
}

and below test calss

@IsTest
public class AccountProcessorTest {
      @IsTest
      private static void testAccountProcessor() {
        Id myId1 = Id.valueOf('0016g000007qSglAAE');
        Id myId2 = Id.valueOf('0016g000007qSgmAAE');
        List<Id> MyList =new List<Id>();
        MyList.add(myId1);
        MyList.add(myId2);
                  
        Test.startTest();
          AccountProcessor.countContacts(MyList);
        Test.stopTest();
          
        // runs callout and check results
        List<AggregateResult> logs = [Select AccountId, Count(Name) from Contact Where AccountId IN :MyList group by AccountId];
        System.assertEquals(0, logs.size());
      }
}

My code is not gettign 100% coverage i treid removing @future as well but it is not executing the SOQL..

Select AccountId, Count(Name) from Contact Where Account.Name Like :AcName group by AccountId

I beleive it is not able to substitute the variable.

14:00:17:006 SOQL_EXECUTE_BEGIN [4]|Aggregations:0|SELECT AccountId, COUNT(Name) FROM Contact WHERE Account.Name LIKE :tmpVar1 GROUP BY AccountId

Is there any lilitation for using AggregateResult?

Thanks,
Sakthi
Test class below that was working perfectly is now failing with "Methods defined as TestMethod do not support Web service callouts" I have narrowed it down to the case insert line insert c; .  Is this a permissions issue on the case object ? all the other inserts work .

@isTest

public class DefaultEntitlementTest {
     static testmethod void ValidateDefaultEntitlementAction() {
        Account[] acc = new Account[] {
            new Account(Name='Test Account 1'),
            new Account(Name='Test Account 2')
        };
        insert acc;
       
        Contact[] contacts = new Contact[] {
            new Contact(FirstName='Test 1', LastName='McTesty', AccountId = acc[0].id),
            new Contact(FirstName='Test 2', LastName='McTesty', AccountId = acc[0].id)
        };
        insert contacts;
       
        Id entitlementProcessId = [SELECT Id FROM SlaProcess WHERE SObjectType = 'Case' LIMIT 1].Id;
       
        Entitlement[] ent = new Entitlement[] {
            new Entitlement (AccountId=acc[0].Id, SLAProcessId = entitlementProcessId, Name = 'Test Entitlement Account',
                                           StartDate = system.today(), EndDate = system.today()),
            new Entitlement (AccountId=acc[1].id, SLAProcessId = entitlementProcessId, Name = 'Test Entitlement Contact',
                                           StartDate = system.today().addDays(-1), EndDate = system.today().addDays(5))
        };
        insert ent;
       
        EntitlementContact ec = new EntitlementContact(ContactId = contacts[0].id, EntitlementId = ent[1].id);
        insert ec;
       
        Case c = new Case(AccountId = acc[0].id, ContactId = contacts[0].id, Subject='Test');
        insert c;
        
        List<Case> caseList = new List<Case>{c};
       
        DefaultEntitlementAction.updateDefaultEntitlements(caseList);
    }
}
 

Hello,
My use case is that I am importing csv files through data import wizard to land on a custom object ("Network Statistic"), which has a lookup field to its parent object, namely "Account" (custom field called "Referral Account"). This is an insert (not upsert) import. I need the lookup field to populate for 100% of the records, and therefore if the parent account does not exist, I need my Trigger to add and insert that account, before my Network Statistic record is added. Below is some sample code that doesn't work but may be on the right track... 

trigger NetworkStatsTrigger on Network_Statistic__c (before insert) {
 Map<String,Network_Statistic__c> hospNumbers = new Map<String,Network_Statistic__c>();
 Set<String> presentHospNumber = new Set<String>();
 List<Account> accList = new List<Account>();
 for(Network_Statistic__c d : Trigger.new){
  if(d.Referral_account__c != null && d.Referral_account__r.Hospital_number__c != null){
    hospNumbers.put(d.Referral_account__r.Hospital_number__c ,d);
  }
 }
 List<Account> presentAccounts = [SELECT Id,hospital_number__c FROM Account WHERE hospital_Number__c in : hospNumbers.keySet()];
 for(Account a : presentAccounts){
     presentHospNumber.add(a.hospital_number__c);
 }
 Set<String> hospNumberToAdd = hospNumbers.keySet(); 
 hospNumberToAdd.removeAll(presentHospNumber); 
 for(String hospNum : hospNumberToAdd){
  Account a = new Account();
  a.Name = hospNumbers.get(hospNum).hospital_name__c;
  a.AccountNumber = hospNum ;
  a.hospital_number__c = hospNum ;
  accList.add(a);
 }
 insert accList;
}
 
If user clicks on the case no. in community page, the details needs to be displayed in community layout. Developing Lightning Web Component for this to display the case details (few fields only). I have html file and xml files ready. When trying to save the .js file, I am getting the below error msg. Can someone help me on this.. new to this. 
I am following the link by @RajVakati  (Displaying Record Fields section)
https://rajvakati.com/lightning-web-components/

The 'title' property does not exist on the component Error

<template>
    <lightning-record-view-form
                record-id={recordId}
                object-api-name="case">
        <div class="slds-grid slds-gutters">
            <div class="slds-col slds-size_1-of-2">
                <lightning-output-field field-name='CaseNumber'></lightning-output-field>
            </div>
            <div class="slds-col slds-size_1-of-2">
                <lightning-output-field field-name='Origin'></lightning-output-field>
            </div>


import { LightningElement ,api} from 'lwc';
 
export default class Recordview extends LightningElement {
    @api recordId ;
}
           
        </div>
    </lightning-record-view-form>
</template>




 
  • January 20, 2020
  • Like
  • 0
Hello all,
I am trying to show another div based on a checkbox toggle but its not working.  I tried using the aura:if but the div never renders.  I am able to use the aura:if is true in other places on the form but not for the checkbox toggle.  
<div class="modalCheckContainer">
                <span>
                    <label class="slds-checkbox--toggle slds-grid checkbox-left">
                        <span class="slds-form-element__label slds-m-bottom--none">file attached?</span>
                        <input id="attfile__c" type="checkbox" name="checkbox"
                            aria-describedby="fileattatoggle" value="{!v.fileatttoggle}" />
                        <span id="Toggle" class="slds-checkbox--faux_container" aria-live="assertive">
                            <span class="slds-checkbox--faux"></span>
                            <span class="slds-checkbox--on"></span>
                        </span>
                    </label>
                </span>
        </div>

Cheers,
P
I am writing an after-insert trigger on the Case object.  I am looking to send an email to one of two people depending on a field that is a child of the Account object.  A sibling to Case.  In my journey I have found that it is not possible to query a sibling (correct me if I'm wrong).  So I've decided,  once I have the Case, I will take the AccountId and do all of my logic and querys from there.

CustObject_Chld2Acct.fieldname - Child to Account, sibling to Contact
 
List<AggregateResult> AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co, 
                                    FROM Case
                                    WHERE CreatedDate = LAST_N_DAYS:5
                                    GROUP BY AccountId, Account.Name
                                    HAVING COUNT(Id)  >= 8];
                       
        Set<Id> accIdSet = new Set<Id>();
        for(Case c: AggregateResultList) {
        if(c.AccountId != null) {
           System.debug(c.AccountId);
           // Now i have the Account ID, what do I do?  
           //Need to access fields in Account Object (Parent)
           //Need to access fields in CustObject_Chld2Acct          
        }

 

Hi,

I'm creating a Unit Test for a method that calls to another callout method.

I got the following error: Methods defined as TestMethod do not support Web service callouts

I've already created the Unit Test for the callout method and everything works OK.

How could I do it?

cass a{

public mycalloutmethod(url){ return Response.body}

public mymethodfortesting(){
String a = mycalloutmethod('myurl');
do something else
}
}

Thanks,
Pedro

 
I have a batch job that is giving me an error when I use the execute anonymous window. Any ideas of what this coud be? 
global class ServiceAppointmentCancel implements Database.Batchable<SObject>, Schedulable{ global Database.QueryLocator start(Database.BatchableContext BC) { String subject = 'Reload'; String status = 'O'; Date scheduledEnd = Date.today(); String query = 'SELECT Subject,Status,SchedEndTime FROM ServiceAppointment ' + ' WHERE subject = : ' + subject + ' AND status = :' + status + ' AND scheduledEnd < ' + scheduledEnd; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<ServiceAppointment> serviceAppointments) { // Loop to iterate over the service appointments for(ServiceAppointment service : serviceAppointments) { service.status = 'C'; } // Preforming the DML operation update serviceAppointments; } global void finish(Database.BatchableContext BC) { } global void execute(System.SchedulableContext SC) { Database.executeBatch(new ServiceAppointmentCancel(), 200); } }

String q = 'SELECT Reload, O, Date.today()'; Database.executeBatch(new ServiceAppointmentCancel(), 200);

User-added image
 
Hi All,
Can anybody help me to write a test class for the below apex class.
public class MobileShopeeClass{
public static void NewCustomerDiscount(list<Mobile__c>MobileList1){
for(Mobile__c m:MobileList1){
if(m.Brand__c=='Samsung'){
m.Price__c=m.Price__c-(m.Price__c*10)/100;
m.Discount_status__c='You have got 10 % Discount!!';
}
else if(m.Brand__c=='Apple')
{
m.Price__c=m.Price__c-(m.Price__c*20)/100;
m.Discount_status__c='You have got 20 % Discount!!';
}
}
}
public static void OldCustomerDiscount(list<Mobile__c>MobileList2){
for(Mobile__c m:MobileList2){
if(m.Brand__c=='Samsung'){
m.Price__c=m.Price__c-(m.Price__c*5)/100;
m.Discount_status__c='You have got 5% Discount!!';
}
else if(m.Brand__c=='Apple')
{
m.Discount_status__c='Sorry,no discount!!';
}
}
}
I have a batch apex job that basically goes through all invoices and totals the amounts for each sales person for each month and year.  The job works as expected in the sandbox environment with the test data I created.  But when I moved the job to production, it runs without errors, but does not update the fields with the monthly invoice sum totals like it does in sandbox.  In reviewing the logs I found one for example that found totals and shows that it updated the fields for the months.  Then in the very next log that did not find any invoices with totals, it updated the fields with null values for the very same records as in the prior log.  The Forecast and Forecast detail objects were created from scratch for this batch job and have no other triggers or processes running against them to udpate any fields.  My code is below, can anyone see why it is not updating the sum fields properly?

global with sharing class Forecast_Batch implements Database.Batchable<sObject>, Database.Stateful{

        global Database.QueryLocator start(Database.BatchableContext BC)
        {
            return Database.getQueryLocator([SELECT Id,OwnerId FROM Account]); //Query all accounts for ID and OwnerId
        }

    global void execute(Database.BatchableContext BC, List<SObject> scope)
    {        
        Map<Id, Map<String,Decimal>> accountAmountMap = new Map<Id,Map<String,Decimal>>();

        List<Id> accountOwnerIds = new List<Id>();
        Set<Id> accountIds = new Set<Id>();
        
        system.debug('+++ SCOPE SIZE ' + scope.size());
        
        for (SObject s : scope) {
            
            Account acc = (Account)s;
            if(!accountIds.contains(acc.Id)){
                accountIds.add(acc.Id);
            }
            
        }
        
        for (Account acc : [SELECT OwnerId,(SELECT Amount__c,InvoiceDate__c,OwnerDetails__c,Inv_Yr__c FROM Invoice__r ) FROM Account WHERE Id in : accountIds]) {
            
            Map<String, Decimal> amountMap = new Map<String, Decimal>();
            
            for (Invoice__c inv : acc.Invoice__r) {
                 
                Decimal amount = amountMap.get(inv.OwnerDetails__c);
                if (amount != null) {
                    amountMap.put(inv.OwnerDetails__c, inv.Amount__c + amount); 
                } else {
                    amountMap.put(inv.OwnerDetails__c, inv.Amount__c); 
                }
            }
            accountAmountMap.put(acc.Id, amountMap);
            accountOwnerIds.add(acc.OwnerID);
            
        }
        System.debug(accountOwnerIds);

         // Query list of forecast details record based on Account's owner Id

        List<Forecast_Details__c> forecastdetails = [SELECT ID,Name,Month_Total__c,OwnerID__c,FDOwnerDets__c from Forecast_Details__c where OwnerID__c IN : accountOwnerIds];

        // Iterate accounts in for loop
        // iterate forecast details record
        // get invoice amount based on account id and forcast month.
        // update in forecast detail record.

        for (SObject s : scope) {
            Account acc = (Account)s;
            Map<String, Decimal> amountMap = accountAmountMap.get(acc.Id);
            for (Forecast_Details__c forecastDet : forecastdetails) {
                if (forecastDet.OwnerID__c == acc.OwnerId)
                    
                {
                    Decimal amount  = amountMap.get(forecastDet.FDOwnerDets__c);  
                    forecastDet.Month_Total__c = amount;
                    System.debug('match');
                    System.debug(amount);
                }
            }
        }
        System.debug(forecastdetails);
        update forecastdetails;
    }  

    global void finish(Database.BatchableContext BC){}



I really appreciate any assistance that anyone can provide!
Hi!

I have the query below in the controller of one of my visualforce pages:
 
SELECT Id, Name, Title, Company, Country, CreatedDate, Status FROM Lead WHERE Status='New' AND OwnerId= :UserInfo.getUserID() ORDER BY CreatedDate DESC

What I would like to do some kind of outer join to check if the Lead.Company field exists as a Account.Name so I can show this on the Visualforce page.

Any ideas on how to do this?
I'm attempting to create a note for an opportunity via the REST API.  I'm finding several examples for the SOAP API, but nothing that works using REST.  Using this API I am able to create a note, but can find no way to associate it with an opportunity ID:

https://developer.salesforce.com/docs/api-explorer/sobject/Note

Any help would be greatly appreciated.

Hi Guys,

I am triggering a POST request via process builder and it works but can you please tell me how can I capture the HTTP response I get back? The external system will send me a string I would like to store on the record which started the process. 
 

@future(callout=true)

        public static void calloutmethod(String name){
                Http http = new Http();
                HttpRequest request = new HttpRequest();
                request.setEndpoint('XXX');
                request.setMethod('POST');
                request.setHeader('Content-Type', 'application/json;charset=UTF-8');
                request.setHeader('accept', 'application/json');
                request.setBody(name);
                
                response = http.send(request);
        }

Thanks a lot.

Krisz
Hi,

I am having a massive confusion,

We have a database of 400,000 records.. which calls for duplication.

I want to check if alternate phone number of any of the account matches with the Primary phone number of any of the account, If it does, there is a checkbox  called "Marked For deletion"  m that checkbox should get selected and primary phone number of that account should become the alternate phone number of the acount against which it has matched 

So lets say ,

Accoount : A  Primary No : 1234  Secondary No : 5678

Accoount : B  Primary No : 9241  Secondary No : 1234 

Accoount : C  Primary No : 9241  Secondary No :  1234

Account B and Account C should have marked for deletion checked.
and Account B's primary phone number should become Secondary phone number of Account A. 

Please help me in achieving this 
 
I need to update the Account Name (Account_Name__c) custom field in the Task tab, with the Account Name (AccountId). My current code is:

trigger Account_Name on Task (before insert, before update) {
    for(Task a : trigger.new) {        
        task.Account_Name__c = a.AccountId;
    }
}


I keep receiving an error that says: A value cannot be stored to Account_Name__c in type task. What am I doing wrong?
Hi,

I am looking to see the best approach for Salesforce CI. I have gone through many forum and blogs but haven't been able to grasp them. I tried to setup CI for the entire org but facing a lot of challeges which I guess you guys quite aware of.

What I am looking to do incremental deployment based on the git diff, dynamically generate package.xml based on the metadata committed which I think would be manageable something like sfdc-git-package https://www.npmjs.com/package/sfdc-git-package. I am having a hard time implementing this.

Please someone help
Can someone help me to show how I can change the Sales Console Lightning Layout. Currently it is showing as shown in the screen shot below as 3 Column layout. I wanted to change the layout to show the highlight panel on top. I am finding no help from Salesforce help section or trailhead for this. Please bear in mind I am talking about Lightning Sales Console and not Classic. I did the Edit Page and takes me but doesn't allow me to change the layout. 

User-added image
Is there a way to hide "Save & New" Button from the Task page Layout?

User-added image

I looked at everywhere and couldn't find the solution. I do want to give them Create/Edit Permission so no option there to remove that.

Please help
Custom URL for the cast creating inline headers and side bar. I tried the following addition things

            urlConcat += '&inline=0';
            urlConcat += '&isdtp=lt';
            urlConcat += '&isdtp=nv';
            urlConcat += '&isdtp=vw';

the only one that work is '&isdtp=nv' but after saving the activity, the hyperlink in the related list doesn't work. I have attached a screen shot 

User-added image

Anyone can help?

 
Hi,

I am looking to see the best approach for Salesforce CI. I have gone through many forum and blogs but haven't been able to grasp them. I tried to setup CI for the entire org but facing a lot of challeges which I guess you guys quite aware of.

What I am looking to do incremental deployment based on the git diff, dynamically generate package.xml based on the metadata committed which I think would be manageable something like sfdc-git-package https://www.npmjs.com/package/sfdc-git-package. I am having a hard time implementing this.

Please someone help
Hi Expert,

I am using add error method, when criteria match then addError method call, but here script doenot stop and execute next loop.

i want to stop script when addError call. i have used break; return; but nothing happen

 
for (Opportunity currOpp: newOpportunities_1){
              System.debug('currOpp name '+currOpp.name);
            if (currOpp.RecordTypeId!=PMRecordTypeId.Id  ){
                currOpp.addError(Label.pmr);   
               
            }
          }

for (Opportunity currOpp: newOpportunities_2){
              System.debug('currOpp name '+currOpp.name);
         
          }

Thanks 
Mukesh

 
hi guys  ,
while i am saving the code i am getting this error"Failed to save campingList.cmp: Invalid definition for null:CampingListController: ApexService.getType() return null with currentNamespace: c, namespace: null, name: CampingListController: Source" I do not know where ii am doing the error and below is my code .


campinglist.cmp
    

<aura:component controller="CampingListController" >

    <aura:attribute name="items" type="Camping_Item__c[]" />
   
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
   
    <aura:attribute name="newItem" type="Camping_Item__c" default="{'sObjectType':'Camping_Item__c','Quantity__c':0,'Price__c':0}" />
      
    <br/><br/>
    <p>Name:
    <ui:inputText aura:id="name" value="{!v.newItem.Name}" Label="Name" />
    </p><br/>
    <p>Quantity:
    <ui:inputNumber aura:id="quantity" value="{!v.newItem.Quantity__c}" Label="Quantity" />
    </p><br/>
    <p>Price:
    <ui:inputCurrency aura:id="price" value="{!v.newItem.Price__c}" Label="Price" />
    </p><br/>
    <p>Packed?:
    <ui:inputCheckBox value="{!v.newItem.Packed__c}" Label="Packed" />
    </p><br />
   
    <ui:button label="Submit" press="{!c.PushItems}" />
   
    <aura:iteration items="{!v.items}" var="item">
   
    <p> <ui:outputText value="{!item.Name}" /> </p>
   
    <p> <ui:outputNumber value="{!item.Quantity__c}" /> </p>
   
    <p> <ui:outputCurrency value="{!item.Price__c}" />  </p>
   
    <p> <ui:outputCheckbox value="{!item.Packed__c}" /> </p>  
       
    </aura:iteration>
       

</aura:component>

can anyone help me .

 
I have created a lookup field on the content version object that I am trying to auto populate whenever a file is uploaded on that object.

I created a trigger but it only works sometimes, and other times it doesn't.

This is the code that I have:

trigger UpdateCVLookup on ContentVersion (after insert) {
    
    Set<Id> contentDocumentIdSet = new Set<Id>();
    
    for(ContentVersion cv:trigger.new)
    {
        if(cv.ContentDocumentId != null)
        {
            contentDocumentIdSet.add(cv.ContentDocumentId);
        }
    }
    
    ContentDocumentLink cdl = [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet LIMIT 1];
 
    // Project__c can be replaced with the object that has the lookup relationship.

    List<Project__c> upList = [SELECT Id, name FROM Project__c where Id =:cdl.LinkedEntityId];   
    
    //In the following line, make sure to replace Project__c(The lookup field name) with the api name of the lookup field on the content version object.
    List<ContentVersion> cvList = [SELECT Id, Project__c, ContentDocumentId FROM ContentVersion where Id IN: Trigger.newMap.keySet()];
    
    for(ContentVersion cv:cvList)
    {
        if(upList.size() > 0)
        {//In the next line Project__c is referring to the lookup object.
            for(Project__c p : upList){
                //The following line Project__c is referring to the lookup field on Content Versions.
                cv.Project__c = p.Id; 
            }
        }
        else if(upList.size() > 0){
            //The next two lines containing Project__c are referring to the lookup field on Content Versions
            cv.Project__c = cdl.LinkedEntityId;
        } else {
            //This line below is required so that files can still be uploaded to other objects.
            cv.Project__c = null;
        }
    }
    update cvList;
}
Hello crew, this problem has got me tasting pennies so if anyone could lend some insight I would be eternally grateful. So this is a vastly simplified version of what I am working with (excuse me if this question is poorly formatted, this submission form is a nightmare):

trigger OpportunityTrigger on Opportunity (after insert, after update) {
   <Unimportant Logic Here>
   Set<String> emailSet = OpportunityTriggerHandler.unimportantLogic(Trigger.oldMap, Trigger.NewMap)
   List<Contact> matchingContactsOpenAccounts = OpportunityTriggerHandler.matchingContactsWithAcctStatus(emailSet, 'OPEN');
<More Unimortant Logic>
}

public class OpportunityTriggerHandler {

    public static List<Contact> matchingContactsWithAcctStatus(Set<String> emailSet, 
                                                               String accountStatus)
    {
        List<Contact> matchingContacts = [
            Select
            AccountId,
            Email
            From Contact
            Where Email In :emailSet
            And Account.Billing_Status__c = :accountStatus
            And Account.Original_Close_Date__c != Null       
        ];
        return matchingContacts;
    }
}

@isTest
public class OpportunityTriggerTest {
   @testSetup
       private static void setup()
       {
           <Set Up A Bunch of Stuff>
       }
   
   @isTest
    private static void testWinBackInsertWithNoMatchingAccounts()
    {
        Account beforeOpp = [Select Id from Account Where Name = 'Acct One'];
        Date now = System.today();
        Opportunity o = New Opportunity(
            Name = 'Test Opp',
            AccountId = beforeOpp.Id,
            StageName = 'Booked at DOW',
            CloseDate = now);
        insert o;
        Account afterOpp = [Select Id, Win_Back__c from Account Where Name = 'Acct One'];
        System.assert(afterOpp.Win_Back__c);
    }
}

So the problem I am running into is with the SOQL query in the method matchingContactsWithAcctStatus. This method accepts a list of strings (emails) and an account status and queries for contacts with a matching email and account bill status WHERE the Original_Close_Date__c != Null. 

Original_Close_Date__c is a rollup field that holds the date of the first closed Opportunity on the account. Now here is the fun part. When I functionally test this trigger by creating objects in my dev org, it works fine. If I create mock data in the above test class and call the static function directly in my test class it works fine. However, in the above example, when I insert a mock Opportunity to fire the trigger IN A TEST CLASS the SOQL function is no longer able to access the value in that rollup field. It always returns Null value when calling the SOQL query from within that function. I literally invoked the trigger in the test class and ran it side by side calling the method with the same params and watched as they returned different data.

My initial reaction is to just stop using rollup functions in Apex triggers if they can't reliably be tested. I can just throw in another function that determines whether or not that field is null but this seems so... dumb. Am I missing anything? 

Thanks!
I am getting an error System.LimitException: Too many SOQL queries: 101 .
my code.
trigger contactaccountrelation on Contact (before insert) {
 
       list<account> acc = [select id, name from account];
    for(account a : acc){
    for(contact con : [select lastname, accountid from contact where accountid =: a.id]){
        con.OtherPhone = a.Phone;
    }
    }
}
I have a custom object called "Returned Mail". This has a field called "parent record". This is a lookup to Returned Mail record (not itself, a different returned mail record). 
Ex: Test 1 and Test 2 are returned mail records. Test 1 is a lookup on Test 2 and is called as the parent record. When someone creates a new record called Test 3 and tries to set Test 2 as its parent record then, they should be prevented from doing so and the field should populate to Test 1. 

User-added image

User-added image
1) I am able to successfully authenticate with the external system, however, I am unable to parse the data to Visualforce page.

2) I get no output on the VF page. What is wrong with the below code?

if(response.getStatusCode()==200)
        {
            Map<String,Object> results= (Map<String,Object>)JSON.deserializeUntyped(response.getBody());                   
            user_id=String.valueOf(results.get('user_id'));
            team_id=String.valueOf(results.get('team_id'));
else
        {
            ApexPages.Message myMsg=new ApexPages.Message(ApexPages.Severity.ERROR, 'There was an error in fetching the data');
            ApexPages.addMessage(myMsg);
Hello. How to trigger code with a button? 

I have HelloWorld trigger 

trigger CreateSparePart on Propulsion_part__c (before insert) {
    System.debug('Hello World!');
}

How to link it to the button on my lighting page? 
Hello!

I'm working with a pretty basic Lightning Web Component. I've followed this guide loosely. https://trailhead.salesforce.com/en/content/learn/projects/lwc-build-flexible-apps/record-list 

The only differentiation is that I'm using a different API. 
Here is my js file
import { LightningElement, wire } from 'lwc';
import getStarships from '@salesforce/apex/StarshipController.getStarships';

export default class StarshipViewer extends LightningElement {
    starships;
	error;

    connectedCallback(){
        getStarships()
			.then(result => {
				this.starships = result;
			})
			.catch(error => {
				this.error = error;
			});
    }
}
Here is my controller
public inherited sharing class StarshipController {
    @AuraEnabled
    public static List<Starship> getStarships(){
        List<Starship> starships = new List<Starship>();
        string strEndPointURL = 'https://swapi.dev/api/starships/';
                
        starships = getStarships(strEndPointURL);
        system.debug(starships.size());
        return starships;
    }
    
    private static List<Starship> getStarships(string strEndPointURL){
        String strResponse = null;
        if(String.isNotBlank(strEndPointURL)) {
            HttpRequest request = new HttpRequest();
			request.setEndpoint(strEndPointURL);
			request.setMethod('GET');
			request.setHeader('Accept', 'application/json');
            
            try {  
                Http http = new Http();   
				HttpResponse response = http.send(request);
                                
                if (response.getStatusCode() == 200 ) {  
                    strResponse = response.getBody();  
                } 
                else {  
                    throw new CalloutException(response.getBody());  
                }   
            } 
            catch(Exception ex) {  
                throw ex;  
            }  
        } 
        
        if(!String.isBlank(strResponse)) {
            JSON2Apex res = JSON2Apex.parse(strResponse); 
            return res.results;
        } else {
        	return new List<Starship>();
        }        
    }
}

I can run it in anonymous window and see results. I also see the aura log that proves it is being called. It returns 10 records, but when I view the results the objects returned are just blank objects.

I'm not sure why it is showing up as blank. Am I being hit by some kind of limit when data is being sent to the front end?

Showing objects in chrome debugger are empty
 
Hi All, 

Any help on the below would be much appreciated.

have the below trigger and its working perfectly in the sandbox but after deploying to prod I am getting a CPU time limit exeeded failure... 

trigger ProfileTrigger on User (before insert, before update) {
    List<Id> userIds = new List<Id>();
    List<Case> cases = new List<Case>();
    List<Case> casesToUpdate = new List<Case>();
    for(User u: Trigger.new) {
        if(u.out_of_office__c==True) {
            userIds.add(u.Id);
        }
        for (case c : (cases = [SELECT id, Status FROM Case where ownerId IN:userIds]))
            IF(c.Status == 'Assigned' || c.Status == 'Working' ||c.Status == 'Escalated'){
            c.Reassign_to_Queue__c=true;
            casesToUpdate.add(c);
        }
        update casesToUpdate;
    }

Many thanks in advance! 
Pete
Hello,

I've been struggling with creating a test class for a custom controller with if statements for a Visualforce page. I have no idea what I'm doing wrong and have looked all over these forums and google for an answer with no luck. If someone could give this a shot and let me know what I am doing wrong that would be amazing.

Here is my controller:
public class SuspectListController {
	public final Account act;
    public SuspectListController(ApexPages.StandardController stdController) {
        this.act = (Account)stdController.getRecord();
    }

    public Id AccountId = ApexPages.currentPage().getParameters().get('id');

    public List<HealthCloudGA__EhrEncounter__c> EHRRecords = [SELECT Name, CreatedDate, HealthCloudGA__HospitalizeDischargeDiagnosis__c
                                                       FROM HealthCloudGA__EhrEncounter__c WHERE HealthCloudGA__Account__c = :AccountId AND CreatedDate = LAST_N_DAYS:365 ORDER BY CreatedDate desc];

    public List<String> RType = new List<String>();
    public List<String> Name = new List<String>();
    public List<String> CDate = new List<String>();
    public List<String> Code = new List<String>();
    public List<String> Description = new List<String>();

    public List<String> getType() {
        for (HealthCloudGA__EhrEncounter__c encounter : EHRRecords) {
             if (!Description.contains(encounter.HealthCloudGA__HospitalizeDischargeDiagnosis__c) && encounter.HealthCloudGA__HospitalizeDischargeDiagnosis__c != null) {
                RType.add('EHR Encounter');
                Name.add(encounter.Name);
                Cdate.add(encounter.CreatedDate.format('MM/dd/yyyy'));
                Code.add('');
                Description.add(encounter.HealthCloudGA__HospitalizeDischargeDiagnosis__c);
            }
        }    
        
        return RType;
    }

    public List<String> getName() {
        return Name;
    }
    
    public List<String> getCDate() {
        return CDate;
    }
    
    public List<String> getCode() {
        return Code;
    }
    
    public List<String> getDescription() {
        return Description;
    }
This controller was created to add field values to a list if they are not on the list already and pass that list to an html table on a Visualforce page (Adding to every list in the first function is a bit funky but it saves from looping through each record in each function). My test class currently passes everything except for the if statement and its contents.

Here is my current test class:
@isTest
private class SuspectListTestClass {
    @testSetup static void testSetup() {
        Account testaccount = new Account();
        testaccount.name = 'Zander Test';
        testaccount.Primary_Insurance__c = 'Test Insurance Company';
        testaccount.Gender__c = 'Male';
        testaccount.County__c = 'Maricopa';
        testaccount.RecordTypeId = '012360000004FEPAA2';
        insert testaccount;
    }

    @isTest static void testEHREncounterPass() {
        Account act = [SELECT Id FROM Account WHERE Name = 'Zander Test' LIMIT 1];
        HealthCloudGA__EhrEncounter__c testencounter1 = new HealthCloudGA__EhrEncounter__c();
        testencounter1.HealthCloudGA__Account__c = act.Id;
        testencounter1.HealthCloudGA__HospitalizeDischargeDiagnosis__c = 'Test';
        insert testencounter1;
        PageReference testpagereference = Page.SuspectList;
        test.setCurrentPage(testpagereference);
        SuspectListController testcontroller = new SuspectListController(new ApexPages.StandardController(act));
        testcontroller.Description.add('');
        String[] record = testcontroller.getType();
        System.assertEquals('EHR Encounter',record[0]);
    }
    
    @isTest static void testEHREncounterFail() {
        Account act = [SELECT Id FROM Account WHERE Name = 'Zander Test' LIMIT 1];
        HealthCloudGA__EhrEncounter__c testencounter2 = new HealthCloudGA__EhrEncounter__c();
        testencounter2.HealthCloudGA__Account__c = act.Id;
        testencounter2.HealthCloudGA__HospitalizeDischargeDiagnosis__c = 'Test';
        insert testencounter2;
        PageReference testpagereference = Page.SuspectList;
        test.setCurrentPage(testpagereference);
        SuspectListController testcontroller = new SuspectListController(new ApexPages.StandardController(act));
        testcontroller.Description.add('Test');
        testcontroller.getType();
    }

    @isTest static void testSuspectListController() {
        Account act = [SELECT Id FROM Account WHERE Name = 'Zander Test' LIMIT 1];
        PageReference testpagereference = Page.SuspectList;
        test.setCurrentPage(testpagereference);
        SuspectListController testcontroller = new SuspectListController(new ApexPages.StandardController(act));
        testcontroller.getName();
        testcontroller.getCDate();
        testcontroller.getCode();
        testcontroller.getDescription();
    }
}
From what I understand you need to have one test where it is meant to pass and one where it is meant to fail. I have made 2 test methods but no matter what I do I can not seem to get one to pass. I get an error from the assertEquals() saying that the index is out of range meaning it did not add "EHR Encounter" to the RType list.

Am I missing something here??
I feel like I have inserted a record that should pass but I guess not.
Please help!

Thanks in advance!

 
Dear Community, would you please help me with creating a trigger for scheduling email reminders for overdue invoices with the the associated invoices being generated? Will appreciate any support. Thanks in advance. 
I have a LWC table which groups records by Custom Field 1. I created a wrapper class that handles the values to be displayed on the table. So far, values up to Custom Field 4 are aligned properly.

Problem starts on Custom Field 5 onwards as values are displayed on the next row.

Here is the expected output:
User-added image

Meanwhile, below is the actual result I've been getting:

User-added image

Below is the current code I am working on:
<template>  
    <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered">
        <thead>
            <tr class="slds-line-height_reset">
                <th scope="col" rowspan="2">
                    <div class="slds-truncate" title="customField1">Custom Field 1</div>
                </th>
                <th scope="col" rowspan="2">
                    <div class="slds-truncate" title="customField2">Custom Field 2</div>
                </th>
                <th scope="col" rowspan="2">
                    <div class="slds-truncate" title="customField3">Custom Field 3</div>
                </th>
                <th scope="col" rowspan="2">
                    <div class="slds-truncate" title="customField4">Custom Field 4</div>
                </th> 
                <th scope="col" colspan="4">
                    <center><div class="slds-truncate" title="someText">NOT A FIELD, JUST SOME TEXT</div></center>
                </th>    
            </tr>
            <tr>  
                <th><div>Custom Field 5</div></th>
                <th><div>Custom Field 6</div></th>
                <th><div>Custom Field 7</div></th>
                <th><div>Custom Field 8</div></th>
            </tr>

        </thead>
        <tbody>
            <template if:true={mapData}>
                <template for:each={mapData} for:item="keyValue">
                    <tr key={keyValue.key} class="slds-hint-parent">
                        <th scope="col">
                            <div>{keyValue.key}</div>
                        </th>
                        <th scope="col">
                            <template for:each={keyValue.value} for:item="mapValue">
                                <div key={mapValue.customField2}>
                                    {mapValue.customField2}
                                </div> 
                            </template>
                        </th>
                        <th scope="col">
                            <template for:each={keyValue.value} for:item="mapValue2">
                                <div key={mapValue2.customField3}>
                                    {mapValue2.customField3}
                                </div> 
                            </template>
                        </th>
                        <th scope="col">
                            <template for:each={keyValue.value} for:item="mapValue3">
                                <div key={mapValue3.customField4}>
                                    {mapValue3.customField4}
                                </div> 
                            </template>
                        </th>
                    </tr>
                    <tr key={keyValue.key} class="slds-hint-parent"> 
                        <th scope="col"></th>
                        <th scope="col"></th>
                        <th scope="col"></th>
                        <th scope="col"></th>
                        <th scope="col">
                            <template for:each={keyValue.value} for:item="mapValue4">
                                <div key={mapValue4.customField5}>
                                    {mapValue4.customField5}
                                </div> 
                            </template>
                        </th>
                        <th scope="col">
                            <template for:each={keyValue.value} for:item="mapValue5">
                                <div key={mapValue5.customField6}>
                                    {mapValue5.customField6}
                                </div> 
                            </template>
                        </th>
                        <th scope="col">
                            <template for:each={keyValue.value} for:item="mapValue6">
                                <div key={mapValue6.customField7}>
                                    {mapValue6.customField7}
                                </div> 
                            </template>
                        </th>
                        <th scope="col">
                            <template for:each={keyValue.value} for:item="mapValue7">
                                <div key={mapValue7.customField8}>
                                    {mapValue7.customField8}
                                </div> 
                            </template>
                        </th>
                    </tr> 
                </template>
            </template> 
        </tbody>
    </table>
</template>

 
Hi all,
I have a list of products with associated schedules where each schedule has different Revenue and ScheduleDate values. I'm trying to get the get the aggregate of Revenue by DATE across the OpportunityLineItems. However, i'm not sure how to achieve this as i couldn't find any date functions specific to date while DAY_ONLY() will only work for datetime fields. Please share your thoughts & recommendations.
Thanks!
Hi, I'm trying to add multiple accounts to one contact. Currently, I am unable to and this causes me to have to make multiple Contacts for the same person. The few things I've tried:

1. Adding a Custom Field & Relationship for Accounts. A Related List field shows up, but only allows me to add New Accounts, not Existing.

2. Enabled "Allow users to relate a contact to multiple accounts" under Account Settings. This creates a field under "Contact Detail" that allows me to add an Existing Acccount. However, when I open that Account, the Contact does not show up in the Related List section.

3. Spoke with a Salesforce Customer Service Rep and they said I may need Developer Assistance to achieve this, because it is a "one-to-many" (or something like that) relationship.

I'm new to Salesforce so any assistance would be greatly appreciated. I'd be happy to share screenshots or further explanation on any of the points above. Thank you!