Page tree
Skip to end of metadata
Go to start of metadata

Prerequisites

The latest version of the PHP API client is available on github.com.

Kayako

To use Kayako REST API, first you need to enable it in your Kayako installation. To enable the API, login to Admin Control Panel and in Options panel on the right choose REST API, and then Settings. Next, set Enable API Interface to Yes and confirm the change by clicking Update button.

PHP

The PHP API client requires version 5.3.0 or later of PHP environment with enabled support for: libXML, cURL, hash, fileinfo and date/time.

Getting Started

To use Kayako REST API you will need API URL, API key and Secret key. API URL and both keys can be obtained through Admin Control Panel - in Options panel on the right choose REST API and then API Information.

Initializing the client

To set up the PHP API client, first you need to load the kyIncludes.php file. Then, you must initialize the client with API URL, API Key and Secret Key. The following code presents these two steps.

//include all necessary classes and helper methods
require_once("kyIncludes.php");

//initialize the client
kyConfig::set(new kyConfig("<API URL>", "<API key>", "<Secret key>"));

Remember to change <API URL>, <API key> and <Secret key> to the values from your Kayako installation.

Default parameters for ticket creation

This step is optional. If the client will be used to create new tickets it’s recommended to set default status, priority and type of new tickets:

kyTicket::setDefaults(<default status id>, <default priority id>, <default type id>);

In order to discover proper identifiers for your installation you can get all objects and print them:

print kyTicketStatus::getAll();
print kyTicketPriority::getAll();
print kyTicketType::getAll();

You can also use filtering to find status, priority and type by their title:

$default_status_id = kyTicketStatus::getAll()->filterByTitle("Open")->first()->getId();
$default_priority_id = kyTicketPriority::getAll()->filterByTitle("Normal")->first()->getId();
$default_type_id = kyTicketType::getAll()->filterByTitle("Issue")->first()->getId();

Advanced initialization settings

Date/time and date formatting

All date/time and date values returned by the client are formatted according to the specified format. Default format of date/time values is Y-m-d H:i:s (ex. 2011-06-19 17:16:00) and default format of date values is Y-m-d (ex. 2011-06-19). The date/time and date format can be changed in the configuration:

//initialize the client with different date/time and date formatting (ex. June 19, 2011, 5:16 pm)
$config = new kyConfig("<API URL>", "<API key>", "<Secret key>");
$config->setDatetimeFormat('F j, Y, g:i a');
$config->setDateFormat('F j, Y');
kyConfig::set($config);

Refer to PHP manual for explanation of date/time formatting options.

Request URL type

The most important part of REST request URL is information about controller (and module as a part of it) to use (ex. /Base/User). There are two methods of providing controller name in request: standard and with an "e" parameter. The default is to use the standard way of constructing request URL. If you want to use an "e" parameter you can change this behaviour in the configuration:

//initialize the client to use "e" query parameter for constructing REST request URL
$config = new kyConfig("<API URL>", "<API key>", "<Secret key>");
$config->setIsStandardURLType(false);
kyConfig::set($config);

At the time of writing this (2012-09-28) Kayako OnDemand environment requires the standard request URL type.

Debugging the client

Sometimes it's helpful to examine what requests are sent to Kayako server and what is the server's response. The client supports debug mode in which all requests (URL and body) and all responses (body) are logged using PHP logging mechanism (error_log). You can enable debug mode in configuration:

//initialize the client with debug mode enabled
$config = new kyConfig("<API URL>", "<API key>", "<Secret key>");
$config->setDebugEnabled(true);
kyConfig::set($config);

Basic Concepts

The key concept of the client is Object. Object can be one of the following types:

  • CustomFieldDefinition
  • Department
  • Staff
  • StaffGroup
  • Ticket
  • TicketAttachment
  • TicketCustomFieldGroup
  • TicketNote
  • TicketPost
  • TicketPriority
  • TicketStatus
  • TicketTimeTrack
  • TicketType
  • User
  • UserGroup
  • UserOrganization

In the following chapters ObjectType in kyObjectType means one of the above object types.

Objects can be loaded (HTTP GET) from server (one object, all objects of certain type or filtered list of objects). An object can be created (HTTP POST), updated (HTTP PUT) and deleted (HTTP DELETE). Not all object types support all these actions. Refer to supported methods table and REST API Reference for information on actions available for each object type.

All files and classes of the client are prefixed with "ky", ex. kyDepartment.

Getting objects

The most basic ways to load objects of certain type from server are getting them all or getting them one by one using their identifiers. Identifier may be a single value or may consist of multiple values (composite identifier). Sometimes you can pass additional parameters to methods getting all objects or use some special methods.

Getting an object using its identifier (where possible)

$object = kyObjectType::get($id);

Getting an object using composite identifier (where needed)

$object = kyObjectType::get($id1, $id2);


Getting all objects of certain type (where possible)

$objects = kyObjectType::getAll();
foreach ($objects as $object) {
    $object->...
}

Getting list of objects filtered by server (where possible)

$objects = kyObjectType::getAll($param1, $param2);
foreach ($objects as $object) {
    $object->...
}

