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

    • Zoho Publish is now available in Zoho One!

      Hello Zoho One users, We’re excited to announce that Zoho Publish is now included as part of the Zoho One suite! As businesses grow, keeping their business information accurate across online platforms can become challenging. Updates may be missed, details
    • How to change an employee mail id

      Hi, Does the administrator have the rights to edit an  employees mail id. 
    • Cousin Domain Verification in Zoho Mail: Identify and block look-alike domains

      Phishing attacks often rely on domain names that closely resemble legitimate ones. This makes it difficult for users to identify fraudulent emails at first glance. Zoho Mail's Cousin Domain Verification feature allows administrators to define trusted
    • How do I add 2 agents under the same email?

      I have 2 agents who use the same email address. I added one, but when adding the second agent, it says that the email is already registered. How do I configure this properly?
    • Zoho Desk API modifiedTimeRange returns HTTP 500 around 2026-03-08T02:00:00.000Z

      Hello Zoho Support Team, We are experiencing a reproducible HTTP 500 Internal Server Error when querying the Zoho Desk API search endpoint with a specific modifiedTimeRange boundary. ### API Endpoint GET /api/v1/tickets/search ### Reproduction Steps &
    • Updating an Invoice Line Item's Discount Account via API Call / Deluge Custom Function

      I need help updating an invoice line item's discount account via API. Below is a screenshot of the line item field I am referring to. Now the field to the left of the highlighted field (discount account) is the sales income account. I am able to modify
    • Collaborate Visually with Whiteboard in Zoho Projects

      Whiteboard in Zoho Projects allows you to collaborate visually by creating diagrams, annotating designs, and sketching project workflows using shapes, text, and images within project modules. Team members can work simultaneously, improving productivity
    • Associate project with timer on iPhone

      When I start the timer without first associating a project (on my iPhone), its starts fine but now when I need to associate a project, and click on the link, I get a list of EVERY project I've ever put into Zoho Books. It used to just show active projects.
    • Sales Tax Refund on Commerce Order

      I've looked high and low. Relatively new to ZOHO but not to systems in general. How do we produce a refund for sales tax charged and paid for by a customer in error? This does not impact inventory stock. Simply for accounting and getting the $ back to
    • Importing Chart of Accounts from Quickbooks -- "Debit or Credit"?

      I'm trying to switch from QB to Zoho Books. I've prepped my chart of accounts and put it into the format following the structure of the sample CSV file. But one thing that does not exist at all on the Quickbooks side is the Zoho column for "Debit or Credit".
    • Long term pricing for customers managing multiple organizations

      I've been using Zoho extensively for quite some time and genuinely think it's one of the most powerful and customizable business platforms available. Between Zoho Books and Zoho Analytics, I've invested a significant amount of time building automations,
    • Default Status for Appointments to Completed

      We use Zoho Bookings integrated with Zoho Desk to book time for tech support sessions, we've configured it to only allow for a contact to book a single session to avoid customers overbooking time that may not be needed. The trouble is, once a session
    • Customer User Fields for use in Rules

      Hi, I would like to be able to add custom fields to the users, such as Department or Role, which can then be used in Rules, Reports, etc. as a condition. A use case is limiting Global lists or Choices based on the users Custom Field, so one form can be
    • Add ZeptoMail to Zoho One

      Hi Zoho Team, I would like to request that ZeptoMail be added as a fully included application within Zoho One. Why this is important Zoho One is positioned as a unified business operating system that brings the applications an organization needs under
    • Item image on document

      I know what I am asking may not be possible, but I will ask anyway, maybe I will get lucky, and someone else is doing it. My business is based on special orders only from various online stores. When I send a quote to a client, I generate a separate quote
    • Dashboard Metric Drill-Down Shows Stale Data

      Summary: When clicking between different metric components on a custom dashboard, the drill-down list shows data from the previously opened metric instead of the one just clicked. Steps to Reproduce: Create a custom dashboard with multiple pre-defined/templatized
    • Zoho Marketing Automation WhatsApp Campaign Import Sync for Zoho Analytics

      WhatsApp is a critical channel in modern marketing, yet WhatsApp Campaign metrics from Zoho Marketing Automation currently cannot be natively imported into Zoho Analytics via the default advanced analytics connector. Integrating this into the standard
    • Allow Reauthorizing CRM Connections Without Revoking First

      Currently, when a Zoho CRM connection needs to be reauthorized or authorized with another account, we first have to revoke the existing authorization and then authorize it again. This creates a gap where the connection is unavailable, and any functions,
    • Programmatic Itemized Expenses?

      It does not appear that it is possible to create itemized expenses programmatically (via the API)? Is this correct, or am I misunderstanding the situation?
    • Prefix & Suffix on Single Line, Number, etc.

      Hi, I would like to have the same Prefix and Suffix that was added to the Unique ID on Text and Number Fields. Use case could be as basic as temperature, as per another Idea I have to use Single Line (Text) for a number that might have leading zeros today,
    • Handle Leading Zeros in a Number Field

      Hi, If I use a Number Field, set with Min 7 Digits and Max 7 Digits, and enter 0000001, it will result in 1 and an error as it removes the leading zeros, the same with entering 0012340 will result in 12340 and error. So I have to use a Text Field and
    • Is there a way to show contact emails in the Account?

      I know I can see the emails I have sent and received on a Contact detail view, but I want to be able to see all the emails that have been sent and received between all an Accounts Contacts on the Account Detail view. That way when I see the Account detail
    • Virtual Option for Fields

      Hi, I would like to be able to choose another option other than Read-Only or Disabled, such as Virtual. And with Virtual, the field is shown on the form and avilable in rules, but NOT saved to the Database. A use case is having multiple Large Lists of
    • Zoho Marketing Automation Cannot Sync Lookiup Fields

      Hello all, It seems that Zoho MA cannot sync Lookup fields from the CRM. Can you confirm if this is the case? Is there a workaround? Do you know if Campaigns can sync with custom modules and also with Lookup field in the CRM? Thank you!
    • Specific ListView Canvas on Canvas Home Page Always Loads Most Recent ListView, Not the One Specified

      I had mentioned this to ZOHO, but I mainly wanted to see if others in the Community are also facing this problem. I created a Canvas ListView for a Custom Module, and then created a Canvas Home page (technically on a tab item, but I'm not sure if that
    • Announcing the new SKILL.md for Zoho CRM and the updated OAS repository!

      We are introducing a new zoho-crm skill to make working with Zoho CRM Developer tools (like APIs, functions, widgets, client scripts, queries etc) easier and faster, with the help of AI in your preferred AI harness like Claude Code, Codex, Cursor, VSCode
    • Zoho Campaigns EU Topics API returns HTTP 200 with empty topicDetails

      Hello, Our Zoho Campaigns EU organisation has two custom topics visible in the Campaigns UI, and contacts are subscribed to them. However, an OAuth request with ZohoCampaigns.contact.READ to https://campaigns.zoho.eu/api/v1.1/topics returns HTTP 200 with
    • Caso de Éxito: Cómo Toyota Financial Services unificó la atención al cliente con Zoho

      "Después de seis meses con el CRM en producción estamos encantados." Miriam Cárdenas, Responsable Departamento ATC Toyota Financial Services es la división financiera de Toyota encargada de gestionar la financiación de vehículos y, junto con KINTO España,
    • Zoho Books - France

      L’équipe de Zoho France reçoit régulièrement des questions sur la conformité de ses applications de finances (Zoho Books/ Zoho Invoice) pour le marché français. Voici quelques points pour clarifier la question : Zoho Books est un logiciel de comptabilité
    • Sending Zoho form link from custom function in Zoho CRM

      Hello,  We intend to send a Zoho form link to certain Contacts using a custom function. The Zoho Form must be pre-filled with the Deal information and contacts receiving it should be able to modify the values and upon submission, those modifications must
    • Automatically remove commas

      Team, Please be consistent in Zoho Books. In Payments, you have commas here: But when we copy and paste the amount in the Payments Made field, it does not accept it because the default setting is no commas. Please have Zoho Books remove commas autom
    • Zoho ERP | Product updates | July 2026

      Hello users, We're back with another round of updates to help you streamline your operations. This month's release brings new features and enhancements designed to help you work more efficiently. Read on to discover everything that's new in Zoho ERP this
    • Zoho CRM

      Cuándo voy a adjuntar un archivo .pdf en un registro en el campo Archivo obtengo el siguiente error:
    • Can I hide some products from a particular customer

      HI I want ot give a customer access to the portal but I need to hide some products from them that are not available for them to buy- is this possible ?
    • Dashboard/Component filter by probability

      Hi all Can I request the ability to add a Component or Dashboard filter for Deal Probability? Would be useful to be able to see data of deals more than 60% probable. Olly
    • Admin Logging in as another User

      How can a Super Admin login as another user. For example, I have a sales rep that is having issues with their Accounts and I want to view their Zoho Account with out having to do a GTM and sharing screens. Latest Update (27th April 2026): With the early
    • OpenAI Is Moving to the Responses API: Here's What It Means for SalesIQ

      OpenAI has deprecated its Assistants API and is moving to the Responses API. If you're using OpenAI Assistants with SalesIQ, you may be wondering if you need to make any changes to your existing setup. You don't. SalesIQ has already taken care of the
    • Free webinar: Zoho Sign for Microsoft apps

      Hello, Did you know Zoho Sign works right inside the Microsoft apps you already use? A signature request shouldn't mean leaving Teams for another tab, or downloading an Outlook attachment just to sign it. Zoho Sign integrates with Microsoft 365, Teams,
    • Billing Status and WO Status Field Colors -

      Hello Team, I noticed that the colors of the Billing Status and WO Status fields in the WO module have been changed. (Org ID:170000078905) This is not urgent to correct, but I wanted to bring it to your attention so you can check whether this is a system
    • Introducing throw statements in Deluge

      Hello everyone, We're introducing a powerful addition to Deluge that gives you more precise control over error handling in your scripts. Whether you're calling an external API, validating user input, or enforcing a business rule, there are moments when
    • Next Page