# Add fields

{% hint style="success" %}
This is the official documentation of the `forestadmin/laravel-forestadmin` v2+ and `forestadmin/symfony-forestadmin` PHP agents.
{% endhint %}

Forest Admin allows creating new Fields on any Collection, either computationally, by fetching data on an external API or based on other data that is available on the connected data sources.

By default, the fields that you create will be read-only, but you can make them [filterable](/developer-guide-agents-php/agent-customization/fields/filter.md), [sortable](/developer-guide-agents-php/agent-customization/fields/sort.md), and [writable](/developer-guide-agents-php/agent-customization/fields/write.md) by using the relevant methods.

### How does it work?

When creating a new field you will need to provide:

| Field                 | Description                                                                                                                                                                                                                              |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| columnType            | Type of the new field which can be [any primitive](/developer-guide-agents-php/under-the-hood/data-model/typing.md#primitive-types) or [composite type](/developer-guide-agents-php/under-the-hood/data-model/typing.md#composite-types) |
| dependencies          | List of fields that you need from the source records and linked records in order to run the handler                                                                                                                                      |
| getValues             | Handler which computes the new value **for a batch of records**                                                                                                                                                                          |
| enumValues (optional) | When columnType is `Enum`, you must specify the values that the field will support                                                                                                                                                       |

### Examples

#### Adding a field by concatenating other fields

This example adds a `user.displayName` field, which is computed by concatenating the first and last names.

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceCustomizer\Decorators\Computed\ComputedDefinition;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

// "User" Collection has the following structure: { id, firstName, lastName }
$forestAgent->customizeCollection(
    'User',
    function (CollectionCustomizer $builder) {
        $builder->addField(
            'displayName',
            new ComputedDefinition(
                // Type of the new field
                columnType: 'String',

                // Dependencies which are needed to compute the new field (must not be empty)
                dependencies: ['firstName', 'lastName'],

                // Compute function for the new field
                // Note that the function computes the new values in batches: the return value must be
                // an array which contains the new values in the same order than the provided records.
                values: fn ($records) => collect($records)->map(fn ($record) => $record['firstName'] . ' ' . $record['lastName']),
            )
        );
    }
);
```

#### Adding a field that depends on another computed field

This example adds a `user.displayName` field, which is computed by concatenating the first and last names, and then another which capitalize it.

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceCustomizer\Decorators\Computed\ComputedDefinition;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

// "User" Collection has the following structure: { id, firstName, lastName }
$forestAgent->customizeCollection(
    'User',
    function (CollectionCustomizer $builder) {
        // Create a first field which is computed by concatenating the first and last names
        $builder->addField(
                'displayName',
                new ComputedDefinition(
                    columnType: 'String',
                    dependencies: ['firstName', 'lastName'],
                    values: fn ($records) => collect($records)->map(fn ($record) => $record['firstName'] . ' ' . $record['lastName']),
                )
            );
        // Create a second field which is computed by uppercasing the first field
        ->addField(
            'displayNameCaps',
            new ComputedDefinition(
                columnType: 'String',
                dependencies: ['displayName'], // It is legal to depend on another computed field
                values: fn ($records) => collect($records)->map(fn ($record) => strtoupper($record['displayName'])),
            )
        )
    }
);
```

#### Adding a field that depends on a many-to-one relationship

We can improve the previous example by adding the city of the user to the display name.

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceCustomizer\Decorators\Computed\ComputedDefinition;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

// Structure:
// User    { id, addressId, firstName, lastName }
// Address { id, city }
$forestAgent->customizeCollection(
    'User',
    function (CollectionCustomizer $builder) {
        $builder->addField(
            'displayName',
            new ComputedDefinition(
                columnType: 'String',

                // We added 'address:city' in the list of dependencies,
                // which tells forest to fetch the related record
                dependencies: ['firstName', 'lastName', 'address:city'],
                values: fn ($records) => collect($records)
                    ->map(fn ($record) => $record['firstName'] . ' ' . $record['lastName'] . ' (from ' . $record['address']['city'] . ' )'),
            )
        );
    }
);
```

#### Adding a field that depends on a one-to-many relationship

Let's now add a `user.totalSpending` field by summing the amount of all `orders`.

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceCustomizer\Decorators\Computed\ComputedDefinition;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Aggregation;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Filters\Filter;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\ConditionTreeFactory;

// Structure:
// User    { id }
// Order { id, customer_id, amount }
$forestAgent->customizeCollection(
    'User',
    function (CollectionCustomizer $builder) {
        $builder->addField(
            'totalSpending',
            new ComputedDefinition(
                columnType: 'Number',
                dependencies: ['id'],
                values: function ($records, $context) {
                    $recordIds = array_map(fn ($r) => $r['id'], $records);

                    // We're using Forest Admin's query interface
                    $filter = new Filter(
                        conditionTree: ConditionTreeFactory::fromArray(
                            ['field' => 'customer_id', 'operator' => 'In', 'value' => $recordIds]
                        )
                    );
                    $aggregation = new Aggregation(operation: 'Sum', field: 'amount', groups: [[ 'field' =>'customer_id' ]]);
                    $rows = $context->getDatasource()->getCollection('Car')->aggregate($filter, $aggregation);

                    return array_map(
                        function ($record) use ($rows) {
                            foreach ($rows as $row) {
                                if ($row['group']['customer_id'] === $record['id']) {
                                    return $row['value'] ?? 0;
                                }
                            }

                            return 0;
                        },
                        $records
                    );
                }
            )
        );
    }
);
```

#### Adding a field fetching data from an API

Let's imagine that we want to check if the email address of our users is deliverable. We can use a verification API to perform that work.

The API we're using is fictional, and the structure of the response is:

```json
{
  "username1@domain.com": {
    "usernameChecked": false,
    "usernameValid": null,
    "domainValid": true
  },
  "username2@domain.com": {
    "usernameChecked": false,
    "usernameValid": null,
    "domainValid": true
  }
}
```

```php
use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceCustomizer\Decorators\Computed\ComputedDefinition;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

// Fictional verification API.
use Fake\EmailVerificationClient;
$client = new EmailVerificationClient();
$client->setApiKey('MY_FAKE_API_KEY');

// "User" Collection has the following structure: { id, email }
$forestAgent->customizeCollection(
    'User',
    function (CollectionCustomizer $builder) {
        $builder->addField(
            'emailDeliverable',
            new ComputedDefinition(
                columnType: 'Boolean',
                dependencies: ['email'],
                values: function ($records) {
                    $response = $client->verifyEmails(collect($records)->map(fn ($record) => $record['email'])->toArray());

                    return collect($records)
                        ->map(function ($record) use ($response) {
                            $check = $response[$record['email']];

                            return $check['domainValid'] && (! $check['usernameChecked'] || $check['usernameValid'])
                        });
                    }
                }
            )
        );
    }
);
```

### Performance

When adding many fields, keep in mind that:

* You should refrain from making queries to external services
  * Use relationships in the `dependencies` array when that is possible
  * Use batch APIs calls instead of performing requests one by one inside of the `records.map` handler.
* Only add fields you need in the `dependencies` list
  * This will reduce the pressure on your data sources (fewer columns to fetch)
  * And increase the probability of reducing the number of records that will be passed to your handler (records are deduplicated).
* Do not duplicate code between handlers of different fields: fields can depend on each other (no cycles allowed).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.forestadmin.com/developer-guide-agents-php/agent-customization/fields/computed.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
