Deluge function to copy parent record file upload field to child record file upload field

Deluge function to copy parent record file upload field to child record file upload field

I'm stuck trying to write a deluge function that is triggered via automation in child record "Appointments," confirms if a file is in file upload "Report" field of parent "Contacts" record via Contacts lookup field "Contact_Name".  If no file is in parent record, function exits.  If there is a file, saves a copy of that file in Appointments.Report file upload field.

Any help would be appreciated, here's what I have so far, also attached as a .txt file.

If it simplifies, it would also be fine saving the copy of the file in Appointments attachment section instead of directly in the file upload field, but ideally it's copied from file upload Contacts.Report file upload to file upload Appointments.Report.

// Trigger: Workflow / automation on the CHILD module "Appointments"
// Goal: Copy the first file from parent Contact.Report into Appointments.Report
// NOTE: This version triggers workflow/approval/blueprint/orchestration on the final updateRecord

void automation.copyReportFromContactToAppointment(int appointmentId)
{
    // ----------------------------
    // CONFIG
    // ----------------------------
    string apptModule = "Appointments";
    string contactModule = "Contacts";
    string contactLookupApi = "Contact_Name";   // lookup field on Appointments -> Contacts
    string fileFieldApi = "Report";             // file upload field on both modules
    string oauthConn = "crm_oauth_connection";  // update to your CRM OAuth connection link name

    // Trigger downstream automations on CRM updates
    options = Map();
    options.put("trigger", {"workflow","approval","blueprint","orchestration"});

    // ----------------------------
    // 1) Get Appointment
    // ----------------------------
    appt = zoho.crm.getRecordById(apptModule, appointmentId);
    if(appt == null || appt.isEmpty())
    {
        info "Appointment not found: " + appointmentId;
        return;
    }

    // ----------------------------
    // 2) Resolve parent Contact via lookup
    // ----------------------------
    contactIdStr = "";
    try
    {
        lookup = appt.get(contactLookupApi);
        if(lookup != null && lookup.get("id") != null)
        {
            contactIdStr = lookup.get("id").toString();
        }
    }
    catch (e1)
    {
        contactIdStr = "";
    }

    if(contactIdStr == "" || !contactIdStr.matches("[0-9]+"))
    {
        info "Could not resolve Contact via lookup field " + contactLookupApi;
        return;
    }

    contactId = contactIdStr.toLong();

    // ----------------------------
    // 3) Get Contact
    // ----------------------------
    contact = zoho.crm.getRecordById(contactModule, contactId);
    if(contact == null || contact.isEmpty())
    {
        info "Contact not found: " + contactId;
        return;
    }

    // ----------------------------
    // 4) Check Contact.Report file upload field
    // ----------------------------
    filesList = ifnull(contact.get(fileFieldApi), list());
    if(filesList.isEmpty())
    {
        info "No file present in Contact." + fileFieldApi + " — exiting.";
        return;
    }

    // Read FIRST file's file_Id (typical key name in CRM file upload fields)
    fileId = "";
    fileName = "";
    try { fileId = ifnull(filesList.get(0).get("file_Id"), "").toString(); } catch (e2) { fileId = ""; }
    try { fileName = ifnull(filesList.get(0).get("file_Name"), "").toString(); } catch (e3) { fileName = ""; }

    if(fileId.trim() == "")
    {
        info "File exists but could not read file_Id from Contact." + fileFieldApi;
        return;
    }

    // ----------------------------
    // 5) Download the file
    // ----------------------------
    downloadedFile = null;
    try
    {
        downloadedFile = invokeurl
        [
            url :"https://www.zohoapis.com/crm/v2.1/files/" + fileId
            type :GET
            connection: oauthConn
            response-format: FILE
        ];
    }
    catch (dlErr)
    {
        info "Download error: " + dlErr.toString();
        return;
    }

    if(downloadedFile == null)
    {
        info "Download returned null. fileId=" + fileId;
        return;
    }

    // Optional file metadata helpers (safe to ignore if unsupported)
    try { downloadedFile.setFileName(fileName); } catch (nf1) {}
    try { downloadedFile.setParamName("file"); } catch (pn1) { try { downloadedFile.setparamname("file"); } catch (pn2) {} }

    // ----------------------------
    // 6) Upload to /crm/v2.1/files to get a NEW file id
    // ----------------------------
    uploadedResp = null;
    try
    {
        uploadedResp = invokeurl
        [
            url :"https://www.zohoapis.com/crm/v2.1/files"
            type :POST
            files: downloadededFile
            connection: oauthConn
        ];
    }
    catch (upErr)
    {
        info "Upload-to-files error: " + upErr.toString();
        return;
    }

    newFileId = "";
    try { newFileId = uploadedResp.get("data").get(0).get("details").get("id").toString(); } catch (e4) { newFileId = ""; }

    if(newFileId.trim() == "")
    {
        info "Upload-to-files did not return new id. Response: " + uploadedResp.toString();
        return;
    }

    // ----------------------------
    // 7) Update Appointments.Report using List(Map(file_id))
    // ----------------------------
    fileUploadList = List();
    fileUploadList.add({"file_id": newFileId});

    updateMap = Map();
    updateMap.put(fileFieldApi, fileUploadList);

    updateResp = zoho.crm.updateRecord(apptModule, appointmentId, updateMap, options);
    info "Appointment update response: " + updateResp;
}
    • Sticky Posts

    • Function #46: Auto-Calculate Sales Margin on a Quote

      Welcome back everyone! Last week's function was about displaying the discount amount in words. This week, it's going to be about automatically calculating the sales margin for a particular quote, sales order or an invoice. Business scenario Where there is sales, there's also evaluation and competition between sales reps. A healthy rivalry helps to better motivate your employees to do smart work and close deals faster and more efficiently. But how does a sales rep get evaluated? 90% of the time, it's
    • Zoho CRM Functions 53: Automatically name your Deals during lead conversion.

      Welcome back everyone! Last week's function was about automatically updating the recent Event date in the Accounts module. This week, it's going to be about automatically giving a custom Deal name whenever a lead is converted. Business scenario Deals are the most important records in CRM. After successful prospecting, the sales cycle is followed by deal creation, follow-up, and its subsequent closure. Being a critical function of your sales cycle, it's good to follow certain best practices. One such
    • User Tips: Auto-Create Opportunity/Deal upon Quote Save (PART 1)

      Problem: We use quotes which convert to sales orders but Users / Sales Reps do not create opportunities / deals and go straight to creating a quote. This leads to poor reporting. Implementing this solution improves reporting and makes it easier for users.
    • Custom Function : Automatically send the Quote to the related contact

      Scenario: Automatically send the Quote to the related contact.  We create Quotes for customers regularly and when we want to send the quote to the customer, we have to send it manually. We can automate this, using Custom Functions. Based on a criteria, you can trigger a workflow rule and the custom function associated to the rule and automatically send the quote to customer through an email. Please note that the quote will be sent as an inline email content and not as a PDF attachment. Please follow
    • Function #50: Schedule Calls to records

      Welcome back everyone! Last week's function was about changing ownership of multiple records concurrently. This week, it's going to be about scheduling calls for records in various modules. Business scenario Calls are an integral part of most sales routines.. Sales, Management, Support, all the branches of the business structure would work in cohesion only through calls. You could say they are akin to engine oil, which is required by the engine to make all of it's components function perfectly. CRM
    • Recent Topics

    • How do I post a new question in Zoho Community forums?

      Hi everyone, I’m new to the Zoho Community and I’m trying to figure out how to properly create and publish a new topic in the forum. When I visit the community page, I can’t clearly find the option like “Add Topic” or “Post Question.” Could someone guide
    • Any Zoho Books users in the Kenyan Hospitality industry? How to set service items for eTims?

      Hello, We are opening a coffee shop in Kenya and would like to know if there are any Zoho books users in hospitality service industry in Kenya? We would love to know: 1. how do you cope with the absence of the mandatory Tourism Levy 2% tax option? 2.
    • Cloning Item With Images Or The Option With Images

      Hello, when I clone an item, I expect the images to carry over to the cloned item, however this is not the case in Inventory. Please make it possible for the images to get cloned or at least can we get a pop up asking if we want to clone the images as
    • Zoho Books | Product updates | May 2026

      Hello users, We're back with the latest updates and enhancements we've rolled out in Zoho Books. From sales tax automation to scanning receipts for free, explore the updates designed to upgrade your bookkeeping experience. Sales Tax Automation [US & Canada
    • Zoho Books | Product updates | June 2026

      Hello users, Welcome to this month's roundup of what's new in Zoho Books! We have an exciting line-up this time. The highlight is the launch of the all-new France Edition with full ISCA compliance. We're also introducing features such as Layout Rules
    • Does Zoho Learn integrate with Zoho Connect,People,Workdrive,Project,Desk?

      Can we propose Zoho LEarn as a centralised Knowledge Portal tool that can get synched with the other Zoho products and serve as a central Knowledge repository?
    • Request to Update Billing Information and Payment Method

      Hello, I’m using Zoho and I would like to update the billing information and change the payment card to our company card. Could you please let me know how I can do this? Thank you in advance for your help.
    • Zoho Analytics "Esc" key problem

      I frequently use the Escape (Esc) key while building dashboards, reports, and writing SQL queries. Since the recent updates to Zoho Analytics, the Esc key no longer behaves as expected. When writing SQL queries, pressing Esc to dismiss a suggestion now
    • Zoho Analytics Filter Bug

      I encountered a bug where typing the letter "A" in the drop-down filter of a table or query table causes the drop-down to close unexpectedly. For example, when typing "Today", the drop-down list closes as soon as "a" is entered. I tested this on another
    • Using Email Triggers on Zoho Flow

      Hello, I'm sending the email to create the variables as this article says: https://help.zoho.com/portal/en/kb/flow/user-guide/create-a-flow/articles/email-trigger#How_email_trigger_works But the collection of the variables only seems to work when the
    • How to customize the "Placeholder Text" separately from the "Field Label" on the Booking Form?

      Hi, I am currently customizing the Booking Form for one of my Workspaces in Zoho Bookings, and I need some help adjusting a custom text field. Right now, when I create a custom text field, the gray "placeholder text" inside the text box automatically
    • Why don't Zia agents support file uploads?

      I am trying to build a Zia Agent that allows uploading of a PDF file and uses the GLM5 model to process it and extract information. But agents.zoho.com has no way to enable file uploads on the agent. Additionally, GLM5 based agents keep outputting their
    • Pasting Images in Zoho Desk ignores cursor location

      My team has reported an issue which started recently where when we paste an image into a new or existing reply or comment, the pasted image seems to ignore the current cursor location instead paste itself at the last character present in the reply/comment,
    • 'Pinned' notes feature of a pipeline record

      Hi team, Could you please implement a feature which will allow users to pin different notes so that they will appear at the very top of the notes tab in a pipeline record. Sometimes we have a wide range of notes on a record which means more important
    • Announcing new features in Trident for Mac (1.37.0)

      Hello everyone! We’re excited to introduce the latest updates to Trident, which are designed to take workplace communication to the next level. Let’s dive into the details. Import EML archives directly into Trident. You can now import EML archives into
    • #10 Bill While You Sleep

      A consultant is reviewing last month's work. Client meetings? Done. Deliverables? Sent. Support requests? Resolved. Then they realize something. "I have completed the work... but I haven't billed the client yet." The work was completed. The client was
    • Access images from form submission in power automate

      Images from form submission show up as links in power automate. How do I access the image data?
    • Kaizen #245 - Real Time Signal Alerts for High-Value Abandoned Checkouts

      Howdy, Tech Wizards! Welcome back to another week of Kaizen. In this post, we will build a real-time abandoned checkout notification system using Stripe, Zoho CRM Functions, Sales Signals, and Widgets. When a customer abandons a high-value purchase, Zoho
    • Unable to attach Fillable File Upload field to Merge Template ever since UI update

      Ever since the new UI update, the field for Attachments for sending document for Signing in Writer has had an issue where trying to add a Fillable item in the Attachment field ends up always becoming a "Choose a File From Drive" option instead. No matter
    • Latest updates in Zoho Meeting | An improved Analytics tab and user interface, an invite pop-up revamp, an enhanced Zoho Meeting iOS app, a recording feature in the Android app, and more

      Hello everyone, We’re excited to share a few updates and enhancements in Zoho Meeting. Here's what we've been working on lately: Improved analytics for meetings, an invite pop-up revamp, a multi-video feed interface in the iOS app, a recording feature
    • Inquiry Regarding Automated Assignment of Zoho TeamInbox Messages using Zoho Flow and Deluge

      Hello, Our company is currently using Zoho TeamInbox, and we are interested in automating the assignment of responsible parties using tools such as ZOHO Flow and Deluge. Is it possible to achieve this? Allow me to provide more details. Currently, when
    • [Bug] WebAuthn passkey registration blocked on rpIds with TLDs longer than 6 characters (.accountant, .technology, etc.) — isValidDomain regex too strict

      Hi, Filing on behalf of an enterprise customer where Zoho Vault is deployed across the company. The Chrome extension blocks WebAuthn passkey registration on legitimate sites whose Relying Party ID (rpId) has a TLD longer than 6 letters. This affects every
    • Celebrating the businesses behind Bigin: Customer Awards 2026

      Hello Biginners, We're excited to announce the very first Bigin Customer Awards! If Bigin has played a role in your organization's journey, we'd love to hear about it. Share your story for a chance to be recognized among the best Bigin users across industries.
    • Zoho Desk: Auto-resizing of the "Description" textarea when creating a ticket.

      I would like to suggest an improvement for Zoho Desk regarding the Auto-Height-Resizing for Description field on the “Create a Ticket” page. It would be highly beneficial if the editor supported auto-resize functionality, allowing it to adjust dynamically
    • Is there an API endpoint to retrieve the remaining email credit balance?

      Hi everyone, Is there any way to retrieve the remaining email credit balance programmatically through the API? I've gone through the full API documentation and it seems like there's no endpoint for this — everything related to credits is only visible
    • Switch between multiple LLMs instantly for tailored Zia experiences

      Availability Editions: Professional , Enterprise, Ultimate , CRMPlus , ZohoOne Release Plan: Available for all DCs Hello everyone, Previously, the multi-LLM feature supported only one LLM at a time for Zia Record Assistant, which restricted users' flexibility
    • Zoho CRM Community Digest - April 2026 | Part 2

      Hello Everyone! We're back with Part 2 of the April Zoho CRM Community Digest to wrap up our monthly roundup. This week, the spotlight is on smart database connections, proactive error tracking, and optimizing subform line items without breaking your
    • 【西日本初開催】「AI and DX Summit 2026」のご案内

      ユーザーの皆さま、こんにちは! 西日本初開催となるZoho ユーザー / 検討中の方々向けイベントのご紹介です。 AI・DX大型カンファレンス「AI and DX Summit 2026」を、2026年7月16日(木)に開催します。 会場は、ウォルドーフ・アストリア大阪。 グラングリーン大阪直結のラグジュアリーな空間で、AIとDXの最新トレンド、実践事例、 展示、ネットワーキングが集結する、特別な1日をお届けします。 👉イベントページを見る ━━━━━━━━━━━━━━━ AIとDXの“今”を、体感。
    • Stop by and explore our six updates in ABM for Zoho CRM

      Dear Customers, We hope you're well! ABM for Zoho CRM is built to sharpen your database so that you engage with the right set of customer accounts. To fine-tune it further, we have six new updates: New access location for ABM Refined account entry criteria
    • Tracking Emails sent through Outlook

      All of our sales team have their Outlook 365 accounts setup with IMAP integration. We're trying to track their email activity that occurs outside the CRM. I can see the email exchanges between the sales people and the clients in the contact module. But
    • Enhancement in Zoho CRM: Introducing New Return Types for String Fields Based on Character Length

      Dear Customers, We hope you’re well! In Zoho CRM, formula field with string return type is used in various scenarios where text is involved like concatenating customers’ first and last names, trimming characters from texts, performing find and replace
    • Incoming Rules: Define how incoming emails are evaluated and handled

      As organizations grow, managing incoming emails manually becomes increasingly difficult. Administrators often need more control than what a standard spam filtering can provide. Whether that's enforcing company-wide email policies, handling messages from
    • Zia Emails Summary: Instant context from past emails

      Hello all, Reading all of the past emails associated with a specific record can be tedious, which in turn makes it difficult to understand the context quickly, as these messages often include irrelevant details that waste time. This is true for everyone
    • Boost your CRM communication with new font types, sizes, and default reply-to options while composing emails

      Hello Everyone, We’re excited to introduce a series of impactful enhancements to the email composer settings in Zoho CRM. These updates enable you to personalize and optimize your customer interactions with greater efficiency. So what's new? Add custom
    • Bing ads integration and tracking

      Hi, Is there any way to track Bing ads in the same way that we are able to track google adwords?  It is important for us to be able to determine the conversion rate of our Bing ads.  If this is not possible now, will this feature be added in the future?
    • Zoho Creator Calendar - Sorting Events

      Hi, I have a calendar view to hold the schedule for a group of engineers. I have created a formula field to show the combination of fields I want visible as the title of the event, but I need to be able to sort the list by something other than the event
    • Upcoming Update: Disposition Sync for Indeed

      We’re updating our Indeed integration to support Disposition Sync, improving how candidate application statuses are communicated. This change is scheduled to go live on 15 June, 2026. What’s changing? Once enabled, this allows candidate application statuses
    • Joining Two Tables on Multiple Ids

      Hello all, I'm guessing there is an obvious solution for this, but definitely not an expert in sql. On our Deals module, we have two user lookup fields. In Analytics, those fields have the user's ids in those table rows, and I'm trying to create a query
    • auto update of item purchase cost

      Would be nice if, when entering bills, the price of the item varied from the stored item price, we could have a user dialogue "Update item price" | "yes / no". Simple, but saves a lot of additional work !
    • Journeys - How to set up a webhook that triggers when a contact meets the goal criteria?

      Hi there, I'm setting up a journey on Marketing Automation. The main goal of the journey is to get the leads to reply our emails. Is there a way to trigger a webhook when that goal is met? The webhook would then trigger a notification. Is that possible?
    • Next Page