Rodger's Helpful Deluge Scripts #3 - Automatically attach files to CRM records when a file is added to Workdrive

Rodger's Helpful Deluge Scripts #3 - Automatically attach files to CRM records when a file is added to Workdrive

Hi Everyone,

I'm hoping this one will be really helpful for a lot of people. One thing that's missing from Zoho is a tighter integration between Workdrive and CRM. Whilst an update is in the works as far as I'm aware, file management can still be a needlessly complicated problem. And while there are apps out there that help with this, they often don't work with custom modules, or in the way you want.

Wouldn't it be great if you could just drag and drop your files into a workdrive folder and they all get renamed and appear on your CRM record without any effort from you? In this post, I will show you how to automatically create folders in workdrive AND LINK THEM TO THE CRM RECORD so that when a new file is added to the folder, it's automatically attached to the CRM record.

This is the basic process:
  1. CRM record is created
  2. Workdrive folder is created
  3. A Data Bind is created between the CRM Record and the Workdrive Folder
  4. When a new file is added to the Workdrive Folder, a function is triggered that attaches the file to the CRm Record.
When the file is attached to the CRM Record, we can take this opportunity to do whatever we want to aid in file management. In one of our organisations we accomplish the following in one of our business processes:

If the new file is a csv, the data is parsed and added to a subform on the recocrd
If the new file is a PDF, it is renamed with a specific format
If the new file contains a specific string of text, we know it's a thumbnail image, so it's uploaded to the record image
...

You get the idea of what we can do, so let's get into it.

Step 1: Create a CRM Function to receive the Data
First we need to create a function in CRM to receive a webhook, essentially a packed of data sent from Workdrive to CRM.

Head over to your functions in CRM and create a new Standalone function. Give it a name and description if you want.



We're going to create an argument called crmAPIRequest (spelled exactly like that, this is case sensitive) and se tthe argument type as string



Now save that and save the function, we don't need anything in there yet. In your function menu, click on the elipses (the 3 dots) and select REST API

 

Turn on "API Key" and the system will generate a url for you. Copy and save that URL as we will need it for Step 2. This finishes Step 1.

Step 2: Create an app in Workdrive
Firstly, we need to create an "App" in Workdrive. This will monitor your folder for specific events and send a webhook when that event is triggered, i.e new file created.

In Workdrive, head to the Admin Console --> Apps --> + New Custom App



Give your app a name that's descriptive and informative and paste your client ID. (There's insructions in the opo-up window about how to get your client ID)

When you have created your Custom App, go into it and head over to "Webhooks" and click "+ Create New Webhook"




Give your webhook a name and description if you please. The endpoint URL will be the url of your function that you created in step 1. This tells the app where to send the packed of data.

Next we select the event that will trigger the webhook. In this case, we want it to trigger when a file is uploaded.



Finally we want to specify the folder to monitor. This will be the parent folder that all your new folders will sit under. When you're done, click "Create Webhook"

Step 3: Setup the Data bind

A data bind links 2 records together with their unique ids. To do this we need a field on your CRM Record to store the Wokdrive Folder ID. Make this a single line field. If you don't know how to do this, then this  guide is not for you.

So that stores the Workdrive folder ID, but what stores the CRM record ID? The answer is a Data Template. In you Workdrive Admin Console, head over to Data Templates and create a data template. Add a single line text field to your data template. This will store the CRM Record ID



Step 4: Create folders in Workdrive with Deluge function.

Now that we have set this up, we need to create folders and associate store the respective IDs. This will be done on record creation.

