Kaizen #92 - Bulk Read in PHP SDK

Kaizen #92 - Bulk Read in PHP SDK

Heya! Welcome back to the PHP SDK fold in our Kaizen series.

In this post, we will explore how to use bulk read APIs and how to structure the criteria format for different field data types in PHP SDK based on v4 APIs. This will ease your process of handling large volumes of data in an efficient and streamlined manner. 

What does Bulk Read API do?

The Bulk Read API helps you to fetch large volumes of data that meet specific criteria in a single request. Unlike the GET Records API , which has a limitation of 200 records per call, the Bulk Read API allows you to extract bulk data, 200k records, for data synchronisation purposes. This prevents the need for you to fire multiple API calls which can easily drain your daily credits.

This Bulk Read is asynchronous, thus the result for your request will not be available immediately. So, you will have to either poll the bulk read job status API to know the status or specify a callback URL for Zoho CRM to send notifications regarding the process. 

The CRM system processes your request and returns the results in either a CSV or ICS (for Meetings/Events module) zipped file. To download your result, use the job ID given in the response of bulk read job API .

This entire process can be wrapped into three stages as given below, 
  • Creating a Bulk Read Job 
  • Checking the status of a Bulk Read Job
  • Downloading the CSV/ICS data zip

Create a Bulk Read Job

1. Adding Callback URL

To get notified of the progress and results of the bulk read job, add a callback URL to the request body using the following format. 
$requestWrapper = new RequestWrapper();

$callbackVar = new CallBack();

$callbackVar->setUrl(" your_callback_url ");

$callbackVar->setMethod(new Choice("post"));

$requestWrapper->setCallback($callbackVar);
The method for callback URL is typically set to POST as it helps the client to send the required data along with the url to handle the callback appropriately.

2. Structuring a Query

A query comprises multiple parameters such as your desired module, fields, custom view ID, page value, file-type and criteria.

A criterion is typically a filter/condition used in a query to narrow down the data to your desired set of records. Criteria can include one or more conditions and you can combine them using group operators like 'and' and 'or' to create more complex filtering logic. 

Each condition in the criteria comprises three components.
  • Field - It refers to the field API name of the record, which you want to use for filtering purpose.
  • Comparator - It determines how the value of the specified field has to be evaluated.
  • Value - It represents the value of the field against which the record has to be evaluated.
This helps you to retrieve only the relevant records, thereby optimising the performance and reducing the amount of data transferred.

To enhance the understanding of how to structure a criterion, it is necessary to address these group operators and comparators before delving into it.

Group Operators 

Group Operators are used to perform logical operations on multiple conditions within a query. They help you in grouping multiple conditions together to create complex search criteria.The possible group operators are 'and' and 'or'.
  • and - It specifies that all conditions within the group must be satisfied for a record to be included in the query result.
  • or - It specifies that any of the conditions within the group can be satisfied for a record to be included in the query result.
These operators provide flexibility in constructing queries and retrieve the desired set of records from your CRM system with ease.

Comparators

Comparators are used in a query condition to specify the type of comparison that should be performed between a field and a value. They define the relationship between the field and the value and determine how the records are filtered. Refer to this help document to find the possible comparators with their field datatypes. 

An example of each datatype is given in PHP for your better understanding. 
Data Type
Example
  Number

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field ->setAPIName("Amount");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("greater_than"));
$conditionVar->setValue(10000);

  Multi-select 

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field ->setAPIName("owner");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("in"));
$owner = ["5545974393001", "5545974393011"]
$conditionVar->setValue($owner);

  DateTime                                   

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field->setAPIName("Created_Time");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("between"));
$createdTime = [date_create("2023-05-01T17:58:47+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get())), date_create("2023-06-01T17:58:47+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get()))];
$conditionVar->setValue($createdTime);

  Boolean

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field ->setAPIName("Email_Opt_Out");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("equal"));
$conditionVar->setValue(false);

  Lookup

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field ->setAPIName("owner.last_name");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("equal"));
$conditionVar->setValue("Boyle");

Structuring Simple Criteria

Below is a query format with a simple criterion of two conditions to filter your records from the given module. 

