• Saravana Bharathi 1
  • NEWBIE
  • 75 Points
  • Member since 2017

  • Chatter
    Feed
  • 2
    Best Answers
  • 2
    Likes Received
  • 1
    Likes Given
  • 2
    Questions
  • 31
    Replies
Hi,

I have to write a trigger to calculate next meeting date from today. I have an object which stores input of Frequency(monthly, two month, quaterly), Day(Mon-Fri),Week (Week1 -Week 5). Based on these input how should I calculate the next meeting date from today.

example: If Frequency is "Monthly", Day is "Wednesday" and Week is "Week 3".
then I have to calculate date of next meeting which should be Wednesday of 3rd week of next month.

Please help.
Thanks!
 
  • April 13, 2017
  • Like
  • 0
I have an apex batch class that I was able to get workig in my sandbox enviorment and that is ready for deployment into my production enviroment. 

However when I went to write the test class for this I ran into some trouble, with an error message that says line 50 = Test Class Error: Argument must be an object that implements Database.Batchable.

Can you guys help me get over this hurdle or tell me if i need a new test class code in order to be able to deploy to production? Below are my batch class and my test class thanks. 

Batch Class
global class UpdateContactsVoter implements Database.Batchable<sObject>{
    global Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'Select ID,FirstName,LastName,MailingPostalCode from contact where contact.voter_file_id__c = null';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext info, List<contact> scope){
        Set<String> set_Str = new Set<string>();
                                Map<String,Voter_File_TX__c> mp_VoterFile;

        for(Voter_File_TX__c VoterFile : [Select ID,First_Name__c, Last_Name__c,Zipcode__c, Contact__c From Voter_File_TX__c] ){
                                                if(mp_VoterFile==null){
                                                                mp_VoterFile = new Map<String,Voter_File_TX__c>();
                                                }
                                                mp_VoterFile.put(VoterFile.First_Name__c +''+VoterFile.Last_Name__c +''+VoterFile.Zipcode__c,VoterFile);
                                }
                                for(Contact ContactList : scope){
                                                if(mp_VoterFile!=null && mp_VoterFile.containsKey(ContactList.FirstName+''+ ContactList.LastName+''+ ContactList.MailingPostalCode))
            
            {
                                                                mp_VoterFile.get(ContactList.FirstName +''+ ContactList.LastName +''+ ContactList.MailingPostalCode).Contact__c = ContactList.id;
                                                }
                                }
                                if(mp_VoterFile!=null && mp_VoterFile.values()!=null){
                                                update mp_VoterFile.values();
                                }
    }
    
    global void finish(Database.BatchableContext info){
        
    }
}


Test Class
 line 50 = Test Class Error: Argument must be an object that implements Database.Batchable.

@isTest 
public class TestClassUpdateContacts 
{
    static testMethod void testMethod1() 
    {
        List<Contact> lstContact= new List<Contact>();
        List<Voter_File_TX__c> lstVoterfile = new List<Voter_File_TX__c>();
        if(contact.voter_file_id__c == null && voter_file_tx__c.contact__c == null)
        {
        Contact cont = new Contact();
        cont.FirstName ='Test';
        cont.LastName = 'Test';
        cont.id = 'Test';
        cont.MailingPostalCode = 'test';
            
        insert cont;
            
        Voter_File_TX__c vf = new Voter_File_TX__c();
        vf.First_Name__c ='Test';
        vf.Last_Name__c ='Test';
        vf.RNC_ID__c = 'Test';
        vf.Zipcode__c = 'Test'; 
                                vf.First_Name__c = cont.FirstName ;
        vf.Last_Name__c = cont.LastName ;
        vf.Zipcode__c = cont.MailingPostalCode ;
        vf.Contact__c = cont.Id ;
        
        insert vf;
       
        cont.FirstName = vf.First_Name__c ;
        cont.LastName = vf.Last_Name__c ;
        cont.MailingPostalCode = vf.Zipcode__c;
        cont.RNC_ID__c = vf.RNC_ID__c ;
            
                                update cont;
        }
        else {
         contact cont1 = new Contact(); 
         Voter_File_TX__c vf1 = new Voter_File_TX__c();
         cont1.Voter_File_ID__c = null;
         vf1.Contact__c = null; 
          
        }
        insert lstContact;
        update lstContact;
        
        Test.startTest();

            TestClassUpdateContacts obj = new TestClassUpdateContacts();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }
}
 


 

I want to access iframe content window in lwc. I am getting Secure Element in console. But I am not able to access it. Is there a way to access iframe content window or document once its loaded. What is the Secure Window, Secure Element, Secure Document in Locker API, how can we access those property .

Below are my code:

LwC - HTML file
<template>
<iframe src='https://domain.salesforce.com/home.jsp'/>
</template>

.js file