Use the following code snipped to create your folder

  1. // Create folder
  2. header = Map();
  3. header.put("Accept","application/vnd.api+json");
  4. data = Map();
  5. data_param1 = Map();
  6. att_param1 = Map();
  7. att_param1.put("name",<Folder Name>);
  8. att_param1.put("parent_id",<Parent Folder ID>);
  9. data_param1.put("attributes",att_param1);
  10. data_param1.put("type","files");
  11. data.put("data",data_param1);
  12. createFolder = invokeurl
  13. [
  14. url :"https://www.zohoapis.com.au/workdrive/api/v1/files"
  15. type :POST
  16. parameters:toString(data)
  17. headers:header
  18. connection: <Your Workdrive Connection>
  19. ];
  20. info createFolder;
  21. // m_record.put("Folder_Id",createFolder.get("data").get("id")); - Put the created folder ID into the map for your CRM record
  22. // Associate Data Template
  23. header = Map();
  24. header.put("Accept","application/vnd.api+json");
  25. data = Map();
  26. data_param1 = Map();
  27. att_param1 = Map();
  28. att_param1.put("resource_id",createFolder.get("data").get("id"));
  29. att_param1.put("data_template_id","s1a2u5f693092015d4edc876d9043efcf9bcd-73963000001705001"); // 
  30. innerattr_param = List();
  31. innerattr_param_map1 = Map();
  32. innerattr_param_map1.put("custom_field_id",<Custom Field ID>);
  33. innerattr_param_map1.put("value",<CRM Record ID>));
  34. innerattr_param.add(innerattr_param_map1);
  35. att_param1.put("custom_data",innerattr_param);
  36. data_param1.put("attributes",att_param1);
  37. data_param1.put("type","custommetadata");
  38. data.put("data",data_param1);
  39. associateDataTemplate = invokeurl
  40. [
  41. url :"https://www.zohoapis.com.au/workdrive/api/v1/custommetadata"
  42. type :POST
  43. parameters:data.toString()
  44. headers:header
  45. connection: <Your Workdrive Connection>
  46. ];
  47. info associateDataTemplate;

Note: Use the following documentation to get the ID of your Data Template Field needed for line 33 above Zoho WorkDrive API Documentation

Then update your CRM record with the ID of the workdrive folder you created.

Generally, we don't attach this folder to the CRM Record, all we want to see in the CRM record are the files within the folder, not the folder itself.

Step 5: Set-up CRM Function to receive Webhook and attach file to CRM Record

Now we need to go back to your CRM Function which you setup in Step 1 and we're going to add some code:

  1. crmAPIRequest = crmAPIRequest.get("body");
  2. getFolderMetadata = invokeurl
  3. [
  4. url :"https://www.zohoapis.com.au/workdrive/api/v1/files/" + crmAPIRequest.get("data").get(0).get("resource_info").get("parent_id") + "/custommetadata"
  5. type :GET
  6. headers:{"Accept":"application/vnd.api+json"}
  7. connection: <Your Workdrive Connection>
  8. ];
  9. info getFolderMetadata.get("data").get(0).get("attributes").get("custom_data").get(0).get("value");
  10. recordId = getFolderMetadata.get("data").get(0).get("attributes").get("custom_data").get(0).get("value"); // Gets the Data out of the Data Template - This is the CRM Record ID
  11. r_record = zoho.crm.getRecordById(<Module>,recordId); //Get your CRm Record
  12. fileID = crmAPIRequest.get("data").get(0).get("resource_info").get("resource_id");
  13. m_map = Map();
  14. // Attach new file to CRM Record
  15. //
  16. l_attachments = list();
  17. data = Map();
  18. data.put("$link_url","https://workdrive.zoho.com.au/file/" + fileID);
  19. data.put("File_Name",<Your File Name>);
  20. if(!data.isEmpty())
  21. {
  22. data.put("$resource_id",recordId);
  23. data.put("$type","teamdrive");
  24. l_attachments.add(data);
  25. payload = "attachments=" + zoho.encryption.urlEncode({"data":l_attachments});
  26. attachFile = invokeurl
  27. [
  28. url :"https://www.zohoapis.com.au/crm/v2/<Module>/" + recordId + "/Attachments"
  29. type :POST
  30. parameters:payload
  31. connection: <Your CRM Connection>
  32. content-type:"application/x-www-form-urlencoded"
  33. ];
  34. info attachFile;
  35. // Rename File in Work Drive
  36. data = Map();
  37. data_param1 = Map();
  38. att_param1 = Map();
  39. att_param1.put("name",<Your File Name>);
  40. data_param1.put("attributes",att_param1);
  41. data_param1.put("type","files");
  42. data.put("data",data_param1);
  43. renameFile = invokeurl
  44. [
  45. url :"https://www.zohoapis.com.au/workdrive/api/v1/files/" + fileID
  46. type :PATCH
  47. parameters:data.toString()
  48. headers:{"Accept":"application/vnd.api+json"}
  49. connection: <Your Workdrive Connection>
  50. ];
  51. info renameFile;
  52. }
  53. if(!m_map.isempty())
  54. {
  55. info zoho.crm.updateRecord(<Module>,recordId,m_proof);
  56. }
  57. return "";

