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

      • CRM x WorkDrive: File storage for new CRM signups is now powered by WorkDrive

        Availability Editions: All DCs: All Release plan: Released for new signups in all DCs. It will be enabled for existing users in a phased manner in the upcoming months. Help documentation: Documents in Zoho CRM Manage folders in Documents tab Manage files
      • Creator Offline

        We had online access setup and working on our iphones. We have just set it up on an 'Android Tablet' and it is not downloading all the images? We use it to show customers our catalogue. Any ideas. Offline components all setup on both devices
      • Drag 'n' Drop Fields to a Sub-Form and "Move Field To" Option

        Hi, I would like to be able to move fields from the Main Page to a Sub-Form or from a Sub-Form to either the Main Page or another Sub-Form. Today if you change the design you have to delete and recreate every field, not just move them. Would be nice to
      • Enable or disable any Field Rule!

        Hello Zoho Forms Community, We are excited to announce a powerful new enhancement to Field Rules that gives you greater control and flexibility in managing your form logic! Previously, if you wanted to temporarily deactivate a field rule, you had two
      • Marketing Tip #20: Increase traffic with strong meta titles and descriptions

        Meta titles and descriptions are what people see first on search results before they ever click through to your website. If your pages use generic titles or basic descriptions, you miss the chance to stand out, and search engines may not know which page
      • Super 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. Moderation Update (8th Aug 2025): We are working
      • Different form submission results for submitter and internal users

        I'm looking for suggestions on how to show an external submitter a few results while sending internal users all the results from the answers provided by the external user. The final page of our form has a section with detailed results and a section with
      • Kanban view on Zoho CRM mobile app!

        What is Kanban? The name doesn't sound English, right? Yes, Kanban is a Japanese word which means 'Card you can see'. As per the meaning, Kanban in CRM is a type of list view in which the records will be displayed in cards and categorized under the given
      • Not able to delete a QC nor able to revert or create a cycle of manufacturing for QC failed Jobs

        Not able to delete a QC nor able to revert or create a cycle of manufacturing for QC failed Jobs
      • Dheeraj Sudan and Meenu Hinduja-How do I customize Zoho apps to suit my needs?

        Hi Everyone, I'm Meenu Hinduja and my husband Dheeraj Sudan, run a business. I’m looking to tweak a few things to fit my needs, and I’d love to hear what customizations others have done. Any tips or examples would be super helpful! Regards Dheeraj Sudan
      • Zoho Desk blank screen

        opened a ticket from my email, zoho desk comes up blank, nothing loads. our receptionist also gets the same thing under her login on her computer. our sales rep also gets same thing on zoho desk at his home on a different computer. I tried clearing cache/history/cookies,
      • is there any way to change the "chat with us now" to custom message?

        is there any way to change the "chat with us now" to custom message? I want to change this text
      • Deprecation Notice: OpenAI Assistants API will be shut down on August 26, 2026

        I recieved this email from openAI what does it means for us that are using the integration and what should we do? Earlier this year, we shared our plan to deprecate the Assistants API once the Responses API reached feature parity. With the launch of Conversations,
      • Capture Last check-in date & days since

        I have two custom fields on my Account form, these are "Date of Last Check-In" and "Days Since Last Contact" Using a custom function how can I pull the date from the last check-in and display it in the field "Date of Last Check-In"? and then also display the number of days since last check-in in the "Days SInce Last Contact" field? I tried following a couple of examples but got myself into a bit of a muddle!
      • Any recommendations for Australian Telephony Integration providers?

        HI,  I am looking for some advice on phone providers as we are looking to upgrade our phone system, does anybody have experience with any of the Australian providers that integrate with CRM Telephony? So far we are looking at RingCentral and Amazon Connect, and would love to hear feedback on any of the other providers you might have tried.  Thank you
      • Why is the ability Customize Calls module so limited?

        Why can't I add additional sections? why can't I add other field types than the very limited subset that zoho allows? Why can I only add fields to the outbound/inbound call sections and not to the Call Information section?
      • Zoho Desk - Upsert Ticket

        Hi Desk Team, It is common to request more information from end-users. Using forms is a great way to ensure all the required information is collected. It would be great if there were an "upsert" option on the Zoho Form -> Zoho Desk integration which would
      • CRM gets location smart with the all new Map View: visualize records, locate records within any radius, and more

        Hello all, We've introduced a new way to work with location data in Zoho CRM: the Map View. Instead of scrolling through endless lists, your records now appear as pins on a map. Built on top of the all-new address field and powered by Mappls (MapMyIndia),
      • Enhance Appointment Buffers in Zoho Bookings

        There was previously a long-standing feature request related to enhancing the way appointment buffers work in Zoho Bookings, but it looks like the original post has been deleted. I am therefore adding a new request that Zoho Bookings adjust how appointment
      • Subscriptions for service call

        So we install products and we want to offer a service contract for the customers yearly service calls to be billed monthly. So ideally at some point we want to email them a quote for their needs. WE will choice it our end based on the equipment. It would
      • Blocklist candidates in Zoho Recruit

        We’re introducing Block Candidate, which helps recruiters to permanently restrict a candidate from applying to current/future job openings. Once the candidate is blocked, they will no longer be able to participate in the recruitment process. This will
      • Add RTL and Hebrew Support for Candidate Portal (and Other Zoho Recruit Portals)

        Dear Zoho Recruit Team, I hope you're doing well. We would like to request the ability to set the Candidate Portal to be Right-to-Left (RTL) and in Hebrew, similar to the existing functionality for the Career Site. Currently, when we set the Career Site
      • Zoho recruit's blueprint configuration is not functioning as mapped

        Current Status: Zoho Blueprint is not functioning as configured. Issue: We are moving a Candidate status in Zoho Recruit "for active file" but we encountered: "Status cannot be changed for records involved in Blueprint." This happens to various client
      • Delay in rendering Zoho Recruit - Careers in the ZappyWorks

        I click on the Careers link (https://zappyworks.zohorecruit.com/jobs/Careers) on the ZappyWorks website expecting to see the job openings. The site redirects me to Zoho Recruit, but after the redirect, the page just stays blank for several seconds. I'm
      • How to add interviews through API

        I'm trying to add an interview without much luck. The documentation gives examples of adding just about everything except an interview. However, the issue might be the way I'm formatting it, because the documentation is unclear to me. It seems as if the xml should be passed in the url, which seems unusual. I've tried the data as both plain and character escaped, but nothing seems to work, nor do I even get an error response. https://recruit.zoho.com/recruit/private/xml/Interviews/addRecords?authtoken=***&scope=recruitapi&version=2&xmlData=<Interviews> <row
      • Connection to other user

        Zoho Cliq handles sharing of Custom OAuth Connections that require individual user logins.
      • How to invite friends on other social media platforms to one of my group chats in arattai?

        Hello, I have formed chat groups in arattai. I want to invite my friends on other social media platforms like WhatsApp/ FB to one of my groups. Different friends would be invited to different groups. How to share an invite link of one of my groups to
      • Cliq does not sync messages after Sleep on Mac

        I'm using the mac app of Cliq. When I open my mac after it was in sleep mode, Cliq does not sync the messages that I received. I always have to reload using cmd + R, which is not what I want when using a chat application.
      • Optimum CRM setup for new B2B business

        Can some advise the most common way to setup Zoho CRM to handle sales for a B2B company? Specifically in how to handle inbound/outbound emails. I have spent hours researching online and can't seem to find an accepted approach, or even a tutorial. I have
      • Facing Issues with Sites Mobile font sizes

        my page renediaz.com is facing issues mobile view, when i try to lower font sizes in home page, instead of changing the size, it changes the line space
      • Does the Customer “Company Name” field appear anywhere in the Zoho Books UI outside of PDFs?

        Hi everyone, I’m trying to understand how the Company Name field is actually used in Zoho Books. There is a Company Name field on the customer record, but when viewing transactions like a Sales Order in the normal UI (non-PDF view), that field doesn’t
      • Set expiration date on document and send reminder

        We have many company documents( for example business registration), work VISA documents. It will be nice if we can set a expiry date and set reminders ( for example 90 days, 60 days, 30 days etc.,) Does Zoho workdrive provide that option?
      • Analytics : How to share to an external client ?

        We have a use case where a client wants a portal so that several of his users can view dashboards that we have created for them in Zoho Analytics. They are not part of our company or Zoho One account. The clients want the ability to have user specific,
      • 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
      • Automatically Update Form Attachment Service with Newly added Fields

        Hi, When I have a Form Setup and connected to a 3rd Party Service such as OneDrive for Form Attachments, when I later add a new Upload Field I have to remove and redo the entire 3rd Party Setup from scratch. This needs to be improved, such as when new
      • Zoho Sheet for Desktop

        Does Zoho plans to develop a Desktop version of Sheet that installs on the computer like was done with Writer?
      • Payroll and BAS ( Australian tax report format )

        Hello , I am evaluating Zoho Books and I find the interface very intuitive and straight forward. My company is currently using Quickbooks Premier the Australian version. Before we can consider moving the service we would need to have the following addressed : 1.Payroll 2.BAS ( business activity statement ) for tax purposes 3.Some form of local backup and possible export of data to a widely accepted format. Regards Codrin Mitin
      • Zoho Desk API - Send Reply to CUSTOMERPORTAL

        Hello! I'll try to send a reply to Customer Portal, But the response is 500 (INTERNAL_SERVER_ERROR in service response). {"Error":"{\"errorCode\":\"INTERNAL_SERVER_ERROR\",\"message\":\"An internal server error occurred while performing this operation.\"}"}
      • Python - code studio

        Hi, I see the code studio is "coming soon". We have some files that will require some more complex transformation, is this feature far off? It appears to have been released in Zoho Analytics already
      • From Zoho CRM to Paper : Design & Print Data Directly using Canvas Print View

        Hello Everyone, We are excited to announce a new addition to your Canvas in Zoho CRM - Print View. Canvas print view helps you transform your custom CRM layouts into print-ready documents, so you can bring your digital data to the physical world with
      • Next Page