0

I need to create a trigger that will autopopulate the field created in Account object. The field value will be auto populated using the value like 'ACC-001','ACC-002' everytime an account is created. Can you guys help with the logic??

5
  • 2
    Is there any reason why you are not using standard auto number field ? Commented Jun 11, 2019 at 13:11
  • Get the count of all records and based on it populate auto number field.
    – MIX DML
    Commented Jun 11, 2019 at 13:13
  • @VijayGanji, hi Vijay..... its not for project implementation purpose. Its for self learning, if is there any other way through triggers, we can implement it using autonumber
    – Ankur ---
    Commented Jun 11, 2019 at 13:14
  • @MIXDML ; yes, i can do that. i will count the records and will append it to 'ACC' . i mean, its field is a text field that will be worked upon as autonumber.
    – Ankur ---
    Commented Jun 11, 2019 at 13:15
  • i need a format 'ACC' + '001'. i am getting Acc1,Acc2.... Acc11 etc
    – Ankur ---
    Commented Jun 11, 2019 at 13:40

1 Answer 1

0

As others have said, there are better approaches on the platform to do this. You want to get the count of records, and then convert the count to a string. Lastly, it looks like you want to pad with 0's. I think this ought to do the trick:

Integer count = [SELECT count() FROM Account];
Integer maxDigits = 10;
String countStr  = String.valueOf(count);
String str = 'ACC' + countStr.leftPad(maxDigits - countStr.length(), '0');

This code should be fine even if you have 'more than 50,0000' Accounts. In the Summer '18 release they changed how the count() works in SOQL

Previously, each individual record matched by the SOQL COUNT() and COUNT(fieldName) functions counted toward the query row limit. So requesting a count could have a significant impact on governor limits, especially when working with many records. Now, if a query using one of these functions returns an integer, it only counts as one query row toward the governor limit.

https://releasenotes.docs.salesforce.com/en-us/summer18/release-notes/rn_apex_soql_count_limits.htm

You must log in to answer this question.

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