So how does the above code work?

Firstly, we get the body of the Webhook, this has all the data we really want.
Next we get the file metadata, this will contain the data in teh Data Template, which of course is the CRM Record ID.
Now that we have the CRM Record ID from the file Metadata, we can fetch the CRM Record. Contained within the Webhook is also the File ID in Workdrive, so this gives us all the information we need to attach the file to your CRM Record and rename the file in Workdrive.

Within this function you can now do whatever you want with the file or anything else. Let's say you want to send an email when a specific file is  uploaded, you can do that here. Or if you want to send a notification via Cliq to someone when a file is uploaded, do that here. You can code specific filename syntaxes so that all your files are perfectly name all the time, the limits are endless.

This is far more advanced than most deluge functions posted on here, so see how you go, play around and have fun. If you have any questions, I'll try to respond as soon as possible.

    Access your files securely from anywhere







                        Zoho Developer Community





                                              Use cases

                                              Make the most of Zoho Desk with the use cases.

                                               
                                                

                                              eBooks

                                              Download free eBooks and access a range of topics to get deeper insight on successfully using Zoho Desk.

                                               
                                                

                                              Videos

                                              Watch comprehensive videos on features and other important topics that will help you master Zoho Desk.

                                               
                                                

                                              Webinar

                                              Sign up for our webinars and learn the Zoho Desk basics, from customization to automation and more

                                               
                                                
                                              • Desk Community Learning Series


                                              • Meetups


                                              • Ask the Experts


                                              • Kbase


                                              • Resources


                                              • Glossary


                                              • Desk Marketplace


                                              • MVP Corner




                                                        Manage your brands on social media



                                                              Zoho TeamInbox Resources



                                                                  Zoho CRM Plus Resources

                                                                    Zoho Books Resources


                                                                      Zoho Subscriptions Resources

                                                                        Zoho Projects Resources


                                                                          Zoho Sprints Resources


                                                                            Qntrl Resources


                                                                              Zoho Creator Resources



                                                                                  Zoho CRM Resources

                                                                                  • CRM Community Learning Series

                                                                                    CRM Community Learning Series


                                                                                  • Kaizen

                                                                                    Kaizen

                                                                                  • Functions

                                                                                    Functions

                                                                                  • Meetups

                                                                                    Meetups

                                                                                  • Kbase

                                                                                    Kbase

                                                                                  • Resources

                                                                                    Resources

                                                                                  • Digest

                                                                                    Digest

                                                                                  • CRM Marketplace

                                                                                    CRM Marketplace

                                                                                  • MVP Corner

                                                                                    MVP Corner







                                                                                      Design. Discuss. Deliver.

                                                                                      Create visually engaging stories with Zoho Show.

                                                                                      Get Started Now


                                                                                        Zoho Show Resources


                                                                                          Zoho Writer Writer

                                                                                          Get Started. Write Away!

                                                                                          Writer is a powerful online word processor, designed for collaborative work.

                                                                                            Zoho CRM コンテンツ






                                                                                              Nederlandse Hulpbronnen


                                                                                                  ご検討中の方




                                                                                                        • Recent Topics

                                                                                                        • What is Zoho Marketing Plus?

                                                                                                          As if there wasn't enough confusion with SalesIQ, CRM, Campaigns and Marketing Automation, now we have Marketing Plus too. Can somebody from Zoho please give us a comparative list of features that are in Marketing Plus compared to what's in Marketing
                                                                                                        • matches() returns different response in CRM vs public Deluge page

                                                                                                          I was using this public Deluge page to test using regular expressions with matches() to evaluate strings: https://deluge.zoho.com/tryout I was trying to use this regular expression to check a string for title case, making sure to escape the backslashes.
                                                                                                        • I didn't receive my domain verification mail

                                                                                                          I didn't receive my domain verification mail 
                                                                                                        • Creating a new deal with specific layout and pipeline

                                                                                                          I am trying to create a button which creates a new deal for a particular account. It needs to be assigned a specific layout and pipeline. It seems like it should be really simple but I've been struggling to get this to work all day, can anyone help?!
                                                                                                        • Announcing New Features in Trident for macOS (v.1.21.0)

                                                                                                          Hello everyone! Trident for macOS is here with interesting features to elevate your workplace communication and productivity. Let's take a quick look at them. Get better visibility for concurrent events. Quickly compare and manage simultaneous events
                                                                                                        • Zoho Inventory search when adding items to SO/PO, etc.

                                                                                                          I do not see that Zoho Inventory searches within the item name for an item lookup. We have many products with variants. So when I search for a product, say a lighting system, and it comes in different sizes and colors, I can only get those products where
                                                                                                        • Introducing Zoho Commerce 2.0 — It's more than just selling!

                                                                                                          Hello! We are proud to launch Zoho Commerce 2.0, a reimagination of how online businesses look, feel, and function. This launch is both timely and symbolic, as we reaffirm our commitment to empowering small and medium enterprises with powerful, yet simple-to-use
                                                                                                        • Modifying Product Details

                                                                                                          I am in the process of setting up new products in Zoho Commerce and have encountered a few problems: 1) Tabs It seems that Product Details pages do not have the ability to create Tabs. eg:  https://www.thedebugstore.com/tp240141-aardvark-usb-i2c-spi-host-adapter-total-phase.html
                                                                                                        • Zoho Commerce B2B

                                                                                                          Hello, I have signed up for a Zoho Commerce B2B product demo but it's not clear to me how the B2B experience would look for my customers, in a couple of ways. 1) Some of my customers are on terms and some pay upfront with credit card. How do I hide/show
                                                                                                        • Creating a custom CSV file using deluge script/

                                                                                                          I have an application I have developed and the client wants us to place an export file in csv onto an ftp server daily. Now I don't see au options in creator to change the separator to anything else. The client wants the separator to be the pipe symbol "|"  I think i would be able to create schedule with some code to create the appropriate data in a string using deluge script but I haven't seen any functionality that would allow me to deposit that data as a file anywhere or attach it to an email
                                                                                                        • Delay function execute

                                                                                                          I've got a workflow which uses a webhook to send information to Flow, which in return updates a record in Creator. Problem is, by the time this has executed, the rest of my script has run and can't find the (yet to be) updated info in the record. Is there
                                                                                                        • Zoho Books | Product updates | July 2025

                                                                                                          Hello users, We’ve rolled out new features and enhancements in Zoho Books. From plan-based trials to the option to mark PDF templates as inactive, explore the updates designed to enhance your bookkeeping experience. Introducing Plan Based Trials in Zoho
                                                                                                        • customize payment page

                                                                                                          Is there a way to customize, other than the theme colour, the payment page that customers are taken to from invoices? I can't seem to find a way. I just don't like the formatting of the current page and would like to make it look better. I've looked at
                                                                                                        • Anyone else experiencing very slow loading of pages in Zoho Projects?

                                                                                                          I reported this yesterday only to be told there are no issues but is anyone else experiencing stupidly slow loading of pages. On our loading screen, it is taking often as long as 60 seconds to load a page and just stays on this screen for ages! Other
                                                                                                        • How can I get a nested value attributes inside a key par?

                                                                                                          Hello! Im getting the following output when reviewing a record I am after. I am trying to put some conditions based on a data value that is inside another data. For example, lets grab the below output. Info {"Account_Name":{"name":"Liberty Construction
                                                                                                        • Unable to attach the file via the API.

                                                                                                          We are trying to attach files to a Candidate in Zoho Recruit using the API. We reviewed the following API documentation: 🔗 Upload Attachment While this API does allow file attachment via a URL, that’s not what we want — we do not want to attach public-facing
                                                                                                        • Item Batch Creation/Updation

                                                                                                          I have a requirement to integrate a local system with Zoho Books. I need to create items in Zoho Books with batch tracking enabled, but I couldn't find a specific API for that in the Zoho Books API documentation. Is there a dedicated API endpoint to create
                                                                                                        • Invoices not arriving and mail server settings

                                                                                                          I am having an issue where some clients are not receiving invoices. I have configured Zoho Books to send on my behalf and configured the appropriate SPF, DKIM and DMARC settings on my mail server and tested these as working. I get the CC'd copies so I
                                                                                                        • Multi Line Text Character Limit

                                                                                                          I want to export my Help Center articles but I realized that the text in the Answer column is being cut off. I'm guessing there is a character limit for multi line text fields. How can I get around this?
                                                                                                        • How do I associate pricebooks to a customer?

                                                                                                          I setup a few pricebooks, that worked fine. But now the only thing I can do with it, when I enter a quote or sales order, I can select which pricebook to use, but I have to do this product by product every time I add one. Is there a way to connect a pricebook
                                                                                                        • Emails bouncing to Hotmail / Outlook.com

                                                                                                          Today I have seen multiple emails bouncing all to Hotmail and outlook.com mailboxes, all other emails are being delivered. Is it just me or is this a widespread issue with Zoho Books ? Bounce Reason : uncategorized-bounce
                                                                                                        • Be careful if you want to purchase zoho one

                                                                                                          Hi, just to add one more complain to the other similar complains. When I purchased zoho one, Divith, my account manager told me (by email) that I would be able to keep different emails that I have inside the company (contact, privacy, etc.). During the
                                                                                                        • Schedule Timeout 5 minutes vs. stated 15 minutes

                                                                                                          I am running into a function run timeout error after 5 minutes for my schedules. The Functions - Limits documents states it should be 15 minutes: Functions - Limits | Online Help - Zoho CRM. What should it actually be? Due to the 5 minute timeout, I'm
                                                                                                        • I can't found API for Sales Receipts

                                                                                                          Hello May you please help me to find an API document for Sales Receipts to get data and retrive a custom fields like Invoice and credit notes Regards
                                                                                                        • Multi-Select lookup field has reached its maximum??

                                                                                                          Hi there, I want to create a multi-select lookup field in a module but I can't select the model I want the relationship to be with from the list. From the help page on this I see that you can only create a max of 2 relationships per module? Is that true?
                                                                                                        • Importing invoices in bulk using the xls file template - still posting as draft - Is there a way to skip "mark as sent" and post it directly?

                                                                                                          Hello everyone, as the title say, is there a way that when I upload from the template file, it will post automatically? I tried changing the "Invoice Status" from draft to approved but it is still appearing as draft and is making me go to invoices so
                                                                                                        • How to set Sales Order Payment Terms when creating a Sales Order via the Zoho Books API

                                                                                                          I am creating Sales Orders via the Zoho Books API. I would like to set the Payment Terms to a particular value from the list of allowed values. Is that possible? I was able to get the list of payment terms via this API call: https://books.zoho.com/api/v3/settings/paymentterms?organization_id=XXXX"
                                                                                                        • Function and workflow to create customer payment and send receipt

                                                                                                           I am attempting to set up a workflow/custom function for the automatic creation of a customer payment and sending the email receipt, but am receiving the error "Improper Statement Error might be due to missing ';' at end of the line or incomplete expression" I've been over everything several times and cannot see where the error is (code is copied into the attached document).  I haven't used custom functions before with Deluge, so it's very likely something very simple, or I've completely mucked
                                                                                                        • How to rename the Submit Button by using deluge script

                                                                                                          Hi everyone, As we know, the Submit button can be renamed in the form builder setting. But I have scenario where I need the Submit Button to be renamed differently according to condition. Anyone knows how to do it? Thank You
                                                                                                        • ADDDATE formula using 2 calculations

                                                                                                          Hello, I want to create an ADDDATE formula using 2 calculations, add 1 month and deduct 1 day. the formula that I need should look like this: ADDDATE(due_date, 1, "Months")+ ADDDATE(due_date, -1, "Days") Each row itself works fine, but when I'm trying
                                                                                                        • Banking: Transfer from another account without base currency

                                                                                                          Scenario: A banking line item shall be categorised as an "internal transfer" from another bank account. This is a USD to EUR transfer. Our base currency is CHF. What we tried: Category: "Transfer from another account" From: Our USD account To: Our EUR
                                                                                                        • Item cost price - How to accomodate changing cost prices

                                                                                                          I am in urgent need of assistance with how to accommodate changing cost prices for items, not manually. We import items so their landed cost is always changing. This cost is NOT reflected however in the item cost price. This is going to cause us some
                                                                                                        • Bigin merge field in email template for subject line to match lead name

                                                                                                          Hello We Are using email in to automatically create leads in our pipelines. When we want to reply from conversations, and apply an email template, it’s not matching the original subject line. It should be lead name to match. But it’s not working. Even
                                                                                                        • GraphQL in new Send Webhooks feature

                                                                                                          Hello, is it possible to use GraphQL apis in the new Send Webhooks feature?
                                                                                                        • Marketer's Space: Targeted messaging : Leveraging Zoho Campaigns for Effective Communication

                                                                                                          Hello Marketers, Welcome back to Marketers’ Space! Targeted messaging ensures your communication reaches the right audience - boosting engagement, conversions, and overall campaign success. In this post, we’ll be looking at targeted messaging to create
                                                                                                        • Assignment Thresholds Resetting After Lead Conversion

                                                                                                          Hello everyone, We're facing an issue with Zoho CRM's lead assignment thresholds that makes them unsuitable for our workflow. I'm hoping to find a potential workaround or solution from the community. Here’s our current process: A new lead is created automatically
                                                                                                        • :between: conditions in search?criteria

                                                                                                          Hello, please help solve problem I try to select deals by Creater_Time between dates i send this GET request /crm/v4/deals/search?criteria=(Created_Time:between:(2024-02-01T18:52:56,24-02-17T18:52:56)) encoded to /crm/v4/deals/search?criteria=%28Created_Time%3Abetween%3A%282024-02-01T18%3A52%3A56%2C24-02-17T18%3A52%3A56%29%29
                                                                                                        • Zoho Creator : Updating Records via Import. Can't use Autonumber or ZohoRecordID ?

                                                                                                          Hi, I am trying to use the function to update a report with an import. I'm running in to the error : "unable to update because the form has no column with unique values" In the release notes it says Only field with unique values can be used to compare
                                                                                                        • 💡 Feature Request: Custom App Bundle Plan (Pick Only the Apps You Need)

                                                                                                          Request: Allow Users to Build a Custom App Bundle (Choose Only the Apps They Need) Hi Zoho Team, I appreciate the value that Zoho One and the Plus Bundles (CRM Plus, Finance Plus, etc.) offer. However, I’m finding it difficult to get the best fit for
                                                                                                        • Search Feature Now Broken

                                                                                                          I have many hundreds of notes on Zoho Notebook but now when I search for a keyword, I only get 30 results maximum. This is unacceptable and yet another feature that has become broken on this quickly deteriorating software. Please fix immediately.
                                                                                                        • Next Page