Kaizen #85 - PHP SDK [Part II]

Kaizen #85 - PHP SDK [Part II]

Hello everyone! Welcome to another week of Kaizen!

In last week's post, we discussed in detail the configuration and initialization steps for PHP SDK. We will take you through sample codes for Record Operations this week, to help you get started with your SDK journey.

1. Custom Fields, Lookup Fields, Picklist Fields

1.1 Custom Fields

To set/update a value for a custom field during a record create/update, use addKeyValue method. This method takes two arguments - the field API name and the value.  
 $variable->addKeyValue("your_custom_field_api_name", "custom_field_value");
  1.  $record->addKeyValue("Designation", "Manager");

1.2 Picklist Fields

To set/update a value for a default picklist field like 'Lead Source' in Leads module, use addFieldValue method in the following format.
 $variable->addFieldValue(ModuleAPIName::FieldName(), new Choice("picklist_value"));
  1. $record->addFieldValue(Contacts::LeadSource(), new Choice("Advertisement"));
Specify your option for the picklist field when you create the Choice class instance. In this example, the LeadsSoure picklist field in Contacts will be updated with the value Advertisement if it is a option for the picklist. If an invalid value is specified, the SDK will throw an UNACCEPTED VALUES ERROR.

For user defined Picklist fields, use the addKeyValue method in the following format.
 $variable->addKeyValue("custom_picklist_field_api_name", new Choice("picklist_choice"));
  1. $record->addKeyValue("Pick_List_2", new Choice("Option 1"));

1.3 Lookup Fields

To set/update a value for a default Lookup field during a record create/update, use addFieldValue method in the following format.
 $lookupVariable = new Record();
 $lookupVariable->addKeyValue("id", "lookup_record_id");
 $recordVariable->addFieldValue(LookupModule::FieldName(), $lookupVariable);

  1. $lookup = new Record();
  2. $lookup->addKeyValue("id", "554597402674230");
  3. $record->addFieldValue(Contacts::AccountName(), $lookup);
For custom Lookup fields, use the addKeyValue method in the following format.
 $lookupVariable = new Record();
 $lookupVariable->addKeyValue("id", "lookup_record_id");
 $recordVariable->addKeyValue("Lookup_Field_API_Name", $lookupVariable);
  1. $lookup = new Record();
  2. $lookup->addKeyValue("id", "55459742674230");
  3. $record->addKeyValue("Lookup_1", $lookup);
For Owner Lookup fields, use the addFieldValue method in the following format.
 $ownerVariable = new User();
 $ownerVariable->setEmail("name@domain.com");
 $recordVariable->addKeyValue("Owner_Field_API_Name", $recordVariable);
  1. $recordOwner = new User();
  2. $recordOwner->setEmail("patricia.boyle@zylker.com");
  3. $record->addKeyValue("Owner", $recordOwner);
Sample Code for creating a new record in Contacts module with the above field types.

<?php
use com\zoho\crm\api\HeaderMap;
use com\zoho\crm\api\record\BodyWrapper;
use com\zoho\crm\api\record\RecordOperations;
use com\zoho\crm\api\record\Contacts;
use com\zoho\crm\api\util\Choice;
use com\zoho\crm\api\users\User;
use com\zoho\crm\api\record\Record;
require_once "vendor/autoload.php";

class CreateRecords {
    public static function initialize() {
        // add initialisation code
        // refer to the previous post for details and examples 
    }
   public static function createRecords1(string $moduleAPIName) {
        $recordOperations = new RecordOperations();
        $bodyWrapper = new BodyWrapper();
        $record = new Record();

        //standard field
        $record->addFieldValue(Contacts::LastName(), "Boyle");

        //custom field
        $record->addKeyValue("Designation", "Accountant");

        // custom picklist field
        $record->addKeyValue("Pick_List_2", new Choice("Option 1"));

        //custom lookup field
        $lookup = new Record();
        $lookup->addKeyValue("id", "5545974771087");
        $record->addKeyValue("Lookup_1", $lookup);

        //Standard picklist field
        $record->addFieldValue(Contacts::LeadSource(), new Choice("Advertisement"));

        //Standard lookup field
        $lookup1 = new Record();
        $lookup1->addKeyValue("id", "55459742674230");
        $record->addFieldValue(Contacts::AccountName(), $lookup1);

        //Owner lookup field
        $recordOwner = new User();
        $recordOwner->setEmail("pat.boyle@zylker.com");
        $record->addKeyValue("Owner", $recordOwner);

        $bodyWrapper->setData([$record]);

        $trigger = ["approval", "workflow", "blueprint"];
        $bodyWrapper->setTrigger($trigger);

        $headerInstance = new HeaderMap();
        $response = $recordOperations->createRecords($moduleAPIName, $bodyWrapper, $headerInstance);

        //Add code to handle the response received in $response. 
       // For more details, refer here.
    }
}
CreateRecords::initialize();
$moduleAPIName = "Contacts";
CreateRecords::createRecords1($moduleAPIName);


