• Daniel Ahl
  • NEWBIE
  • 300 Points
  • Member since 2020
  • Developer
  • Pia Relations AB


  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 35
    Replies
Hello community!  I am having trouble creating a test class for the following code.  Any assistance would be greatly appreciated. Thank you in advance for your help!

global class Reassign implements Schedulable {
    global void execute(SchedulableContext ctx) {
        // Define 'inprogress' and 'newqueue' string variables
        String inprogress;
        String newqueue;
        
        // Find 'In Progress' queue Id and assign to 'inprogress'
        inprogress = [SELECT Id from Group where Name = 'In Progress' and Type = 'Queue'].Id;
        // Find 'New' queue Id and assign to 'newqueue'
        newqueue = [SELECT Id from Group where Name = 'New' and Type = 'Queue'].Id;
        
        // Create lists for cases
        List<Case> cases1 = [SELECT Id, CaseNumber, OwnerId
                            FROM Case
                            WHERE RecordTypeId = '0124u00000060pmAAA' 
                            AND (Status = 'In Progress' OR Status = 'Outreach Attempted')];
        
        List <Case> cases2 = New List<Case>();
        
        List<Case> newcases1 = [SELECT Id
                              From Case
                              Where RecordTypeId = '0124u00000060pmAAA'
                              AND Status = 'New'];
        
        List <Case> newcases2 = New List<Case>();
        
        // Change the owner and status for each Case in the list and add to respective queue
        for (Case c : cases1){
            c.OwnerId = inprogress;
            c.Status = 'In Progress';
            cases2.add(c);
        }
        update cases2;
        
        for (Case d : newcases1){
            d.OwnerId = newqueue;
            newcases2.add(d);
        }
        update newcases2;
    }
}
Any Help would be much apricated I created an Apex Trigger and am having trouble writing the test class for code coverage really green when it comes to this 

Triger 
trigger updateCustomDev on Custom_Programming__c (before Insert) {
  for (Custom_Programming__c Custom : trigger.new) {

    //SQL statement to lookup price 
    List<PricebookEntry> sqlResult = [SELECT UnitPrice 
        FROM PricebookEntry 
        WHERE Product2.Name = 'Custom Development'
                               AND PriceBook2.Name='DAKCS'];

    //save the returned SQL result inside the field 
    Custom.Hourly_Cost__c = sqlResult[0].UnitPrice;
  }    
}

Test Class
@IsTest
public class TestupdateCustomDev {
    @IsTest static void testHourlyCost(){
        //Create Custom
        Custom_Programming__c c = new Custom_Programming__c(Name='Test',Custom_State__c='Active',Custom_Type__c='Custom',Status__c='New');
        
        Test.startTest();
        Database.SaveResult result = Database.insert (c, true);
         System.assert(result.isSuccess());
        Test.stopTest();
    }
}

I was hoping this would be really simple all I want the trigger to do is update a field with an entry from pice book entry.

Thanks again
Trying to create an Apex trigger to query the price-book entries and place the result in a custom field can someone please tell me what i am doing wrong 
get two problems Expression must be a list type: pricebookEntry 
and a value cannot be stored to Hourly_Cost__c in type Custom_Programming__C


trigger updateCustomDev on Custom_Programming__c (after update) {
  

    //SQL statement to lookup price 
    PricebookEntry sqlResult = [SELECT UnitPrice 
        FROM PricebookEntry 
        WHERE Product2.Name = 'Custom Development'
                               AND PriceBook2.Name='DAKCS'];

    //save the returned SQL result inside the field 
    Custom_Programming__c.Hourly_Cost__c = sqlResult[0].UnitPrice;
      
}
Hello,
can you help me write a test for this trigger plz
trigger ContractTrigger on Contract (after update) {
    Public String[] statut_activated   {set;get;}
    Public String[] statut_waiting   {set;get;}
    Public String[] statut_terminated   {set;get;}
    
    statut_activated = new String[] {'Accepted','Accepted2'};
    statut_waiting = new String[] {'waiting','waiting2'}; 
    statut_terminated = new String[] {'terminated','terminated2'}; 

    
    List<Decimal> listAmount= new List<Decimal>();
	set<Id> AccountIds = new set<Id>();
    for(Contract c : Trigger.new){
    if(c.AccountId != null)
    	AccountIds.add(c.AccountId);
    }

  

    Map<String, Contract> cntrMap  = new Map<String, Contract>();
    
    for(Contract contr : [Select Id,contract_stat__c,amount__c From Contract Where AccountId IN: AccountIds]){
        cntrMap.put(contr.Id , contr);
         
         Account acc = [SELECT Id,st__c FROM Account WHERE Id IN: AccountIds];	
        if(contr.amount__c > 0){
            listAmount.add(contr.amount__c);
        }else{
          acc.checked__c=FALSE;
          update acc;
        }
        
       
        if(statut_activated.contains(contr.contract_stat__c)){
             cntrMap.put(contr.contract_stat__c , contr);     
             acc.st__c='customer';   
             update acc;
             break;
            
            /* Contrat En attente*/ 
        }else if(statut_waiting.contains(contr.contract_stat__c)){

             acc.st__c='customer_type2';
             update acc;
             break;
        /*  Contrat En Terminé  */ 
        }else if(statut_terminated.contains(contr.contract_stat__c)){
		
             acc.st__c='customer_type3';
             update acc;
             break;     
        }else{

             acc.st__c='customer_other';
             update acc;       
        }
    }

    for(Decimal l : listAmount){
    	if(l > 0){
          Account acc = [SELECT Id,st__c FROM Account WHERE Id IN: AccountIds];	
          acc.checked__c=TRUE;
          update acc;
         }
	}

}

