---
url: https://trigger.beyondthecloud.dev/after-update/writer.md
description: >-
  After update, create, update or delete other records or publish platform
  events through a unit of work that commits with the save.
---

# AfterUpdate.Writer

Change other records or publish platform events after the update, through a unit of work.

**Signature**

```apex
public interface Writer extends AfterUpdate.Handler {
    Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record);
    void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork);
}
```

* `writeOnAfterUpdateWhen(record)`: called once per record in the chunk; with a RecursionGuard, a record past its limit is skipped without a call. Return `true` to write for the record.
* `writeOnAfterUpdate(record, unitOfWork)`: called right after its predicate returns true, with this Writer’s unit of work.

**Example**

::: code-group

```apex [Skeleton]
public with sharing class ContactWriter implements AfterUpdate.Writer {
    public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
        return record.isChanged(Contact.AccountId);
    }

    public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }
}
```

```cls \[Update the parent]
public with sharing class OpportunityAccountTypeWriter implements AfterUpdate.Writer, AfterUpdate.ParentQuery, AfterUpdate.RecursionGuard {
    public Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnAfterUpdate() {
        return new Map<SObjectField, TriggerTypes.ParentFields>{ Opportunity.AccountId => TriggerTypes.ParentFields.with(Account.Type) };
    }

    public Integer maxRunsPerRecordOnAfterUpdate() {
        return 1;
    }

    public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
        if (!record.isChangedTo(Opportunity.StageName, 'Closed Won')) {
            return false;
        }

        Account account = (Account) record.getNewParent(Opportunity.AccountId);

        return account != null && account.Type != 'Customer - Direct';
    }

    public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        Opportunity newOpportunity = (Opportunity) record.getNewSObject();

        unitOfWork.toUpdate(new Account(Id = newOpportunity.AccountId, Type = 'Customer - Direct'));
    }
}

```

```cls \[Insert a record]
public with sharing class OpportunityWinTaskWriter implements AfterUpdate.Writer, AfterUpdate.ParentQuery, AfterUpdate.ContinueOnError {
    public Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnAfterUpdate() {
        return new Map<SObjectField, TriggerTypes.ParentFields>{ Opportunity.AccountId => TriggerTypes.ParentFields.with(Account.Name) };
    }

    public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
        return record.isChangedTo(Opportunity.StageName, 'Closed Won');
    }

    public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        Opportunity newOpportunity = (Opportunity) record.getNewSObject();
        Account account = (Account) record.getNewParent(Opportunity.AccountId);

        unitOfWork.toInsert(
            new Task(
                WhatId = record.getId(),
                OwnerId = newOpportunity.OwnerId,
                Subject = 'Onboarding kick-off: ' + (account?.Name ?? newOpportunity.Name),
                Description = 'Won on ' + Date.today().format() + '. Agree the implementation plan with the customer.',
                ActivityDate = Date.today().addDays(7),
                Priority = 'High',
                Status = 'Not Started'
            )
        );
    }
}

```

:::

## Rules {#rules}

* **Register, do not run DML.** `toInsert`, `toUpdate`, `toUpsert`, `toDelete` and `toPublish` (platform events) take one record each. The shared unit runs in system mode without sharing. DML in the predicate or the action throws.
* **Gate on a change.** A `toUpdate` of records of this object runs the update triggers again. Qualify with `isChanged` or `isChangedTo`, so the nested run skips the record.
* **Nothing is saved inside the handler.** A `toInsert` record has no Id yet in the action or the Finalizer. For user mode, partial success or commit results, add [OwnUnitOfWork](/after-update/add-ons/own-unit-of-work).
* **Writer wins.** A class that also implements `AfterUpdate.Dispatcher` runs only as a Writer.

::: warning
The trigger rows are read-only. Register a new record with the Id and only the fields to change, such as `new Account(Id = accountId, Type = 'Customer - Direct')`.
:::

## Test {#test}

```apex
@IsTest
static void writeOnAfterUpdateWithWonOpportunity() {
    // Setup
    Opportunity renewal = new Opportunity(Name = 'Acme Renewal', StageName = 'Closed Won');

    DML.mock('triggerUow').allDmls();

    TriggerOrchestrator.mock().afterUpdateFor(OpportunityWinTaskWriter.class).with(renewal, new Opportunity(StageName = 'Negotiation/Review'));

    // Test
    TriggerOrchestrator.runTestFor(new OpportunityWinTaskWriter());

    // Verify
    Assert.areEqual(1, DML.retrieveResultFor('triggerUow').insertsOf(Task.SObjectType).records().size(), 'One task should be registered.');
}
```
