• pigginsb
  • NEWBIE
  • 355 Points
  • Member since 2011
  • Senior Salesforce Developer
  • Flagstar Bank


  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 71
    Replies
I have value like '199924' where 1999 => Year and 24 is week.

I want to get the month of the week (24) and date of the weeks first day. How can i do this in Apex ?
Hello Everyone, 

I've been trying to work on code that was left to our ORG by a developer who is no longer supporting us.  Not being too familiar with Apex, this is proving to be a daunting task for us and blocking us from implementing the triggers/classes that we've been working on.  I know it's a lengthy bit of code, but if someone could offer some assistance we'd be really grateful.  Currently we're getting the SQOL 101 errors with this code:
 
trigger UpdateTruckInventoryByOpportunity_Trgr on Opportunity (before update,before insert,after update, after insert, after delete, after undelete) {
    List<Truck_Inventory__c> lstTruck2Update = new List<Truck_Inventory__c>();
    
    Set<String> rt2bypass = new Set<String>{'Used Truck Quote','Accessory Order'};     
    Map<Id,RecordType> usedTruckQuoteRT = new Map<Id,RecordType>([Select SobjectType,Name,Id From RecordType Where SobjectType ='Opportunity' and Name in :rt2bypass]);
    
    RecordType usedRT = [Select SobjectType,Name,Id From RecordType Where SobjectType ='Truck_Inventory__c' and Name = 'Used' LIMIT 1];
    Map<Id,Truck_Inventory__c> mapNotUsedTruckInv = new Map<Id,Truck_Inventory__c>([Select Id,RecordTypeId From Truck_Inventory__c Where RecordTypeId =:usedRT.Id]);
    Set<String> setTruckInventories = new Set<String>();
    
    if(Trigger.isAfter){
        if(Trigger.isUpdate){
            for(Opportunity opp:Trigger.new){
                if(usedTruckQuoteRT.get(opp.RecordTypeId)==null){
                    

                     if(opp.Truck_Inventory__c!=null){
                        if(opp.StageName == 'Lost Deal - Truck Built' || opp.StageName == 'Lost Deal - Truck Not Built'){
                            lstTruck2Update.add(new Truck_Inventory__c(Id=opp.Truck_Inventory__c,Sold__c=false, Related_Quote_SO__c=null, Customer__c = null));
                        }else if(opp.StageName == 'Sales Order - Pending' || opp.StageName == 'Sales Order - Complete'){
                            lstTruck2Update.add(new Truck_Inventory__c(Id = opp.Truck_Inventory__c,Customer__c = opp.AccountId, Sold__c=true,Related_Quote_SO__c=opp.Id));
                        }else{
                            lstTruck2Update.add(new Truck_Inventory__c(Id=opp.Truck_Inventory__c, Sold__c=true,Related_Quote_SO__c=opp.Id));
                        }
                    }
                    
                    Opportunity oldOpp = Trigger.oldmap.get(opp.Id);
                    if(oldOpp.Truck_Inventory__c!=null && oldOpp.Truck_Inventory__c != opp.Truck_Inventory__c){
                        lstTruck2Update.add(new Truck_Inventory__c(Id=oldOpp.Truck_Inventory__c,Sold__c=false, Related_Quote_SO__c=null, Customer__c = null));
                    }
                    
                }
            }
        }else if(Trigger.isInsert || Trigger.isUndelete){
            for(Opportunity opp:Trigger.new){
                if(usedTruckQuoteRT.get(opp.RecordTypeId)==null) {
                    if(opp.Truck_Inventory__c!=null){         
                        lstTruck2Update.add(new Truck_Inventory__c(Id=opp.Truck_Inventory__c, Sold__c=true,Related_Quote_SO__c=opp.Id));
                    }
                }
            }
        }else if(Trigger.isDelete){
            for(Opportunity opp:Trigger.old){
                if(usedTruckQuoteRT.get(opp.RecordTypeId)==null){
                    if(opp.Truck_Inventory__c!=null){
                        lstTruck2Update.add(new Truck_Inventory__c(id=opp.Truck_Inventory__c,Sold__c=false, Related_Quote_SO__c=null));
                    }
                }
            }
        }
        if(!lstTruck2Update.isEmpty()){
            update lstTruck2Update;
        }
    
    }
    else{
        
        for(Opportunity opp:Trigger.new){
            if(usedTruckQuoteRT.get(opp.RecordTypeId)==null) {
                if(opp.Truck_Inventory__c!=null){
                    if(!mapNotUsedTruckInv.containsKey(opp.Truck_Inventory__c)){    
                        setTruckInventories.add(opp.Truck_Inventory__c);
                    }          
                }
            }
        }
        
        if(!setTruckInventories.isEmpty()){
            Map<String,String> mTruckInParent = new Map<String,String>();
            for(Truck_Inventory__c ti :[Select Truck__c, Id From Truck_Inventory__c where Id in :setTruckInventories]){
                mTruckInParent.put(ti.Id, ti.Truck__c);
            }
         
            for(Opportunity opp:Trigger.new){
                if(usedTruckQuoteRT.get(opp.RecordTypeId)==null) {
                    opp.Truck__c = mTruckInParent.get(opp.Truck_Inventory__c);
                }
            }
        }
    }
}

 
Hello,

Below is a code I created for validating contact deletion. But it dosent seem to work, I'm able to delete the contacts from accounts whose country is India. The trigger is active. Can someone please let me know the reason ?

1    trigger SV1 on Contact (before delete) {
2        //donot allow deletion of any contact whose account country is India
3        for (Contact cont : trigger.old){
4                    if(cont.Account.country__c == 'India'){
5                Cont.addError ('You Cannot delete the contacts of Indian accounts');
6            }
7            
8        }
9            
10    }

Regards,
Usha

 
Hello,