Thanks for help 
Hi and thanks in advance.

I want to see the records that were created or updated via Database.UpsertResult.  The records are being updated and/or created, but I am not getting ANY results from the for loop. 

Any ideas?
 
Schema.SObjectField f = Case.Ticket_Number__c; 

       Database.UpsertResult [] cr = Database.upsert(toBeUpsertCases, f, false);  
        
        // I want to see what was updated / created        
        for(Integer index = 0; index < cr.size(); index++ )
        {
            if(cr[index].isSuccess())
            {
                if(cr[index].isCreated())
                {
                    System.debug(toBeUpsertCases[index].Ticket_Number__c + ' was created');
                } else 
                 {
                   System.debug(toBeUpsertCases[index].Ticket_Number__c + ' was updated'); 
                 }
            }
        }// end for loop

Eric

The data source fied is populated and the associated cross-object formula as well, however when debugging a test class,  it brings the cross-object formula value null.

Would be possible to read values from cross-object formula fields on a test class?

thanks

Hi all, 

Many thanks in advance for reading. 

Im struggling to create a test class for this custom controller. i'm only getting 12% coverage so im clearly doing something fundamentally wrong but with limited experience with custom controllers i'd really appreciate any help? 

Again, much appreciation!

CONTROLLER
public class AddMultipleLinesQuoteController {
    
    Opportunity opportunity;
    ABS_Product__c ABSProduct;
    Quote_Custom__C  quote;
    Quote_Line__c qLine;
    public Integer rowIndex {get;set;}
    
    public Opportunity getOpportunity() {
        if(Opportunity == null) 
            Opportunity = [select id, name, AccountId,ownerID from Opportunity 
                           where id = :ApexPages.currentPage().getParameters().get('id')];
        return Opportunity;
    }
    
    public Quote_Custom__C getquote() {
        if(quote == null) quote = new Quote_Custom__C();
        return quote;
    }
    
	public Quote_Line__c getqLine() {
        if(qLine == null) 
            qLine = [select id,name,Discount__c,ABS_Product__c,Denomination__c, Line_Total__c,Quantity__c,Quote__c
                     from Quote_Line__c];
        return qLine;
    }
    
    public ABS_Product__c getABSProduct() {
        if(ABSProduct == null) 
            ABSProduct = [select id, name from ABS_Product__c];
        return ABSProduct;
    }
    
    Quote_Line__c line = new Quote_Line__c();
    public list<Quote_Line__c> listlines{ get; set; }
    
    public AddMultipleLinesQuoteController() {
        listlines = new list<Quote_Line__c>();
        listlines.add(line);
    }

    Public void addline() {
        Quote_Line__c l = new Quote_Line__c();
        listlines.add(l);
    }
    
    public PageReference deleteRow(){
        rowIndex = Integer.valueOf(ApexPages.currentPage().getParameters().get('rowIndex'));
        listlines.remove(rowIndex);
        return null;
    }
    
