• aam1r
  • NEWBIE
  • 25 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 30
    Replies
Call Visualforce Page Method from Apex Class

Hi everyone,
Is it possible to call a VF page from another apex class?  I currently have a vf page that generates a document and emails it to the contact on an opportunity.  This is executed via an action button.
I have created a lightning component that enlists filtered opportunities and I want to click a button to send the above generated documents, per opportunity to their linked contacts.  
The VF page has the following variables:
<apex:variable var="CompanyName" value="{!CompanyName}" />
<apex:variable var="OppId" value="{!OppId}" />
<apex:variable var="year" value="{!year}" />
<apex:variable var="emailStr" value="{!emailStr}" />
The VF page controller has the following class members:
    public String CompanyName {get;set;}
    public String OppId {get;set;}
    public Integer year {get;set;}
    public String emailStr {get;set;}
and has the following method in the VF page controller is what I want to call that creates the document and sends the email:
public PageReference CreateAndSendPdf() {
I need to be able to set the above parameters and then call the method from the new batch class.  What I’ve tried so far is:
if (lstValidOpps.size() > 0){
   for (Opportunity o : lstValidOpps){
                        
       PageReference pr = new PageReference('/apex/vfPage');
       // set query string parameters and values for the page
       pr.getParameters().put('oppId',o.Id);
       pr.getParameters().put('year','2028');
       pr.getParameters().put('emailStr','aam1r@mail.com');
       //pr.CreateAndSendPdf(); // This line fails
       }
   }
}
However I get an error when I save the batch class.  Line pr.CreateAndSendPdf() throws:
Method does not exist or incorrect signature: void CreateAndSendPdf() from the type System.PageReference
Sorry, I’ve not included all the code as there’s quite a lot of it, but the essentials are included. 
Any ideas how I can achieve this?
aam1r
  • August 02, 2021
  • Like
  • 0
Hi everyone.  I hope you can help with an issue i'm having around sending emails from apex.

What's the setup?
I have a web-to-case form setup, which is working fine in all aspects. I have a trigger/class that will verify the information and send an email back if details could not be found/matched in salesforce.  Valid cases come through just fine, having the System user as the CreatedBy.  Invalid or unmatched details have a process in place where the case is deleted and an email sent out to the address provided on the form asking the person to call instead.  The sender of this email is set from the Oeg-Wide Email Address list.  Here's an extract of the code handling this:
EmailTemplate emailTemplate = [SELECT Id, Body, HtmlValue FROM EmailTemplate WHERE DeveloperName = 'Case_W2C_Details_Mismatch_Template'];
            System.debug('Email template ID = '+emailTemplate.Id);
            OrgWideEmailAddress owea = [SELECT Id, Address, DisplayName FROM OrgWideEmailAddress WHERE Address = 'No-Reply@company.co.uk'];
            System.debug('Email address Id for sender = '+owea.Id);
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            if ( owea != null) {email.setOrgWideEmailAddressId(owea.Id);}
            email.setToAddresses(emailAddresses);
            email.setSaveAsActivity(false);
            email.setSubject('Online Enquiry');
            email.setHtmlBody(emailTemplate.HtmlValue);
            email.setTemplateId(emailTemplate.Id);

            if(EmailDeliverabilityEnabled){
                Messaging.SendEmailResult [] res = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
                System.debug('Send email result' + res);
            }
            else {
                System.debug('WebToCaseService_Error: Email Deliverability is not enabled');
            }

So what's the issue then?
Every part of the process is working fine except the latter, where details are unmatched.  No email is going out to the address provided and in the logs i get this error:

EXCEPTION_THROWN|[169]|System.EmailException: SendEmail failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_OR_READONLY, Not profiled to access this Org-wide Email Address: []

What have i already tried?
1. I went to the no-reply email address in the Org-Wide Email Adresses and edited it to "Allow All Profiles to Use this From Address"

User-added image
This does work, however it allows users to be able to select this email when sending emssages via salesforce - whcih we don't want. 

2. If i "Allow only selected profiles.." and include System Administrator the above error is still faced. 

3. If i "Allow only selected profiles.." and manually select all listed profiles - i still get the same error.

4. I then set up another default no-reply address as a "Special Purpose Org-Wide Email Address" and changing the code to use this instead.  This also worked but is an address inaccessible to selected profiles, so doesn't resolve the issue without creating another.

My Questions then
Why would System user not be allowed access to Org-Wide Emails?  Is there a way around this without setting up a second no-reply address specifically for this purpose?

Many thanks for reading through this.
Aamir
  • July 26, 2021
  • Like
  • 1
I'm hoping someone can help.  I have a batch job that is run via a button click in a Lightning page.  the fucnitonality works fine but i'm struggling with the test class.  After i call the Batch apex method to test, i'm getting full code coverage but any asserts afetr the run are not returning records as i'd expect.  In fact, it's not returning any records.

