+ Start a Discussion
SalesRedSalesRed 

Hello,

 

I was wondering if there is any equivalent string function that can used similar to the charAt function which exists in java?

I know no such method is listed at http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_string.htm

 

I know it's possible to look through the string and to get each character using the substring function in such a loop but it would be much better if a function existed similar to charAt.

 

if anyone knows of a better way of doing this you can let me know.

 

Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
Platy ITPlaty IT

You can use substring the same way you would charAt, it doesn't have to be in a loop.  If you know exactly which character(s) you're trying to grab, substring just requires 2 inputs to get it, the start and end position.  So...

 

charAt(4) is the same as substring(3,4)

nama bekannama bekan 
I am coding using Salesforce Apex and DocuSign API. Here a part of my code :
 
DocuSignAPI.Tab tab100 = new DocuSignAPI.Tab() ;                        
tab100.Type_x = 'Custom' ;     
tab100.RecipientID = 1 ;                           
tab100.DocumentID = 1 ;                           
tab100.PageNumber = 1 ;                           
tab100.XPosition = 40 ;                           
tab100.YPosition = 40 ;
Unfortunately, I try to use other field name like "Font, FontSize" but it is not recognized : I got this message "Variable does not exist : Font".

Thanks
 
Best Answer chosen by nama bekan
Tarun DasTarun Das
Try to create APEX classes, have you used DS WSDL - docusign.net/API/3.0/Schema/dsapi.wsdl?, please check Using DocuSign WSDL (https://developers.docusign.com/docs/esign-soap-api/esign101/wsdls/) in SF 

Please mark it as Solution if it works for you

Regards,
Tarun
Best Answer chosen by Shaikh Rayyan
CharuDuttCharuDutt
Hii Shaikh
Try Below Code
global class BatchUpdateaccnameonOpp implements Database.Batchable <sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'Select Id ,Name,(Select Id,Name,AccountId from Opportunities) from Account';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc,List<Account> batch) {
       for(Account Acc : batch){
        for(Opportunity Opp : Acc.Opportunities){
        if(Acc.Id = opp.AccountId){
         opp.Name = Acc.Name +' _ '+ opp.Name;
         }
        }
       }
       
       if(!batch.IsEmpty()){
       update batch;
       }
    }
    
    global void finish(Database.BatchableContext bc) {
        //Do Nothing.
    }
}
Please Mark it As Best Asnwer If It Helps
Thank You!
b.sakib.saki 
public class acc_contact_num_rollup 
{
    public static Void InsertMethod(list<Contact> lstCon ){
        List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
         for(Contact con : lstCon){ 
            if(con.AccountId != null){
                   setAccIds.add(con.AccountId);      
            }   
        }
        for(Account acc :[Select id,Number_of_Contact__c ,(Select id,name from contacts) from Account where Id in : setAccIds]){
     
        acc.Number_of_Contact__c = acc.contacts.size();
       
        acclist.add(acc);
    }
    if(!acclist.isempty()){
        update accList; 
    }
    }
    public static Void UpdateMethod(list<Contact> lstCon,map<Id,Contact>oldmap ){
        List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
         for(Contact con : lstCon){ 
            if(con.AccountId != null){
                   setAccIds.add(con.AccountId); 
                setAccIds.add(oldMap.get(con.Id).AccountId);
            }   
        }
        for(Account acc :[Select id,Number_of_Contact__c ,(Select id,name from contacts) from Account where Id in : setAccIds]){
     
        acc.Number_of_Contact__c = acc.contacts.size();
       
        acclist.add(acc);
    }
    if(acclist.size()>0){
        update accList; 
    }
    }
    public static Void deleteMethod(list<Contact> lstCon){
        List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
         for(Contact con : lstCon){ 
            if(con.AccountId != null){
                   setAccIds.add(con.AccountId);      
            }   
        }
        for(Account acc :[Select id,Number_of_Contact__c ,(Select id,name from contacts) from Account where Id in : setAccIds]){
     
        acc.Number_of_Contact__c = acc.contacts.size();    
        acclist.add(acc);
    }
    if(acclist.size()>0){
        update accList; 
    }
    }

}
Best Answer chosen by b.saki
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Sai ,

Can you try the below test class which gives you 100% coverage  for the class and even for the trigger using this class as well. We are creating Account and Contact checking the results based on our code .
 
