# Forms by link

> A form for one record that someone without an account fills in through a personal link, such as the intake form of a law firm, a yearly questionnaire or a claim report. How to declare it, write it and hand out the link.

A law firm needs the details of a new client: name, date of birth, bank account, a signed power of attorney. Typing them in from a paper form is slow, and the client has no account in nexxus. With a **form by link** a staff member creates the client's record, sends them a personal link, and the client fills in the form at home or on the firm's tablet. What they enter lands in that one record.

<Flow
  steps={[
    { icon: 'link', title: 'Staff create the link', text: 'For one record: sent by e-mail, copied, or opened on the firm\'s tablet.' },
    { icon: 'file-pen-line', title: 'The client fills it in', text: 'The firm\'s logo and your form. Drafts are kept until they submit.', tone: 'cyan' },
    { icon: 'check-check', title: 'Submitted', text: 'nexxus writes the fields and sets what the package says, such as a status.', tone: 'lavender' },
  ]}
  caption="The client reads and writes only the fields the form declares, of one record, until they submit or the link ends."
/>

## Declare the form

A form is a custom view with the slot `public.form`:

```json
{ "key": "aufnahmebogen.formular", "type": "custom", "slot": "public.form", "target": "aufnahmebogen",
  "html": "ui/aufnahmebogen.html", "label": { "de": "Aufnahmebogen", "en": "Intake form" },
  "fields": ["vorname", "nachname", "geburtsdatum", "iban", "vollmacht_erteilt"],
  "required": ["nachname", "vollmacht_erteilt"],
  "submit": { "set": { "status": "eingegangen", "abgesendet_am": "$now" } },
  "when": { "field": "status", "in": ["offen", "in_bearbeitung"] },
  "link": {
    "days": 14,
    "settings": ["kanzlei_anschrift"],
    "mail": {
      "subject": { "de": "Ihr Aufnahmebogen bei {{firm}}", "en": "Your intake form at {{firm}}" },
      "text": { "de": "Guten Tag {{name}},\n\nbitte füllen Sie den Bogen aus:\n\n{{link}}\n\nDer Link gilt bis {{expires}}.",
                "en": "Hello {{name}},\n\nplease fill in the form:\n\n{{link}}\n\nThe link is valid until {{expires}}." }
    }
  } }
```

| Key | Meaning |
|---|---|
| `target` | The entity of the record the form belongs to. Required, an entity of the package |
| `fields` | The fields the form reads and writes, at least one. Allowed: `string`, `text`, `number`, `boolean`, `date`, `datetime`, `enum` (also `multiple`). Not `readonly`, `ref`, `json` or `geo`, and no running number |
| `required` | Optional. Fields of `fields` that need a value on submit; a `boolean` counts only when it is `true`, like a consent box. It replaces the entity's own required flags on submit, because staff create the record empty before the client fills it in |
| `submit.set` | Optional. What nexxus sets on submit: literals that pass the field's checks, `$now` or `$today`. It may set readonly fields |
| `when` | Optional. A link can be created and used only while the condition holds for the record |
| `link.days` | How long a link lasts by default, 1 to 90, default 14 |
| `link.settings` | Optional. Settings of the package the form may read, such as the firm's address or its cancellation policy |
| `link.mail` | Optional. The e-mail with the link: `subject` and `text`, `de` required. Placeholders `{{link}}`, `{{firm}}`, `{{expires}}` and `{{name}}`. A paragraph that is only `{{link}}` becomes a button |

A form view never appears in `menu` or in a record's action bar. Staff reach it through the link a view of the package hands out (below).

## Write the form

The person who opens the link sees a bar with the firm's logo and name, and your view below it in a card at most 880 px wide. nexxus draws the states around it: loading, a note that the form was submitted when the link is opened again afterwards, and a text for an expired, revoked or unknown link.

Your view gets `user: null` and `form: {state, expiresAt, firm: {name}, fields, settings}` in its context. Only these calls work there; every other one answers `NOT_AVAILABLE`:

| Call | Result |
|---|---|
| `nx.form.get()` | `{data, fields, state, expiresAt}`: the declared fields with their current values |
| `nx.form.save(data)` | Saves some fields as a draft, without checking required ones. `{data, savedAt}` |
| `nx.form.submit(data)` | Saves `data` and submits. Every required field needs a value, else `VALIDATION` with `fieldErrors`. `{state, submittedAt}` |
| `nx.ui.toast(message, {kind?})` | A short message |