$criteriaVar = new Criteria();

$criteriaVar->setGroupOperator(new Choice("operatorValue"));

$conditionVar1 = new Criteria();

$fieldVar = new MinifiedFields();

$fieldVar->setAPIName("Field_API_Name");

$conditionVar1->setField($fieldVar);

$conditionVar1->setComparator(new Choice("comparatorValue"));

$conditionVar1->setValue("Field_Value");

$conditionVar2 = new Criteria();

$field = new MinifiedFields();

$field->setAPIName("Field_API_Name");

$conditionVar2->setField($fieldVar);

$conditionVar2->setComparator(new Choice("comparatorValue"));

$conditionVar2->setValue("Field_Value");

$criteriaVar->setGroup([$conditionVar1,$conditionVar2]);

$query->setCriteria($criteriaVar);

$requestWrapper->setQuery($query);

In the above format, the group operator is used for two different conditions.

Following is the json format of this simple criteria.
{
    "query": {
        "criteria": {
            "group_operator": "operatorValue",
            "group": [
                {
                    "comparator": "comparatorValue",
                    "field": {
                        "api_name": "Field_API_Name"
                    },
                    "value": "Field_Value"
                },
                {
                    "comparator": "comparatorValue",
                    "field": {
                        "api_name": "Field_API_Name"
                    },
                    "value": "Field_Value"
                }
            ]
        }
    }
}

Structuring Complex Criteria

To structure a criterion with four different conditions follow the below format.

//top-level group criteria with 2 different groups comprising of 2 different conditions each

$criteria = new Criteria();

$criteria->setGroupOperator(new Choice("operatorValue"));

//group1 with 2 different conditions

$groupVar1 = new Criteria();

$groupVar1->setGroupOperator(new Choice("operatorValue"));

$conditionVar11 = new Criteria();

$field11 = new MinifiedFields();

$field11->setAPIName("Field_API_Name");

$conditionVar11->setField($field11);

$conditionVar11->setComparator(new Choice("comparatorValue"));

$conditionVar11->setValue("Value");

$conditionVar12 = new Criteria();

$field12 = new MinifiedFields();

$field12->setAPIName("Field_API_Name");

$conditionVar12->setField($field21);

$conditionVar12->setComparator(new Choice("comparatorValue"));

$conditionVar12->setValue("Value");

$groupVar1->setGroup([$conditionVar11, $conditionVar12]);

//group2 with 2 different conditions

$groupVar2 = new Criteria();

$groupVar2->setGroupOperator(new Choice("operatorValue"));

$conditionVar21 = new Criteria();

$field21 = new MinifiedFields();

$field21->setAPIName("Field_API_Name");

$conditionVar21->setField($field21);

$conditionVar21->setComparator(new Choice("comparatorValue"));

$conditionVar21->setValue("Value");

$conditionVar22 = new Criteria();

$field22 = new MinifiedFields();

$field22->setAPIName("Field_API_Name");

$conditionVar22->setField($field22);

$conditionVar22->setComparator(new Choice("comparatorValue"));

$conditionVar22->setValue("Value");

$groupVar2->setGroup([$conditionVar21, $conditionVar22]);

//pushing the groups to the top-level group criteria

$criteria->setGroup([$groupVar1, $groupVar2]);

In the above format, two group variables ($groupVar1 and $groupVar2) are created, each representing a nested group of conditions. Both the groups are further assigned to the top-level group variable ($criteria). 

The json arrangement of the above format is given for your clarity.
{
    "query": {
        "criteria": {
            "group_operator": "operatorValue",
            "group": [
                {
                    "group_operator": "operatorValue",
                    "group": [
                        {
                            "comparator": "comparatorValue",
                            "field": {
                                "api_name": "Field_API_Name"
                            },
                            "value": "Field_Value"
                        },
                        {
                            "comparator": "comparatorValue",
                            "field": {
                                "api_name": "Field_API_Name"
                            },
                            "value": "Field_Value"
                        }
                    ]
                },
                {
                    "group_operator": "operatorValue",
                    "group": [
                        {
                            "comparator": "comparatorValue",
                            "field": {
                                "api_name": "Field_API_Name"
                            },
                            "value": "Field_Value"
                        },
                        {
                            "comparator": "comparatorValue",
                            "field": {
                                "api_name": "Field_API_Name"
                            },
                            "value": "Field_Value"
                        }
                    ]
                }
            ]
        }
     }
}

