如何解决如何将pdf从触发器附加到对象?
我在尝试附加一个包含机会记录中填充值的 pdf 时有点迷茫 代码如下:
触发:
trigger OpportunityTrigger on Opportunity (after insert)
if(trigger.isAfter && trigger.isUpdate) {
opportunityTriggerHelper.attachFiletoOpportunityRecord(trigger.new);
}
助手类:
private void attachFiletoOpportunityRecord(List<Opportunity> lstOpp) {
List<Id> oppListIdsForAttach = new List<Id>();
for(Opportunity opp : lstOpp) {
oppListIdsForAttach .add(opp.Id);
}
attachFiletoOpportunities(oppListIdsForAttach);
}
@future(callout=true)
private static void attachFiletoOppotunities(List<Id> OpportunityIds) {
List<Attachment> attachList = new List<Attachment>();
for(Id oppId : opportunityIds) {
OpportunityPdfController file = new OpportunityPdfController();
file.getData(oppId);
PageReference pdfpage = Page.PdfAttachmentForOpp;
blob pdfBody;
pdfBody = pdfpage.getContent();
Attachment attach = new Attachment();
attach.Body = pdfBody;
attach.Name = 'Pdf file';
attach.IsPrivate = false;
attach.ParenId = oppId;
attachList.add(attach);
}
insert attachList;
}
VF 页面:
<apex:page controller="OpportunityPdfController" renderAs="pdf">
<apex:repeat value="{!pricingDetails}" var="pd">
<apex:outputText>{!pd.basePrice}</apex:outputText>
</apex:repeat>
</apex:page>
VF 页面控制器:
public with sharing class OpportunityPdfController {
public List<PricingDetailWrapper> pricingDetails {get;set;}
public void getData(Id opportunityId) {
List<Pricing_Detail__c> pdList = [
SELECT basePrice
FROM Pricing_Detail__c
WHERE OpportunityId =: opportunityId
];
for(Pricing_Detail__c pd : pdList) {
PricingDetailWrapper pdw = new PricingDetailWrapper();
pdw.basePrice = pd.basePrice;
pricingDetails.add(pdw);
}
}
public class PricingDetailWrapper {
public String basePrice {get;set;}
}
}
结果是,每当我更新机会时,它都会附加相应的 pdf 文件,但它是空白的,如果我将以下内容添加到 vf 页面正文:"<h1> Hello World!</h1>"
这可以正常工作并按预期显示,但这不是发生了我上面要求的事情。
解决方法
您并没有真正将机会 ID 传递给 VF 页面。我怀疑这真的有效吗?如果您以 /apex/PdfAttachmentForOpp?id=006...
的身份手动访问 VF 页面,它会呈现内容吗?我假设它没有。
修复页面
您没有指定构造函数,所以 SF 会为您生成一个,很好。我认为您需要添加类似
public OpportunityPdfController(){
if(ApexPages.currentPage() != null){
Id oppId = ApexPages.currentPage().getParameters().get('id');
System.debug(oppId);
getData(oppId);
}
}
添加这个,尝试访问传递有效 opp id 的页面,看看它是否呈现正常,如果正确的东西显示在调试日志中。 /apex/PdfAttachmentForOpp?id=006...
(VF 页面构造器是一个更大的话题,这可能使用标准控制器 + 扩展类更简单)
修正标注
VF 页面(尤其是作为标注访问)不会与您在代码中创建的 OpportunityPdfController
控制器共享内存。将创建此类的新对象以支持该页面,而您的 file
将被忽略。您可能会尝试使用一些包含当前机会 ID 的静态变量来凑合,但感觉有点恶心。
在正常执行匿名尝试,如果这返回正确的pdf:
PageReference pdfPage = Page.PdfAttachmentForOpp;
pdfPage.getParameters().put('id','006...');
Blob pdfBody = pdfPage.getContent();
System.debug(pdfBody.toString());
如果有效 - 在实际代码中使用类似的技巧,将 id 作为 url 参数传递。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。