2. Multi-select Lookup Fields, Multi-select Picklist Fields and Multi-user Picklist Fields

2.1 Multi-select Lookup Fields

Use the following format to set or update Multi-select Lookup Fields while creating or updating a record.

 $LookupVar1 = new Record();
 $LookupVar1->addKeyValue("id", "lookup_record_id1");
 $mslookupVariable1 = new Record();
 $mslookupVariable1->addKeyValue("Field_API_Name", $LookupVar1);
 $LookupVar2 = new Record();
 $LookupVar2->addKeyValue("id", "lookup_record_id2");
 $mslookupVariable2 = new Record();
 $mslookupVariable2->addKeyValue("Field_API_Name", $LookupVar2);
 $record->addKeyValue("Field_API_Name", [$mslookupVariable1, $mslookupVariable2]);

2.2 Multi-select Picklist Fields

Use the following format to set or update Multi-select Picklist Fields while creating or updating a record.

 $variable->addKeyValue("Picklist_Field_API_Name", [new Choice("Picklist_Value1"), new Choice("Picklist_Value2")]);

2.3 Custom Multi-user Picklist Fields

To set or update a custom Multi-user Picklist Field, use the following format.

 $lookupVar1 = new User();
 $lookupVar1->addKeyValue("id", "user_id1");
 $mulookupVariable1= new User();
 $mulookupVariable1->addKeyValue("Field_API_Name", $lookupVar1);
 $lookupVar2 = new User();
 $lookupVar2->addKeyValue("id", "user_id2");
 $mulookupVariable2= new User();
 $mulookupVariable2->addKeyValue("Field_API_Name", $lookupVar2);
 $record->addKeyValue("Field_API_Name", [$mulookupVariable1, $mulookupVariable2]);

Here is a sample code to create a record in Contacts module with the above field types.

<?php
use com\zoho\crm\api\HeaderMap;
use com\zoho\crm\api\record\BodyWrapper;
use com\zoho\crm\api\record\RecordOperations;
use com\zoho\crm\api\record\Contacts;
use com\zoho\crm\api\util\Choice;
use com\zoho\crm\api\users\User;
use com\zoho\crm\api\record\Record;
require_once "vendor/autoload.php";

class CreateRecords {
    public static function initialize() {
         // add initialisation code
        // refer to the previous post for details and examples 
    }

    public static function createRecords1(string $moduleAPIName) {
        $recordOperations = new RecordOperations();
        $bodyWrapper = new BodyWrapper();
        $record = new Record();

        $record->addFieldValue(Contacts::LastName(), "Boyle");

        // custom multi-picklist
        $record->addKeyValue("Event_Participation", [new Choice("Webinar"), new Choice("Trade Show")]);

        //custom multi-lookup
        $lookup1 = new Record();
        $lookup1->addKeyValue("id", "5545974471152");
        $multiSelectLookup1 = new Record();
        $multiSelectLookup1->addKeyValue("Products", $lookup1);

        $lookup2 = new Record();
        $lookup2->addKeyValue("id", "554597771087");
        $multiSelectLookup2 = new Record();
        $multiSelectLookup2->addKeyValue("Products", $lookup2);
        $record->addKeyValue("Products", [$multiSelectLookup1, $multiSelectLookup2]);

        //multi-user lookup
        $userlookup1 = new User();
        $userlookup1->addKeyValue("id", "5545974393001");
        $multiUserLookup1 = new User();
        $multiUserLookup1->addKeyValue("Sales_Reps", $userlookup1);

        $userlookup2 = new User();
        $userlookup2->addKeyValue("id", "5545974492072");
        $multiUserLookup2 = new User();
        $multiUserLookup2->addKeyValue("Sales_Reps", $userlookup2);
        $record->addKeyValue("Sales_Reps", [$multiUserLookup1, $multiUserLookup2]);
        $bodyWrapper->setData([$record]);
        $headerInstance = new HeaderMap();
        $response = $recordOperations->createRecords($moduleAPIName, $bodyWrapper, $headerInstance);
        //Add code to handle the response received in $response
        // For more details, refer here.
    }
}