The default file type is CSV. To bulk read the Events module always prefer the ICS file type. Refer to this resource to fetch the custom view IDs, module and field API names. 

Below is a sample code for creating a bulk read job with compound criteria. The criteria follow this arrangement ((1 and 2) or (3 or 4)) of conditions.

<?php

use com\zoho\crm\api\bulkread\BulkReadOperations;
use com\zoho\crm\api\bulkread\CallBack;
use com\zoho\crm\api\util\Choice;
use com\zoho\crm\api\bulkread\Query;
use com\zoho\crm\api\bulkread\Criteria;
use com\zoho\crm\api\bulkread\RequestWrapper;
use com\zoho\crm\api\modules\MinifiedModule;
use com\zoho\crm\api\fields\MinifiedFields;
require_once "vendor/autoload.php";

class CreateBulkReadJob
{
public static function initialize()
    {
        // Add initialisation code
        // Refer to this article for more help
    }
    public static function createBulkReadJob(string $moduleAPIName)
    {
        $bulkReadOperations = new BulkReadOperations();
        $requestWrapper = new RequestWrapper();
        $callback = new CallBack();
        $callback->setUrl("https://www.callback.com/example");
        $callback->setMethod(new Choice("post"));
        $requestWrapper->setCallback($callback);

        //query
        $query = new Query();
        $module = new MinifiedModule();
        $module->setAPIName($moduleAPIName);
        $query->setModule($module);
        $query->setCvid("34770610087501");
        $query->setFields(["Last_Name"]);
        $query->setPage(1);

        //top-level group criteria with 2 different groups comprising of 2 different conditions each
        $criteria = new Criteria();
        $criteria->setGroupOperator(new Choice("or"));
        $criteriaList = array();

        //group1 with 2 different conditions
        $groupVar1 = new Criteria();
        $groupVar1->setGroupOperator(new Choice("and"));

        $conditionVar11 = new Criteria();
        $field11= new MinifiedFields();
        $field11->setAPIName("Last_Name");
        $conditionVar11->setField($field11);
        $conditionVar11->setComparator(new Choice("equal"));
        $conditionVar11->setValue("Boyle");
        
        $conditionVar12 = new Criteria();
        $field12 = new MinifiedFields();
        $field->setAPIName("Owner");
        $conditionVar12->setField($field12);
        $conditionVar12->setComparator(new Choice("in"));
        $owner = array("5545974000000393001","5545974000000393011");
        $conditionVar12->setValue($owner);
        $groupVar1->setGroup([$conditionVar11, $conditionVar12]);

         //group2 with 2 different conditions
        $groupVar2 = new Criteria();
        $groupVar2->setGroupOperator(new Choice("or"));

        $conditionVar21 = new Criteria();
        $field21 = new MinifiedFields();
        $field21->setAPIName("Company");
        $conditionVar21->setField($field21);
        $conditionVar21->setComparator(new Choice("equal"));
        $conditionVar21->setValue("Morlong Associates");
        
        $conditionVar22 = new Criteria();
        $field22= new MinifiedFields();
        $field22->setAPIName("Created_Time");
        $conditionVar22->setField($field22);
        $conditionVar22->setComparator(new Choice("between"));
        $createdTime = array(date_create("2023-04-15T17:58:47+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get())), date_create("2023-06-01T17:58:47+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get())));
        $conditionVar22->setValue($createdTime);
        $groupVar2->setGroup([$conditionVar21, $conditionVar22]);

         //pushing the groups to the top-level group criteria
        $criteria->setGroup($criteriaList);
        $query->setCriteria($criteria);
        $requestWrapper->setQuery($query);
        // $requestWrapper->setFileType(new Choice("ics")); for Events module
        $response = $bulkReadOperations->createBulkReadJob($requestWrapper);
        //Add your code to handle the response received in $response
        // For more details, refer here.
    }
}
CreateBulkReadJob::initialize();
$moduleAPIName = "Leads";
CreateBulkReadJob::createBulkReadJob($moduleAPIName);
?>