    public PageReference saveline() {  
        
        if (line.ABS_Product__c == null ||
           line.Denomination__c == null ||
           line.Quantity__c == null ||
           line.Discount__c == null)
		{
    	ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please ensure all quote lines are populated'));
    	return null;
		} 
        
        if ( (Quote.Delivery_Address_Line_1__c != NULL ||
           Quote.Delivery_Address_City__c != NULL ||
              Quote.Delivery_Address_Country__c != NULL ||
           Quote.Delivery_Address_Post_Code__c != NULL) && 
           (Quote.Delivery_Address_Line_1__c == NULL ||
           Quote.Delivery_Address_City__c == NULL ||
              Quote.Delivery_Address_Country__c == NULL ||
           Quote.Delivery_Address_Post_Code__c == NULL))
		{
    	ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'If you are entering a physical delivery address please ensure all fields are completed'));
    	return null;
		} 
        
        
        if ( (Quote.Delivery_Address_Line_1__c == NULL &&
           Quote.Delivery_Address_City__c == NULL &&
              Quote.Delivery_Address_Country__c == NULL &&
           Quote.Delivery_Address_Post_Code__c == NULL) &&
            (Quote.Digital_Delivery_Name__c == null &&
            Quote.Digital_Delivery_Email__c == null))
		{
    	ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter either a physical delivery address or a digital delivery address'));
    	return null;
		} 
        
        if ( (Quote.Digital_Delivery_Name__c != null ||
            Quote.Digital_Delivery_Email__c != null) && 
            (Quote.Digital_Delivery_Name__c == null ||
            Quote.Digital_Delivery_Email__c == null))
		{
    	ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'If you are entering a digital delivery address please ensure both fields are completed'));
    	return null;
		}
 
        if(line.Quote__c == null){
        quote.Opportunity__c = Opportunity.id;
        insert quote;
        List<Quote_Line__c> con = new List<Quote_Line__c>();
        for(Quote_Line__c c : listlines){
            c.quote__c = quote.id;
            con.add(c);
        }
        
            insert con;
            system.debug('listLines inserted');
          
        }
        
        PageReference quotePage = new ApexPages.StandardController(new Quote_Custom__c(id=quote.Id)).view();
        quotePage.setRedirect(true);
        
        return quotePage;
        
    }   
}

CURRENT TEST CLASS
@IsTest
public class MultipleLinesQuoteControllerTest {
    
    private static testmethod void testMultipleLinesQuoteController(){
                
        
        Account acc = new Account();
        	acc.Phone = '01516531700';
        	acc.name = 'testAcc';
        	acc.type = 'Customer';
        	acc.website = 'www.parkgroup.com';
        	acc.BillingCity = 'Park House';
        	acc.BillingCountry = 'Park House';
        	acc.BillingPostalCode = 'NW10 6AJ';
        	acc.BillingStreet = 'Street';
        	acc.Corp_Business_Type__c = 'Staff Rewards- Corporate';
        	acc.Discount__c ='0%';
        	acc.Industry = 'Finance';
        	acc.Lead_Source__c='existing';
        insert acc;
        
        Opportunity opp = new Opportunity();
        	opp.name = 'test opp';
        	opp.AccountId = acc.id;
        	opp.amount = decimal.valueOf(1000);
            opp.First_Order_Value__c = decimal.valueOf(1000);
            opp.closeDate = date.today();
            opp.type = 'New Business';
        	opp.StageName = 'Qualified';
        insert opp;

        AddMultipleLinesQuoteController controller = new AddMultipleLinesQuoteController(); 
        
        Opportunity o = controller.getOpportunity();
  			PageReference pageRef = Page.quoteinput; 
  			pageRef.getParameters().put('id', String.valueOf(opp.Id));
  			Test.setCurrentPage(pageRef);
        
        
        ABS_Product__c prod = controller.getABSProduct();
        	prod.name = 'Love2shop Gift Card';
                
        Quote_Custom__c qu = controller.getQuote();
        	qu.Delivery_Address_Line_1__c = 'street';
            qu.Delivery_Address_City__c = 'city';
            qu.Delivery_Address_Country__c ='country';
            qu.Delivery_Address_Post_Code__c = 'l1 1aa';
            qu.Quote_PO_Reference__c = 'po';
            qu.Quote_Detail_Notes__c = 'details';
            qu.Opportunity__c = opp.id;
        
        Quote_Line__c quLine = controller.getqLine();
        	quLine.Discount__c = decimal.valueOf(1);
            quLine.ABS_Product__c = prod.id;
            quLine.Denomination__c = decimal.valueOf(10);
            quLine.Quantity__c = decimal.valueOf(1);
            quLine.Quote__c = qu.id;
        
        
        Quote_Line__c quLine2 = controller.getqLine();
        	quLine2.Discount__c = decimal.valueOf(1);
            quLine2.ABS_Product__c = prod.id;
            quLine2.Denomination__c = decimal.valueOf(10);
            quLine2.Quantity__c = decimal.valueOf(1);
            quLine2.Quote__c = qu.id;
        
        
        controller.addline();
        controller.deleteRow();
        controller.saveline();
        
        
    }
}

VISUALFORCE PAGE
<apex:page Controller="AddMultipleLinesQuoteController" lightningStylesheets="true" sidebar="false" >
    
    <head>
            <style type="text/css" media="print">
    
				.title {
                font-size: 12px;
                font-weight: bold;
                color: #5670ab;
                }  
                
        </style>
    </head>
    
    <apex:form >
        <apex:pageBlock id="pb">
            <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockSection title="Quote Details">
                <apex:inputField value="{!opportunity.Name}"/>
                <apex:inputField value="{!Quote.Quote_PO_Reference__c}" required="true"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection title="Delivery Details" columns="2">
                <apex:outputtext style="font-size: 14px;font-weight: bold;color: #5670ab;" value="Address for physical delivery:"/><br/>

                    <apex:inputField value="{!Quote.Delivery_Address_Line_1__c}"/><br/>
                    <apex:inputField value="{!Quote.Delivery_Address_City__c}" /><br/>
                    <apex:inputField value="{!Quote.Delivery_Address_Post_Code__c}"/><br/>
                    <apex:inputField value="{!Quote.Delivery_Address_Country__c}"/><br/>
                    <apex:outputtext style="font-size: 14px;font-weight: bold;color: #5670ab;" value="Address for digital delivery:"/><br/>
                    <apex:inputField value="{!Quote.Digital_Delivery_Name__c}"/>
                    <apex:inputField value="{!Quote.Digital_Delivery_Email__c}"/>
            </apex:pageBlockSection>