I have the below code to update the country field if the state field is filled. I was able to save the trigger but I'm getting the following error while I try to save a record with the state field. I have System Administrator profile & ave Read/Write Access on Account object..

Please let me know where I have gone wrong, I'm an administrator trying to learn Apex.

1 trigger SU on Account (After update, After insert) {
2     for(Account acct : Trigger.new){
3         if (acct.Billing_state__c == 'Karnataka'){
4             acct.Country__c = 'India';
5             Update acct;
6         }
7     }
8
9 }
10 /** Unsucessful - get this error - Apex trigger SU caused an unexpected exception, contact your administrator: 
11 *SU: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.SU: line 4, column 1
12 **/

 Apex trigger SU caused an unexpected exception, contact your administrator: SU: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.SU: line 4, column 1


Thanks,
Usha


 
Hi,

I was wondering if there is a way to take a picklist and it's values from one object and using apex class, we create another picklist and the same values on another object.

Essentially, i want to take the Campaign Type field (format: picklist) and its various values and create a picklist field on customObj1__c that has the same picklist values. How would this be possible? I am having trouble trying to figure out how I can use apex class to do this. 

Another scenario that would be okay, if we assume that the customObj1__c already has a picklist field fieldPick__c and certain values. Is there a way to take the Campaign type picklist values and save them as the fieldPick__c values on the customObj1__c object?
  • November 10, 2015
  • Like
  • 0
Modifying some existing code that updates a record and then redirects to a new page. I need to change it so that it runs a query to identify the correct record to update, and then updates the record.
 
public PageReference saveAttendee(){
     
         List<CnP_PaaS_EVT__Event_attendee_session__c> attendee = [SELECT Id, Name, DTCI_Agreement_Active__c, CnP_PaaS_EVT__First_name__c, CnP_PaaS_EVT__Last_name__c, DTCI_Ticket_Level__c, CnP_PaaS_EVT__EventId__r.CnP_PaaS_EVT__category__r.name                                                                                                                                                          
                                                                       FROM CnP_PaaS_EVT__Event_attendee_session__c                                                                            
                                                                       WHERE CnP_PaaS_EVT__Registrant_session_Id__c =:registrantId 
                                                                            AND DTCI_Ticket_Level__c =: ticketLevel           
                                                                            AND DTCI_Attendee_Info_Assigned__c = FALSE
                                                                       ORDER BY DTCI_Ticket_Order__c
                                                                       LIMIT 1
                                                                      ];
        
        attendeeId = attendee.Id;                                                              
        attendeeFirstName = attendee.CnP_PaaS_EVT__First_name__c;
        attendeeLastName = attendee.CnP_PaaS_EVT__Last_name__c;
        mailingCity = attendee.DTCI_Mailing_City__c;
        mailingCountry = attendee.DTCI_Mailing_Country__c;
        mailingCounty = attendee.DTCI_Mailing_County__c;
        mailingState = attendee.DTCI_Mailing_State__c;
        mailingStreet = attendee.DTCI_Mailing_Street__c;
        mailingZip = attendee.DTCI_Mailing_ZIP_Postal_Code__c;
       
                                   
        update attendee;                                        
        
PageReference sendToReleaseForm = new PageReference('/apex/DTCI_Release_Form_Page_AB' + '?attendeePageId=' + attendee.id + '&registrantPageId=' + registrantId + '&eventPageId=' + eventId + '&releasePageType=' + attendee.DTCI_Release_Type__c);  
        sendToReleaseForm.setRedirect(true);                        
        return sendToReleaseForm;     
    }

How can I query the object to find the next suitable record to update and still create the PageReference I need to move forward?

 
Hi folks,
Found something interesting while researching regarding another posted bug:
https://developer.salesforce.com/forums/ForumsMain?id=906F0000000BYt2

I've got a trigger and a test class for it. The trigger basically takes a related list of values and concatenates it, saving it as part of the Account object. My test cases all fail, showing the following error:
Class.TMCR_testAccountInterestList.test_addInterest: line 51, column 1
14:18:05.697 (6697124228)|FATAL_ERROR|System.AssertException: Assertion Failed: Expected: foo
Interest0
Interest1
Interest2
, Actual: foo
Interest0
Interest1
Interest2

The data looks identical. Just to be sure, I put the strings through a hex conversion to compare their hex values and they are indeed different.

My question is what gives? Why are they different? The data going in should be the same.

For reference, here are is the Trigger:
trigger Account_UpdateAccountInterestsList on Interest__c (after delete, after insert, after undelete, 
after update) {
	Interest__c[] interests;
    if (Trigger.isDelete) 
        interests = Trigger.old;
    else
        interests = Trigger.new;
	Set<ID> affected_accounts = new Set<ID>();
	Map<ID, Set<String>> account_interests = new Map<ID, Set<String>>();
	for(Interest__c interest: interests){
		affected_accounts.add(interest.Account__c);
		account_interests.put(interest.Account__c, new Set<String>());
	}

	List<Interest__c> all_interests = [
		SELECT Id, Account__c, Interest__r.Name
		FROM Interest__c
		WHERE Account__c IN :affected_accounts
		ORDER BY Interest__r.Name
	];
	List<Account> accounts_to_update = [
		SELECT Id, Account_Interests_List__c
		FROM Account
		WHERE Id IN :affected_accounts
	];
	
	for(Interest__c interest: all_interests){
		account_interests.get(interest.Account__c).add(interest.Interest__r.Name);
	}
	for(Account account: accounts_to_update){
		account.Account_Interests_List__c = Util_TMCR.combineList(account_interests.get(account.Id));
	}
	
	update accounts_to_update;
}
Here is the test class:
@isTest
private class TMCR_testAccountInterestList {
	static Account getAccount(){
		Util_TMCR_DataFactory.accounts account = new Util_TMCR_DataFactory.accounts();
		Account acc = [
			SELECT Id, Account_Interests_List__c
			FROM Account WHERE Name = :account.get('name')
		];
		return acc;
	}
	static Interests__c addInterest(String name){
		Interests__c new_interest = new Interests__c(Name = name);
		insert new_interest;
		return new_interest;
	}
	static Interest__c addToAccount(Account acc, Interests__c interest){
		Interest__c acc_interest = new Interest__c(Interest__c = interest.Id, Account__c = acc.Id);
		insert acc_interest;
		return acc_interest;
	}
	