2. Status of a Bulk Read Job

To keep track of the status of your bulk read job, use the id provided in the details section of your bulk read job response. 

Here is a sample code for checking the status of a bulk read job.

<?php

use com\zoho\crm\api\bulkread\BulkReadOperations;

require_once "vendor/autoload.php";

class GetBulkReadJobDetails
{
public static function initialize()        
    {
        // Add initialisation code
        // Refer to this article for more help 
    }

    public static function getBulkReadJobDetails(string $jobId)
    {
        $bulkReadOperations = new BulkReadOperations();
        $response = $bulkReadOperations->getBulkReadJobDetails($jobId);
        //Add your code to handle the response received in $response
        // For more details, refer here.
    }
}
GetBulkReadJobDetails::initialize();
$jobId = "55459743108003";
GetBulkReadJobDetails::getBulkReadJobDetails($jobId);
?>

3. Download Bulk Read Result

To download your bulk read job result, use the job id mentioned in the bulk read job response. Additionally, provide the path of the destination folder where you would like to download the result. The result will be downloaded as a zip file containing CSV/ICS files.
Here is a sample code for downloading a bulk read job result.

<?php

namespace samples\bulkread;

use com\zoho\crm\api\bulkread\BulkReadOperations;

require_once "vendor/autoload.php";

class DownloadResult
{
public static function initialize()
    {
        // Add initialisation code
        // Refer to this article for more help  
    }
    public static function downloadResult(string $jobId, string $destinationFolder)
    {
        $bulkReadOperations = new BulkReadOperations();
        $response = $bulkReadOperations->downloadResult($jobId);
        $streamWrapper = $response->getObject()->getFile();
        fputs(fopen($destinationFolder . "/" . $streamWrapper->getName(), "w"), $streamWrapper->getStream());
        //Add your code to handle the response received in $response
        // For more details, refer here.
    }
}
DownloadResult::initialize();
$jobId = "55459743108003";
$destinationFolder = "/Downloads";
DownloadResult::downloadResult($jobId, $destinationFolder);
?>

We hope you found this post useful and engaging! 

If you have any queries, feel free to drop them in the comments section below or reach out to us directly at support@zohocrm.com. We value your thoughts and eagerly look forward to hearing from you.

Stay tuned for more enriching posts coming your way soon!