<br/>
             <apex:outputtext style="font-size: 14px;font-weight: bold;color: #5670ab; text-align: center;" value="Please detail the quote lines below, totals will be generated on the quote pdf:"/><br/>
            <br/>
            <apex:variable var="rowNumber" value="{!0}"/> 
            <apex:pageBlockTable value="{!listlines}" var="l">
                <apex:param value="{!rowNumber+1}"/>
                
                <apex:column headerValue="Item">
                    <apex:inputField value="{!l.ABS_Product__c}" />
                </apex:column>
                <apex:column headerValue="Denomination/Value" style="width: 40%;">
                    <apex:inputField value="{!l.Denomination__c}" />
                </apex:column>
                <apex:column headerValue="Quantity" style="width: 40%;">
                    <apex:inputField value="{!l.Quantity__c}" />
                </apex:column>
                <apex:column headerValue="Discount" style="width: 40%;">
                    <apex:inputField value="{!l.Discount__c}" />
                </apex:column>
                <apex:column >
                    <apex:commandButton value="X" action="{!deleteRow}" reRender="pb" style="font-weight:bold; color: red;">
                        <apex:param name="rowIndex" value="{!rowNumber}"/>
                    </apex:commandButton>
                    <apex:variable var="rowNumber" value="{!rowNumber+1}"/>
                </apex:column>
            </apex:pageBlockTable>
            <apex:pageBlockSection title="Details/Notes" columns="1"  >
                <apex:inputField label="" style="width: 100%; align: center;" value="{!quote.Quote_Detail_Notes__c}"/>
            </apex:pageBlockSection>                
            <apex:pageBlockButtons location="Bottom" >
                <apex:commandButton value="Add New Row" action="{!addline}"/>
                <apex:commandButton value="Generate Quote" action="{!saveline}"/>
            </apex:pageBlockButtons>
            <apex:pageMessages ></apex:pageMessages>
        </apex:pageBlock>
    </apex:form>
</apex:page>

​​​​​​​
 
Hi and thanks for any tips in advance.
First time writing a Get request. 

1. My Class:
public class MaintenanceTicket 
{
	public static String getMaintenanceTickets(string location )
    {
        HTTP h = new HTTP();
        HTTPRequest req = new HTTPRequest();     
                    
        req.setEndpoint('https://api.fake/odata/AccountBalances?$expand=businessUnit&$count=true&$skip=0&$top=3');
      
        req.setTimeout(120000);    
            
        req.setMethod('GET');
       
       // QA Authorization
       req.setHeader('Authorization', 'Bearer ' + 'FakeID');
        HTTPResponse res = h.send(req);
        String strResponse = res.getBody();
        
        if(res.getstatusCode() == 200 && res.getbody() != null)
            system.debug('Response: ' + res.getBody());
        {
         //MAP<String,Object> jsonBody = (Map<String,Object>)Json.deserializeUntyped(res.getBody()); // pass data
        
         List<Object > jsonBody = (List<Object>) Json.deserialize(strResponse, List<Object>.class);
          
         system.debug('Got these values:');
         
         System.debug(jsonBody);
        
        String ticket = String.valueof(jsonBody);
                
        return ticket;
        
        }
                  
     } 
}
2. My Remote Site settings is accurate

3. My anonymous apex code:
String busloc = MaintenanceTicket.getMaintenanceTickets('385');
    System.debug(busloc);