	@testSetup
	static void setup(){
		List<Interests__c> interests = new List<Interests__c>();
		List<Interest__c> account_interests = new List<Interest__c>();
		for(Integer i=0; i<3;i++){
			interests.add(addInterest('Interest' + i));
		}
		Util_TMCR_DataFactory.accounts account = new Util_TMCR_DataFactory.accounts();
		Account acc = account.generate();
		for(Interests__c interest: interests){
			account_interests.add(addToAccount(acc, interest));
		}
	}
	
    static testMethod void test_addInterest() {
		test.startTest();
		Account account = getAccount();
		Interests__c interest = addInterest('foo');
		Interest__c acc_interest = addToAccount(account, interest);
		test.stopTest();
		
		String concat = Util_TMCR.combineList(new List<String>{'foo', 'Interest0', 'Interest1', 'Interest2'});
		Account acc = getAccount();
		System.assertEquals(concat, acc.Account_Interests_List__c);
    }
    static testMethod void test_changeInterest() {
    	test.startTest();
		Interests__c interest = addInterest('foo');
		Interest__c acc_interest = [SELECT Id, Interest__c from Interest__c WHERE Interest__r.Name = 'Interest0' LIMIT 1];
		acc_interest.Interest__c = interest.Id;
		update acc_interest;
    	test.stopTest();
    	List<String> mylist = new List<String>{'foo', 'Interest1', 'Interest2'};
    	String concat = Util_TMCR.combineList(mylist);
    	Account acc = getAccount();
    	System.assertEquals(concat, acc.Account_Interests_List__c);
    }
    static testMethod void test_deleteInterest(){
    	test.startTest();
		Interests__c interest = [SELECT Id, Name FROM Interests__c WHERE Name = 'Interest0' LIMIT 1];
		delete interest;
    	test.stopTest();
    	List<String> mylist = new List<String>{'Interest1', 'Interest2'};
    	String concat = Util_TMCR.combineList(mylist);
    	Account acc = getAccount();
    	System.assertEquals(concat, acc.Account_Interests_List__c);
    }
    static testMethod void test_undeleteInterest(){
    	test.startTest();
		Interests__c interest = [SELECT Id, Name FROM Interests__c WHERE Name = 'Interest0' LIMIT 1];
		delete interest;
		undelete interest;
    	test.stopTest();
    	List<String> mylist = new List<String>{'Interest0', 'Interest1', 'Interest2'};
    	String concat = Util_TMCR.combineList(mylist);
    	Account acc = getAccount();
    	System.assertEquals(concat, acc.Account_Interests_List__c);
    }
}
Finally, here is the function that concatenates both the expected list and the actual list:
public static String combineList(List<String> items){
        String out = '';
        String delimiter = '\n';
        for(String val : items){
        	out = out + val;
        	if(val.right(1) != delimiter){
        		out = out + delimiter;
        	}
        }
        return out;
    }





 
Hi I have a wrapper class in which i have a boolean variable. Now i have a list of Wrapper Class which i have to show on VF page, now i want to show the table in such a way that true values comes first and then false. Now i want to prepare a wrapperlist such that all true records come first and then records with false value.
This is my first attempt at an APEX trigger or any kind of Apex.

I am trying to update a field in a child object from a field in a parent object.  It is giving an error on line 4:  Parent_Object.Parent_Custom_Field__r variable is not found

ie a Parent_Custom_Field__c from Parent_Object__c into the Child_Object__c Child_Custom_Field__c

trigger NEWTRIGGER on Child_Object__c (before insert) {

    For (Child_Object__c ChildField : Trigger.new)
        
    {ChildField.Child_Custom_Field=Parent_Object.Parent_Custom_Field__r;
    }
}

I've built a simple two screen Visualforce sequence on an opportunity.

The first Visualforce page is used to upload documents to the opportunity.

 

This is the second VF page, used to update a field on the opportunity.

<apex:page standardController="opportunity" extensions="Digilant_UpdateRating" showHeader="true" sidebar="true">
    <apex:form >
    
    <apex:pageBlock >
        <apex:pageBlockButtons >
            <apex:commandButton value="Notify Sales" Action="{!saveRating}"/>
            <apex:commandButton value="Cancel" Action="{!cancel}"/>
            </apex:pageBlockButtons>
        <apex:pageBlockSection title="Select Rating" columns="1">    
            <apex:inputField value="{!opportunity.Rating__c}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
    
    </apex:form>
</apex:page>

 

The controller should retrieve set the recId property from a URL parameter, use this to execute a SOQL query, and then update the retrieved record. However, the value is not getting pushed to the record and the update is failing. No error message is being generated.

 

This is the controller code.

public class Digilant_UpdateRating
{
    public Id recId{get;set;}
    public PageReference pr{get;set;}
    public ApexPages.StandardController ctrl;
    public opportunity opp;

    public Digilant_UpdateRating(ApexPages.StandardController controller) {
        ctrl = controller;
        recId = ApexPages.CurrentPage().getParameters().get('opportunityid');
        this.opp = [SELECT Id, rating__c FROM Opportunity WHERE Id =: recId];
        System.debug('opportunity is' + opp.id);
    }
    
    public pageReference saveRating()
    {
        update opp;
        pr = new PageReference('/'+recId);
        pr.setRedirect(true);
        return pr;
    }
}

 

 

