2

I'm trying to populate a Lookup using External ID which is Auto Number field.
It is giving the error:

Compile Error: Field is not writeable: Opportunity.Opportunity_Number__c

Opportunity_Number__c is a Auto Number field. Any workaround to populate the field using Auto Number External Id field type in apex?

3
  • i.e you want to use your custom field as a lookup field rather than ID field created by salesforce
    – anjnkmr
    Commented Dec 5, 2014 at 10:25
  • No. when we use new Opportunity(Opportunity_Number__c = field); It gives us a opportunity record if Opportunity_Number__c is external id
    – Himanshu
    Commented Dec 5, 2014 at 10:52
  • Check your permissions for that specific field. Commented Dec 5, 2014 at 11:05

1 Answer 1

2

No, this is not possible, because Auto-Number fields are never writable in Salesforce.

This could lead you in serious trouble, especially if you need to do data migrations at some point in the future. If you need to replicate old auto-number values, the current best practice approach is even to change the field-type temporarily to Text, then make your work and finally change it back to Auto Number. You see: the field type Auto Number is and stays not writable at all.

If you have Auto Numbers in managed package then you can't change the type temporarily and have no chance at all to influence the numbering sequence.

Due to this risks, we try to avoid the field type Auto Number wherever possible.

In your case you could create a simple External ID Text field and maintain you incrementing by a trigger. To make it really read-only on layouts (even for admins) we do not put the ID field directly on page layouts, but use a formula field instead which just takes the value from the ID field. The result feels as an R/O auto number field, but you keep the driver seat and can adjust the sequences and numbering whenever required by your code.

Another strange thing to take care of is that by default, Salesforce is messing up the auto-number sequence on production org during the deployment. Background: when test data is created in test-methods (can't be avoided if you deploy code), the auto number counter goes up. Result: strange gaps in the numbers. This can be fixed like this:

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .