public with sharing class attachPDF {
private final Facturatie__c a;
    public attachPDF(ApexPages.StandardController standardPageController) {
        a = (Facturatie__c)standardPageController.getRecord(); //instantiate the Facturatie__c object for the current record  
    Facturatie__c  currentRecord = [SELECT Id, Accountname__r.Name FROM Facturatie__c WHERE Id = :ApexPages.currentPage().getParameters().get('id')];

    public PageReference attachPDF() {
        PageReference pdfPage = Page.Factuur2PDF;
        Blob pdfBlob = pdfPage.getContent();

        Attachment attach = new Attachment(parentId = a.Id, Name = 'Factuur ' + '-' + currentRecord.Accountname__r.Name +'-'+ date.today().format() +'.pdf', body = pdfBlob); //create the attachment object
        insert attach;
        PageReference pageWhereWeWantToGo = new ApexPages.StandardController(a).view();
        return pageWhereWeWantToGo;


public class attachPDFTestClass {

static testMethod void testAttachments() { 
    Facturatie__c a = new Facturatie__c(Facturatie__c.Accountname__r.Name='Test');
    insert a; 

    Attachment attach=new Attachment(); 
    attach.Name='Unit Test Attachment'; 
    Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body'); 
    attach.body=bodyBlob; attach.parentId=a.id;
    insert attach;

    List<Attachment> attachments=[select id, name from Attachment where parent.id=:a.id]; 
    System.assertEquals(1, attachments.size()); 

    FeedItem f = new FeedItem();
        f.ParentId = a.id;
        f.body = 'test';
        insert f;
        FeedComment fc = new FeedComment();
        fc.CommentBody = 'legal test';
        fc.FeedItemId = f.Id;
        insert fc;
        System.assertEquals ('legal test', fc.commentbody); 

I get the error:

Invalid field initializer

  • Could you post more info about your error? Which line, which class? – Martin Lezer Feb 15 '17 at 15:59
  • 1
    @isTest(seeAllData=true) <- makes the world sad. Why aren't you creating your test data? – Girbot Feb 15 '17 at 16:00
  • In the testclass line 5 Facturatie__c a = new Facturatie.... – Eager 2 Learn apex Feb 15 '17 at 16:01

You cannot set the value of a relationship field like you are doing here:

Facturatie__c a = new Facturatie__c(Facturatie__c.Accountname__r.Name='Test');

Not to mention the format of


Is not valid, no need to include the Object Name as part of the field name.

You should be setting the Id value to the field

Facturatie__c a = new Facturatie__c(Accountname__c = [YOURVALIDID]);

You will need to create the AccountName__c object first obviously.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.