`fields` describes each field as `{key, type, label, hint?, required, maxLength?, min?, max?, format?, currency?, multiple?, values?}`, in the order of the manifest. Build the inputs from it or write them by hand.

Save drafts while the person types, submit at the end, and show your own thanks: the view stays on the page after the submit.

```js
const ctx = await nx.ready();
const form = await nx.form.get();
let pending = {};
let timer = 0;

for (const field of form.fields) {
  const input = document.getElementById(field.key);
  input.value = form.data[field.key] ?? '';
  input.addEventListener('input', () => {
    pending[field.key] = input.value || null;
    clearTimeout(timer);
    timer = setTimeout(async () => {
      const data = pending;
      pending = {};
      await nx.form.save(data).catch(e => showErrors(e.fieldErrors));
    }, 600);
  });
}

document.querySelector('form').addEventListener('submit', async event => {
  event.preventDefault();
  clearTimeout(timer);
  try {
    await nx.form.submit(pending);
    document.querySelector('form').hidden = true;
    document.getElementById('thanks').textContent = nx.t({
      de: `Vielen Dank, ${ctx.form.firm.name} hat Ihre Angaben.`,
      en: `Thank you, ${ctx.form.firm.name} has your details.`,
    });
  } catch (e) {
    showErrors(e.fieldErrors);
  }
});
```

On submit nexxus applies `submit.set`, and the record's history shows the change as made by the person who created the link. One link takes at most 1000 saves.

## Hand out the link

A signed-in view of the same package creates the link, usually a tab or a detail view on the record. The person needs the right to change the record.

```js
// By e-mail: nexxus shows the mail and sends it only on "Send"
const link = await nx.links.create({view: 'aufnahmebogen.formular', recordId: ctx.record.id,
  email: 'client@example.com', name: 'Anna Berger', locale: 'de'});

// Copied: the link goes to the clipboard (needs the click)
const copied = await nx.links.create({view: 'aufnahmebogen.formular', recordId: ctx.record.id});
await nx.ui.copy(copied.url);

// On the firm's tablet: open it in a new tab (needs the click)
await nx.nav.open({url: copied.url});
```

| Call | Result |
|---|---|
| `nx.links.create({view, recordId, days?, email?, name?, locale?})` | The link, with its `url` only in this answer. `locale` (`de`, `en` or `pl`, default `de`) is the language of the form page and the mail. With `email` nexxus mails the link, but only after a click in the view and once the person sent it in nexxus's dialog <Ui>Send e-mail</Ui>; closing the dialog rejects with `CANCELLED` and makes no link |
| `nx.links.list({view, recordId})` | The links of that form and record, newest first, with state, validity and address, without `url` |
| `nx.links.revoke(id)` | Ends an open link at once |

- **One live link per form and record.** A new link ends the open one.
- **At most 10 link mails an hour** per person and form; beyond that the call fails with `RATE_LIMITED`.
- With `email` but no `link.mail` in the manifest, the call fails with `VALIDATION`: pass the link on yourself.
- Don't ask with `nx.ui.confirm` before a mail. The person would confirm twice.

## Trying it in a development tenant

Create the link without `email` and open or copy it: the form works there like anywhere else. Links by e-mail need a mail server, which a development tenant does not have.

## Error codes

| Code | When |
|---|---|
| `LINK_EXPIRED`, `LINK_REVOKED`, `LINK_CLOSED`, `LINK_SUBMITTED` | The link ended. nexxus shows its own text in place of the form |
| `VALIDATION` | A value or a required field is missing or wrong; `fieldErrors` names the fields |
| `TOO_MANY` | The link reached its 1000 saves |
| `NOT_APPLICABLE` | `when` does not hold for the record, so no link can be created |
| `RATE_LIMITED` | More than 10 link mails of one form in an hour |
| `CANCELLED` | The person closed the mail dialog without sending |
| `NOT_AVAILABLE` | A call that does not exist on a public form, or `nx.form.*` outside one |

## Next steps

<CardGrid>
  <LinkCard title="Customer area" href="/modules/customer-area/" description="When clients should come back and see more than one form." />
  <LinkCard title="Look and feel" href="/modules/design/" description="Your own design for the form, and the checks before you ship it." />
</CardGrid>