Does anyone have a working example of a trigger and class written to implement the TDTM functionality from the HEDA managed package? I have installed the managed package in a dev org, and I am encountering class visibility issues when I try to save the following trigger, which is modeled after the triggers from the unmanaged version of the package (pulled down from GitHub).
trigger TestObject on Attachment (after delete, after insert, after undelete, 
after update, before delete, before insert, before update) {

    hed.TDTM_TriggerHandler handler = new hed.TDTM_TriggerHandler();  
    handler.run(Trigger.isBefore, Trigger.isAfter, Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, 
        Trigger.isUnDelete, Trigger.new, Trigger.old, Schema.Sobjecttype.Attachment, 
        new hed.TDTM_ObjectDataGateway());
}
I am using the "hed" namespace, which worked when my class needed to extend TDTM_Runnable, but I am seeing an error due to TDTM_TriggerHandler not being visible. Also, if I use my class that extends TDTM_Runnable, I see the same visibility error with TDTM_ObjectDataGateway.

I really don't need a trigger on Attachment. I just wanted to see how simple it would be to get this working. Does anyone have a working example or some insight to share?
We are using Apex to create Cases in a customer community, and we have found that email notifications are not being sent to queue members when the Case is successfully assigned to a queue via the default assignment rule. Everything we've seen says to set the DML Options as shown in the below code, and this exact pattern is working elsewhere for Leads.
public class CaseTest {
    public static void InsertTest(String value, String accountId, String contactId) {
    
        Case aNewCase = new Case(
            AccountId = anAccountId,
            ContactId = aContactId,
            Origin = 'Customer Community'
        );

        aNewCase.Reason = 'Other';
        aNewCase.Subject = value;
        aNewCase.Description = value;

        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.assignmentRuleHeader.useDefaultRule= true; // successfully assigns case
        dmo.EmailHeader.triggerAutoResponseEmail = true; // but no email goes to the contact
        dmo.EmailHeader.triggerUserEmail = true; // and no email goes to the queue members
            
        aNewCase.setOptions(dmo);

        insert aNewCase;
    }
}
Additionally, when we create cases via the Salesforce UI, they are assigned correctly and the emails go out as expected. By this we conclude that there is no issue with the queue, the email template, or the email addresses of the assigned users.

Has anyone else encountered this issue, or better yet resolved it?
 

I am trying to perform a SOSL search with the search term, '333-4444-55555', and for some reason it will not return any rows.

 

I am escaping the reserved characters, described in the reference guide...http://www.salesforce.com/us/developer/docs/soql_sosl/salesforce_soql_sosl.pdf

 

Rows will return if I search for '333-4444*', or for '333-*', or even for '333-4444*55555'.

 

But no rows return if the second dash is included in the term.

 

Please let me know if you can help with this.

 

Thanks!

Here's something that would have saved me some time if I had found it by searching. I have a pageBlockSection with two columns, and I wanted to include two fields in one column with a single label applied to both fields, just like the Contact Edit page where the label "First Name" appears before the Salutation and FirstName fields.

 

Only the label was not aligning with the other labels in the same column, until I tried the following. To my surprise, VF didn't recognize this as more than two child components. Hope it helps someone!

 

<apex:pageBlockSectionItem >
                  <apex:outputLabel value="First Name"/>
                  <apex:inputField value="{!Contact.Salutation}">
                      <apex:inputField value="{!Contact.FirstName}"/>
                  </apex:inputField>
</apex:pageBlockSectionItem>

Hi all,

We are a small charity that use nonprofitforce as our database.
We have a tab for creating household for a contact and it's suddenly not working recently.

I have asked salesforce support and she said it is a Custom S control which is a custom coding. We are only a standard customer and do not have any developer support.

Can anyone please help?

Please find below the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<script language="javascript" src="https://www.salesforce.com/services/lib/ajax/beta3.3/sforceclient.js?browser=true" type="text/javascript"></script>
<script id="clientEventHandlersJS" language="javascript">
<!--
function initPage() {
sforceClient.registerInitCallback(setup);
sforceClient.setLoginUrl("https://www.salesforce.com/services/Soap/u/7.0");
sforceClient.init("{!API.Session_ID}", "{!API.Partner_Server_URL_70}", true);
}

//Use this function as the entry point for your DHTML and JAVASCRIPT processing
function setup() {
//create household
var Household = new Sforce.Dynabean('ONEN_Household__c');
var HouseholdArray = new Array(1);
Household.set("Name","{!Contact.FirstName}" + " " + "{!Contact.LastName}" + " Household");    

var mailingstreet = document.getElementById('fixMailingStreet').innerText;
Household.set("MailingStreet__c", mailingstreet );


Household.set("MailingCity__c","{!Contact.MailingCity}");
Household.set("MailingState__c","{!Contact.MailingState}");
Household.set("MailingPostalCode__c","{!Contact.MailingPostalCode}");
Household.set("MailingCountry__c","{!Contact.MailingCountry}");
Household.set("Recognition_Name__c","{!Contact.FirstName}" + " " + "{!Contact.LastName}");
Household.set("Recognition_Name_Short__c","{!Contact.FirstName}");

HouseholdArray[0] = Household;    
//Call create on the Household
var HouseholdSaveResult = sforceClient.Create(HouseholdArray);
//if it worked, relate the Contacts to the household
if (HouseholdSaveResult[0].success == true) {

//get the object that was returned
CreatedHousehold = HouseholdSaveResult[0];
//create a Contact object for updating
var Contact = new Sforce.Dynabean('Contact');
var ContactArray = new Array(1);
//Set the Id
Contact.set("Id","{!Contact.Id}");    

//Set the Household Id    
Contact.set("ONEN_Household__c", CreatedHousehold.id);
ContactArray[0] = Contact;    
//Call create on the Opportunity.
var ContactSaveResult = sforceClient.Update(ContactArray);
//if it worked, redirect to the Household
if (ContactSaveResult[0].success == true) {    
top.location.replace("/" + CreatedHousehold.id);

} else {
alert("Error updating Contact! " + ContactSaveResult[0].message);
}

} else {
alert("Error in creating household!");
}    
}