Here is the test code extract that is executing the batch class:
@isTest
    public static void test_FirstHeaderGeneratorBatch_2(){
        
        String OppToTest = 'Opportunity 1';

        Opportunity opp = [SELECT Id, First_Header_Required__c, First_Header_Created__c, AccountId FROM Opportunity WHERE Name =:OppToTest LIMIT 1];
        System.assert(opp.First_Header_Created__c==false, OppToTest+' should not have processed invoicing');    // succeeds

        Integer headersBefore = [SELECT Id FROM Header__c WHERE Opportunity__c = :opp.Id].size();
        System.assert(headersBefore == 0, OppToTest+' should not have generated headers');  // succeeds

        List<OpportunityLineItem> olis = [SELECT Id, Ordered_Date__c, First_Payment_Date__c, Supplier__r.Name
                                        FROM OpportunityLineItem WHERE OpportunityId =: opp.Id];
        for (OpportunityLineItem oli : olis) {
            System.assert(oli.Ordered_Date__c==null, OppToTest+' should not have ordered products');
        }

        for (OpportunityLineItem oli : olis) {
            if (oli.Supplier__r.Name=='InternalSupplier'){
                oli.Ordered_Date__c = System.today();  
                oli.First_Payment_Date__c = System.today().addMonths(1);
            }
        }

        update olis;

        Test.startTest(); ////////////////////////////////////////
            FirstHeaderGeneratorBatch.executeBatch(Date.today());
        Test.stopTest(); /////////////////////////////////////////
        
        Integer headersAfter = [SELECT Id FROM Header__c WHERE Opportunity__c = :opp.Id].size();
        
        /////// ASSERT FAILS
        System.assert(headersAfter > 0, 'Additional header(s) should have been created. Before: '+headersBefore+', After: '+headersAfter); 
    
    }
The batch does execute and teh logs are showing teh whole process, however the last assert is returning zero.  The query (at line 31) 
Integer headersAfter = [SELECT Id FROM Header__c WHERE Opportunity__c = :opp.Id].size();
.. returns zero records, although i can see the inserts succeeding as part of the batch class execution.

A debug on the batch class post insert:
insert headersToInsert;
 System.debug(' ^^^ LineItems inserted: '+[SELECT Id FROM Header__c].size());
..returns as expected in the logs:
User-added image
Can someone help me understand what i could be doing wrong please?

Many thanks for your time and apologies if my question was not asked in the best of ways.

regards,
Aamir
  • May 22, 2021
  • Like
  • 0
Hi Everyone,

I'm passing a salesforce record that includes date fields to a Lightning compnent's helper class.  The page renders a Lightning datatable and displays the results as expected.  However, the page loads and runs very slow.  Looking at the console logs i can see a huge count of warnings, which i believe is the culprit.  The message that pops up for these logs is as follows:

"<lightning-formatted-date-time> The value attribute accepts either a Date object, a timestamp, or a valid ISO8601 formatted string with timezone offset. but we are getting the object value "Invalid Date" instead."

The Helper class defines the columns and teh formatting as:
{label: 'Ordered Date',     fieldName: 'Ordered_Date__c',           type: 'date', typeAttributes:{year: 'numeric', month:'numeric',day:'numeric'} }
The component utilises the datatable and renders the data correctly but very slow.  Here is the use of the datatable:
<lightning:datatable aura:id="datatable" data="{! v.data }" columns="{! v.columns }" >
The v.data receives the List<Object> from apex and the v.columns is defined in the helper.js class.

I'm guessing it's some issue with how JS and Apex communicate dates but i'm very new to JS so cannot figure out what the issue could be.  Very sorry if teh question is not detailed abundantly.  If someone can give some guidance it would be great, as i really want to rid this error.  It takes too long to load the page with anything more than a a hundred records.

Thanks
Aamir
  • April 02, 2021
  • Like
  • 0
I have two clases:
1. a controller class to a vf page and another as
2. a helper class accessed by multple classes. 

