# Format values without changing queries

A date can display as “Yesterday” while remaining a timestamp in the data model.
That separation matters when the grid requests another page, applies a date
filter or exports the query result.

Grids and read-only form fields show timestamps as a date and time, for example
“Wed 18 Nov 2026, 10:39”, in the browser's time zone. Editable timestamp inputs
show the full timestamp, including its offset and fractional seconds.

Use `fieldPresentation` to choose a different display:

```javascript
const receivedDateText = value => value == null ? '' : new Intl.DateTimeFormat(undefined, {
  dateStyle: 'medium', timeStyle: 'short',
}).format(new Date(String(value)));

grid.fieldPresentation = { fields: { receivedAt: { formatter: ({ value }) => receivedDateText(value) } } };
```

The service declares `receivedAt` as `Edm.DateTimeOffset`. Sorting and filtering
use that raw field; CSV exports its original value. A renderer can supply richer
cell markup and takes precedence over a formatter. Neither presentation function
changes the data or the collection's query.

## Order by another server field

A displayed sender name may need a normalized name or related record's display
field for ordering. Declare the server field explicitly:

```yaml
view:
  columns:
    - field: sender
      sortField: senderSortKey
    - field: receivedAt
  sort: [{ field: sender }]
  filters: {}
  frozen: 0
```

The grid sends an order by `senderSortKey`; filters still refer to the raw
`sender` field. `sortField` also accepts supported navigation paths. The service
must expose and implement the chosen field. The data layer appends entity-key
tie-breakers so equal sort values have stable page boundaries.

A JavaScript normalizer cannot globally order a collection whose other pages
have not been loaded. For paged remote collections, put normalization or
collation in the service and expose its sort key. Client normalizer callbacks for
fully materialized local lists are not part of this API.

## Numbers, currency and percentages

For a number, you rarely need a function. A [ValueFormat](/docs/reference/api/object-ValueFormat.md)
is plain data, and the field's metadata fills what it leaves out (a Decimal's scale is
its places; a `Measures.ISOCurrency` annotation names its currency):

```ts
grid.fieldPresentation = { fields: { price: { format: { kind: "number", style: "currency", currency: "GBP" } } } };
editor.columns = [{ field: "price", format: { style: "currency", currency: "GBP" } }]; // a ListEditor
```

The grid's `format`, a list editor's `ListColumn.format`, the meter and slider labels
and your own text all come from the one exported
[formatFigure](/docs/reference/api/staticMethod-formatFigure.md), so a figure reads the same
everywhere:

```ts
formatFigure("1850.5", { style: "currency", currency: "GBP" }, { field: priceField }); // "£1,850.50"
```

## Use formatters in YAML

Register an ordinary function with the composition registry:

```javascript
const renderers = {
  'received-date': defineCompositeRenderer(['fieldPresentation'], ({ value }) => receivedDateText(value)),
};
```

Then reference it on a Grid child:

```yaml
fieldPresentation:
  fields:
    receivedAt:
      formatter: { renderer: received-date }
```

Function bodies remain in JS/TS. YAML declares their connection to the control.

The [mail workspace](/examples/mail.html) demonstrates sender-name sorting and
real received timestamps displayed as times, “Yesterday” or calendar dates.
The shared Sort panel remains available when a grid switches to narrow cards.
See [shared field presentation](/docs/reference/api/object-FieldPresentation.md) and
[GridColumn.sortField](/docs/reference/api/attr-GridColumn.sortField.md).

## Share display between hosts

Grid, Form and ListEditor accept the same `fieldPresentation` property. Form uses
the treatment when its bound field is read-only; editing keeps the native control.
A local `FormField.presentation` or `ListColumn.presentation` overrides individual
members. Grid geometry and row/cell decoration remain in `Grid.presentation`.

```ts
const display = {
  types: { "Example.EmailAddress": { treatment: "email" } },
  fields: { alternateEmail: { treatment: "email" } },
};
grid.fieldPresentation = display;
form.fieldPresentation = display;
listEditor.fieldPresentation = display;
```

