Kaizen #86 - PHP SDK [Part III]

Kaizen #86 - PHP SDK [Part III]

Hey there!
Welcome back to yet another insightful post in our Kaizen series!

In this post, we will continue the journey of PHP SDK sample codes for Record Operations from last week. Let us delve into a new set of use-cases and expand your horizons with additional examples in the Record and Send Mail Operations. 

1. Subforms

To add subform details of a record during a record create/update, use the following format.

$subformVar = new Record();
$subformVar->addKeyValue("Subform_Field_API_Name", "FieldValue");
$record->addKeyValue("Subform_API_Name", [$subformVar]);

Repeat the second line of the above code to add as many fields as you have in your subform layout. To add multiple subform records, you will have to map the fields within a new object for each subform record. 

Here is a sample code to update the details of a custom subform in Contacts. 

<?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\record\Record;

require_once "vendor/autoload.php";

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

public static function updateRecord1(string $moduleAPIName, string $recordId)
    {
        $recordOperations = new RecordOperations();

        $request = new BodyWrapper();

        $record = new Record();
        $record->addFieldValue(Contacts::LastName(), "Boyle");
        $subformRec1 = new Record();
        $subformRec1->addKeyValue("Language_Proficiency", new Choice("English"));
        $subformRec1->addKeyValue("Personal_Email", "patricia.boyle@zylker.com");
        $subformRec1->addKeyValue("Secondary_Phone", "9876543210");
        $record->addKeyValue("Proficiency_and_Others", [$subformRec1]);
        $request->setData([$record]);
        $headerInstance = new HeaderMap();
        $response = $recordOperations->updateRecord($recordId, $moduleAPIName, $request, $headerInstance);
 //Add your code to handle the response received in $response
 // For more details, see here.
    }
}

UpdateRecord::initialize();
$moduleAPIName = "Contacts";
$recordId = "5545974000002858001";
UpdateRecord::updateRecord1($moduleAPIName, $recordId);
?>

2. Line Items and Line Taxes in Inventory Modules

2.1 Product Line Items and Product Line Taxes

To add or update product line items and their product line taxes in the Inventory module, use the following format.

$lineItemVar = new Record();
$lineItemProductVar = new LineItemProduct();
$lineItemProductVar->setId("product_id");
$lineItemVar->addKeyValue("Product_Name", $lineItemProductVar);
$lineItemVar->addKeyValue("Quantity", Value);
$lineItemVar->addKeyValue("ListPrice", Value);
$lineItemVar->addKeyValue("Discount", Value);
$productLineTaxVar = new LineTax();
$productLineTaxVar->setName("Tax_Name");
$productLineTaxVar->setPercentage(Value);
$lineItemVar->addKeyValue('Line_Tax',  [$productLineTaxVar]);

Repeat this code to add multiple products to the inventory record.
Note that when you update any one of the line items in the inventory records, the remaining line items will become null and have to be re-added to the list. 

2.2 Inventory Record Line Taxes

To add line taxes to an inventory record, use the following format.

$lineTaxVar = new LineTax();
$lineTaxVar->setName("Tax_Name");
$lineTaxVar->setPercentage(Value);
$record->addKeyValue('$line_tax', [$lineTaxVar]);

The 'line_tax' represents the tax amount specific to each line item. Whereas, the '$line_tax' represents the tax applied to the overall products in the line item list.

Following is a sample code to create a record in the Quotes module.

<?php