CreateRecords::initialize();
$moduleAPIName = "Contacts";
CreateRecords::createRecords1($moduleAPIName);


3. Updating Related Records using External ID

For Related Records using External ID, define the external id information in the header as follows:
 $xExternal = "Module.External_ID_Field_Name,Related_Module.External_ID_Field_Name";
 $relatedRecordsOperations = new RelatedRecordsOperations($relatedListAPIName, $moduleAPIName, $xExternal);

Here is a sample code for linking the products with External_Product_ID (External ID field) PR01 and PR02 with a Lead with External_ID (External ID field) ABC123.
<?php
use com\zoho\crm\api\relatedrecords\BodyWrapper;
use com\zoho\crm\api\relatedrecords\RelatedRecordsOperations;
use com\zoho\crm\api\record\Record;
require_once "vendor/autoload.php";

class UpdateRelatedRecordsUsingExternalId {
    public static function initialize() {
         // add initialisation code
        // refer to the previous post for details and examples 
    }

    public static function updateRelatedRecordsUsingExternalId1(string $moduleAPIName, string $externalValue, string $relatedListAPIName) {
        $xExternal = "Leads.External_ID,Products.External_Product_ID";
        $relatedRecordsOperations = new RelatedRecordsOperations($relatedListAPIName, $moduleAPIName, $xExternal);
        $request = new BodyWrapper();

        $record1 = new Record();
        $record1->addKeyValue("External_Product_ID", "PR01");

        $record2 = new Record();
        $record2->addKeyValue("External_Product_ID", "PR02");

        $request->setData([$record1, $record2]);
        $response = $relatedRecordsOperations->updateRelatedRecordsUsingExternalId($externalValue, $request);
       
        //Add your code to handle the response received in $response
       //For more details, refer here.
    }
}
UpdateRelatedRecordsUsingExternalId::initialize();
$moduleAPIName = "Leads";
$externalValue = "ABC123";
$relatedListAPIName = "Products";
UpdateRelatedRecordsUsingExternalId::updateRelatedRecordsUsingExternalId1($moduleAPIName, $externalValue, $relatedListAPIName);


4. Uploading a file to the ZFS

You can upload a file to the ZFS directly using the absolute file path, or you can stream the file from external source using their APIs. Depending on the method, the StreamWrapper class initialisation arguments differs.

If you are using the stream method, use the filename and stream that you obtain from the external source's API response.
 $streamWrapper = new StreamWrapper(filename, stream, null); 

If you want to use the absolute file path, the first two arguments should be null, and provide the file path as the third argument.
 $streamWrapper = new StreamWrapper(null, null, "provide_file_path_here"); 

Here is a sample code to upload a file to ZFS from the local drive using the second method.

<?php
use com\zoho\crm\api\ParameterMap;
use com\zoho\crm\api\file\BodyWrapper;
use com\zoho\crm\api\file\FileOperations;
use com\zoho\crm\api\util\StreamWrapper;
require_once "vendor/autoload.php";

class UploadFiles {
    public static function initialize() {
         // add initialisation code
        // refer to the previous post for details and examples 
    }

public static function uploadFiles1() {
$fileOperations = new FileOperations();
$bodyWrapper = new BodyWrapper();
        $streamWrapper = new StreamWrapper(null, null, "/Users/user-1/Downloads/zoho.png");
        $bodyWrapper->setFile([$streamWrapper]);
        $paramInstance = new ParameterMap();
$response = $fileOperations->uploadFiles($bodyWrapper, $paramInstance);
//Add your code to handle the response received in $response
                //For more details, refer here.
}
}

