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

  • Chatter
    Feed
  • 116
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 1059
    Replies
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);
    }
}
 
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?
I have been asked to make a custom weighting option for one of the smaller businesses in our org. 

If the sales manager picks one of the following picklist options during his opportunity creation, the formula should calculate as appropriate:

Custom Opp Weighting Picklist
Existing client, existing product =  divide opportunity amount by 2
Existing client, new product = divide opportunity amount by 3
New client, existing product = divide opportunity amount by 5
New client, new product = divide opportunity amount by 10

Is there an esy way I can I achive this via a picklist? 

Would really appreciate any help!
 
We need to simulate running monthly scheduled batch apex jobs over multilple months/year to see mutiple records instances being recaluculed over time.

I can see that there are some comments from 2011 saying that this is not possible but just wanted to check in 2019? I am guessing not but just thought to ask.
Hello.
I can get user and public groups from public groups this SOQL,
but public groups add role, can not get add role.
How to get role from public groups?
[SELECT Id, DeveloperName, (SELECT UserOrGroupId FROM GroupMembers)
FROM Group WHERE DeveloperName IN :xxxxxx]
Have a picklist with 10 values, when it is picklist option 2 or 3, i want to check to see if a number field is not null.

NOT ( OR ( ISPICKVAL ( FieldName__c , "Option 2" ), ( ISPICKVAL ( FieldName__c , "Option 3" ) ) ) && NOT ( ISNULL ( NumberField__c ) = true ) )

It validates, but no matter what option 2 or 3 I pick, i can also put numbers in the number field and nothing seems to be stopping me from doing anything....
Hello Team,

While doing the trailhead for Quick Start - Apex Coding for Admins - Create a Trigger, while I am creating the candidate Nina Simone, and update the ZIP Code field as "20008", system gives me an error message stating as - Candidate Zip Code does not exist in specified State.

Kindly advise where I am going incorrect.

Thanks
Vinay Kumar Salve
Hi,

When a Campaign Member is removed from a campaign, it updates the IsDeleted flag, but does anyone know if this also updates the Last Modified date on the Campaign Member?

Thanks,

Kam
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
Helo,

I am trying to log the exceptions in an custom object ,but after throwing an exception entire transaction is rolled back and i am not able to see in the custom objecy any help would be if great help  for example 

List<IBA_Store_Log__c> ibaLogs = New List<IBA_Store_Log__c>(); 
try {
    integer x = 1/0;
} catch (exception e) {
     IBA_Store_Log__c priceLog = IBA_store_datatableHelper.createIbaLog('ERROR', e.getmessage() + e.getlinenumber(), 'Iba_Store_Sap_Simulation', '');
     ibalogs.add(priceLog);    
    throw e;
}finally {
    IBA_store_datatableHelper.createIbaStoreLog(ibalogs);
}
 
We are attempting to move a simple Apex Class and Apex Test Class from Sandbox to Production, and blocked by Code Coverage Failure error. Our Code Coverage is showing 100% in Production (via Developer Console), yet we are seeing a Code Coverage Failure Error (coverage = 33%) even on "Validate" (not "Deploy") of non-apex change set. We have followed instructions in Knowledge Article 000335222 (https://help.salesforce.com/articleView?id=000335222&type=1&mode=1) carefully to reset Code Coverage numbers and are still seeing the above error on validation of non-apex change set as well as on attempt to deploy an apex-loaded change set including test class. Apex Class and Apex Test Class code below for reference, any help greatly appreciated!
 
Public class AutoConvertLeads
{
    @InvocableMethod
    public static void LeadAssign(List<Lead> LeadIds)
    {
        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
        List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
        for(Lead currentlead: LeadIds){
                Account[] matchedaccount = [SELECT Id, Name FROM Account WHERE Name=:currentlead.Company LIMIT 1];
                if(matchedaccount.size() > 0) {
                Database.LeadConvert Leadconvert = new Database.LeadConvert();
                Leadconvert.setLeadId(currentlead.id);                
                Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                Leadconvert.setDoNotCreateOpportunity(TRUE); //Remove this line if you want to create an opportunity from Lead Conversion
                Leadconvert.setAccountId(matchedaccount[0].id);
                MassLeadconvert.add(Leadconvert);
                }
        }
        
        if (!MassLeadconvert.isEmpty()) {
            List<Database.LeadConvertResult> lcr = Database.convertLead(MassLeadconvert);
        }
    }
}

And Test Class:
@isTest 
      public class TestAutoConvertLeads{
      static void createnewlead(){
      User userToCreate = [SELECT id FROM user WHERE profile.name='System Administrator' Limit 1];
      
      Test.startTest();    
      Lead leadToCreate =new Lead();
      List<Lead> LeadIds= New List<Lead>();
      leadToCreate.ownerid= userToCreate.id;
      leadToCreate.LastName ='Gupta';
      leadToCreate.Company='Salesforce';
      insert leadToCreate; 
      LeadIds.add(leadToCreate);
      
      LeadStatus CLeadStatus = new LeadStatus();
      
      Account AccountToCreate = new Account();
      AccountToCreate.ownerid= userToCreate.id;
      AccountToCreate.Name = 'Salesforce';
      insert AccountToCreate; 
      
      AutoConvertLeads.LeadAssign(LeadIds);
      
      Test.stopTest();
   }
}

 
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;
}
 
Looking for help on this error - I'm sure a small syntax issue in my code.  Thank you!
 
<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable,flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="ChangeCaseLabel">
    <aura:handler name="init" value="this" action="{!c.doInit}"/>
    <aura:handler event="force:refreshView" action="{!c.doInit}" />  
    <lightning:workspaceAPI aura:id="workspace" />
</aura:component>
 
({
   init : function(component, event, helper) {
        var action = component.get("c.getCaseOrigin");
        action.setParams({ caseId: component.get("v.recordId")});
        action.setCallback(this,$A.getCallback(function(response1)
         {
         var state = response1.getState();             
         if (state === "SUCCESS")  
         {
             var result= response1.getReturnValue();
         var workspaceAPI = component.find("workspace");
         workspaceAPI.getFocusedTabInfo().then(function(response) {
            var focusedTabId = response.tabId;
            workspaceAPI.setTabLabel({
                tabId: focusedTabId,
                label: result
            });
        })
        .catch(function(error) {
            console.log(error);
        });
         }
         }
        ));
        $A.enqueueAction(action);       
        
        
    }
})
 
({
	doInit : function(component, event, helper) {
		helper.init(component, event, helper);
	}
})
 
public with sharing class ChangeCaseLabel {
    public static ChangeCaseLabelService service = new ChangeCaseLabelService();
    @AuraEnabled 
    public static String getCaseOrigin(String caseId){
        return service.getCaseOrigin(caseId);
    }
    
    
}
 
public class ChangeCaseLabelService {
    
    public String getCaseOrigin(String caseId){
        Case c = [Select id ,CaseNumber , Origin from Case where Id = :caseId];
        return c.Origin+'-'+c.CaseNumber ; 
    }
}

 
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