use com\zoho\crm\api\HeaderMap;
use com\zoho\crm\api\record\BodyWrapper;
use com\zoho\crm\api\record\LineTax;
use com\zoho\crm\api\record\LineItemProduct;
use com\zoho\crm\api\record\RecordOperations;
use com\zoho\crm\api\record\{Accounts, Contacts, Quotes, Deals};
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 createRecords(string $moduleAPIName)
    {
        $recordOperations = new RecordOperations();
        $bodyWrapper = new BodyWrapper();
        $record = new Record();
        $record->addFieldValue(Quotes::Subject(), "Quote No 1");
        $AccountName = new Record();
        $AccountName->addFieldValue(Accounts::id(), "55459742858119");
        $record->addFieldValue(Quotes::AccountName(), $AccountName);
        $dealName = new Record();
        $dealName->addFieldValue(Deals::id(), "55459742858125");
        $record->addFieldValue(Quotes::DealName(), $dealName);
        $contactName = new Record();
        $contactName->addFieldValue(Contacts::id(), "55459742858122");
        $record->addFieldValue(Quotes::ContactName(), $contactName);

         //product 1
        $inventoryLineItem1 = new Record();
        $lineItemProduct1 = new LineItemProduct();
        $lineItemProduct1->setId("55459742897004");
        $inventoryLineItem1->addKeyValue("Product_Name", $lineItemProduct1);
        $inventoryLineItem1->addKeyValue("Quantity", 2.0);
        $inventoryLineItem1->addKeyValue("ListPrice", 150.0);
        $inventoryLineItem1->addKeyValue("Discount", "5%");
        $productLineTax = new LineTax();
        $productLineTax->setName("Sales Tax");
        $productLineTax->setPercentage(2.0);
        $inventoryLineItem1->addKeyValue('Line_Tax', [$productLineTax]);

         //product 2
        $inventoryLineItem2 = new Record();
        $lineItemProduct2 = new LineItemProduct();
        $lineItemProduct2->setId("55459742897009");
        $inventoryLineItem2->addKeyValue("Product_Name", $lineItemProduct2);
        $inventoryLineItem2->addKeyValue("Quantity", 1.0);
        $inventoryLineItem2->addKeyValue("ListPrice", 100.0);
        $inventoryLineItem2->addKeyValue("Discount", "3%");
        $productLineTax1 = new LineTax();
        $productLineTax1->setName("Sales Tax");
        $productLineTax1->setPercentage(2.0);
        $productLineTax2 = new LineTax();
        $productLineTax2->setName("Vat");
        $productLineTax2->setPercentage(4.0);
        $inventoryLineItem2->addKeyValue('Line_Tax', [$productLineTax1, $productLineTax2]);
        $record->addKeyValue("Quoted_Items", [$inventoryLineItem1, $inventoryLineItem2]);

         //line taxes
        $lineTax1 = new LineTax();
        $lineTax1->setName("Sales Tax");
        $lineTax1->setPercentage(2.0);
        $lineTax2 = new LineTax();
        $lineTax2->setName("Vat");
        $lineTax2->setPercentage(2.0);
        $record->addKeyValue('$line_tax', [$lineTax1, $lineTax2]);

        $bodyWrapper->setData([$record]);
        $headerInstance = new HeaderMap();
        $response = $recordOperations->createRecords($moduleAPIName, $bodyWrapper, $headerInstance);
 //Add your code to handle the response received in $response
 // For more details, see here.
    }
}

CreateRecords::initialize();
$moduleAPIName = "Quotes";
CreateRecords::createRecords($moduleAPIName);
?>

3. Events and Tasks Module Operations

3.1 Add and Update Participants in Events

There are two methods to add participants to an event. In the first method, use the record ID of the contact, lead or user. 

$participantVar = new Participants();
$participantVar->addKeyValue("participant", "record_id");
$participantVar->addKeyValue("type", "record_module");
$record->addFieldValue(Events::Participants(), [$participantVar]);

In the second method, mention the participant's email ID with the type key specified as email

$participantVar = new Participants();
$participantVar->setParticipant("name@domain.com");
$participantVar->setType("email");
$record->addFieldValue(Events::Participants(), [$participantVar]);

In the above code snippet, setParticipant() is a method used to assign a new value to the participant field. 

3.2 Reminder in Events

To create/update reminders for any event, use the following format. 

$reminderVar = date_create("YYYY-MM-DDThh:mm:ss.sssZ", new \DateTimeZone(date_default_timezone_get()));
$record->addFieldValue(Events::FieldName(), $reminderVar);

Here date_create() function is used to create the DateTime object with two parameters. The first parameter represents for the DateTime string and the following represents for the time zone

3.3. Reminder in Tasks

To create/update reminder for a task, use the following format.

$remindAtVar = new RemindAt();
$remindAtVar->setAlarm("ACTION=Value;TRIGGER=Condition;TRIGGER_TIME=hh:mm");
$record->addFieldValue(Tasks::FieldName(), $remindAtVar);