UploadFiles::initialize();
UploadFiles::uploadFiles1();


If successful, the $response object would contain the file id. 

5. File Upload Field and Image Upload Field

To upload an image to an image upload field, or a file to a file upload field, you must first upload the file to ZFS using methods described in section 4. Use the id from the response to upload to the respective field. 
 Here is a sample code to upload an image and a file to a image upload field and file upload field respectively, in Leads module.
<?php
use com\zoho\crm\api\HeaderMap;
use com\zoho\crm\api\record\BodyWrapper;
use com\zoho\crm\api\record\FileDetails;
use com\zoho\crm\api\record\RecordOperations;
use com\zoho\crm\api\record\ { Leads };
use com\zoho\crm\api\record\ImageUpload;
use com\zoho\crm\api\record\Record;
require_once "vendor/autoload.php";

class CreateRecords {
    public static function initialize() {
         // add initialisation code
        // refer to the previous post for details and examples 
    }

    public static function createRecords1(string $moduleAPIName) {
        $recordOperations = new RecordOperations();
        $bodyWrapper = new BodyWrapper();

        $record = new Record();
        $record->addFieldValue(Leads::LastName(), "Boyle");
        $record->addFieldValue(Leads::FirstName(), "Patricia");
        $record->addFieldValue(Leads::Company(), "Zylker Corp");
        $imageUpload = new ImageUpload();
        $imageUpload->setEncryptedId("39c17f1033cd120e62f8104c5450213ede77147fe6");
        $record->addKeyValue("Image_Upload", [$imageUpload]);

        $fileDetail = new FileDetails();
        $fileDetail->setFileId("39c17f1033cd120e62f8104c545af0efea6cc3c67cabefb16");
        $record->addKeyValue("File_Upload", [$fileDetail]);

        $headerInstance = new HeaderMap();

        $bodyWrapper->setData([$record]);

        $response = $recordOperations->createRecords($moduleAPIName, $bodyWrapper, $headerInstance);
        //Add your code to handle the response received in $response
       // For more details, refer here.
    }
}
CreateRecords::initialize();
$moduleAPIName = "Leads";
CreateRecords::createRecords1($moduleAPIName);

We hope that you found this post useful. Stay tuned for more of these!

If you have any questions, let us know in the comments below, or write to us at support@zohocrm.com. We would love to hear from you!

See you next week with more useful content.