//-->
</script>
</head>
<body onload="initPage()">
<div id="fixMailingStreet" style="display: none;">{!Contact.MailingStreet}</div>
</body>
</html>

Thank you.
Kind Regards
Gracia


 
Hello Everyone I am writting a trigger for validating a record not be deleted before 2 years from RECORD CREATION
DATE. I am getting error like 'Date expressions must use Integer or Long' Can someone please help me to 
complete this code. Thanks in advance.


trigger DelTrigger on BD__c (before Delete) {

        for(BD__c ObjInd : Trigger.Old){
            if(Trigger.isDelete){
                if (ObjInd.Date__c != null){
                          Integer noOfMonths = (Date.today() - ObjInd.Date__c)/365*12;
                    if (noOfMonths <= 24 ){
                            ObjInd.addError('Record can not be deleted');
                    }
                }
            }
    }
}

Regards,
Dj
  • September 03, 2017
  • Like
  • 0
How to query account on basis of profile i.e.
I want to see how many records have been edited by system admin or any other profile

Thanks in Advance ...
Please help
When I Press the Save button it saves the values but when I hit F5 or refresh the values are gone, they are not visible on my VF page.
And for this :
  • I have created VF page with standard controller and extensions.
  • created one controller.
  • And I have embedded VF page into Opportunity object.
Any idea how I can achieve this ??
Thanks.
  • September 02, 2017
  • Like
  • 0
I have created a REST API with url like "param1/param2/?query1=value1&query2=value2". The API is working and I am getting the response from Salesfore. But when I tried to create a test class for the above API, I am not getting query values passing from the test class to the API Apex class. I have tried to debug it and I was getting null values for the queey strings passed from the test class. Any idea why test class is not supporting query string in the API URL?
I have value like '199924' where 1999 => Year and 24 is week.

I want to get the month of the week (24) and date of the weeks first day. How can i do this in Apex ?
I am trying to copy value from Opportunity product to Opportunity

Field is TotalPrice on Opportunity Product to RSF_CLD_CB_CommValue__c on Opportunity

below is the code i am using but im getting error


