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

    • Sub form doesn't as formula field

      Is it possible to get formula field in sub form in futures?
    • Week date range in pivot table

      Hello, I need to create a report that breakouts the data by week.  I am using the pivot table report, and breaking out the date by week, however the date is displayed as 'Week 1 2014' format.  Is there anyway to get the actual dates in there? ex. 1/6/2014-1/12/2014 Thanks,
    • How do I get Status History data of my Projects?

      I want to build a table in Zoho Analytics that Groups by Date, when Projects entered a certain status. I cannot find Status History or any such useful data available in the Setup of my Data Source sync. Please advise how I can achieve this?
    • Is it possible to hide fields in a Subform?

      Since layout rules cannot be used with Subforms, is there another way, or is it even possible, to hide fields in a subform based on a picklist fields within said subform? For example, if the Service Provided is Internet, then I do not want to see the
    • Weekly Tips :Instantly find what you need with Attachment Viewer

      Your inbox must be packed with project emails, shared notes, and scattered attachments. You are looking for one specific file—a presentation slide or maybe a media clip from a team update—but don’t want to dig through endless email threads or switch between
    • Putting Watermark on Zoho Sheet

      Can this be done?
    • Missing Zoho Desk integration option for form workflows

      According to the help page "Configure Zoho Desk integration in form workflows" we should be able to select Zoho Desk as an integration target but when I open the integrations list then Zoho Desk is not being listed in it. We are on the Premium plan which should already support Zoho Desk integrations.
    • Gantt for 2 or more projects

      Hello, I'm trying the free version of your produtc. It is veryyy good!!!! I don't know if in the Standard plan, I can overview a Gantt Graph for 2 or more Projects Milestone. This would be very helpfull for managing teams and taking decisions about who I will assign a task to. In the paid plan Do I have this possibility? Thank you.
    • Integrating a Zoho Project Gantt Chart into Reports

      Is is possible to integrate a Zoho Project Gantt Chart into a Zoho Report Dashboard. I am in the process of creating Project Status Dashboards for the projects that we track in Zoho Projects and I would like to incorporate the gantt chart within Reports.  Please let me know! Thanks
    • ZOHO BOOKS - EXCESSIVELY SLOW TODAY

      Dear Zoho Books This is not the first time but it seems to be 3 times per week now that the system is extremely slow. I work on Zoho Books 95% of my day so this is very frustrating. Zoho you need to do something about this. I have had my IT guy check
    • Gantt Chart - Zoho Analytics

      Are there any plans to add Gantt Charts capabilities to Zoho Analytics?
    • Displaying related quotes in sales order and back

      Hi, My colleague liked to see to which sales orders, the quote has been converted. Quote shows Invoices, but not SO. Same, they would like to see the quotes in the sales order, as they can see invoices, packages, shipment, How can we achieve this ? Thank
    • Tip of the Week #71–Auto-move incoming messages to the right inboxes with keywords

      We all know that customer-facing teams, especially your sales and support teams, can’t afford to miss even a single customer conversation. But sometimes, sales queries or support requests can easily get lost in a crowded inbox or even end up in the wrong
    • Clearing Fields using MACROS?

      How would I go about clearing a follow-up field date from my deals? Currently I cannot set the new value as an empty box.
    • Migrating a Zoho Forms form into Zoho Creator

      Hi, How can I migrate my Zoho Forms form into Zoho Creator? Thanks. Truly, Emad
    • Is there any way to recall an email sent using Zoho CRM?

      If an email is sent using Zoho Mail, there is a recall option/functionality that is available to the sender. Is there any way to recall an email if it was sent using Zoho CRM? I can't seem to find that option. Any help would be appreciated.
    • Quick Create needs Client Script support

      As per the title. We need client scripts to apply at a Quick Create level. We enforce logic on the form to ensure data quality, automate field values, etc. However, all this is lost when a user attempts a "Quick Create". It is disappointing because, from
    • is it possible to add more than one Whatsapp Phone Number to be integrated to Zoho CRM?

      so I have successfully added one Whatsapp number like this from this User Interface it seems I can't add a new Whatsapp Number. I need to add a new Whatsapp Number so I can control the lead assignment if a chat sent to Whatsapp Phone Number 1 then assign
    • Problem with reports due to "Connected" items change - Yes this IS a problem

      Now that the change has been made to use "connected" items I can no longer run the reporting I need in CRM. I should be able to start with Deals as the parent, connect down to the Account (Account_Name) on the deal as the child, then to any child items
    • Introducing notifications in the vendor portal

      Imagine this: You're a recruiter working with multiple vendors on a high-volume hiring project. You’ve just updated a job description after a last-minute change from the hiring manager. One of your vendors, however, is still working off the older version
    • CRM limit reached: only 2 subforms can be created

      we recently stumbled upon a limit of 2 subforms per module. while we found a workaround on this occasion, only 2 subforms can be quite limiting in an enterprise setting. @Ishwarya SG I've read about imminent increase of other components (e.
    • LESS_THAN_MIN_OCCURANCE - code 2945

      Hi I'm trying to post a customer record to creator API and getting this error message. So cryptic. Can someone please help? Thanks Varun
    • How to update "Lead Status" to more than 100 records

      Hello Zoho CRM, How do I update "Lead Status" to more than 100 records at once? To give you a background, these leads were uploaded or Imported at once but the lead status record was incorrectly chosen. So since there was a way to quickly add records in the system no matter how many they are, we are also wondering if there is a quicker way to update these records to the correct "Lead Status". I hope our concern makes sense and that there will be a fix for it. All the best, Jonathan
    • Analytics for notes created

      Is there a way I can see how many notes were created per day? Via reporting or analytics?
    • No TDS Deduction

      In some of our case, where we are reselling items at the same rate we purchased. In this scenario, Indian IT Law has a provision to request customer not to deduct TDS if the transaction value is same. TDS is paid by us (intermediary reseller) before we
    • Cannot update Recurring_Activity on Tasks – RRULE not accepted

      Hello, I am trying to update Tasks in Zoho CRM to make them recurring yearly, but I cannot find the correct recurrence pattern or way to update the Recurring_Activity field via API or Deluge. I have tried: Sending a string like "RRULE:FREQ=YEARLY;INTERVAL=1"
    • Add image to report...

      Greetings, I send a weekly color coded report via Creator email. I would like to add the legend somewhere in the report. Header, footer where ever. I have the legend saved on Google Drive and can access it via shared link. Sure someone has wanted to add
    • More controls for User Fields in CRM

      Dear All, We are here with a minor but crucial enhancement to the user fields—now set accessibility permissions to the records for user field. User field allows you to extend co-ownership of records to your peers. You can collaborate with them for certain
    • Calls to accounts rather than leads or contacts?

      So..... We have a dilemma and I'm hoping someone has encountered this before and figured out a fix. We have just migrated to Zoho. It's great.....expect for how "Calls" are handled.... We are B2B. We do not use the leads module. A "Lead/Prospect" for
    • Image Upload Field | Zoho Canvas

      I'm working on making a custom view for one of our team's modules. It's an image upload field (Placement Photo) that would allow our sales reps to upload a picture of the house their working on. However, I don't see that field as a opinion when building
    • Power of Automation :: Automated 'Delayed & Closed' Status Update Based on Due Date

      Hello Everyone, A custom function is a software code that can be used to automate a process and this allows you to automate a notification, call a webhook, or perform logic immediately after a workflow rule is triggered. This feature helps to automate
    • Lead Blueprint transition in custom list view

      Hi, Is It possible to insert the Blueprint transition label in a custom Canvas list view? I am using Lead module. I see the status, but it would be great if our users could execute the Blueprint right from the list view without having to enter the detailed
    • Range names in Zoho Sheet are BROKEN!

      Hi - you've pushed an update that has broken range names. A previously working spreadsheet now returns errors because the range names are not updating the values correctly. I've shared a video with the support desk to illustrate the problem. This spreadsheet
    • Has anyone integrated SMS well for Zoho Desk?

      Our company does property management and needs to be able to handle inbound sms messages which create a ticket for Zoho Desk. We then need to be able to reply back from Zoho desk which sends the user an sms message. This seems like a fairly common thing
    • populate email address and name in zoho desk?

      Is it possible to populate the email address and name in the zoho desk widget? We only use it in the context of an authenticated user, so we already know the user's name and email. Thanks,
    • Are there default/pre-built dashboards in Zoho Desk?

      Hi, I am looking for some pre-built dashboard templates in Zoho Desk, similar to what we can find in CRM/Projects, etc Thank you
    • SAP S/4 HANA to CRM Integration - change the SAP Client ID

      Hi I am trying to push the business partners from SAP S/4 HANA to ZOHO CRM module. The SAP Client ID is 421 in my case....kindly let me know how do I specify the sap client because it's a dropdown with specific values as of now. Thanks Ravi Aswani
    • Staff rules

      Hi! Do you people know what are the default staff rules when a new booking is created? We have two staff members in my team (me as the admin, and my employee). As we share the same services, I'm wondering how Zoho will pick the staff for new apointments.
    • Adding branded signature to tickets reply

      Hi, i am unable to figure out how to add signatures with logo to tickets reply. please advice .
    • Zoho Marketing Automation 2.0 - Landing Page function not working

      Dear Zoho Team, I am working on implementing Zoho Marketing Automation 2.0, and am now looking into the section "Lead Generation". If I open the "Landing Pages" section, I immediately get an Error code: Error: internal error occurred. Can you help me
    • Next Page