@isTest 
public class acc_contact_num_rollupTest {
static testMethod void testMethod1() 
 {
 Account testAccount = new Account();
 testAccount.Name='Test Account' ;
     insert testAccount;
     Account testAccount1 = new Account();
 testAccount1.Name='Test Account' ;
     insert testAccount1;

     contact con= new Contact();
     con.lastname='sample';
     con.AccountId= testAccount.id;
     insert con;
     List<Account> acclisr= [select id,Number_of_Contact__c from Account where Id = :testAccount.id];
     
system.assertEquals(1 ,acclisr[0].Number_of_Contact__c );
     
     Con.AccountId= testAccount1.id;
     update con;
     List<Account> acclisr1= [select id,Number_of_Contact__c from Account where Id = :testAccount.id];
     
system.assertEquals(0 ,acclisr1[0].Number_of_Contact__c );
     delete con;
     List<Account> acclisr2= [select id,Number_of_Contact__c from Account where Id = :testAccount.id];
     
system.assertEquals(0 ,acclisr2[0].Number_of_Contact__c );

 
 }
}
Let me know if you face any issue in the code
If this solution helps, Please mark it as best answer.

Thanks,
 
Andrew EAndrew E 
Hi all,

I have some apex code that looks like the code below. In my test class, I have a testMethod for successful execution, but I'm having trouble creating a testMethod for the exception. I've been able to trigger the exception, but the test is marked as Fail and I recieve "System.AuraHandledException: Script-thrown exception". As a result, I'm not getting code coverage for this exception.

How can I successfully test an AuraHandledException from a testMethod without breaking the test and having it result in a Fail?
try{
   update account;
}
catch(Exception e){
   throw new AuraHandledException('error updating account');
}

 
Best Answer chosen by Andrew E
Nayana KNayana K
In your test method also you have to add try catch block. Suppose if you set account.name blank they you know it will throw exception :

account.name  = '';

try
{
 //call the above method which updates the account
}
catch(Exception e) 
{

}
 
Rohini Chaudhary 14Rohini Chaudhary 14 
Apex Class:
public with sharing class ChangeOpptyOwnerCtrl {
    private string oppId;
    public Opportunity oppobj {get;set;}
    public boolean isErrInSave {get;set;}
    
    public ChangeOpptyOwnerCtrl(ApexPages.StandardController ctrl){
        oppId = ApexPages.currentPage().getParameters().get('oppId');
        if(oppId != null)
            oppobj = [Select id, Name, OwnerId from Opportunity where id =: oppId limit 1];
    }
    
    public void saveOwner(){
        isErrInSave = false;
        try{
            if(oppobj != null)
                update oppobj;
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error , e.getMessage()));
            isErrInSave = true;
        }
    }
}


TestClass:

@isTest
public with sharing class ChangeOpptyOwnerCtrlTest {
    @testSetup
    static void setupTestData(){
        Account acc = TestUtility.createAccount('Test A');
        insert acc;
        Opportunity opp = TestUtility.createOpportunity('@test opp', Date.today(), 'To be Invoiced', acc.id);
        opp.Follow_up_Date__c = date.today();
        insert opp;
    }
    
    testmethod static void saveOwnerTest(){
        Opportunity opp = [Select id from Opportunity limit 1];
        test.startTest();
        
        Test.setCurrentPageReference(new PageReference('Page.ChangeOpptyOwnerPage'));
        System.currentPageReference().getParameters().put('oppId',opp.id);        
        ApexPages.StandardController sc = new ApexPages.StandardController(opp);
        ChangeOpptyOwnerCtrl ctrlObj = new ChangeOpptyOwnerCtrl(sc);
        
        ctrlObj.saveOwner();
        
        test.stopTest();
        
    }
    
}



can any one help me to cover catch(Exception e) lines
Best Answer chosen by Rohini Chaudhary 14
Maharajan CMaharajan C
Rohini, Please mark the best Answer to close this thread...
Li LeeLi Lee 
We use Salesforce Manufacturing Cloud for our business. We create a VF page show SalesAgreementProductSchedule record and edit those records.
To get and update records, we use JavaScript Remoting.During test, we found follow weird behavior in Salesfoce.
If we send SalesAgreementProductSchedule like { PlannedQuantity: 48, ID: 0YC8b0000008SDiGAM }, Salesforce Database.update throw error and we can not update this record. But if we put ID at first field in record like { ID: 0YC8b0000008SDiGAM, PlannedQuantity: 48 } we can success update this record.
I want to ask you why cause this behavior? Is there any document about it?
Best Answer chosen by Li Lee
Li LeeLi Lee
Hi, after we research more document we found solution in Salesforce Document: https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm

In this document has follow content:

User-added image
So we change our code as follow:
if (hasId) {
    newSObject(id);
} else { 
    newSObject();
}
Celeste Streeter 7Celeste Streeter 7 
Hi,
I am trying to create an alert on a specific date field on an object that is time-based related. 

