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

    • Windows Device Authentication

      We have recently started using ManageEngine, and my boss saw a device management feature in the Zoho One directory. We thought it would either help give us more intergration into Zoho one through bringing ManageEngine services through Zoho one. Or, it
    • How can I change spell check language?

      I cannot find the way to change spell check language. My "display language" is English, and I want to have the same one for Spell Check, but it is Russian!!! How can I change it? In one of your explanations you mentioned that I have to choose it from
    • Mail is so slow - doesn't even work!

      Mail has been getting slower and slower - and today it's not even pulling up emails in either Inbox or Unread. This is beyond frustrating since email is a big part of business. Sent a request through the useless help portal - no response. Called the useless
    • User marked as SPAMMER. Mail Fetch has also been disabled for any active POP accounts.

      I am the administrator for joelles.com One of our accounts has been blocked saying this: User marked as SPAMMER. Mail Fetch has also been disabled for any active POP accounts. I cannot change the disabled account in the control panel as it says that it
    • My domain did not activate

      Hi, my domain (apsaindustrial.com.ar) did not activate, and the phone verification message never arrived. Please would you solve this problem? Thanks.
    • ME SALE ESTE ERROR: No fue posible enviar el mensaje;Motivo:554 5.1.8 Email Outgoing Blocked

      Ayuda!! Me sale este error al intentar enviar mensajes desde mi correo electronico de Zoho! Tampoco recibo correos pues cuando me envia rebotan. Ayuda, Me urge enviar unos correo importantes!! Quedo atenta MAGDA HERNANDEZ +5731120888408
    • 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?
    • how to see if a specific contact opened an email in zoho campaign?

      how to see if a specific contact opened an email in zoho campaign?
    • Revenue Management: #8 Revenue Recognition in Educational & Training Institutions

      Educational Institutions and training centres typically collect course fees at the time of enrolment, sometimes for a one-day workshop and sometimes for a year-long certification course. You might also charge separately for course materials or evaluation.
    • How to Customize Task Creation to Send a Custom Alert Using JavaScript in Zoho CRM?

      Hello Zoho CRM Community, I’m looking to customize Zoho CRM to send a custom alert whenever a task is created. I understand that Zoho CRM supports client scripts using JavaScript, and I would like to leverage this feature to implement the alert functionality.
    • Using files from Zoho CRM in Gemini/ChatGPT/Claude

      Hi all, I’ve got subscriptions to Gemini and a few other AI tools which I use for tasks like data enrichment, email composition, etc. In our workflow, we often receive various documents from clients — such as process workflows, BRDs/requirement documents
    • Enhancements to the formula field in Zoho CRM: Auto-refresh formulas with the "Now" function, stop formula executions based on criteria, and include formulas within formulas

      Dear Customers, We hope you're well! By their nature, modern businesses rely every day on computations, whether it's to calculate the price of a product, assess ROI, evaluate the lifetime value of a customer, or even determine the age of a record. With
    • Maximum file limit in zoho people LMS

      Dear Team, I am having approximately 4.9 GB of material, including PPTs and videos for uploading in zoho people LMS course. May I know what is the maximum limit limit for the course files Thanking you, With regards, Logeswar V Executive _ Operations
    • Dynamically prefill ticket fields

      Hello, I am using Zoho Desk to collect tickets of our clients about orders they placed on our website. I would like to be able to prefill two tickets fields dynamically, in this case a readonly field for the order id, and a hidden field for the seller
    • Optimize your Knowledge Base for better visibility by allowing search engine crawling and indexing

      All you need to know about no-follow and no-index in KB. What are article crawlability and indexability? Crawlability and indexability are vital for making an article visible and accessible to search engines. When a search engine crawls an article, it
    • Has anyone created a public ASAP Guide that I can check out?

      I am thinking of adding an ASAP guide to my web application, but I have noticed that the ASAP widget itself can be really slow to load sometimes. Has anyone created a public ASAP Guide that I can check to see how performant it is? I don't want to spend
    • Zoho Desk Partners with Microsoft's M365 Copilot for seamless customer service experiences

      Hello Zoho Desk users, We are happy to announce that Zoho Desk has partnered with Microsoft's M365 to empower customer service teams with enhanced capabilities and seamless experiences for agents. Microsoft announced their partnership during their keynote
    • What’s New in Zoho Analytics – September 2025

      Hello Users!! In this month’s update, we’re raising the bar across multiple touchpoints, from how you bring in data, plan and track projects to how you design and brand your dashboards. We’ve added the all-new Gantt chart for project visualization, expanded
    • Zoho MCP has no tools for Creator or 3rd Party Apps?

      I don't see a Zoho MCP community forum so putting this here. Two big problems I see: 1) Although Zoho advertises "over 950 3rd party apps" as available through their MCP, when I go to "Add Tools" there are ZERO 3rd party apps available to choose from.
    • Zoho Forms - Zoho Drive connection - Shared Drives not supported

      Hello i am stuck with Google Drive Connection There is no supported shared drives Connection is not support shared drives boolean Query Parameters - supportsAllDrives=true&supportsTeamDrives=true to activate fetch files from the shared drives. Ahat need
    • Can't create package until Bill created?

      I can't understand why we cannot create a package until a Bill is created? We are having to created draft Bills to create a package when the item is received, but we may not have received a Bill from the supplier. Also, Bill # is required, but we normally
    • Whats the Time out Limit for API Calls from Deluge?

      Hi Creator Devs, We are making API calls to third party server via Deluge. Getting this error message: Error at line : 24, The task has been terminated since the API call is taking too long to respond. Please try again after sometime. Whats the default
    • How to get the authorization code for domain transfer from Zoho?

      I have transferred my domain from zoho to godaddy, and that needs a authorization code. I haven't got any mail containing that. How to get the authorization code from domain transfer? Thanks, Arun
    • I have error AS101 when I try to add paypal@mydomain.com to Zoho

      Please help me with this. I tried to call the help line 4 times but don't get any response.
    • Tip #3: How to change your booking page language

      Displaying your booking page in your target audience's language can greatly increase customer satisfaction. By speaking their language, you will help customers feel more comfortable scheduling with you and create a stronger connection with them. Let's
    • How can I optimize a Zoho Site page for SEO when embedding external menu or restaurant links?

      Hi everyone, I’m experimenting with building small content hubs on Zoho Sites and want to make sure I’m doing it in an SEO-friendly way. For example, I tried creating a page that highlights restaurant menu items and linked out to a resource like this:
    • Diff signature for compose new email and replies

      Hi,   How do i have different signature for replies and new emails. its inconvenient to have one large signature for replies. Usually on Outlook we have the option to keep separate signatures for new emails and for replies.
    • Zoho Website Site Speed Up & Setting

      We are experiencing slow loading speeds on our Zoho website and would like assistance in optimizing its performance. Kindly review the site and suggest or implement necessary improvements to enhance speed, especially related to: > Caching mechanisms >
    • Clickjacking: Zoho Vault's Response

      Issue: Password manager browser extensions are found to be vulnerable to clickjacking security vulnerabilities that could allow attackers to steal account credentials, TFA codes, and card details under certain conditions. Reported by: Marek Toth, Independent
    • Refund

      Hi There, Please refund me asap possible, because of no support given. Thank you
    • No option for pick up in Zoho Books / Inventory but yes on commerce

      Is it planned to release soon on books/inventory?
    • Accessing Zoho form enteries via API

      Hi As a user I can view enteries to a form at: https://forms.zoho.com/<myOrganisation>/report/<myReportName>/records/web How do I access these entries via API? I don't have any problem with scope and getting tokens. But I have no idea what the API call
    • Blueprint Issue - Being able to set a subform field as mandatory

      I'm creating a blueprint. My record involves a subform which is only shown once field is set but the field gets set in step two of the process. My problem - I can't save the record as the subform field is set to mandatory - If I unset the mandatory field,
    • Blueprint - Mandatory file upload field

      Hi, File upload (as we as image upload) field cannot be set as mandatory during a blueprint transition. Is there a workaround? Setting attachments as mandatory doesn't solve this need as we have no control over which attachments are added, nor can we
    • Zoho Books - Include Quote Status in Workflow Field Triggers

      Hi Zoho Books team, I recently tried to create a Workflow rule based on when a Quote is Accepted by the customer. This is something which I thought would be very easy to do, however I discovered that Status is not listed as a field which can be monitored
    • Zoho Books - Show Related Sales Orders on Quotes

      Hi Books team, I've noticed that the Quotes don't show show the related Sales Order. My feature request is to also show related Sales Orders above the Quote so it's easy to follow the thread of records in the sales and fulfilment process. Below screenshot
    • Add VAT/Tax line to bank adjustments

      When categorising transactions and matching bank feeds with transactions such as customer payments, we use the "Add Adjustment" to add things like fees/bank fees. It would be useful to choose a VAT/Tax rate here. Whilst there is a bank charges option when adding a payment, this goes into the default bank charges account. We use the adjustments so that we can choose the account and separate our fees. We use different card providers and Worldpay charges VAT so we are stuck. We cannot integrate with
    • New Menu Layout Feedback

      I'd really like to see the banking item back on the top of the menu. I'm sure part of it is just because that's what I'm accustomed to. However, for a bookkeeping program, I think there's a logic to having banking be on top. Not a giant issue, but something
    • How to use Rollup Summary in a Formula Field?

      I created a Rollup Summary (Decimal) field in my module, and it shows values correctly. When I try to reference it in a Formula Field (e.g. ${Deals.Partners_Requested} - ${Deals.Partners_Paid}), I get the error that the field can’t be found. Is it possible
    • Form Accessibility

      Hi, is there an update on the accessibility standard of Zoho forms? Are the forms WCAG 2.1 AA compliant? 
    • Next Page