I have a simple query running in the helper class that is failing to return any records:
...
public static void refreshOrder(Id orderId, Id accountId){

        // Retrieve the Order
        Order ord = [Select Id, Name, Status From Order Where Id = :orderId];

...
The controller class that calls the above method has the following extract:
...

Order order = new Order(
    Pricebook2Id = OrderHelper.getStandardPriceBookId(),
    Status = ORDER_STATUS_PENDING_PAYMENT, 
    AccountId = acc.Id
    EffectiveDate = System.today(),
    CurrencyIsoCode=pkgCurrencyCode
 );
        
 insert order;

OrderHelper.refreshOrder(order.Id, acc.Id);
...
Any idea why a system.debug in the helper class does show a valid Order Id being apssed but then the simple order query does not return anything, and instead throws an error:
"List has no rows for assignment to SObject" ?
 
  • January 24, 2020
  • Like
  • 0
Hi, I hope someone can point me in the right direction here.

I'm facing an issue with a SIte Guest User unable to insert a record via VF pages and Controller.  I have tracked the issue down to an insert of a custom object record - in my case Booking__c.  Its quite a large class, which i'm not going to paste here.  

The Booking object has a lookup to Contact and Order objects and also a custom Event, with the latter being a M-D relationship.  I have checked the CRUD for thsi user's profile and it has View All and Modifiy all for Booking and Event and it has as much access as can be granted for Contacts and Orders (being Standard objects).  I have granted this user's Field-Level securty (accessibility) read and edit on each of teh above mentioned objects.

However, when i get to the of..
insert booking;
in my code, i get:
Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []
And i haven't a clue what coudl be wrong.  Coincidently, this issue suddenly arose in our sandbox last weekend when Spring 20 came about, however i was also developing at the time so its a stale-mate situation right now.

Any pointers would be great.

Thanks
Aamir

 
  • January 09, 2020
  • Like
  • 0
Hi Guys,

This may be something i kick myself with (and i hope it is) but i have a simple query in my apex code and i cannot understand why it has started failing for a specific site guest user.  Here's an extract form my class that contains the query:
// Retrieve the Order
System.debug('*** Ref: orderId = ' + orderId);
System.debug('*** Current user = ' + [select name from user where id = :userinfo.getuserid()].name);

Order ord = [Select Id, Name, Status From Order Where Id = :orderId];
I'm leaving the debug steps in here so we can see the debug logs:
USER_DEBUG|[106]|DEBUG|*** Ref: orderId = 8013N000000YSUoQAO
SOQL_EXECUTE_BEGIN|[107]|Aggregations:0|SELECT name FROM user WHERE id = :tmpVar1
SOQL_EXECUTE_END|[107]|Rows:1
USER_DEBUG|[107]|DEBUG|*** Current user = Site Guest User
SOQL_EXECUTE_BEGIN|[108]|Aggregations:0|SELECT Id, Name, Status FROM Order WHERE Id = :tmpVar1
SOQL_EXECUTE_END|[108]|Rows:0
SYSTEM_MODE_EXIT|false
FATAL_ERROR|System.QueryException: List has no rows for assignment to SObject
Now, looking in Salesforce, the record id for Order 8013N000000YSUoQAO does exist.  it has created by and owner as Site Guest User.  If i change the query on the order to be without the where clause for the order id and execute the same steps then i do get a number of Order IDs returned.  if i run teh query as anonymous, it works fine.  If i run the same steps for system admin it works fine. I have checked to make sure teh Site Guest User has CRUD access to Order  object and it does.

Either i've worked on this project too long and intensivley that i cannot see the obvious or something else is missing that i'm not catching.

Can someone please make a suggestion please?

Thanks
Aamir
 
  • January 05, 2020
  • Like
  • 0
Hi everyone,

I hope you are able to help me out here.  I currently have a Visualforce page with an iframe that displays a third-party form.  Upon completion of this form i get a success message within the iframe and a button that say Finish.  The Finish button is programmed to redirect to a URL (a visualfofrce page) stored on a field on a record.  However, this redirect does not happen.

I've been told that using PostMessage, along with an event listener to trap events will help me resolve this but i'm unable to figure out how to code this.

My Visualforce page outputPanel is as follows:
<apex:outputPanel layout="block" id="aContainer" style="width: 500px; height: 1000px; margin: 0 auto;">
          <apex:outputtext escape="false" value="{!APayForm}"></apex:outputtext>
          <apex:iframe width="100%" height="1000px" src="" scrolling="true" id="paymentFrame" frameborder="false"/>
          <script>
                    document.getElementById('APayForm').submit();
          </script>
</apex:outputPanel>
The APayForm is built dynamically usinga controller and teh following is an example of what is returned and used in teh outputPanel value above;
// example: <form target="paymentFrame" action="https://test.protected.net/PMWeb1?pRef=1837&amp;pid=a233N0000008SgR" method="post" id="APayForm" >
The Cancel button on teh form returns and event 'a--cancel' and the finish button retruns and event 'a--exit'.  how can use these events to redirct to the same visualforce page called 'PostPayment', which renders a message according to the status of a parent record.  The PostPayment page renders correctly but i'm unable to redirect to it.

Can someone help me figure out the code required for the postMessage and event listener (also where this is to be coded) please?
 
  • December 06, 2019
  • Like
  • 0
Is there an easy way to count how many times some text or substring appears in an apex string variable?  So if a a varibale holds "The quick brown fox jumps over the lazy dog"  i want to find how many times fox appears in this string.
  • November 13, 2019
  • Like
  • 0
Hi, I've exported all teh notes from an Org and want to import them as ContentNotes (Enhanced Notes).  The problem i'm facing is that the export csv file contains the notes along with all other system fields as expected.  However, when i want to import into ContentNotes the Content field is expecting a directory path to an individual file (eg. txt) and does not accept a simple field mapping.  How can i work around this?  Is there a way of exporting Notes as txt files?
  • January 12, 2017
  • Like
  • 0
Hi Guys, 

I know its another one, but i've looked at similar issues to see if i can identify the cause of my code coverage failure but have not found anything.  So, i'm getting 0% code coverage for a new trigger and cannot see why.  Here is my Trigger:
 
trigger MilestoneTaskTrigger on MPM4_BASE__Milestone1_Task__c (before insert, before update) {

if ((Trigger.isBefore && Trigger.isInsert) || (Trigger.isBefore && Trigger.isUpdate)){


	// Create list to hold Milestone Components to update
	List<Milestone_Component__c> components = new List<Milestone_Component__c>();

	// Get list of all Milestone Components that are set in Prod but not in Test
	List<Milestone_Component__c> cmps = [SELECT Id FROM Milestone_Component__c WHERE PROD__c = True AND Test_Sandbox__c = False];

	for (Milestone_Component__c c : cmps){
		c.Test_Sandbox__c = True;
		components.add(c);
	}

	for (MPM4_BASE__Milestone1_Task__c task : System.Trigger.new){
		// Is Refresh Test checked
		if (task.Refresh_Test__c == True && task.MPM4_BASE__Complete__c == True){
			// update all milestone components
			update components;

			// unset Resfresh Test checkbox
			task.Refresh_Test__c = False;
		}
	}
}

}

And here's my test class:
 
@isTest
public with sharing class MilestoneTaskTriggerTest {
	static testMethod void  MilestoneTaskTriggerTest() {
		
		// Insert Project
		System.debug('Inserting Milestone Project');
        MPM4_BASE__Milestone1_Project__c project = new MPM4_BASE__Milestone1_Project__c (Name='DEVELOPMENT');
        try { insert project; } catch (exception e) {}

        // get Salesforce Project record type for Milestone? - Nah!! default record type will be used.
        
        // Insert Milestone
        System.debug('Inserting Milestone');
        MPM4_BASE__Milestone1_Milestone__c milestone = new MPM4_BASE__Milestone1_Milestone__c(Name='Milestone', MPM4_BASE__Project__c=project.id);
        try { insert milestone; } catch (exception e) {}
		
		// Insert Task
		System.debug('Inserting Task');
        MPM4_BASE__Milestone1_Task__c task = new MPM4_BASE__Milestone1_Task__c(Name='Task', MPM4_BASE__Priority__c='4 - Low');
        try { insert task; } catch (exception e) {}

		// Insert Components (x3)
		System.debug('Inserting Components');
        Component__c component1 = new Component__c(Name='Comp1');
        try { insert component1; } catch (exception e) {}

        Component__c component2 = new Component__c(Name='Comp2');
        try { insert component2; } catch (exception e) {}

        Component__c component3 = new Component__c(Name='Comp3');
        try { insert component3; } catch (exception e) {}

        Component__c component4 = new Component__c(Name='Comp4');
        try { insert component4; } catch (exception e) {}

		// Insert Milestone Components (x3) setting Prod in one of them and 2 in test
		System.debug('Inserting Milestone Components');
        Milestone_Component__c mscomponent1 = new Milestone_Component__c(SFDC_Component__c=component1.id, Test_Sandbox__c=False, PROD__c=TRUE, Milestone__c=milestone.id, Task__c=task.id, Action__c='Update');
        try { insert mscomponent1; } catch (exception e) {}

        Milestone_Component__c mscomponent2 = new Milestone_Component__c(SFDC_Component__c=component2.id, Test_Sandbox__c=TRUE, PROD__c=False, Milestone__c=milestone.id, Task__c=task.id, Action__c='Update');
        try { insert mscomponent2; } catch (exception e) {}

        Milestone_Component__c mscomponent3 = new Milestone_Component__c(SFDC_Component__c=component3.id, Test_Sandbox__c=TRUE, PROD__c=False, Milestone__c=milestone.id, Task__c=task.id, Action__c='Update');
        try { insert mscomponent3; } catch (exception e) {}

        Milestone_Component__c mscomponent4 = new Milestone_Component__c(SFDC_Component__c=component4.id, Test_Sandbox__c=False, PROD__c=False, Milestone__c=milestone.id, Task__c=task.id, Action__c='Update');
        try { insert mscomponent4; } catch (exception e) {}

		// Update Task.Refresh_Test__c to true and set task to complete
		System.debug('Updating Task');
        task.Refresh_Test__c = TRUE;
        task.MPM4_BASE__Complete__c = TRUE;
        try { update task; } catch (exception e) {}

		// Check that there are 3 Milestone Components flagged as in Test
		List<Milestone_Component__c> mscomponents = [SELECT Id FROM Milestone_Component__c WHERE Test_Sandbox__c = TRUE];
		System.assertEquals(false, mscomponents.size()==3, ' there should be only 3 milestone components with Test Sandbox set as true');

		// Check that the Refresh_Test__c flag is false now.
		MPM4_BASE__Milestone1_Task__c checktask = [SELECT Id, Refresh_Test__c FROM MPM4_BASE__Milestone1_Task__c WHERE Id = :task.id];
		System.assertEquals(false, checktask.Refresh_Test__c==False, ' Refresh Test flag should be false!');

	}
}

Any help is greatly appreciated.
Thanks
Aamir
  • June 22, 2016
  • Like
  • 0
Hi Everyone,

Requirement: Capture Find Duplicates button click event on Lead records

Current Solution: I currently have a Javascript button that checks a box on a Lead record when it is clicked and directs the page to the leadmergewizard.jsp page.  Here is the Javascript begind the button currently:
 
{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/33.0/apex.js")}

var ld = new sforce.SObject("Lead");
ld.Id = '{!Lead.Id}';
ld.Duplicate_Searched__c = 1;

var result = sforce.connection.update([ld]);
if(result[0].getBoolean("success"))
{
window.location = "/lead/leadmergewizard.jsp?retURL=%2F{!Lead.Id}&id={!Lead.Id}&00Ne0000001OKhg=1";
}
else{
alert('Error : '+result);
}

New Solution needed: The above setup works fine, however i want to implement something that does this via Global Action so i can have this functionality on mobile and also Lightneing Experience.

Is this possible, and can someone guide me with any sample code if i need to implement this using triggers, classes and/or vf pages?

Many thanks for your help.
aamir
 
  • May 25, 2016
  • Like
  • 0
Hi, I am trying to use a record lookup to return a list of Accounts that are of certain record types (say 'Local' and 'National').  I can easliy do this for either 'Local' or 'National' but cannot find a way of including both except to list every type and set Record Type not equal to (all the rest of Record types). Essentially, i'm after an OR condition / logic for my setup in Flow.  Here is what i'm trying to achieve but it doesn't work:

User-added image

Any help is greatly appreciated.

Aamir
  • April 20, 2016
  • Like
  • 0
Hi, i'm trying to record the start of day date/time value for a given Business Hour as part of an Apex trigger but not sure of the way to do this.  Can someone help me try and achieve this please? The basic logc is to check what day it is today and then record the Start of Day date/time in to a field  (Start_of_Day__c) for that same day defined for the Business Hour.

Thanks
  • March 07, 2016
  • Like
  • 0
Hi everyone.  I hope you can help with an issue i'm having around sending emails from apex.

What's the setup?
I have a web-to-case form setup, which is working fine in all aspects. I have a trigger/class that will verify the information and send an email back if details could not be found/matched in salesforce.  Valid cases come through just fine, having the System user as the CreatedBy.  Invalid or unmatched details have a process in place where the case is deleted and an email sent out to the address provided on the form asking the person to call instead.  The sender of this email is set from the Oeg-Wide Email Address list.  Here's an extract of the code handling this:
EmailTemplate emailTemplate = [SELECT Id, Body, HtmlValue FROM EmailTemplate WHERE DeveloperName = 'Case_W2C_Details_Mismatch_Template'];
            System.debug('Email template ID = '+emailTemplate.Id);
            OrgWideEmailAddress owea = [SELECT Id, Address, DisplayName FROM OrgWideEmailAddress WHERE Address = 'No-Reply@company.co.uk'];
            System.debug('Email address Id for sender = '+owea.Id);
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            if ( owea != null) {email.setOrgWideEmailAddressId(owea.Id);}
            email.setToAddresses(emailAddresses);
            email.setSaveAsActivity(false);
            email.setSubject('Online Enquiry');
            email.setHtmlBody(emailTemplate.HtmlValue);
            email.setTemplateId(emailTemplate.Id);

            if(EmailDeliverabilityEnabled){
                Messaging.SendEmailResult [] res = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
                System.debug('Send email result' + res);
            }
            else {
                System.debug('WebToCaseService_Error: Email Deliverability is not enabled');
            }

So what's the issue then?
Every part of the process is working fine except the latter, where details are unmatched.  No email is going out to the address provided and in the logs i get this error:

EXCEPTION_THROWN|[169]|System.EmailException: SendEmail failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_OR_READONLY, Not profiled to access this Org-wide Email Address: []

What have i already tried?
1. I went to the no-reply email address in the Org-Wide Email Adresses and edited it to "Allow All Profiles to Use this From Address"

User-added image
This does work, however it allows users to be able to select this email when sending emssages via salesforce - whcih we don't want. 

2. If i "Allow only selected profiles.." and include System Administrator the above error is still faced. 

3. If i "Allow only selected profiles.." and manually select all listed profiles - i still get the same error.

4. I then set up another default no-reply address as a "Special Purpose Org-Wide Email Address" and changing the code to use this instead.  This also worked but is an address inaccessible to selected profiles, so doesn't resolve the issue without creating another.

My Questions then
Why would System user not be allowed access to Org-Wide Emails?  Is there a way around this without setting up a second no-reply address specifically for this purpose?

Many thanks for reading through this.
Aamir
  • July 26, 2021
  • Like
  • 1
Call Visualforce Page Method from Apex Class

Hi everyone,
Is it possible to call a VF page from another apex class?  I currently have a vf page that generates a document and emails it to the contact on an opportunity.  This is executed via an action button.
I have created a lightning component that enlists filtered opportunities and I want to click a button to send the above generated documents, per opportunity to their linked contacts.  
The VF page has the following variables:
<apex:variable var="CompanyName" value="{!CompanyName}" />
<apex:variable var="OppId" value="{!OppId}" />
<apex:variable var="year" value="{!year}" />
<apex:variable var="emailStr" value="{!emailStr}" />
The VF page controller has the following class members:
    public String CompanyName {get;set;}
    public String OppId {get;set;}
    public Integer year {get;set;}
    public String emailStr {get;set;}
and has the following method in the VF page controller is what I want to call that creates the document and sends the email:
public PageReference CreateAndSendPdf() {
I need to be able to set the above parameters and then call the method from the new batch class.  What I’ve tried so far is:
if (lstValidOpps.size() > 0){
   for (Opportunity o : lstValidOpps){
                        
       PageReference pr = new PageReference('/apex/vfPage');
       // set query string parameters and values for the page
       pr.getParameters().put('oppId',o.Id);
       pr.getParameters().put('year','2028');
       pr.getParameters().put('emailStr','aam1r@mail.com');
       //pr.CreateAndSendPdf(); // This line fails
       }
   }
}
However I get an error when I save the batch class.  Line pr.CreateAndSendPdf() throws:
Method does not exist or incorrect signature: void CreateAndSendPdf() from the type System.PageReference
Sorry, I’ve not included all the code as there’s quite a lot of it, but the essentials are included. 
Any ideas how I can achieve this?
aam1r
  • August 02, 2021
  • Like
  • 0
I'm hoping someone can help.  I have a batch job that is run via a button click in a Lightning page.  the fucnitonality works fine but i'm struggling with the test class.  After i call the Batch apex method to test, i'm getting full code coverage but any asserts afetr the run are not returning records as i'd expect.  In fact, it's not returning any records.

Here is the test code extract that is executing the batch class:
@isTest
    public static void test_FirstHeaderGeneratorBatch_2(){
        
        String OppToTest = 'Opportunity 1';

        Opportunity opp = [SELECT Id, First_Header_Required__c, First_Header_Created__c, AccountId FROM Opportunity WHERE Name =:OppToTest LIMIT 1];
        System.assert(opp.First_Header_Created__c==false, OppToTest+' should not have processed invoicing');    // succeeds

        Integer headersBefore = [SELECT Id FROM Header__c WHERE Opportunity__c = :opp.Id].size();
        System.assert(headersBefore == 0, OppToTest+' should not have generated headers');  // succeeds

        List<OpportunityLineItem> olis = [SELECT Id, Ordered_Date__c, First_Payment_Date__c, Supplier__r.Name
                                        FROM OpportunityLineItem WHERE OpportunityId =: opp.Id];
        for (OpportunityLineItem oli : olis) {
            System.assert(oli.Ordered_Date__c==null, OppToTest+' should not have ordered products');
        }

        for (OpportunityLineItem oli : olis) {
            if (oli.Supplier__r.Name=='InternalSupplier'){
                oli.Ordered_Date__c = System.today();  
                oli.First_Payment_Date__c = System.today().addMonths(1);
            }
        }

        update olis;

        Test.startTest(); ////////////////////////////////////////
            FirstHeaderGeneratorBatch.executeBatch(Date.today());
        Test.stopTest(); /////////////////////////////////////////
        
        Integer headersAfter = [SELECT Id FROM Header__c WHERE Opportunity__c = :opp.Id].size();
        
        /////// ASSERT FAILS
        System.assert(headersAfter > 0, 'Additional header(s) should have been created. Before: '+headersBefore+', After: '+headersAfter); 
    
    }
The batch does execute and teh logs are showing teh whole process, however the last assert is returning zero.  The query (at line 31) 
Integer headersAfter = [SELECT Id FROM Header__c WHERE Opportunity__c = :opp.Id].size();
.. returns zero records, although i can see the inserts succeeding as part of the batch class execution.

A debug on the batch class post insert:
insert headersToInsert;
 System.debug(' ^^^ LineItems inserted: '+[SELECT Id FROM Header__c].size());
..returns as expected in the logs:
User-added image
Can someone help me understand what i could be doing wrong please?

Many thanks for your time and apologies if my question was not asked in the best of ways.

regards,
Aamir
  • May 22, 2021
  • Like
  • 0
Hi Everyone,

I'm passing a salesforce record that includes date fields to a Lightning compnent's helper class.  The page renders a Lightning datatable and displays the results as expected.  However, the page loads and runs very slow.  Looking at the console logs i can see a huge count of warnings, which i believe is the culprit.  The message that pops up for these logs is as follows:

"<lightning-formatted-date-time> The value attribute accepts either a Date object, a timestamp, or a valid ISO8601 formatted string with timezone offset. but we are getting the object value "Invalid Date" instead."

The Helper class defines the columns and teh formatting as:
{label: 'Ordered Date',     fieldName: 'Ordered_Date__c',           type: 'date', typeAttributes:{year: 'numeric', month:'numeric',day:'numeric'} }
The component utilises the datatable and renders the data correctly but very slow.  Here is the use of the datatable:
<lightning:datatable aura:id="datatable" data="{! v.data }" columns="{! v.columns }" >
The v.data receives the List<Object> from apex and the v.columns is defined in the helper.js class.

I'm guessing it's some issue with how JS and Apex communicate dates but i'm very new to JS so cannot figure out what the issue could be.  Very sorry if teh question is not detailed abundantly.  If someone can give some guidance it would be great, as i really want to rid this error.  It takes too long to load the page with anything more than a a hundred records.

Thanks
Aamir
  • April 02, 2021
  • Like
  • 0
We have a custom object called "X" and we have DocuSign linked to it. I need to customize a custom button so that it auto populates the DocuSign Envelope's Recipient section using a custom field called email in X Here is what I have done currently and what is the requirement
a. Name of the field in the custom object X is Email__c (type text)
b. I have kept the Add recipients section blank in the Docusign panel ,however in doing so I am loosing out on all the custom tags which I had set for the template.
c. I have created a custom button and the contents are

 
!URLFOR('/apex/dsfs__DocuSign_CreateEnvelope', null, [
SourceID = X.Id ,
CCRM = 'Decision Maker~Signer 1',
CCTM = 'Decision Maker~Signer',
DST = '873cd9f7-c905-4340-996e-e166e3594a1c',
**CRL = 'Email~' +X.Email__c ,**
OCO = 'Send',
LA = '0',
LF = '0',
OCO = 'Tag'
]
)}

We have a custom object called "X" and we have DocuSign linked to it. I need to customize a custom button so that it auto populates the DocuSign Envelope's Recipient section using a custom field called email in X Here is what I have done currently and what is the requirement
a. Name of the field in the custom object X is Email__c (type text)
b. I have kept the Add recipients section blank in the Docusign panel ,however in doing so I am loosing out on all the custom tags which I had set for the template.
c. I have created a custom button and the contents are
{!URLFOR('/apex/dsfs__DocuSign_CreateEnvelope', null, [ SourceID = X.Id , CCRM = 'Decision Maker~Signer 1', CCTM = 'Decision Maker~Signer', DST = '873cd9f7-c905-4340-996e-e166e3594a1c', **CRL = 'Email~' +X.Email__c ,** OCO = 'Send', LA = '0', LF = '0', OCO = 'Tag' ] )}


Now the problem is
1)If I have the default recipient and role set here then the emails are being sent in the email id provided,but the requirement is to make it dynamic.
User-added image