4. Response body (system.debug):
13:10:22:633 USER_DEBUG [26]|DEBUG|Response: {"@odata.context":"http://api.fake/$metadata#AccountBalances(businessUnit())",
"@odata.count":xxx,
"value":[{"id":1,
"businessUnitId":xxx,
"charges":46536.710000,
"credits":-37741.810000,
"balance":8794.900000,
"effectiveDate":"2020-03-03T02:54:03.81-06:00",
"businessUnit":{"id":385,"transactionType":2,"billToNumber":&quot

5.  The error:
13:10:22:654 FATAL_ERROR System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set

13:10:22:000 FATAL_ERROR Class.System.JSON.deserialize: line 15, column 1

13:10:22:000 FATAL_ERROR Class.MaintenanceTicket.getMaintenanceTickets: line 30, column 1

Regards,
Eric
​​​​​​​

 
Hi All,

I have created button which calls javascript method and from script passing arguments to apex:actionFunction. 

actionFunction invokes apex controller method.

once i click on button it generating 2 logs. 
User-added image
among this 2 logs only one log contains debug statement.

VF code:
 
<apex:actionFunction action="{!split}" name="methodOneInJavascript2" reRender="resultofjs"  >
            <apex:param name="selectedStringValues"   assignTo="{!selectedStringValues}"  value="" /> 
            <apex:param name="selectedDoubleValues"   assignTo="{!selectedDoubleValues}"  value="" />
            <apex:param name="selectedIntegerValues"  assignTo="{!selectedIntegerValues}"  value="" />
        </apex:actionFunction>



<script>
function test(){
        var list=' ';
        var list2=' ';
        var list3=' ';
        var i,j,k;
        for(i=1;i<={!stringsize};i++){
            if(document.getElementById(i).checked == true){
                list += document.getElementById(i).value + '#';
                
            }
        }
        for(j={!stringsize+1};j<={!doublesize};j++){
            if(document.getElementById(j).checked == true){
                list2 += document.getElementById(j).value + '#';
            }
        }
        for(k={!doublesize+1};k<={!integersize};k++){
            if(document.getElementById(k).checked == true){
                list3 += document.getElementById(k).value + '#';
            }
        }
        methodOneInJavascript2(list,list2,list3);       
    }
</script

Apex: Controller
public void test(){
        system.debug('selectedStringValues'+selectedStringValues);
    }


Can someone please help me why it is calling 2 times.
If you want to debug logs do let me know I'll share if required.

Thank you.
 
Hi. I found this apex class sample online. It triggered successfully in my sandbox. The trigger finds a string in a custom field and replaces it with a new character. When deploying to my production org, I realized I don't have a test class.

This is the Apex Trigger:
trigger replaceCharactersSB on rC_Connect__Batch_Upload__c (before insert) {
 String str = '&amp;gt;';
    String str2 = '&gt;';
    String replacement = '>';
    for(rC_Connect__Batch_Upload__c des : trigger.new){
        if(des.SB_donation_allocations__c.contains(str)){
            des.SB_donation_allocations__c = des.SB_donation_allocations__c.replace(str, replacement);
        }
        if(des.SB_donation_allocations__c.contains(str2)){
            des.SB_donation_allocations__c = des.SB_donation_allocations__c.replace(str2, replacement);
        }
    }
}

Anyone know how to create a test class for this? Thank you for your help!

I have a question that I'm having a hard time explaining and solving.
So for starters, I've built an aura component where I want to use Lightning:datatable to enter the Amount of an Opportunity that looks like this:

(This is not the actual component I want to use, but for this one I've built an example for better explanation.)

Opportunity.cmp

<aura:component controller="testController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="recordId" type="String"/>
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="errors" type="Object" default="[]"/>
    <aura:attribute name="draftValues" type="Object" default="[]"/>

    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <div style="height: 300px">
        <lightning:datatable
            columns="{! v.columns }"
            data="{! v.data }"
            keyField="Id"
            errors="{! v.errors }"
            draftValues="{! v.draftValues }"
            onsave="{! c.handleSaveEdition }"
        />
    </div>
</aura:component>


OpportunityController.js:
({
	init : function(cmp, event, helper) {
        console.log('no');
		cmp.set('v.columns', [
            {label: 'Opp Name', fieldName: 'Name', type: 'Text', editable: false },
            {label: 'Amount', fieldName: 'Amount', type: 'currency', typeAttributes: {currencyCode: { fieldName: 'CurrencyIsoCode' }}, editable: true}
        ]);
        
        helper.fetchOpps(cmp);
	},
    
    handleSaveEdition: function (cmp, event, helper) {
        var draftValues = event.getParam('draftValues');
		console.log(draftValues);
        helper.saveEdition(cmp, draftValues);
    }
})


OpportunityHelper.js:
({
    fetchOpps : function(cmp) {
        let getOpp = cmp.get('c.getOpp');
        getOpp.setParams({OppId : cmp.get('v.recordId')});
        getOpp.setCallback(this, function(response){
            if(response.getState() == 'SUCCESS'){
                console.log(response.getReturnValue());
                cmp.set('v.data', response.getReturnValue());
            }
        });
        $A.enqueueAction(getOpp);
    },
    
    saveEdition : function(cmp, draftValues) {
        var self = this;
        console.log(draftValues);
        let saveOpps = cmp.get('c.saveOpps');
        saveOpps.setParams({opps : draftValues});
        saveOpps.setCallback(this, function(res){
            if(res.getState() == 'SUCCESS'){
                cmp.set('v.errors', []);
                cmp.set('v.draftValues', []);
                self.fetchOpps(cmp);
            } else if (res.getState() === "ERROR") {
                var errors = response.error;
                console.error(errors);
            }
        });
        $A.enqueueAction(saveOpps);
    }
})



Apex Controller = testController.apxc
public class testController {
    @AuraEnabled
    public static List<Opportunity> getOpp(String OppId){
        return [SELECT Id, Name, CurrencyIsoCode, FORMAT(Amount) FROM Opportunity WHERE Id =: OppId];
    }
    
    @AuraEnabled
    public static void saveOpps(List<Opportunity> opps){
        System.debug(opps);
        update opps;
    }
}


Organization information:
Currency: SEK

Enabled currencies: SEK and USD, both having 2 decimal places.

So the issue I have is that this component is behaving odd.
My locale is Swedish, the Opportunity Currency is set to USD.


When I edit the amount field to be 123,45 and save, the saved value is: 12 345,00 US$.

Why is that?
One more question, if I set the value to 123,4 it gets turned into 123,40 US$ but the value is saved as 12,00 US$.


The reason to why I'm using FORMAT(Amount) is because I would like to have the value to be the local currency setting for the record, even when using multi-currencies, but for now this won't let me use decimals for this.

 

Images for trying to explain further:

The amount start at 12,00 US$
So the Opporunity starts with an Amount of 12,00 US$.
I want to set it to 12,34:

User-added image
After saving and retrieving record from database again:
User-added image

Hi Everyone!
I am new to this. 
I have a string as:
String str = '{
         "@microsoft.graph.downloadUrl": "https://ww.google.com",
         "createdDateTime": "xyz"}';

I want to get the value of @microsoft.graph.downloadUrl and https://ww.google.com

I am using substringBetween but it is not working.
How to get these value and store in some variable.
I will be very grateful. 

Thank you in advance!

Hi All,

I have to compare two string vales in apex whether they are same vales or not. Could anyone please help me.  

String str1 = Pay TV;AVOD;Basic TV;
String str2 = Basic TV;Pay TV;AVOD;

Thanks,
Anil Kumar
Error says "You might not have the required permissions, or the named credential "ProjectService" might not exist."                                 t .
Hi ,
  • My parent objet Test_Campaign__c have lookup Core_Campaign_Model__c on itself.
  • My child object have lookup field Test_Campaign__c to Test_Campaign__c 
My need is to link child records to parent every time new parent is created with Core_Campaign_Model__c   equal child.Test_Campaign__c

Here's my trigger : 
 
trigger TRG_LinkCampaing on Test_Campaign__c (after insert,after update) {

    
    set<Id> ParID = new set<Id>();
    
    
    for(Test_Campaign__c TestCamp : Trigger.new)
    {
      ParID.add(TestCamp.Core_Campaign_Model__c);
    }
    List<Test_Scenario__c> TS = [Select Id , Test_Campaign__c from Test_Scenario__c where  Test_Campaign__c In :ParID ];
    List<Test_Campaign__c> TC = [Select Id,name from Test_Campaign__c where Id = : Trigger.new];

     List<Test_Scenario__c> TestCampaToUpdate = new List<Test_Scenario__c>();
    for (Test_Scenario__c Testsc : TS){
         
       Testsc.Test_Campaign__c = TC[0].Id;
        TestCampaToUpdate.add(Testsc);
        
    }
    update TestCampaToUpdate;
}

This trigger works fine but only one time due to TC[0].Id , how can i avoid this?
Here is my code. Please help me with the testclass.
public class AccountContactListController { 
   
   
    @AuraEnabled
    public static List<Contact> fetchAccts(id recordId, String pageSize, String pageNumber) {
         List<Contact> conlist = new List<Contact>(); 
        ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(Database.getQueryLocator('SELECT Id, Name, Title, Status__c, Email, Phone, AccountId, Account_Name_Formula__c FROM Contact where Flag_For_Deletion__c = false AND (AccountId =: recordId OR Account.ParentId =: recordId OR Account.Parent.ParentId =: recordId OR Account.Parent.Parent.ParentId =: recordId OR Account.Parent.Parent.Parent.ParentId =: recordId) ORDER BY Status__c ASC, Name ASC'));
         ssc.setpagesize(Integer.valueOf(pageSize));
        ssc.setPageNumber(Integer.valueOf(pageNumber));
         conlist = (List<Contact>)ssc.getRecords();
        return  conlist;  
      }
Thanks in advance.
Hello community!  I am having trouble creating a test class for the following code.  Any assistance would be greatly appreciated. Thank you in advance for your help!

global class Reassign implements Schedulable {
    global void execute(SchedulableContext ctx) {
        // Define 'inprogress' and 'newqueue' string variables
        String inprogress;
        String newqueue;
        
        // Find 'In Progress' queue Id and assign to 'inprogress'
        inprogress = [SELECT Id from Group where Name = 'In Progress' and Type = 'Queue'].Id;
        // Find 'New' queue Id and assign to 'newqueue'
        newqueue = [SELECT Id from Group where Name = 'New' and Type = 'Queue'].Id;
        
        // Create lists for cases
        List<Case> cases1 = [SELECT Id, CaseNumber, OwnerId
                            FROM Case
                            WHERE RecordTypeId = '0124u00000060pmAAA' 
                            AND (Status = 'In Progress' OR Status = 'Outreach Attempted')];
        
        List <Case> cases2 = New List<Case>();
        
        List<Case> newcases1 = [SELECT Id
                              From Case
                              Where RecordTypeId = '0124u00000060pmAAA'
                              AND Status = 'New'];
        
        List <Case> newcases2 = New List<Case>();
        
        // Change the owner and status for each Case in the list and add to respective queue
        for (Case c : cases1){
            c.OwnerId = inprogress;
            c.Status = 'In Progress';
            cases2.add(c);
        }
        update cases2;
        
        for (Case d : newcases1){
            d.OwnerId = newqueue;
            newcases2.add(d);
        }
        update newcases2;
    }
}
Any Help would be much apricated I created an Apex Trigger and am having trouble writing the test class for code coverage really green when it comes to this 

Triger 
trigger updateCustomDev on Custom_Programming__c (before Insert) {
  for (Custom_Programming__c Custom : trigger.new) {

    //SQL statement to lookup price 
    List<PricebookEntry> sqlResult = [SELECT UnitPrice 
        FROM PricebookEntry 
        WHERE Product2.Name = 'Custom Development'
                               AND PriceBook2.Name='DAKCS'];

    //save the returned SQL result inside the field 
    Custom.Hourly_Cost__c = sqlResult[0].UnitPrice;
  }    
}

Test Class
@IsTest
public class TestupdateCustomDev {
    @IsTest static void testHourlyCost(){
        //Create Custom
        Custom_Programming__c c = new Custom_Programming__c(Name='Test',Custom_State__c='Active',Custom_Type__c='Custom',Status__c='New');
        
        Test.startTest();
        Database.SaveResult result = Database.insert (c, true);
         System.assert(result.isSuccess());
        Test.stopTest();
    }
}

I was hoping this would be really simple all I want the trigger to do is update a field with an entry from pice book entry.

Thanks again
Trying to create an Apex trigger to query the price-book entries and place the result in a custom field can someone please tell me what i am doing wrong 
get two problems Expression must be a list type: pricebookEntry 
and a value cannot be stored to Hourly_Cost__c in type Custom_Programming__C


trigger updateCustomDev on Custom_Programming__c (after update) {
  

    //SQL statement to lookup price 
    PricebookEntry sqlResult = [SELECT UnitPrice 
        FROM PricebookEntry 
        WHERE Product2.Name = 'Custom Development'
                               AND PriceBook2.Name='DAKCS'];

    //save the returned SQL result inside the field 
    Custom_Programming__c.Hourly_Cost__c = sqlResult[0].UnitPrice;
      
}
Hello,
can you help me write a test for this trigger plz
trigger ContractTrigger on Contract (after update) {
    Public String[] statut_activated   {set;get;}
    Public String[] statut_waiting   {set;get;}
    Public String[] statut_terminated   {set;get;}
    
    statut_activated = new String[] {'Accepted','Accepted2'};
    statut_waiting = new String[] {'waiting','waiting2'}; 
    statut_terminated = new String[] {'terminated','terminated2'}; 

    
    List<Decimal> listAmount= new List<Decimal>();
	set<Id> AccountIds = new set<Id>();
    for(Contract c : Trigger.new){
    if(c.AccountId != null)
    	AccountIds.add(c.AccountId);
    }

  

    Map<String, Contract> cntrMap  = new Map<String, Contract>();
    
    for(Contract contr : [Select Id,contract_stat__c,amount__c From Contract Where AccountId IN: AccountIds]){
        cntrMap.put(contr.Id , contr);
         
         Account acc = [SELECT Id,st__c FROM Account WHERE Id IN: AccountIds];	
        if(contr.amount__c > 0){
            listAmount.add(contr.amount__c);
        }else{
          acc.checked__c=FALSE;
          update acc;
        }
        
       
        if(statut_activated.contains(contr.contract_stat__c)){
             cntrMap.put(contr.contract_stat__c , contr);     
             acc.st__c='customer';   
             update acc;
             break;
            
            /* Contrat En attente*/ 
        }else if(statut_waiting.contains(contr.contract_stat__c)){

             acc.st__c='customer_type2';
             update acc;
             break;
        /*  Contrat En Terminé  */ 
        }else if(statut_terminated.contains(contr.contract_stat__c)){
		
             acc.st__c='customer_type3';
             update acc;
             break;     
        }else{

             acc.st__c='customer_other';
             update acc;       
        }
    }

    for(Decimal l : listAmount){
    	if(l > 0){
          Account acc = [SELECT Id,st__c FROM Account WHERE Id IN: AccountIds];	
          acc.checked__c=TRUE;
          update acc;
         }
	}

}

Thanks for help 
Hi and thanks in advance.

I want to see the records that were created or updated via Database.UpsertResult.  The records are being updated and/or created, but I am not getting ANY results from the for loop. 

Any ideas?
 
Schema.SObjectField f = Case.Ticket_Number__c; 

       Database.UpsertResult [] cr = Database.upsert(toBeUpsertCases, f, false);  
        
        // I want to see what was updated / created        
        for(Integer index = 0; index < cr.size(); index++ )
        {
            if(cr[index].isSuccess())
            {
                if(cr[index].isCreated())
                {
                    System.debug(toBeUpsertCases[index].Ticket_Number__c + ' was created');
                } else 
                 {
                   System.debug(toBeUpsertCases[index].Ticket_Number__c + ' was updated'); 
                 }
            }
        }// end for loop

Eric

We have created a Lightning URL list button and added it to a related list in One Layout.

But, after the Winter-21 updates, we started to receive an issue.

So when we try to click on it, we are getting redirected to Classic version and giving error saying "URL No Longer Supported". This is an intermittent issue.

Can someone help me to fix this issue

  • November 12, 2020
  • Like
  • 0

I have a question that I'm having a hard time explaining and solving.
So for starters, I've built an aura component where I want to use Lightning:datatable to enter the Amount of an Opportunity that looks like this:

(This is not the actual component I want to use, but for this one I've built an example for better explanation.)

Opportunity.cmp

<aura:component controller="testController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="recordId" type="String"/>
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="errors" type="Object" default="[]"/>
    <aura:attribute name="draftValues" type="Object" default="[]"/>

    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <div style="height: 300px">
        <lightning:datatable
            columns="{! v.columns }"
            data="{! v.data }"
            keyField="Id"
            errors="{! v.errors }"
            draftValues="{! v.draftValues }"
            onsave="{! c.handleSaveEdition }"
        />
    </div>
</aura:component>


OpportunityController.js:
({
	init : function(cmp, event, helper) {
        console.log('no');
		cmp.set('v.columns', [
            {label: 'Opp Name', fieldName: 'Name', type: 'Text', editable: false },
            {label: 'Amount', fieldName: 'Amount', type: 'currency', typeAttributes: {currencyCode: { fieldName: 'CurrencyIsoCode' }}, editable: true}
        ]);
        
        helper.fetchOpps(cmp);
	},
    
    handleSaveEdition: function (cmp, event, helper) {
        var draftValues = event.getParam('draftValues');
		console.log(draftValues);
        helper.saveEdition(cmp, draftValues);
    }
})


OpportunityHelper.js:
({
    fetchOpps : function(cmp) {
        let getOpp = cmp.get('c.getOpp');
        getOpp.setParams({OppId : cmp.get('v.recordId')});
        getOpp.setCallback(this, function(response){
            if(response.getState() == 'SUCCESS'){
                console.log(response.getReturnValue());
                cmp.set('v.data', response.getReturnValue());
            }
        });
        $A.enqueueAction(getOpp);
    },
    
    saveEdition : function(cmp, draftValues) {
        var self = this;
        console.log(draftValues);
        let saveOpps = cmp.get('c.saveOpps');
        saveOpps.setParams({opps : draftValues});
        saveOpps.setCallback(this, function(res){
            if(res.getState() == 'SUCCESS'){
                cmp.set('v.errors', []);
                cmp.set('v.draftValues', []);
                self.fetchOpps(cmp);
            } else if (res.getState() === "ERROR") {
                var errors = response.error;
                console.error(errors);
            }
        });
        $A.enqueueAction(saveOpps);
    }
})



Apex Controller = testController.apxc
public class testController {
    @AuraEnabled
    public static List<Opportunity> getOpp(String OppId){
        return [SELECT Id, Name, CurrencyIsoCode, FORMAT(Amount) FROM Opportunity WHERE Id =: OppId];
    }
    
    @AuraEnabled
    public static void saveOpps(List<Opportunity> opps){
        System.debug(opps);
        update opps;
    }
}


Organization information:
Currency: SEK

Enabled currencies: SEK and USD, both having 2 decimal places.

So the issue I have is that this component is behaving odd.
My locale is Swedish, the Opportunity Currency is set to USD.


When I edit the amount field to be 123,45 and save, the saved value is: 12 345,00 US$.

Why is that?
One more question, if I set the value to 123,4 it gets turned into 123,40 US$ but the value is saved as 12,00 US$.


The reason to why I'm using FORMAT(Amount) is because I would like to have the value to be the local currency setting for the record, even when using multi-currencies, but for now this won't let me use decimals for this.

 

Images for trying to explain further:

The amount start at 12,00 US$
So the Opporunity starts with an Amount of 12,00 US$.
I want to set it to 12,34:

User-added image
After saving and retrieving record from database again:
User-added image