Generic way of Attaching Documents on any Record of the Page in Microsoft Dynamics Business Central - Template Code
In Microsoft Business Central, there is a way to attach attachments only on Documents or Master Table records. But, what if this requirement is for other tables such as Opportunities, custom tables, etc.
Introduction:I have seen many developers afraid to touch the attachment-related customization as it seems complicated.
Well, I have found a solution and here it goes.
In this blog, I'm attempting to create a generic template for code that needs to have an attachment feature on any table that you like using AL Code.
This means that you simply cannot copy-paste the same code for all the tables but a simple change in variable sub-type will ease your work significantly
- Microsoft Dynamics Business Central
- VS Code
- Al Language Extension
Demonstration:1. How it works:
Document Attachment is a table which stores a few things that help in tracking information related to the attachment
|Document Attachment Table Fields|
The main unique thing that works for all the different tables is the TableID, Line No and No. fields.
Along with this, the document is attached through a stream inside a Media DataType.
There are 2 important functions
1. SaveAttachment2 : This function takes a few parameters RecRef for origin Table ID, FileName to
store the file name, Blob which will be imported a Stream in Document Reference ID Media type field,
Recs.No which will store the unique record for which the attachment is attached.
This function when the line has no attachment attached to it. This is done by checking if the field
Document Reference ID has no value.
2. Export2: This function exports the attached BLOB to a file. This is done if the Document
Reference ID field has any value.
This is both functions are complimentary of each other and are trigger on FileName field DrillDown
|DrillDown to Attach OR Export|
2. Things that you need to change:
Either you are using the Generic Attachment Template code first time or mulitple times in the same project, you need to find //Change the Table Name Here----OLISTER and //Change the Page Name Here----OLISTER comment and replace your table name. Also, you will need to manage with the PageName and IDs. Read through README.TXT in the project.
3. Custom Attachments for multiple tables:
In the above case, I have created the code for the Opportunity Card page. I will repeat the same for Item Card Page.
|Prior to Items Card Page|
|After adding a new set of pages for different tables|
Change the Table Nos on the comment line //Change the Table Name Here----OLISTER and
//Change the Page Name Here----OLISTER
|After changing Table Names|
|After changing Page Names|
|After changing Part Page Names|
Finally, I got this.
Hope this helps!