function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
anandanandanandanand 

Field is not writeable:Invoice__c.Id

Field is not writeable:Invoice__c.Id

 

public class SampleAcc {

   static testMethod void testAccTrigger(){
  
 Pricebook2 s = [select id from Pricebook2 where IsStandard = true];  
  
 // create the product
    Product2 p1 = new Product2(
        name='Test Product 1',
        IsActive=true,
        Description='My Product',
        ProductCode='12345'
    );
    insert p1; 
   
    PricebookEntry pbe1 = new PricebookEntry(
        Pricebook2Id=s.id,
        Product2Id=p1.id,
        UnitPrice=0.00,
        IsActive=true,
        UseStandardPrice=false
    );
    insert pbe1;  
   
 Opportunity opp1 = new Opportunity(Name='ww',StageName='Qualification',CloseDate=date.today());
 insert opp1;
  
 OpportunityLineItem oli = new OpportunityLineItem();
 oli.Quantity = 1;
    oli.TotalPrice = 1;
    oli.PricebookEntryId = pbe1.id;
    oli.OpportunityId = opp1.id;   
    insert oli; 
 
 Invoice__c inv =new Invoice__c();
 inv.Id=opp1.id;
 inv.name = 'ww';
 insert inv;
  
   Accomodation__C acc = new Accomodation__C();
   acc.name='ww';

   Test.startTest();
   insert acc;
   Test.stopTest();
 }
}

 

shows error in this line

inv.Id=opp1.id;

Field is not writeable:Invoice__c.Id

 

am new to apex .please solve it

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

You can't write to the id field once you've instantiated an  object, but you can set the id at instantiation time.

 

E.g.

 

 

Invoice__c inv =new Invoice__c(Id=opp1.Id);

 

 

All Answers

bob_buzzardbob_buzzard

You can't write to the id field once you've instantiated an  object, but you can set the id at instantiation time.

 

E.g.

 

 

Invoice__c inv =new Invoice__c(Id=opp1.Id);

 

 

This was selected as the best answer
nnewbold-sfdcnnewbold-sfdc

Id is a special field that's exposed on every object.  Once a record is created, the Id is set automatically.  In your code, you are attempting to provide a value prior to inserting it.  That won't work even if you specify new Invoice__c(Id='someid').

 

You need to either remove the line that sets the Id, or change your DML to an update.

NikhilNikhil

i can see that you are trying to link the Invoice and opporunity object.

 

Create a lookup field on Invoice (lookup to opportunity) then pass the id of opportunity to that field as ..

 

 

Invoice i = new Invoice();

xyzopplookupfield__c = opp.id;

....

...

...

 

insert i;