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

    Nederlandse Hulpbronnen


      • Recent Topics

      • Workflows being applied and the Large unwanted popup

        When a workflow is being applied do to an action, then the Agent is left with a large Window asking if they would like the see the changes this workflow did. Is there any way to disable this prompt from appearing?
      • What's New in Zoho Billing | March 2026

        March is here with a fresh wave of updates to Zoho Billing. From making compliance easier, reporting more flexible, to making day-to-day workflows smoother across the board. Here's everything that's new this month. Introducing Usage-Based Billing Reports
      • Business Day Logic Update: More Accurate Scheduling for Your Workflows

        Hello everyone, We’re improving how business-day calculations work in workflows, especially when triggers happen on weekends. This update ensures that offsets like +0, +1, and +2 business days behave exactly as intended, giving you clearer and more predictable
      • How to add a filter

        Hi Team, How can I set a filter like excel, instead of adding a new button.
      • A POS solution to complete the business solution for SME businesses

        For such a long time one aspect of SME business completely ignored has been a suitable POS solution native to Zoho and integrated with all the usual and necessary applications such as Inventory, Books, Commerce and CRM. The first and generally only option
      • Zoho Form not synching with Zoho CRM in CRM email template

        I have in the past successfully created an email template that has access to a Zoho Form in the url link to Forms in the email template. I am in the Contact Module of the CRM and I have created a Form for contacts and mapped the two. I am using the upsert
      • 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
      • Coupon Codes and Cancelling Subscriptions

        We have two Zoho One organizations, one we use for dev/testing. In Zoho Billing when we cancel a subscription, we are getting two different behaviors with regards to coupons. In one environment, the coupon is removed upon cancellation. In the other, the
      • Zoho Books | Product updates | April 2026

        Hello users, Welcome to our April 2026 product updates roundup! Highlights include profit margin for sales transactions, insights in reports, recording deposits from undeposited funds in banking, and faster production workflows with improved assembly
      • Journal Entries Do Not Show Multiple Entries to the Same Account

        Another basic accounting function that Books ... Accountants sometimes write journal entries, debiting and/or crediting the same account in the same entry. This is due to the need to record specific activity in an account when we pull reports especially
      • Email Opt Out Question

        Has the problem where if a customer is emailed opt out prevents you sending standard emails? For me this feature is simply to stop any email marketing and should not block people from receiving emails via Zoho mobile, which makes no sense.
      • Bulk Writer Export

        Pardon me if this has already been discussed (I can't find anything about it in these forums and my last attempt to start a thread seems to have failed). Is it possible to export more than one document at once? I would be really great to be able to burn OpenOffice.Org files of all my Zoho documents once a month to a CDR. If that feature is available/were created, this would be my main word processor. Without being able to do my own bulk backups I'm leery to count on Zoho's servers (which are robust
      • Sites API

        Is there a Sites API and if so where can we find documentation
      • Extracting phone number from variable

        Hi. I've created a flow between Calendly and Zoho CRM. So when someone schedules a meeting in Calendly, there is a lead created in Zoho CRM. However, I am not able to fill in the phone number field in Zoho CRM, because the phone number is included in
      • I can't fetch Calendly Fields

        Hello, I have set up a flow to connect Calendly with Zoho CRM, A few days ago I have mentioned that I should update the Calendly app connection and I have done, After Calendly has been updated I have some issues such as Event location missing I can map
      • Edit a previous reconciliation

        I realized that during my March bank reconciliation, I chose the wrong check to reconcile (they were for the same amount on the same date, I just chose the wrong check to reconcile). So now, the incorrect check is showing as un-reconciled. Is there any way I can edit a previous reconciliation (this is 7 months ago) so I can adjust the check that was reconciled? The amounts are exactly the same and it won't change my ending balance.
      • What's new in Zoho Social - Q1 recap

        Hello everyone, We’ve rolled out a bunch of updates in Q1, and we’re excited to walk you through them. To help you explore these features in detail, we’re hosting a Q1 recap webinar where we’ll show you how to make the most of each update. Q1 recap webinar
      • Ignore Auto Sales Order number generation not working

        Hi, My Flow has broken and I'm no longer able to use the Ignore auto number generation function and instead use the field that came from the trigger (via Jotform) when creating a new Sales Order in Books. Any suggestions how to fix this?
      • Vendor bills cannot be assigned to a customer or a customer project?

        I'm confused on how to handle outsourced contractor expenses on a customer project.  Between my business and the contractor, the invoice they send me fits obviously into Zoho Books as a Bill. However, I need to be able record those expenses to the client
      • Anyone using Books to track Project Profitability? If so, I could use some guidance

        Hello Zoho Community. I am a recent subscriber to Zoho, and its part of an ongoing evaluation.  My company (and my clients) have extensive project-tracking needs.  The Projects module seems to be good from a project management standpoint, but I am perplexed
      • Introducing parent-child ticketing in Zoho Desk [Early access]

        Hello Zoho Desk users! We have introduced the parent-child ticketing system to help customer service teams ensure efficient resolution of issues involving multiple, related tickets. You can now combine repetitive and interconnected tickets into parent-child
      • Problem in usage zoho

        Difficulty to submit the from in my training to handle ticket on your free trial
      • In-House, Non-Billable Projects

        I use Zoho Projects solely for in-house projects with fixed cost budgets.  Only bills and expenses need to be charged against the budget.  There are no customers to be billed or invoices to be created. How can such a non-billable project be set up?   As
      • [Webinar] What's New in Zoho Analytics: Q1, 2026

        To all the data enthusiasts out there, we're back again with another power-packed webinar in the What's New series! This last quarter was marked by exciting new features and product updates focused on offering you top-notch solutions. With new data connectors,
      • Ask The Expert: Deep Dive into Zoho CRM, Desk, SalesIQ, and Campaigns!

        Are you using Zoho to power your sales, support, and marketing, and have questions about configuration, automation, or best practices? We have great news: the “Ask The Expert” session is coming to the Zoho Benelux Community! This session is specifically
      • Users I've shared the sheet with cannot use the Custom Functions

        Hi, I have a Zoho Sheet worksheet that I shared to 2 colleagues, giving them full access: In that worksheet, I created a button with a custom Deluge function and it works flawlessly for me: For those I shared the worksheet to, when they click the button,
      • Limiting the form - Zoho People

        Hi Team, I would like to limit the number of form/request submissions for employees within a given month. For example, if an employee has already submitted 3 requests in the current month, they should not be allowed to submit any further requests. An
      • Automate the file import step

        Hello everyone, I have a Sales - 'Account' category, and currently import the file to update it as follows: Import Accounts - From File - Update existing Accounts only - select and match the field the CRM. Since we have been using Microsoft 365 SharePoint.
      • Zoho Creator In-App Notification

        Hi Team, I have implemented an in-app notification using code, as it required some customization. I followed the example in the link below: https://www.zoho.com/deluge/help/pushnotify-using-deluge.html#Example I have a couple of questions regarding this
      • Deluge Error: "Data type of argument of function 'get' did not match required type [BIGINT]" when working with Lookup fields

        Hi everyone, I’m facing an issue in Zoho CRM Deluge while working with lookup fields. Setup: Module: Monthly Bills Field: Customer (Lookup → Accounts) Module: Laundry Orders Field: Laundry_Account_Name (Lookup → Accounts) Field: Expected_Revenue (Currency)
      • Add Flexible Recurrence Options for Meeting Scheduling in Zoho Cliq (e.g., Every 2 Weeks)

        Hello Zoho Cliq Team, We hope you are doing well. Currently, when scheduling a meeting inside Zoho Cliq, the recurrence options are limited to Daily, Weekly, Monthly, and Yearly. There is no ability to set a meeting to occur every X weeks — for example,
      • Announcing Zoho Sheet desktop app for macOS and Windows (Beta)

        Hello Sheet users, We know you’ve been waiting for this one. It has always been the top priority on our roadmap to provide a single native desktop app for macOS and Windows that works both online and offline. Today, we are excited to announce that the
      • In App Auto Refresh/Update Features

        Hi,    I am trying to use Zoho Creator for Restaurant management. While using the android apps, I reliased the apps would not auto refresh if there is new entries i.e new kitchen order ticket (KOT) from other users.   The apps does received notification but would not auto refresh, users required to refresh the apps manually in order to see the new KOT in the apps.    I am wondering why this features is not implemented? Or is this feature being considered to be implemented in the future? With the
      • Unable to Log In to FSM Mobile App

        Hello FSM Team, We are encountering an issue when logging in to the FSM mobile app. When entering the user email, the system shows the error: “This account does not exist.” However, the same user is able to log in successfully via web (fsm.zoho.com).
      • Clarification on “Change Owner” vs Dispatcher Role in Work Orders

        Hi Mr. Abid, Good day! We would like to understand the purpose and correct usage of the “Change Owner” option in the Work Order module. As we noticed, there is an option to Change Owner in the Work Order. At the same time, there is also a separate field/role
      • New Income Tax Act 2025 and Rules 2026 for India (Effective 1 April 2026)

        Hello everyone, The Income Tax Act 2025 came into effect from 1 April 2026. This new law replaces the old Income Tax Act of 1961. Along with the new Act, the Income Tax Rules 2026 have also been released by the government. These updates bring practical
      • Facturation électronique 2026 - obligation dès le 1er septembre 2026

        Bonjour, Je me permets de réagir à divers posts publiés ici et là concernant le projet de E-Invoicing, dans le cadre de la facturation électronique prévue très prochainement. Dans le cadre du passage à la facturation électronique pour les entreprises,
      • How can I delete a user profile created ?

        I can't delete custom profiles created. Why ?
      • Search API filter/sort ignores comment-triggered modifiedTime updates

        Summary When a comment is added to a Call or Account, the parent record's modifiedTime is correctly bumped. This bumped value is visible in: GET /api/v1/calls/{id} ✅ GET /api/v1/calls/search without a filter ✅ — the record's response body shows the new
      • ZOHO Cadence

        Can you edit when a cadence is set to enroll? For instance, I currently have it set up to enroll three days after a new record is created that fits the custom view criteria; however, I would like to change it to enroll immediately. I do not see where
      • Next Page