Using a CRM Client Script Button to create a Books Invoice

Using a CRM Client Script Button to create a Books Invoice

Hello,
I need help handling error messages returned to my client script from a function.

The scenario
I have setup a client script button which is available from each Deal.
This CS executes a crm function, which in turn creates an invoice based on the information in the Deal.
The client script checks the deal is at the correct stage and displays the amount to be invoiced, before proceeding to execute the function.

The problem
It all works perfectly well except for the error handling. I'm only testing for a 'response' from the function ( in the Client Script) before showing a success or error message, so even if the function returns null or undefined, it still says it has been successful.

What I tried
So, I wanted to pass something more useful to the client script, like the newly created invoice number or id but it just doesn't seem to be working. I have tried using variations of this approach:
var output = JSON.parse(response.details.output)
but get this error amongst others...
"undefined" is not valid JSON 
What doesn't help matters is that I can't fully test the invoice creation process, even using a crm sandbox, because it will still create real invoices in Books, which I would rather avoid.

What are your thoughts on how to approach this?  Below are the relevant parts of my code, in case it is useful to see.

CRM Function
  1. string standalone.createtradeinvoicesa(String orderId,String userId,String invType)
  2. {
  3. // earlier code creates invMap with invoice items
  4. // CREATE NEW INVOICE IN ZOHO BOOKS
  5. resp = zoho.books.createRecord("Invoices",orgId,invMap,"zbooksall");
  6. if(resp.get("code") == 0)
  7. {
  8. //for client script
  9. invoiceid = resp.get("invoice").get("id");
  10. invoiceinfo = zoho.books.getRecordsByID("invoices",orgId,invoiceid,"zbooksall");
  11. info "client-script-output=" + invoiceinfo;
  12. invoiceNum = resp.get("invoice").get("invoice_number");
  13. invoiceDate = today.toDate("dd/mm/yyyy");
  14. invoiceDate = invoiceDate.toString("dd/MM/yyyy");
  15. //user id and name for note
  16.    else
  17. {
  18. returnMsg = "Error : an invoice has not been created in Zoho Books.";
  19. }
  20. return invoiceinfo;
  21. }

Client Script

  1. var functionName = "xxx";
  2. // get the order and user ID of this page
  3. var record_id = $Page.record_id;
  4. var user_id = $Crm.user.id;
  5. // get field values
  6. var stage_value = ZDK.Page.getField('Stage').getValue();
  7. var orderNo = ZDK.Page.getField('Deal_Name').getValue();
  8. // other checks go before this in the full script
  9. //If user clicks Proceed button
  10. if (isProceed) {
  11. // Message
  12. var successText = 'You will find your draft invoice in the Zoho Finance section below.';
  13. var errorText = 'There has been a problem, your invoice has not been created.';
  14. // show loader
  15. ZDK.Client.showLoader({ type: 'page', template: 'spinner', message: 'Creating Invoice...' });
  16. // call function in variable
  17. var response = ZDK.Apps.CRM.Functions.execute(functionName, { "orderId": record_id, "userId": user_id });
  18. ZDK.Client.hideLoader();
  19. // show sucess or error messages and execute function
  20. // response from function is the new invoice information, so in theory, the response should be null/undefined if the invoice wasn't created.
  21. if (response) {
  22. var sucessMessage = ZDK.Client.showAlert(successText, 'Invoice Created', 'Close');
  23. return response & successMessage & $Client.refresh();
  24. } else {
  25. errorMessage = ZDK.Client.showMessage(errorText, { type: 'error' });
  26. return errorMessage;
  27. }
  28. }
  29. //If user clicks Cancel button from invoice creation
  30. else {
  31. return false;
  32. }

    • Sticky Posts

    • Kaizen #222 - Client Script Support for Notes Related List

      Hello everyone! Welcome to another week of Kaizen. The final Kaizen post of the year 2025 is here! With the new Client Script support for the Notes Related List, you can validate, enrich, and manage notes across modules. In this post, we’ll explore how
    • Kaizen #217 - Actions APIs : Tasks

      Welcome to another week of Kaizen! In last week's post we discussed Email Notifications APIs which act as the link between your Workflow automations and you. We have discussed how Zylker Cloud Services uses Email Notifications API in their custom dashboard.
    • Kaizen #216 - Actions APIs : Email Notifications

      Welcome to another week of Kaizen! For the last three weeks, we have been discussing Zylker's workflows. We successfully updated a dormant workflow, built a new one from the ground up and more. But our work is not finished—these automated processes are
    • Kaizen #152 - Client Script Support for the new Canvas Record Forms

      Hello everyone! Have you ever wanted to trigger actions on click of a canvas button, icon, or text mandatory forms in Create/Edit and Clone Pages? Have you ever wanted to control how elements behave on the new Canvas Record Forms? This can be achieved
    • Kaizen #142: How to Navigate to Another Page in Zoho CRM using Client Script

      Hello everyone! Welcome back to another exciting Kaizen post. In this post, let us see how you can you navigate to different Pages using Client Script. In this Kaizen post, Need to Navigate to different Pages Client Script ZDKs related to navigation A.
    • Recent Topics

    • Zoho Desk 2025 Recap

      Hello everyone, Let’s take a look at the major features and enhancements from Zoho Desk in 2025. Zia in web Zia (powered by open source language model [Llama 3.1]), can perform a variety of actions from predicting behavior to automating crucial ticket
    • Print Sales Orders, Purchase Orders or Invoices from API

      Hello, Is it possible to use the print option that is available in Sales Orders Purchase Orders and Invoices with the API?. I don't see any information in the docs about this. Thanks
    • New in Smart Prompt: Record Assistant for contextual assistance, and support for new AI models

      Smart Prompt helps teams stay informed and move faster by providing relevant suggestions where work happens in CRM. With this update, Smart Prompt becomes more adaptable to your organization’s AI preferences. You can now choose which Large Language Model
    • 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),
    • Zoho Books - How to Invoke a Custom Function in Schedulers

      We have multiple schedulers that send emails to customers in batches. Currently, we are maintaining the same code across several schedulers. Is it possible to use a custom function inside a scheduler script? If yes, how can we invoke the custom function
    • How to show a hided report??

      in CRM Report , I clicked Hide incidently , how to show the floder again? Nowhere I can find the hided report floder...
    • To print Multiple delivery notes in batches

      In Zoho Books, we can print a Delivery Note from an Invoice using the Print Delivery Note option, but it is non-editable and always prints all line items from the invoice. Our requirement is to deliver invoiced items in batches and print delivery notes
    • Converting Customer Invoice to Purchase Bill

      Hi, In my service-based business, I sometimes create the customer invoice first, and later I receive the purchase bill from the vendor for the same job. Is there any option in Zoho Books to: Convert a customer invoice into a purchase bill, or Link/associate
    • Email tracking inquiry

      I am trying to track when my emails are opened and clicked like I previously did in HubSpot. HubSpot pretty much did the entire process automatically. After digging through, I finally found in settings --> emails --> BCC Dropbox there is an email I can
    • Mass Update of Lookup Fields not possible

      Hello List I've created a custom field for Leads and Contacts 'Current Campaign'. This is very Handy as I can filter leads and then related them to a campaign. Everything ready, but then I realized that mass update doesn't work for lookup fields... a
    • How to apply customized Zoho Crm Home Page to all users?

      I have tried to study manuals and play with Zoho CRM but haven't found a way how to apply customized Zoho CRM Home Page as a (default) home page for other CRM users.. How that can be done, if possible? - kipi Moderation Update: Currently, each user has
    • Blueprint transitions on locked records

      We use the ability to automatically lock records (quotes, sales orders, etc.) based on criteria, such as stage. For instance, if a quote has been sent to a client, the quote is then locked for further edits. Our ideal quote stage process is: Draft>Sent>Won.
    • Collapsible Sections & Section Navigation Needed

      The flexibility of Zoho CRM has expanded greatly in the last few years, to the point that a leads module is now permissible to contain up to 350 fields. We don't use that many, but we are using 168 fields which are broken apart into 18 different sections.
    • Quick Create needs Client Script support

      As per the title. We need client scripts to apply at a Quick Create level. We enforce logic on the form to ensure data quality, automate field values, etc. However, all this is lost when a user attempts a "Quick Create". It is disappointing because, from
    • Instant Messaging Update | Now migrate your WhatsApp Business phonenumber from another BSP to Zoho Desk | Dec'23

      Hi All, Everything seems to move at lightning speed these days, and time is certainly flying by for the IM team. But we are delighted at how much ground we covered this year. 🚀 For one, we enabled WhatsApp business phone number migration so that you
    • Whatsapp Connection Status still "Pending" after migration

      Hello, I migrated my WhatsApp API to Zoho from another provider a day ago. So far the connection status is still “Pending”. There is a problem? How long does it usually take?
    • Zoho Books Items Categorisation/Grouping/Folder

      Is there a way to do items categorisation? a folder structure? Product Type A - Option 1/2/3 Product Type B - Option 1/2/3 Current problem : I have more than 50 items on the list, its hard for team to navigate.
    • Desk DMARC forwarding failure for some senders

      I am not receiving important emails into Desk, because of DMARC errors. Here's what's happening: 1. email is sent from customer e.g. john@doe.com, to my email address, e.g info@acme.com 2. email is delivered successfully to info@acme.com (a shared inbox
    • Ticket layout based on field or contact

      Hi! I want to support the following use-case: we are delivering custom IT solutions to different accounts we have, thus our ticket layouts, fields and languages (priority, status field values should be Hungarian) will be different. How should I setup
    • No funcionan correctamente el calculo de las horas laborales para informe de tickets

      Hola, estoy intentando sacar estadísticas de tiempo de primera respuesta y resolución en horario laboral de mis tickets, pero el calculo de horas en horario laboral no funciona correctamente cree los horarios con los feriados : Ajusté los acuerdos de
    • Sharing URLs and direct access

      Hello, I am storing my team's email signature images on Workdrive. I am creating a public image download share and adding “?directDownload=true” so that the image can be accessed without the Workdrive interface. A few questions: 1) Can we generate friendly
    • Ability to Set a Unified Tab Order/View for All Users in Zoho Projects

      Hello Zoho Projects Team, We hope you are doing well. We would like to submit a feature request regarding tab/menu organization in Zoho Projects. Current Behavior: The tab (module) order in Zoho Projects is user-specific. Each user (internal or external)
    • Zoho Mail Android app update: Set out of office response exclusively for organization members and external users, response interval

      Hello everyone! We have now introduced an option to configure out of office messages exclusively for organization members and external users within the Zoho Mail app. Additionally, now you can also customize response intervals for the Out of office messages.
    • Global Search placement in the new UI

      Having a hard time with the global search placement in the UI redesign. Surely I can't be the only one. Previously global search placement was perfect. A bar at the top/center of the page. Exactly where you would expect it to be. Since the new UI has
    • Cliq iOS can't see shared screen

      Hello, I had this morning a video call with a colleague. She is using Cliq Desktop MacOS and wanted to share her screen with me. I'm on iPad. I noticed, while she shared her screen, I could only see her video, but not the shared screen... Does Cliq iOS is able to display shared screen, or is it somewhere else to be found ? Regards
    • Feature Request: Detailed View - Related Block Links!

      Desperately need a view record link option on records displaying in the related blocks on a Detail View. For the love of god, please add this feature. Thank you!
    • Seamless Round-Trip Navigation for Related Blocks (Detail View)

      As highlighted previously in this post (and here, here, here, and here), we still lack a fundamental capability for seamless navigation in Related Blocks. The popup that appears when adding a related record doesn't exist for viewing/editing existing records,
    • Sub-Form Padding in CSV Export

      Hi, When you use the Sub-Form, and for example you have a Date Field on the Main Page, then Option 1 and Option 2 fields on the Subform, when you export this to CSV the Date column will only have the Date in 1 row, the first row, it would be nice to pad
    • Dependent / Dynamic DropDown in ZohoSheets

      Has anyone figured out a way to create a Dropdown, the values of which is dependent on Values entered in the other cell ?
    • How do I change the order of fields in the new Task screen?

      I have gone into the Task module layout, and moving the fields around does not seem to move them in the Create Task screen. Screenshot below. I have a field (Description) that we want to use frequently, but it is inconveniently placed within the More
    • Zoho → ShipStation Integration – Sales Order–Driven Fulfilment Workflow

      Hello All, I’m reaching out to explore the best way to integrate a shipping tool into our inventory which will speed our process up. We are looking to integrate ShipStation into our existing order-to-fulfilment workflow, as we’re keen to standardise on
    • IA ou je peux trouver comment utiliser IA

      Je voudrais utiliser IA dans l'interface zoho pour m'aider quand j'ai des questions de rôle partage ou autre configuration d'automatisation, j'utiliser ChatGPT externe mais il ne connait pas toujours l'interface zoho et les réponses sont parfois longue
    • Zoho One account closure vs deactivation

      I wonder what are the best practices and guidelines around deactivating vs deleting Zoho accounts in organisations? Any practical considerations?
    • Data Processing Basis

      Hi, Is there a way to automate the data processing for a candidate every time an application arrives from job boards, without requiring manual intervention? That is, to automatically acquire consent for data processing. I've seen a workflow that allows
    • Disable Zoho Inventory Tracking / Delink Zoho Books & Inventory

      We have integrated zoho inventory with zoho books? Now after a long time, we want to disable inventory tracking and delink these 2 modules. Zoho says we cant do it. Anybody else going thru the same ? Any possibility at all? Why does zoho not allow to
    • UPLOAD A CREATED PDF AUTOMATICALLY

      Using the html header pdf+print button, I have managed to find a way to have a user create a pdf using entered form data. Using the schedule button, I can have a "file uploaded" pdf mailed to someone as an attachment. The missing piece is to be able to add the pdf, created in that html page to a file upload field automatically? Right now one has to save it to computer and then upload it in a FILE UPLOAD FIELD. Any help would appreciated !  
    • How create a draft via workflow?

      I wish to create a workflow rule for specific emails that creates a draft response - not an automatic email reply, but just a draft with a set response ready to be verified by an agent who can then manually select recipients. Alternatively, the workflow
    • Zoho vault instal on windows

      I am trying to use Zoho Vault Desktop for Windows, but I am unable to complete the sign-in process. Problem description After logging in to my Zoho account and clicking Accept on the authorization page, nothing happens. The application does not proceed
    • Zoho CRM for Everyone's NextGen UI Gets an Upgrade

      Hello Everyone We've made improvements to Zoho CRM for Everyone's Nextgen UI. These changes are the result of valuable feedback from you where we’ve focused on improving usability, providing wider screen space, and making navigation smoother so everything
    • ZOHO GLITCHES

      Ok, you guys have done a great job at building a platform that has the potential to surmount the competition but these glitches are becoming more than frustrating! This is beyond annoying, I'm trying draft lawsuits and type up privacy and refund policies
    • Next Page