Cheers!

    • Recent Topics

    • Improve History Feature in Zoho Inventory

      At present there is a "history" tab on Zoho Inventory Items, however this only shows a date and time stamp along with the users name. It doesn't say what was changed. What is the value of this if you can't see what was changed? My Ideal is to include
    • Show backordered items on packing slip

      We send out a lot of large orders, and often there are one or two things backordered. How can I fix the packing slips to show quantity ordered  & quantity packed There should also be the ability to "ship" 0 of an item so the receiver knows that things
    • Document | Files

      The vendor "Partial matches" still not fixed here after years of putting up with having to select most vendors manually ! ( again, the banking "Transaction rules" would solve a lot of these issues ) Some unwanted, irrelevant pdf's also arrive. It would
    • books+POS+ tap to pay+ stripe

      So in the UK we now have tap to pay with stripe. So we can use the stripe app as a POS terminal. Brilliant news. Can we hope that the Books App might add this feature ASAP. It would be great to have one system rather than using the not very good Square
    • Canvas Form View - Client Script Page on load - Url params not working

      We have a custom module with a canvas page for form view. We have a button in Customers module to open this canvas page using invokeurl function. We send few parameters as in the URL as query parameters. https://crm.zoho.in/crm/orgxxxxxxxx/tab/CustomModule12/create/canvas/64333200000261xxxx?layoutId=643332000002605001&c=${Customers.Customer
    • Sending Recruit SMS's to Zoho Cliq - Or tracking in the Messages module in Recruit?

      Is there any way to send SMS Gateway messages in Recruit to ZOho Cliq? We use 2-way SMS massages a lot in Zoho Recruit to speed up communication with Candidates. However the only way to keep track of received SMS's is by keeping a look out for the Email
    • This mobile number has been marked spam. Please contact support.

      Hi Support, Can you tell me why number was marked as spam. I have having difficult to add my number as you keep requesting i must use it. My number is +63....163 Or is Zoho company excluding Philippines from their services?
    • Zohomail does not support additional fields in mailto links

      Hello, I set up Zohomail as default composer in Firefox according to manual here: https://www.zoho.com/mail/help/defaultcomposer.html#alink2 Later, I wanted to use this functionality to answer in a Linux mailing list thread using mailto link: mailto:xxxxx@kernel.org?In-Reply-To=%3C727o0521-q24p-s0qq-66n0-sn436rpqqr1p@example.com%3E&amp;Cc=xxxxx%example.org&amp;Subject=Re%3A%20%5BPATCH%20v2%28%29
    • Is it possible to set a customer context variable in Zobot

      Hi, I want to use a context variable to route users down different paths in my Zobot chat flow. I know I can do this when the user enters data. But I want to know if I can use a variable that is 'hard coded' on the card, that the user is unaware of. Use
    • Cannot change Blog Title

      There is nowhere to change the blog title. You can change the blog URL but that is making no difference to the text "Enter Your Post Title" am I missing something?
    • Kaizen #203 - Answering Your Questions | Handling API Limits and Error Responses

      Hi Everyone, Welcome back to yet another post in the Kaizen Series! We appreciate your keen participation in the 200th milestone celebration of the Kaizen series. We will continue to answer the queries we received through the feedback. When working with
    • How to verify website ownership with google search console

      Hi, I am having a free .in domain provided by Zoho I have created a website on it now I want to verify my ownership to google webmaster. Can you please help me how to do that.
    • Kaizen #89 - Color Coding using Client Script

      Hello everyone! Welcome back to another exciting Kaizen post. Today let us see how you can apply color codes to the List and Detail Pages of Zoho CRM using Client Script. Need for color code in Zoho CRM When you mark things with different colors as a
    • "SPF record exceed the allowed limit of 10"

      Hi, I was wondering if there were a "universal Zoho SPF record" that would allow all my configured Zoho services that email things to meet this limitation ? or do I have to have an entry for mail, com, billing, etc?
    • Zoho Mail android app update: Block & reject future emails, Report phishing, Spam alerts, Suspicious URL detection

      Hello everyone! In the most recent Zoho Mail Android app update, we have brought in support for the following features: Block & reject future emails Report Phishing Spam alerts in the mail details screen. Suspicious URL detection. Block & reject future
    • Animated GIF Images in Chat

      I know this seems to be a small feature request but in a recent Cliq update Zoho disabled autoplay for animated GIFs posted in Cliq conversations. We think this was not a good change. In our organization, animated GIFs in a chat play a role in expressing
    • I can't seem to login in to Mail Apps of MacOS /IOS

      Hi, i'm having trouble in signing in to mail apps from IOS. It's always come back to wrong passwords. But i already changed my password like 3 times. But still it says wrong credentials
    • Profile Image Showing Incorrectly in Zoho Mail

      Hi everyone, I’m facing a serious issue with Zoho Mail. The profile image showing for my email address is incorrect — it’s not my image. When I send an email to my Gmail account, it displays someone else’s image. This looks very suspicious and can make
    • I need access to my old email

      I need access to my old email bromzeman@zoho.com to verify it for forwarding. I can’t access the inbox to get the confirmation code. Please assist with recovery or forwarding. as you might already know, they made alot of the email addresses to have that
    • Set Defaults for Email Groups

      Is there a way to set defaults for all of the groups that I establish as a moderator? For example, I want every group I establish to have the following settings: 1. Moderator is <user> 2. User is <user>, <user> 3. Notifications for new group turned
    • LOGS FOR RECEIVED MAIL ( READ DATE & TIME)

      In Zoho mail we can extract the read logs of received mails so that we can see when we have read the mail and at what time & we have read it.
    • Domain verification probem

      Hello, i use a domain from Namecheap with hosting from Cinfu when i try to verify my domain on zoho i get "TXT Verification failure" i even tried the HTML verification and the code appears but also giving me the verification failure error.
    • Switching to Cloudflare email routing from Zoho Mail

      Hello, I'm currently working on migrating from Zoho Mail to Cloudflare's email routing solution. This requires changing MX and TXT records for our custom domain - when we do this, will our users still be able to log into their accounts and access an archived
    • Un Subscription Button

      How can i Add the Un Subscription Button in Zoho mail
    • Documents unable view and need to downlad

      I can't view .doc files in Zoho mail unless I download them, but I can view PDF files without downloading.
    • we encountered a problem while sending your email. please try again later.

    • Adding and removing people from groups

      We're having problems adding people to a group. Apparently Zoho has one email address and will not recognize a different email address.
    • MAIL SEARCH IS NOT WORKING

      THIS ISSUE HAS BEEN BUGGING ME SINCE MORNING, PLEASE RESOLVE THIS AT THE EARLIEST
    • URL Parameter on Help Center SIgn in link

      Is it possible to add a url parameter to the sign in link on the Help Center?
    • migrating from HelpScout

      I am attempting to import a conversation file from helpscout into desk and am receiving size errors. What is the current file size restriction. Does anyone have any tips for a successful migration?
    • Layout Rules Don't Apply To Blueprints

      Hi Zoho the conditional layout rules for fields and making fields required don't work well with with Blueprints if those same fields are called DURING a Blueprint. Example. I have field A that is used in layout rule. If value of field A is "1" it is supposed to show and make required field B. If the value to field A is "2" it is supposed to show and make required field C. Now I have a Blueprint that says when last stage moves to "Closed," during the transition, the agent must fill out field A. Now
    • Article Name Sorting in Zoho Desk Knowledge Base (agent / admin side)

      Dear Zoho Desk Support, We are writing to request an enhancement to the Knowledge Base management feature within Zoho Desk. Currently, there is no option to sort articles by their name, which significantly hinders efficient article management, especially
    • How to parse JSON data with SQL in Zoho Analytics?

      Hi all, I have a column with JSON data. I want to show this column in a chart, but it is very messy, and no JSON parsing function is supported on Zoho Analytics. data example: {"id": 5, "status": "false", "date": "15/10/22"} what I want to do in SQL is
    • Ability to turn off "Would you like this amount to be reflected in the Payment field?" message

      Team, Is there any way to turn off the message" Would you like this amount to be reflected in the Payment field?" when I make a payment? This is so annoying. This happens EVERY TIME I put an amount in the Payment Made field.
    • Add an Equation Field (Or update the Formula Field)

      Hi, I would like to be able to have one field as a Text Field with QR Code, and then have multiple Equation/Formula Fields that then take parts of that fields data with LEFT, MID, RIGHT, REGEX, etc. Thanks Dan
    • How to parse column having JSON data using SQL?

      We have a daily sync from a PostgreSQL database that brings data into Zoho Analytics. Some of the columns store raw JSON data. We need to build SQL queries on top to parse data from JSON and store them in discrete columns. There is no option for "Data
    • Enable report button based on the current user role

      Greetings  i have a report that contains action buttons, i want these buttons to appear as enabled only when the current logged in user has a certain role, for example only CEO role users will be able to use this button. but when setting the conditions
    • 500 Internal Error In Mail API

      I'm getting 500 Internal Error when using mail API. I'm getting this error for this one account, it works fine for other Account IDs which I have in my system.
    • Piss poor service in Support in Domains and email

      Srijith Narayanan B contacted me today. Very pleasant fellow. Just didn't want to tell him how bad your support service is. You help the person, but you leave before we can finish the next stage. Which causes a lot of frustration. It's been 8 days now
    • Zoho live chat widget in React Js

      I am trying to test Zoho live chat widget code in react js, below is the sample code void(0)} onClick={()=>window.$zoho.salesiq.floatwindow.visible("show")}>LIVE CHAT window.$zoho = window.$zoho || {};window.$zoho.salesiq = window.$zoho.salesiq
    • Next Page