Error: Compile Error:
id,RSF_CLD_CB_CommValue__c from Opportunity)
^
ERROR at Row:1:Column:62
Didn't understand relationship 'Opportunity' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 5 column 51


 
trigger CommValue on OpportunityLineItem (after insert,after update) {

            List<Opportunity> lstOppUpdate = new List<Opportunity>();
                    
               List<OpportunityLineItem> lstOli = [select id,TotalPrice,(select id,RSF_CLD_CB_CommValue__c from Opportunity) 
                        from OpportunityLineItem where id in: trigger.newmap.keyset()];
                    
                
                       
                for(OpportunityLineItem oli : lstOli){
                
                if(oli.TotalPrice != NULL){

            for(Opportunity opp: oli.Opportunity__r){              

                opp.RSF_CLD_CB_CommValue__c += oli.TotalPrice;
                
                lstOppUpdate.add(opp); 
                }
        }

    }

    if(lstOppUpdate.size() > 0){

        update lstOppUpdate;

    }

 
Hi,  I'm working to clean up a messy org and my current challenge is to remove the Volunteers App. There are loads of dependencies to delete including a lot of apex code, before I can uninstall the app.  I'm stuck because the apex test coverage for the org is around 76%, and when I remove the offending apex it drops to 74% which stops the deployment.

How do I find other classes in the org which have minimal or no coverage, so I can cover or delete them.  I read there was a test-coverage console window in the dev console under the  Test tab but I don't see such a thing.

Any help would be greatly appreciated.  Thanks,
Mark

 
We are using Apex to create Cases in a customer community, and we have found that email notifications are not being sent to queue members when the Case is successfully assigned to a queue via the default assignment rule. Everything we've seen says to set the DML Options as shown in the below code, and this exact pattern is working elsewhere for Leads.
public class CaseTest {
    public static void InsertTest(String value, String accountId, String contactId) {
    
        Case aNewCase = new Case(
            AccountId = anAccountId,
            ContactId = aContactId,
            Origin = 'Customer Community'
        );

        aNewCase.Reason = 'Other';
        aNewCase.Subject = value;
        aNewCase.Description = value;

        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.assignmentRuleHeader.useDefaultRule= true; // successfully assigns case
        dmo.EmailHeader.triggerAutoResponseEmail = true; // but no email goes to the contact
        dmo.EmailHeader.triggerUserEmail = true; // and no email goes to the queue members
            
        aNewCase.setOptions(dmo);

        insert aNewCase;
    }
}
Additionally, when we create cases via the Salesforce UI, they are assigned correctly and the emails go out as expected. By this we conclude that there is no issue with the queue, the email template, or the email addresses of the assigned users.

Has anyone else encountered this issue, or better yet resolved it?
 

1.System.QueryException: List has no rows for assignment to SObject
Class.Leadpage.: line 11, column 1 Class.Leadtestss.runTest1: line 28, column 1

2.System.QueryException: List has no rows for assignment to SObject
Class.Leadpage.: line 11, column 1 Class.Leadtestss.runTest2: line 58, column 1

so on...

 
@isTest
public class Leadtestss{  
    static testMethod void runTest1() {
    Account account = new Account();
       account.Name = 'Accc3';
       insert account;         

       Contact contact = new Contact();
       contact.FirstName = 'Todda';
       contact.LastName = 'Wilmss1';
       contact.AccountID = account.Id;
       contact.Email = 'twilms@verisign.conm';
       contact.MobilePhone = '918527116723';
       insert contact; 
              
       Lead lead1 = new Lead();
       lead1.FirstName = 'test';
       lead1.LastName = 'Bcc3'; 
       lead1.company='cc3';      
       insert lead1; 
            
         test.startTest();
         PageReference pageRef1 = Page.Leadpage; // Your page name
         pageRef1.getParameters().put('Id', String.valueOf(lead.Id));
         Test.setCurrentPage(pageRef1);
        Test.setMock(HttpCalloutMock.class, new Leadpagemock());
          ApexPages.StandardController sc1 = new ApexPages.StandardController(lead1);//Instance of your object
         Leadpage testDObj = new Leadpage();
          testDObj.getperformcallout();
           test.stopTest();  
            
    }
    static testMethod void runTest2() {
    Account account = new Account();
       account.Name = 'Accc4';
       insert account;         

       Contact contact = new Contact();
       contact.FirstName = 'Todda1';
       contact.LastName = 'Wilmss2';
       contact.AccountID = account.Id;
       contact.Email = 'twilms@verisign.cnm';
       contact.MobilePhone = '918527117723';
       insert contact; 
              
       Lead lead1 = new Lead();
       lead1.FirstName = 'test1';
       lead1.LastName = 'Bcc4'; 
       lead1.company='cc4';      
       insert lead1; 
            
         test.startTest();
         PageReference pageRef1 = Page.Leadpage; // Your page name
         pageRef1.getParameters().put('Id', String.valueOf(lead.Id));
         Test.setCurrentPage(pageRef1);
        Test.setMock(HttpCalloutMock.class, new Leadpagemock());
          ApexPages.StandardController sc1 = new ApexPages.StandardController(lead1);//Instance of your object
         Leadpage testDObj = new Leadpage();
          testDObj.getperformcallout1();
           test.stopTest();  
            
    }
    static testMethod void runTest3() {
    Account account = new Account();
       account.Name = 'Accc5';
       insert account;         

       Contact contact = new Contact();
       contact.FirstName = 'Todda2';
       contact.LastName = 'Wilmss';
       contact.AccountID = account.Id;
       contact.Email = 'twilms@verisign.conm';
       contact.MobilePhone = '918527116723';
       insert contact; 
              
       Lead lead1= new Lead();
       lead1.FirstName = 'test2';
       lead1.LastName = 'Bcc5'; 
       lead1.company='cc5';      
       insert lead1; 
            
         test.startTest();
         PageReference pageRef1 = Page.Leadpage; // Your page name
         pageRef1.getParameters().put('Id', String.valueOf(lead.Id));
         Test.setCurrentPage(pageRef1);
        Test.setMock(HttpCalloutMock.class, new Leadpagemock());
          ApexPages.StandardController sc1 = new ApexPages.StandardController(lead1);//Instance of your object
         Leadpage testDObj = new Leadpage();
          testDObj.getperformcallout2();
           test.stopTest();  
            
    }
    static testMethod void runTest4() {
    Account account = new Account();
       account.Name = 'Accc6';
       insert account;         

       Contact contact = new Contact();
       contact.FirstName = 'Todda3';
       contact.LastName = 'Wilmss3';
       contact.AccountID = account.Id;
       contact.Email = 'twilms@verisign.conjm';
       contact.MobilePhone = '9185271163';
       insert contact; 
              
       Lead lead1= new Lead();
       lead1.FirstName = 'test4';
       lead1.LastName = 'Bcc6'; 
       lead1.company='cc6';      
       insert lead1; 
            
         test.startTest();
         PageReference pageRef1 = Page.Leadpage; // Your page name
         pageRef1.getParameters().put('Id', String.valueOf(lead.Id));
         Test.setCurrentPage(pageRef1);
        Test.setMock(HttpCalloutMock.class, new Leadpagemock());
          ApexPages.StandardController sc1 = new ApexPages.StandardController(lead1);//Instance of your object
         Leadpage testDObj = new Leadpage();
          testDObj.getperformcallout3();
           test.stopTest();  
            
    }
    static testMethod void runTest5() {
    Account account = new Account();
       account.Name = 'Accc7';
       insert account;         

       Contact contact = new Contact();
       contact.FirstName = 'Todda4';
       contact.LastName = 'Wilmss4';
       contact.AccountID = account.Id;
       contact.Email = 'twilms@verisign.m';
       contact.MobilePhone = '918527016723';
       insert contact; 
              
       Lead lead1= new Lead();
       lead1.FirstName = 'test4';
       lead1.LastName = 'Bcc7'; 
       lead1.company='cc7';      
       insert lead1; 
            
         test.startTest();
         PageReference pageRef1 = Page.Leadpage; // Your page name
         pageRef1.getParameters().put('Id', String.valueOf(lead.Id));
         Test.setCurrentPage(pageRef1);
        Test.setMock(HttpCalloutMock.class, new Leadpagemock());
          ApexPages.StandardController sc1 = new ApexPages.StandardController(lead1);//Instance of your object
         Leadpage testDObj = new Leadpage();
          testDObj.getperformcallout4();
           test.stopTest();  
            
    }

  
  
  
 static testMethod void fakeTest11(){
  

     Leadpage.fakeMethod11();
       
  } 
  static testMethod void fakeTest12(){
  

     Leadpage.fakeMethod12();
       
  }
  static testMethod void fakeTest13(){
  

     Leadpage.fakeMethod13();
       
  }
  static testMethod void fakeTest14(){
  

     Leadpage.fakeMethod14();
       
  }
  static testMethod void fakeTest15(){
  

     Leadpage.fakeMethod15();
       
  }
 
}

 
Hi All,

I am writing a trigger that creates an Invoice Item based on a selection of services.

The trigger works well if the selection is made on record creation but if it is being updated it doesn't fire.

Here is the code:

trigger PickupService on Invoice__c (after Insert) {
    List <Invoice_Item__c> Item = new List <Invoice_Item__c>();
    for (Invoice__c Inv: Trigger.new)
    {
        if (Inv.Pickup_Service__c == True)
        {
            Invoice_Item__c I = new Invoice_Item__c();
            I.Invoice__c = Inv.Id;
            I.Quantity__c= 1;
            I.Product__c = '01t4B000000Rnir';
            I.Service_Fee_Type__c = 'Room Service- Pickup';
            I.Item_Price__c = 15.00;
            
            Item.add(I);           
            
        }
        insert Item;
    
    }
}

When I add 'after update' the trigger fails to fire and the original record fails to create. I've tried doing this using Process Builder as well and the same issue occurs.

The error I email I get is very long but the final error states: CUMULATIVE_LIMIT_USAGE_END
There are other Apex Classes and Triggers build into the org is it possible that because of the existing code there are too many queries being processed?

I've tried building the same functionality in a different Sandbox that is blank and it is working fine. Any ideas?

Thanks for your help.
In an attempt to clean up my org and remove some fields, I'm trying to modify code that grabs Trade totals from one specific Fund Number and applies to them to the corresponding fields, and instead combine Fund Numbers and sums them to one field. Here is my example with code snippets:
public static final Set<String> FUND_NUMBERS = new Set<String> {
        '3915',
        '3917',
    };

    // All amounts/shares
    public static final Map<String, SObjectField[]> FIELDMAP_TOTAL = new Map<String, SObjectField[]>  {
        '3915' => new SobjectField[] { Account.Total_NS_Income_II_Sales__c , Account.Total_NS_Income_II_Shares__c },
'3917' => new SobjectField[] { Account.Total_NS_Income_II_T_Share_Sales__c, Account.Total_NS_Income_II_T_Shares__c },
    };
        // Fetch all the trades for these accounts
        Trades__c[] tradesList = [
            SELECT Name
                 , Dollar_Amount_of_the_transaction__c
                 , Fund_Number__c
                 , Number_of_Shares_of_the_transaction__c
                 , Resolved_Firm_Trading_ID__c
                 , Trade_Date__c
              FROM Trades__c
             WHERE Resolved_Firm_Trading_ID__c IN :accountIds
               AND Resolved_Firm_Trading_ID__c <> NULL
               AND Fund_Number__c IN :FUND_NUMBERS
               AND Trade_Date__c != NULL
               AND Dollar_Amount_of_the_transaction__c >= 0
               AND Number_of_Shares_of_the_transaction__c >= 0
        ];

            Decimal amount = trade.Dollar_Amount_of_The_Transaction__c;
            Decimal shares = trade.Number_of_Shares_of_the_transaction__c;
            String fn = trade.Fund_Number__c;
            SobjectField f0, f1;

            // Always apply to totals
            if (true) {
                f0 = FIELDMAP_TOTAL.get(fn)[0];
                f1 = FIELDMAP_TOTAL.get(fn)[1];

                account.put(f0, (Decimal) account.get(f0) + amount);
                account.put(f1, (Decimal) account.get(f1) + shares);
            }
        }

        // Done, try to update
        update accountMap.values();
    }
