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 #198: Using Client Script for Custom Validation in Blueprint

        Nearing 200th Kaizen Post – 1 More to the Big Two-Oh-Oh! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
      • Kaizen #226: Using ZRC in Client Script

        Hello everyone! Welcome to another week of Kaizen. In today's post, lets see what is ZRC (Zoho Request Client) and how we can use ZRC methods in Client Script to get inputs from a Salesperson and update the Lead status with a single button click. In this
      • 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

        • Recent Topics

        • Is there a way to sync Tags between CRM and Campaigns/Marketing Hub?

          I wonder if there is a way to synch the tags between CRM and Marketing-Hub / Campaigns?
        • The 3.1 biggest problems with Kiosk right now

          I can see a lot of promise in Kiosk, but it currently has limited functionality that makes it a bit of an ugly duckling. It's great at some things, but woeful at others, meaning people must rely on multiple tools within CRM for their business processes.
        • Does anyone else wish you could download Mail Merge quotations from the Zoho CRM mobile app?

          Is it just me, or has anyone else run into this? I’m in sales, so I’m rarely at my desk. I’m usually in meetings, visiting clients, or travelling. One thing that genuinely frustrates me is that if a client asks me for a quotation, I can’t generate or
        • Assign account to a ticket created with WebToCase

          We use Zoho Desk. Our large client uses WebToCase form to submit tickets. I have two workflow rules: When a contact is created and its email ends with example.com, it runs a custom function, which assigns the new contact the right account Example with
        • How to track the source of form submissions using referrer names in Zoho Forms?

          Ever wondered where your users are accessing your form links from? By tracking the origin of your form entries—whether it's from social media, email campaigns, direct links, or embedded on your website—you can identify which channels are driving the most
        • Zoho One Backup of entire account

          Hello, When using Zoho one is there a way to backup your entire account of all apps that you are using \ activively using in a single step or do you have to backup each applications data individually? Thanks,
        • Custom invoice template issue

          Hi. I created a custom invoice template, but it isn't working properly. Even though I select my custom template, Zoho still opens the standard one while showing that the custom one is selected. Please advise on how to fix this
        • Can't view nor download attachments

          Me and a number of people I know suddenly stopped being able to either view nor download attachments that arrive in new emails we receive since this morning. Older emails work just fine and we can download/view them. Zoho Mail states the it wasn't able
        • Zoho CRM APIs

          Hello, I think as a developer, it is very important to have the ability to manage, develop, and execute functions directly from my local development environment (for example, VS Code). Zoho CRM should have a way to create, deploy, and manage functions
        • Record Payment - Auto Populate Amount as payments are selected

          When recording payments you have the option of clicking on "Pay in Full" next to the bill which automatically adds the total at the bottom of the page next to "Amount used for payments" but this should also auto populate / update the total at the top
        • Zoho Projects - Add Event Change as Trigger

          I am currently trying to create an automation in Zoho Flow that sends a notification when an Event is updated in Zoho Projects. At present, Zoho Projects only provides a trigger for Event creation. There is no trigger available when an existing Event
        • Tips & Tricks #4: Zoho People - Mejoras y Novedades durante el Q2 de 2026

          ¡Hola, Comunidad de Zoho en Español! Os traemos una selección de las novedades y mejoras más interesantes que llegaron a Zoho People durante el segundo trimestre de 2026. En este artículo te hablamos de: Zia, el asistente de IA para RR. HH. OKR llega
        • You do not have sufficient permissions to perform this operation. Contact your administrator.

          When I attempt to log a call I initiate the +New Call and Start Calling and I click Answered Call in the popup dialog box that follows. Any attempt to save or close this dialog box results in "You do not have sufficient permissions to perform this operation. Contact your administrator." The only way I can get the popup to disappear is to refresh the page and it will go away. I have found others reporting this issue when they attempt to run reports.  Any suggestions? Thank you in advance for taking
        • More flexibility on Hosted Pages ?

          I like more flexibility on Hosted Pages, this is due to the fact I am not a programmer I wold like to have more customization on Hosted Pages like: - add Addons and coupon to a plan already suscribed in the past - cutomize the look an feel (as a form
        • Marketer's Space: Write CTAs your audience can't ignore

          Hello Marketers! Welcome back to Marketer's Space! Today we're zeroing in on a small concept that decides whether your whole campaign was worth sending: the call-to-action (CTA). You could write the sharpest subject line and design the most polished template
        • Button to renew offline subscription.

          If i have a customer who pays offline, and wants to renew the subscription, you have to wait till the end of the subscription and reactivate it. or else it affects metrics. There is a way to upgrade or downgrade a subscription, immedeatly or at the end
        • multiple Brands separate topic landing pages

          hii, i cant seem to figure out how to separate brands from the select topics marketing landingpage. i can only add topics for other brands, but i want to keep them complete separate
        • Public Forms for an all-inclusive feedback system

          The more we seek information from the customers, the more we solve their needs and gain their trust. However, reaching out to every customer to seek requirements, solve their issues, and gather feedback can be tasking. Circulating a public form helps
        • How to embed event list page from Backstage onto my site

          I'd like to embed the events list page from Zoho Backstage ( https://biz2bizlinksevents.zohobackstage.com/events) into my site, but when I use an iframe it says the page refused to connect. My other iframes with microsites from Zoho recruit and forms
        • Function #40: Notify users when invoices exceed the credit limit

          Hello everyone, and welcome back to our series! Businesses tend to offer goods or services on credit to customers, which can, in overtime, lead to the accumulation of significant overdue balances. To address this, Zoho Books allows you to define a Credit
        • Zoho CRM - Kiosk Studio: Build Once, Execute Multiple Times with Loops

          Hello Everyone, Introducing Loop Functionality in Kiosk Studio. If you've ever built a Kiosk that needed to perform the same action multiple times like updating a list of contacts, scheduling calls for a batch of leads, or processing multiple products
        • Manual Journal not affecting the YE Trial Balance

          I have done a manual journal moving an expense from prior year to current year. However, it is not affecting the prior year figures at all, when I go to the expense the journal isn't even reflecting at all. I have made sure dates are correct and both
        • Tip #82 – Let Zia Answer Bot Handle the Questions So You Can Focus on the Fix – 'Insider Insights'

          Tip #82 – Let Zia Answer Bot Handle the Questions So You Can Focus on the Fix – 'Insider Insights' Hello Zoho Assist Community! Imagine you're in the middle of a critical remote session. The customer, a project manager at a mid-sized firm, has been locked
        • Caso de Éxito: Namencis Education crece un 117% con Zoho One

          "Hemos estado creciendo en torno a un 117% al año, que es una barbaridad. Tuvimos una rentabilidad del 33%, que antes no teníamos ni por asomo. Escalamos en tres años lo que no habíamos escalado en los anteriores siete." Borja Domínguez, CTO de Namencis
        • Introducing Workqueue: your all-in-one view to manage daily work

          Hello all, We’re excited to introduce a major productivity boost to your CRM experience: Workqueue, a dynamic, all-in-one workspace that brings every important sales activity, approval, and follow-up right to your fingertips. What is Workqueue? Sales
        • [IDEA] Bring Layout - Conditional Rules and Client Scripts to Zoho Books

          The problem We run Zoho Books with two e-invoicing integrations: myData (Greek tax authority, AADE) and PEPPOL (EU e-invoicing). Between the two, our Invoice form carries a large number of custom fields — document type codes, VAT exemption categories,
        • Introducing the Revamped Zoho Projects Chrome Extension

          Zoho Projects Chrome Extension brings your project management capabilities directly to your browser. Users can access all their portals, create tasks, file issues, log time, and stay updated on project activities without navigating to the main application.
        • Bigin Android app update: Alerts while creating tasks outside of working days, conflicting events and calls.

          Hello everyone! In the most recent version of the Bigin Android app, we have brought in support to display an alert if task is being scheduled outside of the working days. Also, when scheduling an event or call in the Activities module, a conflict alert
        • Create modules using natural language prompts

          Hello all, We’ve introduced a new enhancement to Zia that allows you to create custom and team modules in Zoho CRM using plain language prompts. Why this enhancement? Creating a custom module traditionally involves multiple steps—choosing field types,
        • 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.
        • Can the SEO Keyword field be increased from 100 characters to the industry standard 160 characters

          Hello, Currently Commerce restricts the SEO meta-keywords to 100 characters, which I'd always found to be a bit constraining, often times not enough space to suit my needs. I recently discovered however that search engines will accept up to 160 characters
        • Cookies Consent Management in Webforms

          Hello Everyone! We are excited to introduce Cookie Consent Management for webforms. Read on to learn more. Webforms are online forms embedded on websites that allow users to submit data and create records in Zoho CRM. These forms utilize cookies to track
        • Trigger workflows from SLA escalations in Zoho Desk?

          Hey everyone, I’m currently working with SLA escalation rules in Zoho Desk and ran into a limitation that I’m hoping someone here has solved more elegantly. As far as I can tell, SLA escalations only support fairly limited actions (like changing the ticket
        • Como exportar la base a excel sin perder datos

          Estimados quisiera saber como exportar o descargar la base de tickets para hacer estadisticas sin perder datos al copiar
        • Show my cost or profit while creating estimate

          Hi, While creating estimate it becomes very important to know exact profit or purchased price of the products at one side just for our reference so we can decide whether we can offer better disc or not .
        • Mise à jour de Zoho Books – France

          Chers clients, Merci pour votre patience et votre soutien continu. Avec les évolutions réglementaires à venir en France nous introduisons de nouvelles fonctionnalités dans Zoho Books pour les clients français. Ces mises à jour ont été conçues pour répondre
        • Is there any way to have Dataprep ingest RSS?

          As stated by the title. Does the Zoho environment offer tools that I can use to, directly or using workarounds, have Dataprep ingest an RSS feed? Thanks
        • Connect ZOHO social with Google Data Studio and download data from ZOHO social

          Dear ZOHO team, I am writing this message to enquire about how to connect ZOHO social with Google data studio since our company would like to use Google data studio to generate reports. Is it a way to download data from ZOHO social? Best regards, Chris
        • Zoho People Whats New - Q2 2026

          Hello Users! We're excited to share the latest updates introduced in Zoho People during Q2 2026. This release brings a range of new features and enhancements designed to simplify HR operations, automate routine processes, and deliver a smarter, more connected
        • Manage booking pages from your Android phone

          Hello everyone! We are happy to announce that users can now add and manage booking pages from their Bigin Android app. It is a multi-step form that users can create for purposes like booking appointments, scheduling calls or meetings, conducting webinars,
        • Next Page