renderedcallback(){
const iframe = this.template.querySelector('iframe);
iframe.style.background='red';//This is working.
console.log(iframe.contentDocument or iframe.contentWindow) //I am not getting anything in console, but if i use breakpoint, it gives SecureElement in debugger. I could see all the document and DOM Element.

How do i access those element?

Thanks in Advance.

Regards,
Saravana
Hi All,

I am a newbie to Lightning component Development.

I have written a lightning component, which holds Text Input, and a button.
When User enters some text in the text field, by clicking a button. I am calling a javascript controller, then to Javascript Handler, then to Apex Controller. I am searching and returning the result to handler, to javascript handler and then to component attribute values.

I am setting Response to Component attribute in Handler.

I am not getting the response in UI. When I debugged using Lightning Inspector - Chrome Extensions, Actions are successful, and I am getting result in the attributes.

Please let me know, whether i am missing anything.

Thanks in advance.
Hi All,

I am a newbie to Lightning component Development.

I have written a lightning component, which holds Text Input, and a button.
When User enters some text in the text field, by clicking a button. I am calling a javascript controller, then to Javascript Handler, then to Apex Controller. I am searching and returning the result to handler, to javascript handler and then to component attribute values.

I am setting Response to Component attribute in Handler.

I am not getting the response in UI. When I debugged using Lightning Inspector - Chrome Extensions, Actions are successful, and I am getting result in the attributes.

Please let me know, whether i am missing anything.

Thanks in advance.
I have search box in header
when i search something i get search results in another page
but when i redirect to another page i want to show searchtext in searchbox which i didnt get
window.location.href = base_url + '/community/s/search-results?searchterm=' + searchquery + '&searchcontext=' + objType + '&globalsearch=true&aid=' + this.portalConfig.selectedAccount;
using this to redirect
 
Hii Team,

As I have written one apex method for sum rollup functionality which is working fine when i call from anonymous window.
                                                 Apex
@AuraEnabled
    public static object sumRollup(String recordObject,String recordField) {
        System.debug(recordObject);
        Object recordSum;             
        //String sum = [select sum(annualrevenue) from account];
        String sum = 'select' +' '+ 'SUM'+ '('+recordField+')'  + ' from ' + recordObject;  
        AggregateResult[] groupedResults = database.query(sum);
        for (AggregateResult ar : groupedResults)  {
            recordSum=ar.get('expr0');         
            System.debug('Sum amount -- ' + recordSum);
        }
        return recordSum;
    } 
But 
when i select field from picklist dynamically it is not pritting result only run till console.log("2 sum") You can see this console below.
                                              Here is my JS
sumRecordType() {
    console.log("2 sum");
    sumRollup({
      recordObject: this.selectedObjectValue,
      recordField: this.selectedFieldValue,
    })
      .then((result) => {
        console.log("Hello Sum" + result);
        this.recordCountTypeValue = result;
      })
      .catch((error) => {
        this.error = error;
      });
  }
How to resolve it Please help This is LWC question
I am implementing a custom lookup field in my LWC form. So far, the record is selected properly. I verify it via console.log statement so that I can know if it is really returning any value.

I also wanted to see the CustomTextField__c value of the selected account record, but every time I check the logs, it returns undefined value. I already assigned a variable that will hold its value, but same result occurs.

Meanwhile, below are the codes I have:

customLookup html file
<template>
    <lightning-record-edit-form object-api-name={childObjectApiName}>
        <label for="fieldid">{fieldLabel}</label>
        <lightning-input-field id="fieldid" required={required} variant="label-hidden" field-name={targetFieldApiName}
            value={value} onchange={handleChange} disabled={disabled}>
        </lightning-input-field>
    </lightning-record-edit-form>
</template>
customLookup js file
import { LightningElement, api } from 'lwc';

export default class CustomLookup extends LightningElement {
    @api childObjectApiName = 'Case'; 
    @api targetFieldApiName = 'AccountId'; 
    

    @api fieldLabel = 'Your field label here';
 
    @api disabled = false;
    @api value;

    @api required = false;

    handleChange(event) {
        const selectedEvent = new CustomEvent('valueselected', {
            detail: event.detail.value[0]
        });
    
        this.dispatchEvent(selectedEvent);
    }

    @api isValid() {
        if (this.required) {
            this.template.querySelector('lightning-input-field').reportValidity();
        }
    }
}
portion from custom form referencing custom lookup lwc html file
<div class="slds-col slds-size_1-of-2">
   <div class="slds-var-m-right_small slds-var-m-bottom_medium">
      <c-custom-lookup field-label="Account" 
            child-object-api-name='Case'
            target-field-api-name='AccountId'
            onvalueselected={handleAccountChange}>
      </c-custom-lookup>
   </div>
</div>
portion from custom form js file
@track selectedAccountId; 
@track selectedAccountCustomTextField;

handleAccountChange(event) {
    //this portion works, display expected id of selected record
    this.caseRec.AccountId = event.detail;
    this.selectedAccountId = event.detail;
    console.log('this.selectedAccountId' + this.selectedAccountId);


    //this portion returns undefined    
    this.selectedAccountCustomTextField__c = this.caseRec.Account.CustomTextField__c; 
    console.log('this.selectedAccountCustomTextField' + this.selectedAccountCustomTextField);
}



 
Hi,

I'm facing one issue while inserting a record.

I have once Multi-select picklist,
if select anyone i need to create one more record with the same name

the first time it is inserting fine,
but if try next time getting an error
Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Special Initiative: id value of incorrect type: a4D6C000000DMXJUA4

please help me,

List<Contact> mrl = new List<Contact>();

for(Integer i=0; i<wrapperList.size(); i++){
            System.debug('mkList===========>>>>>>'+mkList);
            Contact mr = new Contact();
            mr.name = wrapperList[i];
            mr.Account = wrapperList[i];
            mr.Opportunity__c = recordId;
            mrl.add(mr);
        }
        if(!mrl.isEmpty()){
            Insert mrl;
        }

I'm inserting name with accountId only

Thanks,
Dhilip
I want to run a schedule apex after every 2 years is it possible to do so and if yes how to do it.
Thanks in advance.
Hey everyone. I'm very new to Lightning components, so I'm hoping this will be a relatively easy answer for the experts on here.  I have a very simple Lightning Web Component embedded inside a parent Aura Component. What I would like to do is be able to have my parent Aura Controller retrieve the property value from my child LWC, but I can't figure out how. 

For example, here is my simple LWC HTML file that returns Hello World.
samplelwc.html
<template>
    <lightning-card  title="Sample LWC">
        <p class="slds-p-horizontal_small">My LWC variable is: {lwcVariable}</p>
    </lightning-card>
</template>
samplelwc.js
import { LightningElement, api } from 'lwc';

export default class Samplelwc extends LightningElement {
    @api lwcVariable = 'Hello World';
}

In my Aura Component, I would like to retrieve lwcVariable from my LWC controller, but I can't figure out how to do this.

Here is the Aura Compoent I have:
sampleac.cmp
<aura:component implements="flexipage:availableForAllPageTypes" access="global">
    <c:samplelwc aura:id="mylwc"/>
    <aura:attribute name="lwcVariable" type="String"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <lightning:card title="Sample Aura Component">
        <p class="slds-p-horizontal_small">The variable from my aura controller is: {!v.lwcVariable}</p>
    </lightning:card> 
</aura:component>
What I would like to do is have {!v.lwcVariable} pulled from my LWC, but I can't figure it out. Right now I'm hardcoding it with Hello World! as shown in my Aura Controller. I'm not sure how to have the component.set method pull the value from my lwcVariable property in my LWC Controller.
sampleacController.js
({
    doInit : function(component, event, helper) {
        component.set("v.lwcVariable", "Hello World!");
    }
})
If any help is greatly appreciated. Thanks!

 
 
To get values of both CreatedById and CreatedDate, I used getFieldDisplayValue in my javascript file. After getting both values, I concatenate both values and displayed it in html. But when I check the value, only the CreatedDate displays the expected output, while CreatedById returns a null value. I would like to ask for your help regarding this issue.

transactionsLWC.html
<template>
    <div class="slds-theme_default">  
        <lightning-record-edit-form object-api-name="Transaction__c" record-id={recordId} layout-type="Full" mode="view">
            <lightning-messages></lightning-messages>
            <div class="slds-var-m-around_medium">
                <div class="slds-grid slds-wrap"> 
                    <div if:true={fscalctool.data}>   
                        <div class="slds-col slds-size_1-of-2">  
                            <label class = "slds-var-m-right_small slds-var-m-bottom_medium">Transaction Detail</label>      
                            <p>{createdByAndDateTime}</p>
                        </div>
                    </div> 
                </div>   
            </div>  
        </lightning-record-edit-form>
    </div>
</template>
transactionsLWC.js
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldDisplayValue } from 'lightning/uiRecordApi';
import CREATEDBYID_FIELD from '@salesforce/schema/Transaction__c.CreatedById';
import CREATEDDATE_FIELD from '@salesforce/schema/Transaction__c.CreatedDate';

const fields = [CREATEDBYID_FIELD, CREATEDDATE_FIELD];

export default class TransactionsLWC extends LightningElement {
    @api recordId;
    @api objectname;

    @wire(getRecord, { recordId: '$recordId', fields })
    transaction;

    get createdById() {
        return getFieldDisplayValue(this.transaction.data, CREATEDBYID_FIELD);
    }

    get createdDate() {
        return getFieldDisplayValue(this.transaction.data, CREATEDDATE_FIELD);
    }

    get createdByAndDateTime() {
        return `${this.createdById},${this.createdDate}`;
    }
}
My expected value does not match the actual value.

Following is an example:

Expected: retailuser,10/19/2020,5:39 AM

Actual: null,10/19/2020,5:39 AM

 
There is a field on the Account record called "Ultimate Parent ID" .(which is a formula field to calculate the Parent Account ID for that Account).
This field is a 15 character text formula field.
I am trying to write an after trigger to update a field "ultimate Parent ID 18".
The functionality of this trigger is to convert the above 15 digit ID to an 18 digit salesforce ID and store it in a field on the Account record.
Apex:
public without sharing class AccTriggerHandlerUpdUltParentId extends TriggerHandlerBase {

    public virtual override void mainEntry(TriggerParameters tp) {

        UpdUltParentID(tp);
    }

    public virtual override void inProgressEntry(TriggerParameters tp) {

        UpdUltParentID(tp);
    }


    void UpdUltParentID(TriggerParameters tp) {

        List < Account > lstToUpdate = new List < Account > ();
        List < Account > ListAcc = (List < Account > ) tp.newList;
        Map < Id, Account > newMapAcc = (Map < Id, Account > ) tp.newMap;
        Map < Id, Account > oldMapAcc = (Map < Id, Account > ) tp.oldMap;
        Set < Id > setAccountIds = new Set < Id > ();
        string idStr;
        id idval;
         for(Account acc : ListAcc){
            setAccountIds.add(acc.Id);
         }

        if (tp.tEvent == 'afterUpdate') {
            for (Account acctNew: ListAcc) {
                    acctNew.Ultimate_Parent_ID_18__c = acctNew.Ultimate_Parent_Id__c;
                    idval = acctNew.Ultimate_Parent_ID_18__c;
                    acctNew.Ultimate_Parent_ID_18__c = idval;
                    lstToUpdate.add(acctNew);
               // }

            }
        }

    }
}
 I am receiving the following error:

Question: Should this trigger be in an Afterupdate or before Update?
I tried in the context of After but there was an error saying "record is read only".
Thank you for the help!
 
<template>
<div class="slds-col"> 
            
            <label class="slds-form-element__label slds-no-flex">Posting Date</label>
            <lightning-input type="date" 
                        name="Postingdate" 
                        value={PostingDate}
                        onchange={PostingDateChange}
            >
            </lightning-input>  
         
        </div>     
</template>

CR.html 
import { LightningElement,api ,track} from 'lwc';

import getInvoiceData from '@salesforce/apex/CustomerRefundLwcController.getInvoiceData';
import getBankAccounts from '@salesforce/apex/CustomerRefundLwcController.getBankAccounts';
import processCustomerRefund from '@salesforce/apex/CustomerRefundLwcController.processCustomerRefund';

export default class CustomerRefund extends LightningElement {
    @api recordId; /*Sales Credit Id*/
    @track invoiceData;
    @track invoiceLinesData;
    @api headerText;
    @api recordProcessing;
    @api bankAccounts = new Array();
    @track selectedBankId;
    @track allocateToSalesCredit;
    @track referenceDetail;
    @track bShowModal = false;
    @track PostingDate;
    /*Toast Event Variables*/
    @api isError = false;
    @api iswarning = false;
    @api issuccess = false;
    @api ToastMessage;


 PostingDateChange(event)
    {
        this.PostingDate = event.target.value;
        this.invoiceData.PostingDate = this.PostingDate;
    }

processRefundHandler() {
        this.recordProcessing = true;
        //console.log('this.formData----'+JSON.stringify(this.invoiceLinesData));
        console.log('this.formData----'+JSON.stringify(this.invoiceData));
        processCustomerRefund({ lstInvoiceLines : this.invoiceLinesData, bankId : this.selectedBankId, allocateToSalesCredit : this.allocateToSalesCredit, reference : this.referenceDetail, postingdate : this.PostingDate })
        .then(result => {
            var responseMessage = result;
            this.recordProcessing = false;
            
            this.ToastMessage = responseMessage;
            if(responseMessage == "Success"){
                //this.issuccess = true;
                this.isError = false;
                this.ToastMessage = "Your Bank Customer Refund has been created";
                this.bShowModal = true;
            }else{
                this.isError = true;
            }
        })
        .catch(error => {
            this.isError = true;
            this.ToastMessage = error ;
            console.log(error);
        });
    }

CR.js
public with sharing class CustomerRefundLwcController {
    public CustomerRefundLwcController() {

    }
 @AuraEnabled
    public static string processCustomerRefund(List<ScLineWrapper> lstInvoiceLines,string bankId,boolean allocateToSalesCredit,string reference){
        system.debug('start update');
        string successMessage = 'Success';
        string responseMessage = 'Success';
        Savepoint spTran = database.setSavePoint();
        try{
            List<Sales_Invoice_Line_Item__c> lstLinesToUpdate = new List<Sales_Invoice_Line_Item__c>();
            decimal amount=0;
            Id taxRate;
            Id salesinvoiceid;

            boolean isValid = true;
            boolean allocateToInvoice = allocateToSalesCredit;
            map<id,Sales_Invoice_Line_Item__c> mapOfSelectedLines = new map<id,Sales_Invoice_Line_Item__c>();

            for(ScLineWrapper lineWrapper : lstInvoiceLines){
                system.debug('isselect>> ' + lineWrapper.isSelected);
                if(lineWrapper.isSelected){
                    salesinvoiceid = lineWrapper.InvoiceLine.Sales_Invoice__c;
                    decimal lineAmount = lineWrapper.InvoiceLine.Foreign_Gross__c;
                    if(lineAmount != null && lineAmount > 0){
                        amount += lineAmount;
                        mapOfSelectedLines.put(lineWrapper.InvoiceLine.id,lineWrapper.InvoiceLine);
                    }

                    if(lineWrapper.InvoiceLine.Tax_Rate__c != null){
                        taxRate = lineWrapper.InvoiceLine.Tax_Rate__c;
                    }
                }
            }

            if(salesinvoiceid == null){
                isValid = false;
                responseMessage = 'Please select at least one sales invoice line';
            }else if(bankId == null){
                isValid = false;
                responseMessage = 'Please select bank account';
            }else if(amount <= 0){
                isValid = false;
                responseMessage = 'Refund amount should be greater than zero';
            }

            system.debug('updatelst>> ' + lstLinesToUpdate);
            //update lstLinesToUpdate;
            if(isValid){
                Sales_Invoice__c siInfo = [select id,Status__c,Account__c,Name from Sales_Invoice__c where id=: salesinvoiceid];
                BankCustomerRefundService objCustomerRefundService = new BankCustomerRefundService();
                BankCustomerRefundService.BankCustomerRefundWrapper objRefundWrapper = new BankCustomerRefundService.BankCustomerRefundWrapper();
                Id accountId = siInfo.Account__c;
                objRefundWrapper.AccountId = accountId;
                objRefundWrapper.PostingDate = Date.Today()+(-216);
                objRefundWrapper.BankAccountId = bankId;
                objRefundWrapper.TaxRate = taxRate;
                objRefundWrapper.Amount = amount;
                objRefundWrapper.Reference = reference;
                BankCustomerRefundService.Response objResponse = objCustomerRefundService.CreateBankCustomerRefund(objRefundWrapper);
                responseMessage = objResponse.ResponseMessage;
    
                if(allocateToInvoice && responseMessage == successMessage){
                    Bank_Payment__c objBankPayment = objResponse.BankPayments.get(accountId);
                    List<Ledger__c> listofLedgers = [Select id,name,Foreign_Gross_Total__c,Type__c
                                                    FROM Ledger__c
                                                    Where Customer_Supplier_Account_Name__c =: accountId AND Show_On_Transaction__c=1
                                                    AND Paid__c = 'N' AND Is_Deleted__c = false
                                                    AND (Sales_Invoice_Line_Item__c IN: mapOfSelectedLines.keyset() OR Bank_Payment__c =: objBankPayment.id) ];
                    
                    if(!listofLedgers.isEmpty()){
                        BankAllocateCreditsAndPaymentsService objAllocateCreditsAndPaymentService = new BankAllocateCreditsAndPaymentsService();
                        BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsWrapper objAllocateCreditWrapper = new BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsWrapper();
                        objAllocateCreditWrapper.AccountId = accountId;
                        objAllocateCreditWrapper.PostingDate = Date.Today()+(-216);
                        List<BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper> BankAllocateCreditsAndPaymentsLines = new List<BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper>();
                        for(Ledger__c ledger : listofLedgers){
                            BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper objPaymentLine = new BankAllocateCreditsAndPaymentsService.BankAllocateCreditsAndPaymentsLineWrapper();
                            objPaymentLine.LedgerName = ledger.Name;
                            objPaymentLine.Amount = ledger.Foreign_Gross_Total__c;
                            BankAllocateCreditsAndPaymentsLines.add(objPaymentLine);
                        }

                        objAllocateCreditWrapper.BankAllocateLines = BankAllocateCreditsAndPaymentsLines;
                        BankAllocateCreditsAndPaymentsService.Response objAllocateResponse = objAllocateCreditsAndPaymentService.BankAllocateCustomerBalance(objAllocateCreditWrapper);
                        responseMessage = objAllocateResponse.ResponseMessage;
                        system.debug('Response>>' + objAllocateResponse.ResponseMessage);
                    }                                                    
                }
                
            }
        }catch(Exception ex){
            responseMessage = ex.getStackTraceString();
        }
        
        if(responseMessage != successMessage){
            Database.rollback(spTran);
        }
        system.debug('Response>>' + responseMessage);
        return responseMessage;
        
    }

CRLWCController.cls

I want to use LWC datepicker input to pass date value in CRLWC.cls in PostingDate variable. 

Can anyone help please

Hi All:

I am trying to implement Bitly with a custom field in Opportunity. I am successful in getting the Bitly Url for the Opportunity field. However I am having trouble in getting test cases set up for the same. I followed the following article:

https://douglascayers.com/2015/10/21/salesforce-create-short-urls-with-bitly-process-builder-and-apex/
https://gist.github.com/DouglasCAyers/de978590b97e235a96fc

However my test method fails in static void test_shorten() in BitlyShortenURLInvocableTest, where it throws the following error:

System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out
Class.BitlyService.getAccessToken: line 56, column 1
Class.BitlyService.: line 12, column 1
Class.BitlyShortenURLInvocable.shortenAsync: line 25, column 1


I have got a process builder that calls the method shorten of BitlyShortenURLInvocable, on creation/update of Opportunity. My code in test_shorten is given below.
 

    Test.startTest();
    Test.setMock( HttpCalloutMock.class, new MockHttpResponse() );
    
    Opportunity job = new Opportunity();
    job.Name = 'Test Job';
    job.StageName = 'Not yet started';
    job.CloseDate = System.today() ; 
    insert job;
    Test.stopTest();
      
      
    job  = [ SELECT id, Shortened_Url__c FROM Opportunity WHERE id = :job.id LIMIT 1 ];
    
    System.assert( String.isNotBlank( job.Shortened_Url__c ) );
Any help will be much appreciated.

Regards,
Anindya


 

i want to get results even if i give single letter in searchfield
help me in getting output i tried to manage but still errors 




public class OppNameSearchController {
    public string Name{set;get;}
    public Decimal amount{set;get;}
    public Opportunity Opp{set;get;}
    public string searchstring {get;set;} 
    public boolean show{set;get;}
    
    public void method()
    {
        
       if(searchstring != null && searchstring != '' ){  
    string searchquery='select Name, Amount from opportunity where Name like \'%'+searchstring+'%\'  Limit 10';  
    
     Opp = Database.query(searchstring); 
           show = true;

                   }
        else
        {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'There are no Opportunities with the Name -'  +searchstring);
            ApexPages.addMessage(myMsg);
            show = false;
        }
    }
    
    public void save()
    {
        Opportunity op = Opp;
        update op;
      }
     public void clear(){  
   opp.clear();  
   }  
}







<apex:page controller="OppNameSearchController" >
    <apex:form>
        <apex:pageBlock >
            <apex:pageBlockSection title="Search Filter" >
                Opportunity Name: <apex:inputText value="{!searchstring}"/>
                <apex:commandButton value="Search" action="{!method}" />
            </apex:pageBlockSection>
            <apex:pageMessages ></apex:pageMessages>
            
            
            <apex:pageBlockSection title="Searched Record" rendered="{!show}" >
                <apex:inlineEditSupport showOnEdit="saveButton, cancelButton" 
                                        hideOnEdit="editButton" event="ondblclick" 
                                        changedStyleClass="myBoldClass" resetFunction="resetInlineEdit">
                    <apex:outputField value="{!Opp.Name}"></apex:outputField>
                    <apex:outputField value="{!Opp.Amount}"/>
                </apex:inlineEditSupport>
                <apex:commandButton action="{!save}" value="Save"/>
                <apex:commandButton action="{!clear}" value="reset"/>
            </apex:pageBlockSection>
        </apex:pageBlock>        
           
        
    </apex:form>
</apex:page>



 
Hi,

I have to write a trigger to calculate next meeting date from today. I have an object which stores input of Frequency(monthly, two month, quaterly), Day(Mon-Fri),Week (Week1 -Week 5). Based on these input how should I calculate the next meeting date from today.

example: If Frequency is "Monthly", Day is "Wednesday" and Week is "Week 3".
then I have to calculate date of next meeting which should be Wednesday of 3rd week of next month.

Please help.
Thanks!
 
  • April 13, 2017
  • Like
  • 0
HI, 

we have 15 record types in case object.

do not want to allow to CLOSE/EDIT other records types cases . 

but 3 record types are allowed to close/edit each other cases? 

How to achieve this? 

 
Hi,

I need help on the following issue 

I am having a trigger on account object 

When, we trying to upload bulk records  via dataloader or ETL , system is facing 'CPU usage limition'' issue.
For one Account record creation, the trigger is running four times instead of one time.

How to avoid the issue, Kindly help me pls
MY TRIGGER :

trigger AccountTrigger on Account (after insert, before update, after update, after delete) {  
    
    /* Assign & create Account team members based on user department*/
    if(Trigger_Status__c.getValues('AccountTeam').Active__c && Trigger.isUpdate  && Trigger.isBefore ){
        /* Before insert process */
        AccountTriggerHelper.updateAccountTeam(Trigger.newMap, Trigger.oldMap);
    } 
    
    /* Trigger to invoke the AccountIneligibilty Logs Tracking*/
    if(Trigger_Status__c.getValues('AccountEligibilityLogTrigger').Active__c && Trigger.isAfter && Trigger.isUpdate){
        AccountTriggerHelper.createAccountEligiblityLogs(Trigger.newMap, Trigger.oldMap);
    }
    
    /* Trigger to invoke the DiscountCode Calculations on Products*/
    if(Trigger_Status__c.getValues('AccountAirlineLeveltrigger').Active__c && Trigger.isAfter && Trigger.isUpdate) {
        AccountTriggerHelper.calculateDiscountCode(Trigger.newMap,Trigger.oldMap);
    }
    
    /* Trigger to invoke the DeleteAccount Tracking of Records*/
    if(Trigger_Status__c.getValues('AccountDeleteTrigger').Active__c && Trigger.isAfter && Trigger.isDelete) {
        AccountTriggerHelper.createDelAccountLogTracker(Trigger.oldMap); 
    }        
}
MY CLASS:

public class AccountTriggerHelper {
    
    /*--------------------------------------------------------------------------------------      
  Method Name:        updateAccountTeam
  Description:        Method to Assign & create Account team members based on user department
  Parameter:          Account New Map & Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void updateAccountTeam(Map<Id,Account> newMapAccount, Map<Id,Account> oldMapAccount){
      try{
        AccountTeamHandler accHandler = new AccountTeamHandler();
        List<Account> lstNewAccount = newMapAccount.values();
            accHandler.setRevenueManualUpdate(lstNewAccount, oldMapAccount);
            accHandler.createAccountTeamMembers(lstNewAccount, oldMapAccount);
      }
      catch(Exception ex){
        String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('Account Team - Account Trigger', 'AccountTriggerHelper', 
                                                                      'updateAccountTeam', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
      }
    }

    /*--------------------------------------------------------------------------------------      
  Method Name:        createAccountEligiblityLogs
  Description:        Method to Create AccountIneligibilty Logs and Update
  Parameter:          Account New Map & Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void createAccountEligiblityLogs(Map<Id,Account> newMapAccount, Map<Id,Account> oldMapAccount){
      try{
        AccountEligibilityLogHandler.createAccountEligiblityLogs(newMapAccount, oldMapAccount);
      }
      catch(Exception ex){
        String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('SME - Account Trigger', 'AccountTriggerHelper', 
                                                                      'createAccountEligiblityLogs', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
      }
    }

    /*--------------------------------------------------------------------------------------      
  Method Name:        calculateDiscountCode
  Description:        Method to DiscountCode Calculations on Products
  Parameter:          Account New Map & Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void calculateDiscountCode(Map<Id,Account> newMapAccount, Map<Id,Account> oldMapAccount){
    try{
            AccountAirlineLevelHandler.updateDiscountCodeOnProducts(newMapAccount, oldMapAccount);
      }
      catch(Exception ex){
        String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('SME - Account Trigger', 'AccountTriggerHelper', 
                                                                      'calculateDiscountCode', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
      }
    }

    /*--------------------------------------------------------------------------------------      
  Method Name:        createDelAccountLogTracker
  Description:        Method to Create Delete Tracker Logs records when any Account is Deleted
  Parameter:          Account Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void createDelAccountLogTracker(Map<Id,Account> oldMapAccount){
        try{
            String recTypeName = CustomSettingsUtilities.getConfigDataMap('Del Log SME Account Rec Type');
            List<CreateLogs.DeleteLogWrapper> lstDelLogWrapper = new List<CreateLogs.DeleteLogWrapper>();
            for(Account acc: oldMapAccount.values()){
                String directvalue = CustomSettingsUtilities.getConfigDataMap('AccListner Type Direct Stream');
                if(acc.Listner_Type__c == directvalue){
                    CreateLogs.DeleteLogWrapper delLogWrapper = new CreateLogs.DeleteLogWrapper();
                    delLogWrapper.recType = recTypeName;
                    delLogWrapper.recName =  acc.Name;
                    delLogWrapper.abnNumber = acc.ABN_Tax_Reference__c;
                    delLogWrapper.sobjectId = acc.Id;
                    delLogWrapper.sobjectName = 'Account';
                    lstDelLogWrapper.add(delLogWrapper);
                }
            }
            List<Delete_Tracker_Log__c> lstDelTrackerLog = CreateLogs.createDeleteLog(lstDelLogWrapper);
            insert lstDelTrackerLog;
        }catch(Exception ex){
            String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('Direct Stream - Account Trigger', 'AccountTriggerHelper', 
                                                                      'createDelAccountLogTracker', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
        }
    }

}
Kindly help me pls

Thanks in Advance

 
I have an apex batch class that I was able to get workig in my sandbox enviorment and that is ready for deployment into my production enviroment. 

However when I went to write the test class for this I ran into some trouble, with an error message that says line 50 = Test Class Error: Argument must be an object that implements Database.Batchable.

Can you guys help me get over this hurdle or tell me if i need a new test class code in order to be able to deploy to production? Below are my batch class and my test class thanks. 

Batch Class
global class UpdateContactsVoter implements Database.Batchable<sObject>{
    global Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'Select ID,FirstName,LastName,MailingPostalCode from contact where contact.voter_file_id__c = null';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext info, List<contact> scope){
        Set<String> set_Str = new Set<string>();
                                Map<String,Voter_File_TX__c> mp_VoterFile;

        for(Voter_File_TX__c VoterFile : [Select ID,First_Name__c, Last_Name__c,Zipcode__c, Contact__c From Voter_File_TX__c] ){
                                                if(mp_VoterFile==null){
                                                                mp_VoterFile = new Map<String,Voter_File_TX__c>();
                                                }
                                                mp_VoterFile.put(VoterFile.First_Name__c +''+VoterFile.Last_Name__c +''+VoterFile.Zipcode__c,VoterFile);
                                }
                                for(Contact ContactList : scope){
                                                if(mp_VoterFile!=null && mp_VoterFile.containsKey(ContactList.FirstName+''+ ContactList.LastName+''+ ContactList.MailingPostalCode))
            
            {
                                                                mp_VoterFile.get(ContactList.FirstName +''+ ContactList.LastName +''+ ContactList.MailingPostalCode).Contact__c = ContactList.id;
                                                }
                                }
                                if(mp_VoterFile!=null && mp_VoterFile.values()!=null){
                                                update mp_VoterFile.values();
                                }
    }
    
    global void finish(Database.BatchableContext info){
        
    }
}


Test Class
 line 50 = Test Class Error: Argument must be an object that implements Database.Batchable.

@isTest 
public class TestClassUpdateContacts 
{
    static testMethod void testMethod1() 
    {
        List<Contact> lstContact= new List<Contact>();
        List<Voter_File_TX__c> lstVoterfile = new List<Voter_File_TX__c>();
        if(contact.voter_file_id__c == null && voter_file_tx__c.contact__c == null)
        {
        Contact cont = new Contact();
        cont.FirstName ='Test';
        cont.LastName = 'Test';
        cont.id = 'Test';
        cont.MailingPostalCode = 'test';
            
        insert cont;
            
        Voter_File_TX__c vf = new Voter_File_TX__c();
        vf.First_Name__c ='Test';
        vf.Last_Name__c ='Test';
        vf.RNC_ID__c = 'Test';
        vf.Zipcode__c = 'Test'; 
                                vf.First_Name__c = cont.FirstName ;
        vf.Last_Name__c = cont.LastName ;
        vf.Zipcode__c = cont.MailingPostalCode ;
        vf.Contact__c = cont.Id ;
        
        insert vf;
       
        cont.FirstName = vf.First_Name__c ;
        cont.LastName = vf.Last_Name__c ;
        cont.MailingPostalCode = vf.Zipcode__c;
        cont.RNC_ID__c = vf.RNC_ID__c ;
            
                                update cont;
        }
        else {
         contact cont1 = new Contact(); 
         Voter_File_TX__c vf1 = new Voter_File_TX__c();
         cont1.Voter_File_ID__c = null;
         vf1.Contact__c = null; 
          
        }
        insert lstContact;
        update lstContact;
        
        Test.startTest();

            TestClassUpdateContacts obj = new TestClassUpdateContacts();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }
}
 


 

I am trying to insert a record from developer console for object 'TestTriggers__c'. The record is failing to insert as expected because I am not passing the required field 'Amount__c'. I need to, however, catch this in my trigger, which i am unable to. I can see the error 'System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Amount__c]: [Amount__c]' in the debug log, but unable to catch it within my trigger 'TestTriggers'. Is there any way to do that. I need to use the same approach to catch the errors from different integrations (like data loader) we have in our SF instance.
Hi,
I know Salesforce has limitations but I would need alternate to this issue, please check the below code and provide alternate to that?
The requirement is: calling externam API that has 28000 records to get and that API has limitations on results (only 400 allows) so loooping 72 to get 28K and another for loop on 400 records.

@future (callout=true)
    public static void getAllUsersFromCampusLabs(){
        for (integer i=1;i<=72;i++){
            Map<String,String> parameters = new Map<String,String>();
            parameters.put('page',string.valueof(i));
            parameters.put('page','1');
            parameters.put('pageSize','400');
            String respString = DataAccessController.call_RESTFulAPI_Request('users',parameters);
            Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(respString);
            List<Object> usersList = (List<Object>)jsonMap.get('items');
                for (Object userObject:usersList){
                    Map<String, Object> user = (Map<String, Object>)userObject;
                    String jsonUserName = String.valueOf(user.get('userId')).trim();
                    String userName = (String)user.get('username');
                    String netID = userName.split('@')[0].trim().toLowerCase();
                    List<Contact> userContacts = [SELECT ID,userID__c,userName__c  from Contact where userID__c=:netID];
                    if (userContacts.size()>0){
                        Contact userContact = userContacts[0];
                        userContact.userName__c = jsonUserName;
                         update userContact;
                    }
                }
            }
    }
Hi All,

I am a newbie to Lightning component Development.

I have written a lightning component, which holds Text Input, and a button.
When User enters some text in the text field, by clicking a button. I am calling a javascript controller, then to Javascript Handler, then to Apex Controller. I am searching and returning the result to handler, to javascript handler and then to component attribute values.

I am setting Response to Component attribute in Handler.

I am not getting the response in UI. When I debugged using Lightning Inspector - Chrome Extensions, Actions are successful, and I am getting result in the attributes.

Please let me know, whether i am missing anything.

Thanks in advance.
Hi All,

I have a trigger to assign Contacts by criteria-based-Round Robin based on Project and Language parameters. The below code query was returning values as long as the Projects field was a picklist, now after I've converted it into a multipicklist, it doesn't seem to return any values. Please asist
 
trigger AssignSalesmanager on contact(before insert , after update)
{
    String currentuser = [Select alias From User Where Id = :UserInfo.getUserId()].alias;
            system.debug(currentuser);
            if(currentuser == 'guest' || currentuser == 'oadmi')
            {
    if(Trigger.isBefore)
    {
        if(Trigger.IsInsert)
        {
            Map<String,List<round_robin__c>> mapOfLangUsers = new  Map<String,List<round_robin__c>>();
            Map<String,List<round_robin__c>> mapOfProjUsers = new  Map<String,List<round_robin__c>>();
           
            map<string,list<contact>> MapoflangandContacts = new map<string,list<contact>>();
            map<string,list<contact>> MapofprojandContacts = new map<string,list<contact>>();
            Set<String> projectValues = new Set<String>();
            String projValues;
            Set<String> langValues = new Set<String>();
            List<Contact> allContacts = new List<contact>();
            Boolean hasModifiedUser = false;
            for(contact eachcontact: trigger.new){
  
               if(!String.isBlank(eachcontact.Language__c) && !String.isBlank(eachcontact.Projects__c)) {
                   allContacts.add(eachcontact);
                   langValues.add(eachcontact.language__c);
                   projectValues.add(eachcontact.projects__c);
                   projvalues= String.valueOf(projectValues);
                     
               }     
             
            }
            
            if(MapoflangandContacts.size() > 0 && MapoflangandContacts!= null) {
            for(string strlang : MapoflangandContacts.keyset()){
                integer i=0;
                for(Contact objContact : MapoflangandContacts.get(strlang)){
                    objContact.ownerid = mapOfLangUsers.get(objContact.Language__c)[i].Round_Robin_User__c;
                    mapOfLangUsers.get(objContact.Language__c)[i].Count__c = mapOfLangUsers.get(objContact.Language__c)[i].Count__c+1;
           
                    i++;
                if(i==mapOfLangUsers.get(objContact.Language__c).size())
                    i=0;
                }
            } 
           
            list<round_robin__c> lstrb = new list<round_robin__c>();
    
            for(list<round_robin__c> lstuser : mapOfLangUsers.values()){
                lstrb.addall(lstuser);
            }  
            update lstrb; 
           
           }
           if(MapofprojandContacts.size() > 0 && MapofprojandContacts!= null) {
               for(string strProject : MapofprojandContacts.keyset()){
                    integer i=0;
                    for(Contact objContact : MapofprojandContacts.get(strProject)){
                        objContact.ownerid = mapOfProjUsers.get(objContact.Projects__c)[i].Round_Robin_User__c;
                        mapOfProjUsers.get(objContact.Projects__c)[i].Count__c = mapOfProjUsers.get(objContact.Projects__c)[i].Count__c+1;
               
                        i++;
                    if(i==mapOfProjUsers.get(objContact.Projects__c).size())
                        i=0;
                    }
                } 
           
                list<round_robin__c> lstrb = new list<round_robin__c>();
        
                for(list<round_robin__c> lstuser : mapOfProjUsers.values()){
                    lstrb.addall(lstuser);
                }  
                update lstrb; 
           }
          
           if(allContacts.size() > 0 && allContacts!=null) {
           Integer recordCount = [select count() from contact];
           system.debug('recordCount='+recordCount);
           Integer rr = [select Count() from round_robin__c where Is_Active__c = TRUE AND Language__c IN:langValues AND Projects__c INCLUDES (:projvalues)   ];
             system.debug('rr='+rr);
             if(rr!=0)
           {
             Integer index = Math.mod(recordCount+1,rr);
            
           list <round_robin__c> lstRoundSpecificUsers  = [select id,name,Count__c,Round_Robin_User__c,Language__c,Projects__c from round_robin__c where Is_Active__c = TRUE AND Language__c IN:langValues AND Projects__c INCLUDES (:projvalues)   ];
               system.debug(lstRoundSpecificUsers  );
               Integer i;
               IF(i==null)
               {i=0;}

               for(contact eachContact : trigger.new) {
                   
                       system.debug('index='+index);
                     eachContact.ownerId = lstRoundSpecificUsers[index].Round_Robin_User__c;
              
                   
               }
               }  
           } 
        } 
      
     }   
     }
    
   if(trigger.isUpdate) { 
       System.debug('----->Entered');
        Map<Id,Id> mapOfContact = new Map<Id,Id>();
        for(Contact con: trigger.new)
         {
             
           if(con.OwnerId != trigger.oldmap.get(con.id).ownerId)
           {
               System.debug('----->Entered111');
              mapOfContact.put(con.Id,con.OwnerId);
          }
        }
        list<pba__Request__c> lstRequest = [select id,name,Contact_Owner__c,pba__Contact__c from pba__Request__c where pba__Contact__c IN:mapOfContact.keySet() ];
        if(lstRequest.size() > 0) {
            for(pba__Request__c eachReq : lstRequest) {
                eachReq.OwnerId = mapOfContact.get(eachReq.pba__Contact__c);
            }
        }
        update lstRequest;
    }
}


The system.debug statement for vairable rr keeps returning as 0 if I compare it with a set of values. It returns rows if I hardcode the values, which I don't want to. I want this to be dynamic.

How do i work around this.

Thanks,

Avinash