Type keys match `Field.annotations["AsterData.Type"]`. The recognized `email`
hint selects a mailto link automatically. An application can map any declared
type, such as `Example.EmailAddress`, to the same treatment. Unknown metadata
uses the primitive display. Empty and malformed addresses stay readable text.

Each member inherits from the local occurrence, host field, host semantic type,
recognized metadata, then primitive defaults. Content uses `display(context)`,
then `formatter(context)`, then `valueMap`, then typed formatting. Callbacks get
`field`, `name`, raw `value`, `key` and a frozen `entity` projection containing
only loaded, visible values. Hidden and unloaded fields never invoke callbacks.
Register `display` or `formatter` callbacks for `fieldPresentation` through the
existing composition registry. No code is loaded from metadata.

## Bind named displays from model metadata

`bindFieldPresentations(ctx, model, set, registry, overrides?)` connects model
references to trusted, separately authored registrations. Give its `presentation`
to Grid and Form, then call `dispose()` when the view closes. The
[named displays example](/examples/formatting.html) shows a compact person and
an abbreviated commit with an ordinary Aster copy button in both hosts.

```ts
const model = {
  types: {
    Tickets: { fields: { requester: { ref: 'People' } } },
    People: {
      fields: { name: { type: 'text' }, email: { type: 'text' } },
      displayField: 'name', display: { renderer: 'person-compact' },
    },
  },
};
registry.renderer('person-compact', defineCompositeRenderer(
  ['fieldPresentation'],
  ({ entity }) => `${entity.name} · ${entity.email}`,
  { dependencies: { People: ['name', 'email'] } },
));
const displays = bindFieldPresentations(ctx, model, 'Tickets', registry);
grid.fieldPresentation = form.fieldPresentation = displays.presentation;
```

The model's type names identify entity sets. `inherits` and field mixins resolve
before binding. A type's `display` applies to its compact related-record display;
its `displayField` remains the plain text label. A scalar field or custom type can
also declare `display`. Explicit field metadata wins over custom-type metadata;
explicit host field presentation wins over the resulting metadata presentation.

In an authored model, the same references use YAML:

```yaml
model:
  types:
    Tickets:
      fields:
        requester: {ref: People}
    People:
      displayField: name
      display: {renderer: person-compact}
      fields:
        name: {type: text}
        email: {type: text}
```

This is model metadata, separate from composition YAML. The registered JavaScript
implementation above supplies `person-compact`; the application binds the model
and exposes the resulting presentation to its composition model. A composition
child can then borrow it through the existing binding syntax:

```yaml
children:
  tickets:
    type: Grid
    props:
      fieldPresentation: {ref: model.ticketPresentation}
```

Registrations used by model metadata must declare `dependencies`, including `{}`
when they need only `value`. Dependency keys identify the current display type or
an ancestor, and each field must exist on that type and in served scalar metadata.
Unknown names fail binding before any reads. Dependencies select data through
the existing batched `DataContext.lookup`; they grant no additional access.

Direct field callbacks retain the containing record context. For an explicit
related binding, `value` remains the foreign key, while `entity` and `key` belong
to the related record. The related projection is frozen and contains only loaded,
permitted scalar values. Hidden fields, stale fields outside the known projection
and nested objects are excluded. For related displays, a missing dependency suppresses that callback:
the permitted `displayField` is shown, or “Unavailable” if no label is available.
Null references display empty text. A direct scalar display with an unavailable
dependency uses its raw value as text. Loaded local edits override stored values;
host-hidden and server-hidden fields remain excluded. Renderers handle loaded null
values themselves.

This binding supports scalar foreign keys to a single-key entity set. Collection
references and composite foreign keys are outside this compact display contract.
It neither executes metadata code nor changes query sorting, filtering or exports.

Migration: replace `Grid.renderers` and `ListEditor.renderers` with
`fieldPresentation.fields[name].display`, and `Grid.formatters` with
`fieldPresentation.fields[name].formatter`. Callbacks now accept the context
object. Replace `(entity, key)` with `({ entity, key })` and `(value, entity,
field)` with `({ value, entity, field })`.