2)If I am using the above code piece for the javascript button url then it is opening up the document where I am unable to create any custom tags and it is saying must select one recipient with name and email to send the mail\


Please help on it
I have two clases:
1. a controller class to a vf page and another as
2. a helper class accessed by multple classes. 

I have a simple query running in the helper class that is failing to return any records:
...
public static void refreshOrder(Id orderId, Id accountId){

        // Retrieve the Order
        Order ord = [Select Id, Name, Status From Order Where Id = :orderId];

...
The controller class that calls the above method has the following extract:
...

Order order = new Order(
    Pricebook2Id = OrderHelper.getStandardPriceBookId(),
    Status = ORDER_STATUS_PENDING_PAYMENT, 
    AccountId = acc.Id
    EffectiveDate = System.today(),
    CurrencyIsoCode=pkgCurrencyCode
 );
        
 insert order;

OrderHelper.refreshOrder(order.Id, acc.Id);
...
Any idea why a system.debug in the helper class does show a valid Order Id being apssed but then the simple order query does not return anything, and instead throws an error:
"List has no rows for assignment to SObject" ?
 
  • January 24, 2020
  • Like
  • 0
I'm working on a way to easily search all of our validation rules for specific strings.  Many of the rules contain reference to role name.  We're planning on updating our role names and we'll need to update all these rules.

I have setup VS Code and thought I would be able to easily download all objects, (standard and custom - and i'm more concerned about standard ones), but I can't find a way to do so.  If I use Org Browser and click the Retrieve icon at the Custom Objects level, it only downloads the custom objects.  I can click retrieve next to each standard object, but this is time consuming.  

Does anyone know of the best way to download all objects easily.  Additionally, does anyone know a better way of specifically searching all validation rules other than searching every object file - e.g. narrowing the search to just validation rules?  
Hi Guys,

This may be something i kick myself with (and i hope it is) but i have a simple query in my apex code and i cannot understand why it has started failing for a specific site guest user.  Here's an extract form my class that contains the query:
// Retrieve the Order
System.debug('*** Ref: orderId = ' + orderId);
System.debug('*** Current user = ' + [select name from user where id = :userinfo.getuserid()].name);

Order ord = [Select Id, Name, Status From Order Where Id = :orderId];
I'm leaving the debug steps in here so we can see the debug logs:
USER_DEBUG|[106]|DEBUG|*** Ref: orderId = 8013N000000YSUoQAO
SOQL_EXECUTE_BEGIN|[107]|Aggregations:0|SELECT name FROM user WHERE id = :tmpVar1
SOQL_EXECUTE_END|[107]|Rows:1
USER_DEBUG|[107]|DEBUG|*** Current user = Site Guest User
SOQL_EXECUTE_BEGIN|[108]|Aggregations:0|SELECT Id, Name, Status FROM Order WHERE Id = :tmpVar1
SOQL_EXECUTE_END|[108]|Rows:0
SYSTEM_MODE_EXIT|false
FATAL_ERROR|System.QueryException: List has no rows for assignment to SObject
Now, looking in Salesforce, the record id for Order 8013N000000YSUoQAO does exist.  it has created by and owner as Site Guest User.  If i change the query on the order to be without the where clause for the order id and execute the same steps then i do get a number of Order IDs returned.  if i run teh query as anonymous, it works fine.  If i run the same steps for system admin it works fine. I have checked to make sure teh Site Guest User has CRUD access to Order  object and it does.

Either i've worked on this project too long and intensivley that i cannot see the obvious or something else is missing that i'm not catching.

Can someone please make a suggestion please?

Thanks
Aamir
 
  • January 05, 2020
  • Like
  • 0
Hi everyone,

I hope you are able to help me out here.  I currently have a Visualforce page with an iframe that displays a third-party form.  Upon completion of this form i get a success message within the iframe and a button that say Finish.  The Finish button is programmed to redirect to a URL (a visualfofrce page) stored on a field on a record.  However, this redirect does not happen.

I've been told that using PostMessage, along with an event listener to trap events will help me resolve this but i'm unable to figure out how to code this.

My Visualforce page outputPanel is as follows:
<apex:outputPanel layout="block" id="aContainer" style="width: 500px; height: 1000px; margin: 0 auto;">
          <apex:outputtext escape="false" value="{!APayForm}"></apex:outputtext>
          <apex:iframe width="100%" height="1000px" src="" scrolling="true" id="paymentFrame" frameborder="false"/>
          <script>
                    document.getElementById('APayForm').submit();
          </script>
</apex:outputPanel>
The APayForm is built dynamically usinga controller and teh following is an example of what is returned and used in teh outputPanel value above;
// example: <form target="paymentFrame" action="https://test.protected.net/PMWeb1?pRef=1837&amp;pid=a233N0000008SgR" method="post" id="APayForm" >
The Cancel button on teh form returns and event 'a--cancel' and the finish button retruns and event 'a--exit'.  how can use these events to redirct to the same visualforce page called 'PostPayment', which renders a message according to the status of a parent record.  The PostPayment page renders correctly but i'm unable to redirect to it.

Can someone help me figure out the code required for the postMessage and event listener (also where this is to be coded) please?
 
  • December 06, 2019
  • Like
  • 0
Is there an easy way to count how many times some text or substring appears in an apex string variable?  So if a a varibale holds "The quick brown fox jumps over the lazy dog"  i want to find how many times fox appears in this string.
  • November 13, 2019
  • Like
  • 0
Hi, I've exported all teh notes from an Org and want to import them as ContentNotes (Enhanced Notes).  The problem i'm facing is that the export csv file contains the notes along with all other system fields as expected.  However, when i want to import into ContentNotes the Content field is expecting a directory path to an individual file (eg. txt) and does not accept a simple field mapping.  How can i work around this?  Is there a way of exporting Notes as txt files?
  • January 12, 2017
  • Like
  • 0
Hi Guys, 

I know its another one, but i've looked at similar issues to see if i can identify the cause of my code coverage failure but have not found anything.  So, i'm getting 0% code coverage for a new trigger and cannot see why.  Here is my Trigger:
 
trigger MilestoneTaskTrigger on MPM4_BASE__Milestone1_Task__c (before insert, before update) {

if ((Trigger.isBefore && Trigger.isInsert) || (Trigger.isBefore && Trigger.isUpdate)){


	// Create list to hold Milestone Components to update
	List<Milestone_Component__c> components = new List<Milestone_Component__c>();

	// Get list of all Milestone Components that are set in Prod but not in Test
	List<Milestone_Component__c> cmps = [SELECT Id FROM Milestone_Component__c WHERE PROD__c = True AND Test_Sandbox__c = False];

	for (Milestone_Component__c c : cmps){
		c.Test_Sandbox__c = True;
		components.add(c);
	}

	for (MPM4_BASE__Milestone1_Task__c task : System.Trigger.new){
		// Is Refresh Test checked
		if (task.Refresh_Test__c == True && task.MPM4_BASE__Complete__c == True){
			// update all milestone components
			update components;

			// unset Resfresh Test checkbox
			task.Refresh_Test__c = False;
		}
	}
}

}

And here's my test class:
 
@isTest
public with sharing class MilestoneTaskTriggerTest {
	static testMethod void  MilestoneTaskTriggerTest() {
		
		// Insert Project
		System.debug('Inserting Milestone Project');
        MPM4_BASE__Milestone1_Project__c project = new MPM4_BASE__Milestone1_Project__c (Name='DEVELOPMENT');
        try { insert project; } catch (exception e) {}

        // get Salesforce Project record type for Milestone? - Nah!! default record type will be used.
        
        // Insert Milestone
        System.debug('Inserting Milestone');
        MPM4_BASE__Milestone1_Milestone__c milestone = new MPM4_BASE__Milestone1_Milestone__c(Name='Milestone', MPM4_BASE__Project__c=project.id);
        try { insert milestone; } catch (exception e) {}
		
		// Insert Task
		System.debug('Inserting Task');
        MPM4_BASE__Milestone1_Task__c task = new MPM4_BASE__Milestone1_Task__c(Name='Task', MPM4_BASE__Priority__c='4 - Low');
        try { insert task; } catch (exception e) {}

		// Insert Components (x3)
		System.debug('Inserting Components');
        Component__c component1 = new Component__c(Name='Comp1');
        try { insert component1; } catch (exception e) {}

        Component__c component2 = new Component__c(Name='Comp2');
        try { insert component2; } catch (exception e) {}

        Component__c component3 = new Component__c(Name='Comp3');
        try { insert component3; } catch (exception e) {}

        Component__c component4 = new Component__c(Name='Comp4');
        try { insert component4; } catch (exception e) {}

		// Insert Milestone Components (x3) setting Prod in one of them and 2 in test
		System.debug('Inserting Milestone Components');
        Milestone_Component__c mscomponent1 = new Milestone_Component__c(SFDC_Component__c=component1.id, Test_Sandbox__c=False, PROD__c=TRUE, Milestone__c=milestone.id, Task__c=task.id, Action__c='Update');
        try { insert mscomponent1; } catch (exception e) {}

        Milestone_Component__c mscomponent2 = new Milestone_Component__c(SFDC_Component__c=component2.id, Test_Sandbox__c=TRUE, PROD__c=False, Milestone__c=milestone.id, Task__c=task.id, Action__c='Update');
        try { insert mscomponent2; } catch (exception e) {}

        Milestone_Component__c mscomponent3 = new Milestone_Component__c(SFDC_Component__c=component3.id, Test_Sandbox__c=TRUE, PROD__c=False, Milestone__c=milestone.id, Task__c=task.id, Action__c='Update');
        try { insert mscomponent3; } catch (exception e) {}

        Milestone_Component__c mscomponent4 = new Milestone_Component__c(SFDC_Component__c=component4.id, Test_Sandbox__c=False, PROD__c=False, Milestone__c=milestone.id, Task__c=task.id, Action__c='Update');
        try { insert mscomponent4; } catch (exception e) {}

		// Update Task.Refresh_Test__c to true and set task to complete
		System.debug('Updating Task');
        task.Refresh_Test__c = TRUE;
        task.MPM4_BASE__Complete__c = TRUE;
        try { update task; } catch (exception e) {}

		// Check that there are 3 Milestone Components flagged as in Test
		List<Milestone_Component__c> mscomponents = [SELECT Id FROM Milestone_Component__c WHERE Test_Sandbox__c = TRUE];
		System.assertEquals(false, mscomponents.size()==3, ' there should be only 3 milestone components with Test Sandbox set as true');

		// Check that the Refresh_Test__c flag is false now.
		MPM4_BASE__Milestone1_Task__c checktask = [SELECT Id, Refresh_Test__c FROM MPM4_BASE__Milestone1_Task__c WHERE Id = :task.id];
		System.assertEquals(false, checktask.Refresh_Test__c==False, ' Refresh Test flag should be false!');

	}
}

Any help is greatly appreciated.
Thanks
Aamir
  • June 22, 2016
  • Like
  • 0
Any idea how to move old notes to the new enhanced notes and maintain the original owner/creator and date/time?
Challenge Description:
  • Upload a specified zip file as a static resource. The zip will have directories with images and you have to display a specific image on a Visualforce page.The page must be named 'ShowImage'.
  • This file must be uploaded as a Static Resource named 'vfimagetest'.
  • The page must have a Visualforce apex:image tag that displays the 'kitten1.jpg' image from the 'cats' directory of the static resource.

Screenshot of Visualforce Page:
User-added image
Screenshot of Resource Page:
User-added image

Screenshot of page preview:
User-added image

Exact text of error:
Challenge not yet complete... here's what's wrong: 
The page does not include a reference to the specified image

Can't figure out whats wrong, everything looks like its working perfectly and I used the examples in the module as a base for the code.