Skip to content

attachment

An attachment field allows the user to upload a file to the server, or replace a file which was previously uploaded. Attachments are most often used indirectly through the core image and file piece types. Each of those piece types contains an attachment field and some metadata fields, making them a convenient way to reuse files.

You may also use attachment fields directly as well, however doing so means that the uploaded file will not be available in the media library or file manager. It will only be accessible as a property of the piece or page where it is uploaded. This can be appropriate for files that are only relevant for a single piece of content, such as resumes and job applications for a specific person.

Module field definition

All fields in a piece or page module use their object key as their database field name (e.g., resume below).

javascript
// Configuring the `resume` field in a module's `fields.add` subsection:
resume: {
  label: 'Resume',
  type: 'attachment',
  fileGroup: 'office'
}

Settings

Required

PropertyTypeDefaultDescription
labelStringn/aSets the visible label for the field in the UI
typeStringn/aSpecifies the field type (attachment for this type)

Optional

PropertyTypeDefaultDescription
fileGroupStringn/aCan be set to the default images or office groups, or a custom group, to limit the file types that can be uploaded. See more below.
helpStringn/aHelp text for the content editor
htmlHelpStringn/aHelp text with support for HTML markup
ifObject{}Conditions to meet before the field is active. See the guide for details.
requiredIfObject{}Conditions to meet before the field is required. See the guide for details.
hiddenBooleanfalseIf true, the field is hidden
requiredBooleanfalseIf true, the field is mandatory
readOnlyBooleanfalseIf true, prevents the user from editing the field value

NOTE

The uploaded files are stored in a web-accessible folder, however their file names are prepended with a randomized ID to avoid naming collisions.

Custom file groups

Developers can configure file type groups in addition to office and image using the fileGroups or addFileGroups options of the @apostrophecms/attachment module. Those custom group names can then be used for an attachment field's fileGroup setting.

Use in templates

The attachment field value will be an object with various properties, including many metadata properties. They can be accessed directly, but it is more common to use a template helper when working with attachments in templates.

The most common helper method for attachments in templates is apos.attachments.url. Once an attachment field has a value, you can obtain the file's public URL with the apos.attachments.url template helper.

nunjucks
<!-- `data.piece.resume` is an attachment object -->
<a href="{{ apos.attachment.url(data.piece.resume) }}">Download</a>