Friday, April 7, 2017

AX 2012: Attach documents or creates notes through X++

Came across a requirement to attach documents and create notes for a sales order after reading files from directories.

Documents can be attached to a sales order manually from the following button.








Code snippet to create notes or attach documents


 DocuRef             docuRef;
 DocuActionArchive   docuArchive;
 SalesTable          salesTable = SalesTable::find("SO00001");

 Filename            fileName = @"C\Temp\SalesOrder.docx";

 ttsbegin;

 // Code to create notes
 docuRef.TypeId = 'Note';
 docuRef.Name = "Sales order notes";
 docuRef.Notes = "Checked Postcode: 2000, Select resident type";
 docuRef.Restriction = DocuRestriction::External;
 docuRef.RefTableId = tableNum(SalesTable);
 docuRef.RefRecId = salesTable.RecId;
 docuRef.RefCompanyId = curext();
 docuRef.insert();

 //Code to attach file
 docuArchive = new DocuActionArchive();
 docuArchive.add(docuRef, fileName);

 ttscommit;


DocuRef Table has field RefTable and RefRecId which could be referenced by any table in AX and with any record respectively.

Do set RefCompanyId field in DocuRef table otherwise records will not create.