In the above code, the setAlarm() method is used to set the reminder properties. The multiple key-value pairs in the string argument denote the properties of your reminder. Following are the representation of keys for this field type.
  • ACTION - Specifies the notification type of the reminder.
  • TRIGGER - Defines the trigger condition that activates the reminder.
  • TRIGGER_TIME - Indicates the time at which the alarm should be triggered.
Refer to this document, to learn more about these key-value pairs and their possible values.

3.4 Recurring Activity in Events and Tasks

Use the following format to create a recurring event.

$recurringActivityVar = new RecurringActivity();
$recurringActivityVar->setRrule("FREQ=value;INTERVAL=value;BYMONTH=mm;BYMONTHDAY=dd;
DTSTART=yyyy-mm-dd;UNTIL=yyyy-mm-dd");
$record->addFieldValue(Module_API_Name::FieldName(), $recurringActivityVar);

Here, the setRrule() method is used to define the elements that determine the recurrence of the activity. This format is common for all the activity modules. To know more about the Rrule elements, refer to this post.

Below is a sample code to create an event using the above field types.

<?php

use com\zoho\crm\api\HeaderMap;
use com\zoho\crm\api\record\BodyWrapper;
use com\zoho\crm\api\record\Participants;
use com\zoho\crm\api\record\RecordOperations;
use com\zoho\crm\api\record\RecurringActivity;
use com\zoho\crm\api\record\Events;
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(Events::EventTitle(), "Test Events");
        $startdatetime = date_create("2023-05-16T23:03:06+05:30", new \DateTimeZone(date_default_timezone_get()));
        $record->addFieldValue(Events::StartDateTime(), $startdatetime);
        $enddatetime = date_create("2023-05-16T23:45:06+05:30", new \DateTimeZone(date_default_timezone_get()));
        $record->addFieldValue(Events::EndDateTime(), $enddatetime);

         //add participants 
        $participant1 = new Participants();
        $participant1->setParticipant("patricia.boyle@zylker.com");
        $participant1->setType("email");
        $participant2 = new Participants();
        $participant2->addKeyValue("participant", "5545974000002858122");
        $participant2->addKeyValue("type", "contact");
        $record->addFieldValue(Events::Participants(), [$participant1, $participant2]);

         //event reminder
        $remindAt = date_create("2023-05-16T21:00:06+05:30", new \DateTimeZone(date_default_timezone_get()));
        $record->addFieldValue(Events::RemindAt(), $remindAt);

         //recurring event
        $recurringActivity = new RecurringActivity();
        $recurringActivity->setRrule("FREQ=YEARLY;INTERVAL=1;BYMONTH=5;BYMONTHDAY=16;DTSTART=2023-05-16;UNTIL=2026-05-16");
        $record->addFieldValue(Events::RecurringActivity(), $recurringActivity);

        $BodyWrapper->setData([$record]);
        $headerInstance = new HeaderMap();
        $response = $recordOperations->createRecords($moduleAPIName, $BodyWrapper, $headerInstance);
 //Add your code to handle the response received in $response
 // For more details, see here.
    }
}

CreateRecords::initialize();
$moduleAPIName = "Events";
CreateRecords::createRecords1($moduleAPIName);
?>

Here is a sample code for creating a recurring task with a reminder.

<?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\RecurringActivity;
use com\zoho\crm\api\record\RemindAt;
use com\zoho\crm\api\record\Tasks;
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(Tasks::Subject(), "Follow-up call");

         //task reminder
        $remindAt = new RemindAt();
        $remindAt->setAlarm("ACTION=EMAIL;TRIGGER=-P0D;TRIGGER_TIME=14:20");
        $record->addFieldValue(Tasks::RemindAt(), $remindAt);

         // recurring task
        $recurringActivity = new RecurringActivity();
        $recurringActivity->setRrule("FREQ=WEEKLY;INTERVAL=1;UNTIL=2023-06-01;BYDAY=TH;DTSTART=2023-06-01");
        $record->addFieldValue(Tasks::RecurringActivity(), $recurringActivity);

        $bodyWrapper->setData([$record]);
        $headerInstance = new HeaderMap();
        $response = $recordOperations->createRecords($moduleAPIName, $bodyWrapper, $headerInstance);
 //Add your code to handle the response received in $response
 // For more details, see here.
    }
}

