PHP Developer Guide
Other documentationsDemoCommunityGitHub
  • Forest Admin
  • Getting started
    • How it works
    • Quick start
      • Symfony
      • Laravel
    • Create your agent
    • Troubleshooting
    • Migrating legacy agents
      • Pre-requisites
      • Recommendations
      • Migration steps
      • Code transformations
        • API Charts
        • Live Queries
        • Smart Charts
        • Route overrides
        • Smart Actions
        • Smart Fields
        • Smart Relationships
        • Smart Segments
  • Data Sources
    • Getting Started
      • Collection selection
      • Naming conflicts
      • Query interface and Native Queries
        • Fields and projections
        • Filters
        • Aggregations
    • Provided data sources
      • Doctrine
      • Eloquent
        • Polymorphic relationships
    • Write your own
      • Translation strategy
        • Structure declaration
        • Capabilities declaration
        • Read implementation
        • Write implementation
        • Intra-data source Relationships
      • Contribute
  • Agent customization
    • Getting Started
    • Actions
      • Scope and context
      • Result builder
      • Static Forms
      • Dynamic Forms
      • Related data invalidation
    • Charts
      • Value
      • Objective
      • Percentage
      • Distribution
      • Leaderboard
      • Time-based
    • Fields
      • Add fields
      • Move, rename and remove fields
      • Override binary field mode
      • Override writing behavior
      • Override filtering behavior
      • Override sorting behavior
      • Validation
    • Hooks
      • Collection hook
      • Collection override
    • Pagination
    • Plugins
      • Write your own
    • Relationships
      • To a single record
      • To multiple records
      • Computed foreign keys
      • Under the hood
    • Search
    • Segments
  • Frontend customization
    • Smart Charts
      • Create a table chart
      • Create a bar chart
      • Create a cohort chart
      • Create a density map
    • Smart Views
      • Create a Map view
      • Create a Calendar view
      • Create a Shipping view
      • Create a Gallery view
      • Create a custom tinder-like validation view
      • Create a custom moderation view
  • Deploying to production
    • Environments
      • Deploy on AWS
      • Deploy on Heroku
      • Deploy on GCP
      • Deploy on Ubuntu
    • Development workflow
    • Using branches
    • Deploying your changes
    • Forest Admin CLI commands
      • init
      • login
      • branch
      • switch
      • set-origin
      • push
      • environments:create
      • environments:reset
      • deploy
  • Upgrade
    • Laravel agent upgrade to v3
  • Under the hood
    • .forestadmin-schema.json
    • Data Model
      • Typing
      • Relationships
    • Security & Privacy
Powered by GitBook
On this page
  • How does it work
  • Making a field read-only
  • Examples

Was this helpful?

  1. Agent customization
  2. Fields

Override writing behavior

PreviousOverride binary field modeNextOverride filtering behavior

Last updated 1 year ago

Was this helpful?

This is the official documentation of the forestadmin/laravel-forestadmin v2+ and forestadmin/symfony-forestadmin PHP agents.

Forest Admin allows replacing the default field writing behavior with your own custom logic.

This is useful when you want to change how a given field behaves, but also to make writable.

How does it work

The replaceFieldWriting function allows to change the behavior of any change by creating a new patch that will be applied to the record.

You should refrain from using handlers that have side effects (to perform error handling, validation, ...) and .

Making a field read-only

Can be achieved without any code .

Examples

Changing other fields in the same record

In the following example, editing or creating a fullName will update both firstName and lastName fields of the record.

use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

$forestAgent->customizeCollection(
    'Customer',
    function (CollectionCustomizer $builder) {
        $builder->replaceFieldWriting(
        	'fullName',
        	function($value) {
        		[$firstName, $lastName] = explode(' ', $value);

        		return compact('firstName', 'lastName');
        	}
        );
    }
);

Having specific behavior only for updates

You can have different behavior for creations and updates.

In this example, each time the firstName field is edited, we also want to update a timestamp field.

use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;
use ForestAdmin\AgentPHP\DatasourceCustomizer\Decorators\Write\WriteReplace\WriteCustomizationContext;

$forestAgent->customizeCollection(
    'Customer',
    function (CollectionCustomizer $builder) {
        $builder->replaceFieldWriting(
        	'firstName',
        	function($value,  WriteCustomizationContext $context) {
        		return match ($context->getAction()) {
        			'create' => ['firstName' => $value, 'firstNameLastEdited' => null],
        			'update' => ['firstName' => $value, 'firstNameLastEdited' => 'updated' => date('c')],
        			default => throw new ForestException('invalid action'),
                };
        	}
        );
    }
);

Changing fields in related records

Handling relationships inside a replaceFieldWriting will only work for ManyToOne and OneToOne relationships.

In this simple example, we have two collections that are linked together:

  • The Users collection has a job and a portfolioId as foreignKey

  • The Portfolios collection has a title

When the user updates his job field we want also to update the title of the portfolio by the job name.

use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

$forestAgent->customizeCollection(
    'Customer',
    function (CollectionCustomizer $builder) {
        $builder->replaceFieldWriting(
        	'job',
        	function($value) {
        		return ['job' => $value, 'portfolio' => ['title' => $value]];
        	}
        );
    }
);

If the relationships do not exist it will create them with the given field values.

You can also provide another portfolioId to update the relationships and their fields:

use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

$forestAgent->customizeCollection(
    'Customer',
    function (CollectionCustomizer $builder) {
        $builder->replaceFieldWriting(
        	'job',
        	function($value) {
        		return ['job' => $value, 'portfolioId' => 8, 'portfolio' => ['title' => $value]];
        	}
        );
    }
);

Of course, you can chain the relationships. For example, if a portfolio has a one-to-one relationship with the formats collection, you can update it by writing the right path.

use ForestAdmin\AgentPHP\DatasourceCustomizer\CollectionCustomizer;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\ConditionTree\Operators;

$forestAgent->customizeCollection(
    'Customer',
    function (CollectionCustomizer $builder) {
        $builder->replaceFieldWriting(
        	'job',
        	function($value) {
        		return [
        			'job' => $value,
        			'portfolioId' => 8,
        			'portfolio' => [
        				'title' => $value,
        				'format' => [
        					'name' => 'pdf'
        				]
        			]
        		];
        	}
        );
    }
);
computed fields
use hooks instead
in the field settings ↗