The issue is that both Process Builder and WorkFlow only fire when an object is updated or created, but not when a date becomes Today (naturally, without editing or creating the object's fields).

Here are my 3 separate use cases (each needs its own solution, but has the same problem):
1. On a custom object called "Project" we have a date-field called KICKOFF DATE.  When the date becomes today, we want an email alert to send out a reminder that today is kickoff date for this project.
2. When an Opp is in Stage 1 and it's Age = 60 days, we want to send an email alert that the Opportunity is 60 days old (from created date) and is in stage 1.
3. When an Opportunity is approaching the Close Date and is in a lower Stage, we want an alert to fire that says warns it is approaching.
So now I think I need a trigger to help fire this in Process Builder. 

Anybody ever had this need before or accomplished this?
Best Answer chosen by Celeste Streeter 7
Abhishek BansalAbhishek Bansal
Hi Celeste,

You can simply achieve this bys using a workflow rule. You can set the criteria as TRUE if you always want to execute this. You can add a time dependent workflow action which will be executed 0 days after KICKOFF Date.

Let me know if you need any help in setting up this worklflow rule.

Thanks,
Abhishek Bansal.
Gmail: abhibansal2790@gmail.com
Skype: abhishek.bansal2790
sumit dsumit d 
Hi All,
          I want to show users like below image. how can i do this in LWC? any suggestions?
 User-added image
Best Answer chosen by sumit d
Maharajan CMaharajan C
Hi Sumit,

I have done some changes and able to navigate like standard related list:

Please use by below components for your reference:

By default i will display only 5 records using this propert =====>   @api defaultrecords = 5;

HTML:
 
<template>
    <template if:true={users.data}>
    <lightning-card  title="Forum members"  icon-name="standard:groups">
        <div class = "slds-var-m-around_medium slds-box slds-p-around_none slds-m-top_x-small slds-m-bottom_medium slds-m-horizontal_none">
            <template if:true={users.data}>
                <lightning-layout multiple-rows>
                    <template for:each={users.data} for:item = "member" for:index="index">
                        <template if:true={ifChecker}>
                            <lightning-layout-item padding="around-small" key={member.id} size="4">
                                <div key={member.id}>
                                    <img src={member.SmallPhotoUrl} />
                                    <br/><br/>
                                    {member.Name}
                                </div>
                            </lightning-layout-item>
                        </template>
                    </template>
                </lightning-layout>
          </template>
        </div>
        <div slot="footer" class="slds-align_absolute-center">  
            <a id="viewall" href="javascript:void(0)" onclick={handleviewAll}>view All</a>
        </div>
   </lightning-card>
   </template>
</template>

JS:
 
import { LightningElement,track,wire,api } from 'lwc';
import getForumMember from '@salesforce/apex/GetForumMembers.getForumMember';
import { NavigationMixin } from 'lightning/navigation';


export default class CustomForumMembers extends NavigationMixin(LightningElement) {
    @track users;
    @api defaultrecords = 5;
    currentIndex = 0;
   
    @wire(getForumMember)
    users

    get ifChecker(){
        this.currentIndex++;
        return this.currentIndex<=this.defaultrecords;
    }

    handleviewAll(){
        let defRecord = this.users.data.length;
        this[NavigationMixin.Navigate]({
            type: "standard__component",
            attributes: {
                componentName: "c__NavigateToLWC"
            },
            state: {
                c__defaultrecords: defRecord
            }
        });
    }
}

Created one Aura Component for Navigation because LWC to LWC navigation won't work directly: 
https://salesforcediaries.com/2020/06/07/navigate-to-lightning-web-component-from-another-lightning-web-component/

Component Name :   NavigateToLWC
<aura:component implements="flexipage:availableForAllPageTypes,lightning:isUrlAddressable" access="global">
    <aura:attribute type="String" name="defaultrecords"/>
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>    
    <div class="slds-card">
        <c:customForumMembers defaultrecords="{!v.defaultrecords}"/>
    </div>
</aura:component>
JS:
({
    init: function(cmp, evt, helper) {
        var myPageRef = cmp.get("v.pageReference");
        var propertyValue = myPageRef.state.c__defaultrecords;
        cmp.set("v.defaultrecords", propertyValue);
    }
})

My Apex Class:
public class GetForumMembers {
	@AuraEnabled(cacheable = true)
    public static List<user> getForumMember(){
        return [Select Id,Name,SmallPhotoUrl from user limit 12];
    }
}

Now you can use the view all functionalities from custom component.

Please close this thread by marking the best answer!!!

Thanks,
Maharajan.C
Desiree DixonDesiree Dixon 
Hello! I'm just now digging into Apex Triggers, and I'm having a little trouble with creating tests. Here's my Apex class:
trigger CanceledProgram on Program__c (before update) {
	Program__c pNew = Trigger.new[0];
    Program__c pOld = Trigger.oldMap.get(pNew.id);
    
    if(pNew.Canceled__c != pOld.Canceled__c && pNew.Canceled__c == true){
        System.debug('Updated to True');
        System.debug('New value = ' + pNew.Canceled__c);
        System.debug('Old value = ' + pOld.Canceled__c);
        
        if(pOld.Name.length() <= 70){
            pNew.Name = 'CANCELED: ' + pNew.Name;
            System.debug('New name length: '+pNew.Name.length());
            System.debug('Old name length: '+pOld.Name.length());
            System.debug(pNew.Name);
        } else if (pOld.Name.length() > 70){
            String pNameShort = pNew.Name.substring(0, 65) + '...';
            pNew.Name = 'CANCELED: ' + pNameShort;
            System.debug(pNew.Name);
            System.debug(pNew.Name.length());
        }
        
        
    } else if (pNew.Canceled__c != pOld.Canceled__c && pNew.Canceled__c == false) {
        System.debug('Updated to False');
        System.debug('New value = ' + pNew.Canceled__c);
        System.debug('Old value = ' + pOld.Canceled__c);
        if(pNew.Name.startsWith('CANCELED: ')){
            pNew.Name = pNew.Name.substring(10);
        }
        
        
    } else {
        System.debug('The Canceled Field was not changed');
    }
    
    if (pNew.Name != pOld.Name && pOld.Name.length() >70){
        
        System.debug(pOld.Name.length());
        System.debug(pNew.Name.length());
    }
        
}

And see below for the test class. It says I have 100% coverage, but that the 3/4 tests failed. I assume they need to succeed in order to push this class to production. I don't understand why they didn't pass though? In the first test method, I did a little testing, trial, and error with using System.debug to double check the values, and the test should be passing. Can anyone tell me what I'm doing wrong? Thanks for any help you can provide!
 
@isTest
private class CanceledProgramTest {     

    @isTest static void TestCanceledProgramWithShortName() {
        Program__c p1 = new Program__c(Name='Will not happen');
        insert p1;
        
        p1 = [SELECT Id, Name, Canceled__c FROM Program__c WHERE Id = :p1.Id];
        System.debug(p1);
        Test.startTest();
        p1.Canceled__c = true;
        update p1;
        System.assertEquals('CANCELED: Will not happen', p1.Name);
        Test.stopTest();
    }
    
    @isTest static void TestCanceledProgramWithLongName() {
        Program__c p = new Program__c(Name='This program will not happen. I am sorry, but this program just will not happen.');
        insert p;
        p.Canceled__c = true;
        update p;
        System.assertEquals('CANCELED: This program will not happen. I am sorry, but this program just w...', p.Name);
    }
    
    @isTest static void TestUnCanceledProgramChangeName() {
        Program__c p = new Program__c(Name='CANCELED: We will have it after all. Name changes.', Canceled__c = true);
        insert p;
        p.Canceled__c = false;
        update p;
        System.assertEquals('We will have it after all. Name changes.', p.Name);
    }
    
    @isTest static void TestUnCanceledProgramSameName() {
        Program__c p = new Program__c(Name='We will have it after all. Name is same.' , Canceled__c = true);
        insert p;
        p.Canceled__c = false;
        update p;
        System.assertEquals('We will have it after all. Name is same.', p.Name);
    }
}

 
Best Answer chosen by Desiree Dixon
Maharajan CMaharajan C
Hi Dixon,

Please try the below test class:
 
@isTest
private class CanceledProgramTest {     

    @isTest static void TestCanceledProgramWithShortName() {
        Project__c p1 = new Project__c(Name='Will not happen');
        insert p1;
        
        System.debug(p1);
        Test.startTest();
        p1.Canceled__c = true;
        update p1;
        
        p1 = [SELECT Id, Name, Canceled__c FROM Project__c WHERE Id = :p1.Id];
        System.assertEquals('CANCELED: Will not happen', p1.Name);
        Test.stopTest();
    }
    
    @isTest static void TestCanceledProgramWithLongName() {
        Project__c p = new Project__c(Name='This program will not happen. I am sorry, but this program just will not happen.');
        insert p;
        p.Canceled__c = true;
        update p;
        p = [SELECT Id, Name, Canceled__c FROM Project__c WHERE Id = :p.Id];
        System.assertEquals('CANCELED: This program will not happen. I am sorry, but this program just w...', p.Name);
    }
    
    @isTest static void TestUnCanceledProgramChangeName() {
        Project__c p = new Project__c(Name='CANCELED: We will have it after all. Name changes.', Canceled__c = true);
        insert p;
        p.Canceled__c = false;
        update p;
        p = [SELECT Id, Name, Canceled__c FROM Project__c WHERE Id = :p.Id];
        System.assertEquals('We will have it after all. Name changes.', p.Name);
    }
    
    @isTest static void TestUnCanceledProgramSameName() {
        Project__c p = new Project__c(Name='We will have it after all. Name is same.' , Canceled__c = true);
        insert p;
        p.Canceled__c = false;
        update p;
        System.assertEquals('We will have it after all. Name is same.', p.Name);
    }
}

Thanks,
Maharajan.C