### Custom View Setup Handler Example
Source: https://docs.espocrm.com/development/frontend/view-setup-handlers
Implement a custom view setup handler. The `process` method can contain logic executed after view rendering or model changes. It can optionally return a Promise to control view rendering flow.
```javascript
define('custom:some-handler', [], () => {
class Handler {
/**
* @param {import('view').default} view
*/
constructor(view) {
this.view = view;
}
process() {
this.listenTo(this.view, 'after:render', () => {
// Do something with view after render.
});
this.view.listenTo(this.view.model, 'change', () => {});
}
}
// Establish event support. If needed.
Object.assign(Handler.prototype, Backbone.Events);
return Handler;
});
```
--------------------------------
### Basic API Client Usage and Requests
Source: https://docs.espocrm.com/development/api-client-php
Demonstrates how to initialize the API client, set an API key, and make POST and GET requests to the EspoCRM API. Includes examples for creating a Lead and retrieving Opportunities.
```php
use Espo\ApiClient\Client;
$client = new Client('https://your-espocrm-site');
$client->setApiKey('API_KEY');
// The second parameter is the path.
$response = $client->request(Client::METHOD_POST, 'Lead', [
'firstName' => 'Test',
'lastName' => 'Hello',
]);
$response = $client->request(Client::METHOD_GET, 'Opportunity', [
'maxSize' => 10,
'select' => 'id,name,assignedUserId',
'orderBy' => 'createdAt',
'order' => 'desc',
'primaryFilter' => 'open',
]);
$parsedBody = $response->getParsedBody();
$fileContents = $client->request(Client::METHOD_GET, "Attachment/file/$attachmentId")
->getBodyPart();
```
--------------------------------
### EspoCRM API Client Usage Example in Java
Source: https://docs.espocrm.com/development/api-client-java
Demonstrates how to build an EspoApiClient instance, configure request parameters including filters and sorting, and make a GET request to the EspoCRM API. Ensure you replace placeholder keys and host with your actual credentials.
```java
import java.io.IOException;
import java.security.InvalidKeyException;
import dev.array21.espocrm.client.ClientBuilder;
import dev.array21.espocrm.client.EspoApiClient;
import dev.array21.espocrm.client.RequestException;
import dev.array21.espocrm.types.Where;
import dev.array21.espocrm.types.FilterType;
import dev.array21.espocrm.types.Method;
import dev.array21.espocrm.types.Params;
public class ExampleClass {
public static void main(String[] args) {
EspoApiClient client = new ClientBuilder()
.setHost("YOUR ESPOCRM HOST")
.setApiKey("YOUR ESPOCRM API KEY")
.setSecretKey("YOUR ESPOCRM SECRET KEY") // for HMAC method
.build();
Where[] whereFilter = new Where[] {
new Where(FilterType.EQUALS, "SomeEspoCrmField").setValue("itMustBeEqualToThis")
}
Params requestParams = new Params()
.setOffset(0)
.setMaxSize(50)
.setSelect("id")
.setOrderBy("id")
.setOrder(Order.DESC)
.setWhere(whereFilter);
try {
String jsonResponse = client.requestGet("Account", requestParams);
} catch(InvalidKeyException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(RequestException e) {
e.printStackTrace();
}
}
}
```
--------------------------------
### Example GET API Request
Source: https://docs.espocrm.com/development/api
Demonstrates a basic GET request to retrieve a specific contact record. The site URL and API version path are omitted in this example.
```http
GET https://address_of_your_crm/api/v1/Contact/55643ca033f7ab4c5
```
--------------------------------
### Making a List GET Request
Source: https://docs.espocrm.com/development/api-client-go
Example of making a list GET request to retrieve multiple records, with an option to set query parameters like filtering.
```go
import "github.com/definitepotato/espocrm"
parameters := espocrm.NewParameters(
espocrm.SetWhere([]espocrm.Where{
{
Type: espocrm.Equals,
Attribute: "myAttribute",
Value: "myValue",
},
}),
)
client := espocrm.NewApiClient(
"https://espocrm.example.com",
espocrm.WithApiKeyAuth("Your API Key here"),
)
contacts, err := client.List("Contact", parameters)
```
--------------------------------
### Python API Client Example
Source: https://docs.espocrm.com/development/api-tutorial
This snippet shows how to initialize and use the EspoCRM API client in Python for GET requests. Make sure to install the 'requests' package.
```python
from espo_api_client import EspoAPI
client = EspoAPI('https://address-of-your-espocrm', 'paste_api_key_here')
params = {
"select": "id,phoneNumber",
"where": [
{
"type": "equals",
"attribute": "emailAddress",
"value": 'some@email.com',
},
],
}
result = client.request('GET', 'Lead', params)
```
--------------------------------
### Example Espo.Ajax GET Request
Source: https://docs.espocrm.com/development/frontend/ajax
An example of making a GET request to retrieve specific data by ID. The response is parsed and logged to the console.
```javascript
Espo.Ajax.getRequest('MyController/action/getSomeDataById', {id: id})
.then(response => {
// A parsed response.
console.log(response);
});
```
--------------------------------
### Install Composer Dependencies
Source: https://docs.espocrm.com/development/how-to-start
Run this command in the project's root directory to install Composer dependencies. Use '--ignore-platform-reqs' if some PHP extensions are missing.
```bash
php composer.phar install --ignore-platform-reqs
```
```bash
composer install --ignore-platform-reqs
```
--------------------------------
### Install Espo API Client with Composer
Source: https://docs.espocrm.com/development/api-client-php
Install the EspoCRM PHP API client using Composer. Ensure you have Composer installed and configured.
```bash
composer require espocrm/php-espo-api-client
```
--------------------------------
### PHP Script for Post-Installation Configuration
Source: https://docs.espocrm.com/development/extension-packages
An example of a PHP script executed after an extension is installed. This script modifies the CRM's configuration to add a custom entity tab.
```php
getByClass(Config::class);
$configWriter = $container->getByClass(InjectableFactory::class)
->create(ConfigWriter::class)
$tabList = $config->get('tabList') ?? [];
if (!in_array('MyCustomEntity', $tabList)) {
$tabList[] = 'MyCustomEntity';
$configWriter->set('tabList', $tabList);
}
$configWriter->save();
}
}
```
--------------------------------
### Controller with API Action Example
Source: https://docs.espocrm.com/development/api-action
Example of a controller with a PUT action for updating a record, demonstrating dependency injection and request handling.
```php
getRouteParam('id');
$data = $request->getParsedBody();
$result = $this->someDependency->doSomething($id, $data);
// Response can be returned or written with `Response::writeBody`.
return $result->toStdClass();
}
}
```
--------------------------------
### Controller Example
Source: https://docs.espocrm.com/development/api-action
Demonstrates how to map routes to controller actions, providing an alternative to using dedicated action classes.
```APIDOC
## GET /Hello/test/:id
### Description
This route triggers the `doSomething` action within the `MyController` class, passing the `id` from the route.
### Method
GET
### Endpoint
/Hello/test/:id
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID from the route.
#### Request Body
- **controller** (string) - Required - Set to 'MyController'.
- **action** (string) - Required - Set to 'doSomething'.
- **id** (string) - Required - The ID from the route, passed as a parameter.
## POST /HelloWorld/:name
### Description
This route triggers the `helloWorld` action within the `MyController` class, passing the `name` from the route.
### Method
POST
### Endpoint
/HelloWorld/:name
### Parameters
#### Path Parameters
- **name** (string) - Required - The name from the route.
#### Request Body
- **controller** (string) - Required - Set to 'MyController'.
- **action** (string) - Required - Set to 'helloWorld'.
- **name** (string) - Required - The name from the route, passed as a parameter.
```
--------------------------------
### Example Dashlet Access Configuration
Source: https://docs.espocrm.com/development/metadata/dashlets
An example of how to configure the 'accessDataList' for a dashlet, specifically disabling it for portal users.
```json
{
"accessDataList": [
{
"inPortalDisabled": true
}
]
}
```
--------------------------------
### Defining View Setup Handlers in clientDefs
Source: https://docs.espocrm.com/development/frontend/view-setup-handlers
Configure view setup handlers by specifying handler names for different view types within the clientDefs configuration. Use `__APPEND__` to extend existing handler lists.
```json
{
"viewSetupHandlers": {
"list": [
"__APPEND__",
"custom:some-handler-1"
],
"record/search": [
"__APPEND__",
"custom:some-handler-2"
]
}
}
```
--------------------------------
### Instantiate Collection with Factory
Source: https://docs.espocrm.com/development/collection
Demonstrates instantiating a collection using a factory, typically in a View setup. It waits for the collection to be fetched.
```javascript
export default class extends View {
setup() {
this.wait(this.loadCollection());
}
async loadCollection() {
this.collection = await this.getCollectionFactory().create('Account');
await this.collection.fetch();
}
}
```
--------------------------------
### Custom TargetList Hook Example
Source: https://docs.espocrm.com/development/hooks
Example of a custom hook for the TargetList entity, demonstrating the afterOptOut method.
```php
{
return class extends SidePanelView {
templateContent = '
{{viewObject.someKey}}
'
setup() {
this.someKey = 'Hello';
}
}
});
```
--------------------------------
### Custom Controller Example
Source: https://docs.espocrm.com/development/api-action
Example of a custom controller with a PUT action to update a record. Dependencies are injected via the constructor.
```APIDOC
## PUT api/v1/MyModule/MyController/update/{id}
### Description
Updates a record using the provided data.
### Method
PUT
### Endpoint
`/api/v1/MyModule/MyController/update/{id}`
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID of the record to update.
#### Request Body
- **(object)** - Required - The data to update the record with.
### Request Example
```json
{
"field1": "value1",
"field2": "value2"
}
```
### Response
#### Success Response (200)
- **(object)** - The updated record data.
#### Response Example
```json
{
"id": "123",
"field1": "value1",
"field2": "value2"
}
```
```
--------------------------------
### Example routes.json Configuration
Source: https://docs.espocrm.com/development/api-action
Defines custom API routes with methods, action class names, and optional parameters like noAuth.
```json
[
{
"route": "/MyAction",
"method": "get",
"actionClassName": "Espo\\Modules\\MyModule\\Api\\GetMyAction"
},
{
"route": "/MyScope/:id/something",
"method": "post",
"actionClassName": "Espo\\Modules\\MyModule\\Api\\PostMyScopeSomething"
},
{
"route": "/TestNoAuth",
"method": "get",
"params": {
"myParam1": "MyValue1",
"myParam2": "MyValue2"
},
"noAuth": true
}
]
```
--------------------------------
### Field Definition Example
Source: https://docs.espocrm.com/development/metadata/entity-defs
An example of defining a field with its type and custom parameters.
```json
{
"fields": {
"myField": {
"type": "varchar",
"someParam": "someValue"
}
}
}
```
--------------------------------
### Build EspoCRM
Source: https://docs.espocrm.com/development/how-to-start
Run Grunt to build the project. This includes transpiling Javascript and installing Composer dependencies by default. Use 'grunt offline' to skip Composer dependency installation.
```bash
grunt
```
```bash
grunt offline
```
--------------------------------
### Route Parameters Example
Source: https://docs.espocrm.com/development/api-action
Shows how to define and use route parameters that are passed to the action class, allowing for flexible routing configurations.
```APIDOC
## GET Account/:id/myItems
### Description
This route fetches items for a specific Account record. It uses a common action class `Espo\Modules\MyModules\Api\GetItems` but specifies the `entityType` as 'Account' via route parameters.
### Method
GET
### Endpoint
/Account/:id/myItems
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID of the Account record.
- **entityType** (string) - Required - Set to 'Account', passed to the action class.
## GET Contact/:id/myItems
### Description
This route fetches items for a specific Contact record. It uses the same action class `Espo\Modules\MyModules\Api\GetItems` but specifies the `entityType` as 'Contact'.
### Method
GET
### Endpoint
/Contact/:id/myItems
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID of the Contact record.
- **entityType** (string) - Required - Set to 'Contact', passed to the action class.
```
--------------------------------
### App Cleanup Configuration Example
Source: https://docs.espocrm.com/development/metadata/app-cleanup
A Key-Value map defining cleanup classes. This configuration is used by the Cleanup job.
```json
{
"someName": {
"className": "Espo\\SomeImplementation"
}
}
```
--------------------------------
### Initialize EspoAPI Client
Source: https://docs.espocrm.com/development/api-client-python
Instantiates the EspoAPI client with the CRM URL and API key. Ensure the 'requests' package is installed.
```python
from espo_api_client import EspoAPI
client = EspoAPI('https://address-of-your-espocrm', 'paste_api_key_here')
```
--------------------------------
### Example Entity Template List
Source: https://docs.espocrm.com/development/metadata/app-entity-template-list
A sample list of entity templates available in EspoCRM's Entity Manager.
```json
[
"Base",
"BasePlus",
"Event",
"Person",
"Company"
]
```
--------------------------------
### Making a GET Request with Parameters
Source: https://docs.espocrm.com/development/api-client-rust
Construct and execute a GET request to the EspoCRM API using the EspoApiClient. Supports setting parameters like offset and complex 'where' clauses.
```rust
use espocrm_rs::{EspoApiClient, Params, Where, FilterType, Value, NoGeneric};
use reqwest::Method;
let params = Params::default()
.set_offset(0)
.set_where(vec![
Where {
r#type: FilterType::IsTrue,
attribute: "exampleField".to_string(),
value: None
},
Where {
r#type: FilterType::ArrayAnyOf,
attribute: "exampleField2".to_string(),
value: Some(Value::array(vec![
Value::str("a"),
Value::str("b"),
Value::str("c")
]))
}
])
.build();
let client = EspoApiClient::new("https://espocrm.example.com")
.set_secret_key("Your Secret Key")
.set_api_key("Your api key")
.build();
let result = client.request::(Method::GET, "Contact".to_string(), Some(params), None);
```
--------------------------------
### Constructor Injection Example
Source: https://docs.espocrm.com/development/di
Demonstrates constructor injection where services are resolved by binding or parameter name, and non-services are instantiated on demand.
```php
$options
*/
public function beforeSave(Entity $entity, array $options): void
{
if ($entity->isNew() && !$entity->get('accountName')) {
$entity->set('accountName', 'No Account');
}
}
}
```
--------------------------------
### Export Format List Example
Source: https://docs.espocrm.com/development/metadata/scopes
Specifies the allowed export formats for an entity.
```json
{
"exportFormatList": ["csv"]
}
```
--------------------------------
### Controller Example
Source: https://docs.espocrm.com/development/services
A controller class that injects a service and calls its method to perform business logic.
```PHP
getParsedBody();
$id = $data->id ?? null;
if (!$id) {
throw new BadRequest();
}
$this->myService->doSomething($id);
$response->writeBody('true');
}
}
```
--------------------------------
### Layout Availability List Example
Source: https://docs.espocrm.com/development/metadata/entity-defs
Specifies the layout types for which the field is available. An empty array disables it in all layouts.
```json
{
"layoutAvailabilityList": [
"list",
"detail"
]
}
```
--------------------------------
### Initialize and Make API Requests
Source: https://docs.espocrm.com/development/api-client-js
Demonstrates how to initialize the API client with credentials and make POST and GET requests to the EspoCRM API. Includes basic error handling.
```javascript
const Client = require('./espocrm-api-client');
const client = new Client(
'https://your-espocrm-site',
'API_KEY',
'SECRET_KEY' // optional, if hmac auth is used
);
// POST example
const payload = {
name: 'Some name',
};
client
.request('POST', 'Account', payload)
.then(response => {
// success
console.log(response);
})
.catch(response => {
// error
console.log(response.statusCode, response.statusMessage);
});
// GET example
const params = {
maxSize: 5,
where: [
{
type: 'equals',
attribute: 'type',
value: 'Customer',
},
],
select: ['id', name'],
};
client
.request('GET', 'Account', params)
.then(response => {
console.log(response);
})
.catch(response => {
// error
console.log(response.statusCode, response.statusMessage);
});
```
--------------------------------
### GET Contact by ID
Source: https://docs.espocrm.com/development/api
Retrieves a specific contact record by its unique identifier. This is an example of a GET request to fetch a single entity.
```APIDOC
## GET /api/v1/Contact/{id}
### Description
Retrieves a specific contact record by its unique identifier.
### Method
GET
### Endpoint
/api/v1/Contact/{id}
### Parameters
#### Path Parameters
- **id** (string) - Required - The unique identifier of the contact to retrieve.
### Response
#### Success Response (200)
- **(object)** - The contact record details.
### Response Example
{
"example": "{\"id\": \"55643ca033f7ab4c5\", \"name\": \"John Doe\", ...}"
}
```
--------------------------------
### Initialize API Client with Basic Authentication
Source: https://docs.espocrm.com/development/api-client-go
Initialize the API client using Basic Authentication. This method is highly discouraged due to security risks.
```go
import "github.com/definitepotato/espocrm"
client := espocrm.NewApiClient(
"https://espocrm.example.com",
espocrm.WithBasicAuth("username", "password"),
)
```
--------------------------------
### Factory Example with Explicit Dependency
Source: https://docs.espocrm.com/development/di
A factory class that uses `createWith` to instantiate a `SomeType` and inject a `userId` parameter.
```php
injectableFactory->createWith(SomeType::class, [
'userId' => $userId,
]);
}
}
```
--------------------------------
### Extending Account Controller
Source: https://docs.espocrm.com/development/api-action
Example of extending the Account controller to add custom POST and GET actions.
```APIDOC
## POST api/v1/Account/action/test
### Description
A custom POST action to perform a specific test operation.
### Method
POST
### Endpoint
`/api/v1/Account/action/test`
### Parameters
#### Query Parameters
- **someParam** (string) - Optional - A parameter passed via the query string.
#### Request Body
- **someKey** (any) - Optional - A key within the request payload.
### Response
#### Success Response (201)
- **(boolean)** - Indicates the success of the operation.
#### Response Example
```json
true
```
## GET api/v1/Account/action/test
### Description
A custom GET action to retrieve data.
### Method
GET
### Endpoint
`/api/v1/Account/action/test`
### Parameters
#### Query Parameters
- **someParam** (string) - Optional - A parameter passed via the query string.
### Response
#### Success Response (200)
- **(string)** - A string indicating success, e.g., 'true'.
#### Response Example
```
true
```
```
--------------------------------
### Initialize API Client with API Key Authentication
Source: https://docs.espocrm.com/development/api-client-go
Use this snippet to initialize the API client with API Key authentication. Replace 'Your API Key here' with your actual API key.
```go
import "github.com/definitepotato/espocrm"
client := espocrm.NewApiClient(
"https://espocrm.example.com",
espocrm.WithApiKeyAuth("Your API Key here"),
)
```
--------------------------------
### Dashlet Options Layout Example
Source: https://docs.espocrm.com/development/metadata/dashlets
Demonstrates the structure for defining the layout of dashlet options, including nested rows and fields like 'title'.
```json
{
"options": {
"layout": [
{
"rows": [
[
{"name": "title"},
false
]
]
}
]
}
}
```
--------------------------------
### Service Class Example
Source: https://docs.espocrm.com/development/services
A service class demonstrating business logic, including entity retrieval, access control checks, and entity saving.
```PHP
entityManager->getEntityById(Opportunity::ENTITY_TYPE, $id);
if (!$opportunity) {
throw new NotFound();
}
if (!$this->acl->check($opportunity, Table::ACTION_EDIT)) {
throw new Forbidden("No 'edit' access.");
}
$opportunity->set('stage', Opportunity::STATUS_CLOSED_WON);
$opportunity->set('probability', 100);
$this->entityManager->saveEntity($opportunity);
}
}
```
--------------------------------
### Relationship Parameters Configuration
Source: https://docs.espocrm.com/development/metadata/record-defs
Example of setting relationship parameters, including access controls and mandatory attributes for related records.
```json
{
"relationships": {
"cases": {
"linkRequiredAccess": "edit",
"linkRequiredForeignAccess": "read",
"linkForeignAccessCheckDisabled": false,
"mandatoryAttributeList": ["number"]
}
}
}
```
--------------------------------
### Listen to Collection Sync Event
Source: https://docs.espocrm.com/development/collection
Example of listening to the 'sync' event on a collection, which is triggered once the collection is successfully fetched from the backend.
```javascript
this.listenTo(collection, 'sync', (collection, response, options) => {});
```
--------------------------------
### Manual Instantiation with Factory
Source: https://docs.espocrm.com/development/di
Shows how to manually instantiate a class using a factory, with options to resolve dependencies via ReflectionClass or explicitly define them.
```php
create(SomeClass::class);
```
--------------------------------
### Extend Existing Controller (Account Scope)
Source: https://docs.espocrm.com/development/api-action
Example of extending the Account controller to add custom POST and GET actions. Demonstrates accessing query parameters and request body, and setting custom response status codes.
```php
getQueryParam('someParam'); // GET parameter
$data = $request->getParsedBody(); // payload
$someValue = $data->someKey ?? null;
$response->setStatus(201); // example how to set custom response status code
// call some service class here
return $someData; // can be true, false, array or object.
}
/**
* GET api/v1/Account/action/test
*/
public function getActionTest(Request $request, Response $response): void
{
$someParam = $request->getQueryParam('someParam'); // GET parameter
// call some service class here
$response->writeBody('true');
}
}
```
--------------------------------
### Initialize EspoCRM Client with API Key Authentication
Source: https://docs.espocrm.com/development/api-client-zig
Initialize the EspoCRM client by providing the EspoCRM URL and your API key for authentication. Ensure you have a page allocator available.
```zig
const allocator = std.heap.page_allocator;
const client: espocrm.Client = .init(
"https://espocrm.example.com",
.{ .api_key = "Your API Key here" },
);
```
--------------------------------
### Full Binding Example in a Custom Module
Source: https://docs.espocrm.com/development/di
Demonstrates various binding methods within a custom EspoCRM module's BindingProcessor. This includes binding services, implementations, values, and callbacks for specific classes.
```php
bindService('Espo\\SomeServiceName', 'someServiceName')
->bindImplementation('Espo\\SomeInterface', 'Espo\\SomeImplementation');
$binder
->bindService('Espo\\SomeServiceName $name', 'anotherServiceName');
$binder
->for('Espo\\SomeClass')
->bindImplementation('Espo\\SomeInterface', 'Espo\\SomeImplementation')
->bindValue('$paramName', 'Some Value')
->bindCallback(
'Espo\\AnotherClass',
// Callback arguments are resolved automatically.
function (SomeDependency $dependency) {
return $dependency->getSomething();
}
);
}
}
```
--------------------------------
### Create a Basic Entry Point
Source: https://docs.espocrm.com/development/entry-points
Defines a simple entry point class that can be accessed without authentication. Implement the 'run' method for your custom logic.
```php
createWith($className, [
'parameterName1' => $value1,
'parameterName2' => $value2,
]);
```
--------------------------------
### Where Clause: Is Linked Example
Source: https://docs.espocrm.com/development/api-search-params
Example of an 'isLinked' condition for link-multiple fields in a 'where' clause, checking if an attribute is linked to any record.
```json
{
"type": "isLinked",
"attribute": "teams"
}
```
--------------------------------
### Transaction Management: Start, Commit, Rollback
Source: https://docs.espocrm.com/development/orm
Manages a database transaction by explicitly starting, committing, or rolling back operations.
```php
getTransactionManager();
$tm->start();
try {
// do something
$tm->commit();
} catch (Throwable $e) {
$tm->rollback(); // this will roll back everything done within the transaction
}
```
--------------------------------
### Admin Panel Configuration Example
Source: https://docs.espocrm.com/development/metadata/app-admin-panel
This JSON object defines a panel for the administration page, including its label, order, and a list of items. Each item can have a URL, label, icon, description, and optionally a record view for settings or be enabled for tab quick search.
```json
{
"panelName": {
"label": "Some Panel Label",
"itemList": [
{
"url": "#SomeUrl",
"label": "Some Item Label",
"iconClass": "fas fa-cogs",
"description":"descriptionLanguageKey",
"tabQuickSearch": true
},
{
"url": "#Admin/mySettingsPage",
"label": "My Settings",
"iconClass": "fas fa-cogs",
"description":"mySettings",
"recordView": "custom:views/admin/my-settings"
}
],
"order": 20
}
}
```
--------------------------------
### Where Clause: Contains Example
Source: https://docs.espocrm.com/development/api-search-params
Example of a 'contains' condition within a 'where' clause for API search parameters, used for text-based searches.
```json
{
"type": "contains",
"attribute": "someTextOrVarcharField",
"value": "text"
}
```
--------------------------------
### Where Clause: Linked With Example
Source: https://docs.espocrm.com/development/api-search-params
Example of a 'linkedWith' condition for link-multiple fields in a 'where' clause, checking if an attribute is linked to specific records.
```json
{
"type": "linkedWith",
"attribute": "teams",
"value": ["someTeamId"]
}
```
--------------------------------
### Basic Authentication
Source: https://docs.espocrm.com/development/api-client-go
Shows how to initialize the API client using Basic Authentication (discouraged).
```APIDOC
## Basic Authentication
### Description
Initializes the API client with Basic Authentication. This method is highly discouraged.
### Method
`espocrm.NewApiClient` with `espocrm.WithBasicAuth`
### Parameters
- **baseURL** (string) - The base URL of the EspoCRM instance.
- **username** (string) - The username for Basic Authentication.
- **password** (string) - The password for Basic Authentication.
### Request Example
```go
import "github.com/definitepotato/espocrm"
client := espocrm.NewApiClient(
"https://espocrm.example.com",
espocrm.WithBasicAuth("username", "password"),
)
```
```
--------------------------------
### Where Clause: Is True Example
Source: https://docs.espocrm.com/development/api-search-params
Example of an 'isTrue' condition within a 'where' clause for API search parameters, used to check boolean attributes.
```json
{
"type": "isTrue",
"attribute": "someBoolField"
}
```
--------------------------------
### Where Clause: Is Null Example
Source: https://docs.espocrm.com/development/api-search-params
Example of an 'isNull' condition within a 'where' clause for API search parameters, used to check if an attribute has no value.
```json
{
"type": "isNull",
"attribute": "assignedUserId"
}
```
--------------------------------
### Client Initialization and Request Methods
Source: https://docs.espocrm.com/development/api-client-js
Demonstrates how to initialize the EspoCRM API client and make POST and GET requests. The `request` method handles sending data and receiving responses, supporting HMAC or API key authentication.
```APIDOC
## Client Class
### Description
The `Client` class provides an interface for interacting with the EspoCRM API. It handles authentication, request building, and response processing.
### Constructor
```javascript
constructor(url, apiKey, secretKey = null, options = {})
```
Initializes a new API client instance.
- **url** (string): The base URL of the EspoCRM instance.
- **apiKey** (string): The API key for authentication.
- **secretKey** (string|null, optional): The secret key for HMAC authentication. Defaults to null.
- **options** (object, optional): Additional options for the client.
- **port** (number): The port to use for the request.
- **timeout** (number): The request timeout in milliseconds.
### Method: request
```javascript
request(method, action, data)
```
Makes an API request to the specified action.
- **method** ('GET'|'POST'|'PUT'|'DELETE'|'PATCH'|'OPTIONS'): The HTTP method for the request.
- **action** (string): The API endpoint action (e.g., 'Account').
- **data** (Record, optional): The data payload for the request (for POST, PUT, PATCH) or parameters (for GET).
Returns a Promise that resolves with the response data or rejects with an error.
### Usage Examples
#### POST Request
```javascript
const Client = require('./espocrm-api-client');
const client = new Client(
'https://your-espocrm-site',
'API_KEY',
'SECRET_KEY' // optional, if hmac auth is used
);
const payload = {
name: 'Some name',
};
client
.request('POST', 'Account', payload)
.then(response => {
// success
console.log(response);
})
.catch(response => {
// error
console.log(response.statusCode, response.statusMessage);
});
```
#### GET Request
```javascript
const params = {
maxSize: 5,
where: [
{
type: 'equals',
attribute: 'type',
value: 'Customer',
},
],
select: ['id', 'name'],
};
client
.request('GET', 'Account', params)
.then(response => {
console.log(response);
})
.catch(response => {
// error
console.log(response.statusCode, response.statusMessage);
});
```
```
--------------------------------
### Where Clause: Greater Than Example
Source: https://docs.espocrm.com/development/api-search-params
Example of a 'greaterThan' condition within a 'where' clause for API search parameters, typically used for numerical comparisons.
```json
{
"type": "greaterThan",
"attribute": "amountConverted",
"value": 1000.00
}
```
--------------------------------
### Where Clause: In Example
Source: https://docs.espocrm.com/development/api-search-params
Example of an 'in' condition within a 'where' clause for API search parameters, checking if an attribute's value is within a list.
```json
{
"type": "in",
"attribute": "status",
"value": ["New", "Assigned"]
}
```
--------------------------------
### Making a Read GET Request
Source: https://docs.espocrm.com/development/api-client-go
Retrieve a single record by its ID using a GET request. Ensure you have the correct entity type and record ID.
```go
import "github.com/definitepotato/espocrm"
client := espocrm.NewApiClient(
"https://espocrm.example.com",
espocrm.WithApiKeyAuth("Your API Key here"),
)
contact, err := client.Read("Contact", "78abc123def456")
```
--------------------------------
### Instantiate Collection without Factory
Source: https://docs.espocrm.com/development/collection
Shows how to instantiate a collection directly using 'new Collection()' and setting its URL. It then fetches data from the specified endpoint.
```javascript
import View from 'view';
import Collection from 'collection';
export default class extends View {
setup() {
const collection = new Collection();
// The URL will be used when fetching from the backend.
collection.url = 'MyEntityType/someEndPoint';
this.wait(
collection.fetch()
);
}
}
```
--------------------------------
### Post to Stream Payload Example
Source: https://docs.espocrm.com/development/api/stream
Example of the JSON payload structure for posting a message to the stream. Ensure 'parentId', 'parentType', and 'post' fields are correctly populated.
```json
{
"type": "Post",
"parentId": "someId",
"parentType": "Case",
"post": "This is a test\n\nHello"
}
```
--------------------------------
### CLI Command to Print Bindings
Source: https://docs.espocrm.com/development/di
Command-line interface command to display all configured bindings within the application.
```bash
bin/command app-info --binding
```
--------------------------------
### Make a List GET Request with Parameters
Source: https://docs.espocrm.com/development/api-client-zig
Fetch a list of entities with optional filtering, sorting, and size limits. The `Parameters` struct should be encoded before being passed.
```zig
var params = espocrm.Parameters.init();
_ = params.setMaxSize(10).setOrder(espocrm.Parameters.Order.Asc);
const params_encoded = try params.encode(allocator);
const allocator = std.heap.page_allocator;
const result = try client.listEntities(allocator, "Contact", params, &[_]espocrm.Where{
.{ .filter_type = espocrm.FilterOption.Equals, .filter_attribute = "name", .filter_value = "Alice" },
.{ .filter_type = espocrm.FilterOption.GreaterThan, .filter_attribute = "age", .filter_value = "42" },
});
defer result.deinit();
```
--------------------------------
### Hook Class Name Example
Source: https://docs.espocrm.com/development/metadata/fields
Specifies a hook class to be called after a field is created or edited in the Entity Manager tool. This example uses the NumberType hook class.
```string
"hookClassName": "Espo\Core\Utils\FieldManager\Hooks\NumberType"
```
--------------------------------
### API Middleware Configuration Example
Source: https://docs.espocrm.com/development/metadata/app-api
This JSON object demonstrates how to configure various types of API middlewares. Use this structure to define global, route, action, controller, and controller action specific middlewares.
```json
{
"globalMiddlewareClassNameList": [
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test1",
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test2"
],
"routeMiddlewareClassNameListMap": {
"get_/:controller": [
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test3"
]
},
"actionMiddlewareClassNameListMap": {
"get_/Activities": [
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test3"
]
},
"controllerMiddlewareClassNameListMap": {
"Contact": [
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test4"
]
},
"controllerActionMiddlewareClassNameListMap": {
"Contact_get_index": [
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test5"
],
"Contact_post_create": [
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test6"
],
"Contact_put_update": [
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test7"
],
"Contact_get_read": [
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test8"
],
"Contact_delete_delete": [
"Espo\\Custom\\Classes\\ApiMiddlewares\\Test9"
]
}
}
```
--------------------------------
### CurrencyRate Update Payload Example
Source: https://docs.espocrm.com/development/api/currency-rate
Example payload for updating currency rates via the PUT CurrencyRate endpoint. Specify one or more currency codes and their corresponding rates.
```json
{
"EUR": 1.11,
"UAH": 0.037
}
```
--------------------------------
### Espo.Ajax GET Request Structure
Source: https://docs.espocrm.com/development/frontend/ajax
Basic structure for making a GET request to an Espo API endpoint. The API base path 'api/v1' is automatically prepended to the URL.
```javascript
Espo.Ajax.getRequest(url, data, options)
.then(response => {})
.catch(xhr => {});
```
--------------------------------
### Import Classes at File Beginning
Source: https://docs.espocrm.com/development/coding-rules
Declare all necessary class imports at the start of the file for better readability and organization. Avoid fully qualified names within the code body.
```php