• Ryan Greene
  • NEWBIE
  • 435 Points
  • Member since 2015

  • Chatter
    Feed
  • 11
    Best Answers
  • 0
    Likes Received
  • 3
    Likes Given
  • 27
    Questions
  • 106
    Replies

Dear All, 
I have a set of records (about 100) of the BCAccount type object. I would need to go through each of them and update the same field with a specific value. 
What's the easiest and fast way to do it having the list of BCAccountId which identify each record?

I was thinking to use Dataloader.

Thank you for your help.

GC

 

Hello,

I have a trigger on the task object before insert and before update. It works on the vast majority of my tasks, however it seems to not fire when a user uses the send email button on a contact. I can click edit and save and it will update fine but it will not fire on the insert of the task. Are the email tasks inserted in a special way compared to other tasks?
 
trigger TaskBeforeInsertBeforeUpdate on Task (before insert, before update) {

	// Initialize our lists we will use to query the related accounts and contacts later
	List<ID> accIDList = new List<ID>();
	List<ID> conIDList = new List<ID>();

	// Initialize our lists we will use to store our object querys
	List<Account> accList = new List<Account>();
	List<Contact> conList = new List<Contact>();


	// Loop through our tasks and assign the LCT variables, at the end we will build our lists of objects to query
	for (Task taskTrigger : Trigger.new) {
		String accIDString = String.Valueof(taskTrigger.WhatID);
		String conIDString = String.Valueof(taskTrigger.WhoID);

		if(conIDString == NULL){
			conIDString = '0';
		}

		if(accIDString == NULL){
			accIDString = '0';
		}

		if(taskTrigger.Call_Direction__c != NULL){
			taskTrigger.CallDisposition = taskTrigger.Call_Result__c;
			taskTrigger.CallType = taskTrigger.Call_Direction__c;
		}
		if(accIDString.startsWith('001')){
			taskTrigger.AccountLookup__c = taskTrigger.WhatID;
		}
		if(conIDString.startsWith('003')){
			taskTrigger.ContactLookUpField__c = taskTrigger.WhoID;
		}

		if(taskTrigger.qbdialer__Call_Date_Time__c != NULL && taskTrigger.status == 'Completed' && taskTrigger.AccountLookup__c != NULL){
			accIDList.add(taskTrigger.WhatID);
		}

		if(taskTrigger.ContactLookUpField__c != NULL && taskTrigger.status == 'Completed' && taskTrigger.qbdialer__Call_Date_Time__c != NULL){
			conIDList.add(taskTrigger.WhoID);
		}
	}

	// Query and update our contacts
	if(conIDList.size()>0){
		conList = [SELECT ID, qbdialer__Dials__c, AccountID, qbdialer__LastCallTime__c, OpportunityStage__c FROM Contact WHERE ID IN: conIDList];

		for(Task taskTrigger : Trigger.new){
			for(Contact con : conList){
				if(taskTrigger.WhoID == con.Id && (taskTrigger.qbdialer__Call_Date_Time__c > con.qbdialer__LastCallTime__c || con.qbdialer__LastCallTime__c == NULL)){
					con.qbdialer__LastCallTime__c = taskTrigger.qbdialer__Call_Date_Time__c;
					if(con.qbdialer__Dials__c == NULL){
						con.qbdialer__Dials__C = 0;
					}
					con.qbdialer__Dials__C += 1;
					if(taskTrigger.AccountLookup__c != con.AccountID){
						taskTrigger.AccountLookup__c = con.AccountID;
						taskTrigger.WhatID = con.AccountID;
						accIDList.add(con.AccountID);
					}
				}
			}
		}
		update conList;
	}

	// Query and update our accounts
	if(accIDList.size()>0){
		accList = [SELECT ID, qbdialer__Dials__c, qbdialer__LastCallTime__c, Type, Status__C FROM Account WHERE ID IN: accIDList];

		for(Task taskTrigger : Trigger.new){
			for(Account acc : accList){
				if(taskTrigger.AccountLookup__c == acc.Id && (taskTrigger.qbdialer__Call_Date_Time__c > acc.qbdialer__LastCallTime__c || acc.qbdialer__LastCallTime__c == NULL)){
				//if(taskTrigger.AccountLookup__c == acc.Id){
					acc.qbdialer__LastCallTime__c = taskTrigger.qbdialer__Call_Date_Time__c;
					if(acc.qbdialer__Dials__c == NULL){
						acc.qbdialer__Dials__c = 0;
					}
					acc.qbdialer__Dials__C += 1;
				}
			}
		}
		update accList;

	}

 
No matter what I do I cant get my code to validate using the test methods I made. I want to test a web service callout and already created the test class and static resource that mock uses to make the response. In order to properly test I needed to return the httpresponse I recieved in my desearialize method. This ment I couldnt make it @future(callout=true) so I created another method with the future tag that gets called by my trigger, the test method can call deserialize directly and use it to compare the expected httpResponse to the actual response. But no matter what I seem to do the program wont validate using my test code. It just immeaditally fails saying it cant test webservice callouts. Can anyone offer me a solution that lets me test my respose while maintaining the future callout and in such a way that salesforce will accept it?

WRAPPER:
public class GDPRWrapper{

    public GDPRWrapper(List<GDPRData> templst){
            GDPRList = templst;
        }
    public List<GDPRData> GDPRList {get; set;}

    public class GDPRData {

        public Integer gdprId {get; set;}  //26636
        public String firstName {get; set;}
        public String lastName {get; set;}
        public String email {get; set;}
        public String phone {get; set;}
        public String accountName {get; set;}
        public String contactId {get; set;}    //AA111222333AAAe
        public String emailHash {get; set;}    //78fcb5ad502033c46d35abcecb3615bd92757fb0451485a19b27b7515f6d82d0
        public String createDate {get; set;}   //2018-05-17T15:19:37.000+0000
        public String responseDate {get; set;} //2018-05-21T10:38:53.000+0000
        public String notifyDate {get; set;}
        public boolean marketing {get; set;}
        public boolean security {get; set;}
        public boolean support {get; set;}
        public boolean contactPhone {get; set;}
        public boolean contactEmail {get; set;}
        public boolean contactOther {get; set;}
        public boolean invalid {get; set;}
        
        
    }
   public static List<GDPRData> parse(httpResponse json){
        return (List<GDPRData>) System.JSON.deserialize(json.getBody(), List<GDPRData>.class);
    }
 
    
}

Web callout class:
public class JSONDeserialize {

    public GDPRWrapper wrapper {get;set;}
    public HttpResponse httpResponse {get;set;}
   
    
    @Future(callout=true)
    Public static void firecallout(string str)
    { 
        System.debug('@@@ ' + str);
        JSONDeserialize.deserialize();
    }
    public static HttpResponse deserialize() {
        GDPRWrapper wrapper;
        HttpResponse httpResponse = new HttpResponse();
        
        Http h = new Http();
        HttpRequest request = new HttpRequest();
        
        request.setEndPoint('PRIVATE');
        Blob headerValue = Blob.valueOf('d18849ea4155:d83ce6ef3dbe');
        String authorizationHeader = ('Basic ' + EncodingUtil.base64Encode(headerValue));
        
        
        request.setHeader('Authorization', authorizationHeader);
        request.setMethod('GET');
        HttpResponse response = new HttpResponse();
        try{
        response = h.send(request);
        
        
        System.debug('JSON RESPONSE: ' + response);
        List<GDPRWrapper.GDPRData> obj = GDPRWrapper.parse(response);
        wrapper = new GDPRWrapper(obj);
        
        System.assert(wrapper.GDPRList!=null);
        updateData(wrapper);
        }catch(JSONException j){
                    System.debug('An unexpected error has occured: ' + j.getMessage());
                }
              
        return response;
      }
      
      
      public static void UpdateData(GDPRWrapper wrapper){
        List<Contact> contactPref = new List<Contact>();
        List<Contact> newContacts = new List<Contact>();
          
        for(Integer i = 0; i < wrapper.GDPRList.size(); i ++){
        if(wrapper.GDPRList[i].contactId.length() > 3){
                if(wrapper.GDPRList[i].contactId.subString(0,3) == '003'){
                    Contact toInsert = new Contact();
                    toInsert.firstName = wrapper.GDPRList[i].firstName;
                    toInsert.lastName = wrapper.GDPRList[i].lastName;
                    toInsert.email = wrapper.GDPRList[i].email;
                    toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
                    toInsert.Id = wrapper.GDPRList[i].contactId;
                    toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
                    toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
                    toInsert.Product_Information__c = wrapper.GDPRList[i].support;
                    toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
                    toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
                    contactPref.add(toInsert);
           
                }
            }
        else{
             Contact toInsert = new Contact();
             toInsert.firstName = wrapper.GDPRList[i].firstName;
             toInsert.lastName = wrapper.GDPRList[i].lastName;
             toInsert.email = wrapper.GDPRList[i].email;
             toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
             
             toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
             toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
             toInsert.Product_Information__c = wrapper.GDPRList[i].support;
             toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
             toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
             newContacts.add(toInsert);
        
        
        }
           
            
          
        
        }
          try{
              if(contactPref.size()>0){
                  upsert contactPref;
              }
              if(NewContacts.size()>0){
                  insert NewContacts;
              }          
            } 
            catch(DmlException e){
                    System.debug('An unexpected error has occured: ' + e.getMessage());
                }
      
      }
     }

Test Class:
@isTest
private class JSONDeserializeTest {

        @isTest static void testCalloutEithStaticResource(){
            StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
            mock.setStaticResource('GDPR');
            mock.setStatusCode(200);
            mock.setHeader('Content-Type', 'application/json');
            
            Test.setMock(HttpCalloutMock.class, mock);
            HttpResponse res = JSONDeserialize.deserialize();
            System.assertEquals('PRIVATE DATA', res.getBody());
            System.assertEquals(200, res.getStatusCode());
            System.assertEquals('application/json', res.getHeader('Content-Type'));
        
        
        }


}

Trigger:
 
trigger GDPR_Prefrences_Updater on Contact (after insert, after update) {
   if(System.IsBatch() == false && System.isFuture() == false)
    {
        JSONDeserialize.firecallout('callout fires');
    }

}

Errors:
User-added image
Guys, I am an Admin who needs help from a developer. I have an apex trigger that was written and implemented by a contractor. It is on Contacts object. What is does is assign the contact to an owner based on the first three digits of the postal code. I need to have the same assignment triggger on Leads object.
I had 100% code coverage yesterday but today its 69% only. I dont know how this happened.
This is the code:-
trigger updatestatus on Task (after insert) {
set<id> setid = new set<id>();
list<contact> lstcon = new list<contact>();
for(task t :trigger.new){
setid.add(t.whatid);
setid.add(t.whoid);
}
for(contact cc :[select id,boolean__C,(select subject from tasks ) from contact where id=:setid]){
For(task t1 :trigger.new){
if(t1.subject=='Mass Email: Fourth Followup for Accounts New'){
Contact cc1 = new contact();
cc1.id=cc.id;
cc1.boolean__c='True';
lstcon.add(cc1);

}
update lstcon;
}

}

}

This is the Test class :-
@isTest 
private class SampleTestClass {
    static testMethod void validateContactsAndTasks() {
       Contact con = new Contact(LastName='Sample Last NAme', boolean__c=True);
       insert con;
        
        Task tsk = New Task();
        tsk.WhoId = con.Id;
        tsk.Subject = 'Mass Email';
        tsk.Status = 'In Progress';
        tsk.Priority = 'Low';
        insert tsk;
    }
}

Please help
When I add a date field to a visualforce page and its an input field the calendar automatically opens even if a date is already populated, and this means users have to click out of the date field to see the other fields for data entry.  I tested if the first input field in the section is not a date field and this works, but many of our sections start with date fields... 

User-added image

 
Hello,

I want to send Visualforce page as pdf in email for e-sign using Adobe EchoSign When clicked on command button on Visualforce page. This Visualforce page contains data from multiple objects. How can I send this page for signature using Adobe EchoSign? Please help asap.
I created a WFR formula that automatically inputs/updates (project expiration) Date fields based on the picklist value that is selected. I also created a time-based WFR that sends email alerts 30, 60,90 days prior to that Date. Is there a way that I can set the email alerts to only go to a specific group of users based on the picklist value that is selected?

Example:
IF Picklist Value = Project A or Project B or Project C
    Send the 30 day (60 or 90 depending on the expiration Date field) email alert to User 1 and  User 2 ONLY

IF Picklist Value = Project D or Project E or Project F
      Send the 30 day (60 or 90 depending on the expiration Date field) email alert to User 3 and User 4 ONLY

This is my current Time Based Workflow Rule:
Description: Notifies management 30/60/90 days prior to Project#1 Exp Date
Rule Criteria: Project: Project #1 Exp Date NOT EQUAL TO null

Time-Dependent Workflow Actions
Email Alert Alert 90 days before Project#1 Exp Date
Email Alert Alert 60 days before Project#1 Exp Date
Email Alert Alert 30 days before Project#1 Exp Date
I would like my SavePDF action to save the French and English PDF visualforce pages I have.  I've tried using an if/else statment but couldn't get it to work so I thought I would just try to have BOTH attached no matter what, but I'm having trouble getting that to work too...

Is this possible?  Here is what I've tried based on my research:
 
public pageReference savePDF(){

PageReference pagePdf = 
          new PageReference('/apex/Residential_Order_Form_PDF');
		  new PageReference('/apex/Residential_Order_Form_PDF_French');
          pagePdf.getParameters().put('id', idVal);
          Blob pdfPageBlob;
          pdfPageBlob = pagePdf.getContentAsPDF();
Should I be stating it differently?
 
I don't think there is an easy way to do this, but I thought I'd ask.  Thanks!
Hi all,

I hope that somebody answers my question as I am making efforts to describe what my problem is. I am trying to solve this without success.
I would like to autopopulate two lookup fields when I press the button New on a related list.

Matriculaci_n__c is the object where the related list Títulos is to find. The object is T_tulo__c.
I would like to add a button New on the related list Titulos, in order to get to the detail page where I can find two lookups autopopulated with the Postgraduate Course (Programa_acad_mico_1__c) and the Name of the Applicant (Cuenta_de_Alumno__c) mentioned in the Matriculaci_n__c object.

For this I built the following Apex Code:
 
public with sharing class SobreescribeTituloNuevo {
    
 public SobreescribeTituloNuevo(ApexPages.StandardController controller) {
    }
    public Pagereference onLoad(){
        PageReference newPage = new PageReference('/a10/e?');
        String TituloId;
        for(String keyValue : ApexPages.currentPage().getParameters().keySet()){
            if(!keyValue.contains('override') ){
                newPage.getParameters().put(keyValue, ApexPages.currentPage().getParameters().get(keyValue));
                if(keyValue.contains('retURL')) {
                  TituloId = ApexPages.currentPage().getParameters().get('retURL');
                }
            }
        }
        system.debug(TituloId);
        TituloId =  TituloId.removeStart('/');
        if(TituloId.length() >= 15) {
        Matriculaci_n__c objMatriculacion = [Select Id, Programa_acad_mico_1__c, Programa_acad_mico_1__r.Name, Cuenta_de_Alumno__c, Cuenta_de_Alumno__r.Name from Matriculaci_n__c where Id =: TituloId];
            newPage.getParameters().put('00N3E000000QaTd_lkid', objMatriculacion.Programa_acad_mico_1__c);
            newPage.getParameters().put('00N3E000000QaTd', objMatriculacion.Programa_acad_mico_1__r.Name);
			newPage.getParameters().put('00N3E000000XmQ3_lkid', objMatriculacion.Cuenta_de_Alumno__c);
			newPage.getParameters().put('00N3E000000XmQ3', objMatriculacion.Cuenta_de_Alumno__r.Name);
            newPage.getParameters().put('nooverride','1');
        }
        else {
            newPage.getParameters().put('nooverride','0');
        }
        return newPage.setRedirect(true);
    }
}
My Visualforce page looks like this:
 
<apex:page standardController="T_tulo__c" extensions="SobreescribeTituloNuevo" action="{!onLoad}">
</apex:page>
When I try to create a button for the related list Títulos, the Content field doesn't display anything, does anybody know why?. I already tried with many of the supposed solutions given in the internet, but none works for me, and I don't know where else do I have to change something or where is the mistake here.

User-added image
The IDs are here on this page fictitious.

As you see the Content field is not shown, can please somebody help me? :(.

 
Hello,
How can I move my custom buttons to the bottom of the Lightning Action with my VF Page? In the screenshot below, I'd like to move the button "Send Now" to the bottom where Cancel and Save are found. And actually I'd like to replace Save with the Send Now.
When I click the Action button now below is what pops up:
User-added image
My VF Page looks like this:
<apex:page standardcontroller="Lead" lightningStylesheets="true" extensions="SaveAmend">
    <apex:form >
        
        <!--Other info here-->
        
        <apex:commandButton value="Send Now" action="{!Send}"/>
    </apex:form>  
</apex:page>
I tried putting the apex:commandbutton inside apex:pageblockbutton, but that didnt work either.
Thanks for your help!
Hello,
How can I move my custom buttons to the bottom of the Lightning Action with my VF Page? In the screenshot below, I'd like to move the button "Send Now" to the bottom where Cancel and Save are found. And actually I'd like to replace Save with the Send Now.
When I click the Action button now below is what pops up:
User-added image
My VF Page looks like this:
<apex:page standardcontroller="Lead" lightningStylesheets="true" extensions="SaveAmend">
    <apex:form >
        
        <!--Other info to go here-->
        
        <apex:commandButton  value="Send Now" action="{!Send}"/>
    </apex:form>  
</apex:page>
I tried putting the apex:commandbutton inside apex:pageblockbutton, but that didnt work either.
Thanks for your help!
 
Hello,
I have an embedded VF Page in my Leads which pulls a custom onbject Documents, and displays all Documents in the list as below:
User-added image
You can probably tell what I'd like to do is upload a file to 'Proposal' and another one to other doc types I do not have listed there, and then click the 'Save All Docs Attached' button and have the attachments save properly to eash Document Type which is a separate record. Right now when I click Save it saves the attachment to each of the Doc Types in the list. Is there a way I can save the Attachment to a List, then have the List save to each respective Doc Type?
Apex:
public with sharing class LeadDoc{
    public ApexPages.StandardController Controller;
    public LeadDoc(ApexPages.StandardController Controller){
        this.Controller = Controller;}
    public Id getid {get;set;}{
        getid = ApexPages.currentPage().getParameters().get('id');}
    public List<Lead> Lds {get;set;}
    public List<Document__c> Docs {get;set;}
    public String fileName {get;set;}
    public transient Blob fileBody {get;set;}
    
    public LeadDoc(){
        Lds = [SELECT Id, Name FROM Lead WHERE Id =: getid];
        Docs = [SELECT Id, Name,Count_Attachments__c,Attach_Request_Status__c, Document__c,View_Doc__c,
                Lead__c FROM Document__c WHERE Lead__c =: Lds[0].Id];
    }
    public PageReference Save(){
        //List<Attachment> att = fileBody;
        for(Document__c doc : Docs){
            if(fileBody!=null){
                Attachment attachment = new Attachment();
                attachment.body = fileBody;
                attachment.name = this.fileName;
                attachment.parentId = doc.Id;
                insert attachment;}
        }
        return null;
    }
}

 
Hello,
I have a vf page as PDF which pulls all of the "Additional Owners" from a Lead, and places them in a table. Right now I use the class to determine the list size like this:
public Integer add {get;set;}
    public LeadPDF(){
        AO = [SELECT Id,Name FROM Additional_Owner__c WHERE Lead__c =: Ld[0].Id];
        add = AO.size();
So then my VF Page renders the section if the size equals 1, 2, 3 and so on. Is there a better way to write this VF Page to loop and add additional spaces if needed? I could potentially have 30+ additional owners at some point and really don't want to write 30+ different tables.
Thank you!
-Ryan
VF Page table section:
<apex:outputPanel rendered="{!IF(add=1,True,False)}">
                <center><b>Additional Owner</b></center>
                <table style="width:100%">
                    <tr>
                        <th>Entity/Officer</th>
                        <th>Ownership Type</th>
                        <th>Officer Email</th>
                        <th>Phone</th>
                        <th>Ownership Percentage</th>
                    </tr>
                    <tr>
                        <td><apex:outputLabel style="color:black"><apex:outputfield value="{!AO[0].Entity_Officer__c}"/></apex:outputLabel></td>
                        <td>{!AO[0].Ownership_Type__c}</td>
                        <td>{!AO[0].Officer_Email__c}</td>
                        <td>{!AO[0].Phone__c}</td>
                        <td>{!AO[0].Ownership_Percentage__c}</td>
                    </tr>
                </table>
                </apex:outputPanel>
            <apex:outputPanel rendered="{!IF(add=2,True,False)}"><center><b>Additional Owners</b></center>
                <table style="width:100%">
                    <tr>
                        <th>Entity/Officer</th>
                        <th>Ownership Type</th>
                        <th>Officer Email</th>
                        <th>Phone</th>
                        <th>Ownership Percentage</th>
                    </tr>
                    <tr>
                        <td><apex:outputLabel style="color:black;"><apex:outputfield value="{!AO[0].Entity_Officer__c}"/></apex:outputLabel></td>
                        <td>{!AO[0].Ownership_Type__c}</td>
                        <td>{!AO[0].Officer_Email__c}</td>
                        <td>{!AO[0].Phone__c}</td>
                        <td>{!AO[0].Ownership_Percentage__c}</td>
                    </tr>
                    <tr>
                        <td><apex:outputfield value="{!AO[1].Entity_Officer__c}"/></td>
                        <td>{!AO[1].Ownership_Type__c}</td>
                        <td>{!AO[1].Officer_Email__c}</td>
                        <td>{!AO[1].Phone__c}</td>
                        <td>{!AO[1].Ownership_Percentage__c}</td>
                    </tr>
                </table>
            </apex:outputPanel>
            <apex:outputPanel rendered="{!IF(add=3,True,False)}">EXTRA TABLE SECTIONS HERE</apex:outputPanel>
            <apex:outputPanel rendered="{!IF(add=4,True,False)}">EXTRA TABLE SECTIONS HERE</apex:outputPanel>
            <apex:outputPanel rendered="{!IF(add=5,True,False)}">EXTRA TABLE SECTIONS HERE</apex:outputPanel>
Hello,
I thought I had a simple straight forward code......never the case for me! Basically what I'm looking to do is if the ContentNote is updated or created, then push that note to a field in the Lead. Since ContentNote uses ContentDocumentLink as a sort of junction the Trigger is based of the ContentDocumentLink. Also, a trigger is not possible from the ContentNote itself (at least I couldn't find it). My code fails on line 9 showing error in the log of "FATAL_ERROR System.QueryException: List has no rows for assignment to SObject". Even though the log also shows the SOQL pulls 1 record. Any advice on getting this to work properly?
Trigger:
trigger Note on ContentDocumentLink (after insert, after update){
	Set<Id> cnote = new Set<Id>();
    Set<Id> leed = new Set<Id>();
    for(ContentDocumentLink cl : Trigger.new){
        cnote.add(cl.ContentDocumentId);
        leed.add(cl.LinkedEntityId);
    }
    ContentNote cn = [SELECT Id,Content FROM ContentNote WHERE Id IN :cnote];
    Lead ld = [SELECT Id,Last_Note__c FROM LEAD WHERE Id IN :leed LIMIT 1];
    for(ContentDocumentLink clnk : Trigger.new){
        ld.Last_Note__c = cn.Content.toString();
        update ld;
    }
}

 
Hello,
I have a VF Page (code below) on a Contact which renders as a PDF and is inserted in another record when a Lead is converted. If I pull the page independently it works filling the correct info. When it is paired with the Apex (code below) it fails with a fatal error and the break occurs on the line in the Apex "pdfBody = pdfPage.getContentAsPDF();". Should I be calling the page in a different way, or am I completely doing this wrong?
Thank you
VF Page:
<apex:page standardController="Contact" applyBodyTag="false" renderAs="pdf">
<!--CSS Styling Removed-->
        <html>
            <body>
                 <!-- Breaks when trying to pull Contact First Name. If I do not pull the first name Apex and VF Page run perfectly -->
                I, {!Contact.FirstName} acknowledge blah blah blah
Apex:
public class EchoSignRG{
    public ApexPages.StandardController Controller;
    public EchoSignRG(ApexPages.StandardController Controller){
        this.Controller = Controller;}
    @InvocableMethod
    public static void SendPDF(List<ID> conid){
        Lead L = [SELECT Id,Name,Street,City,State,PostalCode,ConvertedContactId,ConvertedOpportunityId,LeadSource,ConvertedAccountId FROM Lead WHERE Id =: conid];
        Contact con1 = [SELECT Id,AccountId,email,Firstname,lastname FROM Contact WHERE Id =: L.ConvertedContactId];
//SOME OTHER CODE HERE
            pageReference pdfPage = Page.ContactPDF;
            pdfPage.getParameters().put('id',con1.Id);
            blob pdfBody;
            if(Test.isRunningTest()){
                pdfBody = blob.valueOf('Unit.Test');
            }else{
                pdfBody = pdfPage.getContentAsPDF();}
//Fatal Error LINE ABOVE
            attachment pdfFile = new attachment();
            pdfFile.isPrivate = false;
            pdfFile.body      = pdfBody;
            pdfFile.parentId  = agreementRec1.id;
            pdfFile.Name      = agreementRec1.Name+'.pdf';
            
            insert pdfFile;
Hello,
I have an apex Emthod which calls a VF Page as a PDF and inserts the PDF to a record. Right now it is working as long as I don't call any Contact info for use in the PDF. As you can see in the VF Page I am trying to access the First Name of the Contact. The Error Log below I started where it starts looking at the PDF, then through where the Fatal Error comes in. The VF Page and Apex, I put in some comments in line. I have a feeling running the Method as static void has something to do with the error? Any suggestions much appreciated!!
Thanks,
Ryan
Error Log:
13:02:11.430 (5727412584)|STATEMENT_EXECUTE|[95]
13:02:11.430 (5727438344)|HEAP_ALLOCATE|[95]|Bytes:16
13:02:11.430 (5727493424)|VARIABLE_SCOPE_BEGIN|[95]|pdfPage|System.PageReference|true|false
13:02:11.430 (5728228256)|VARIABLE_ASSIGNMENT|[95]|pdfPage|"/apex/contactpdf"|0x70a80652
13:02:11.430 (5728244984)|STATEMENT_EXECUTE|[96]
13:02:11.430 (5728274749)|SYSTEM_METHOD_ENTRY|[96]|System.PageReference.getParameters()
13:02:11.430 (5728318848)|HEAP_ALLOCATE|[96]|Bytes:0
13:02:11.430 (5728348187)|SYSTEM_METHOD_EXIT|[96]|System.PageReference.getParameters()
13:02:11.430 (5728361632)|HEAP_ALLOCATE|[96]|Bytes:2
13:02:11.430 (5728411478)|SYSTEM_METHOD_ENTRY|[96]|Map<String,String>.put(Object, Object)
13:02:11.430 (5728453867)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:-4
13:02:11.430 (5728478883)|SYSTEM_METHOD_EXIT|[96]|Map<String,String>.put(Object, Object)
13:02:11.430 (5728490327)|STATEMENT_EXECUTE|[97]
13:02:11.430 (5728519858)|VARIABLE_SCOPE_BEGIN|[97]|pdfBody|Blob|false|false
13:02:11.430 (5728539640)|VARIABLE_ASSIGNMENT|[97]|pdfBody|null
13:02:11.430 (5728561572)|METHOD_ENTRY|[99]||System.Test.isRunningTest()
13:02:11.430 (5728593511)|METHOD_EXIT|[99]||System.Test.isRunningTest()
13:02:11.430 (5728603950)|STATEMENT_EXECUTE|[101]
13:02:11.430 (5728606748)|STATEMENT_EXECUTE|[102]
13:02:11.430 (5728618628)|SYSTEM_METHOD_ENTRY|[102]|System.PageReference.getContentAsPDF()
13:02:11.430 (5797457576)|FATAL_ERROR|Internal Salesforce.com Error
VF Page:
<apex:page standardController="Contact" applyBodyTag="false" renderAs="pdf">
<!--CSS Styling Removed-->
        <html>
            <body>
                 <!-- Breaks when trying to pull Contact First Name. If I do not pull the first name Apex and VF Page run perfectly -->
                I, {!Contact.FirstName} acknowledge blah blah blah
Apex:
public class EchoSignRG{
    public ApexPages.StandardController Controller;
    public EchoSignRG(ApexPages.StandardController Controller){
        this.Controller = Controller;}
    @InvocableMethod
    public static void SendPDF(List<ID> conid){
        Lead L = [SELECT Id,Name,Street,City,State,PostalCode,ConvertedContactId,ConvertedOpportunityId,LeadSource,ConvertedAccountId FROM Lead WHERE Id =: conid];
        Contact con1 = [SELECT Id,AccountId,email,Firstname,lastname FROM Contact WHERE Id =: L.ConvertedContactId];
//SOME OTHER CODE HERE
            pageReference pdfPage = Page.ContactPDF;
            pdfPage.getParameters().put('id',con1.Id);
            blob pdfBody;
            if(Test.isRunningTest()){
                pdfBody = blob.valueOf('Unit.Test');
            }else{
                pdfBody = pdfPage.getContentAsPDF();}
//Fatal Error LINE ABOVE
            attachment pdfFile = new attachment();
            pdfFile.isPrivate = false;
            pdfFile.body      = pdfBody;
            pdfFile.parentId  = agreementRec1.id;
            pdfFile.Name      = agreementRec1.Name+'.pdf';
            
            insert pdfFile;



 
Hello all,
I am having trouble with an HTTP Callout Test. I have a Trigger which sends it's info to the Class which houses the Http Callout. To Test for an Http Callout I followed the Apex Dev documentation (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm) where I create two Test classes, one sends Mock Http info and the other calls the Mock info. I beleive the problem is in the passing the "String ldid" from the Trigger to the Class. Trigger/Class/Tests below. Any ideas on how to solve this? Thanks!
Trigger:
String ldid;       
if(Trigger.isBefore){
      if(Trigger.isUpdate || Trigger.isInsert){
          for(Lead ld : Trigger.new){
              if(ld.IsConverted == TRUE && ld.Segment__c == 'Large Group'){
                  ldid = ld.Id;
                  CallApply.basicAuthCallout(ldid);
Class:
public class CallApply {
    public static HttpResponse basicAuthCallout(String ldid){
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://test');
        req.setMethod('POST');
        String body = '{"LeadId":"'+ldid+'"}';
        req.setHeader('Content-Type','application/json');  
        req.setBody(body);
        Http http = new Http();
        HTTPResponse res = http.send(req);
        return res;
    }
}
Test1:
@isTest
global class Test_callApply1 implements HttpCalloutMock {
    global HTTPResponse respond(HttpRequest req) {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type','application/json');
        res.setBody('{"example":"test"}');
        res.setStatusCode(200);
        return res;
    }
}
Test2:
@isTest
private class Test_callApply2 {
     @isTest static void testCallout() {
        Test.setMock(HttpCalloutMock.class, new Test_callApply1());
        //create Lead to pass value 'ldid'
        Lead ld = new Lead();
        ld.FirstName = 'testRyan';
        ld.LastName = 'testGreene';
        ld.email = 'testingtrigger1@test.com';
        ld.Company = 'testCompanyasdasdasdeyjhlnn';
        insert ld;
        String ldid = ld.id;
         
        HttpResponse res = CallApply.basicAuthCallout(ldid);
        
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = res.getBody();
        String expectedValue = '{"example":"test"}';
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
    }
}

 
Hello All,
I wrote a simple Trigger to not allow deletion of a specific record. Also, I wrote a Test Class with 100% code coverage in dev. When attempting change set I am receiving a Code Coverage Failure, with 0% code coverage. What is happening? I have tried the Change Set as both Default, and only run the Test related to my Trigger. I am deploying both in the same Change Set. All suggestions appreciated!
Thanks, Ryan
Trigger:
trigger callapplyTrigger on Lead (before update, before insert,before delete){
    if(Trigger.isDelete){
        for (Lead l : [SELECT Id,Email FROM Lead WHERE Email = 'testingtrigger1@test.com' AND Id IN :Trigger.old]){
            Trigger.oldMap.get(l.Id).addError(
                'Cannot delete this Lead.');
        }
    }
}
Test Class:
@isTest
public class Test_callApply {
    @isTest static void TestDelete(){
        Lead lead = new Lead(Segment__c='Small Group',Email='testingtrigger1@test.com',
                             FirstName='testRyan',LastName='testGreene',Status='New',
                          Company='testCompany',City='Orlando',State='FL',LeadSource='Event');
        insert lead;
        
        Test.startTest();
        Database.DeleteResult result = Database.delete(lead,false);
        Test.stopTest();

        System.assert(!result.isSuccess());
        System.assert(result.getErrors().size() > 0);
        System.assertEquals('Cannot delete this Lead.',result.getErrors()[0].getMessage());
    }
}

 
Hello,
I created an Apex Trigger to create a Note in the ContentNote upon creation of the record, and the trigger works great and copies the information perfectly with no strange value. Partial code for the Trigger:
for(Lead lds : Trigger.new){
        ContentNote cnt = new ContentNote();
        cnt.Content = Blob.valueof(lds.Sales_Notes__c);
        cnt.Title = 'Creation Note';
Now I created another code to transfer existing "Sales Notes" to the ContentNote. This is an Apex Class and works off a VF button. It also transfers the note and displays the text in the "Text Preview" appropriately, but when the ContentNote is opened it displays Korean/Chineese sysmbols. WHAT IS GOING ON?? Screenshots and Apex Class code below:
TextPreview WorksWHAT?!?!
 
for(Lead lds : lead){
            ContentNote cnt = new ContentNote();
            cnt.Content = Blob.valueof(lds.Sales_Notes__c);
            cnt.Title = 'Creation Note';

 
Hello,
I created a very simple trigger to add a Note when a Lead is created. The Note is not getting added, what am I doing wrong? (Code below) Is it not working because the Lead is not yet created? With an After Insert this shouldn't matter though. Notes are turned on and are working to manually create them.
Thanks,
Ryan
trigger AddNote on Lead (after insert) {
	List<Note> addnte = new List<Note>();
        for(Lead lds : Trigger.new){
            Note addedntes = new Note();
            addedntes.ParentId = lds.Id;
            addedntes.Body = lds.Sales_Notes__c;
            addedntes.Title = 'Creation Note';
            addnte.add(addedntes);
        }
    if(addnte.size()>0){
        insert addnte;
    }
}

 
public class ProposalEC {
    public List<Lead> Ld {get;set;}
    public List<Component__c> Com {get;set;}
    public List<User> us {get;set;}
    public Id getid {get;set;}{
        getid = ApexPages.currentPage().getParameters().get('id');}    
    public ProposalEC(){
        Ld = [SELECT Id,OwnerId,UW_Facility_Size__c,Max_Advance_Rate__c,City__c,State_Company__c,Zip_Code__c, Street__c, Entity__c, Company,
              FirstName, LastName FROM Lead WHERE Id =: getid];
        Com = [SELECT Id,Aging_Collection_Every_X_Days__c,Aging_Collection_Beyond_X_Days__c,Fee_Aging_Collection__c,Fee_Funds_Usage_Daily__c,
               Fee_Inventory_Monitoring__c,Fee_Invoice_Purchase__c,Advance_Rate_Inventory__c,Inventory_Sublimit__c,
               Name,Fee_Field_Appraisal__c,Fee_Field_Exam__c,Fee_Proposal__c,Fee_Due_Diligence__c,Special_Pricing__c
               FROM Component__c WHERE RecordTypeId = '0123F0000008XdC' AND Active_Component__c = True AND Related_Lead__c =: Ld[0].Id];
        us = [SELECT FirstName, LastName FROM User WHERE Id =: Ld[0].OwnerId];
    }
 
<apex:page controller="ProposalEC" renderAs="pdf">
    <apex:image url="{!$Resource.Logo}" style="left;" width="15%" height="15%"></apex:image>
    
    <apex:outputPanel rendered="{!Ld[0].Entity__c == '1'}">  
        <html>
            Working Capital Proposal
        </html>
    </apex:outputPanel>
    
    <apex:outputPanel rendered="{!Ld[0].Entity__c == '2'}">  
        <html>
           Working Capital Proposal
        </html>
    </apex:outputPanel>
    <apex:outputText value="{0,date,MMMM dd, yyyy}">
        <apex:param value="{!TODAY()}" />
    </apex:outputText>
    <html>
        For: {!Ld[0].Company}<br/>
        {!Ld[0].Street__c}<br/>
        {!Ld[0].City__c}, {!Ld[0].State_Company__c} {!Ld[0].Zip_Code__c}<br/>          
        {!Com[0].Name}<br/><br/><br/><br/>
        {!Ld[0].FirstName},<br/><br/>
        I'm pleased to present {!Ld[0].Company} ("Client") with the following terms for a financing facility (the "Facility").<br/><br/>
        <b>Facility Size:</b> ${!IF(Ld[0].UW_Facility_Size__c < 1000, TEXT(ROUND(Ld[0].UW_Facility_Size__c,0)), 
        IF(Ld[0].UW_Facility_Size__c < 1000000, TEXT(FLOOR(ROUND(Ld[0].UW_Facility_Size__c,0) /1000)) 
        & ',' & RIGHT(TEXT(ROUND(Ld[0].UW_Facility_Size__c,0)), LEN(TEXT(ROUND(Ld[0].UW_Facility_Size__c,0))) - LEN(TEXT(FLOOR(ROUND(Ld[0].UW_Facility_Size__c,0) /1000)))), 
        IF(Ld[0].UW_Facility_Size__c < 1000000000, TEXT(FLOOR(ROUND(Ld[0].UW_Facility_Size__c,0) /1000000)) 
        & ',' & MID(TEXT(ROUND(Ld[0].UW_Facility_Size__c,0)), 1 + LEN(TEXT(1 + FLOOR(ROUND(Ld[0].UW_Facility_Size__c,0) /1000000))),3) 
        & ',' & RIGHT(TEXT(ROUND(Ld[0].UW_Facility_Size__c,0)), LEN(TEXT(ROUND(Ld[0].UW_Facility_Size__c,0))) - LEN(TEXT(FLOOR(ROUND(Ld[0].UW_Facility_Size__c,0) /1000)))), 
        NULL)))}.<br/><br/>
        <b>Advance Rate:</b> Up to {!Ld[0].Max_Advance_Rate__c}% on Client’s eligible accounts receivable.<br/>
    </html>
    <apex:outputPanel id="ARI" rendered="{!Com[0].Advance_Rate_Inventory__c != null}">  
        <html>
            <b>Advance Rate Inventory:</b> The lesser of 1) 65% of Net Orderly Liquidation Value as determined by an Inventory Appraiser acceptable to {!Ld[0].Entity__c} and 2) 50% of Eligible A/R and 3) the Inventory Sublimit, 
            ${!IF(Com[0].Inventory_Sublimit__c < 1000, TEXT(ROUND(Com[0].Inventory_Sublimit__c,0)), 
            IF(Com[0].Inventory_Sublimit__c < 1000000, TEXT(FLOOR(ROUND(Com[0].Inventory_Sublimit__c,0) /1000)) 
            & ',' & RIGHT(TEXT(ROUND(Com[0].Inventory_Sublimit__c,0)), LEN(TEXT(ROUND(Com[0].Inventory_Sublimit__c,0))) - LEN(TEXT(FLOOR(ROUND(Com[0].Inventory_Sublimit__c,0) /1000)))), 
            IF(Com[0].Inventory_Sublimit__c < 1000000000, TEXT(FLOOR(ROUND(Com[0].Inventory_Sublimit__c,0) /1000000)) 
            & ',' & MID(TEXT(ROUND(Com[0].Inventory_Sublimit__c,0)), 1 + LEN(TEXT(1 + FLOOR(ROUND(Com[0].Inventory_Sublimit__c,0) /1000000))),3) 
            & ',' & RIGHT(TEXT(ROUND(Com[0].Inventory_Sublimit__c,0)), LEN(TEXT(ROUND(Com[0].Inventory_Sublimit__c,0))) - LEN(TEXT(FLOOR(ROUND(Com[0].Inventory_Sublimit__c,0) /1000)))), 
            NULL)))}.
        </html>
    </apex:outputPanel>
    <apex:outputPanel id="IPF" rendered="{!Com[0].Fee_Invoice_Purchase__c != null}">  
        <html>
            <b>Invoice Purchase Fee:</b> {!Com[0].Fee_Invoice_Purchase__c}% on the gross amount of all invoices submitted to {!Ld[0].Entity__c} for funding.
        </html>
    </apex:outputPanel>    
    <apex:outputPanel id="IMF" rendered="{!Com[0].Fee_Inventory_Monitoring__c != null}">  
        <html>
            <b>Inventory Monitoring Fee:</b> {!Com[0].Fee_Inventory_Monitoring__c}%.<br/><br/>
            <b>Inventory Advance Formula:</b> The lesser of 1) 65% of Net Orderly Liquidation Value as determined by an Inventory Appraiser acceptable and 2) 50% of Eligible A/R and 3) the Inventory Sublimit.
        </html>
    </apex:outputPanel>

Hello,
I have a VF Page rendered as a PDF and the page populates all of my needed information except for one field; Max_Advance_Rate__c, should be around line 32 in the VF code. It is a percent field, and I do have other percent fields displayed and working on the current VF Page. Any suggestions? VF and Class below
 
I continue to receive error messages when trying to invoke Apex when a record is created. My Lead object has a related object called Additional Owners which are basically additional Contacts, so when the Lead is Converted I have a Trigger which takes the Additional Owners and creates Contact Records for them. Then I have an invocable method which sends PDFs to the newly created Contact. The invocable method is run from a Process Builder which runs when that new Contact is created. Each time I test converting a Lead Additional Owner, I recieve the error "Error:Apex trigger ContactfrmAO caused an unexpected exception, contact your administrator: ContactfrmAO: execution of BeforeUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow. A flow trigger failed to execute the flow with version ID 3013F00000005Bx. Flow error messages: An unhandled fault has occurred in this flow
An unhandled fault has occurred while processing the flow. Please contact your system administrator for more information. Contact your administrator for help.: []: Trigger.ContactfrmAO: line 17, column 1"

The trigger ContactfrmAO is the trigger to create a Contact from the Additional Owner object. Line 17 is the insert of the Contact. The Flow error is for the Process Builder invoking the Apex.

It seems I am trying to do too many funcitons all at once. Any thoughts on how to make this work?
I have a seemingly simple Test I wrote but when run it receives the error: Methods defined as TestMethod do not support getContent call. I do not have a .getContent call in my Test. I have narrowed down the error to most likely be the line "conid.add(con.Id);". I'm think the .add() when called acts like a .getContent()? Any thoughts on a way around the call?
Thank you,
Ryan
@isTest
public class Test_EchoSign2 {
    static testmethod void testechosign(){
    	Account ac = new Account(RecordTypeId = [SELECT Id, SobjectType, Name FROM Recordtype WHERE Name = 'Prospect/Client' AND SobjectType = 'Account' LIMIT 1].Id);
    	ac.Name = 'TestAcnt';
    	ac.Type = 'Prospect';
    	insert ac;
    
		Contact con = new Contact(RecordTypeId = [SELECT Id,SObjectType,Name FROM RecordType WHERE Name = 'Prospect/Client' AND SobjectType = 'Contact' LIMIT 1].Id);
		con.LastName = 'testLastName';
    	con.AccountId = ac.Id;
        con.Email = 'ryan.greene@outlook.com';
	    con.LeadSource = 'Unknown';
        insert con;
 
        List<Id> conid = new List<Id>();
        conid.add(con.Id);
		EchoSign.SendPdf(conid);
    }
}

 
Hello,
I am writing a test for an @InvocableMethod and for some reason I keep getting an error that says Invalid Type: SendPdf. Code below, any help is appreciated!!
Controller
public with sharing class EchoSign {
    private ApexPages.StandardController standardController;
    public EchoSign(ApexPages.StandardController standardController){
        this.standardController = standardController;}

@InvocableMethod
    public static void SendPdf(List<ID> conid){
        
    List<Contact> con = [SELECT Id, AccountId, Name FROM Contact WHERE Id =: conid LIMIT 1];  
        
        pageReference pdfPage = Page.ContactPDF;
        pdfPage.getParameters().put('Id',con[0].Id);
        blob pdfBody;
        pdfBody = pdfPage.getContentAsPDF();

//creation of Adobe Sign Agreement and Attachment here
}
}
Test
@isTest
public class Test_EchoSign2 {
    static testMethod void testechosign(){
    	Account ac = new Account(RecordTypeId = [SELECT Id, SobjectType, Name FROM Recordtype WHERE Name = 'Prospect/Client' AND SobjectType = 'Account' LIMIT 1].Id);
    	ac.Name = 'TestAcnt';
    	ac.Type = 'Prospect';
    	insert ac;
    
		Contact con = new Contact(RecordTypeId = [SELECT Id,SObjectType,Name FROM RecordType WHERE Name = 'Prospect/Client' AND SobjectType = 'Contact' LIMIT 1].Id);
		con.LastName = 'testLastName';
    	con.AccountId = ac.Id;
	    con.LeadSource = 'Unknown';
        insert con;
        
        Test.startTest();
        
        PageReference ContactPDF = Page.ContactPDF;
        ContactPDF.getParameters().put('Id',con.Id);
        Test.setCurrentPage(ContactPDF);
        
        SendPdf pdf = new SendPdf();
    }
}


 
Hello,
I have a button on my page which runs a VF Page with an extension to my controller. It works to press the button and it produces the EchoSign Agreement as directed. However, the page it goes to when I click the button is a blank page. I would like to redirect it to the Id of the record I just created upon pressing the button. Basic outline of code below. So how can I get a void method to redirect to the ID of the record it just created?
public void SendPdf(){
//reference PDF Creator VF Page
pageReference pdfPage = Page.ContactPDF;
pdfPage.getParameters().put('Id',getid);
blob pdfBody;
pdfBody = pdfPage.getContentAsPDF();
          
// Build Echosign agreement record
echosign_dev1__SIGN_Agreement__c agreementRec = new echosign_dev1__SIGN_Agreement__c();
agreementRec.Name = 'Credit Info Release for: ';
//other variables entered here
insert agreementRec;

// insert the pdf as an attachment
attachment pdfFile = new attachment();
pdfFile.isPrivate = false;
pdfFile.body = pdfBody;
pdfFile.parentId = agreementRec.id;
pdfFile.Name = 'Agreement.pdf';
insert pdfFile;
}

 
Hello,
I have not written Apex Tests before (I probably should have) and I am running into an error each time I run the test, but there is no error on the page. Test Class below and I am receiving the error on line 6: Error Message - System.NullPointerException: Attempt to de-reference a null object  Stack Trace - Class.Test_UploadAttachmentController.testattach
 
@isTest
private class Test_UploadAttachmentController {
    static testMethod void testattach(){
        Document__c doc = new Document__c(Document__c = 'Aging', RecordTypeId = [SELECT Id, SobjectType, Name FROM Recordtype WHERE Name = 'Request' AND SobjectType = 'Document__c' LIMIT 1].Id);
        insert doc;
        UploadAttachmentController controller = new UploadAttachmentController(new ApexPages.StandardController(doc));
        
        controller.fileName = 'Unit Test Attachment Body';
        controller.fileBody = Blob.valueOf('Unit Test Attachment Body');
        controller.processUpload();
        
        LIST<Attachment> attch = [SELECT Id, Name FROM Attachment WHERE parent.id =: doc.Id];
        System.assertEquals(1, attch.size());
    }
}

 
I currently have a Hyperlink from a custom object "Document" to a VF page. This hyperlink is displayed on the related list on the Lead, Opp, and some other custom objects. So the VF Page can be accessed from any of the records related to the Document record. The issue I am running into is how to set the return URL. I can set the Return URL ID based on each related record but how can I tell which record the user just accessed the VF Page from?
Hyperlink formula: HYPERLINK("/apex/AttachDoc?id="& Id &"&retURL=%2F"& Lead__r.Id ,"Upload Docs Here","_self")
So the formula above would only return the user to the Lead, but what if they actually accessed the link from the Opp or one of the other custom objects?
Hello,
I am trying to create two records when a Lead hits a certain point, then have those two new records associated to one another. The Lead will create one Underwriting record, then can create several Issues related to the Underwriting record it just created. I just started adding the create Issue records to the code and I know the first part works that creates a single UW record from the Lead. Just need to resolve relating the new Issues back to the UW record. Trigger below:
trigger SubmitUW on Lead (after update) {
    List<Underwriting__c> uw = new List<Underwriting__c>();
    List<Issue__c> i = new List<Issue__c>();
    Set<Id> UWId = new Set<Id>();
    for(Lead l : Trigger.new){
        if(l.Create_UW__c == TRUE){
            Underwriting__c u = new Underwriting__c();
            u.Lead__c = l.Id;
            //Add all fields below which need to be mapped from the Lead to the UW
            //format as follows - "u.UnderwritingFieldAPIName = l.LeadFieldAPIName;"
            u.City__c = l.City__c;
            u.Industry__c = l.Industry;
            //Adds all fields above to the compiled List
            uw.add(u);
            UWId.add(u.Id);
        }
        if(uw.size()>0)
        insert uw;
        
        if(l.Collateral__c == True){
            Issue__c is = new Issue__c();
            is.Underwriting__c = UWId;
        }
    }
}
My error is currently on "is.Underwriting__c = UWId;" with error: Illegal assignment from Set<Id> to Id
also not sure if the line "UWId.add(u.Id);" sets the Id properly

Thanks for your help!
 
Hello,
I am having difficulty adding a number to a set, then once it is set how do I add 1 to that number?

Code below; I receive error on line 3 of: void add(Decimal) from the type Set<Integer>
and error on line 11 of: void valueOf(Set<Integer>) from the type assign, which is directly related to line 3 not being set
Set<Integer> assignid = new Set<Integer>();
    for(Lead lead : [SELECT AssignIDDateTime__c, Assignment_ID__c FROM Lead WHERE AssignIDDateTime__c != null ORDER BY AssignIDDateTime__c DESC LIMIT 1]){
        assignid.add(lead.Assignment_ID__c);
    }
    
    for(Lead l : Trigger.new){
        if(l.Status == 'Underwriting'){
	        if(l.AssignIDDateTime__c == null){
            	l.Assignment_ID__c = decimal.valueOf(1);
            }else{
                l.Assignment_ID__c = decimal.valueOf(assignid) + decimal.valueOf(1);
            }
        }

    }
Thank you!
Hi There

I am trying to create a button which will sit in the Opportunity related list which allows you to update the field 'POP Request' on all the product lines you use in the Multi Picklist. I am getting the following message: 

Error Message: <span class="errorStyle">Error: The Name field is required.</span>

This is the first time I have tried this so any help is much appreciated! 

Thanks, Sarah 


{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
var p = new sforce.SObject('OpportunityLineItem');
p.id = "{OpportunityLineItem.Id}";
p.POP_Request__c = TRUE;
result = sforce.connection.update([p]);
location.reload(true);

User-added image

 
I have a series of process builders that are routinely causing this error. I have already enabled: Query optimization in bulk mode. Is there a limit to the number of process builder that are recommended running at a single time or what can I do to help resolve this? 


Here is one of the error messages I get frequently: 

Cannot execute flow trigger: We can't save this record because the “Regional Territory Assignment” process failed. Give your Salesforce admin these details. This error occurred when the flow tried to update records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: DSCORGPKG.DiscoverOrgCustomMapping_Lead: System.LimitException: Apex CPU time limit exceeded. You can look up ExceptionCode values in the SOAP API Developer Guide. Error ID: 93739643-76958 (-820305936)
I deleted record 222 in the custom object Charge Scrubber Edit Request yesterday.  I need assistance restoring the record.  
Is there any way to Override New button with new VisualForce page but to keep it Layout style. Actualy I want to update some minor thing I don't want to create whole page of it again. Is it possible ??

Regards
Hi,
We have an apex class that is defaulting information for a Visualforce page to send an email.
I have changed the class to pull the email signature from the user file. This is copying a rich text area field into another rich text area field.
This seems to work, shockingly, since I am not a coder. BUT there seems to be additional spacing on the visualforce page input.
Would someone be able to tell me how to fix this?

Apex Class code:
public PCharter(ApexPages.StandardController stdController) {
    this.ProjectCharter = (Project_Charter__c)stdController.getRecord();
    this.getProjectCharter();
    User u = [Select Id, Name, Email_Signature__c from User where Id =: UserInfo.getUserId()];
    this.ProjectCharter.Email_Message__c = u.Email_Signature__c;

Visualforce Page:
<p>Message:  <br /><apex:inputTextarea richtext="true" value="{!ProjectCharter.Email_Message__c}" rows="20"/></p>

Here is my email signature:
Email Signature from User record
This is what the field ends up looking like:
Email Message
See the additional line spacing? How can I make it look exactly like the email signature?

Thanks!!!

Dear All, 
I have a set of records (about 100) of the BCAccount type object. I would need to go through each of them and update the same field with a specific value. 
What's the easiest and fast way to do it having the list of BCAccountId which identify each record?

I was thinking to use Dataloader.

Thank you for your help.

GC

 

When deploying a Customized application to production , a test class from Manged Package is failed. Could someone guide me What can be done in this regard ?. Is  it something wrong with code i am trying to deploy ?
Hello,

I have a trigger on the task object before insert and before update. It works on the vast majority of my tasks, however it seems to not fire when a user uses the send email button on a contact. I can click edit and save and it will update fine but it will not fire on the insert of the task. Are the email tasks inserted in a special way compared to other tasks?
 
trigger TaskBeforeInsertBeforeUpdate on Task (before insert, before update) {

	// Initialize our lists we will use to query the related accounts and contacts later
	List<ID> accIDList = new List<ID>();
	List<ID> conIDList = new List<ID>();

	// Initialize our lists we will use to store our object querys
	List<Account> accList = new List<Account>();
	List<Contact> conList = new List<Contact>();


	// Loop through our tasks and assign the LCT variables, at the end we will build our lists of objects to query
	for (Task taskTrigger : Trigger.new) {
		String accIDString = String.Valueof(taskTrigger.WhatID);
		String conIDString = String.Valueof(taskTrigger.WhoID);

		if(conIDString == NULL){
			conIDString = '0';
		}

		if(accIDString == NULL){
			accIDString = '0';
		}

		if(taskTrigger.Call_Direction__c != NULL){
			taskTrigger.CallDisposition = taskTrigger.Call_Result__c;
			taskTrigger.CallType = taskTrigger.Call_Direction__c;
		}
		if(accIDString.startsWith('001')){
			taskTrigger.AccountLookup__c = taskTrigger.WhatID;
		}
		if(conIDString.startsWith('003')){
			taskTrigger.ContactLookUpField__c = taskTrigger.WhoID;
		}

		if(taskTrigger.qbdialer__Call_Date_Time__c != NULL && taskTrigger.status == 'Completed' && taskTrigger.AccountLookup__c != NULL){
			accIDList.add(taskTrigger.WhatID);
		}

		if(taskTrigger.ContactLookUpField__c != NULL && taskTrigger.status == 'Completed' && taskTrigger.qbdialer__Call_Date_Time__c != NULL){
			conIDList.add(taskTrigger.WhoID);
		}
	}

	// Query and update our contacts
	if(conIDList.size()>0){
		conList = [SELECT ID, qbdialer__Dials__c, AccountID, qbdialer__LastCallTime__c, OpportunityStage__c FROM Contact WHERE ID IN: conIDList];

		for(Task taskTrigger : Trigger.new){
			for(Contact con : conList){
				if(taskTrigger.WhoID == con.Id && (taskTrigger.qbdialer__Call_Date_Time__c > con.qbdialer__LastCallTime__c || con.qbdialer__LastCallTime__c == NULL)){
					con.qbdialer__LastCallTime__c = taskTrigger.qbdialer__Call_Date_Time__c;
					if(con.qbdialer__Dials__c == NULL){
						con.qbdialer__Dials__C = 0;
					}
					con.qbdialer__Dials__C += 1;
					if(taskTrigger.AccountLookup__c != con.AccountID){
						taskTrigger.AccountLookup__c = con.AccountID;
						taskTrigger.WhatID = con.AccountID;
						accIDList.add(con.AccountID);
					}
				}
			}
		}
		update conList;
	}

	// Query and update our accounts
	if(accIDList.size()>0){
		accList = [SELECT ID, qbdialer__Dials__c, qbdialer__LastCallTime__c, Type, Status__C FROM Account WHERE ID IN: accIDList];

		for(Task taskTrigger : Trigger.new){
			for(Account acc : accList){
				if(taskTrigger.AccountLookup__c == acc.Id && (taskTrigger.qbdialer__Call_Date_Time__c > acc.qbdialer__LastCallTime__c || acc.qbdialer__LastCallTime__c == NULL)){
				//if(taskTrigger.AccountLookup__c == acc.Id){
					acc.qbdialer__LastCallTime__c = taskTrigger.qbdialer__Call_Date_Time__c;
					if(acc.qbdialer__Dials__c == NULL){
						acc.qbdialer__Dials__c = 0;
					}
					acc.qbdialer__Dials__C += 1;
				}
			}
		}
		update accList;

	}

 
No matter what I do I cant get my code to validate using the test methods I made. I want to test a web service callout and already created the test class and static resource that mock uses to make the response. In order to properly test I needed to return the httpresponse I recieved in my desearialize method. This ment I couldnt make it @future(callout=true) so I created another method with the future tag that gets called by my trigger, the test method can call deserialize directly and use it to compare the expected httpResponse to the actual response. But no matter what I seem to do the program wont validate using my test code. It just immeaditally fails saying it cant test webservice callouts. Can anyone offer me a solution that lets me test my respose while maintaining the future callout and in such a way that salesforce will accept it?

WRAPPER:
public class GDPRWrapper{

    public GDPRWrapper(List<GDPRData> templst){
            GDPRList = templst;
        }
    public List<GDPRData> GDPRList {get; set;}

    public class GDPRData {

        public Integer gdprId {get; set;}  //26636
        public String firstName {get; set;}
        public String lastName {get; set;}
        public String email {get; set;}
        public String phone {get; set;}
        public String accountName {get; set;}
        public String contactId {get; set;}    //AA111222333AAAe
        public String emailHash {get; set;}    //78fcb5ad502033c46d35abcecb3615bd92757fb0451485a19b27b7515f6d82d0
        public String createDate {get; set;}   //2018-05-17T15:19:37.000+0000
        public String responseDate {get; set;} //2018-05-21T10:38:53.000+0000
        public String notifyDate {get; set;}
        public boolean marketing {get; set;}
        public boolean security {get; set;}
        public boolean support {get; set;}
        public boolean contactPhone {get; set;}
        public boolean contactEmail {get; set;}
        public boolean contactOther {get; set;}
        public boolean invalid {get; set;}
        
        
    }
   public static List<GDPRData> parse(httpResponse json){
        return (List<GDPRData>) System.JSON.deserialize(json.getBody(), List<GDPRData>.class);
    }
 
    
}

Web callout class:
public class JSONDeserialize {

    public GDPRWrapper wrapper {get;set;}
    public HttpResponse httpResponse {get;set;}
   
    
    @Future(callout=true)
    Public static void firecallout(string str)
    { 
        System.debug('@@@ ' + str);
        JSONDeserialize.deserialize();
    }
    public static HttpResponse deserialize() {
        GDPRWrapper wrapper;
        HttpResponse httpResponse = new HttpResponse();
        
        Http h = new Http();
        HttpRequest request = new HttpRequest();
        
        request.setEndPoint('PRIVATE');
        Blob headerValue = Blob.valueOf('d18849ea4155:d83ce6ef3dbe');
        String authorizationHeader = ('Basic ' + EncodingUtil.base64Encode(headerValue));
        
        
        request.setHeader('Authorization', authorizationHeader);
        request.setMethod('GET');
        HttpResponse response = new HttpResponse();
        try{
        response = h.send(request);
        
        
        System.debug('JSON RESPONSE: ' + response);
        List<GDPRWrapper.GDPRData> obj = GDPRWrapper.parse(response);
        wrapper = new GDPRWrapper(obj);
        
        System.assert(wrapper.GDPRList!=null);
        updateData(wrapper);
        }catch(JSONException j){
                    System.debug('An unexpected error has occured: ' + j.getMessage());
                }
              
        return response;
      }
      
      
      public static void UpdateData(GDPRWrapper wrapper){
        List<Contact> contactPref = new List<Contact>();
        List<Contact> newContacts = new List<Contact>();
          
        for(Integer i = 0; i < wrapper.GDPRList.size(); i ++){
        if(wrapper.GDPRList[i].contactId.length() > 3){
                if(wrapper.GDPRList[i].contactId.subString(0,3) == '003'){
                    Contact toInsert = new Contact();
                    toInsert.firstName = wrapper.GDPRList[i].firstName;
                    toInsert.lastName = wrapper.GDPRList[i].lastName;
                    toInsert.email = wrapper.GDPRList[i].email;
                    toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
                    toInsert.Id = wrapper.GDPRList[i].contactId;
                    toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
                    toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
                    toInsert.Product_Information__c = wrapper.GDPRList[i].support;
                    toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
                    toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
                    contactPref.add(toInsert);
           
                }
            }
        else{
             Contact toInsert = new Contact();
             toInsert.firstName = wrapper.GDPRList[i].firstName;
             toInsert.lastName = wrapper.GDPRList[i].lastName;
             toInsert.email = wrapper.GDPRList[i].email;
             toInsert.Email_Hash__c = wrapper.GDPRList[i].emailHash;
             
             toInsert.Sales_and_Marketing__c = wrapper.GDPRList[i].marketing;
             toInsert.Critical_Security_Notes__c = wrapper.GDPRList[i].security;
             toInsert.Product_Information__c = wrapper.GDPRList[i].support;
             toInsert.Contact_Via_Text__c = wrapper.GDPRList[i].contactPhone;
             toInsert.Contact_Via_Email__c = wrapper.GDPRList[i].contactEmail;
             newContacts.add(toInsert);
        
        
        }
           
            
          
        
        }
          try{
              if(contactPref.size()>0){
                  upsert contactPref;
              }
              if(NewContacts.size()>0){
                  insert NewContacts;
              }          
            } 
            catch(DmlException e){
                    System.debug('An unexpected error has occured: ' + e.getMessage());
                }
      
      }
     }

Test Class:
@isTest
private class JSONDeserializeTest {

        @isTest static void testCalloutEithStaticResource(){
            StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
            mock.setStaticResource('GDPR');
            mock.setStatusCode(200);
            mock.setHeader('Content-Type', 'application/json');
            
            Test.setMock(HttpCalloutMock.class, mock);
            HttpResponse res = JSONDeserialize.deserialize();
            System.assertEquals('PRIVATE DATA', res.getBody());
            System.assertEquals(200, res.getStatusCode());
            System.assertEquals('application/json', res.getHeader('Content-Type'));
        
        
        }


}

Trigger:
 
trigger GDPR_Prefrences_Updater on Contact (after insert, after update) {
   if(System.IsBatch() == false && System.isFuture() == false)
    {
        JSONDeserialize.firecallout('callout fires');
    }

}

Errors:
User-added image
Hi,

I have an Apex Code that I believe relates to creating a new record from a custom object in a transaction wizard.

This is part of the code:
 
// Create order
        Order__c newOrder = new Order__c(
            Status__c = 'Draft',
            Primary_Account__c = primary.get(0).record.Account.Id,
            Primary_Contact__c = primary.get(0).record.Id,
            Advisor__c = (primaryRole == 'Advisor' || primaryRole == 'Calling On Behalf Of Investor' ? investor.get(0).record.Id : null)
        );
        insert newOrder;

        // Create purchases
        List<Transaction__c> newTransactions = new List<Transaction__c>();
        List<Current_Holding__c> modifiedHolders = new List<Current_Holding__c>();
        List<String> newTransactionTypes = new List<String>();
        for (Purchase t : purchases) {
            for (PurchaseRecord p : t.purchases) {
                
                if (p.isValid()) {
                    
                    Transaction__c purchase = new Transaction__c(
                        RecordTypeId = t.record.RecordTypeId,
                        Order__c = newOrder.Id,                      
                        Transaction_Reason__c = t.record.Transaction_Reason__c,
                        Campaign_Source__c = t.record.Campaign_Source__c,
                        Gift_Card_Required__c = t.record.Gift_Card_Required__c,
                        Gift_Card_To__c = t.record.Gift_Card_To__c,
                        Gift_Card_From__c = t.record.Gift_Card_From__c,
                        Occasion__c = t.record.Occasion__c,
                        Registration_Type__c = t.record.Registration_Type__c,
                        Entry_Type__c = (t.record.Registration_Type__c == 'Registered Account' ? t.record.Entry_Type__c : 'Book Entry'),
                        Payment_Method__c = t.record.Payment_Method__c,
                        Issue__c = p.record.Issue__c,
                        Rate__c = p.record.Rate__c,
                        Units__c = p.record.Units__c,
                        Increment__c = 0,
                        Amount__c = p.bondDetails.Minimum_Subscription__c * p.record.Units__c,
                        CurrencyIsoCode = issueCurrencyMap.get(p.record.Issue__c)
                    );

In the part of order creation, I would like to add the update of the currency from the wizard, just like it is on the second part of the code.
However, I get an error when trying to copy and paste it from one part to another.
Note: the currency is currently shown as the default currency.

Any suggestions on how to make sure that the currency chosen in the wizard will be inserted in the 'order' record?

Thank you for your help!
Guys, I am an Admin who needs help from a developer. I have an apex trigger that was written and implemented by a contractor. It is on Contacts object. What is does is assign the contact to an owner based on the first three digits of the postal code. I need to have the same assignment triggger on Leads object.
VF Page
<apex:page Controller="Contactsrd" sidebar="false">  
  <style type="text/css">  
  .popup {  
  background-color: White;  
  border-width: 2px;  
  border-style: solid;  
  z-index: 9999;  
  left: 50%;  
  padding:10px;  
  position: absolute;  
  width: 400px;  
  margin-left: -250px;  
  top:80px;  
  }  
  .popupBg{  
  background-color:grey;  
  opacity: 0.20;  
  filter: alpha(opacity = 70);  
  position: absolute;  
  width: 100%;  
  height: 100%;  
  top: 0;  
  left: 0;  
  z-index: 9998;  
  }  
  </style>  
  <apex:form id="form">  
  <apex:pageblock id="pb">   
  <apex:pageBlockTable id="pbt" value="{!getcontactt}" var="ct">  
  <apex:column headerValue="Contact Name">  
  <apex:outputText value="{!ct.name}"></apex:outputText>   
  </apex:column>  
  <apex:column headerValue="Detail">  
  <apex:outputPanel >  
  <apex:actionSupport event="onclick" action="{!detailPage}" rerender="popup,pb">  
  <input type="radio" name="det" />  
  <apex:param value="{!ct.id}" assignTo="{!id}" name="id"/>  
  </apex:actionSupport>  
  </apex:outputPanel>  
  </apex:column>  
  </apex:pageBlockTable>  
 </apex:pageblock>  
 <!--popup code starts-->  
  <apex:outputPanel id="popup">  
  <apex:outputPanel styleClass="popupBg" layout="block" rendered="{!displayPopUp}"/>  
  <apex:outputPanel styleClass="popup" layout="block" rendered="{!displayPopUp}">  
  <apex:messages />  
  <center><h2>{!ct_name} Information</h2></center>  
  <apex:panelGrid columns="2" >  
  <apex:outputLabel value="Contacts"/>
      <apex:inputText value="{!ct_name}"></apex:inputText>
  <apex:commandButton value="Update" action="{!updaterec}"/>  
  <apex:commandButton value="cancel" action="{!closePopup}" rerender="popup,pb"/>  
  </apex:panelGrid>
      
  </apex:outputPanel>  
  </apex:outputPanel>  
 <!-- end of popup code-->  
  </apex:form>  
 </apex:page>
Controller:
public class Contactsrd{
  Public String ct_name { get; set; }  
  public boolean displayPopUp { get; set; }  
  Contact cont {get; set;}
   List<Contact> clist= new List<Contact>();
     //cont= new contact();
 public PageReference closePopup() {//hide method  
  displayPopup = false;  
  return null;  
  }  
 public PageReference detailPage() {// action method which shows popup on selection  
  displayPopup = true;  
  system.debug('Select Item Id is :'+ApexPages.currentPage().getParameters().get('id'));  
  String id = ApexPages.currentPage().getParameters().get('id'); 
  Contact ac = [select id,name from Contact where id =: id];
  ct_name = ac.name; 
  //update ac;
  return null;  
  }  
  public list<Contact> getGetContactt() {  
  list<Contact> ctl = [select id,name from Contact];  
  return ctl;  
  }  
  public Contactsrd(){
  Id id= ApexPages.currentPage().getParameters().get('id');
  cont=(id==null)? new Contact():[Select lastName FROM Contact Where Id= :id];
  }
 public PageReference updaterec() {//update popup record   
  //displayPopup = true; 
  Try{upsert(cont);}catch(system.DMLException e){ApexPages.addMessages(e); return null;}
  //try{
  //contact c= [SELECT Id FROM Contact WHERE Id=:id];
  //c.Salutation= ct_name;
  //c.FirstName=ct_name;
  //c.LastName=ct_name;
  //update cont;
  return null;  
  }  
  }
See below image.I got an error while upserting record.

User-added image
Hi There,

I would like to know is there any possibility to restrict users from creating more than a single opportunity per day by per person on Acount object?

Thanks
Syed
Hi Experts,

I have added a button "opt-out" in the email template.
This email will be sent to people and when they click the opt-out button, then the stage in opportunity should change to opt out.
How can do this

Please help.
Thanks.