Now if I want to combine Fund Numbers 3915 & 3917 to be summed into the same fields, like so:
'3915' + '3917' => new SobjectField[] { Account.Test_Total_Sales__c, Account.Test_Total_Shares__c}
I get thrown an "Attempt to de-reference a null object" error on line 36 (in first snippet), the f1 = FIELDMAP_TOTAL.get(fn)[1];.

What is the proper way to structure this map to combine Fund Numbers?
Hello Everyone, 

I've been trying to work on code that was left to our ORG by a developer who is no longer supporting us.  Not being too familiar with Apex, this is proving to be a daunting task for us and blocking us from implementing the triggers/classes that we've been working on.  I know it's a lengthy bit of code, but if someone could offer some assistance we'd be really grateful.  Currently we're getting the SQOL 101 errors with this code:
 
trigger UpdateTruckInventoryByOpportunity_Trgr on Opportunity (before update,before insert,after update, after insert, after delete, after undelete) {
    List<Truck_Inventory__c> lstTruck2Update = new List<Truck_Inventory__c>();
    
    Set<String> rt2bypass = new Set<String>{'Used Truck Quote','Accessory Order'};     
    Map<Id,RecordType> usedTruckQuoteRT = new Map<Id,RecordType>([Select SobjectType,Name,Id From RecordType Where SobjectType ='Opportunity' and Name in :rt2bypass]);
    
    RecordType usedRT = [Select SobjectType,Name,Id From RecordType Where SobjectType ='Truck_Inventory__c' and Name = 'Used' LIMIT 1];
    Map<Id,Truck_Inventory__c> mapNotUsedTruckInv = new Map<Id,Truck_Inventory__c>([Select Id,RecordTypeId From Truck_Inventory__c Where RecordTypeId =:usedRT.Id]);
    Set<String> setTruckInventories = new Set<String>();
    
    if(Trigger.isAfter){
        if(Trigger.isUpdate){
            for(Opportunity opp:Trigger.new){
                if(usedTruckQuoteRT.get(opp.RecordTypeId)==null){
                    

                     if(opp.Truck_Inventory__c!=null){
                        if(opp.StageName == 'Lost Deal - Truck Built' || opp.StageName == 'Lost Deal - Truck Not Built'){
                            lstTruck2Update.add(new Truck_Inventory__c(Id=opp.Truck_Inventory__c,Sold__c=false, Related_Quote_SO__c=null, Customer__c = null));
                        }else if(opp.StageName == 'Sales Order - Pending' || opp.StageName == 'Sales Order - Complete'){
                            lstTruck2Update.add(new Truck_Inventory__c(Id = opp.Truck_Inventory__c,Customer__c = opp.AccountId, Sold__c=true,Related_Quote_SO__c=opp.Id));
                        }else{
                            lstTruck2Update.add(new Truck_Inventory__c(Id=opp.Truck_Inventory__c, Sold__c=true,Related_Quote_SO__c=opp.Id));
                        }
                    }
                    
                    Opportunity oldOpp = Trigger.oldmap.get(opp.Id);
                    if(oldOpp.Truck_Inventory__c!=null && oldOpp.Truck_Inventory__c != opp.Truck_Inventory__c){
                        lstTruck2Update.add(new Truck_Inventory__c(Id=oldOpp.Truck_Inventory__c,Sold__c=false, Related_Quote_SO__c=null, Customer__c = null));
                    }
                    
                }
            }
        }else if(Trigger.isInsert || Trigger.isUndelete){
            for(Opportunity opp:Trigger.new){
                if(usedTruckQuoteRT.get(opp.RecordTypeId)==null) {
                    if(opp.Truck_Inventory__c!=null){         
                        lstTruck2Update.add(new Truck_Inventory__c(Id=opp.Truck_Inventory__c, Sold__c=true,Related_Quote_SO__c=opp.Id));
                    }
                }
            }
        }else if(Trigger.isDelete){
            for(Opportunity opp:Trigger.old){
                if(usedTruckQuoteRT.get(opp.RecordTypeId)==null){
                    if(opp.Truck_Inventory__c!=null){
                        lstTruck2Update.add(new Truck_Inventory__c(id=opp.Truck_Inventory__c,Sold__c=false, Related_Quote_SO__c=null));
                    }
                }
            }
        }
        if(!lstTruck2Update.isEmpty()){
            update lstTruck2Update;
        }
    
    }
    else{
        
        for(Opportunity opp:Trigger.new){
            if(usedTruckQuoteRT.get(opp.RecordTypeId)==null) {
                if(opp.Truck_Inventory__c!=null){
                    if(!mapNotUsedTruckInv.containsKey(opp.Truck_Inventory__c)){    
                        setTruckInventories.add(opp.Truck_Inventory__c);
                    }          
                }
            }
        }
        
        if(!setTruckInventories.isEmpty()){
            Map<String,String> mTruckInParent = new Map<String,String>();
            for(Truck_Inventory__c ti :[Select Truck__c, Id From Truck_Inventory__c where Id in :setTruckInventories]){
                mTruckInParent.put(ti.Id, ti.Truck__c);
            }
         
            for(Opportunity opp:Trigger.new){
                if(usedTruckQuoteRT.get(opp.RecordTypeId)==null) {
                    opp.Truck__c = mTruckInParent.get(opp.Truck_Inventory__c);
                }
            }
        }
    }
}

 
Modifying some existing code that updates a record and then redirects to a new page. I need to change it so that it runs a query to identify the correct record to update, and then updates the record.
 