CreateRecords::initialize();
$moduleAPIName = "Tasks";
CreateRecords::createRecords1($moduleAPIName);
?>

5. Send Email

You can either use an email or inventory template to send mail or write your own HTML/text body for the email. Refer to this sample code on GitHub to know how to fetch the inventory template IDs.  To use a template in your email follow the below structure.

$mail = new Mail();
$templateVar = new EmailTemplate();
$templateVar->setId(template_id);
$mail->setTemplate($templateVar);

Use the following format to write your own email body.

$mail = new Mail();
$mail->setContent("your_html_content");
$mail->setMailFormat("html");

To specify plain text as the value for the setContent() method, you have to set text as the value for the setMailFormat() method.

Here is a sample code of send mail using email template for your reference.

<?php

use com\zoho\crm\api\sendmail\SendMailOperations;
use com\zoho\crm\api\sendmail\Mail;
use com\zoho\crm\api\emailtemplates\EmailTemplate;
use com\zoho\crm\api\sendmail\BodyWrapper;
use com\zoho\crm\api\sendmail\UserAddress;
//use com\zoho\crm\api\inventorytemplates\InventoryTemplate;

require_once "vendor/autoload.php";

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

    public static function sendMail1(string $recordId, string $moduleAPIName)
    {
        $sendMailOperations = new SendMailOperations();
        $mail = new Mail();
        $from = new UserAddress();
        $from->setUserName("Patricia Boyle");
        $from->setEmail("patricia.boyle@zylker.com");
        $mail->setFrom($from);
        $to = new UserAddress();
        $to->setUserName("Carissa Kidman");
        $to->setEmail("carissa-kidman@yahoo.com");
        $mail->setTo([$to]);
        $mail->setSubject("Mail subject");

         //use this for customized email body
        //$mail->setContent("Hello! Thank you for shopping with us!");
        //$mail->setMailFormat("text");

         //use this for inventory template
        //$template = new InventoryTemplate();
        //$template->setId("55459741230768");
        //$mail->setTemplate($template);

        $template = new EmailTemplate();
        $template->setId("55459741230058");
        $mail->setTemplate($template);
        $mail->setConsentEmail(true);
        $wrapper = new BodyWrapper();
        $wrapper->setData([$mail]);
        $response = $sendMailOperations->sendMail($recordId, $moduleAPIName, $wrapper);
 //Add your code to handle the response received in $response
 // For more details, see here.
    }
}

SendMail::initialize();
$recordId = "5545974000002935001";
$moduleAPIName = "Contacts";
SendMail::sendMail1($recordId, $moduleAPIName);
?>

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 eagerly await your thoughts and feedback on this!

Keep an eye out for future posts packed with similar content!

Cheers!

Additional Reading


    Access your files securely from anywhere

        Zoho Developer Community




                                  Zoho Desk Resources

                                  • Desk Community Learning Series


                                  • Digest


                                  • Functions


                                  • Meetups


                                  • Kbase


                                  • Resources


                                  • Glossary


                                  • Desk Marketplace


                                  • MVP Corner


                                  • Word of the Day



                                      Zoho Marketing Automation


                                              Manage your brands on social media



                                                    Zoho TeamInbox Resources

                                                      Zoho DataPrep Resources



                                                        Zoho CRM Plus Resources

                                                          Zoho Books Resources


                                                            Zoho Subscriptions Resources

                                                              Zoho Projects Resources


                                                                Zoho Sprints Resources


                                                                  Qntrl Resources


                                                                    Zoho Creator Resources



                                                                        Zoho Campaigns Resources


                                                                          Zoho CRM Resources

                                                                          • CRM Community Learning Series

                                                                            CRM Community Learning Series


                                                                          • Kaizen

                                                                            Kaizen

                                                                          • Functions

                                                                            Functions

                                                                          • Meetups

                                                                            Meetups

                                                                          • Kbase

                                                                            Kbase

                                                                          • Resources

                                                                            Resources

                                                                          • Digest

                                                                            Digest

                                                                          • CRM Marketplace

                                                                            CRM Marketplace

                                                                          • MVP Corner

                                                                            MVP Corner





                                                                              Design. Discuss. Deliver.

                                                                              Create visually engaging stories with Zoho Show.

                                                                              Get Started Now