Cheers!



    • Recent Topics

    • Created Date/Invalid Fields

      Since Saturday we have suddenly had issues with our webhooks and data retrieval from CRM. Specifically how Created Date is handled. It appears there was some sort of change within CRM that broke a lot of our code that has been in place for several years.
    • add employees and customiz

      I want a Zoho software to track employees record. I logged in a demo so now I tried adding employee, first thing when I click on add employee it takes me to a page where it says add user maximum 10 users, my first doubt why users I don't want employees
    • Revenue Management: #9 Revenue Recognition in Media & Publishing

      Media & Publishing industry has evolved in recent times. It offers subscriptions, bundles digital and print access, runs sponsored content, and sometimes even sells ad spaces. If you run a media or publishing business, you will always get into a situation
    • Zoho CRM Community Digest - July 2025 | Part 2:

      Hello, Everyone! We’re closing out July with a can’t-miss highlight: Zoholics Europe 2025! Happening from September to October, it’s your chance to level up your CRM skills, covering everything from automation and CPQ to dashboards and advanced workflows.
    • How can I trigger a flow action only once while updating contact?

      Hi, we have a trigger to merge&mail file when the field YYY is filled out. For this acion I used "Create or update module entry". But unfortunately we get tens of email on a day with this merged file, because the contact is being regularly updated. The
    • Copy a Record Template from one Form to another

      I have a Creator application with several forms.  I developed a record template for one of the reports/forms but want to use most of it for another of the form/report combinations in the application. Is there a way to copy the template (code or otherwise) to another form?
    • Tip of the Week #70 – Create common team signatures for your shared inboxes

      Did you know that a small detail, such as an email signature, can make a big difference in how your brand is perceived? One simple yet smart way to enhance your team’s communication is by creating common team signatures for your shared inboxes. Instead
    • Enhanced data export features: XLSX format, custom character encoding, and selective record export

      Greetings all, Here are a few enhancements related to exporting CRM data, including the ability to export data in XLSX file format now. The Export feature under Data Administration now offers new options that expand its flexibility and enable users to
    • Tip #42 – How to manage data security with Privacy Settings – 'Insider Insights'

      Data privacy is a cornerstone of trust in remote support. Through Privacy Settings in Zoho Assist, you can set up how data is gathered, stored, and handled in your organization. These settings ensure compliance, data protection for sensitive details,
    • Zoho DataPrep and File Pattern configuration

      I'm using Zoho data prep to ingest data from One Drive into Zoho Analytics... The pipeline is super simple but I can't any way to get all the files that I need. Basically I need to bring all the files with a certain pattern and for that I'm using a regex
    • Introducing Dark Mode / Light Mode : A New Look For Your CRM

      Hello Users, We are excited to announce a highly anticipated feature - the launch of Day, Night and Auto Mode implementation in Zoho CRM's NextGen user interface! This feature is designed to provide a visually appealing and comfortable experience for
    • Quick Item Search & Auto-suggestion for Invoices

      Hi Team, I am facing an issue while creating invoices in Zoho Books. Currently, I have to type the full item name in the correct sequence and spelling for it to appear. For example, my item name is: "Distemper Acri Silk Special White 10kg" If I type something
    • Ticketbai! en el Pais Vasco

      Hola a todos, En enero de 2.022 se va a implantar en el país vasco un nuevo sistema de facturación, denominado ticketbai!, ¿hay alguna previsión de realizar las adaptaciones en zoho books o zoho invoices? Ignoro la cantidad de clientes que tienen estas
    • Zoho CRM mobile app feature update: home page widgets, field tooltips and user image upload

      Hello everyone! Your business doesn't pause when you're on the move, and neither should your CRM. That's why in our latest update, we've introduced a few new features to make your mobile CRM experience smoother and more efficient. Let's take a quick look
    • Zoho CRM Plain Text Template: Line Breaks and Formatting Issue

      Hello, I'm following the instructions to create email templates in Zoho CRM, but I'm having a problem with the plain text version. https://help.zoho.com/portal/en/kb/zoho-sign/integrations/zoho-apps/zoho-crm/articles/zoho-crm-email-templates#Steps_to_create_a_custom_email_template
    • Optimizing Task Handling: Auto-Remove Recurrence for cancelled Tasks.

      Hello Everyone, A Custom function is a user-written set of code to achieve a specific requirement. Set the required conditions needed as when to trigger using the Workflow rules (be it Tasks / Project) and associate the custom function to it. Requirement:
    • Important updates to your connectors

      Hello everyone, Greeting from Zoho Creator! We're excited to announce that we'll be rolling out significant backend updates to Zoho Creator's built-in connectors to enhance security by following the latest frameworks. The existing version of some of the
    • Create, collaborate, and manage agreements with Zoho Sign

      Agreements drive business. We launched Zoho Sign in 2017 as a simple digital signature tool to sign agreements from anywhere, at any time. Over the years, we've learned that most agreements go through last-minute changes before they're signed. Our users
    • Function #25: Automatically generate purchase orders from a sales order

      We kicked off the "Function Fridays" series with the goal of helping you automate your everyday accounting tasks. As we delve into today's post, I'm delighted to announce that we're here to present the 25th custom function in this series. While it is
    • DNS set up

      I want to create an email with my company domain. When I tried to add new record with cloudflare it didn't work. The DNS record can't be manually added. I followed the instruction but still can't add it. Could you help?
    • hiding a topic from all but one segment (or list)

      My organization sends out a number of newsletters using Zoho Campaigns. One of those newsletters is for volunteers. In order to become a volunteer, a person has to first go through our volunteer orientation (training). After that, they can receive newsletters
    • How do I set up this automation correctly?

      When contacts enter my Subscribers list, I want it to reference a custom field to see if it is empty. Then I want it to do two things: If empty: Assign a tag based on a different custom field. If that custom field is empty, assign a different tag. If
    • Function #62: Display associated Quote on Invoice details screen

      Hello everyone! Today, we are sharing a Related List script that makes it easy to view and access the quote from which an invoice was created right from the invoice details screen. This Related List displays the Quote number and Amount, allowing you to
    • Desk x CRM Integration

      Howdy! We currently use SalesIQ but we are considering moving across to Desk as it seems to have more functionality that we want. One of the pulls is the ability for our customers to self serve. But, I might be getting over excited and not actually need
    • Function #53: Transaction Level Profitability for Invoices

      Hello everyone, and welcome back to our series! We have previously provided custom functions for calculating the profitability of a quote and a sales order. There may be instances where the invoice may differ from its corresponding quote or sales order.
    • Issue with Save & Share Link – Works for Others but Not Creator

      I’ve enabled the "Save and Share" feature in Zoho Forms, and it works correctly for all users accessing the public link—except for me (the form creator). Issue Details: When I save and share the link, recipients see a “no permission” error. The form is
    • Save the pdf report from a registration form in a Folder

      Through Zoho Forms I created a registration form with quite a lot of rules to handle different variables (TEAM types, payment in installments, etc.), and the result is pretty good. The automatic PDF that is sent to the respondent upon submission is already
    • zoho forms integration to zoho work drive

      Scenario: A user fills out a Zoho Form, entering details such as email, mobile number, and other required information, and uploads supporting documents like PAN, Aadhaar, etc. Upon submission, the data is available in Zoho Forms Reports. Requirement:
    • Zoho Forms to Zoho CRM Integration failed - can I restart it?

      The integration of Zoho Form to Zoho CRM has failed. Is there a way for me to restart it for the impacted entry?
    • insert an equation, but in document, it shows an image not available.

      I'm new to Zoho writer and used Zoho writer in desktop app version . When I inserted an equation, I got an image not available sign. Any help is appreciated. Thanks, Charles
    • Zoho Desk Android app update - Swipe action customization

      Hello everyone! We have brought in support for the swipe action customization in latest version(v2.9.13) of the Zoho Desk Android app update, enabling you to configure left and right swipe gestures on tickets to carry out the actions swiftly without opening
    • Import KB template OR Export template for zoho desk?

      Greetings. Can you tell me if there is a way to get an EXPORT of my KB articles? OR is there a template you supply for importing KB articles into my zoho desk? I am looking for a method of understanding what fields can be imported, and what their possible
    • XML format to import knowledgebase into Zoho Desk

      Hi, We just started to use Zoho Desk and want to import our knowledgebase from our old support system (Freshdesk) to Zoho Desk. Can anyone give us information about the format of xml file to import? There is no explanation on the related page.
    • Zoho Desk integration with Power BI

      Hi, I want to be able to create a Power BI report which has live updates of ticket data from zoho desk, is this possile at all? Thanks Jack
    • Arranging Ticket Templates

      Is there any way to arrange our ticket templates? It doesn't look very organised when it's just arranged according to when they were created. We want the list to look more organised, by arranging/grouping them by topics, or even just by alphabetical
    • What they mean with "Portal"?

      I just downloaded this app to take my personal notes on digital art studio because it seemed to me the most comfortable app to do it, I use it very often, what do they mean by “no activity on your portal”? I have about 1 year of work here and I don't
    • favorites no longer listed

      Hello, I can no longer navigate to my Favorites from the pulldown at the top of my grid view (see attached screenshot). I wasn't able to find it anywhere! Please help me display my Favorites. Thank you!
    • Notecards Disappeared

      Got a new phone. Downloaded and signed in Zoho Notebook. Not finding the Note cards. Just Empty Note books. Frustrating.
    • Table Errors

      Hello, I'm new to Zoho Notebook and using it on several Mac/Apple devices. My question is regarding tables: Why do they become broken, and how to fix the error without retyping all my data? (Please see the screenshot attached.)
    • Online Calculator with Zoho Forms?

      I'd like to build a custom calculator on my website. Zoho Forms seems to offer all the fields for basic calculations performed live without pressing any "Calculate" buttons. Unfortunately, there is still that "Submit" button at the bottom. There is nothing
    • Next Page