public PageReference saveAttendee(){
     
         List<CnP_PaaS_EVT__Event_attendee_session__c> attendee = [SELECT Id, Name, DTCI_Agreement_Active__c, CnP_PaaS_EVT__First_name__c, CnP_PaaS_EVT__Last_name__c, DTCI_Ticket_Level__c, CnP_PaaS_EVT__EventId__r.CnP_PaaS_EVT__category__r.name                                                                                                                                                          
                                                                       FROM CnP_PaaS_EVT__Event_attendee_session__c                                                                            
                                                                       WHERE CnP_PaaS_EVT__Registrant_session_Id__c =:registrantId 
                                                                            AND DTCI_Ticket_Level__c =: ticketLevel           
                                                                            AND DTCI_Attendee_Info_Assigned__c = FALSE
                                                                       ORDER BY DTCI_Ticket_Order__c
                                                                       LIMIT 1
                                                                      ];
        
        attendeeId = attendee.Id;                                                              
        attendeeFirstName = attendee.CnP_PaaS_EVT__First_name__c;
        attendeeLastName = attendee.CnP_PaaS_EVT__Last_name__c;
        mailingCity = attendee.DTCI_Mailing_City__c;
        mailingCountry = attendee.DTCI_Mailing_Country__c;
        mailingCounty = attendee.DTCI_Mailing_County__c;
        mailingState = attendee.DTCI_Mailing_State__c;
        mailingStreet = attendee.DTCI_Mailing_Street__c;
        mailingZip = attendee.DTCI_Mailing_ZIP_Postal_Code__c;
       
                                   
        update attendee;                                        
        
PageReference sendToReleaseForm = new PageReference('/apex/DTCI_Release_Form_Page_AB' + '?attendeePageId=' + attendee.id + '&registrantPageId=' + registrantId + '&eventPageId=' + eventId + '&releasePageType=' + attendee.DTCI_Release_Type__c);  
        sendToReleaseForm.setRedirect(true);                        
        return sendToReleaseForm;     
    }

How can I query the object to find the next suitable record to update and still create the PageReference I need to move forward?

 
Super simple page, but when I run it I get an exception, "sObject type 'CollaborationGroupMember' is not supported."  I'm able to query other objects, and Googling around I haven't found an explanation why--or I'm Googling the wrong terms.

However, this link might suggest such a query from VF just isn't possible.
http://salesforce.stackexchange.com/questions/3574/receive-this-error-from-installed-package-system-queryexception-sobject-type
 
<apex:page >
	<apex:includescript value="/soap/ajax/33.0/connection.js" />
	<apex:includescript value="/soap/ajax/33.0/apex.js" />
	
	<script>
		try { 
			var query = "select collaborationGroupId, collaborationGroup.name from CollaborationGroupMember where memberid = '{!$User.ID}'"
			//var query = "select id from account";
			alert(query);
			
			//sforce.connection.sessionId = "{!$Api.Session_ID}";
			var records = sforce.connection.query(query); 
			
			console.log(records); 
		} 
		catch(e) { 
			alert(e); 
		}
	</script>
</apex:page>