Searching for objects (where possible)

$objects = kyObjectType::search($param1, $param2);
foreach ($objects as $object) {
    $object->...
}

Refer to supported methods table for information on load methods available for each object type.

Result sets

Result sets are lists of objects of certain type and are returned by client methods when more than one object can be returned, for example:

//all getAll methods return result sets
$objects = kyObjectType::getAll();

//examples of other methods returning result sets (there are more)
$tickets = kyTicket::search($query);
$posts = $ticket->getPosts();
$notes = $ticket->getNotes();

Result sets can be iterated, counted and accessed like ordinary PHP arrays:

$objects = kyObjectType::getAll();

//iterate using foreach
foreach ($objects as $object) {
    print $object;
}

//iterate using for (count and array access used)
for ($i = 0; $i < count($objects); $i++) {
    print $objects[$i];
}

Sometimes (usually when you're sure that result set will contain only one object) you'll want to get the first object from result set:

$first_object = kyObjectType::getAll()->first();

Accessing object API fields

Available API fields are defined for each object type by Kayako REST API.

There are two possible ways of accessing object API fields. Recommended one, is to use public setters and getters of objects. Another way, is to access API fields directly by their names as they were object properties. Both these ways are described in the following chapters.

Available API fields

You can display available API fields for each object type using getAPIFields() static method.

print_r(kyObjectType::getAPIFields());

For example:

print_r(kyUserGroup::getAPIFields());

will output:

Array
(
    [id] => User group identifier. (getter: getId, setter: no setter, required: no, aliases: none)
    [title] => User group title. (getter: getTitle, setter: setTitle, required: create, update, aliases: none)
    [type] => User group type. (getter: getType, setter: setType, required: create, aliases: grouptype)
    [ismaster] => Whether this user group is master group (built-in). (getter: getIsMaster, setter: no setter, required: no, aliases: none)
)

This means that kyUserGroup objects has four API fields, exactly the same as described in Kayako REST API UserGroup reference:

  1. id: user group identifier
    • it can only be read
    • you can use getId() method to read it
  2. title: user group title
    • it can be read and written
    • you can use getTitle() method to read it and setTitle() to change it
    • you must set it to create or update an object
  3. type: user group type
    • it can be read and written
    • you can use getType() method to read it and setType() to change it
    • you must set it to create an object
    • it's accessible also using grouptype alias
  4. ismaster: whether this user group is master group (built-in)
    • it can only be read
    • you can use getIsMaster() method to read it

Accessing API fields using setters and getters

Setters are object methods beginning with set keyword, and they are used to change object API fields. Getters, on the contrary, are used to read object API fields and they begin with keyword get. Available objects setters and getters names are, in most cases, based on API field names. So for example, to read usergroupid value of User object, getUserGroupId() method should be called on kyUser instance.

There are also some additional setters and getters used for automatic loading of related objects. For example, to get instance of kyUserGroup associated with kyUser instance, getUserGroup() method can be used. In this chapter, however, we're focusing on basic methods used to read or write object API fields.

To discover available methods you can:

  • print available API fields,
  • use some development environment with code completion support (ex. Eclipse PDT),
  • read source code documentation placed in doc subdirectory of Kayako PHP Library package.
  • look inside the source code of Kayako PHP Library, all methods are described there.
//load an object
$object = kyObjectType::get($id);

//read object field value
$value = $object->getSomeField();

//set object field value
$object->setSomeField($value);

//set values of object fields using methods chaining
$object
    ->setSomeField1($value)
    ->setSomeField2($value)
    ->setSomeField3($value);

When dealing with result sets, you can get API field values of all objects in result set into an array with collect methods. Collect methods names are constructed from get method names of objects within result set - the word get is replaced by word collect:

$some_values = kyObjectType::getAll()->collectSomeField();

//this is the same as above
$some_values = array();
foreach (kyObjectType::getAll() as $object) {
    $some_values[] = $object->getSomeField();
}

Examples:

//get titles of all departments
$department_titles = kyDepartment::getAll()->collectTitle();

//get identifiers of all staff users
$staff_ids = kyStaff::getAll()->collectId();

Accessing API fields as properties

For those who still use Notepad for programming or don't feel comfortable with looking through the Library source code, nor reading some additional documentation to find proper setter or getter, there is another way of accessing object API fields. You can read or write object API fields directly as they were object properties. So, for example to read User's usergroupid field value you can get it directly by calling its name on kyUser instance. The Library will silently call proper setter or getter for this property.

//load an object
$object = kyObjectType::get($id);

//read object field value
$value = $object->somefield;

//set object field value
$object->somefield = $value;

If you try to read write-only field or write read-only field the operation will be ignored and User Notice will be issued.

Creating objects

When creating object some of its fields may be mandatory. Please refer to REST API Reference for further information or display API fields available for each object type and their description.

An object can be created in several ways but one thing is common for all of them - you must call object's create() or save() method in the end to actually send the data to your Kayako server.

Creating an object using constructor and bunch of set method calls

$new_object = new kyObjectType();
$new_object->setSomeMandatoryParam1($mandatory_param_1);
$new_object->setSomeMandatoryParam2($mandatory_param_2);
$new_object->setSomeNotMandatoryParam1($not_mandatory_param1)
$new_object->create();

Creating an object using methods chaining

$new_object = kyObjectType::createNew()
    ->setSomeMandatoryParam1($mandatory_param_1)
    ->setSomeMandatoryParam2($mandatory_param_2)
    ->setSomeNotMandatoryParam1($not_mandatory_param1)
    ->save();

Creating an object using shurtcut methods (if defined)

$new_object = kyObjectType::createNew($mandatory_param_1, $mandatory_param_2)
    ->setSomeNotMandatoryParam1($not_mandatory_param1)
    ->create();

Creating an object using relations between objects (as defined)

$object = kyObjectType::get(1);
$new_object = $object->newRelated($mandatory_param_1, $mandatory_param_2)
    ->setSomeNotMandatoryParam1($not_mandatory_param1)
    ->save();

Creating an object using other object as template

$object = kyObjectType::get(1);
$object->setSomeParam1($param1)->create();

Updating objects

You can only update objects that exists on server (were created before or loaded from server). To actually send updates to server you must call object's update() or save() method.

Updating an object without methods chaining

$object = kyObjectType::get($id);
$object->setSomeParam1($param1);
$object->setSomeParam2($param2);
$object->update();

Updating an object with methods chaining

$object = kyObjectType::get($id)
    ->setSomeParam1($param1)
    ->setSomeParam2($param2)
    ->save();

Deleting objects

You can only delete objects that exists on server (were created before or loaded from server). To delete an object you must simply call its delete() method. The request is immediately sent to Kayako server.

$object_to_delete->delete();

To delete all objects in result set, call its deleteAll() method. Be careful!.

$objects = kyObjectType::getAll();
$objects->deleteAll();

You can't restore deleted object as-it-was in any way, so use the delete method carefully.

Deleted object is still available in the client until the end of script, so if it's needed you can create a new object with the same parameters as the deleted one by simply calling the object's create() method.

$object->delete();
//create new object with the same parameters as deleted one
$object->create();

Object relations

Since there are some relations between Kayako objects (ex. user belongs to some group and organization) the client exposes methods which help to load related objects. Calling these methods usually involves sending a request to the server, but the client tries to cache related objects till the end of script.

Below are some examples of loading related objects:

//get group the user belongs to
$user_group = $user->getUserGroup();

//get organization the user belongs to
$user_organization = $user->getUserOrganization();

//get all ticket attachments, force reloading it from server (not using cached value), returns result set
$ticket_attachments = $ticket->getAttachments(true);

//get group of the staff
$staff_group = $staff->getStaffGroup(true);

Printing objects

For debugging purposes when developing your software which uses the client, you can print an object and a list of objects:

$object = kyObjectType::get(1);
print $object;

$objects = kyObjectType::getAll();
print $objects;

The output will contain object type, its identifier, basic info about the object and some of its properties.

Filtering, sorting and paging

The client implements client-side filtering, sorting and paging of result sets.

Remember that filtering, sorting and paging described in this chapter are executed by the client, not by the server.

Discovering available filters

Filter names are based on get method names defined in object type. To display available filters for an object type use:

print_r(kyObjectType::getAvailableFilterMethods());

For example calling:

//display filters available for ticket priorities
print_r(kyTicketPriority::getAvailableFilterMethods());

will output:

Array
(
    [0] => filterByTitle
    [1] => filterByDisplayOrder
    [2] => filterByForegroundColor
    [3] => filterByBackgroundColor
    [4] => filterByType
    [5] => filterByUserVisibilityCustom
    [6] => filterByUserGroupId
)

Simple filtering

You can filter result set by calling filter method on it and passing desired value or values. You can also combine multiple filters using methods chaining.

$objects = kyObjectType::getAll();

//filter objects
$filtered_objects = $objects
    ->filterBySomeFilter1(array($filter_value1, $filter_value2)) //works like $filter_value1 OR $filter_value2
    ->filterBySomeFilter2($filter_value3)
    ->filterBySomeFilter3($filter_value4);

//print filtered result set
print $filtered_objects;

Example:

//get priorities with title "Normal" or "High" visible only to user group with id = 1
$ticket_priorities = kyTicketPriority::getAll()
    ->filterByTitle(array("Normal", "High"))
    ->filterByUserVisibilityCustom(true)
    ->filterByUserGroupId(1);

//print the result set
print $ticket_priorities;

Advanced filtering

You can also filter using Perl regular expressions or relational operators. This is done by passing array with operator and value instead of simple value:

$objects = kyObjectType::getAll()
    ->filterBySomeFilter(array("operator", $value));

Available operators are:

~

match to Perl regular expression using filter value as pattern

>

match objects with values greater than filter value

>=

match objects with values greater than or equal to filter value

<

match objects with values lesser than filter value

<=

match objects with values lesser than or equal to filter value

!=

match objects with values other than filter value

Some examples:

//get tickets with word "help" inside subject
$tickets = kyTicket::getAll($department_id)
    ->filterBySubject(array("~", "/help/"));

//get ticket priorities with display order greater than 3 or lesser than 2
$ticket_priorities = kyTicketPriority::getAll()
    ->filterByDisplayOrder(array(array(">", 3), array("<", 2)));

//get ticket types other than "Issue"
$ticket_types = kyTicketType::getAll()
    ->filterByTitle(array("!=", "Issue"));

Removing filters

You can remove last used filter (one or more) or remove all filters to perform another filtering on the same result set.

//remove last filter from result set
$objects->removeFilter();

//remove three last filters from result set
$objects->removeFilter(3);

//remove all filters from result set
$objects->removeFilters();

Example:

//get public ticket priorities
$public_priorities = kyTicketPriority::getAll()
    ->filterByType(kyTicketPriority::TYPE_PUBLIC);

print $public_priorities;

//remove filtering by Public type and apply filtering by Private type
$private_priorities = $public_priorities
    ->removeFilter() //removes filterByType(kyTicketPriority::TYPE_PUBLIC)
    ->filterByType(kyTicketPriority::TYPE_PRIVATE);

print $private_priorities;

Discovering available sorting

Ordering method names are also based on get method names defined in object type. To display available ordering methods for an object type use:

print_r(kyObjectType::getAvailableOrderMethods());

For example calling:

//display order methods available for ticket priorities
print_r(kyTicketPriority::getAvailableOrderMethods());

will output:

Array
(
    [0] => orderByTitle
    [1] => orderByDisplayOrder
    [2] => orderByType
)

Sorting

You can sort objects in result sets by calling available order method. Optionally you can pass parameter indicating direction of sorting (true for ascending, false for descending):

$objects = kyObjectType::getAll();

//sort objects by some property ascending (default)
$sorted_objects_asc = $objects->orderBySomeProperty();

//sort the same objects descending
$sorted_objects_desc = $objects->orderBySomeProperty(false);

Objects can be sorted using only one order method at once, that is, effectively, only the last order method is used:

$objects = kyObjectType::getAll();

//both are the same
$sorted_objects = $objects->orderBySomeProperty1()->orderBySomeProperty2();
$sorted_objects = $objects->orderBySomeProperty2();

Example:

//print ticket priorities sorted by their display order
print kyTicketPriority::getAll()->orderByDisplayOrder();

Paging

Result sets include helper methods for paging results. Important parameter in these methods is maximum number of items per page. It's default value is 20 and it must be the same for all calls within paging context.

Page numbering starts from 1.

$objects = kyObjectType::getAll();

//get page count, assuming 10 items per page
$page_count = $objects->getPageCount(10);

//get first page, assuming 10 items per page
$first_page = $objects->getPage(1, 10);
$objects = kyObjectType::getAll();

//apply filtering, sorting and iterate over pages, assuming 20 items per page (the default)
$filtered_sorted_objects = $objects
    ->filterBySomeFilter($value1)
    ->orderBySomeProperty();

$pages = array();
for ($page_number =  1; $page_number <= $filtered_sorted_objects->getPageCount(); $page_number++) {
    $pages[$i] = $filtered_sorted_objects->getPage($page_number);
}

Usage Examples

Following usage examples assume that proper initialization of the client was performed. Examples were tested on Kayako Fusion On Demand Trial and make use of the basic data automatically created during server installation. Some examples uses data created in previous examples, so it's better to read and run them in presented sequence.

Creating department

//load General department
$general_department = kyDepartment::getAll()
    ->filterByTitle("General")
    ->filterByModule(kyDepartment::MODULE_TICKETS)
    ->first();

/**
 * Create subdepartment in General department:
 * title: Printers (example)
 * type: public (default)
 * module: tickets (default)
 */
$printers_department = $general_department
    ->newSubdepartment("Printers (example)")
    ->create();

/**
 * Create some livechat department:
 * title: Urgent problems (example)
 * type: public
 * module: livechat
 */
$livechat_department = kyDepartment::createNew("Urgent problems (example)", kyDepartment::TYPE_PUBLIC, kyDepartment::MODULE_LIVECHAT)
    ->create();

It's not currently possible to assign staff groups to departments via API. You must do it using Admin Control Panel.

Creating a staff user

/**
 * Create a staff group:
 * title: Lazy guys (example)
 * isadmin: false (default)
 */
$lazy_staff_group = kyStaffGroup::createNew("Lazy guys (example)")
    ->create();

/**
 * Create a staff user in just created staff group:
 * firstname: John
 * lastname: Doe
 * username: lazyguy
 * email: john.doe@lazycorp.com
 * password: veryhardpassword
 */
$staff_user = $lazy_staff_group
    ->newStaff("John", "Doe", "lazyguy", "john.doe@lazycorp.com", "veryhardpassword")
    ->setDesignation("useless specialist") //designation
    ->setSignature("Sorry I couldn't help you") //signature
    ->create();

//we forgot to set mobile number, let's update the staff user
$staff_user
    ->setMobileNumber("427 078 528") //mobilenumber
    ->update();

Creating a user

//load Registered user group
$registered_user_group = kyUserGroup::getAll()
    ->filterByTitle("Registered")
    ->first();

//load some user organization
$user_organization = kyUserOrganization::getAll()
    ->first();

/**
 * Create new user in Registered group:
 * fullname: Anno Ying
 * email: anno.ying@example.com
 * password: qwerty123
 */
$user = $registered_user_group
    ->newUser("Anno Ying", "anno.ying@example.com", "qwerty123")
    ->setUserOrganization($user_organization) //userorganizationid
    ->setSalutation(kyUser::SALUTATION_MR) //salutation
    ->setSendWelcomeEmail(false) //sendwelcomeemail
    ->create();

Creating a ticket

Following usage examples assume that ticket creation defaults was set before.

//find ticket priority with title "Urgent"
$priority_urgent = kyTicketPriority::getAll()
    ->filterByTitle("Urgent")
    ->first();

//create urgent ticket as the user created in previous step
$ticket = $user
    ->newTicket(
        $printers_department,
        "The printer on 4th floor in building B2 doesn't print at all. Fix it quickly, please.",
        "Printer not working (example)")
    ->setPriority($priority_urgent)
    ->create();

//get ticket display id
$ticket_display_id = $ticket->getDisplayId();

//print the ticket display id
printf("The ticket was created and its ID is: %s", $ticket_display_id);

If the user, who wants to report a problem, may not exist in your Kayako server, you can create a ticket only by providing user's name and e-mail.

//find ticket priority with title "Urgent"
$priority_urgent = kyTicketPriority::getAll()
    ->filterByTitle("Urgent")
    ->first();

/**
 * Create urgent ticket providing only name and e-mail of the user.
 * The user will be looked up based on the e-mail address. If none is found, the system will create a new user based on the information supplied.
 */
$ticket = kyTicket::createNewAuto(
        $printers_department,
        "Anno Ying",
        "anno.ying@example.com",
        "The printer on 4th floor in building B2 doesn't print at all. Fix it quickly, please.",
        "Printer not working (example)")
    ->setPriority($priority_urgent)
    ->create();

//get ticket display id
$ticket_display_id = $ticket->getDisplayId();

//print the ticket display id
printf("The ticket was created and its ID is: %s\n", $ticket_display_id);

Ticket processing

//load the ticket using its display id
$ticket = kyTicket::get($ticket_display_id);

//get the user that created the ticket
$user = $ticket->getUser();

//find ticket status with title "In Progress"
$status_in_progress = kyTicketStatus::getAll()
    ->filterByTitle("In Progress")
    ->first();

//find ticket status with title "Closed"
$status_closed = kyTicketStatus::getAll()
    ->filterByTitle("Closed")
    ->first();

//assign the staff user created before
$ticket
    ->setOwnerStaff($staff_user)
    ->update();

//add new post (staff user reply)
$ticket
    ->newPost($staff_user, "Did you switched the printer on?")
    ->create();

//change ticket status
$ticket
    ->setStatus($status_in_progress)
    ->update();

//add new post (user reply)
$user_reply_post = $ticket
    ->newPost($user, "Yes, of course! See attached photo of the printer.")
    ->create();

//add attachment to the post (for now using example image from Wikimedia Common)
$user_reply_post
    ->newAttachmentFromFile("http://upload.wikimedia.org/wikipedia/commons/0/0b/Canon_ir2270.jpg")
    ->create();

//add "note to myself"
$ticket->newNote($staff_user, "Power cable needs replacement.")
    ->create();

//add new post (staff user reply)
$ticket
    ->newPost($staff_user, "I think I know what's wrong. It will be fixed within half an hour.")
    ->create();

//change ticket status
$ticket
    ->setStatus($status_in_progress)
    ->update();

//add new post (user reply)
$ticket
    ->newPost($user, "Thank you. It's working now.")
    ->create();

//close the ticket
$ticket
    ->setStatus($status_closed)
    ->update();

Cleanup

Following code deletes all objects created by previous examples. It's better to cleanup, before running these examples again.

$example_department = kyDepartment::getAll()->filterByTitle("Printers (example)");
if (count($example_department) > 0) {
	kyTicket::getAll($example_department)
	    ->filterBySubject("Printer not working (example)")
	    ->deleteAll();
}

kyUser::getAll()
    ->filterByEmail("anno.ying@example.com")
    ->deleteAll();

kyStaff::getAll()
    ->filterByEmail("john.doe@lazycorp.com")
    ->deleteAll();

kyStaffGroup::getAll()
    ->filterByTitle("Lazy guys (example)")
    ->deleteAll();

kyDepartment::getAll()
    ->filterByTitle(array("Urgent problems (example)", "Printers (example)"))
    ->deleteAll();

Ticket custom fields

Since Ticket custom fields are updated with separate controller, it's not possible to create ticket with custom fields in one request to the server. So, creating ticket with custom fields requires following steps:

  1. Create a ticket (server won't complain about missing required custom fields).
  2. Inspect the ticket custom fields and set their values.
  3. Save the ticket (or save just custom field values).

To work with ticket custom fields, the ticket must exists on the server (it must be fetched from server or saved to server).

You must enabled User Editable field flag if you want to update field's value through API.

The code in following chapters assumes that some ticket is fetched from server into $ticket variable.

Knowing your custom fields

Custom fields are grouped into custom field groups. The easiest way to inspect ticket custom fields is to print them:

/**
 * Print all ticket custom fields.
 */
print $ticket->getCustomFields();

/**
 * Pretty print all ticket custom fields.
 * Be careful with big files.
 */
$field_groups = $ticket->getCustomFieldGroups();
foreach ($field_groups as $field_group) {
	printf("%s:\n", $field_group->getTitle());
	foreach ($field_group->getFields() as $field) {
		switch ($field->getType()) {
			case kyCustomFieldDefinition::TYPE_DATE:
				printf("%s (%s): %s\n", $field->getTitle(), $field->getName(), $field->getDate());
				break;
			case kyCustomFieldDefinition::TYPE_CHECKBOX:
			case kyCustomFieldDefinition::TYPE_MULTI_SELECT:
				printf("%s (%s):\n%s\n", $field->getTitle(), $field->getName(), '- '.implode("\n- ", $field->getValues()));
				break;
			case kyCustomFieldDefinition::TYPE_FILE:
				printf("%s (%s): %s (%d)\n%s\n", $field->getTitle(), $field->getName(), $field->getFileName(), strlen($field->getContents()), $field->getContents());
				break;
			default:
				printf("%s (%s): %s\n", $field->getTitle(), $field->getName(), $field->getRawValue());
				break;
		}
	}
}

The two most important custom field parameters are its type and its name. The Library choose proper class when creating custom field instance based on custom field type. The custom field name is used to load proper field instance from custom fields collection.

foreach ($ticket->getCustomFields() as $custom_field) {
    //get field type
    $custom_field_type = $custom_field->getType();

    //get field name
    $custom_field_name = $custom_field->getName();

	switch ($custom_field_type) {
        case kyCustomFieldDefinition::TYPE_TEXT:
        case kyCustomFieldDefinition::TYPE_TEXTAREA:
        case kyCustomFieldDefinition::TYPE_PASSWORD:
        case kyCustomFieldDefinition::TYPE_CUSTOM:
            //plain text field, kyCustomField class
		break;

        case kyCustomFieldDefinition::TYPE_RADIO:
        case kyCustomFieldDefinition::TYPE_SELECT:
            //field with options and single option as value, kyCustomFieldSelect class
		break;

        case kyCustomFieldDefinition::TYPE_LINKED_SELECT:
            //field with options and single option as value that has parent option specified, kyCustomFieldLinkedSelect class
		break;

        case kyCustomFieldDefinition::TYPE_CHECKBOX:
        case kyCustomFieldDefinition::TYPE_MULTI_SELECT:
            //field with options and multiple options as value, kyCustomFieldMultiSelect class
		break;

        case kyCustomFieldDefinition::TYPE_DATE:
            //date field, kyCustomFieldDate class
		break;

        case kyCustomFieldDefinition::TYPE_FILE:
            //file field, kyCustomFieldFile class
		break;
	}
}

It's good idea to inspect the client source code for possible methods which can be used with custom fields. Below are some examples:

//get field by name
$custom_field = $ticket->getCustomField('<custom field name>');

//get its type (kyCustomFieldDefinition::TYPE_* constants.
$custom_field_type = $custom_field->getType();

//get field definition
$custom_field_definition = $custom_field->getDefinition();

//get field description
$custom_field_description = $custom_field->getDefinition()->getDescription();

//is this field required?
$is_required = $custom_field->getDefinition()->getIsRequired();

//get the field default value (applicable for text fields)
$is_required = $custom_field->getDefinition()->getDefaultValue();

//get field possible options (applicable for Radio, Select, Linked Select, Checkbox, Multi Select fields)
$custom_field_options = $custom_field->getDefinition()->getOptions();

//get the field options selected by default
$custom_field_default_options = $custom_field->getDefinition()->getDefaultOptions();

//get field option with specific value
$custom_field_option = $custom_field->getOption('Radio 1');

//get field option with specific id
$custom_field_option = $custom_field->getOption(10);

Getting custom field value

To get the value of single field you can use one of the following methods:

//get value in one shot
$custom_field_value = $ticket->getCustomFieldValue('<custom field name>');

//get field, then value
$custom_field = $ticket->getCustomField('<custom field name>');
$custom_field_value = $custom_field->getValue();

The interpretation of custom field value while getting it, depends on its type:

kyCustomFieldDefinition::TYPE_TEXT

plain text value

kyCustomFieldDefinition::TYPE_TEXTAREA

plain text value

kyCustomFieldDefinition::TYPE_PASSWORD

plain text value

kyCustomFieldDefinition::TYPE_CUSTOM

plain text value

kyCustomFieldDefinition::TYPE_RADIO

kyCustomFieldOption object

kyCustomFieldDefinition::TYPE_SELECT

kyCustomFieldOption object

kyCustomFieldDefinition::TYPE_LINKED_SELECT

kyCustomFieldOption object

kyCustomFieldDefinition::TYPE_CHECKBOX

array of kyCustomFieldOption objects

kyCustomFieldDefinition::TYPE_MULTI_SELECT

array of kyCustomFieldOption objects

kyCustomFieldDefinition::TYPE_DATE

date formatted according to the configured default date format

kyCustomFieldDefinition::TYPE_FILE

array with file name as the first element and file contents as the second element

It's good idea to inspect the client source code for other possible methods which can be used to get custom fields values. Below are some examples:

//file field
$file_custom_field = $ticket->getCustomField('<file custom field name>');
$file_name = $file_custom_field->getFileName();
$file_contents = $file_custom_field->getContents();

//date field
$date_custom_field = $ticket->getCustomField('<date custom field name>');
$date_formatted = $date_custom_field->getDate('d-m-Y');
$date_timestamp = $date_custom_field->getTimestamp();

//select field
$select_custom_field = $ticket->getCustomField('<select custom field name>');
$selected_option = $select_custom_field->getSelectedOption();

//multiple select field
$multi_select_custom_field = $ticket->getCustomField('<multi select custom field name>');
$selected_options = $multi_select_custom_field->getSelectedOptions();

Setting custom field value

To update ticket custom field value, the field name is needed. Two main ways of setting custom fields values are:

$ticket->setCustomFieldValue('<custom field name>', $value);

$ticket->getCustomField('<custom field name>')->setValue($value);

The interpretation of custom field value while setting it, depends on its type:

kyCustomFieldDefinition::TYPE_TEXT

plain text value

kyCustomFieldDefinition::TYPE_TEXTAREA

plain text value

kyCustomFieldDefinition::TYPE_PASSWORD

plain text value

kyCustomFieldDefinition::TYPE_CUSTOM

plain text value

kyCustomFieldDefinition::TYPE_RADIO

field option value OR field option id OR kyCustomFieldOption object

kyCustomFieldDefinition::TYPE_SELECT

field option value OR field option id OR kyCustomFieldOption object

kyCustomFieldDefinition::TYPE_LINKED_SELECT

field child option value OR field child option id OR kyCustomFieldOption object of child select

kyCustomFieldDefinition::TYPE_CHECKBOX

array of: field option values OR field option identifiers OR kyCustomFieldOption objects

kyCustomFieldDefinition::TYPE_MULTI_SELECT

array of: field option values OR field option identifiers OR kyCustomFieldOption objects

kyCustomFieldDefinition::TYPE_DATE

date in format understood by PHP strtotime

kyCustomFieldDefinition::TYPE_FILE

full path to file

Examples using setValue method:

//text field
$ticket->setCustomFieldValue('<some text field name>', 'text value');

//textarea field
$ticket->getCustomField('<some textarea field name>')->setValue("multiline\ntext\nvalue");

//password field
$ticket->setCustomFieldValue('<some password field name>', "password");

//checkbox field
$ticket->setCustomFieldValue('<some checkbox field name>', array('Checkbox 2', 'Checkbox 3'));

//radio field
$ticket->setCustomFieldValue('<some radio field name>', "Radio 3");
$ticket->getCustomField('<some other radio field name>')->setValue(<field option id>);

//multi select field
$ticket->setCustomFieldValue('<some multiselect field name>', array(<field option id>, <field option id>));

//select field
$ticket->setCustomFieldValue('<some select field name>', "Select 3");

//custom field
$ticket->getCustomField('<some date field name>')->setValue('2011-12-06');

//file field
$ticket->setCustomFieldValue('<some file field name>', '/var/www/kayako/kyIncludes.php');

It's good idea to inspect the client source code for possible methods which can be used to set custom fields values. Below are some examples:

//file field
$file_custom_field = $ticket->getCustomField('<file custom field name>');
$file_custom_field->setFileName('filename.txt');
$file_custom_field->setContents('file contents');
$file_custom_field->setContentsFromFile('/path/to/file.txt', 'another_name.txt');

//date field
$date_custom_field = $ticket->getCustomField('<date custom field name>');
$date_custom_field->setDate('12-02-2012');
$date_custom_field->setTimestamp(strtotime("+3 months"));

//select field
$select_custom_field = $ticket->getCustomField('<select custom field name>');
$select_custom_field->setSelectedOption($select_custom_field->getOption('Select 2'));

//multiple select field
$multi_select_custom_field = $ticket->getCustomField('<multi select custom field name>');
$multi_select_custom_field->setSelectedOptions($multi_select_custom_field->getDefinition()->getDefaultOptions());

If you created your own form to set or update custom field values then you can use following method to update custom field values using POST data from submitted form:

/**
 * Set custom fields values from current request POST data.
 */
$ticket->setCustomFieldValuesFromPOST();

Saving custom fields to server

To send custom fields values to server you can following methods:

/**
 * Update ticket data and custom fields on server.
 */
$ticket->update();

/**
 * Update only ticket custom fields on server.
 */
$ticket->updateCustomFields();

File custom fields will be sent only when changed.

Performing a ticket search

Ticket search using getAll

/**
 * Search for open tickets in departments with (caseless) "printer" inside of title,
 * which were created by user with e-mail anno.ying@example.com.
 */
$tickets = kyTicket::getAll(
    kyDepartment::getAll()
        ->filterByTitle(array("~", "/printer/i")),
    kyTicketStatus::getAll()
        ->filterByTitle(array("!=", "Closed")),
    array(),
    kyUser::getAll()
        ->filterByEmail("anno.ying@example.com")
);

//print them
print $tickets;

Ticket search using TicketSearch controller

/**
 * Search for tickets with "power cable" text in contents of posts or notes.
 */
$tickets = kyTicket::search("power cable", array(kyTicket::SEARCH_CONTENTS, kyTicket::SEARCH_NOTES));

//print them
print $tickets;

Ticket search using client-side filtering

/**
 * Search for open and assigned tickets with no replies in all departments.
 * WARNING: Can be time consuming.
 */
$tickets = kyTicket::getAll(kyDepartment::getAll())
    ->filterByStatusId(kyTicketStatus::getAll()
        ->filterByTitle(array("!=", "Closed"))->collectId())
    ->filterByReplies(array('<=', 1))
    ->filterByOwnerStaffId(array("!=", null));

//print them
print $tickets;

Sample HTML form for ticket submission

Sample HTML/PHP script featuring complete ticket submission with custom fields is included with the client in file examples/ticket_form.php. To use it you must set configuration data at the top of this file:

//name of ticket status which should be assigned to newly created tickets
define('DEFAULT_TICKET_STATUS_NAME', 'Open');

//Kayako REST API URL (Admin CP -> REST API -> API Information)
define('BASE_URL', '<API URL>');

//Kayako API Key (Admin CP -> REST API -> API Information)
define('API_KEY', 'API Key');

//Kayako Secret Key (Admin CP -> REST API -> API Information)
define('SECRET_KEY', '<Secret Key>');

//true to output HTTP requests and responses to PHP error log, false to disable debugging
define('DEBUG', true);

//true to send controller as URL query, false to send controller in URL path (required for Kayako OnDemand)
define('CONTROLLER_AS_QUERY', true);

//name of the user group that should be used to prepare the list of available ticket types and ticket priorities
define('USER_GROUP_TITLE', 'Registered');

Then upload complete client directory to your web server document root and navigate to

http://<your web server url>/<client directory>/examples/ticket_form.php

.

Common Problems

Creating department

  1. HTTP error: 400
    • You are trying to create subdepartment with different module than parent department.

Creating ticket

  1. HTTP error: 400

Updating or deleting objects

  1. HTTP error: 405 Not Allowed

Custom fields

  1. Custom field value is not updated
    • make sure that User Editable flag is enabled for the custom field.

Other problems

  1. Enable client debug mode and review PHP logs for more information.
  2. Ask for help on Kayako Forums.

Supported Methods

API

Get all

Get (GET)

Create (POST)

Update (POST)

Delete (DELETE)

CustomField

kyCustomFieldDefinition::getAll()

N/A

N/A

N/A

N/A

Department

kyDepartment::getAll()

kyDepartment::get($id)

Yes

Yes

Yes

Staff

kyStaff::getAll()

kyStaff::get($id)

Yes

Yes

Yes

StaffGroup

kyStaffGroup::getAll()

kyStaffGroup::get($id)

Yes

Yes

Yes

Ticket

kyTicket::getAll($departments, $ticket_statuses, $owner_staffs, $users)

kyTicket::get($id)

Yes

Yes

Yes

TicketAttachment

kyTicketAttachment::getAll($ticket_id)

kyTicketAttachment::get($ticket_id, $id)

Yes

N/A

Yes

TicketCustomField

kyTicketCustomFieldGroup::getAll($ticket_id)

N/A

$ticket->updateCustomFields()

N/A

N/A

TicketCount

kyTicket::getStatistics()

N/A

N/A

N/A

N/A

TicketNote

kyTicketNote::getAll($ticket_id)

kyTicketNote::get($ticket_id, $id)

Yes

N/A

Yes

TicketPost

kyTicketPost::getAll($ticket_id)

kyTicketPost::get($ticket_id, $id)

Yes

N/A

Yes

TicketPriority

kyTicketPriority::getAll()

kyTicketPriority::get($id)

N/A

N/A

N/A

TicketSearch

kyTicket::search($query, $areas)

N/A

N/A

N/A

N/A

TicketStatus

kyTicketStatus::getAll()

kyTicketStatus::get($id)

N/A

N/A

N/A

TicketTimeTrack

kyTicketTimeTrack::getAll($ticket_id)

kyTicketTimeTrack::get($ticket_id, $id)

Yes

N/A

Yes

TicketType

kyTicketType::getAll()

kyTicketType::get($id)

N/A

N/A

N/A

User

kyUser::getAll($starting_user_id, $max_items)

kyUser::get($id)

Yes

Yes

Yes

UserGroup

kyUserGroup::getAll()

kyUserGroup::get($id)

Yes

Yes

Yes

UserOrganization

kyUserOrganization::getAll()

kyUserOrganization::get($id)

Yes

Yes

Yes

UserSearch

kyUser::search($query)

N/A

N/A

N/A

N/A

  • No labels